Python course Β· Module 10: AI and Language Models
ReAct Agents - Reasoning and Acting
In this lesson7
Welcome! Darwin here. Ask an ordinary model: "What is the weather in Serengeti and what animals live there?". It will answer smoothly, but it will make up the weather, because it has no access to any weather station. In earlier lessons we gave the model tools. Now we will teach it to use them step by step, like a tracker who first thinks, then follows the tracks, and finally assesses what they found.
ReAct (Reasoning and Acting) is a design pattern for AI agents that combines reasoning with taking actions. The agent alternates between "thinking" (reasoning) and "doing" (acting), which leads to better results! The pattern was described by researchers from Princeton and Google in the 2022 paper "ReAct: Synergizing Reasoning and Acting in Language Models".
What is ReAct?
ReAct is a paradigm in which an AI agent:
- Thought - analyzes the situation, plans
- Action - performs an action (e.g. calls a tool)
- Observation - observes the result of the action
- Repeat - repeats the cycle until the problem is solved
The loop keeps turning until the agent decides it has enough information. The bottom of the diagram shows the log of one expedition:
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β ReAct Loop β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β ββββββββββββ ββββββββββββ βββββββββββββββ β
β β Thought βββββΆβ Action βββββΆβ Observation β β
β β (Think) β β (Act) β β (Observe) β β
β ββββββββββββ ββββββββββββ ββββββββ¬βββββββ β
β β² β β
β ββββββββββββββββββββββββββββββββββββ β
β (Repeat) β
β β
β Example: β
β Thought: I need to check the weather in Serengeti β
β Action: get_weather("Serengeti") β
β Observation: Temperature 28Β°C, sunny β
β Thought: Now I can answer the user β
β Action: final_answer("The weather in Serengeti...") β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββObservation is the key: the model does not guess the result of an action, it receives the tool's real answer.
Basic ReAct implementation
The ReActAgent class stores a dict of tools, an iteration limit and the history of steps. The system prompt inserts tool descriptions, taking them from the functions' docstrings (func.__doc__), and teaches the model the Thought/Action/Answer format:
from openai import OpenAI
from typing import Callable
import json
import re
client = OpenAI()
class ReActAgent:
"""An agent implementing the ReAct pattern."""
def __init__(self, tools: dict[str, Callable], max_iterations: int = 10):
self.tools = tools
self.max_iterations = max_iterations
self.history: list[str] = []
def _create_system_prompt(self) -> str:
"""Creates a system prompt with tool descriptions."""
tool_descriptions = "\n".join([
f"- {name}: {func.__doc__}"
for name, func in self.tools.items()
])
return f"""You are a helpful Safari assistant who solves problems step by step.
Available tools:
{tool_descriptions}
Use this format:
Thought: [your reasoning about what to do next]
Action: [tool_name(arguments)]
When you have enough information to answer:
Thought: [final reasoning]
Answer: [your answer for the user]
Always think before acting. Analyze observations before taking the next step."""The max_iterations limit is a safety fuse: without it, an agent stuck in a loop would burn tokens forever.
The parser extracts three fragments with regular expressions from the re module. The re.DOTALL flag lets the dot match newline characters too:
def _parse_response(self, response: str) -> tuple[str, str, str]:
"""Parses the response into thought, action, and answer."""
thought_match = re.search(r'Thought:\s*(.+?)(?=Action:|Answer:|$)', response, re.DOTALL)
action_match = re.search(r'Action:\s*(.+?)(?=Thought:|Observation:|Answer:|$)', response, re.DOTALL)
answer_match = re.search(r'Answer:\s*(.+)', response, re.DOTALL)
thought = thought_match.group(1).strip() if thought_match else ""
action = action_match.group(1).strip() if action_match else ""
answer = answer_match.group(1).strip() if answer_match else ""
return thought, action, answerA missing match raises no exception, it just returns an empty string.
Executing an action turns text like get_weather("Serengeti") into a call of a real function:
def _execute_action(self, action_str: str) -> str:
"""Executes an action and returns the observation."""
# Parse function name and arguments
match = re.match(r'(\w+)\((.*)\)', action_str)
if not match:
return f"Error: Invalid action format: {action_str}"
func_name = match.group(1)
args_str = match.group(2)
if func_name not in self.tools:
return f"Error: Unknown tool: {func_name}"
try:
# Simple argument parsing
if args_str:
args = [arg.strip().strip('"').strip("'") for arg in args_str.split(',')]
result = self.tools[func_name](*args)
else:
result = self.tools[func_name]()
return str(result)
except Exception as e:
return f"Execution error: {str(e)}"Every error goes back to the model as observation text instead of stopping the program. Parsing arguments with split(',') is deliberately simple and breaks on a comma inside a string - in production it is better to use native function calling, which I show below.
The run method ties everything into a loop:
def run(self, query: str) -> str:
"""Runs the ReAct agent."""
self.history = [f"User: {query}"]
for i in range(self.max_iterations):
# Build context
context = "\n".join(self.history)
# Call LLM
response = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[
{"role": "system", "content": self._create_system_prompt()},
{"role": "user", "content": context}
],
temperature=0
)
llm_response = response.choices[0].message.content
thought, action, answer = self._parse_response(llm_response)
# Record thought
if thought:
self.history.append(f"Thought: {thought}")
print(f"Thought: {thought}")
# If there's a final answer
if answer:
print(f"Answer: {answer}")
return answer
# Execute action
if action:
self.history.append(f"Action: {action}")
print(f"Action: {action}")
observation = self._execute_action(action)
self.history.append(f"Observation: {observation}")
print(f"Observation: {observation}")
return "Exceeded iteration limit without finding an answer."Every turn appends the thought, the action and the observation to history, and on the next call the model receives the whole history. temperature=0 gives decisions that are as repeatable as possible, which is why I chose gpt-4.1-mini - reasoning models such as gpt-5-mini accept only the default temperature.
ReAct usage example
The tools are ordinary functions with docstrings. Here they return hard-coded data, in a real application they would call a weather API or a species database:
# Tool definitions
def get_weather(location: str) -> str:
"""Retrieves the current weather for a given location."""
weather_data = {
"Serengeti": "28Β°C, sunny, humidity 45%",
"Kilimanjaro": "5Β°C, cloudy, snow at the summit",
"Nairobi": "22Β°C, partly cloudy"
}
return weather_data.get(location, f"No weather data for {location}")
def search_animals(query: str) -> str:
"""Searches for information about Safari animals."""
animals = {
"lion": "Panthera leo - Africa's largest cat, lives in groups called prides",
"elephant": "Loxodonta africana - the largest land animal, lives 60-70 years",
"giraffe": "Giraffa camelopardalis - the tallest animal in the world, up to 5.5m tall"
}
for key, value in animals.items():
if key in query.lower():
return value
return f"No information found about: {query}"
def calculate_distance(from_loc: str, to_loc: str) -> str:
"""Calculates the distance between Safari locations."""
distances = {
("Nairobi", "Serengeti"): 350,
("Serengeti", "Kilimanjaro"): 280,
("Nairobi", "Kilimanjaro"): 200
}
key = (from_loc, to_loc)
reverse_key = (to_loc, from_loc)
if key in distances:
return f"{distances[key]} km"
elif reverse_key in distances:
return f"{distances[reverse_key]} km"
return f"Unknown distance between {from_loc} and {to_loc}"The docstring is not decoration: it goes into the system prompt, and the model decides which tool to use based on it.
Now we register the tools and send the agent into the field:
# Create the agent
tools = {
"get_weather": get_weather,
"search_animals": search_animals,
"calculate_distance": calculate_distance
}
agent = ReActAgent(tools=tools)
# Run
result = agent.run("What's the weather in Serengeti and what animals live there?")
print(f"\nFinal answer: {result}")For this question the agent usually performs two actions - get_weather and search_animals - before returning an Answer.
ReAct with LangChain
LangChain has a ready ReAct agent, so you do not write the loop yourself: the @tool decorator turns a function into a tool and takes the description from its docstring:
from langchain.agents import create_react_agent, AgentExecutor
from langchain_openai import ChatOpenAI
from langchain.tools import tool
from langchain import hub
# Tools as LangChain tools
@tool
def safari_weather(location: str) -> str:
"""Retrieves weather for a Safari location."""
return f"Weather in {location}: 26Β°C, sunny"
@tool
def animal_info(animal_name: str) -> str:
"""Searches for information about a Safari animal."""
return f"Information about {animal_name}: A magnificent African animal!"
@tool
def safari_distance(from_location: str, to_location: str) -> str:
"""Calculates the distance between Safari points."""
return f"Distance from {from_location} to {to_location}: 150 km"Now we connect the model, a ready ReAct prompt from LangChain Hub and the tools, and AgentExecutor runs the whole loop:
# LLM and prompt
llm = ChatOpenAI(model="gpt-4.1-mini", temperature=0)
prompt = hub.pull("hwchase17/react")
# ReAct Agent
tools = [safari_weather, animal_info, safari_distance]
agent = create_react_agent(llm, tools, prompt)
# Executor
agent_executor = AgentExecutor(
agent=agent,
tools=tools,
verbose=True,
handle_parsing_errors=True,
max_iterations=10
)
# Run
result = agent_executor.invoke({
"input": "Check the weather in Serengeti and tell me about lions"
})
print(result["output"])handle_parsing_errors=True sends a format error back to the model instead of stopping, and verbose=True prints every step. Mind the versions: this code works in LangChain 0.3. In LangChain 1.0, create_react_agent, AgentExecutor and hub were moved to the langchain-classic package (you import them from langchain_classic), and the recommended successor is create_agent from langchain.agents.
ReAct with OpenAI Function Calling
Modern models have built-in tool calling, so there is no text to parse. We describe the tool with a JSON schema, and the executing function receives ready arguments:
from openai import OpenAI
import json
client = OpenAI()
# Tool definitions for OpenAI
tools = [
{
"type": "function",
"function": {
"name": "get_safari_info",
"description": "Retrieves information about Safari",
"parameters": {
"type": "object",
"properties": {
"topic": {
"type": "string",
"description": "Topic: weather, animals, locations"
},
"query": {
"type": "string",
"description": "Detailed query"
}
},
"required": ["topic", "query"]
}
}
}
]
def execute_safari_tool(topic: str, query: str) -> str:
"""Executes a Safari tool."""
if topic == "weather":
return f"Weather for {query}: 28Β°C, sunny"
elif topic == "animals":
return f"Information about {query}: A fascinating Safari animal!"
elif topic == "locations":
return f"Location {query}: A popular Safari destination"
return "Unknown topic"The description field plays the same role as a docstring, and required says which arguments the model must not leave out.
The loop looks familiar, only instead of regular expressions we read message.tool_calls:
def react_with_functions(query: str) -> str:
"""ReAct using OpenAI function calling."""
messages = [
{
"role": "system",
"content": "You are a Safari expert. Answer step by step, using available tools."
},
{"role": "user", "content": query}
]
for _ in range(5): # Max iterations
response = client.chat.completions.create(
model="gpt-5-mini",
messages=messages,
tools=tools,
tool_choice="auto"
)
message = response.choices[0].message
messages.append(message)
# Check for tool calls
if message.tool_calls:
for tool_call in message.tool_calls:
args = json.loads(tool_call.function.arguments)
result = execute_safari_tool(**args)
messages.append({
"role": "tool",
"tool_call_id": tool_call.id,
"content": result
})
else:
# No tool calls = final answer
return message.content
return "Exceeded iteration limit"
# Usage
answer = react_with_functions("What's the weather like in Serengeti?")
print(answer)The model's reply with tool_calls must be appended to messages before the results, and each result is linked to its call through tool_call_id. tool_choice="auto" lets the model decide whether it needs a tool. The thought is not printed as Thought here, but the action and observation cycle stays the same. For new projects I recommend exactly this version, because it is the most robust against format errors.
Advanced ReAct with memory
An agent can also assess its own progress. First a structure for a single step - @dataclass generates the constructor, and field(default_factory=datetime.now) inserts the creation time:
from dataclasses import dataclass, field
from typing import Optional
from datetime import datetime
@dataclass
class ThoughtStep:
"""An agent reasoning step."""
thought: str
action: Optional[str] = None
observation: Optional[str] = None
timestamp: datetime = field(default_factory=datetime.now)Optional[str] means the action and the observation may be empty, for example for the final thought.
An agent with reflection asks the model every few steps to assess the route so far:
class AdvancedReActAgent:
"""Advanced ReAct agent with memory and reflection."""
def __init__(self, tools: dict, model: str = "gpt-5-mini"):
self.tools = tools
self.model = model
self.client = OpenAI()
self.thought_history: list[ThoughtStep] = []
self.long_term_memory: list[str] = []
def reflect(self) -> str:
"""Reflects on the steps taken so far."""
if len(self.thought_history) < 2:
return ""
steps_summary = "\n".join([
f"- Thought: {s.thought}, Action: {s.action}, Result: {s.observation}"
for s in self.thought_history[-3:]
])
response = self.client.chat.completions.create(
model=self.model,
messages=[
{
"role": "system",
"content": "Analyze the steps taken so far and suggest improvements."
},
{
"role": "user",
"content": f"Steps so far:\n{steps_summary}"
}
],
max_completion_tokens=1000
)
return response.choices[0].message.content
def should_reflect(self) -> bool:
"""Decides whether the agent should reflect."""
# Reflect every 3 steps or when the last action failed
if len(self.thought_history) % 3 == 0 and len(self.thought_history) > 0:
return True
if self.thought_history and "error" in (self.thought_history[-1].observation or "").lower():
return True
return False
def run(self, query: str) -> str:
"""Runs the agent with reflection."""
# ... implementation similar to the basic version
# but with added reflection
for i in range(10):
if self.should_reflect():
reflection = self.reflect()
print(f"Reflection: {reflection}")
# ... rest of the ReAct logic
return "Answer"The run method is a skeleton to complete in the exercise. In reflect I used max_completion_tokens: reasoning models do not accept the older max_tokens, and the new limit also covers hidden reasoning tokens, so do not set it too low.
ReAct patterns
The basic loop can be extended in several ways. The docstring at the top is a map of the variants, and the class below it sketches the planning variant:
"""
Popular patterns used in ReAct agents:
1. BASIC ReAct
Thought -> Action -> Observation -> Repeat
2. ReAct with Reflection
Thought -> Action -> Observation -> Reflect -> Repeat
3. ReAct with Planning
Plan -> Thought -> Action -> Observation -> Replan -> Repeat
4. ReAct with Self-Consistency
Multiple ReAct traces -> Vote on best answer
5. ReAct with Retrieval (RAG-ReAct)
Thought -> Retrieve -> Augment -> Action -> Observation
"""
# Example: ReAct with Planning
class PlanningReActAgent:
def __init__(self, tools: dict):
self.tools = tools
self.plan: list[str] = []
self.current_step = 0
def create_plan(self, query: str) -> list[str]:
"""Creates an action plan before starting."""
# LLM creates a step-by-step plan
response = client.chat.completions.create(
model="gpt-5-mini",
messages=[
{
"role": "system",
"content": "Create a step-by-step plan to solve the task. Each step on a new line."
},
{"role": "user", "content": query}
]
)
plan = response.choices[0].message.content.split("\n")
return [step.strip() for step in plan if step.strip()]
def replan(self, remaining_steps: list[str], new_info: str) -> list[str]:
"""Updates the plan based on new information."""
# LLM can modify the remaining steps
return remaining_steps # or modified stepsSelf-consistency runs several independent traces and picks the answer most of them point to. My advice: start with basic ReAct and add variants only when you see a concrete problem.
ReAct is a powerful pattern for AI agents. It combines reasoning with acting, which leads to more thoughtful and accurate answers. In the next module you will learn even more advanced techniques - RAG and Multi-Agent systems!
Remember: a good agent is like a good tracker - it thinks first, then checks the tracks, and answers only once it has seen them with its own eyes.
Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What is the ReAct pattern in the context of AI agents?
Hands-on tasks in the game
- Vertical ordering
Arrange the steps of the ReAct loop in the correct order:
- Vertical ordering
Arrange the steps of the ReAct loop in the correct order:
- Code editor
Create a ReActAgent class with run() and execute_action() methods.
- Click in order
Click the buttons to create a ReAct agent with LangChain:
- Vertical ordering
Arrange the ReAct steps with reflection:
- Code editor
Implement an agent with tools: get_weather, search_animals, calculate_distance.
Tasks after this lesson
- QuestionReAct Pattern
- Put in orderReAct Loop
- Put in orderReAct Loop
- Coding taskReAct Agent
- Click in orderReAct with LangChain
- Put in orderReAct with Reflection
- Coding taskProject: ReAct Safari Agent
- VideoAI with LLM - Theory Summary
- Coding taskProject: Safari Chatbot
- Coding taskProject: AI with Tools
- Coding taskProject: Safari AI API
- Project to submitSubmit your AI project to a mentor
- VideoModule Summary