/ module 14 · Building with LLMs
Agent Loop Tracer
An agent is a loop around an LLM: the model either answers or asks for a tool, your code runs the tool, the result goes back into the conversation, and the loop repeats. Step through real-shaped traces to see every message, the MCP wire format and what each turn costs.
- Explain the agent loop: think, call a tool, read the result, repeat
- Read a tool call and an MCP message
- Say why input tokens grow each turn and why max steps matters
Try this first: Choose 'Tool error and retry' and press Step until it finishes.
pattern
The loop in five lines
messages = [system, user]
for step in range(MAX_STEPS):
reply = llm(messages, tools=TOOL_SCHEMAS)
if not reply.tool_calls: return reply.text # final answer
for call in reply.tool_calls: messages += [reply, run_tool(call)]
raise Stop("max steps reached")Every call resends the whole history, including tool schemas, so the input grows each turn. That is why long agent runs get slow and expensive, and why a max steps guard matters.
Two tools, four calls. The model never does arithmetic in its head; it delegates to the calculator.
- system · 102 tokens of tool schemas attachedYou are an agent. Think briefly, call tools when you need facts or maths, and give a final answer when done.
- userIs it warmer in Chennai or Bengaluru right now? Answer in °F.
- … press Step or Play
practice
Design rules for reliable agents
- Give tools precise names, descriptions and JSON schemas; the model chooses tools from these words alone.
- Return errors to the model as tool results, not crashes, so it can retry or change plan.
- Cap steps, time and spend. Log every call so you can replay and evaluate runs.
- Treat tool output as untrusted data (see prompt injection in the Evals module) and give agents the least permissions they need.
Check yourself
Tick each one you could explain to a friend. If you can't yet, scroll back up and replay the lab.