Reasoning WithOut Observation
local graph
Chapter 22 — Reasoning WithOut Observation
Section titled “Chapter 22 — Reasoning WithOut Observation”Reasoning WithOut Observation (ReWOO), proposed by Xu et al. (https://arxiv.org/abs/2305.18323), is a framework that combines a multi-step planner and variable substitution for effective tool use. It aims to improve upon ReAct-style agents by reducing token consumption and execution time by generating the full chain of tool usage in a single pass, thus minimizing redundant LLM calls. It also aims to simplify the fine-tuning process by enabling fine-tuning without actually invoking tools as planning data doesn’t depend on tool outputs (in theory).
ReAct operates through a cyclical “think-act-observe” pattern, where an AI engages in reasoning, performs an action, examines the resulting feedback, and then adjusts its subsequent actions accordingly, facilitating a dynamic and responsive problem-solving strategy. In contrast, ReWOO emphasizes comprehensive upfront planning, generating a complete sequence of actions before any execution occurs, thereby minimizing the necessity for continuous observation and feedback. This distinction allows ReWOO to pursue greater efficiency by reducing token consumption and computational costs, shifting from ReAct’s iterative feedback loop to a more streamlined “plan-act” methodology.
So, ReWOO refers to an LLM’s ability to make inferences, predictions, or decisions about scenarios it has not directly observed or been trained on. ReWOO enhances this by incorporating external tool use into the reasoning process.
ReWOO’s ability to plan and reason without direct observation makes it suitable for complex planning and decision-making tasks:
- Strategic planning: As mentioned, ReWOO can generate strategic plans based on hypothetical situations, goals, and constraints
- Scenario analysis: ReWOO can explore multiple potential outcomes of a given scenario, considering various factors and uncertainties
- Resource allocation: By planning tool use and reasoning about their results, ReWOO can optimize resource allocation in complex environments
- Risk assessment: ReWOO can help assess potential risks and develop mitigation strategies by simulating different scenarios and their consequences
In this chapter, we’ll be covering the following topics:
- Implementing ReWOO with LangGraph
- Advantages of ReWOO
- Evaluating quality and ethical considerations
- Future directions
Implementing ReWOO with LangGraph
Section titled “Implementing ReWOO with LangGraph”LangGraph is an open source framework designed for building stateful, multi-agent applications using LLMs. It extends the capabilities of the LangChain ecosystem by introducing a directed graph model, where nodes represent functions (including LLM invocations) and edges represent transitions between states based on logic, conditions, or memory. Unlike traditional sequential chains, LangGraph allows complex workflows involving conditional branching, loops, memory passing, and asynchronous agent coordination. LangGraph is particularly useful for implementing systems where interactions are dynamic, iterative, and dependent on state changes. This includes multi-agent collaboration, decision trees, retrieval-augmented generation with control flow, and autonomous agents that need to revisit prior steps or loop through subtasks until certain goals are met.
LangGraph leverages concepts from graph theory and automata, representing execution flows as state machines or directed acyclic graphs (or cyclic graphs when loops are needed). Developers define a graph with nodes (functions or tools), edges (state transitions), and conditions (logic for routing). The runtime engine then executes the graph in response to inputs, updating the state at each step.
LangGraph supports both synchronous and asynchronous execution, and it integrates with LangChain’s components, such as tools, memory, and agents. It also supports streaming responses, fine-grained control over state, and multi-modal inputs/outputs, making it suitable for production-level applications.
In practice, LangGraph is used to build agentic systems where different agents interact, coordinate, and share memory, while still following a well-defined computational graph. This makes it different from naive agent loops or unstructured LLM orchestration methods.
LangGraph is available at https://github.com/langchain-ai/langgraph and supports Python-based implementation, with core dependencies on LangChain and state machine execution frameworks.
The ReWOO architecture consists of three modules:
- Planner: Generates a high-level plan to solve the problem, including identifying which tools to use and their arguments, potentially using variable substitution to represent dependencies between steps. Variable substitution in AI planning, particularly within systems such as ReWOO, enables the creation of flexible and efficient plans by employing placeholders to represent values that are determined during execution. This technique allows the AI to define dependencies between steps, such as using the output of a search tool as the input for a price extraction tool, without needing to know the specific values in advance. By using variables such as
search_resultorprice, the AI can construct a clear blueprint of the task, deferring the resolution of dynamic information until it becomes available, thereby streamlining the planning process and avoiding unnecessary computations. - Worker: Executes the tool with the provided arguments, potentially using variable substitution from previous steps.
- Solver: Generates the final answer based on the tool observations and the plan.
This architecture may seem a little abstract initially. Let’s implement ReWOO using LangGraph. We’ll use a Tavily search engine as an example tool:
- Install the necessary packages and set
Tavily is a search engine designed specifically for AI agents. It’s built to provide accurate and reliable information retrieval, tailored to the needs of AI systems performing complex tasks (see https://tavily.com/). The following script sets environment variables for API keys if they haven’t been defined yet:# %pip install -U langgraph langchain_community langchain_openai tavily-pythonimport getpassimport osdef _set_if_undefined(var: str):if not os.environ.get(var):os.environ[var] = getpass.getpass(f"{var}=")_set_if_undefined("TAVILY_API_KEY")_set_if_undefined("OPENAI_API_KEY")
- Next, define the graph state. To do so, define the state dictionary so that it can hold the task, plan, steps, results, and
from typing import Listfrom typing_extensions import TypedDictclass ReWOO(TypedDict):task: strplan_string: strsteps: Listresults: dictresult: str
- Create the planner prompt
from langchain_openai import ChatOpenAImodel = ChatOpenAI(model="gpt-4o")prompt = """For the following task, create a series of plans that can solve the problem step-by-step. For each plan, specify which external tool and its corresponding input should be used to gather evidence. You can store the evidence in a variable #E (e.g., #E1, #E2, #E3, etc.) that can be referenced by subsequent tools. Note that all the variables are independent, so make sure to include all necessary information in each tool input.Tools can be one of the following:Google[input]: A search engine worker that retrieves results from Google. Use this when you need concise answers or information about a specific topic. The input should be a search query.LLM[input]: A pretrained Large Language Model (like me). Use this when you need to leverage general world knowledge, common sense, or perform complex reasoning. Prioritize this tool when you are confident in solving the problem without external assistance. The input can be any instruction or question.Calculator[input]: A tool that can perform mathematical calculations. Use this when you need to perform arithmetic operations. The input should be a valid mathematical expression.WolframAlpha[input]: A computational knowledge engine. Use this when you need to solve equations, perform symbolic calculations, or get data-driven answers. The input should be a query in Wolfram Language or natural language related to a math or science problem.For example,Task: Alice, Bob, and Carol earned a total of $540 from their part-time jobs last week. Alice earned y dollars. Bob earned $20 more than three times what Alice earned, and Carol earned $15 more than Bob. How much money did Carol earn?Plan: Given Alice earned y dollars, translate the problem into algebraic expressions and solve with Wolfram Alpha.#E1 = WolframAlpha[Solve y + (3y + 20) + ((3y + 20) + 15) = 540]Plan: Find out the amount of money Alice earned.#E2 = LLM[What is y, given #E1]Plan: Calculate the amount of money Carol earned.#E3 = Calculator[((3 * #E2) + 20) + 15]Begin!Describe your plans with rich details. Each Plan should be followed by only one #E.Task: {task}"""
- Create a LangGraph node for
import refrom langchain_core.prompts import ChatPromptTemplateregex_pattern = (r"Plan:\s*(.+)\s*(#E\d+)\s*=\s*(\w+)\s*"r"\[([^\]]+)\]")prompt_template = ChatPromptTemplate.from_messages([("user", prompt)])planner = prompt_template | modeldef get_plan(state: ReWOO):task = state["task"]result = planner.invoke({"task": task})matches = re.findall(regex_pattern, result.content)return {"steps": matches, "plan_string": result.content}
- Instantiate the search engine and define the tool
from langchain_community.tools.tavily_search import TavilySearchResultssearch = TavilySearchResults()def _get_current_task(state: ReWOO):if "results" not in state or state["results"] is None:return 1if len(state["results"]) == len(state["steps"]):return Noneelse:return len(state["results"]) + 1def tool_execution(state: ReWOO):_step = _get_current_task(state)_, step_name, tool, tool_input = state["steps"][_step - 1]_results = (state["results"] or {}) if "results" in state else {}for k, v in _results.items():tool_input = tool_input.replace(k, v)if tool == "Google":result = search.invoke(tool_input)elif tool == "LLM":result = model.invoke(tool_input)else:raise ValueError_results[step_name] = str(result)return {"results": _results}
- Create the solver prompt
solve_prompt = """Solve the following task or problem. To solve the problem, we have made step-by-step Plan and \retrieved corresponding Evidence to each Plan. Use them with caution since long evidence might \contain irrelevant information.{plan}Now solve the question or task according to provided Evidence above. Respond with the answerdirectly with no extra words.Task: {task}Response:"""def solve(state: ReWOO):plan = ""for _plan, step_name, tool, tool_input in state["steps"]:_results = ((state["results"] or {}) if "results" in state else {})for k, v in _results.items():tool_input = tool_input.replace(k, v)step_name = step_name.replace(k, v)plan += (f"Plan: {_plan}\n"f"{step_name} = {tool}[{tool_input}]\n")prompt = solve_prompt.format(plan=plan, task=state["task"])result = model.invoke(prompt)return {"result": result.content}
- Build the LangGraph workflow:
The provided code establishes an AI workflow usingdef _route(state):_step = _get_current_task(state)if _step is None:return "solve"else:return "tool"from langgraph.graph import END, StateGraph, STARTgraph = StateGraph(ReWOO)graph.add_node("plan", get_plan)graph.add_node("tool", tool_execution)graph.add_node("solve", solve)graph.add_edge("plan", "tool")graph.add_edge("solve", END)graph.add_conditional_edges("tool", _route)graph.add_edge(START, "plan")app = graph.compile()
StateGraph, a data structure for managing multi-step processes. The_routefunction acts as a conditional director, determining the next step based on the current state. It checks if further tool-based actions are required; if not, it routes the process to the"solve"node for final answer generation. Otherwise, it directs it to the"tool"node for tool execution. Here,StateGraphdefines the execution flow: starting with"plan"for strategy creation, proceeding to"tool"for external tool usage, and finally, to"solve"for result generation, culminating in theENDstate. The_routefunction’s conditional logic within the"tool"node is key, allowing dynamic routing based on the task’s progression.StateGraphis crucial for structured workflow management, enabling conditional branching for adaptive AI behavior, especially in tool-dependent tasks. It ensures logical action sequencing, improving robustness and clarity, and facilitating ReWOO’s planned execution. Compiling the graph into an"app"makes it executable. - Let’s look at an example use case, and test the
task = "what is the exact hometown of the 2024 mens australian open winner"for s in app.stream({"task": task}):print(s)print("---")
The preceding code provides a simple implementation of the ReWOO framework using LangGraph. It defines the state, planner, executor, and solver modules, and connects them into a graph. This example usage demonstrates how to run the agent on a sample task.
Advantages of ReWOO
Section titled “Advantages of ReWOO”ReWOO offers several advantages over traditional ReAct-style agents:
- Reduced token consumption and execution time: By generating the entire plan in a single pass and using variable substitution, ReWOO minimizes redundant LLM calls and context passing
- Simplified fine-tuning: The independence of the planning data from tool outputs (in theory) allows for fine-tuning without the need to invoke the tools
- Efficient LLM calls: The LLM tool receives less of the prompt, making calls more token-efficient compared to the ReACT paradigm
Evaluating quality and ethical considerations
Section titled “Evaluating quality and ethical considerations”Evaluating the quality of ReWOO’s reasoning can be challenging as it often deals with hypothetical scenarios. Possible approaches include the following:
- Human evaluation: Using human experts to assess the coherence, relevance, and completeness of the generated plans and reasoning
- Comparison with ground truth: For scenarios with known outcomes, ReWOO’s predictions can be compared with actual results
- Benchmarking: Using standardized test sets designed to evaluate abstract reasoning and planning capabilities
It is also crucial to keep ethical considerations in mind while doing any evaluation:
- Bias amplification: ReWOO might inherit and amplify biases present in the training data of the underlying LLM
- Misuse potential: The ability to generate plans and reason about hypothetical scenarios could be misused for malicious purposes
- Overreliance: Users might place too much trust in ReWOO’s outputs without considering their speculative nature
Future directions
Section titled “Future directions”As research progresses, ReWOO and related techniques will likely play an increasingly important role in the development of more capable and versatile AI systems. The following are some promising directions for ReWOO:
- Human-in-the-loop systems: Integrating human oversight and feedback into the ReWOO framework to improve accuracy and address ethical concerns
- Improved planning algorithms: Developing more sophisticated planning algorithms that can handle more complex scenarios and larger search spaces
- Enhanced tool integration: Seamlessly integrating a wider range of tools, including specialized APIs and knowledge bases
- Multi-agent collaboration: Enabling multiple ReWOO agents to collaborate on complex tasks, potentially leading to more robust and diverse solutions
- Meta-learning: Applying meta-learning techniques to improve the agent’s ability to generalize and adapt to new scenarios over time
Summary
Section titled “Summary”This chapter delved into ReWOO, a framework designed to empower LLMs with the ability to reason about hypothetical situations and leverage external tools effectively. ReWOO utilizes a multi-step planner coupled with variable substitution, enabling it to generate comprehensive action plans in a single pass, thereby minimizing token consumption and execution time compared to the iterative “think-act-observe” cycle of ReAct agents. This chapter demonstrated the implementation of ReWOO using LangGraph, highlighting its architecture, components (planner, worker, solver), and advantages, such as simplified fine-tuning and efficient LLM calls.
Beyond simply reiterating the framework’s mechanics, this chapter emphasized ReWOO’s potential for strategic planning, scenario analysis, resource allocation, and risk assessment. However, it also touched upon the critical ethical considerations surrounding ReWOO, including the potential for bias amplification, misuse, and overreliance on its outputs. This chapter concluded with a view toward the future, discussing the need for human-in-the-loop systems, improved planning algorithms, enhanced tool integration, multi-agent collaboration, and the application of meta-learning techniques to further refine ReWOO’s capabilities and ensure responsible application in real-world scenarios.
In the next chapter, we will discuss techniques that enable LLMs to engage in self-reflection and iterative improvement.
Get This Book's PDF Version and Exclusive Extras
|