Sub topic 1
What an agent is
An agent is a program that asks a language model what to do, carries out the answer, and repeats until the task is done. This chapter gives you the working model that the later chapters on handoffs and orchestrators build on.
Prerequisites
You should have:
- Basic Python experience.
- A rough idea of how a large language model (LLM) takes messages and returns text.
- Familiarity with JSON.
Tool calling is reviewed in the next chapter, so you don't need it yet.
The four parts of an agent
An agent has four parts:
- Model. The LLM that decides the next step.
- Instructions. A system prompt that sets the agent's role and rules.
- Tools. Functions the model can ask the program to run, such as a database lookup.
- Loop. Code that calls the model, runs any requested tool, adds the result to the message history, and calls the model again.
The model never runs anything itself. It returns a structured request, and your code decides whether to run it. A plain chat call is one model call. An agent is the loop around many calls.
A minimal agent
The code below is a complete agent. A stub function stands in for the model so the example runs without an API key. It asks for a tool first, then gives a final answer once it sees the tool result.
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 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":
return reply["text"]
result = agent.tools[reply["name"]](**reply["args"])
messages.append({"role": "tool", "name": reply["name"], "content": str(result)})
raise RuntimeError("max_turns exceeded")
def lookup_order(order_id: int) -> str:
return "delivered"
def stub_model(agent: Agent, messages: list) -> dict:
if messages[-1]["role"] == "tool":
return {"type": "final", "text": f"Order status: {messages[-1]['content']}."}
return {"type": "tool", "name": "lookup_order", "args": {"order_id": 1042}}
support = Agent(
name="support",
instructions="Answer questions about orders.",
tools={"lookup_order": lookup_order},
)
history = [{"role": "user", "content": "Where is order 1042?"}]
print(run(support, history, stub_model))Running it prints Order status: delivered. After the run, history holds the user message and the tool result. That list is the agent's working memory. The model sees only what is in it, plus the instructions.
Common errors
- No turn limit. If the model keeps requesting tools, the loop never ends and you keep paying for calls. The
max_turnsargument above prevents this. - Assuming the model remembers. Nothing persists between calls except the messages you resend. If a fact isn't in the history, the model doesn't know it.
- Too many tools. Each tool adds description text and another choice. Models pick the wrong tool more often as the list grows.
- Vague instructions. An agent that does everything is hard to test. This is the main reason to split work across several agents, which the "Why use more than one agent" chapter covers.
Exercise
In the example, what two things would you change to make the agent stop after at most three model calls, and what happens if the limit is reached?
Show answer
Pass maxturns=3 to run (or change the default). If the model has not returned a final answer within three calls, the loop ends and run raises RuntimeError("maxturns exceeded").