Sub topic 1
What an Agent Is
This chapter defines the agent that the rest of the tutorial builds on. Handoffs and orchestrators are ways of arranging several agents, so you need a precise picture of one agent first. By the end you will be able to name its parts, trace one run of its loop, and see where a single agent starts to strain.
Prerequisites
This chapter assumes you have the following:
- Basic Python, including dataclasses, dictionaries, and passing functions as arguments.
- A working idea of what a large language model (LLM) is, and how a conversation is sent to it as a list of messages with roles such as
userandassistant. - Comfort reading JSON.
- A rough awareness of tool (function) calling. The next chapter reviews it, so you can follow this one without it.
The short definition
An agent is a program that uses an LLM to decide what to do next, acts on that decision, and repeats until the task is done. Four parts make up that definition:
| Part | What it is | Who controls it |
|---|---|---|
| Model | The LLM that reads the conversation and produces the next step | You choose it |
| Instructions | Text that sets the agent's role, rules, and style, usually sent as a system prompt | You write it |
| Tools | Functions the model may ask the program to run | You implement them |
| Loop | Code that calls the model, runs requested tools, and feeds results back | You write it |
The model only produces text. It never runs a function itself. When it wants a tool, it emits a structured request that names the tool and gives its arguments. Your loop runs the function and appends the result to the conversation. The loop is therefore what makes an agent an agent. A single model call with a prompt is not one.
Agent versus plain LLM call
A plain call takes a prompt and returns one reply. The program decides the control flow, and the model fills in text.
An agent shifts part of the control flow to the model. The model decides whether to answer now or call a tool first, which tool to call, and when it has enough information to stop. The number of model calls is not known in advance. That flexibility is useful, and it is also the source of most agent failures: loops that never end, wrong tool choices, and runaway cost. Later chapters cover turn limits and failure handling for this reason.
The loop
One run follows these steps:
- Start with a message history that contains the user's request.
- Call the model with the agent's instructions, its tool descriptions, and the history.
- If the model returns a final answer, stop and return it.
- If the model requests a tool, run the tool, append the result to the history, and go back to step 2.
The message history is the agent's only working memory. The model keeps nothing between calls. Anything it should "remember" has to be in the history you send each time. This matters a great deal in multi-agent systems, where a central design question is which history each agent sees.
A runnable single agent
The code below implements the loop. A scripted function stands in for the model so that you can run it with no API key. In a real system, call_model would call an LLM API and convert its response into the same three-field shape.
from dataclasses import dataclass, field
from typing import Callable
@dataclass
class Agent:
name: str
instructions: str
tools: dict[str, Callable] = field(default_factory=dict)
def get_order_status(order_id: str) -> str:
return f"Order {order_id} shipped on 2026-11-20."
def fake_model(agent: Agent, messages: list) -> dict:
"""A scripted stand-in for an LLM.
It asks for the tool once, then answers using the tool result.
"""
if not any(m["role"] == "tool" for m in messages):
return {"type": "tool", "name": "get_order_status", "args": {"order_id": "1042"}}
return {"type": "final", "text": "Update: " + messages[-1]["content"]}
def run(agent: Agent, messages: list, call_model, max_turns: int = 10) -> str:
for _ in range(max_turns):
reply = call_model(agent, messages)
if reply["type"] == "final":
messages.append({"role": "assistant", "content": reply["text"]})
return reply["text"]
# The model asked for a tool: record the request, run it, record the result.
messages.append({"role": "assistant", "tool_call": reply["name"], "args": reply["args"]})
result = agent.tools[reply["name"]](**reply["args"])
messages.append({"role": "tool", "name": reply["name"], "content": str(result)})
raise RuntimeError("max_turns exceeded")
support = Agent(
name="support",
instructions="You help customers check the status of their orders.",
tools={"get_order_status": get_order_status},
)
history = [{"role": "user", "content": "Where is order 1042?"}]
print(run(support, history, fake_model))
print(len(history), "messages in history")Running it prints Update: Order 1042 shipped on 2026-11-20. and then 4 messages in history. The four messages are the user request, the tool request, the tool result, and the final answer.
Three details are worth noticing:
toolsis a dictionary from a name to a function. The model sees the names and descriptions, and your loop looks up the function by name.- The loop appends the tool request as well as the result. Real model APIs require this pairing, because the result must refer back to the call that produced it.
max_turnsbounds the loop. Without it, a model that keeps requesting tools would run forever.
Writing good instructions and tools
Both are part of the agent's interface to the model, so treat them as carefully as code.
- Keep instructions focused. State the role, what the agent may and may not do, and the shape of the final answer. A long list of unrelated rules makes the model follow each one less reliably.
- Name tools by what they do, and describe each argument. The model chooses tools mostly from their names and descriptions.
- Return short, plain results from tools. Everything a tool returns is added to the history and costs tokens on every later call.
- Make tool errors readable. A tool that raises a bare exception gives the model nothing to correct. Returning a message such as
"No order with id 99"lets the model recover.
Where one agent runs out of room
A single agent works well for small, well-defined jobs. Problems appear as the job grows:
- Every tool description and instruction competes for the model's attention. With dozens of tools, selection errors increase.
- One long history carries every earlier step. It grows, costs more, and can bury the details that matter.
- One agent has one set of permissions. If it can both read customer records and issue refunds, a mistake or a malicious input can reach both.
- Different steps may need different models, such as a cheap fast one for classification and a stronger one for reasoning.
These pressures are the motivation for splitting work across several agents. Chapter 3 treats that argument in detail. Chapter 2 first reviews tool calling, which both the handoff and orchestrator patterns depend on.
Common mistakes
- Treating the model as stateful. If a fact is not in the history you send, the model does not know it.
- Putting secrets, such as API keys, in instructions or tool results. Both go into the model's context and may be logged.
- Letting tools do more than the task needs. A tool is a capability you are granting. Give each agent only the tools its role requires.
- Assuming the model's choice of tool is always valid. Check that the requested name exists in
toolsbefore calling it, and handle a missing name as an error the model can see.
Exercise
In the run function above, what are two separate things that stop the loop, and which one is a normal outcome?
Show answer
The loop stops when the model returns a reply of type "final", which is the normal outcome, and the function returns the answer. It also stops when the for loop uses up max_turns iterations without a final answer, in which case it raises RuntimeError("max_turns exceeded"). That second exit is a safety guard against a model that keeps requesting tools.
Exercise
An agent has 25 tools covering orders, billing, and shipping. It sometimes picks a billing tool for a shipping question, and its history grows long. Name two reasons that splitting it into several agents might help.
Show answer
Each smaller agent would have fewer tools and shorter instructions, so the model chooses between fewer options and makes fewer selection errors. Each agent would also work with a shorter, more focused history, which lowers cost and keeps relevant details visible. Separate permissions per agent are another valid reason.