Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 10

ReAct Pattern: Interleaving Reasoning and Tool Actions

Recommended resources

Introduction

In our last lesson, we constructed the core engine of our agent: an asynchronous observe-think-act loop. This loop gives our agent the ability to call tools and use their outputs to inform its next step. However, the "think" phase remained a black box. The LLM would decide to call a tool, but its reasoning for that decision was implicit in its internal state.

This lesson will open that black box. We will implement the ReAct (Reason + Act) pattern, a foundational technique in agent design. By modifying our agent's prompt and loop logic, we will instruct the LLM to externalize its thought process, interleaving explicit reasoning traces with its tool actions. This not only makes the agent's behavior more transparent and debuggable but also significantly enhances its ability to solve complex, multi-step problems. Your experience with async programming will continue to be valuable as we refine our agent's core loop.


The ReAct Pattern: Combining Reasoning and Action

The core idea of ReAct is to have the agent "think out loud." Instead of just deciding on an action, the agent first generates a Thought, which is a textual rationale for its plan. It then performs an Action (like calling a tool), receives an Observation (the tool's output), and repeats the cycle.

A simple diagram illustrating the iterative ReAct cycle. The agent generates a Thought, performs an Action, receives an Observation, and then loops back to generate a new Thought based on the new information.

A simple diagram illustrating the iterative ReAct cycle. The agent generates a Thought, performs an Action, receives an Observation, and then loops back to generate a new Thought based on the new information.

This seemingly simple change has profound implications for agent performance. To understand why, let's explore the theory behind it.

ReAct Pattern: Interleaving Reasoning and Action for LLM Agents

This article provides an excellent deep dive into the principles of the ReAct pattern. It explains not just what it is, but why it is so effective.

As you read, focus on these three key areas: Start with the introductory section, from the beginning, to understand the fundamental gap that ReAct fills. Next, read the section on "The ReAct Formulation" to see how this pattern is formalized as a sequence of (thought, action, observation) triples. This will appeal to your mathematical inclinations, as it defines the agent's execution history, or trajectory τ. Find this section by looking for the heading The ReAct Formulation. Finally, read the section on "The Reasoning-Action Interleaving". This part contrasts ReAct with two alternatives: "Reason-then-Act" and "Act-without-Reason." Understanding these trade-offs is crucial from a systems architecture perspective, as it highlights ReAct's advantages in flexibility and error recovery. Find this section under the heading The Reasoning-Action Interleaving.

As the article explains, the key benefit of ReAct is its dynamic, self-correcting nature. A "Reason-then-Act" agent that creates a full plan upfront is brittle; if an early step fails or returns unexpected information, the rest of the plan is likely invalid. An "Act-without-Reason" agent lacks strategic direction and can get stuck in loops. ReAct provides the best of both worlds: each action is guided by explicit reasoning, and each observation immediately informs the next step, allowing the agent to adapt on the fly.


Prompting for Thoughts and Actions

To implement ReAct, we must teach the LLM to generate output in the desired Thought -> Action format. This is achieved through prompt engineering, specifically by providing a detailed system prompt that includes clear instructions and few-shot examples.

The prompt must define:

  1. The structure of the loop: Thought, Action, Observation.
  2. The format for thoughts (free-form text).
  3. The format for actions (a specific, parsable syntax like tool_name[parameters]).
  4. A list of available tools and their descriptions.
  5. One or more complete examples of a successful ReAct trajectory.

Let's watch a clear breakdown of how to construct such a prompt and define the tools the agent can use.

Python: Create a ReAct Agent from Scratch

This video provides an excellent walkthrough of creating a system prompt specifically for a ReAct agent.

Watch the segment from this timestamp. Pay close attention to how the prompt: Instructs the model on the Thought, Action, Pause, Observation cycle. Defines the available actions (calculate, getPlanetMass) with clear syntax examples. Provides a complete few-shot example showing a multi-step interaction to solve a query. Defines the tool functions in Python that correspond to the actions described in the prompt.

The key takeaway is that the LLM learns the desired behavior by imitating the structure provided in the system prompt. The consistency and clarity of your few-shot examples are critical for reliable performance.


Implementation: Modifying the Agent Loop for ReAct

Now, let's turn theory into practice by modifying our asynchronous agent loop. The core logic remains the same—a while loop that calls an LLM—but we will change what we do inside that loop. Instead of just checking for tool calls, we will now parse for Thought and Action text, execute the action, and format the Observation to be fed back in the next iteration.

Simon Willison's article on the ReAct pattern provides a concise and elegant from-scratch implementation that we can use as a reference. It uses simple string parsing with regular expressions, which is a perfect way to build this from first principles.

A simple Python implementation of the ReAct pattern for ...

This article demonstrates a complete, minimal implementation of the ReAct pattern in Python.

First, review the examples to see the raw output of the agent. Notice the clear Thought:, Action:, PAUSE, and Observation: markers. This is the text we will be generating and parsing. Then, study the Python code provided in the article. You don't need to copy it verbatim, as our agent has a slightly different structure, but focus on the core logic: The System Prompt: Note how the prompt is constructed to explain the pattern and available actions. The Main Loop: See how it repeatedly calls the LLM. Parsing Logic: The most important part is how it parses the LLM's output string to find the action to execute. The article uses a simple if "Action:" in response: check and string splitting. For our purposes, a regular expression is more robust. Action Execution: Once parsed, the action is executed, and its output is formatted as an Observation: string for the next loop iteration.

Let's integrate this into our existing Agent class. The main changes will be in the run method of the agent loop we built in the last lesson.

Here is the pseudocode for our updated loop:

# Assume 'agent' is an instance of our Agent class
# and 'prompt' contains the system prompt and initial user query.

history = [user_query]
for i in range(MAX_ITERATIONS):
    # 1. THINK
    response_text = await agent.call_llm(history)
    history.append(response_text) # Add LLM's raw Thought/Action output

    # 2. PARSE ACTION
    # Use regex to find "Action: tool_name[parameters]"
    action_match = re.search(r"Action:\s*(\w+)\[(.*?)\]", response_text)

    if not action_match:
        # If no action, the agent might be giving a final answer or is stuck.
        # Break or handle accordingly.
        print("Final Answer:", response_text)
        break
    
    tool_name = action_match.group(1)
    tool_params = action_match.group(2)
    
    if tool_name == "finish":
        # Agent has decided it's done.
        print("Final Answer:", tool_params)
        break

    # 3. ACT & OBSERVE
    # Execute the tool and get the observation.
    observation = await execute_tool(tool_name, tool_params)
    
    # Format the observation and add it to history for the next loop.
    observation_text = f"Observation: {observation}"
    history.append(observation_text)

This loop explicitly implements the Thought-Action-Observation cycle.

  • Thought: The response_text from the LLM contains the thought. We don't need to parse it separately; we just add the whole thing to the history so the LLM remembers its own reasoning.
  • Action: We parse the Action: line using a regular expression to extract the tool and its parameters.
  • Observation: We execute the tool and format its output as a string, which is then appended to the history for the next iteration.

This iterative process of appending (Thought+Action) and then Observation to the history is what builds the full ReAct trajectory, τ, in the LLM's context window.


A Worked Example: Multi-Hop Question Answering

Let's see this in action with a query that requires multiple steps: "What is the population of the city where the author of 'The Old Man and the Sea' was born?"

This requires the agent to:

  1. Find the author of the book.
  1. Find the birthplace of the author.
  2. Find the population of that city.

Here is how a ReAct agent would tackle this, with the trajectory building at each step.

Iteration 1:

  • Prompt: (System Prompt) Question: What is the population of the city where the author of 'The Old Man and the Sea' was born?
  • LLM Output (Thought + Action): Thought: I need to first find the author of 'The Old Man and the Sea'. I will use the search tool for this.\nAction: search[author of The Old Man and the Sea]
  • Action Execution: The agent calls the search tool with the query.
  • Observation: Observation: The author of 'The Old Man and the Sea' is Ernest Hemingway.

Iteration 2:

  • Prompt: (History from Iteration 1) ... Observation: The author... is Ernest Hemingway.
  • LLM Output (Thought + Action): Thought: Now that I know the author is Ernest Hemingway, I need to find his birthplace.\nAction: search[Ernest Hemingway birthplace]
  • Action Execution: The agent calls the search tool again.
  • Observation: Observation: Ernest Hemingway was born in Oak Park, Illinois.

Iteration 3:

  • Prompt: (History from Iteration 2) ... Observation: Ernest Hemingway was born in Oak Park, Illinois.
  • LLM Output (Thought + Action): Thought: I have the birthplace, Oak Park, Illinois. Now I need to find its population.\nAction: search[population of Oak Park, Illinois]
  • Action Execution: Another search call.
  • Observation: Observation: The population of Oak Park, Illinois is 54,583.

Iteration 4:

  • Prompt: (History from Iteration 3) ... Observation: The population of Oak Park, Illinois is 54,583.
  • LLM Output (Thought + Action): Thought: I have all the pieces of information required to answer the question. I will now provide the final answer.\nAction: finish[The population of the city where the author of 'The Old Man and the Sea' was born is 54,583.]
  • Action Execution: The agent sees the finish action and terminates the loop, returning the final answer.

This step-by-step trace, where each thought justifies the subsequent action, is the hallmark of the ReAct pattern and is what makes the agent's behavior both powerful and auditable.


Conclusion

In this lesson, we have fundamentally upgraded our agent's cognitive architecture. By moving from an implicit to an explicit reasoning process, we have laid the groundwork for more complex and reliable agentic behavior.

Your key takeaways are:

  • The ReAct pattern integrates reasoning and acting into a tight loop (Thought -> Action -> Observation), allowing agents to tackle complex problems and dynamically adapt to new information.
  • Prompt engineering is key: The agent learns the ReAct pattern by following detailed instructions and few-shot examples in its system prompt.
  • The implementation involves modifying the core agent loop to parse for both thoughts and actions, execute the action, and feed the resulting observation back into the context.
  • This explicit reasoning chain creates an auditable trajectory, making it easier to debug why an agent took a certain action, a critical feature for production systems.

Our agent can now think and act more transparently. However, it still operates under a "happy path" assumption. What happens if a tool fails? For instance, what if an API times out or returns an error code? Our current loop would likely fail or get stuck.

In our next lesson, we will address this by implementing robust error handling. You will learn how to propagate tool execution errors back to the LLM, enabling the agent to recognize the failure, reason about it in its next "thought," and attempt to recover by re-planning or trying an alternative tool.