Objectives
- Implement the ReAct agent design loop.
- Bind custom tools to a ChatOpenAI model.
- Route queries dynamically using a
ToolNodeand 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
- Define the state schema using
add_messagesto append messages to history. - Create tools and bind them to the LLM.
- Define the LLM call node, the
should_continueconditional router, and theToolNodetool runner. - 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 usingadd_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
- Create two tools
@toolfordivide(a: float, b: float)andpower(base: float, exponent: float). - Bind the new tools list to the model.
- Set up the ReAct
StateGraphwith the agent node, the conditional routershould_continue, and the tool node. - Verify step-by-step tool execution.
Solution
Solution
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