GGiriBioAI

/ 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.

By the end you can
  • 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.

about 15 min hover ? for help

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.

agent loop
Call the model, run any tool it asks for, append the result, repeat until it gives a final answer.
tool schema
A JSON Schema describing a tool's name and arguments, sent to the model so it can call it correctly.
Live lab · Agent trace

Two tools, four calls. The model never does arithmetic in its head; it delegates to the calculator.

  1. system · 102 tokens of tool schemas attached
    You are an agent. Think briefly, call tools when you need facts or maths, and give a final answer when done.
  2. user
    Is it warmer in Chennai or Bengaluru right now? Answer in °F.
  3. … 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.
MCP
Model Context Protocol: a standard JSON-RPC way for AI apps to discover and call tools and data sources.
max steps
A hard cap on loop iterations so a confused agent cannot run (and spend) forever.

Check yourself

Tick each one you could explain to a friend. If you can't yet, scroll back up and replay the lab.

Finished exploring?
Progress is saved only in this browser.