Courses / Agentic AI / Module 1
Module 1: The agent loop: ReAct, tool calling, and when a workflow beats an agent
10 h · theory 3 · hands-on 4 · project 2 · revision 1
You will be able to
- Write an agent loop from scratch: model call, tool call, observation, stop
- Explain ReAct and why step limits and stop conditions matter
- Classify a task as a workflow, a router or an agent
- Trace and cost every step of a run
Capstone increment: A hand-written agent loop with two tools, a step limit and a per-run trace of steps, tokens and cost.
Job-description skills: Agent loop, Tool calling · Lab tools: python3.12, openai, pydantic
1. An agent is a loop, not a magic model
Strip away the frameworks and an agent is a short loop: send the task and context to a model; if it asks for a tool, run the tool and append the result as an observation; call the model again; stop when it answers or when a limit is hit. The model decides what to do next, which is the only real difference from ordinary code.
That one difference is also the risk. Because the model picks the path, the number of steps, the cost and the actions taken are not fixed in advance. Everything else in this course (state machines, memory, MCP, approvals, evals, budgets) exists to make that loop reliable and safe.
2. ReAct: reason, act, observe
ReAct (reason + act) is the pattern behind most agents: the model writes a short thought about what it needs, calls a tool, reads the observation and repeats. The thought makes the next action more likely to be sensible, and it gives you a readable trace when things go wrong.
Modern tool-calling APIs do the "act" part in structured form: the model returns a tool name and JSON arguments instead of free text, and your code runs the tool. Your loop still owns everything else: which tools exist, what happens on errors, when to stop, and what is logged.
Deep dive
Deep dive: what a tool call really is
The model never runs anything. Tool definitions (a name, a description and a JSON Schema for the arguments) are put into the prompt; the model has been trained to emit a structured block when it wants a tool; your code, the harness, parses that block, validates the arguments, runs the function and appends the result as a new message. Then the model is called again with the longer conversation.
That is the whole agent loop: call the model, run the tools it asked for, append the results, and repeat until it answers without asking for a tool or you hit a step limit. ReAct is the same loop with the model’s reasoning written out between actions.
Worked example: one investigation as messages (simplified from the Anthropic Messages API)
user: “Why is checkout returning 502s?”
assistant: tool_use id=t1 name=search_logs input={"service": "checkout", "level": "error", "since": "15m"}
harness: validates the input, runs search_logs(...) in 480 ms
user: tool_result tool_use_id=t1 → “312 errors: upstream payments-api timeout”
assistant: tool_use id=t2 name=get_metrics input={"service": "payments-api", "metric": "p99_latency"}
user: tool_result tool_use_id=t2 → “p99 4.1 s (normally 300 ms) since 10:42”
assistant: “Checkout 502s come from payments-api timeouts; its p99 rose to 4.1 s at 10:42.”
3 model calls, 2 tool calls, and every model call re-sends the whole conversation3. Step through a real investigation
The stepper below replays an ops agent investigating a slow checkout API. Step through the happy path first, then break it: take a tool offline, or make the model keep re-checking instead of answering. Watch three numbers: model calls, context size and cost.
Two lessons stand out. First, errors must go back to the model as observations, not crash the loop, so it can try another route. Second, every call resends the whole conversation, so input tokens grow with each step: a run that loops is not just slow, it gets more expensive per step.
- User: The checkout API is slow. Find out why.
Guided experiments
- Run the happy path. How many model calls did it take, and why does each call cost more input tokens than the one before?
- Turn on “Log tool is down”. The error goes back to the model as an observation. What does it do next? What would happen if the loop crashed on tool errors instead?
- Turn on “Model keeps re-checking”. Raise the step limit to 12. What happens to context size and cost? This is why every agent needs a step limit and a budget (covered in depth in the Agentic AI course).
- Set the step limit to 3 on the happy path. The agent is stopped one step short of the answer. How would you pick a limit for a real task?
- The last step proposes a rollback but doesn’t do it. Why should that action wait for a human approval?
4. Workflow, router or agent?
Before building an agent, classify the task. A workflow has known steps in a known order: write it as code that calls the model at fixed points (extract, then classify, then draft). A router picks one of a few known paths: one model call that chooses, then fixed code. An agent is for tasks where the steps depend on what earlier steps discover, such as an investigation.
Workflows are cheaper, faster, easier to test and easier to explain to an auditor. Many production "agents" are really workflows with one agentic step inside. A useful rule: start with a workflow, and turn a step into an agent only when you can show the fixed version failing on real cases.
5. Trace and cost from the first line
Log every step: the model's tool choice, the arguments, the observation, tokens in and out, latency and cost. That trace is how you debug, how you evaluate trajectories (Module 11), and how you answer "why did the agent do that?" in an incident review.
The second starter below estimates cost per run from the token counts. Multiply by expected volume early: an agent that costs a tenth of a cent per run is fine for 1,000 incidents a month and a serious bill at a million.
Hands-on: coding window
The coding window and the full VS Code lab are available after you sign in.
Sign in to codeLabs
Lab 1.1: Make the loop robust
In the capstone's src/agent/loop.py, add loop detection: stop with stopped="loop" when the model calls the same tool with the same arguments twice in a row. Add a test.
Expected: pytest passes, including a new test where a looping model stops after 2 identical calls.
Lab 1.2: Add a trace
Record tokens in and out and latency for each step in the Run object (estimate tokens as characters / 4 for now) and return the total cost for given prices.
Expected: run.steps carries tokens and latency; a test checks the cost for a scripted 3-step run.
Lab 1.3: Workflow or agent?
For five tasks (invoice extraction, ticket routing, incident investigation, weekly report, refund approval), decide workflow, router or agent, and justify each in docs/adr/0002-workflow-or-agent.md.
Expected: An ADR with a one-paragraph justification per task and the risks of the agentic ones.
Go deeper
Videos
- What's next for AI agentic workflows ft. Andrew Ng of AI Fund · Sequoia Capital · ~14 min. The four agentic design patterns (reflection, tool use, planning, multi-agent) in 14 minutes; the map for this course.
- Building more effective AI agents · Anthropic · ~19 min. Anthropic engineers on workflows versus agents and when an agent is worth it.
- Tips for building AI agents · Anthropic · ~18 min. Practical pitfalls from teams shipping agents: tool design, evaluation and keeping things simple.
- Understanding ReACT with LangChain · Sam Witteveen · ~21 min. ReAct traced step by step in code, so you can see each thought, action and observation.
Further reading
- Paper ReAct: Synergizing Reasoning and Acting in Language Models · Yao et al., ICLR 2023. The paper behind the reason, act, observe loop. The trajectories in its appendix are worth reading.
- Article Building effective agents · Anthropic. The clearest guide to when you need an agent at all, and the workflow patterns to try first.
- Article LLM Powered Autonomous Agents · Lilian Weng. A structured survey of planning, memory and tool use, with the key papers for each.
- Docs Tool use with Claude · Anthropic docs. The exact message format for tool definitions, tool_use blocks and tool_result blocks.
- Paper Toolformer: Language Models Can Teach Themselves to Use Tools · Schick et al., 2023. How a model learns to decide when to call an API, the idea behind today's trained tool use.
GitHub repositories
- anthropics/claude-cookbooks: patterns/agents/basic_workflows.ipynb and orchestrator_workers.ipynb: the workflow patterns to try before reaching for an agent.
- huggingface/smolagents: src/smolagents/agents.py: a compact, readable ReAct loop with step limits and memory.
- openai/openai-agents-python: src/agents/run.py: how a production SDK runs the loop, handles tool errors and enforces max turns.
- langchain-ai/langgraph: The README quickstart only, for now: Module 3 rebuilds this module's loop as a LangGraph graph.
Checkpoint quiz
Interview questions
- Write an agent loop from memory on a whiteboard. Where do you put the step limit, error handling and logging?
- A stakeholder asks for an AI agent to process invoices. How do you decide whether it should be an agent at all?
- Explain ReAct. What does the reasoning step buy you, and what does it cost?
- An agent's cost per task tripled after a prompt change. How do you find out why?
- What limits would you put on an agent that can restart production services?
Ask the professor
Sign in to ask questions about this module.
Discussion
Community discussion appears here once giscus is configured (see README).