What you’ll build
An agent that:- Decides when to use tools
- Calls multiple tools as needed
- Processes tool results
- Provides informed responses
Prerequisites
Install required packages:Tutorial
1
Define state and tools
Create the agent state and define tools for the agent to use.
2
Create the agent node
Build the agent that decides which tools to call.The agent:
- Receives conversation history
- Decides if tools are needed
- Returns either a tool call or final answer
3
Create the tool execution node
Build a node that executes tool calls.The ToolNode:
- Automatically executes tool calls
- Handles multiple tools
- Returns results as messages
4
Add routing logic
Create a function to decide whether to call tools or finish.This router:
- Checks for tool calls in the last message
- Routes to tool execution or completion
5
Build the graph
Assemble the agent with conditional routing.The flow:
- START → agent
- agent → tools (if tool calls) OR END (if done)
- tools → agent (for next decision)
6
Run the agent
Test the agent with different queries.
7
Complete example
Here’s the full working code:Save as
tool_agent.py and run:Expected output
When testing the agent:Key concepts
- Tool Binding:
model.bind_tools(tools)enables the model to call tools - Tool Calls: Model returns structured tool call requests
- ToolNode: Automatically executes tool calls and formats results
- Conditional Routing: Routes based on whether tools are needed
- Agent Loop: Agent → Tools → Agent until task is complete
Advanced features
Add tool error handling
Add tool error handling
Add streaming
Add streaming
Add custom tools with APIs
Add custom tools with APIs
Next steps
ReAct Agent
Build an agent that reasons about tool usage
Multi-Agent
Coordinate multiple specialized agents
Tool calling is a fundamental capability for building useful agents. The agent can now interact with the external world through tools.