Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

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:

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.

PatternWho decides the next stepBicycle-shop exampleWhat to check
RoutingA classifying call picks one of a fixed set of branchesSend a receipt request to the billing writerAn unknown route fails loudly
Parallel callsYour code runs independent calls at the same timePrice the parts and estimate the laborEach result keeps its job’s name
Orchestrator and workersA planning call chooses the subtasks for this inputChoose the jobs a mixed ticket needsReject an unknown job before any worker runs
Evaluator and optimizerA judging call accepts a draft or sends it backRevise a receipt reply until it is clearCap 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:

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:

TurnCheck before the callCall?UsedSpent after
10 + 4 = 4, not over 10Yes33
23 + 4 = 7, not over 10Yes47
37 + 4 = 11, over 10No: stop with cost_limit7

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:

TaskSteps known in advance?Design
Route a ticket to one of three queues, with no toolsYes: one decisionOne call, checked as in Module 7
Give the price and the bench time of a named serviceYes: two fixed lookupsA 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 neededNo: depends on what each lookup findsAn 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 0.9510≈0.600.95^{10} \approx 0.60 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

Summary

Self-check

Answer each question before you open its answer.

  1. 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.

  2. 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.

  3. 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.

  4. 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.

  5. 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 with end_turn, so the loop stopped after its third call without an answer.

Further reading