Most agent tutorials hand you a framework and hide the interesting part. This one does the opposite: you will build a ReAct agent in Python with zero dependencies, in code short enough to read top to bottom. The agent writes out its reasoning in plain text, calls tools you define, reads the results, and repeats until it has an answer. No LangChain, no API key needed for the demo. Every line below was executed and verified before publishing.
What the ReAct loop actually is
ReAct, short for Reasoning and Acting, comes from a 2022 paper by Yao et al. (arXiv:2210.03629). The idea is simple: instead of asking a language model to answer in one shot, you let it interleave thinking with doing. Each cycle has three moves:
- Thought: the model reasons about what it knows and what it still needs.
- Action: it picks a tool and supplies an argument.
- Observation: your code runs the tool and hands the result back.
The model reads the observation, thinks again, and the cycle repeats until it writes a final answer. Because the protocol is plain text, it works with any model from any provider. You are not tied to a framework’s tool-calling API.
Step 1: Define the tools
A tool is just a Python function that takes a string and returns a string. We will build two: a calculator and a web-search stub. The calculator deserves care. Plenty of tutorials call eval() on model output directly, which lets a misbehaving model run arbitrary code. This version whitelists characters first and strips __builtins__, so even a hostile expression cannot touch the file system:
def calculate(expression: str) -> str:
"""Evaluate a math expression. Example input: '11200000 * 0.1'"""
if not set(expression) <= set("0123456789+-*/().% "):
return "Error: illegal characters in expression."
try:
return str(eval(expression, {"__builtins__": {}}))
except Exception as e:
return f"Error: {e}"
The search tool is a stub backed by a small dictionary. In a real project you would swap the body for a call to a search API; the rest of the agent never notices the difference:
def search_web(query: str) -> str:
"""Stub search tool. Swap this body for a real search API later."""
facts = {
"population of paris": "Paris population: about 11,200,000 (urban area).",
"capital of france": "The capital of France is Paris.",
}
q = query.lower()
for key, fact in facts.items():
if key in q or q in key:
return fact
return f"No facts found for '{query}'."
TOOLS = {"calculate": calculate, "search_web": search_web}
Registering a tool means adding one entry to the TOOLS dictionary. Nothing else in the agent changes.
Step 2: Write the prompt contract
The model cannot read your Python. It only sees text, so you teach it the protocol with a system prompt. This prompt is the most important string in the whole project: it defines the exact output format the parser will look for.
SYSTEM_PROMPT = """You are a problem-solving assistant. Reply in this exact format:
Thought: <your reasoning about what to do next>
Action: <tool name>[<single string argument>]
Available tools:
- calculate[expression]: evaluates math, e.g. calculate[11200000 * 0.1]
- search_web[query]: looks up a fact, e.g. search_web[population of paris]
Rules:
1. Output exactly ONE Thought line and ONE Action line per response.
2. When you have everything needed, reply with a Thought line and:
Final Answer: <your answer to the user>
3. Never invent tool results; only use what the Observation lines give you.
"""
Three details matter here. The format is rigid on purpose: a loose format turns parsing into a guessing game. The tool list sits in the same prompt the code defines, so adding a tool means updating one description. And rule 3 fights the model’s urge to hallucinate observations instead of waiting for the real ones.
Step 3: The loop and its parser
The loop itself is short. On each step it sends the conversation history to the model, extracts the action with a regular expression, runs the tool, and appends the observation. The LLM call hides behind one function, call_llm(), so you can plug in OpenAI, Anthropic, Ollama, or anything else without touching the loop:
def call_llm(messages: list[dict]) -> str:
"""Plug your provider's API call in here. Same shape in and out."""
raise NotImplementedError("Wire up your LLM provider here.")
def run_agent(task: str, llm=call_llm, max_steps: int = 6) -> None:
messages = [
{"role": "system", "content": SYSTEM_PROMPT},
{"role": "user", "content": task},
]
for step in range(1, max_steps + 1):
reply = llm(messages)
print(f"--- Step {step} ---")
print(reply.strip())
final = re.search(r"Final Answer:s*(.+)", reply, re.S)
if final:
print("nDone.")
return
action = re.search(r"Action:s*(w+)[(.*?)]", reply, re.S)
if not action:
print("Could not parse an Action line. Stopping.")
return
tool_name, tool_arg = action.group(1), action.group(2).strip()
if tool_name in TOOLS:
observation = TOOLS[tool_name](tool_arg)
else:
observation = f"Error: unknown tool '{tool_name}'."
print(f"Observation: {observation}n")
messages.append({"role": "assistant", "content": reply})
messages.append({"role": "user", "content": f"Observation: {observation}"})
print(f"Stopped after {max_steps} steps without a final answer.")
The failure handling is deliberate, not bolted on. A missing action line stops the run instead of crashing. An unknown tool name becomes an error observation the model can read and recover from. And max_steps caps the loop so a confused model cannot spin forever on your budget.
Step 4: Run the full worked example
To run the loop with no API key, use a small demo harness: a class that replays a fixed, human-written trajectory. This is a stand-in for call_llm(), and I am labeling it as such. It demonstrates the plumbing, not real model behavior.
class ScriptedLLM:
"""Replays a fixed trajectory. Demo harness only."""
def __init__(self):
self.step = 0
self.script = [
"Thought: I need the population of Paris first.n"
"Action: search_web[population of paris]",
"Thought: Paris has about 11,200,000 people. Now 10% of that.n"
"Action: calculate[11200000 * 0.1]",
"Thought: I have both numbers now.n"
"Final Answer: Paris has roughly 11.2 million people, "
"and 10% of that is about 1.12 million.",
]
def __call__(self, messages):
reply = self.script[self.step]
self.step += 1
return reply
run_agent(
"What is the population of Paris, and what is 10% of that number?",
llm=ScriptedLLM(),
)
The printed transcript shows the pattern doing its job:
--- Step 1 ---
Thought: I need the population of Paris first.
Action: search_web[population of paris]
Observation: Paris population: about 11,200,000 (urban area).
--- Step 2 ---
Thought: Paris has about 11,200,000 people. Now 10% of that.
Action: calculate[11200000 * 0.1]
Observation: 1120000.0
--- Step 3 ---
Thought: I have both numbers now.
Final Answer: Paris has roughly 11.2 million people, and 10% of that is about 1.12 million.
Done.
Each observation changes what the agent does next. The agent never has to get the plan right up front, because every tool result is a chance to correct course.
What breaks in real runs, and the guards that catch it
With a live model instead of the script, three things go wrong most often. First, the model writes an action the regex cannot parse — extra words around the brackets, a missing bracket. The loop stops cleanly, and the printed reply shows exactly what the model produced. Second, it invents a tool name that is not in TOOLS. That becomes an error observation, which usually nudges the model back to a real tool on the next step. Third, it loops: searching, calculating, searching again without converging. That is what max_steps is for. When a run hits the cap, read the transcript. It tells you whether the prompt needs tightening or the task needs smaller pieces.
Plug in a real model and go further
Swapping the demo for a live model means implementing call_llm(): send the message list to your provider, return the assistant’s text. Keep the temperature low so the output sticks to the format. From there, useful next steps are a third tool that reads files, a conversation log written to disk so you can replay failures, and a stricter action grammar if your model keeps drifting from the format. The loop stays the same no matter how many tools you add, because the behavior lives in the protocol rather than in a framework around it. When the tool list outgrows the loop, the natural next step is to expose those tools through the Model Context Protocol instead of hard-coding them.