Skip to content
ImagineWorld

Reasoning and Acting

node_idnode-book_llm-design-patterns_chapter-21-reasoning-and-acting
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num21
chapter_titleReasoning and Acting
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Reasoning and Acting (ReAct) is a prompting technique developed by researchers from Princeton University and Google that enhances an LLM’s ability to perform reasoning and acting in simulated environments (https://arxiv.org/pdf/2210.03629). It allows LLMs to mimic human-like operations in the real world, where we reason verbally and take actions to gain information. ReAct combines reasoning and acting to solve complex language reasoning and decision-making tasks.

While CoT prompting enables LLMs to generate reasoning traces, its lack of access to the external world can lead to issues such as fact hallucination. ReAct addresses this by allowing LLMs to generate both verbal reasoning traces and text actions for a task. These text actions enable the model to interact with its environment (for example, by querying an external knowledge source or using a tool), gather information, and adjust its reasoning accordingly.

The key characteristics of ReAct are as follows:

  • Reasoning traces: LLMs generate text that explains their thought process step by step
  • Action generation: LLMs produce text actions that represent interactions with external tools or environments
  • Observation incorporation: The results of actions (observations) are fed back into the LLM’s context, influencing subsequent reasoning and actions
  • Iterative process: ReAct typically involves multiple Thought / Action / Observation steps, allowing for dynamic problem solving

ReAct excels in the following scenarios:

  • When a task requires information beyond the LLM’s pre-trained knowledge (for example, multi-hop question answering or fact verification)
  • When an LLM needs to navigate and interact with a simulated environment (for example, online shopping or text-based games)
  • When you need to combine the power of LLMs with the capabilities of external tools (for example, search engines, calculators, and APIs)
  • When the task requires a problem to be broken down into smaller steps and decisions must be made based on intermediate results

In this chapter, we’ll be covering the following topics:

  • Implementing ReAct in LangChain
  • Building ReAct agents with LangChain’s Expression Language
  • Completing tasks and solving problems
  • Evaluating ReAct’s performance
  • Safety, control, and ethical considerations
  • Limitations and future directions

The open source LLM framework LangChain (https://www.langchain.com/) provides a powerful and flexible implementation of the ReAct framework through its Agent class. Let’s explore how to create and use ReAct agents in LangChain:

  1. Install the
    # !pip install langchain openai duckduckgo-search youtube_search wikipedia langchainhub
    These packages enhance language model capabilities within the LangChain framework:
    • LangChain serves as a framework for developing applications powered by language models, enabling them to connect to external data sources and tools
      • OpenAI provides access to powerful language models through its API, forming the core of many LangChain applications
      • duckduckgo-search and youtube_search integrate search engine functionalities, allowing language models to retrieve real-time information from the web and YouTube, respectively
      • wikipedia enables language models to access and utilize information from Wikipedia, broadening their knowledge base
      • langchainhub is a central repository for sharing and discovering LangChain assets, such as prompts, chains, and agents
  2. Initialize the language model and tools such as wikipedia, ddg-search, and llm-math. These are listed in the following code snippet:
    import os
    import getpass
    os.environ["OPENAI_API_KEY"] = getpass.getpass("Enter Your OpenAI API Key:")
    from langchain.agents import load_tools
    from langchain.chat_models import ChatOpenAI
    # load the language model, you can use any model you like
    llm = ChatOpenAI(model = "gpt-4o", temperature=0)
    # load tools
    tools = load_tools(['wikipedia', 'ddg-search','llm-math'],
    llm=llm)
    Here, we import the necessary modules from langchain. Then, a language model (ChatOpenAI) is initialized with the specified model (gpt-4-1106-preview and temperature. Finally, we load some tools that our agent will use.
  3. Initialize the ReAct agent. Here, the initialize_agent function creates and initializes
    from langchain.agents import initialize_agent
    from langchain.agents import AgentType
    # initialize agent
    agent = initialize_agent(
    tools,
    llm,
    agent=AgentType.ZERO_SHOT_REACT_ DESCRIPTION,
    verbose=True
    )
    In the preceding code, we list tools and llm, which refers to the language model, as well as specify the agent type as AgentType.ZERO_SHOT_REACT_DESCRIPTION. Here, verbose=True enables detailed logging of the agent’s thought process.
  4. Inspect the ReAct agent’s prompt. The following line prints the prompt template used by the ReAct agent. This prompt provides instructions to the LLM on how to use the available tools and follow the ReAct format (Thought, Action, Action Input, and Observation):
    print(agent.agent.llm_chain.prompt.template)
    Inspecting the ReAct agent’s prompt is important because it reveals the structure and logic that guide the behavior of the language model during tool-augmented reasoning and action. By printing the prompt template with print(agent.agent.llm_chain.prompt.template), you’re not just seeing arbitrary instructions – you’re inspecting the behavioral scaffold that governs how the agent sequences its reasoning and tool use. This includes how it interprets a user query, chooses a tool from its available action set, constructs the input to the tool, and integrates the tool’s output (Observation) into further reasoning. If the prompt is poorly constructed, the model may misinterpret the tools, take invalid actions, or fail to chain thoughts coherently. Additionally, the template often includes few-shot examples that demonstrate how to alternate between the ReAct components properly. These examples act as implicit instructions for formatting and logic, helping the model generalize to unseen tasks. Inspecting them can reveal whether the agent was trained or instructed using general patterns or highly specific use cases. It also helps developers debug unexpected behavior or hallucinations since modifying the template directly influences the agent’s action selection, reasoning fidelity, and overall alignment with the intended ReAct cycle.
  5. The following code block demonstrates how to customize the prompt template. You can modify the instructions, examples, and formatting to better suit your specific
    prompt = """
    You are an intelligent agent designed to solve complex queries by breaking them down systematically and using available tools strategically. Follow the ReAct (Reasoning and Acting) framework to approach each task.
    ReAct Principles:
    1. Reasoning: Always start by carefully analyzing the question and developing a clear, step-by-step thought process.
    2. Tool Selection: Critically evaluate which tools will be most effective for addressing the specific query.
    3. Iterative Interaction: Be prepared to cycle between reasoning and action multiple times, refining your approach as you gather more information.
    4. Comprehensive Understanding: Aim to not just find an answer, but to truly comprehend the underlying context and nuances of the question.
    5. Transparent Decision-Making: Clearly articulate your reasoning, actions, and thought process at each step.
    Available Tools:
    - Wikipedia: Retrieve factual information about people, places, historical events, and general knowledge topics.
    - Google Search: Fetch current information, recent events, and up-to-date context.
    - Calculator: Perform mathematical calculations and numerical analysis.
    Interaction Format:
    Question: The specific query to be solved
    Thought: Detailed reasoning about the approach, breaking down the problem
    Action: Selected tool (Wikipedia/Google Search/Calculator)
    Action Input: Precise query for the selected tool
    Observation: Results obtained from the tool
    ... (Repeat reasoning, action, and observation as needed)
    Thought: Final synthesized understanding
    Final Answer: Comprehensive and well-reasoned response to the original question
    Important Guidelines:
    - Be methodical and explicit in your reasoning
    - Use tools judiciously and avoid unnecessary actions
    - Integrate information from multiple sources when appropriate
    - Provide a clear, concise, and informative final answer
    Begin!
    Question: {input}
    Thought:{agent_scratchpad}
    """
    Here, agent.agent.llm_chain.prompt.template = prompt updates the agent’s prompt with the custom template.
  6. Next, you can modify the descriptions of the tools to provide more specific guidance to the LLM on when and how to use
    tools[1].description = "A date retrieval tool that provides the current date and time, useful for temporal queries, scheduling, age calculations, or understanding time-sensitive contexts."
    tools[2].description = "A powerful computational tool capable of performing various mathematical operations, including arithmetic calculations, algebraic computations, percentage calculations, unit conversions, and advanced mathematical functions."
  7. The following line executes the agent with a sample query. The agent will use the ReAct framework to perform reasoning, select tools, execute actions, and generate a
    agent.run("What is the population of the largest city in Canada? How many days would it take for that city's population to count to 1 billion if each person counts one number per second without breaks? Then, compare this time to the average lifespan of a human in years, and explain which is longer.")

Next, we’ll look at an example of using ReAct for document processing that leverages LangChain.

LangChain also provides a DocstoreExplorer class for implementing ReAct logic with document stores such as Wikipedia. We’ll demonstrate an example by using DocstoreExplorer with Wikipedia for document-based ReAct:

from langchain import Wikipedia
from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType
from langchain.agents.react.base import DocstoreExplorer
docstore = DocstoreExplorer(Wikipedia())
search_tool = Tool(name="Search",
func=docstore.search,
description="Search for latest information about any topic"
)
lookup_tool = Tool(name="Lookup",
func=docstore.lookup,
description="Lookup tool for get information from a keyword"
)
tools = [search_tool, lookup_tool]
llm = OpenAI(temperature=0)
react = initialize_agent(tools,
llm,
agent=AgentType.REACT_DOCSTORE,
verbose=True)
question = "Who is the current governor of Texas and when was he born ?"
react.run(question)

This code sets up a LangChain agent designed to answer questions by interacting with Wikipedia. Here’s a breakdown:

  1. Wikipedia access: First, it initializes a connection to Wikipedia, allowing the agent to retrieve information from it.
  2. Tool creation: Next, it defines two tools: Search and Lookup. The Search tool enables the agent to find relevant Wikipedia pages, whereas the Lookup tool lets it extract specific information from those pages.
  3. Agent initialization: Then, it creates a ReAct agent. This agent is configured to use the previously defined tools and an OpenAI language model. In the preceding code, AgentType.REACT_DOCSTORE explicitly configures the agent for document store interactions – in this case, those for Wikipedia.
  4. Question execution: Finally, it runs the agent with a question that requires accessing and processing information from Wikipedia. The agent will use the Search tool to find relevant pages and the Lookup tool to extract the answer.

Building ReAct agents with LangChain’s Expression Language

Section titled “Building ReAct agents with LangChain’s Expression Language”

LangChain Expression Language (LCEL) offers a declarative approach to constructing ReAct agents. Instead of manually orchestrating the steps, LCEL allows you to define a processing graph that handles user input, reasoning, action selection, and final response generation. This section demonstrates how to implement a ReAct agent using this powerful framework.

The core idea is to establish a data pipeline that takes a user’s query, uses an LLM to reason through a series of steps, potentially leveraging external tools, and ultimately arrives at an answer. This pipeline can be succinctly expressed using LCEL.

The following is a Python code example demonstrating this process:

from langchain_core.prompts import ChatPromptTemplate
from langchain_core.runnables import chain
from langchain.agents.format_scratchpad import format_log_to_str
from langchain.agents.output_parsers import(
ReActSingleInputOutputParser)
from langchain.tools import DuckDuckGoSearchRun
from langchain_openai import ChatOpenAI
# 1. Define Tools: In this simple example, we are using a search tool.
tools = [DuckDuckGoSearchRun()]
# 2. Construct the Prompt: Instead of pulling from a hub, we'll define a basic prompt template.
template = """Answer the following questions as best you can. You have access to the following tools:
{tool_descriptions}
Use the following format:
Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question
Begin!
Question: {input}
{agent_scratchpad}"""
prompt = ChatPromptTemplate.from_template(template)
prompt = prompt.partial(
tool_names=", ".join([t.name for t in tools]),
tool_descriptions="\n".join(
[f"{t.name}: {t.description}" for t in tools]
),
)
# 3. Instantiate the LLM: We use ChatOpenAI, but any LLM can be used.
llm = ChatOpenAI(temperature=0)
# We also configure it to stop when it sees '\nObservation:'
llm_with_stop = llm.bind(stop=["\nObservation:"])
# 4. Construct the Agent Pipeline using LCEL:
agent = (
{
"input": lambda x: x["input"],
"agent_scratchpad": lambda x:
format_log_to_str(x["intermediate_steps"]),
}
| prompt
| llm_with_stop
| ReActSingleInputOutputParser()
)

Let’s take a closer look at this setup:

  1. A custom prompt template is defined to guide the LLM’s reasoning and action selection, instead of one being fetched from a hub. This template instructs the LLM on the expected format of the interaction (Question, Thought, Action, Observation, Final Answer).
  2. ChatOpenAI serves as the LLM, configured to halt generation upon encountering the \nObservation: string. This signal indicates that the agent has completed an action and is awaiting the result.
  3. The agent pipeline is constructed via LCEL, which is the chaining operation (|). This pipeline orchestrates the flow of information:
    • It formats the input and agent’s scratchpad (previous reasoning steps)
      • It feeds the formatted input to the prompt
      • The LLM, with its configured stopping criteria, processes the prompt
      • Finally, ReActSingleInputOutputParser parses the LLM’s output, distinguishing between actions to be taken and the final answer

This component is key for interpreting the LLM’s output and determining the next step in the ReAct loop:

  • Instantiation: You create an instance of the parser, ready to process LLM-generated text
  • Functionality: It examines the LLM’s output for patterns that indicate either an AgentAction object (requesting the execution of a tool) or an AgentFinish object (providing the final answer)
    • If it detects AgentAction, it extracts the tool’s name and the input to be passed to the tool
      • If it finds AgentFinish, it extracts the final answer
  • Usage: The parser receives the raw text output from the LLM and returns either AgentAction or AgentFinish
  • Error handling: If the LLM’s output doesn’t conform to the expected ReAct format (for example, it’s missing Action: or Final Answer:), the parser raises an exception, indicating a problem with the LLM’s reasoning or the prompt

In the following code, AgentExecutor is a component responsible for managing the execution of an agent’s actions, which are chosen based on the agent’s decision-making process. It acts as a driver for the agent, facilitating the interaction between the agent and external tools.

Here’s an example:

from langchain.agents import AgentExecutor
agent_executor = AgentExecutor(agent=agent, tools=tools, verbose=True)
response = agent_executor.invoke(
{
"input": "Who is the current CEO of Microsoft and what is their age squared?"
}
)
print(response)

Here, the following occurs:

  1. We create an AgentExecutor instance, providing it with the agent pipeline we defined earlier and the available tools, before setting verbose=True to see the agent’s thought process.
  2. The agent_executor.invoke method starts the process. It takes a dictionary containing the user’s input ("input": "Who is the current CEO of Microsoft and what is their age squared?").
  3. Then, AgentExecutor manages the ReAct loop:
    1. It feeds the input to the agent pipeline. 2. The agent (LLM and parser) decides on an action (for example, using a search tool to find the CEO’s name). 3. The AgentExecutor executes the action (calls the search tool). 4. It passes the result back to the agent as an “ Observation.” 5. This process repeats until the agent decides it has enough information to produce a final answer.

This example demonstrates the basic structure of a ReAct agent built with LCEL. It showcases how you can define a clear, modular pipeline for complex reasoning tasks by combining prompts, language models, parsers, and external tools. This approach promotes code readability, maintainability, and flexibility in designing intelligent agents. This particular example asks who the current CEO of Microsoft is and then what their age is squared, demonstrating simple multi-turn reasoning from name recall to arithmetic calculation.

The ReAct framework, with its ability to integrate reasoning and acting, is highly applicable in various task completion and problem-solving scenarios:

  • Question-Answering (QA) with external knowledge: ReAct can be used to create QA systems that can access and reason about external knowledge sources, such as Wikipedia or a search engine, to provide more accurate and up-to-date answers
  • Web navigation and interaction: ReAct agents can navigate websites, interact with web elements, and gather information, enabling tasks such as automated web research, data scraping, and online shopping assistance
  • Software application control: By integrating with APIs and tools, ReAct agents can control software applications, automate workflows, and perform complex tasks that require interacting with multiple systems
  • Robotics and physical world interaction: While LLMs primarily operate in the textual domain, ReAct principles can be extended to controlling robots or other physical systems, where actions involve physical movements or interactions with the real world
  • Multi-step problem solving: ReAct is well-suited for tasks that require breaking down a complex problem into smaller steps, reasoning about each step, taking actions, and using the observations to inform subsequent steps

Evaluating ReAct agents involves assessing both the quality of the reasoning and the effectiveness of the actions taken. The following metrics can be used:

  • Success rate: The percentage of tasks successfully completed by the agent
  • Efficiency: The number of steps or the amount of time taken to complete a task
  • Reasoning accuracy: The correctness and relevance of the LLM’s reasoning traces
  • Action relevance: The appropriateness of the actions chosen by the agent
  • Observation utilization: How effectively the agent incorporates observations into its subsequent reasoning and actions
  • Error analysis: Identifying common failure modes or weaknesses in the agent’s performance

Let’s consider some evaluation techniques that can be used:

  • Human evaluation: Having human experts evaluate the agent’s reasoning, actions, and final outputs
  • Automated metrics: Using automated scripts or LLMs to assess specific aspects of the agent’s performance, such as the correctness of answers or the relevance of actions
  • Benchmarking: Comparing the agent’s performance against predefined benchmarks or other agents on standardized tasks
  • Ablation studies: Systematically removing or modifying components of the ReAct framework (for example, removing the reasoning steps) to understand their contribution to overall performance

Safety, control, and ethical considerations

Section titled “Safety, control, and ethical considerations”

ReAct systems, especially when integrated with external tools, raise several safety, control, and ethical concerns:

  • Unpredictable behavior: The combination of LLM reasoning and external tool use can lead to unpredictable or unintended behavior
  • Safety of actions: Actions taken by the agent may have real-world consequences, especially if the agent is connected to systems that can affect the physical world
  • Bias and fairness: ReAct agents may inherit and amplify biases present in the training data of the LLM or the external tools they use
  • Misuse potential: Malicious actors could potentially use ReAct agents for harmful purposes, such as generating misinformation or automating attacks
  • Accountability: Determining responsibility for the actions and decisions of a ReAct agent can be challenging due to the non-deterministic nature of the underlying LLM models

The following are some mitigation strategies for these issues:

  • Sandboxing: Running ReAct agents in isolated environments to limit their potential impact
  • Human oversight: Incorporating human review and approval into the ReAct process, especially for critical decisions or actions
  • Safety rules and constraints: Implementing rules and constraints to prevent the agent from taking harmful or unethical actions
  • Monitoring and auditing: Continuously monitoring the agent’s behavior and maintaining logs for auditing purposes
  • Transparency and explainability: Designing ReAct agents that can explain their reasoning and decision-making process to improve understanding and trust

While ReAct is a powerful framework, it has certain limitations:

  • Dependency on external tools: ReAct’s effectiveness is partly dependent on the capabilities and reliability of the external tools it uses
  • Error propagation: Errors in tool use or interpretation of observations can propagate through the reasoning process, leading to incorrect conclusions or actions
  • Token limitations: The iterative nature of ReAct can lead to long sequences of text, potentially exceeding the token limits of some LLMs
  • Computational cost: Multiple rounds of reasoning, action, and observation can be computationally expensive, especially when using LLMs or complex tools
  • Prompt engineering challenges: Designing effective ReAct prompts that properly guide the LLM’s reasoning and action selection can be challenging and may require experimentation

Figure 22*.1* shows the limitations of ReAct pattern:

Figure 22.1 – Limitations of the ReAct pattern

However, by combining the power of LLMs with the ability to take actions and incorporate external information, ReAct provides new possibilities for creating more capable and versatile AI systems:

  • Improved tool integration: Developing more seamless and robust methods for integrating LLMs with external tools
  • Enhanced reasoning capabilities: Combining ReAct with other advanced reasoning techniques, such as ToT, to handle more complex scenarios
  • Learning from experience: Enabling ReAct agents to learn from their past interactions and improve their performance over time
  • Multi-agent ReAct: Exploring scenarios where multiple ReAct agents collaborate or compete to solve problems
  • Real-world deployment: Moving beyond simulated environments and deploying ReAct agents in real-world applications with the appropriate safety and control mechanisms

In this chapter, you learned about the ReAct framework, a powerful technique for prompting your LLMs to not only reason through complex scenarios but also plan and simulate the execution of actions, similar to how humans operate in the real world.

The ReAct framework represents a significant advancement in the development of intelligent agents that can reason, plan, and interact with their environment. ReAct can also be considered a precursor to more advanced frameworks such as Reasoning WithOut Observation (ReWOO), something we’ll explore in the next chapter.