Back to Blog

Build AI Apps with Python: The ReAct Agent Pattern — Think Act Observe | Episode 18

Celest KimCelest Kim

Video: Build AI Apps with Python: The ReAct Agent Pattern — Think Act Observe | Episode 18 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Build AI Apps with Python: The ReAct Agent Pattern — Think Act Observe

The ReAct pattern is a powerful approach to building AI agents that can reason through multi-step problems by iteratively thinking, acting, and observing results. Unlike simple chatbots that respond once, ReAct agents loop through this cycle until they reach a conclusion. This example demonstrates how to implement a ReAct agent in Python using two tools: a weather lookup and a calculator.

Code

import time

# Define tools the agent can use
def weather_lookup(location):
  # Simulate fetching weather data
  return f"The weather in {location} is sunny and 75°F."

def calculator(expression):
  # Evaluate a simple math expression safely
  try:
    result = eval(expression, {"__builtins__": {}})
    return f"The result of {expression} is {result}."
  except Exception:
    return "Invalid expression."

# Map tool names to functions
TOOLS = {
  "weather": weather_lookup,
  "calc": calculator,
}

class ReActAgent:
  def __init__(self):
    self.history = []

  def think(self, question):
    # Simple heuristic to pick tool based on keywords
    if "weather" in question.lower():
      return "weather", question.split("in")[-1].strip()
    elif any(op in question for op in ["+", "-", "*", "/"]):
      return "calc", question
    else:
      return None, question

  def act(self, tool_name, tool_input):
    if tool_name in TOOLS:
      return TOOLS[tool_name](tool_input)
    return "No suitable tool found."

  def observe(self, observation):
    self.history.append(observation)

  def run(self, question):
    done = False
    current_question = question
    while not done:
      tool, tool_input = self.think(current_question)
      if tool is None:
        # No tool needed, answer directly
        answer = f"Answer: {current_question}"
        self.observe(answer)
        done = True
      else:
        observation = self.act(tool, tool_input)
        self.observe(f"Used {tool} tool: {observation}")
        # For demo, assume one loop is enough
        done = True
    return self.history

# Example usage
agent = ReActAgent()
trace = agent.run("What is the weather in New York?")
for step in trace:
  print(step)

Key Points

  • The ReAct pattern structures AI agents as a loop of Thinking, Acting, and Observing until a solution is found.
  • Agents differ from chatbots by iterating multiple reasoning steps rather than producing a single response.
  • Tools are defined as functions and mapped by name, allowing the agent to dispatch actions dynamically.
  • The agent uses simple heuristics to select which tool to invoke based on the input question.
  • Observations from each action are recorded to maintain a trace of the agent’s reasoning process.