What You Will Build
Every agent in this course, however many work together, runs the same small
loop: send the conversation to a model, run any tools it asks for, send back
the results, and repeat until it answers. In this lesson you write that loop
as three modules of the course's kit package: the message format, a
scripted model that stands in for a real one, and the loop itself. Every
later lesson builds on them without changing them.
This module is a bridge. If you have already built a tool-calling agent (for example in Building AI Agents and Tool-Calling Workflows), try the readiness check below; if you can answer it, read the exercise quickly, save the files and move on. Either way you need the three files, because later lessons import them.
Readiness Check: Read a Recorded Exchange
Here is a recorded conversation between a program and a model. Mark which messages the program wrote and which the model wrote, and predict the next message.
1 user "Is order A-1007 on its way?"
2 assistant text "Let me check."
tool_use id=toolu_01 name=order_status input={"order_id": "A-1007"}
stop_reason: tool_use
3 user tool_result for toolu_01:
{"order_id": "A-1007", "status": "shipped", "placed_on": "2026-10-14"}
The answer is in Answer and Reasoning.
Model Basics You Will Need
A language model reads text and writes text. Both are measured in tokens, pieces of a few characters each; in English a token is often about four characters. A model reads at most a fixed number of tokens at once (its context window), and everything it should know for a request must be in that request: the instructions (the system text), the conversation so far and the descriptions of the tools it may use. Providers charge per token, separately for input and output. For example, on 2026-10-21 Claude Opus 5.5 cost $4 per million input tokens and $20 per million output tokens (S18), so a call that reads 1,000 tokens and writes 200 costs about $0.004 + $0.004 = $0.008. Prices change; always date them.
Two more facts matter throughout the course. A model can write fluent text that is wrong, so its output is checked, never trusted as fact. And the same request can produce different answers on different runs, which is why the course practises with scripted models whose answers you control.
Messages, Tools and Stop Reasons
The loop speaks the format of the Claude Messages API (S19, S20).
- A conversation is a list of messages, each with a role,
userorassistant, and content: a string, or a list of blocks. - A
textblock holds words. - A tool definition tells the model a tool exists: its name, a
description, and an input schema saying what input it accepts. The
schema is written in JSON Schema, a standard way to describe JSON data:
{"type": "object", "properties": {"order_id": {"type": "string"}}, "required": ["order_id"]}means "an object with a string field calledorder_id, which must be present". - When the model wants a tool, its reply contains a
tool_useblock with anid, the tool'snameand aninput, and the reply's stop reason istool_use. - The program runs the tool and sends back a
tool_resultblock carrying the sameid(astool_use_id), the result ascontent, andis_error: trueif it failed. All results for one reply go back in one user message, immediately after it. - Any other stop reason ends the turn:
end_turn(the model has answered),max_tokens(it ran out of output space),refusal(it declined) and a few others.

The loop in kit/loop.py. The left arrow is the next step; blue labels are
the events reported to on_event.
Exercise: Run an Agent Three Ways
Goal: save the three kit modules and an order-status agent, then run the agent through a success, a tool error and a step-limit stop, predicting each message history first.
Starting state: lessons 1 to 3 completed, with kit/shop.py saved
(watch-a-multi-agent-run)
and the course environment active. Check:
python -c "from kit.shop import shop_tools; print('kit ready')"
Effects: adds three kit modules (kept for the rest of the course) and an
exercise folder with one script and a shop.sqlite3 file. Runs take well
under a second and make no network calls.
-
Save this as
kit/messages.pyin your practice folder:"""Messages and content blocks in the shape the Claude Messages API uses. A conversation is a list of messages. Each message has a role ("user" or "assistant") and content: a string, or a list of blocks. The blocks used in this course are text, tool_use (the model asks for a tool) and tool_result (the program answers it). """ def text(value): return {"type": "text", "text": value} def tool_use(block_id, name, tool_input): return {"type": "tool_use", "id": block_id, "name": name, "input": tool_input} def tool_result(tool_use_id, content, is_error=False): return {"type": "tool_result", "tool_use_id": tool_use_id, "content": content, "is_error": is_error} def user(content): return {"role": "user", "content": content} def assistant(blocks): return {"role": "assistant", "content": blocks} def blocks_of(message, kind): """The blocks of one kind in a message, in order.""" content = message["content"] return [] if isinstance(content, str) else [b for b in content if b["type"] == kind] def final_text(message): """All text blocks of a message joined into one string.""" content = message["content"] return content if isinstance(content, str) else " ".join(b["text"] for b in blocks_of(message, "text")) -
Save this as
kit/scripted.pyin your practice folder:"""A scripted model: a stand-in for a language model that answers from rules you write. create() returns a response with the fields of a Claude Messages API response: content blocks, a stop reason and token usage. The token counts are illustrative (about four characters per token), not a real tokenizer's. """ import json import math from kit.messages import text def count_tokens(value): """An illustrative token count: about four characters of JSON per token.""" return max(1, math.ceil(len(json.dumps(value)) / 4)) def say(value): """A reply with one text block.""" return [text(value)] def call(name, **tool_input): """A tool_use block; the model fills in its ID when it replies.""" return {"type": "tool_use", "id": None, "name": name, "input": tool_input} class ScriptedModel: """Answers each request from a rule, or from a list of replies used in order. A reply is a list of blocks, or a dict with "content" and "stop_reason" for anything other than the usual end_turn or tool_use. rule(messages) receives the conversation so far and returns a reply. """ def __init__(self, rule=None, replies=None, name="scripted"): if (rule is None) == (replies is None): raise ValueError("give exactly one of rule or replies") self.rule = rule self.replies = None if replies is None else list(replies) self.name = name self.calls = 0 self.tool_calls = 0 def create(self, *, system, messages, tools=(), max_tokens=1024): self.calls += 1 if self.rule is not None: reply = self.rule(messages) elif self.replies: reply = self.replies.pop(0) else: raise RuntimeError(f"{self.name} has no scripted reply left for call {self.calls}") if isinstance(reply, dict): content, stop_reason = reply["content"], reply["stop_reason"] else: content = reply stop_reason = "tool_use" if any(b["type"] == "tool_use" for b in content) else "end_turn" content = [dict(block) for block in content] # copies, so a script can reuse its blocks for block in content: if block["type"] == "tool_use" and block["id"] is None: self.tool_calls += 1 block["id"] = f"toolu_{self.name}_{self.tool_calls:02d}" return { "id": f"msg_{self.name}_{self.calls:02d}", "type": "message", "role": "assistant", "model": self.name, "content": content, "stop_reason": stop_reason, "stop_sequence": None, "usage": {"input_tokens": count_tokens([system, list(tools), messages]), "output_tokens": count_tokens(content)}, } -
Save this as
kit/loop.pyin your practice folder:"""The agent loop: call the model, run the tools it asks for, repeat until it stops. run_agent() works with any model object whose create(system=, messages=, tools=) returns a Messages-API-shaped response. Tools are a dictionary of name -> {"description", "input_schema", "fn"}. If on_event is given, it is called with a dictionary for the start of the run, every model call, every tool call and the end of the run. """ import json import time from dataclasses import dataclass, field from kit.messages import assistant, blocks_of, final_text, tool_result, user JSON_TYPES = {"string": str, "integer": int, "number": (int, float), "boolean": bool, "object": dict, "array": list} @dataclass class AgentResult: stop_reason: str text: str messages: list steps: int usage: dict = field(default_factory=dict) def validate(schema, value): """Check a tool input against the JSON Schema subset tools use; return the problems.""" if not isinstance(value, dict): return ["input must be an object"] problems = [f"missing required field '{name}'" for name in schema.get("required", []) if name not in value] properties = schema.get("properties", {}) for name, item in value.items(): spec = properties.get(name) if spec is None: if schema.get("additionalProperties") is False: problems.append(f"unexpected field '{name}'") continue expected = JSON_TYPES.get(spec.get("type")) is_number = spec.get("type") in ("integer", "number") if expected and (not isinstance(item, expected) or (is_number and isinstance(item, bool))): problems.append(f"field '{name}' must be of type {spec['type']}") elif "enum" in spec and item not in spec["enum"]: problems.append(f"field '{name}' must be one of {spec['enum']}") return problems def tool_definitions(tools): """What the model is told about each tool: its name, description and input schema.""" return [{"name": name, "description": tool["description"], "input_schema": tool["input_schema"]} for name, tool in tools.items()] def run_tools(blocks, tools, emit): """Run every tool_use block and return their tool_result blocks in the same order.""" results = [] for block in blocks: started = time.perf_counter() tool = tools.get(block["name"]) if tool is None: content, is_error = f"unknown tool '{block['name']}'; available: {', '.join(tools)}", True elif problems := validate(tool["input_schema"], block["input"]): content, is_error = "invalid input: " + "; ".join(problems), True else: try: content, is_error = json.dumps(tool["fn"](**block["input"])), False except Exception as error: # the model sees the error and can react to it content, is_error = f"{type(error).__name__}: {error}", True results.append(tool_result(block["id"], content, is_error)) emit({"type": "tool_call", "tool": block["name"], "input": block["input"], "is_error": is_error, "seconds": time.perf_counter() - started}) return results def finish_run(stop_reason, messages, steps, usage, agent, emit): """Build the result and report the end of the run.""" last = messages[-1] result = AgentResult(stop_reason, final_text(last) if last["role"] == "assistant" else "", messages, steps, dict(usage)) emit({"type": "run_end", "agent": agent, "stop_reason": stop_reason, "steps": steps, "usage": dict(usage)}) return result def run_agent(model, *, system, task, tools, max_steps=8, agent="agent", on_event=None): """Run one agent on one task until it stops or reaches max_steps model calls.""" emit = on_event or (lambda event: None) emit({"type": "run_start", "agent": agent, "task": task}) messages = [user(task)] usage = {"input_tokens": 0, "output_tokens": 0} definitions = tool_definitions(tools) for step in range(1, max_steps + 1): started = time.perf_counter() response = model.create(system=system, messages=messages, tools=definitions) for key in usage: usage[key] += response["usage"][key] emit({"type": "model_call", "agent": agent, "step": step, "model": response["model"], "stop_reason": response["stop_reason"], "usage": dict(response["usage"]), "seconds": time.perf_counter() - started}) messages.append(assistant(response["content"])) if response["stop_reason"] != "tool_use": return finish_run(response["stop_reason"], messages, step, usage, agent, emit) results = run_tools(blocks_of(messages[-1], "tool_use"), tools, lambda event: emit({**event, "agent": agent, "step": step})) messages.append(user(results)) return finish_run("step_limit", messages, max_steps, usage, agent, emit) def broadcast(*handlers): """One on_event handler that passes every event to several handlers.""" def emit(event): for handler in handlers: handler(event) return emit -
Create the exercise folder and move into it:
mkdir -p ~/multi-agent-practice/agent-loop cd ~/multi-agent-practice/agent-loopSave this as
order_agent.pyin it:"""An order-status agent driven by a scripted model, run through the course's agent loop.""" import json import sys from pathlib import Path from kit.loop import run_agent from kit.messages import blocks_of from kit.scripted import ScriptedModel, call, say from kit.shop import create_shop, shop_tools SYSTEM = "You answer questions about Quillfield Cycles orders. Use the tools; never guess a status." def order_rule(messages): """The scripted model's decisions: look the order up, then answer from the result.""" last = messages[-1] if isinstance(last["content"], str): # the task: the order ID is its last word return [call("order_status", order_id=last["content"].split()[-1])] result = blocks_of(last, "tool_result")[0] if result["is_error"]: return say(f"I could not look that order up ({result['content']}).") status = json.loads(result["content"]) return say(f"Order {status['order_id']} is {status['status']} (placed {status['placed_on']}).") def always_calls_a_tool(messages): """A broken script that never gives an answer.""" return [call("order_status", order_id="A-1003")] def show(result): print(f"stop_reason={result.stop_reason} steps={result.steps} usage={result.usage}") for number, message in enumerate(result.messages, 1): content = message["content"] if isinstance(content, str): print(f" {number} {message['role']}: {content}") continue for block in content: if block["type"] == "text": print(f" {number} {message['role']}: text {block['text']!r}") elif block["type"] == "tool_use": print(f" {number} {message['role']}: tool_use {block['id']} {block['name']} {block['input']}") else: print(f" {number} {message['role']}: tool_result for {block['tool_use_id']}" f" is_error={block['is_error']} {block['content']}") print(f"final text: {result.text!r}") def main(): tools = shop_tools(create_shop(Path("shop.sqlite3"))) which = sys.argv[1] if len(sys.argv) > 1 else "found" if which == "found": result = run_agent(ScriptedModel(rule=order_rule), system=SYSTEM, task="Where is order A-1003", tools=tools) elif which == "unknown": result = run_agent(ScriptedModel(rule=order_rule), system=SYSTEM, task="Where is order Z-9", tools=tools) else: result = run_agent(ScriptedModel(rule=always_calls_a_tool), system=SYSTEM, task="Where is order A-1003", tools=tools, max_steps=3) show(result) if __name__ == "__main__": main() -
Predict the message history for "Where is order A-1003": how many messages, which blocks in each, and the stop reason. Then run:
python order_agent.py foundOutput (exact; the script and its token counts are fixed):
stop_reason=end_turn steps=2 usage={'input_tokens': 448, 'output_tokens': 46} 1 user: Where is order A-1003 2 assistant: tool_use toolu_scripted_01 order_status {'order_id': 'A-1003'} 3 user: tool_result for toolu_scripted_01 is_error=False {"order_id": "A-1003", "status": "shipped", "placed_on": "2026-10-12"} 4 assistant: text 'Order A-1003 is shipped (placed 2026-10-12).' final text: 'Order A-1003 is shipped (placed 2026-10-12).'Now run the other two cases, predicting each first:
python order_agent.py unknown python order_agent.py limit
Success: found ends with end_turn after 2 model calls and the answer
above; unknown ends with end_turn after a tool_result marked
is_error=True containing LookupError: unknown order Z-9; order IDs look like A-1001; limit ends with step_limit after 3 model calls and no final
text. Together they show the three ways a run ends: the model answers, the
model answers after a tool failed, or the loop stops a model that would not.
How the Loop Works
One run, step by step. run_agent starts the conversation with the task
as a user message, then repeats up to max_steps times. Excerpt from
run_agent in kit/loop.py; the usage and event lines between the call and
the append are omitted:
response = model.create(system=system, messages=messages, tools=definitions)
...
messages.append(assistant(response["content"]))
if response["stop_reason"] != "tool_use":
return finish_run(response["stop_reason"], messages, step, usage, agent, emit)
results = run_tools(blocks_of(messages[-1], "tool_use"), tools,
lambda event: emit({**event, "agent": agent, "step": step}))
messages.append(user(results))
The model receives the whole conversation every time: models remember
nothing between requests, so the history is the agent's memory. The reply
is appended before anything else, so the history always shows what the model
asked for. Any stop reason other than tool_use ends the run with that
reason. Otherwise every requested tool runs, and all the results go back as
one user message. If the loop gets through max_steps calls without an
answer, it ends with the course's own stop reason, step_limit.
What the model is told about tools. tool_definitions sends each tool's
name, description and input schema, but never the Python function: the model
only ever asks; your code decides whether and how to run anything.
Validation before running. run_tools checks each request before running
it. An unknown tool name, or an input that fails validate, becomes an error
result instead of a call. validate checks the parts of JSON Schema the
course uses: an object, required fields, each field's type (rejecting True
where a number is expected, because Python treats booleans as integers),
enum choices, and additionalProperties: false. Its messages read like
this:
missing required field 'order_id'
field 'order_id' must be of type string
unexpected field 'note'
Tool errors go back to the model. If a tool raises an exception, the loop
catches it and returns "<ErrorType>: <message>" with is_error: True. The
model can then apologise, ask for a correct ID or try another tool, which is
why the shop's LookupError message says what an order ID looks like. Two
consequences follow. First, a tool's error text is read by the model, so it
must never contain secrets or internal details you would not show a user;
later lessons return to this. Second, the loop does not crash on a tool
failure, but it does let a failure of the model call itself escape, so
the code around the loop can decide whether to retry; lesson 5 shows one.
The result. finish_run packages an AgentResult with the stop reason,
the final text (the last assistant message's text, or empty if the run did
not end on an assistant message), the full message list, the number of model
calls and the summed token usage.
The Scripted Model
ScriptedModel answers each create call in one of two ways: from a rule,
a function that looks at the conversation and returns a reply, or from a list
of replies used in order. A reply is a list of blocks; say("...") and
call("tool", field=value) build them. In order_agent.py, order_rule
looks at the last message: if it is the task (a string), it asks for
order_status; if it is a tool result, it answers from it.
Three details make scripted runs behave like real ones:
- IDs.
call()leaves the ID empty and the model fills it in (toolu_scripted_01,toolu_scripted_02, ...), just as a real model assigns IDs, so your tool results must echo the ID they answer. - Stop reasons. A reply containing a
tool_useblock getstool_use; otherwiseend_turn. A rule can return a dictionary withcontentandstop_reasonto produce any other reason, which lesson 5 uses. - Usage. Each response reports
input_tokensandoutput_tokens, estimated as one token per four characters of JSON. These numbers are illustrative, not a real tokenizer's, but they grow the way real counts do: thelimitrun read 803 input tokens over 3 calls because each call re-sends the growing history.
When a list of replies runs out, the model raises
RuntimeError: scripted has no scripted reply left for call 2 (with your
model's name and call number), so a script that is too short fails loudly
instead of quietly.
The Event Hook
run_agent reports what happens to an optional on_event function, as one
dictionary per event:
| Event | When | Main fields |
|---|---|---|
run_start | Before the first call | agent, task |
model_call | After each model call | agent, step, model, stop_reason, usage, seconds |
tool_call | After each tool runs | agent, step, tool, input, is_error, seconds |
run_end | When the run finishes | agent, stop_reason, steps, usage |
The loop does not care what the function does with them. Lesson 7 counts
tokens with it, lesson 27 stops runs that exceed a budget, and lesson 30 turns
the events into a trace, all without changing kit/loop.py. broadcast(a, b)
passes each event to several handlers.
Reading the Three Runs
- found: two model calls. The first asks for a tool (message 2), the program answers it (message 3), and the second call writes the answer (message 4).
- unknown: also two calls. The tool raised
LookupError, the loop turned it into an error result, and the rule answered from it. The run "succeeded" in the loop's sense (end_turn) while the task did not: a stop reason describes how the run ended, not whether it achieved anything. - limit: the broken script asks for the same tool forever. The loop stops
it after
max_steps=3, so a confused or looping model costs at most three calls. The final text is empty because the last message is a tool result.
When It Goes Wrong
| What you see | Cause | Fix |
|---|---|---|
ModuleNotFoundError: No module named 'kit.loop' | A kit file is missing or misnamed | Check ls ~/multi-agent-practice/kit; re-save from this lesson |
ModuleNotFoundError: No module named 'kit' | The environment is not active | Activate it (setup lesson) |
A tool_result reads TypeError: Object of type date is not JSON serializable | A tool returned something JSON cannot encode | Return strings, numbers, lists and dictionaries |
unknown tool 'nope'; available: ... in a result | The model asked for a tool you did not provide | Check the tool's name in both places |
RuntimeError: ... has no scripted reply left | A replies list is shorter than the run | Add replies, or use a rule |
stop_reason=step_limit unexpectedly | The model never answered | Read the history: it shows what it kept asking for |
Your Turn: Two Tools in One Reply
Change order_rule so that, for the task, it asks for both
order_status and order_details in one reply, and then answers with the
status and the total, for example Order A-1003 is shipped; total 41.00.
Before running python order_agent.py found, predict how many messages the
history has, how many blocks messages 2 and 3 contain, and how many model
calls the run makes.
Reset and Clean Up
Keep the three kit modules. Remove the exercise folder:
cd ~/multi-agent-practice
case "$PWD" in */multi-agent-practice) rm -rf agent-loop ;; *) echo "not in the practice folder" ;; esac
PowerShell:
cd ~/multi-agent-practice
if ((Get-Location).Path -like "*multi-agent-practice") { Remove-Item -Recurse -Force agent-loop }
Check Your Understanding
- Why does the loop send the whole conversation on every call?
- The
unknownrun ended withend_turn. Did the agent succeed? What would you check instead of the stop reason? - Why does
run_toolsreturn an error result for an invalid input instead of raising an exception? - What does
max_stepsprotect you from, and what does it cost to set it too low?
Answer and Reasoning
Readiness check. The program wrote messages 1 (the question) and 3 (the
tool result); the model wrote message 2, which pairs a sentence with a
tool_use request. The next message is the model's: an assistant message
with a text block such as "Yes, order A-1007 was shipped; it was placed on
2026-10-14", and stop reason end_turn, because it now has what it needs.
Your turn. One way to write the rule:
def order_rule(messages):
"""Ask for the status and the details in one reply, then answer from both."""
last = messages[-1]
if isinstance(last["content"], str):
order_id = last["content"].split()[-1]
return [call("order_status", order_id=order_id), call("order_details", order_id=order_id)]
status_result, details_result = blocks_of(last, "tool_result")
if status_result["is_error"]:
return say(f"I could not look that order up ({status_result['content']}).")
status = json.loads(status_result["content"])
details = json.loads(details_result["content"])
return say(f"Order {status['order_id']} is {status['status']}; total {details['total']:.2f}.")
The history still has four messages and the run still makes two model calls.
Message 2 contains two tool_use blocks (toolu_scripted_01 and
toolu_scripted_02); message 3 contains two tool_result blocks, in the same
order, in one user message. The answer is Order A-1003 is shipped; total 41.00. (a chain at 32.00 and a bell at 9.00). Asking for independent tools in
one reply saves a model call; it is only possible when neither request needs
the other's result.
Understanding check.
- The model keeps nothing between requests; the conversation is its only memory of the task and of what its tools returned.
- Not necessarily:
end_turnonly means the model stopped asking for tools. Check the outcome against the task, here whether the answer contains a status, which it does not. - So the model can correct itself: the error text explains what was wrong. Raising would end the whole run over a mistake the model could fix.
- A model that never stops asking for tools, which would otherwise cost calls, time and money without end. Too low a limit stops agents that legitimately need more steps, so set it from the longest correct run you expect, plus a margin.
References
- S19: Claude documentation, Tool use overview:
tool_useblocks and thetool_usestop reason. - S20: Claude documentation, Handle tool calls:
tool_resultblocks,is_error, and results immediately after their request. - S18: Claude documentation, Pricing: per-token prices, opened 2026-10-21.