Objectives: LO-9.1, LO-9.2, LO-9.3
Prerequisites: the Module 9 reading and
Lab 8
Time: about 2.5 hours
In this lab you implement four workflow patterns, in which your code decides each step: routing, parallel calls, an orchestrator with workers, and an evaluator with an optimizer. Then you build an agent, in which the model decides, with limits on its turns and its cost, and trace its run from its log.
No cell sends anything over the network. Each model is a ScriptedModel from promptlab,
which answers from a script written in the cell, so its replies are illustrative, not model
output. The helper ask(model, text, system) sends one user message and returns the reply’s
text; it raises ValueError if the reply didn’t end with "end_turn". The agent can call only
the three read-only tools from Lab 8, which read a fictional menu.
Each exercise ends with a check cell that prints passed or fails with a message. Run the
cells in order, from the top. Some cells fail on purpose until you finish the exercise above
them.
Setup¶
import sys
import json
import threading
from jsonschema import validate, ValidationError
from promptlab import ScriptedModel, make_response
from promptlab.shop_tools import MENU, TOOLS, tool_turn, run_tool, text_of, ask
SCHEMA = {
"type": "object",
"properties": {"queue": {"enum": ["repair", "billing", "account"]},
"summary": {"type": "string", "minLength": 1, "maxLength": 80}},
"required": ["queue", "summary"],
"additionalProperties": False,
}
from concurrent.futures import ThreadPoolExecutor
print("Python", sys.version.split()[0])Trace an independent branch¶
This branch doesn’t need any other branch’s answer. Predict what ask returns, and the job
name you would store it under, then run the cell.
print(ask(ScriptedModel(["25 minutes"]), "Flat tire", "Estimate time."))Exercise L9.1 (LO-9.1, ★★, about 25 minutes)¶
Route to a known worker. Write routed(router, workers, ticket). Get the route from the
router model with ask, then send the ticket to the worker in workers that the route names,
and return that worker’s reply. Raise ValueError for a route that names no worker, before
calling any worker.
def routed(router, workers, ticket):
raise NotImplementedError("L9.1")billing = ScriptedModel(["Ask for the invoice ID."])
repair = ScriptedModel([])
reply = routed(ScriptedModel(["billing"]), {"billing": billing, "repair": repair}, "Receipt")
assert reply == "Ask for the invoice ID.", f"Return the billing worker's reply, not {reply!r}."
assert billing.calls == 1 and repair.calls == 0, "Call only the worker that the router named."
assert billing.requests[0]["messages"][0]["content"] == "Receipt", \
"Send the ticket itself to the worker."
idle = ScriptedModel(["This worker should never be called."])
try:
routed(ScriptedModel(["refunds"]), {"billing": idle, "repair": idle}, "Receipt")
except ValueError:
assert idle.calls == 0, "Raise before calling any worker."
else:
raise AssertionError("The route 'refunds' names no worker, so it should raise ValueError.")
print("passed")Exercise L9.2 (LO-9.1, ★★, about 25 minutes)¶
Run parallel reads. Write parallel(workers, ticket). Use a ThreadPoolExecutor with two
workers. Submit one ask for each stand-in in workers, all with the same ticket, and return a
dictionary from job names to replies. Submit every job before you wait for any result, so the
jobs can overlap. The check’s second test makes each job wait for the other, so it passes only
if both run at the same time.
def parallel(workers, ticket):
raise NotImplementedError("L9.2")workers = {"parts": ScriptedModel(["$18"]), "labor": ScriptedModel(["25 minutes"])}
result = parallel(workers, "Flat tire")
assert result == {"parts": "$18", "labor": "25 minutes"}, \
f"Key each reply by its job's name: expected parts and labor, got {result!r}."
assert all(w.requests[0]["messages"][0]["content"] == "Flat tire" for w in workers.values()), \
"Send the same ticket to every worker."
meeting = threading.Barrier(2, timeout=5)
def waits_for_partner(reply):
def answer(request):
meeting.wait() # returns only when both jobs have reached this line
return reply
return answer
together = {"parts": ScriptedModel([waits_for_partner("$18")]),
"labor": ScriptedModel([waits_for_partner("25 minutes")])}
try:
parallel(together, "Flat tire")
except threading.BrokenBarrierError:
raise AssertionError("The two jobs didn't run at the same time. Submit both to the executor "
"before you ask for either result.") from None
print("passed")Exercise L9.3 (LO-9.1, ★★, about 25 minutes)¶
Check an orchestration plan. Write orchestrate(planner, workers, ticket). The planner’s
reply should be a JSON array of unique job names, each the name of a worker. Reject anything
else, including an unknown job, with ValueError, before running any worker. Then pass the
whole ticket to each worker in the plan, and return the replies keyed by job, in plan order.
def orchestrate(planner, workers, ticket):
raise NotImplementedError("L9.3")jobs = {"parts": ScriptedModel(["Flat kit"] * 5)}
result = orchestrate(ScriptedModel(['["parts"]']), jobs, "Flat")
assert result == {"parts": "Flat kit"}, \
f"A one-job plan should give {{'parts': 'Flat kit'}}, not {result!r}."
bad_plans = {'["parts", "missing"]': "an unknown job", '["parts", "parts"]': "a repeated job",
'{"jobs": ["parts"]}': "a reply that isn't a JSON array"}
for plan, why in bad_plans.items():
try:
orchestrate(ScriptedModel([plan]), jobs, "Flat")
except ValueError:
pass
else:
raise AssertionError(f"A plan with {why} should raise ValueError: {plan}")
assert jobs["parts"].calls == 1, "Reject an invalid plan before running any of its workers."
team = {"parts": ScriptedModel(["Flat kit"]), "labor": ScriptedModel(["25 minutes"])}
result = orchestrate(ScriptedModel(['["labor", "parts"]']), team, "Flat")
assert list(result.items()) == [("labor", "25 minutes"), ("parts", "Flat kit")], \
f"Return the replies keyed by job, in plan order, not {result!r}."
assert team["labor"].requests[0]["messages"][0]["content"] == "Flat", \
"Pass the whole ticket to each worker."
print("passed")Exercise L9.4 (LO-9.1, ★★, about 25 minutes)¶
Revise with a bounded evaluator. Write optimize(draft, judge, ticket, max_drafts). Call
draft with the ticket, followed by the judge’s last review, if there is one. Call judge
with the ticket and the new draft. Return the first draft whose review is exactly pass, or
None after max_drafts attempts.
def optimize(draft, judge, ticket, max_drafts):
raise NotImplementedError("L9.4")draft = ScriptedModel(["Done!", "Could you share the invoice ID?"])
judge = ScriptedModel(["Include an invoice request.", "pass"])
result = optimize(draft, judge, "Receipt", 2)
assert result == "Could you share the invoice ID?", \
f"Return the draft that the judge passed, not {result!r}."
assert "Include an invoice request." in draft.requests[1]["messages"][0]["content"], \
"Send the judge's review with the next request for a draft."
assert "Done!" in judge.requests[0]["messages"][0]["content"], "Send each draft to the judge."
assert optimize(ScriptedModel([]), ScriptedModel([]), "Receipt", 0) is None, \
"With max_drafts=0, return None without calling either model."
writer, critic = ScriptedModel(["A", "B"]), ScriptedModel(["Too short.", "Still too short."])
assert optimize(writer, critic, "Receipt", 2) is None, "Return None when no draft passes."
assert writer.calls == 2 and critic.calls == 2, \
f"Stop after max_drafts attempts: expected 2 drafts and 2 reviews, " \
f"got {writer.calls} and {critic.calls}."
print("passed")Exercise L9.5 (LO-9.2, LO-9.3, ★★, about 25 minutes)¶
Trace both budget stops. Write agent(model, task, max_turns, budget, reserve), a tool loop
like Lab 8’s that uses TOOLS and run_tool, with two limits:
Before each call, reserve
reserveoutput tokens, the most a call may use; a real loop would send it asmax_tokens. If the credits spent so far plus the reserve would exceedbudget, stop with"cost_limit"without calling.After each call, charge the response’s actual
usage["output_tokens"]. RaiseValueErrorif a scripted response used more than the reserve.After
max_turnscalls without a final answer, stop with"turn_limit".
Return a triple: the status (the stop reason, "cost_limit", or "turn_limit"), the final
text or None, and a log. Each log entry is a dictionary with turn (starting at 1), used,
spent, stop, and tools, the names of the tools called that turn.
In your notes, compare this loop with one direct lookup in MENU for a pricing question, and
say which you would ship and why.
def agent(model, task, max_turns, budget, reserve):
raise NotImplementedError("L9.5")read = tool_turn(("one", "find_service", {"service": "flat"}), credits=2)
status = agent(ScriptedModel([read]), "Price", 1, 10, 3)[0]
assert status == "turn_limit", \
f"One tool turn with max_turns=1 ends with turn_limit, not {status!r}."
model = ScriptedModel([read])
status, result, log = agent(model, "Price", 5, 4, 3)
assert status == "cost_limit" and result is None, \
f"After spending 2 of 4, a reserve of 3 can't fit: expected ('cost_limit', None), " \
f"got {(status, result)!r}."
assert model.calls == 1, f"Stop before the second call: expected 1 call, got {model.calls}."
assert log == [{"turn": 1, "used": 2, "spent": 2, "stop": "tool_use",
"tools": ["find_service"]}], f"The log doesn't match the run: {log!r}"
finished = agent(ScriptedModel([read, make_response("$18", output_tokens=2)]), "Price", 5, 5, 3)
assert finished[0:2] == ("end_turn", "$18"), \
f"Spending 2 + 2 within a budget of 5 should end with ('end_turn', '$18'), " \
f"not {finished[0:2]!r}."
greedy = tool_turn(("big", "find_service", {"service": "flat"}), credits=5)
try:
agent(ScriptedModel([greedy]), "Price", 1, 20, 3)
except ValueError:
pass
else:
raise AssertionError("A response that used 5 credits against a reserve of 3 should raise "
"ValueError.")
print("passed")Summary¶
A router picks one known branch, and fails loudly on a route that names none.
Parallel calls overlap only if every job is submitted before any result is awaited. They cost the same as running the jobs one after another.
An orchestrator’s plan is checked whole before any worker runs, and an evaluator loop stops at its draft limit even when no draft passes.
An agent reserves a call’s maximum cost before calling, charges what it used after, and stops at its cost limit or its turn limit. Its log shows what it did, not whether it was right.