Building a ReAct Agent in Python: Reason, Act, Observe

Build a ReAct agent from scratch in Python. The reason-act-observe loop in 31 lines, its three failure modes, and what the scratchpad costs you per step.

Cover Image for Building a ReAct Agent in Python: Reason, Act, Observe

You ask an assistant a question whose answer depends on information it has to look up. It could make a plan before searching, but the first result may change what it should do next. A ReAct agent handles that by alternating between choosing an action and reading what happened. Building a ReAct agent in Python lets you see how an ordinary request becomes a sequence of tool calls, and where the loop needs to stop.

The stop condition matters because every model call resends the growing history. Total context cost therefore grows faster than the step count, although the loop takes only thirty-one lines including blanks. We trace a scripted run, inspect tool-result updates and break the loop before connecting it to a live model.

This post builds that loop in Python, with no framework and no API key. A scripted stand-in model replays a fixed transcript, so every number below reproduces exactly and the whole thing runs in under a second on a laptop. You will measure why interleaving beats planning up front, watch a prompt grow from 500 to 2,124 characters over nine model calls, and break the loop three ways before fixing each one. One optional cell at the end swaps in a real Claude call.

Let's Build It

Open this in Google Colab and run it top to bottom.

Open In Colab

Here is the loop working through a question that needs eight lookups. The left panel is the scratchpad, the only memory the agent has. The right panel is the size of the prompt being sent on each call.

Animation of a ReAct agent answering a question over nine model calls. The left panel shows the scratchpad filling with grey Thought lines, blue Action lines and amber Observation lines, scrolling as it grows past twelve lines, and ending with a green Final Answer AlexNet. The right panel shows a bar chart of prompt size climbing from 500 characters on the first call to 2,124 on the ninth.

The agent has two tools. search looks up an entry in a small encyclopedia and suggests close titles when nothing matches exactly, which is the behaviour of the Wikipedia API in the original ReAct paper. calculator evaluates arithmetic and refuses anything else.

ENCYCLOPEDIA = {
    "LSTM": "The long short-term memory network is a recurrent architecture "
            "whose gated cell carries state across many time steps without the "
            "gradient vanishing. It was published in 1997 by Hochreiter and "
            "Schmidhuber.",
    "Transformer": "The Transformer was published in 2017 in the paper "
                   "Attention Is All You Need. ...",
    # eight more entries
}

def search(query):
    """Return the entry, or the closest titles when the query is not one."""
    for title, body in ENCYCLOPEDIA.items():
        if title.lower() == query.strip().lower():
            return body
    close = rank_by_word_overlap(query, ENCYCLOPEDIA)
    return f'Could not find "{query}". Similar: {", ".join(close[:3])}.'

ARITHMETIC = re.compile(r"^[\d\s+\-*/().]+$")

def calculator(expression):
    if not ARITHMETIC.match(expression):
        raise ToolError(f"calculator accepts digits and + - * / ( ) only")
    return str(eval(expression, {"__builtins__": {}}, {}))

TOOLS = {"search": search, "calculator": calculator}

The loop itself is thirty-one lines, blank ones included. Everything an agent framework wraps is here.

import re

ACTION = re.compile(r"^Action:\s*(\w+)\[(.*)\]\s*$", re.MULTILINE)
FINAL = re.compile(r"^Final Answer:\s*(.*)$", re.MULTILINE)


def run_react(llm, question, tools, max_steps=8):
    """Reason, act, observe, repeat. This is the whole agent."""
    scratchpad = ""
    for _ in range(max_steps):
        reply = llm(f"{SYSTEM}\nQuestion: {question}\n{scratchpad}")

        answer = FINAL.search(reply)
        if answer:
            return answer.group(1).strip(), scratchpad

        action = ACTION.search(reply)
        if action is None:
            observation = "No action found. Write Action: tool[argument]."
        else:
            name, argument = action.group(1), action.group(2)
            if name not in tools:
                observation = f"Unknown tool {name!r}. Available: {', '.join(tools)}."
            else:
                try:
                    observation = tools[name](argument)
                except Exception as exc:
                    observation = f"{name} failed: {exc}"

        scratchpad += f"{reply.strip()}\nObservation: {observation}\n"
    return None, scratchpad

llm is any callable that takes a prompt and returns text. The notebook passes a scripted stand-in that replays a fixed transcript, so this run is identical every time. Point it at a question whose answer sits in no single entry, and whose first lookup misses:

answer, trace = run_react(stub.complete, "How many years separate the LSTM "
                          "paper from Attention Is All You Need?", TOOLS)
print(trace, "\nFinal Answer:", answer)
Thought: I will look up Attention Is All You Need.
Action: search[Attention Is All You Need]
Observation: Could not find "Attention Is All You Need". Similar: Transformer, Adam, AlexNet.
Thought: That was not an entry, but Transformer was suggested.
Action: search[Transformer]
Observation: The Transformer was published in 2017 in the paper Attention Is All You Need. It replaced recurrence with self-attention, and the base model stacks 6 encoder layers with 8 attention heads.
Thought: Now the year for LSTM.
Action: search[LSTM]
Observation: The long short-term memory network is a recurrent architecture whose gated cell carries state across many time steps without the gradient vanishing. It was published in 1997 by Hochreiter and Schmidhuber.
Thought: I have both years, so I can subtract.
Action: calculator[2017-1997]
Observation: 20

Final Answer: 20

Four tool calls, five model calls, and a plan that changed after the first observation came back empty-handed. That change is the part worth understanding.

The notebook runs this exact function, then switches to an instrumented version of the same loop that records prompt sizes and lets each guard be turned off, both of which the measurements below need.

What Just Happened?

The trace format

The model has no special channel for calling tools here. It writes plain text in an agreed shape, and the loop reads that text with two regular expressions:

Thought: why I am doing this
Action: tool[argument]

The loop replies in the same medium, appending one line:

Observation: what the tool returned

Nothing else in the agent is doing any work. The loop never parses Thought, which exists for the model's benefit. Action is the only line the loop reads, and Observation is the only line it writes. Modern APIs give you structured tool calls instead of this text protocol, and the mechanics underneath are identical. Something in your code still has to decide when to stop, what to run, and what to paste back.

The scratchpad

Each pass, the loop rebuilds the entire prompt from three pieces:

prompt = f"{SYSTEM}\nQuestion: {question}\n{scratchpad}"

SYSTEM and question never change. scratchpad is a string that only ever grows, by three lines a pass. The model is stateless between calls, so the scratchpad is the agent's memory, and the model on call five knows what happened on call two only because the whole scratchpad was sent again.

State diagram of the ReAct loop. Four rounded boxes sit at the corners of a rectangle with grey arrows running clockwise: Thought to Action across the top, Action down to Tool on the right, Tool back to Observation across the bottom, and Observation up to Thought on the left. A grey three-block stack labelled scratchpad sits in the centre, with an amber dashed arrow into it from Observation and a blue dashed arrow out of it to Thought. A green arrow leaves Thought upward to a box labelled Final answer. A caption reads that every observation is appended, and the whole scratchpad goes back into the next prompt.

The dashed arrows carry the idea that the solid ones do not. Every observation is appended to the scratchpad, and the whole scratchpad is read back before the next decision. An agent that could not see its own previous observations would search for the Transformer entry forever.

Termination

Two things end the run, and you need both. The model can write Final Answer:, which is the exit it chooses. max_steps is the exit you impose. Only the second one holds when the model stops cooperating.

The redirect

Look again at the first two steps of the trace above. The action on step two, search[Transformer], is not derivable from the question. Nothing in "How many years separate the LSTM paper from Attention Is All You Need?" mentions the Transformer entry. That action exists because the observation from step one suggested it.

That dependency is the whole argument for interleaving, and it is measurable.

Going Deeper

Interleaving against planning up front

The alternative design is to plan the tool calls before running any of them: ask the model for a list of actions, execute the list, then reason once over everything that came back. It is a real pattern with real advantages, chiefly that the calls can run in parallel.

Twelve questions, all of the "how many years separate A and B" shape. Seven name entries that exist under their own titles. Five name something by description ("the paper that introduced residual connections", "the Hochreiter and Schmidhuber network"), so the first lookup misses and returns suggestions. The planner is given one adaptive step after its plan finishes, which is more than the canonical version gets.

Two panels. The left panel is a grouped bar chart of questions answered correctly, for seven questions with no redirect and five with a redirect. On the seven, all three designs score 7. On the five, the ReAct loop scores 5, plan then execute with one adaptive step scores 0, and plan then execute with two adaptive steps scores 5. The right panel is a bar chart of model calls used by the ReAct loop for each of the twelve questions: Q1 to Q7 use 4 calls each and are blue, Q8 to Q12 use 5 calls each and are amber, with a note that a redirect costs one extra round trip.

The ReAct loop answers 12 of 12. The planner answers 7 of 12, and the five it misses are exactly the five where the first lookup missed. Its plan was fixed before any observation existed, so it spent its single adaptive step on the redirect and had nothing left for the arithmetic.

Give the planner two adaptive steps and it answers 12 of 12 as well. That result matters more than the first one. The gap measures how much adaptation you budgeted before seeing any data, and a planner with enough adaptive steps has become a ReAct loop with a redundant plan in front of it. Plan up front when you know the shape of the work and want the calls to run in parallel. Interleave when an observation can change what the next call should be.

The right panel prices that adaptivity. Every redirect costs one extra round trip, four model calls becoming five.

The scratchpad bill

Here is the same loop on a question needing eight lookups, measured character by character.

Two panels. The left panel is a bar chart of prompt size in characters against model call, rising from 500 on call one to 2,124 on call nine, with a grey dashed line marking the 500-character empty scratchpad. The right panel plots cumulative input characters against model calls made, curving upward to 11,755 by call nine, against a flat grey dashed line at 2,124 marking the final prompt sent once. An annotation reads 11,755 characters billed for a 2,124-character answer, equal to 5.5 times.

The left panel is the part everyone expects. The prompt starts at 500 characters, of which all 500 are the system prompt and the question, and each pass adds roughly 200 more.

The right panel is the part that surprises people the first time they see a bill. Nine calls whose largest prompt is 2,124 characters cost 11,755 characters of input, because call one is re-sent nine times, call two eight times, and so on. Input grows with the square of the step count while the visible context grows linearly. Prompt caching is the standard answer, and it works well here because the scratchpad is append-only, so every cached prefix stays valid. At typical input rates the absolute number is small, though a hundred steps over a large codebase changes that. The LLM cost calculator will turn character counts into money for a model you have in mind, and the KV cache calculator covers the memory side of the same growth on the serving end.

The runaway loop

Delete max_steps and the first failure mode arrives on its own. A model that keeps issuing the same search and never writes Final Answer: has no reason to stop.

Line chart of cumulative input characters on a log scale against model call. A red line labelled no step cap rises steeply and continues to 100 calls, reaching over one million characters. A blue line labelled max_steps equals 6 stops after six calls at about 5,800 characters. An annotation reads 190 times the input of the capped run, and still going.

Stopped at 100 calls, the uncapped run has consumed 1,107,750 characters of input against the capped run's 5,835, a factor of 190. It was still going. A step cap is the only thing standing between a parsing bug and an unbounded bill.

Two crashes and their guards

The other two failure modes are crashes, and both come from trusting model output.

FailureWithout the guardWith the guard
The model names a tool that does not existKeyError: 'wikipedia'The observation reads Unknown tool 'wikipedia'. Available tools: search, calculator. The next action uses search and the run finishes two steps later
The action line does not parse (Action: calculator(2017-1997))ValueError: could not parse an actionThe observation names the expected format. The next action writes calculator[2017-1997] and the run finishes two steps later
The model never writes Final Answer:runs until the bill or the context window stops itmax_steps ends the run with a reported outcome

Both guards work the same way. They turn the error into an observation and let the model read it. A model that can see Unknown tool 'wikipedia'. Available tools: search, calculator. will pick a real tool on the next pass. A traceback teaches it nothing, because a traceback never reaches it.

The calculator in this post takes the same view of arithmetic. It matches its argument against ^[\d\s+\-*/().]+$ before evaluating and raises otherwise, which is why calculator[2017 minus 1997] produces an observation instead of an exception, and why eval on model output is survivable here.

Truncating observations

Real tool output is long. Paste a web page, a SQL result or a stack trace in whole and the scratchpad stops fitting. So you truncate, and truncation is where careful agents quietly break.

Sweeping the per-observation budget over the same twelve questions, with two truncation strategies:

Line chart of questions answered correctly out of twelve against characters kept per observation. A red line for keeping the head rises from 0 at 20 characters through 2 at 80 and 5 at 120 to 12 at 200. A green line for keeping the head and the tail rises faster, reaching 4 at 60, 10 at 80 and 12 from 120 onward. A grey band marks that entries are 120 to 204 characters long.

Keeping the first N characters needs a 200-character budget to answer all twelve, because several entries put the year in the final sentence. Keeping half the budget from each end reaches twelve at 120 characters and still answers ten at 80, where head-only truncation answers two.

Nothing errors in the failing runs. The agent reads a real observation, finds no year in it, and concludes it cannot answer. That is the shape of the bug in production too: a truncation limit set for one tool's output silently removes the field another tool puts at the end, and the agent starts giving up on questions it used to answer. Log what you cut.

Below 40 characters both strategies collapse to zero, and head-only briefly beats head-and-tail, since splitting a tiny budget in two leaves neither half containing anything whole.

Frameworks above the loop

The loop above is thirty-one lines and handles one model, two tools and one trace format. LangChain, the model SDKs' tool runners and the agent platforms are all solving what comes after that: retries and backoff, streaming partial output, structured tool schemas instead of a text protocol, parallel tool calls, tracing and replay, permission gates on destructive actions, and context management once the scratchpad outgrows the window.

Every one of those is worth having, and none of them changes the loop. Knowing where the seam sits tells you which layer to debug when an agent stalls, and lets you judge a framework on the list above instead of on the thirty-one lines it also happens to include.

Swapping in a real model

Everything so far ran against a scripted model, which is why the numbers reproduce. run_react takes the model as a function of one string, so a real one drops straight in:

# The only cell that needs an API key, and the only one that costs money.
import anthropic

client = anthropic.Anthropic()

def claude(prompt):
    message = client.messages.create(
        model="claude-opus-5",
        max_tokens=512,
        stop_sequences=["Observation:"],   # the loop supplies observations
        messages=[{"role": "user", "content": prompt}],
    )
    return "".join(b.text for b in message.content if b.type == "text")

answer, trace = run_react(claude, question, TOOLS)

stop_sequences is the load-bearing line. Without it a model will happily continue past its own action and write an Observation: of its own invention, and the loop will parse that invented text as though a tool had produced it. Stopping generation at the word the loop owns keeps the model's half of the transcript separate from the loop's.

Where This Comes From

Yao et al. introduced the pattern in "ReAct: Synergizing Reasoning and Acting in Language Models" (2022, arXiv:2210.03629). The paper's framing of why the two halves belong together:

"reasoning traces help the model induce, track, and update action plans as well as handle exceptions, while actions allow it to interface with and gather additional information from external sources such as knowledge bases or environments"

Those two clauses map onto the two experiments above. "Update action plans" is the redirect, and the twelve-question set is a miniature of the paper's HotpotQA setup, where a question names something the search index does not hold under that title. "Handle exceptions" is the guard table, where recovery from an unknown tool name amounts to the model reading an error and revising, with the loop doing nothing except passing the message along.

The tool surface here follows the paper's directly. Its Wikipedia API exposed search[entity], which returns the first five sentences of the matching page or the top five similar entity names when there is no exact match, plus lookup[string] and finish[answer]. The suggestion behaviour carries the experiment. It creates an environment where a fixed plan fails and a revised plan succeeds, which is why this post kept it.

Schick et al.'s "Toolformer: Language Models Can Teach Themselves to Use Tools" (2023, arXiv:2302.04761) asks the adjacent question. ReAct prompts a model to use tools it was never trained to use. Toolformer trains the model to insert API calls into its own text, keeping the calls that reduce perplexity on the following tokens. One is a property of the loop, the other a property of the weights, and current tool-using models are built with both.

Anthropic's engineering note "Building Effective Agents" (2024) is the practitioner counterweight. It separates workflows, where the code fixes the path, from agents, where the model directs its own steps, and recommends the simplest structure that works, because an agent's step count is its cost and its failure surface at the same time. The measurements above put numbers on that advice. Adaptivity buys the five redirect questions and costs one round trip each, and the loop that never stops costs 190 times the loop that does.

Further reading

  • The original paper: Yao et al. (2022), sections 3.1 and 3.2 for the Wikipedia action space and the HotpotQA prompts
  • The training-side counterpart: Schick et al. (2023), for tool use learned rather than prompted
  • The practitioner's view: Anthropic (2024), "Building Effective Agents", for when a workflow beats an agent
  • Next topic to learn: structured output and constrained decoding, which replaces the fragile Action: tool[argument] text contract with a schema the model cannot violate

Interactive Tools

  • LLM Cost Calculator: Turn the re-send multiplier measured above into money for the model and step count you have in mind
  • KV Cache Calculator: Size the memory side of the same growing context on the serving end

Stay in the loop

Get notified when new tutorials and deep-dives are published. No spam, unsubscribe anytime.

Related Posts

Frequently Asked Questions