Courses / AI Engineering: LLMs, RAG and Agentic System Design / Chapter 9
Module 4 · Fine-tuning and first agents · Chapter 9 of 24
AI agents and multi-agent systems
Builds on Working with model APIs and Building LLM applications: chains, tools and memory. Next up: Agent design fundamentals.
Part 1 · From a tool call to an agent loop
What an agent is
Support bots, coding helpers and research tools share one trick: the model does not answer in a single step. It asks for information, reads what comes back, and decides what to do next.
The application patterns chapter ended with one tool round trip: the model asks for a call, your code runs it, the result goes back, and the model answers. An agent is that round trip repeated. The model is called in a loop. Each time, it either asks for more tool calls or gives a final answer. Your code runs the calls, appends the results to the message list, and calls the model again. The loop ends when the model replies without a tool call, or when your code decides to stop it.
Anthropic's article on building effective agents draws a useful line. A workflow is a fixed path of steps that your code controls. An agent is a system where the model decides the next step, and how many steps there will be, while your code supplies tools and guards. Because the model chooses, the number of model calls is not known in advance, and that is both the power and the cost of the design.
The pattern has a name from research. The paper *ReAct: Synergizing Reasoning and Acting in Language Models* (Yao et al., 2022) describes models that alternate between reasoning steps and task-specific actions, such as querying an outside source, so that each helps the other. Reasoning decides which action to take, and the action's result feeds the next round of reasoning. Tool-calling APIs give you the same shape without a special text format: the reasoning is the model's turn, the action is a tool_calls entry, and the observation is the tool message you append.
Three parts make up every agent. The model decides. The tools are functions your code exposes, each with a name, a description and an argument schema. The loop is ordinary code that connects them, keeps the message history, and enforces limits. Most agent failures are loop failures: a missing stop rule, a lost message, a tool error the model never saw.
The loop in code
The example works for Pennur Bazaar, a made-up shop that sells groceries and household goods. It has two tools: lookup_price, which reads a small dictionary of catalogue prices, and calculate, which evaluates arithmetic. The calculator parses the expression into a syntax tree and allows only numbers and the four basic operators. It never passes model text to eval, because a model's output is untrusted input.
def lookup_price(item): if item not in PRICES: return f"error: no item {item!r}. Known: {sorted(PRICES)}" return f"{PRICES[item]} rupees" def calculate(expression): def walk(n): is_num = isinstance(n, ast.Constant) if is_num and type(n.value) in (int, float): return n.value if isinstance(n, ast.BinOp) and type(n.op) in OPS: return OPS[type(n.op)](walk(n.left), walk(n.right)) raise ValueError("only + - * / on numbers") try: return str(walk(ast.parse(expression, mode="eval").body)) except (SyntaxError, ValueError, ZeroDivisionError) as e: return f"error: {e}" TOOLS = { "lookup_price": (lookup_price, PriceArgs, "Get the price in rupees of one catalogue item by exact name."), "calculate": (calculate, CalcArgs, "Evaluate an arithmetic expression such as 2 * 640."), }
Above this excerpt, the file defines the PRICES dictionary, two small Pydantic classes for the arguments and a table of allowed operators. The TOOLS table maps each tool name to its function, its argument class and its description, and a helper turns it into the tools list the API expects.
The loop itself is short. It keeps one messages list. Every pass calls the model, appends the model's message, and returns if there are no tool calls. Otherwise it runs each call and appends one tool message per call, with the matching tool_call_id. A step limit bounds the loop.
import json from llm import client, MODEL from shop_tools import TOOLS, specs def run(task, max_steps=6): messages = [{"role": "user", "content": task}] for step in range(1, max_steps + 1): r = client.chat.completions.create( model=MODEL, messages=messages, tools=specs(), reasoning_effort="none") msg = r.choices[0].message messages.append(msg) if not msg.tool_calls: return msg.content for call in msg.tool_calls: args = json.loads(call.function.arguments) fn, model, _ = TOOLS[call.function.name] result = fn(**model(**args).model_dump()) print(f"step {step}: {call.function.name}({args})" f" -> {result}") messages.append({"role": "tool", "tool_call_id": call.id, "content": result}) return None task = ("I want 2 of basmati rice 5kg and 3 of toor dal 1kg. " "What is the total in rupees?") print("answer:", run(task))
A real run
The task asks for a total that needs two lookups and one calculation. The loop prints each tool call as it runs.
step 1: lookup_price({'item': 'basmati rice 5kg'}) -> 640 rupees step 1: lookup_price({'item': 'toor dal 1kg'}) -> 165 rupees step 2: calculate({'expression': '(2 * 640) + (3 * 165)'}) -> 1775 answer: The total cost for 2 units of basmati rice 5kg and 3 units of toor dal 1kg is 1,775 rupees.
Output from one run; yours will differ. Long lines are wrapped here.
Step 1 contains two tool calls. The model asked for both prices in the same turn, so the loop ran both before calling the model again. Step 2 is the calculation, built from the two results. Step 3, which prints nothing because it has no tool call, is the final answer. Three model calls and three tool calls produced one answer.
The model was free to pick a different path. It could have looked up the prices one at a time, or computed the sum in its head and skipped the calculator. Run the script again and the number of steps may change, though a correct run always needs the two prices. The wording of the answer changes too: in two later runs of this script the model wrote a total of 1,770 rupees although the calculator had returned 1775, an arithmetic slip that the third lesson shows. That variation is why the loop needs limits, which the third lesson adds.
Watch for the loop repeating until the model stops asking for tools
Read it as steps
The model calls tools until it has what it needs, then answers.
Part 2 · Tools a model can use well
Names, descriptions and schemas
The model sees a tool only through its definition: a name, a description and a JSON Schema for the arguments. It has no other way to learn what the tool does. A tool the model uses badly is usually a tool that was described badly.
Good tool design follows a few habits. Name the tool with a verb and a noun that match what it does, such as lookup_price. Write the description as an instruction for when to use it and what it returns, including the format of any identifier it needs. Keep the argument list short, and give each argument a type the schema can enforce. A tool with many optional arguments invites the model to guess.
The script prints the definition that the loop sends for lookup_price, then feeds three bad calls to the same function the loop uses to run tools.
import json from types import SimpleNamespace as NS from agent import specs, run_tool from shop_tools import TOOLS fn = specs(TOOLS)[0]["function"] print(fn["name"]) print(fn["description"]) print(json.dumps(fn["parameters"]["properties"])) print(fn["parameters"]["required"]) for name, raw in (("lookup_price", '{"name": "ghee 500ml"}'), ("lookup_price", "not json"), ("refund", "{}")): call = NS(function=NS(name=name, arguments=raw)) print(name, raw) print(" ", run_tool(TOOLS, call))
lookup_price
Get the price in rupees of one catalogue item by exact name.
{"item": {"title": "Item", "type": "string"}}
['item']
lookup_price {"name": "ghee 500ml"}
error: bad arguments: Field required
lookup_price not json
error: bad arguments: Invalid JSON: expected ident at line 1
column 2
refund {}
error: unknown tool 'refund'Output from one run. Long lines are wrapped here.
The schema comes from the Pydantic class, so the definition the model reads and the validator that checks its arguments cannot drift apart. The three bad calls each return a short error string and none raises an exception. A wrong field name gives Field required, text that is not JSON gives a parse error, and an unknown tool name is reported by name.
Errors the model can act on
A tool call can fail for many reasons: the arguments are wrong, the item does not exist, a service is down. What matters is what the model reads next. An error written for a developer, such as a bare error, tells the model nothing about how to repair the call. An error that names the problem and the valid options lets the model fix its own mistake.
The next script compares the two on one task. The catalogue holds ghee 500ml, with no space before ml, and the user writes ghee 500 ml. The terse tool returns the single word error for an unknown item. The helpful tool returns the unknown name and the list of known names. Each variant runs five times, and the script checks whether the final answer contains the correct total, 1,640 rupees for four units.
import re import shop_tools from agent import run_agent from shop_tools import TOOLS, PriceArgs def terse_lookup(item): return "error" if item not in shop_tools.PRICES else \ f"{shop_tools.PRICES[item]} rupees" TERSE = dict(TOOLS) TERSE["lookup_price"] = (terse_lookup, PriceArgs, TOOLS["lookup_price"][2]) task = "How much do 4 of ghee 500 ml cost in rupees?" for label, tools in (("terse", TERSE), ("helpful", TOOLS)): ok = 0 for i in range(5): r = run_agent(task, tools) text = r.answer or "" good = bool(re.search(r"(?<![\d,])1,?640(?![\d,])", text)) ok += good print(label, i, r.stop, r.steps, "correct" if good else "wrong") if label == "terse" and not good: print(" ", text[:60]) print(label, "correct", ok, "of 5")
terse 0 final 5 wrong I'm sorry, but I don't have any information on the price of terse 1 final 3 wrong I'm sorry, but I cannot find the price for "ghee 500 ml" in terse 2 final 6 wrong I'm sorry, but I couldn't find the price for "ghee 500 ml" i terse 3 final 5 wrong I'm sorry, but I couldn't find the price for "ghee 500 ml" i terse 4 final 5 wrong I'm sorry, but I couldn't find the price for "ghee 500 ml" i terse correct 0 of 5 helpful 0 final 4 correct helpful 1 final 4 correct helpful 2 final 4 correct helpful 3 final 4 correct helpful 4 final 4 correct helpful correct 5 of 5
Output from one run; yours will differ.
With the helpful error, every run found the right item name on its second call and gave the correct answer. With the terse error, all five runs in this output ended with an apology and a request for more information, because the model had nothing to repair the call with. The script was run four times for this lesson. The helpful error gave 5 correct of 5 every time. The terse error gave 0 of 5 in three runs and 3 of 5 in the fourth, where the model guessed the exact item name without help. In one of the zero-correct runs the repeated-call limit of the next lesson stopped three runs that kept asking for the same item. This is one model and a few runs, so read it as a direction and not a rate.
Rules for tool results
Return errors as results, not exceptions. An exception inside the loop stops the whole run, while a result string goes back into the conversation, where the model can act on it. Log the full error for yourself as well.
Keep results short and in plain text or small JSON. Everything a tool returns is added to the context, so a tool that returns a whole database table spends tokens on every later step and can push earlier messages out of the window. Return what the next decision needs, and offer a narrower tool or a limit argument for the rest.
Treat every argument as untrusted input. The model may have been steered by text it read earlier, so validate types and ranges as you would for a web form, and never build a shell command, file path or query by pasting model text into it.
Prefer fewer, sharper tools. Two tools with overlapping descriptions force the model to choose between near-identical options and sometimes it picks the wrong one. If you can merge them, do. If you cannot, say in each description when the other one is the better choice.
A tool fails because an argument is invalid. Should it raise an exception or return text, and why?
- Return text that names the problem and the valid options. The model reads the result and can repair its call, while an exception would end the run.
Why does the script build the tool schema from the Pydantic class that also validates the arguments?
- One definition drives both, so the description the model sees and the check your code applies cannot disagree.
In the comparison, the helpful error gave 5 correct answers of 5 and the terse error gave fewer. What can you not conclude from that?
- That the rates hold in general. Five runs per variant is a small sample, and the counts differ between runs, so it shows a direction, not a measured rate.
Part 3 · Budgets and stop rules
Why every loop needs limits
A loop that stops when the model says it is done has a weakness: the model decides when that is. A model can keep calling tools without making progress, repeat the same call because the result did not help, or wander through a long task and spend far more than the task is worth. Each model call costs tokens and seconds, and an agent's calls are added up across steps.
Four limits cover most failures. A step budget caps the number of model calls. A token budget caps the total tokens used across calls. A deadline caps wall-clock time. Repeated-call detection stops the run when the same tool is called with the same arguments more than a set number of times, which is the usual sign of a loop going nowhere. Each limit ends the run with a named reason, so that the caller can tell a finished answer from a forced stop.
Stopping is not the same as failing quietly. The loop returns a result object with the answer, or None, the reason it stopped, the steps and tokens used, and the list of calls. The caller can then retry with a bigger budget, escalate to a person, or show a clear message. A run that ends because of a limit must never look like a run that ended because the model finished.
The full loop, with the limits added, is in agent.py. The model call is a parameter, which will matter in a moment.
def run_agent(task, tools, model=real_model, max_steps=6, max_tokens=20000, deadline_s=120, max_repeat=2): messages = [{"role": "user", "content": task}] seen, calls, used = {}, [], 0 start = time.monotonic() for step in range(1, max_steps + 1): if time.monotonic() - start > deadline_s: return Result(None, "deadline", step - 1, used, calls) msg, tokens = model(messages, tools) used += tokens messages.append(msg) if not msg.tool_calls: return Result(msg.content, "final", step, used, calls) if used > max_tokens: return Result(None, "token_budget", step, used, calls) for call in msg.tool_calls: key = (call.function.name, call.function.arguments) seen[key] = seen.get(key, 0) + 1 if seen[key] > max_repeat: return Result(None, "repeated_call", step, used, calls) result = run_tool(tools, call) calls.append((call.function.name, call.function.arguments, result)) messages.append({"role": "tool", "tool_call_id": call.id, "content": result}) return Result(None, "max_steps", max_steps, used, calls)
Testing the limits without a model
Limits are code, so they can be tested like code. A test that calls the real model is slow and its behaviour varies, so it cannot reliably produce a runaway loop. A scripted fake model solves this. It is a function with the same signature as the real model call that returns the replies you choose. A test can then force a model that never stops, one that repeats itself, or one that burns tokens, and check that the loop stops at the right point.
The tests below use the pytest runner. Each builds a fake model and checks the stop reason and the counts.
from types import SimpleNamespace as NS from agent import run_agent from shop_tools import TOOLS def call(i, name, args): return NS(id=f"c{i}", function=NS(name=name, arguments=args)) def scripted(*turns, tokens=100): it = iter(turns) def model(messages, tools): content, calls = next(it) return NS(content=content, tool_calls=calls), tokens return model def looping_model(tokens=100): n = {"i": 0} def model(messages, tools): n["i"] += 1 args = '{"item": "ghee 500ml %d"}' % n["i"] return NS(content=None, tool_calls=[ call(n["i"], "lookup_price", args)]), tokens return model def test_final_answer(): m = scripted((None, [call(1, "lookup_price", '{"item": "ghee 500ml"}')]), ("410 rupees", None)) r = run_agent("price?", TOOLS, model=m) assert (r.stop, r.answer, r.steps) == ("final", "410 rupees", 2)
The remaining tests cover the token budget, the deadline and an unknown tool name. For the token budget, each fake reply costs 900 tokens and the limit is 2,000, so the third step crosses it. The run command and its result follow.
uv run python -m pytest -q test_agent.py
...... [100%] 6 passed in 0.70s
Output from one run; the run of spaces before the percentage is shortened. Timing varies on this machine.
All six pass, including the step budget, where the fake model asks for a new tool call on every turn and the loop stops after exactly three. These tests do not prove the real model behaves; they prove that the limits work when it does not.
A limit firing on a real model
Every run in the previous lesson ended with the stop reason final, because none of them came near a limit. To see a limit fire on the real model, tighten it. The shop task from the first lesson needs three model calls, so a budget of two cannot finish it.
from agent import run_agent from shop_tools import TOOLS task = ("I want 2 of basmati rice 5kg and 3 of toor dal 1kg. " "What is the total in rupees?") for limit in (2, 6): r = run_agent(task, TOOLS, max_steps=limit) print(f"max_steps={limit}: stop={r.stop} steps={r.steps} " f"tokens={r.tokens} calls={len(r.calls)}") print(" answer:", r.answer)
max_steps=2: stop=max_steps steps=2 tokens=432 calls=3 answer: None max_steps=6: stop=final steps=3 tokens=728 calls=3 answer: The total cost for 2 bags of basmati rice 5kg and 3 bags of toor dal 1kg is 1,770 rupees.
Output from one run; yours will differ. Long lines are wrapped here.
With a budget of two steps the loop stopped with max_steps, returned no answer, and still reported that three tool calls had run. With six steps it finished in three. The caller sees a named reason, not a silent answer. The finished run also shows why limits are not enough: its answer states a total of 1,770 rupees, while two bags at 640 and three packs at 165 come to 1,775. The model made an arithmetic slip even with a calculator result in front of it. A loop can bound a run, but only a check on the answer can catch a wrong one.
Choosing the numbers is a design decision. Set the step budget from the task: a simple lookup may need four steps, a research task twenty. Set the token budget from what the task is worth in money. Set the deadline from what the user will tolerate. Start tight, watch how often runs hit a limit in your logs, and raise a limit only when a hit run would have succeeded with more room.
Provider-side limits add to yours. A request has a context window, a maximum output length and rate limits. Your budget should sit well inside those, so that your own rule fires before a provider error does.
Which stop reason fires when the model asks for the same lookup a third time, with the default of two repeats allowed?
repeated_call. The call is counted by tool name and exact argument string, and the run stops before the call executes.
Part 4 · Role-based agents and a sequential team
Roles, goals and tasks
One agent with many tools can handle a task end to end. Sometimes it is easier to split the work between several agents, each with its own instructions and a narrow job, and pass results between them. The common vocabulary for this comes from frameworks such as CrewAI, whose documentation describes an agent by a role, a goal and a backstory, and a task by a description and an expected output.
These are not new mechanisms. A role, goal and backstory are three sentences placed in the system message. A task is a user message with a description and a required output format. An agent run is a model call, or a loop, with those messages. The vocabulary is useful because it makes each part of the prompt a named field you can review and change.
A sequential process runs the tasks in a fixed order. The output of each task is available to the ones after it. CrewAI names this process sequential and also offers a hierarchical one, which the next lesson builds. Here the same shape is written in plain Python, with a small dataclass for the agent, another for the task, and one function that runs a task.
@dataclass class Agent: role: str goal: str backstory: str def system(self): return (f"You are a {self.role}. Your goal: {self.goal} " f"{self.backstory}") @dataclass class Task: description: str expected_output: str agent: Agent USAGE = {"calls": 0, "tokens": 0} def run_task(task, context=""): prompt = (f"Task: {task.description}\n" f"Expected output: {task.expected_output}\n") if context: prompt += f"\nInput from the previous step:\n{context}" msg, r = chat([{"role": "system", "content": task.agent.system()}, {"role": "user", "content": prompt}], max_tokens=400, temperature=0.3) USAGE["calls"] += 1 USAGE["tokens"] += r.usage.total_tokens return msg.content.strip()
A three-step team over made-up notes
The team has a researcher, a writer and a reviewer. The input is five short notes about a milk collection centre run by a village cooperative. The researcher lists the facts, the writer turns them into a note for farmers, and the reviewer checks the note against the facts and replies APPROVED or REVISE.
from team import Agent, Task, run_task, USAGE NOTES = """- Collection centre opens 6:00, closes 9:30 daily. - Milk is paid every 10 days, by bank transfer. - Fat below 3.5 percent is paid at the lower rate. - Cans must be at the centre by 9:00 to be tested. - The centre is closed on the second Sunday of each month.""" researcher = Agent("researcher", "pull out only the facts a farmer needs.", "You never add facts that are not in the notes.") writer = Agent("writer", "write a clear note for farmers.", "You write short plain English for readers in a village.") RULE = "You reply APPROVED, or REVISE and one line saying why." reviewer = Agent("reviewer", "check the note against the facts.", RULE) tasks = [ Task("List the facts in the notes as short bullets.", "5 bullets, no extra facts.", researcher), Task("Write a note of at most 60 words for farmers.", "One paragraph.", writer), Task("Check the note against the bullets.", "APPROVED, or REVISE and one line.", reviewer), ] if __name__ == "__main__": context = "Notes:\n" + NOTES for t in tasks: out = run_task(t, context) context += f"\n\n{t.agent.role} output:\n{out}" print(f"[{t.agent.role}] {out}\n") print(USAGE)
The loop at the bottom of the script passes the notes plus every earlier output to the next task. Passing only the previous output would starve the reviewer, which needs the facts and the note to compare them.
[researcher] - Collection centre opens 6:00 and closes 9:30 daily. - Milk is paid every 10 days by bank transfer. - Fat below 3.5 percent is paid at the lower rate. - Cans must be at the centre by 9:00 to be tested. - The centre is closed on the second Sunday of each month. [writer] The collection centre is open daily from 6:00 to 9:30. Please bring your milk cans by 9:00 for testing. Payment is sent to your bank every 10 days. Note that milk with less than 3.5% fat gets a lower price. The centre is closed on the second Sunday of every month. [reviewer] APPROVED {'calls': 3, 'tokens': 897}
Output from one run; yours will differ. Long lines are wrapped here.
Three calls and 897 tokens produced a note and a verdict. The writer used only facts from the researcher's list, and the reviewer approved it. The wording of the writer's note differs from run to run.
Handoffs and what can go wrong
Watch for each agent seeing the outputs of the steps before it
Read it as steps
Each step sees the notes and everything the earlier steps wrote.
The scene shows that the agents never talk to each other. Your code is the only thing that sends messages, so the whole team is a function that calls other functions in order. That makes a sequential team easy to log and test: each step has an input, an output and a token count.
The design has costs. Errors flow downstream: if the researcher invents a fact, the writer will state it and the reviewer, given the same wrong list, may approve it. The reviewer is also a model, so its verdict needs the same scepticism as any model output. Give reviewers a narrow, checkable rule, such as comparing against the list, and prefer a code check wherever one exists, such as a word count or a required field.
Role prompts help most when roles differ in what they are told to do, not only in what they are called. A writer told to use short words for village readers will write differently from a researcher told never to add facts. If two roles would get the same instructions, they are one agent.
In the script, why does the reviewer's task receive the notes and the researcher's bullets as well as the note?
- The reviewer must compare the note with the facts. If it received only the note, it would have nothing to check the note against.
Part 5 · A manager-led team
A manager that assigns work
A sequential team has a fixed order. A manager-led team does not: one agent, the manager, looks at the current state of the work and chooses which worker should act next, or decides the work is finished. CrewAI calls this its hierarchical process and requires a manager_llm or a manager_agent for it. The same idea is called an orchestrator in the patterns of the next chapter.
The manager's job is a routing decision with memory. Given the goal and everything produced so far, it names the next worker and why. Because your code has to act on that choice, the manager should answer in a fixed format, not free text. A schema with a closed list of worker names removes the risk that the manager invents one.
The script defines the decision as a Pydantic class with a Literal field and asks the model to fill it using chat.completions.parse, which the model APIs chapter introduced. The loop runs the chosen worker, appends its output to the history, and asks the manager again. A hard cap of six turns bounds it.
class Decision(BaseModel): worker: Literal["researcher", "writer", "reviewer", "done"] reason: str SYSTEM = ("You manage a team: researcher (extracts facts), writer " "(drafts the note), reviewer (checks it). Pick the next " "worker. Reply done once the note is approved.") def decide(history): msgs = [{"role": "system", "content": SYSTEM}, {"role": "user", "content": history}] r = client.chat.completions.parse( model=MODEL, messages=msgs, response_format=Decision, reasoning_effort="none", max_tokens=200) USAGE["calls"] += 1 USAGE["tokens"] += r.usage.total_tokens return r.choices[0].message.parsed
The loop that drives it prints each decision, then runs the chosen worker and adds its output to the history.
history = "Goal: a farmer note from these notes.\n" + NOTES for turn in range(1, 7): d = decide(history) print(f"turn {turn}: {d.worker} | {d.reason[:40]}") if d.worker == "done": break agent, job = WORKERS[d.worker] out = run_task(Task(job, "Short.", agent), history) history += f"\n\n{d.worker} output:\n{out}" print(" ->", out.split()[0]) done = out.strip().strip("*#").upper().startswith("APPROVED") if "--code-stop" in sys.argv and done: print("code: reviewer approved, stop") break print(USAGE)
What the manager actually did
The workers are the three agents from the last lesson, and the goal is the same note for farmers. The loop at the end of the script prints each decision, the first word of the worker's output and, at the end, the totals.
turn 1: researcher | I need to extract the core facts from th -> - turn 2: writer | The researcher has extracted the key fac -> Dear turn 3: reviewer | The writer has produced a draft based on -> APPROVED turn 4: reviewer | The researcher extracted all key facts, -> APPROVED turn 5: reviewer | The reviewer has already approved the no -> APPROVED turn 6: writer | The researcher has extracted the facts, -> Dear {'calls': 12, 'tokens': 3926}
Output from one run; yours will differ.
The manager chose the researcher, then the writer, then the reviewer, which is the right order. Then it kept going. The reviewer had already replied APPROVED, but the manager never said done, and the run only ended because the cap of six turns was reached. It used 3,926 tokens over 12 calls, where the sequential team used 897 over 3. The extra turns changed nothing.
The manager's instructions said to reply done once the note is approved, so a prompt rule was not enough. The manager is a model reading a long history, and it did not apply the rule. Wording the instruction more strongly may help but is no guarantee. A better design takes the decision out of the model wherever your code can make it. The script's --code-stop flag does that: when the reviewer's output starts with APPROVED, the loop stops.
turn 1: researcher | The researcher needs to organize and str -> - turn 2: writer | The researcher has successfully extracte -> **Notice turn 3: reviewer | The writer has successfully synthesized -> APPROVED code: reviewer approved, stop {'calls': 6, 'tokens': 1737}
Output from one run; yours will differ.
With the code rule, the run ended after three turns and 1,737 tokens. The manager still decided the order of workers. Code decided when to stop.
One agent or many
A team costs more than one agent. For comparison, one call that wrote the same note from the same facts, with no team at all, follows.
Dear Farmers, The collection centre is open daily from 6:00 to 9:30. To ensure testing, cans must arrive by 9:00. Note that fat below 3.5% receives a lower rate. Payments are made via bank transfer every 10 days. Please note: the centre is closed on the second Sunday of every month. {'calls': 1, 'tokens': 197}
Output from one run; yours will differ. Long lines are wrapped here.
It used 197 tokens for one call. The note is as good as the team's note for this task. That is the usual finding for work this small: splitting it adds calls, tokens, delay and places to fail, and buys nothing.
A team earns its cost in a few situations. The work divides into parts that need different instructions or different tools, so that one prompt would grow long and confused. The parts can run in parallel. A step needs an independent check, so a second agent with a different brief is worth having. Or the context for one job would crowd out another. When none of these hold, use one agent, and add roles only when a measured failure points to a role.
Whatever the structure, keep the same controls from the third lesson: a step cap for the manager, a budget for each worker, and a logged reason for every stop. Test the manager with a scripted fake, as before: feed it decisions in a fixed order and check that the loop obeys the cap and the code stop.
Why does the manager answer through a schema with a Literal list of workers?
- Your code must act on the choice. A closed list guarantees the value is a real worker or
done, so no free text needs parsing.
The run ended only because of the six-turn cap. What went wrong and what is the fix?
- The manager never chose
done, although its prompt said to. Make the stop a code rule: stop when the reviewer's output starts withAPPROVED.
For the milk-centre note, was the team better than one call?
Part 6 · Tools over MCP
Why a protocol for tools
So far each tool was a Python function written inside the agent's own program. If ten applications want the same price lookup, each has to copy it, and each has to learn how every other service exposes its tools. The Model Context Protocol (MCP) is an open protocol that standardises this connection between an application that uses a model and the services that provide tools and data.
The specification (revision 2026-07-28) defines three roles. A host is the application that contains the model and starts connections. A client is a connector inside the host that talks to one server. A server is a program that offers capabilities. Messages are JSON-RPC 2.0. A server can offer tools (functions the model can call), resources (data the application can read) and prompts (templates). A client can offer elicitation, which lets a server ask the user for more information.
For tools, the client asks for the list with a tools/list request. Each tool has a name, a description and an inputSchema in JSON Schema, which is exactly what a Chat Completions tool definition needs. The client calls one with tools/call, giving the name and arguments, and receives content blocks plus an isError flag. In this revision requests are stateless and self-contained, so each carries its own metadata, and the specification notes that a server holding state across calls should return explicit handles.
MCP changes where the tool lives, not how the model sees it. The model still receives a list of function definitions and still replies with tool_calls. Your loop translates in the middle.
Watch for the tool list arriving before any tool is called
Read it as steps
A server and a client in Python
The Python SDK (mcp 2.3.0) provides MCPServer. A decorated function becomes a tool: its name, its docstring and its type hints become the definition. A resource is registered with a URI. Raising ToolError returns an error whose message the model can read.
from mcp.server.mcpserver import MCPServer from mcp.server.mcpserver.exceptions import ToolError import shop_tools mcp = MCPServer("shop") @mcp.tool() def lookup_price(item: str) -> str: """Get the price in rupees of one catalogue item by exact name.""" if item not in shop_tools.PRICES: raise ToolError(f"no item {item!r}") return f"{shop_tools.PRICES[item]} rupees" @mcp.resource("shop://catalogue") def catalogue() -> str: """The item names the shop sells.""" return ", ".join(sorted(shop_tools.PRICES))
Its Client can connect to a server object in the same process, which suits tests and demos. A real deployment would connect to a separate process over a transport such as standard input and output or HTTP. The script lists the tools, calls one, calls it with a bad item, calls a tool that does not exist, and reads the resource.
import asyncio from mcp import Client from mcp_server import mcp async def main(): async with Client(mcp) as client: print("server:", client.server_info.name, "| protocol:", client.protocol_version) tools = (await client.list_tools()).tools for t in tools: print("tool:", t.name, "|", t.description) print("args:", t.input_schema["properties"], t.input_schema["required"]) res = await client.call_tool("lookup_price", {"item": "ghee 500ml"}) print("is_error:", res.is_error) print("content:", res.content[0].text) print("structured:", res.structured_content) bad = await client.call_tool("lookup_price", {"item": "tea"}) print("unknown item:", bad.is_error, "|", bad.content[0].text) odd = await client.call_tool("refund", {}) print("unknown tool:", odd.is_error, "|", odd.content[0].text) r = await client.read_resource("shop://catalogue") print("resource:", r.contents[0].text) asyncio.run(main())
server: shop | protocol: 2026-07-28 tool: lookup_price | Get the price in rupees of one catalogue item by exact name. args: {'item': {'title': 'Item', 'type': 'string'}} ['item'] is_error: False content: 410 rupees structured: {'result': '410 rupees'} unknown item: True | Error executing tool lookup_price: no item 'tea' unknown tool: True | Unknown tool: refund resource: basmati rice 5kg, ghee 500ml, toor dal 1kg
Output from one run. Long lines are wrapped here.
Wiring the tool into the loop
The loop from the first lesson needs two changes. It lists the server's tools once and converts each to a function definition, and it sends calls to the client instead of a local dictionary. The conversion is one dict, because the inputSchema is already a JSON Schema.
import asyncio import json from mcp import Client from llm import client as llm, MODEL from mcp_server import mcp def to_spec(t): return {"type": "function", "function": { "name": t.name, "description": t.description, "parameters": t.input_schema}} async def main(task, max_steps=5): async with Client(mcp) as tools: specs = [to_spec(t) for t in (await tools.list_tools()).tools] messages = [{"role": "user", "content": task}] for step in range(1, max_steps + 1): r = llm.chat.completions.create( model=MODEL, messages=messages, tools=specs, reasoning_effort="none") msg = r.choices[0].message messages.append(msg) if not msg.tool_calls: return msg.content for c in msg.tool_calls: args = json.loads(c.function.arguments) res = await tools.call_tool(c.function.name, args) text = res.content[0].text print(f"step {step}: {c.function.name}{args} -> {text}") messages.append({"role": "tool", "tool_call_id": c.id, "content": text}) print(asyncio.run(main("What does 1 ghee 500ml cost?")))
step 1: lookup_price{'item': '1 ghee 500ml'} -> Error executing tool lookup_price: no item '1 ghee 500ml' step 2: lookup_price{'item': 'ghee 500ml'} -> 410 rupees 1 ghee 500ml costs 410 rupees.
Output from one run; yours will differ. Long lines are wrapped here.
In this run the model first asked for the item 1 ghee 500ml, with the quantity stuck to the name. The server raised ToolError, the message came back as the tool result, and on the second step the model asked for ghee 500ml and got the price. That is the repair loop of the second lesson working across the protocol. The agent code knows nothing about how the price is looked up, so swapping the server leaves the loop unchanged.
A protocol that lets a model call any server's tools also lets a hostile or careless server do harm. The specification states that tools represent arbitrary code execution and that hosts must obtain explicit user consent before invoking any tool. Tool annotations must be treated as untrusted unless they come from a trusted server. For this chapter's read-only price lookup, consent is trivial. For a tool that sends money or messages, build a confirmation step into the host, as the next chapter does with guards and approval.