Objectives: LO-9.1, LO-9.2, LO-9.3
Prerequisites: Module 8, and the chains of
Module 6
Time: about 6 hours: 2 for this reading, 2.5 for Lab 9, and 1.5 for the
practice; PA4 follows, and takes about 3 more
Module 6 chained prompts in a fixed order, and Module 8 built a loop that runs a model’s tool calls. This module asks one question of every system built from model calls: who decides the next step, your code or the model? You will meet four patterns in which your code decides, and an agent in which the model does, with limits on its turns and its cost. Then you will choose among one call, a workflow, and an agent for a task, and say why. In Lab 9 you implement all five with stand-ins, and trace an agent’s run from its log.
Who decides the next step¶
Erik S. and Barry Zhang’s Anthropic article Building effective agents (December 19, 2024) draws the line this module uses:
A workflow runs model calls and tools through code paths written in advance. Your code decides every step.
An agent lets the model direct its own process and its tool use. The model decides which step comes next, inside a loop that your code runs.
A single call is one request, as in Modules 3–7.
The article’s advice is to find the simplest solution that works, and to add complexity only when it is needed. It says agentic systems often trade latency and cost for better task performance, and that for many applications one well-built call, with retrieval and examples, is enough. It also notes that much of the tooling it describes has changed since December 2024.
Worked example. Ticket T10 says “Can I get the receipt for Tuesday’s repair?” A single call
with Module 3’s routing prompt labels it billing: one request. A workflow that routes it and then
drafts a reply makes two requests, in an order your code fixed. An agent given the same ticket and
Module 8’s tools might look up nothing, or call three tools over four turns; its cost depends on
what it decides. That uncertainty is what the limits later in this module are for.
Four workflow patterns¶
The article names five workflows: prompt chaining, which Module 6 covered, and the four below. In each, your code fixes the shape of the work.
| Pattern | Who decides the next step | Bicycle-shop example | What to check |
|---|---|---|---|
| Routing | A classifying call picks one of a fixed set of branches | Send a receipt request to the billing writer | An unknown route fails loudly |
| Parallel calls | Your code runs independent calls at the same time | Price the parts and estimate the labor | Each result keeps its job’s name |
| Orchestrator and workers | A planning call chooses the subtasks for this input | Choose the jobs a mixed ticket needs | Reject an unknown job before any worker runs |
| Evaluator and optimizer | A judging call accepts a draft or sends it back | Revise a receipt reply until it is clear | Cap the number of drafts |
Routing¶
Routing classifies an input and sends it to a branch built for that kind of input. The article gives two uses: sending each kind of customer-service query to its own process, and sending common questions to a smaller model while harder ones go to a more capable one.
Worked example. A router returns billing for T10, and the code calls the billing worker with
the ticket. Suppose the router runs on Claude Haiku 5.5 with 150 input tokens and 3 output tokens,
and the billing worker runs on Claude Opus 5.5 with 400 input and 120 output. At Module 2’s prices,
the router costs (150 × 0.10 + 3 × 0.50) / 1,000,000 = 0.0000165 dollars, and the worker
(400 × 4 + 120 × 20) / 1,000,000 = 0.004 dollars. Routing adds one call, at less than 0.5% of the
worker’s cost. If the router returns Billing or refunds, which name no branch, the code raises
an error rather than guessing a default. A wrong guess sends the customer to the wrong desk with no
record of why. Exercise L9.1 implements a router.
Parallel calls¶
Parallelization, in the article, runs calls at the same time and combines their outputs in code. It comes in two kinds: sectioning splits a task into independent subtasks, and voting runs the same task several times to compare the answers.
In Python, a ThreadPoolExecutor from concurrent.futures runs functions on a pool of threads.
The Python documentation says that
submit schedules a call and returns a Future at once, and that Future.result() waits for the
call’s value, raising the call’s exception if it raised one. A with block waits for every pending
call before it exits. Submit every job first, and only then ask for the results; asking for each
result right after its submit makes the calls run one after another.
Worked example. For a flat tire, the parts job and the labor job don’t need each other’s
answers. A parts worker returns $18, and a labor worker returns 25 minutes. Suppose each call
takes 1.5 seconds. Run one after the other, they take about 3 seconds; submitted together to two
threads, about 1.5. Both versions send the same tokens, so they cost the same. Keep each result
under its job’s name, {"parts": "$18", "labor": "25 minutes"}, so nothing depends on which call
finished first. Exercise L9.2 builds this with two workers.
Orchestrator and workers¶
In an orchestrator-workers workflow, the article says, a central model breaks a task down, hands the pieces to workers, and combines their results. Unlike parallel calls, the subtasks aren’t fixed in advance: the orchestrator chooses them for each input. The article’s examples are coding changes that touch several files and searches that gather from several sources.
Worked example. A ticket says “Flat rear tire. How long would a brake job take too?” The
planner replies with the JSON array ["parts", "labor"]. Before any worker runs, the code parses
the reply and checks the whole plan: it is a list, every item is a string that names a known
worker, and no job appears twice. Only then does it call the two workers, in plan order. That
makes three calls, one more than the fixed parallel workflow, which is the price of letting the
planner choose. A plan such as ["parts", "paint"] names a worker that doesn’t exist, so the code
rejects it whole, and no worker runs. Exercise L9.3 checks plans this way, and Exercise P9.1 asks
about a plan with a repeated job.
Evaluator and optimizer¶
In an evaluator-optimizer workflow, one call writes a response and another judges it and gives feedback, in a loop. The article says it fits when there are clear criteria for judging and when feedback measurably improves the response. Anthropic’s prompting best practices calls the same shape, a draft, a review against criteria, and a revision, the most common way to chain prompts.
Worked example. The handbook’s section H03 says a receipt copy needs an invoice reference. For
T10, draft 1 reads “Done! We’ve sent it.” The judge replies “The reply promises a receipt without
an invoice reference. Ask for it.” Draft 2, written from the ticket and that feedback, reads “Could
you send the invoice reference for Tuesday’s repair?” The judge replies pass, so the loop returns
draft 2. With a limit of two drafts, this run made four calls, two drafts and two judgments. If the
judge had rejected both, the loop would return no draft at all, and the code would fall back, for
example to a person. A judge is a grader, so measure its agreement with human labels first, as in
Module 7; a loop amplifies a judge’s mistakes. Exercise L9.4 builds this loop, and Exercise P9.4
counts its calls.
Agents: the model chooses the next step¶
An agent is Module 8’s tool-use loop with the model in charge of its length. Each turn, the model reads the results so far and decides whether to call another tool or to answer. The article says an agent needs ground truth from its environment at each step, such as tool results, to judge its progress. It recommends stopping conditions, such as a maximum number of iterations, and warns that autonomy brings higher costs and the potential for compounding errors. It advises extensive testing in sandboxed environments, with guardrails.
Yao and colleagues’ ReAct paper (ICLR 2023) studied this loop: a model writes reasoning and actions in turn, and each action’s result, such as the text that a Wikipedia lookup returns, informs the next step. With only one or two examples in the prompt, ReAct beat imitation and reinforcement learning methods on two interactive tasks, ALFWorld and WebShop, by 34 and 10 percentage points of success rate.
Limits on turns and cost¶
A loop that the model controls needs two limits that your code enforces:
A turn limit stops the loop after a fixed number of model calls, however cheap each one is.
A cost limit stops it before a call that could take spending over budget. Before each call, reserve the most it can cost.
max_tokenscaps a response’s output, as Module 2 showed, so it sets the reserve. If what you have spent plus the reserve is over the budget, stop without calling. After the call, add what it used.
Worked example. In Lab 9, one credit is one output token, and the budget counts output only. Take a budget of 10 credits, a reserve of 4, and a turn limit of 3:
| Turn | Check before the call | Call? | Used | Spent after |
|---|---|---|---|---|
| 1 | 0 + 4 = 4, not over 10 | Yes | 3 | 3 |
| 2 | 3 + 4 = 7, not over 10 | Yes | 4 | 7 |
| 3 | 7 + 4 = 11, over 10 | No: stop with cost_limit | 7 |
The run spent 7 of its 10 credits, and the cost limit, not the turn limit, stopped it. A real cost
cap counts dollars and reserves input too, and input grows every turn, because the loop resends the
history (Module 2). For a turn on Opus 5.5 with a 2,000-token prompt and max_tokens of 1,000, the
reserve is (2,000 × 4 + 1,000 × 20) / 1,000,000 = 0.028 dollars. Exercise L9.5 builds an agent
with both limits, and Exercise P9.2 traces a run that hits one.
Reading an agent’s log¶
An agent’s log records what it did on each turn, so you can trace a run after it ends. Lab 9 logs the turn number, the credits it used, the total spent, the stop reason, and the tools called:
[{"turn": 1, "used": 3, "spent": 3, "stop": "tool_use",
"tools": ["find_service", "estimate_minutes"]},
{"turn": 2, "used": 4, "spent": 7, "stop": "tool_use", "tools": ["shop_hours"]}]This log, from the run in the table, shows two model calls and three tool calls. No entry has
end_turn, so the run ended without an answer, and the status that the agent returns beside its
log, cost_limit, says why. The log doesn’t show whether the model chose the right tools or would
have answered correctly. A log is evidence of what happened, not of whether it was right; test the
decisions themselves with labeled cases.
Choosing a design¶
Choose by four things about the task: how complex it is, what a good result is worth, how well the model does it, and what an error costs. The article’s rule of thumb is the simplest design that meets the need. Three shop tasks show the range:
| Task | Steps known in advance? | Design |
|---|---|---|
| Route a ticket to one of three queues, with no tools | Yes: one decision | One call, checked as in Module 7 |
| Give the price and the bench time of a named service | Yes: two fixed lookups | A workflow of two parallel lookups, or code that reads MENU with no model at all |
| Plan the repair of a bicycle with several symptoms, checking prices, times, and hours as needed | No: depends on what each lookup finds | An agent with turn and cost limits, and a person’s approval before any paid service is added, as section H07 requires |
Errors compound as steps multiply, as Module 6 computed for chains. If each step of a run is right 95% of the time, independently, a 10-step run is right throughout of the time. An agent is worth that risk, and its extra calls, only when the task’s value justifies them and its errors can be caught or undone.
Common misconceptions¶
“An agent is always better than a workflow.” The article recommends the simplest design that works. An agent routing T10 might make several calls where one suffices, and each extra turn is another chance to go wrong.
“Parallel calls are cheaper.” They send the same tokens, so they cost the same. In the worked example they saved about 1.5 seconds, not money.
“A turn limit caps the cost.” A turn can use up to
max_tokens, and its input grows every turn. Five turns withmax_tokensof 8,000 on Opus 5.5 can spend 5 × 8,000 × 20 / 1,000,000 = 0.80 dollars on output alone. Use a cost limit too.“A plan can run as soon as it parses.”
["parts", "paint"]parses, and names a worker that doesn’t exist. Check the whole plan before any worker runs, or half of it runs.“An evaluator makes the output correct.” It enforces only what the judge checks. A judge that passes everything returns the first draft, however bad.
“A complete log proves the agent worked.” A log that reads
tool_use,end_turnshows two turns and a finished answer, not a correct one.
Summary¶
A workflow’s steps are fixed by your code; an agent’s are chosen by the model in a loop your code runs. Start with the simplest design, and add complexity only when it pays.
Routing picks one branch, parallel calls run independent jobs at once, an orchestrator chooses subtasks for each input, and an evaluator sends drafts back until they pass or a limit stops it.
Validate every model decision before acting on it: an unknown route or job fails before any worker runs.
An agent needs a turn limit and a cost limit. Reserve a call’s maximum cost before calling, and charge what it used after.
A log shows what an agent did, not whether it was right.
Self-check¶
Answer each question before you open its answer.
Which pattern suits independent price and labor lookups?
Answer
Parallel calls, with each result kept under its job’s name. The lookups don’t need each other’s answers, so they can overlap. Running them one after the other gives the same results, only more slowly.
What happens when 4 credits are spent, the next call reserves 3, and the budget is 6?
Answer
The loop stops before the call, with
cost_limit. 4 + 3 = 7 is over 6, so the call might take spending past the budget, and the loop can’t know in advance that it wouldn’t.Would you give a model control over queue routing for three well-defined labels and no tools?
Answer
No. One classifying call, or plain code, handles a single decision among three labels. An agent loop would add calls, cost, and ways to fail without making the decision better.
An orchestrator returns
["labor", "parts"]for a ticket. How many model calls does the workflow make, and how many would a fixed parallel workflow make for the same two jobs?Answer
Three: the planner and two workers. The fixed parallel workflow makes two, because it needs no planner. The extra call buys the ability to choose different jobs for a different ticket.
An agent’s log has three entries, each with
"stop": "tool_use", and the turn limit is 3. How did the run end?Answer
With
turn_limit. Every turn asked for more tools, and none ended withend_turn, so the loop stopped after its third call without an answer.
Further reading¶
Erik S. and Barry Zhang, Building effective agents. The distinction between workflows and agents, each pattern with an example, and when an agent is worth its cost.
Yao and colleagues, “ReAct: Synergizing Reasoning and Acting in Language Models,” ICLR 2023, arXiv:2210.03629. The loop of reasoning, acting, and reading each result, measured on four tasks, from question answering to online shopping.
Python Software Foundation,
concurrent.futures. HowThreadPoolExecutor,submit, andFuture.result()behave, including what happens to an exception raised in a thread.