Modules 1 to 3 built the pieces: a loop, a model client, and tools. This module puts them together into the agent that the rest of the course extends, and it asks two questions about it. The first is about structure: which parts does an agent need beyond a loop, and why? The answer is a record of the run, tools as objects, a termination policy, and a way to return a typed result. The second is about quality: how do you know the agent works? The answer starts with a small benchmark, and with the ways a benchmark can mislead you.

Notebooks

Notebook 4: The ReAct agent runs ReAct as a text protocol and breaks it three ways. It then rebuilds the course’s Agent from its parts in about 50 lines and checks it against the library class. It stages every stop reason, gets typed output through a final_answer tool, and builds an eight-task benchmark with a grader, a concurrent runner and error analysis.

Reason, then act

The ReAct paper (Yao et al., 2022) named the pattern that almost every agent now follows: before each action, the model writes a short piece of reasoning about what to do next.

Definition 4.1 (ReAct).

A ReAct agent repeats three moves. It writes a thought, which is free text about the situation and the next step. It takes an action, such as a tool call or a final answer. Then it receives an observation, which is the action’s result. Each thought, action and observation is appended to the context that the next move is conditioned on.

Write for the task, , and for the thought, action and observation at step , and for the model. Step of Definition 4.1 is then

The paper’s framing is that a thought is an action that does not touch the environment. It returns no observation and changes only the context. That is its whole effect, and it is enough. In , a thought makes the next action depend on an explicit plan instead of only on the raw history. When an observation surprises the model, the next thought is where it can notice.

The paper tested this on question answering and fact checking with a Wikipedia search tool (HotpotQA, FEVER), and on two interactive tasks: a text-based household game (ALFWorld) and a shopping website (WebShop). On the interactive tasks, prompting with one or two examples beat imitation and reinforcement learning baselines by 34 and 10 points of absolute success rate. On question answering the picture was more mixed. Chain-of-thought alone invented facts more often, while ReAct’s errors were mostly about reasoning and search. One error was a loop in which the model repeated its earlier thoughts and actions. Another was a search result with no useful content, which derailed the next step. The best scores came from combining the two methods.

The paper also found that fine-tuning a model on ReAct trajectories beat prompting alone. That finding foreshadows today’s practice. Models are now trained to act as agents during post-training (CS329Z Lecture 6), which is why the format in the next section works with current models.

From a text protocol to tool calls

In 2022, ReAct was a text protocol, because models had no other interface. The prompt described lines such as Thought:, Action: search[query] and Observation:. The model continued the text. A regular expression turned the Action: line into a function call, and your code appended the Observation: line. Notebook 4 runs this version and stages its three usual failures. In the first, the model writes the observation itself. In the second, it writes an action the parser cannot read, which costs an extra step to repair. In the third, a tool with several arguments does not fit in tool[input].

Remark 4.1 (The model that writes its own observation).

A text model continues the pattern it is shown, and the pattern says that an Observation: line comes next. Unless the API is told to stop at that string, the model writes one itself, with an invented result, and then reasons from it. The original ReAct code used the API’s stop parameter to end generation at the next Observation line for this reason. Notebook 4 shows that a parser which looks for finish[...] anywhere in the reply returns an invented answer of USD 45.00 for a true total of USD 55.50.

Native tool calling removes all three failures. The reply carries structured calls with JSON arguments, so the provider does the parsing. Some providers can also constrain the arguments to the schema during decoding. The turn ends at the call, so there is no observation to invent (Remark 4.1), and one reply can contain several independent calls. The loop is unchanged. The thought is the text before a call, or, in a reasoning model, the thinking it does before it replies. The action is the call, and the observation is the tool result. What moved is the parsing and the format discipline: from your regular expression into the model’s training and the provider’s API.

The parts of an agent

Notebook 1’s loop kept a plain list of messages. That stops being enough as soon as the agent needs to pause for a person’s approval, share a run with another agent, or compact its history. All of these need to know who wrote what, in what order, and what state the run is in.

Definition 4.2 (Execution context).

The execution context is the single record of one agent run. It holds an append-only list of events and a few fields: the step count, a state dictionary and the final result. An event has an author and a list of content items, and each item is a message, a tool call or a tool result. The model’s input is computed from the events. It is never stored separately.

With Definition 4.2 in place, one step of the agent is a cycle through the log:

run should_stop? think call the model act run the tools status request reply results execution context: an append-only log of events user reply results reply results answer

The code follows the figure closely. Here is the core of Notebook 4’s MiniAgent.step:

async def step(self, context):
    request = LlmRequest(instructions=[self.instructions], contents=context.contents(),
                         tools=self.tools, tool_choice="auto")
    response = await self.think(request)                  # the model call
    context.add_event(Event(execution_id=context.execution_id, author=self.name,
                            content=response.content))
    if response.tool_calls:
        await self.act(context, response.tool_calls)      # results become one event
    else:
        context.final_result = response.text              # no calls: the answer
    context.increment_step()

Tools are objects rather than bare functions. BaseTool fixes the interface: a name, a JSON Schema definition and an async execute. FunctionTool builds that interface from a plain function. Subclassing BaseTool directly is for tools that hold state, such as a connection, a cache or a call counter. Tools that need to shape the prompt use the process_llm_request hook, which lets a tool add an instruction to every request it is part of. The library’s Agent adds hooks before and after each model call and tool call, handles a failed model call, and can pause for a person’s approval. Module 5 uses the hooks and the pause. None of these change the cycle in the figure.

When to stop

Every loop needs a termination policy, and it is the decision with the largest effect per line of code. The course’s agent checks three conditions before each step. The run stops when a final result exists, when the model call failed, or when the step budget is spent. Each condition becomes the run’s status, and each status calls for a different response:

statuswhat happenedwhat the caller should do
completea final answer existsuse result.output
max_stepsthe budget ran outtreat it as a failure, and raise the budget only if the trace shows progress
errorthe model call failed, or a guard stopped the runretry later after a rate limit; otherwise report it
pending_confirmationa tool needs a person’s approval (Module 5)ask, then resume the same context
Remark 4.2 (A stop rule encodes a belief about your tools).

A step budget stops every runaway loop, but only after paying for all of it. A sharper rule stops when the model repeats the same call with the same arguments. Notebook 4 adds one in a few lines by overriding _should_stop. Whether that rule is right depends on the tools. For a tool that polls a long-running job, repeating the same call is the correct behaviour. Stop rules belong to the agent you build, which is why the method is meant to be overridden.

Structured output through a final-answer tool

A program that calls an agent usually wants a value, not a sentence. Module 2 got JSON from a single model call with a response schema. An agent makes this harder, because on every step the model either calls a tool or finishes, and the schema should apply only to the finish. The book’s solution is to make finishing itself a tool.

Remark 4.3 (Finishing is a tool call).

Given an output_type, the agent adds a tool named final_answer whose one argument has the output’s JSON Schema. The agent also sends tool_choice="required", so every reply must be a tool call. A reply is either more work or the answer, never loose prose. The run is complete only when final_answer succeeds. Its argument is validated with Pydantic, so a malformed answer becomes an ordinary tool error that the model sees and can repair. In Notebook 4, the error names both bad fields and the allowed values.

Measuring an agent, in miniature

“It answered the three questions I tried” is not evidence that an agent works. Even a small benchmark needs four parts. It needs tasks with checkable answers, and a runner that runs every task the same way and keeps each trace. It needs a grader that decides pass or fail the same way every time, and a report detailed enough to explain each failure. The book’s version runs ten GAIA questions with and without tools, three at a time. Notebook 4 builds the same harness for eight questions about a made-up shop. The data is invented, so no model can answer from memory.

Remark 4.4 (Graders fail in both directions).

A grader written in plain code is fast, free and repeatable, and it fails in two ways. In a false fail, the answer is right in substance and wrong in form. In Notebook 4 the agent reports "stock": 0 for “Is the Canvas Tote in stock?”, and the grader rejects it because the word “no” is missing. In a false pass, the right words appear in a wrong answer. “The Canvas Tote costs more than the Desk Lamp” passes a check for “Desk Lamp”. So does the offline model’s canned reply, which only repeats the question. The fixes are to ask for structured output (Remark 4.3) and compare fields, or to grade with a rubric and a judge model (Module 10). Read a sample of the traces either way.

Small benchmarks have one more trap: their pass rates are noisy. If of tasks pass, the estimated pass rate and its standard error are

For 7 of 8 tasks, gives and a standard error of about . A rough 95% interval runs from about 65% to 100%. The same pass rate on 100 tasks gives an interval of about points. At the normal approximation is crude, and Module 10 uses better intervals, but the conclusion holds. A difference of one or two tasks between two agent designs on a small benchmark is not evidence that either is better.

Try this

  • In Notebook 4, give ShopAnswer an in_stock: bool | None field. Rerun the benchmark with output_type=ShopAnswer and grade by comparing fields. Which of the grader errors in Remark 4.4 disappear, and which remain?
  • Write a stop rule for an agent whose tools include job_status(job_id), which is meant to be polled (Remark 4.2). What should stop the run, and what should not?
  • Use equation to work out how many tasks you need before a difference of 10 points between two agents at a pass rate of about 70% is larger than two standard errors.

Readings