Skip to content

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.

Task + contextsystem, tools, historyModel calltool call or answer?toolApproval gateonly for risky actionsRun toolresult or errorappend the observation to the context, then call the model againanswer → stopAlso stop on: step limit, token or cost budget, repeated identical calls (a loop)
An agent is this loop. Everything else in the course (state, memory, MCP, multi-agent, evals) makes the loop safer or smarter.
Common misconception: "Agentic" does not mean "smarter". An agent is a design choice that trades predictability for flexibility. It is the right choice only when the steps genuinely can't be known in advance.

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.

Tip: Write the loop yourself once (this module's starter does) before using LangGraph in Module 3. Framework bugs are much easier to debug when you know what the framework is doing underneath.

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 conversation
In production: Every loop iteration re-sends the full history, so total tokens grow roughly with the square of the number of steps. Cap steps, cache the stable prefix (system prompt and tool definitions) and keep tool results short.

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

Agent loop stepperTask: “The checkout API is slow. Find out why.” Step through the loop, then break it.
0 model calls · context now 640 tokens · run cost $0.00000
  1. User: The checkout API is slow. Find out why.
Guided experiments
  1. Run the happy path. How many model calls did it take, and why does each call cost more input tokens than the one before?
  2. 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?
  3. 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).
  4. 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?
  5. The last step proposes a rollback but doesn’t do it. Why should that action wait for a human approval?
In production: Every production agent needs a step limit, a token or cost budget and loop detection (the same tool called with the same arguments twice in a row). Module 12 builds all three; this module's starter already has the step limit.

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.

Common misconception: Multi-agent is not automatically better than one agent. Each extra agent adds calls, cost and failure modes. Module 7 covers when it pays off.

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 code

Labs

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

Further reading

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

1. What makes a program an agent rather than a workflow?
2. A tool raises an exception mid-run. What should the loop do?
3. Why does each step of an agent run usually cost more input tokens than the last?
4. Which task is the best fit for an agent?
5. Which guard catches a model that keeps calling the same tool with the same arguments?

Interview questions

  1. Write an agent loop from memory on a whiteboard. Where do you put the step limit, error handling and logging?
  2. A stakeholder asks for an AI agent to process invoices. How do you decide whether it should be an agent at all?
  3. Explain ReAct. What does the reasoning step buy you, and what does it cost?
  4. An agent's cost per task tripled after a prompt change. How do you find out why?
  5. 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).