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

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.

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.

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.

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.

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.
| Failure | Without the guard | With the guard |
|---|---|---|
| The model names a tool that does not exist | KeyError: '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 action | The 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 it | max_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:

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
Related Posts
- KV Cache Memory: Sizing LLM Inference: What the growing scratchpad costs in GPU memory rather than in tokens
- LLM Serving: Continuous Batching & PagedAttention: Why agent traffic, with its many short calls over a shared prefix, is the hard case for a serving stack
- GraphRAG in Python: Knowledge Graphs for Document QA: A retrieval tool worth putting behind the
searchaction in this post - Reward Hacking in Reinforcement Learning: The failure mode of a system that optimises the measurement of a task instead of the task
- GRPO from Scratch: Group-Relative Advantage Without a Critic: The post-training method that teaches a model to use loops like this one well
- Four Multi-Agent Orchestration Patterns in Python: Agents like this one composed as a chain, a supervisor, a fan-out and a debate, with tokens, wall-clock and accuracy measured for each






