Skip to main content
In this section, we will build a ReAct (Reasoning and Acting) agent that utilizes mathematical tools to solve multi-step calculations.

Objectives

  1. Implement the ReAct agent design loop.
  2. Bind custom tools to a ChatOpenAI model.
  3. Route queries dynamically using a ToolNode and conditional routing.

Agent III: ReAct Agent

Goal

Build a ReAct agent that binds arithmetic tools (add, subtract, multiply) and dynamically decides whether to execute a tool or finish.

Sample Input

Sample Output

Outputs performing addition first, then multiplication: 312.

Plan

  1. Define the state schema using add_messages to append messages to history.
  2. Create tools and bind them to the LLM.
  3. Define the LLM call node, the should_continue conditional router, and the ToolNode tool runner.
  4. Build the graph connecting START -> agent, agent -> conditional edge (tools or END), and tools -> agent.

Code Implementation

1. Define the State Schema

We define a state schema using add_messages annotation:

2. Define Custom Tools

We define three custom functions decorated with @tool and bind them to the model:

3. Define Nodes and Routing Logic

We write the model call node and the routing function:

4. Build and Compile the Graph

5. Invoke the Agent

We invoke the compiled app:

Exercise: Division and Power ReAct Agent âž—

Goal

Build a ReAct Agent that adds division (divide) and exponentiation (power) tools, and successfully handles mathematical queries requiring these functions.

Sample Input

Sample Output

Outputs performing division, then exponentiation, returning the final answer: 15625.0.

Plan

  1. Create two tools @tool for divide(a: float, b: float) and power(base: float, exponent: float).
  2. Bind the new tools list to the model.
  3. Set up the ReAct StateGraph with the agent node, the conditional router should_continue, and the tool node.
  4. Verify step-by-step tool execution.

Practice & Exercises

To reinforce what you’ve learned in this section, practice with the interactive notebook:

Practice & Exercises

Practice binding custom tools, routing conditional edges based on tool_calls, and handling multi-step reasoning.💻 VS Code | 🚀 Colab | 📥 Download