Lesson 5 of 11 · Agents
A Tool-Calling Agent
Build a tool-calling agent in LangGraph: MessagesState, a model node with bound tools, ToolNode, tools_condition, error handling, recursion limits and guards.
- 7 min read
- Advanced
- Reviewed
- Build the agent loop as a graph: model node, tool node and a conditional edge
- Use ToolNode and tools_condition from LangGraph's prebuilt components
- Handle tool errors so the model can recover
- Add custom control, such as a limit on tool rounds
- Choose between a hand-built graph and create_agent
The agent loop as a graph
Every tool-calling agent runs the same loop: the model replies; if the reply contains tool calls, run them and send the results back; otherwise, finish. In LangGraph, that loop is a graph with two nodes and one conditional edge:
- agent: calls the model with the conversation so far.
- tools: runs every tool call in the model's last message.
- conditional edge after agent: tool calls → tools; no tool calls → end. And tools always goes back to agent.
Building it
from langchain.chat_models import init_chat_model
from langchain_core.messages import SystemMessage
from langchain_core.tools import tool
from langgraph.graph import START, MessagesState, StateGraph
from langgraph.prebuilt import ToolNode, tools_condition
@tool
def get_weather(city: str) -> str:
"""Get today's weather for a city."""
return {"lisbon": "24°C, sunny", "porto": "17°C, light rain until 2pm"}.get(city.lower(), "no data")
@tool
def get_bike_routes(city: str) -> list[str]:
"""List recommended bike routes in a city, easiest first."""
return {"porto": ["Riverside path to Foz (8 km, flat)", "Park loop (5 km)"]}.get(city.lower(), [])
tools = [get_weather, get_bike_routes]
model = init_chat_model("anthropic:MODEL_NAME").bind_tools(tools)
SYSTEM = SystemMessage("You are a cycling assistant. Use the tools; never guess the weather.")
def agent(state: MessagesState) -> dict:
return {"messages": [model.invoke([SYSTEM] + state["messages"])]}
builder = StateGraph(MessagesState)
builder.add_node("agent", agent)
builder.add_node("tools", ToolNode(tools)) # runs every tool call in the last message
builder.add_edge(START, "agent")
builder.add_conditional_edges("agent", tools_condition) # tool calls -> "tools", otherwise end
builder.add_edge("tools", "agent") # results go back to the model
graph = builder.compile()
result = graph.invoke({"messages": [("user", "Is today good for cycling in Porto? Suggest a route.")]},
config={"recursion_limit": 12})
for m in result["messages"]:
print(f"{m.type:>5}: {m.content or [(c['name'], c['args']) for c in m.tool_calls]}")human: Is today good for cycling in Porto? Suggest a route.
ai: [('get_weather', {'city': 'Porto'}), ('get_bike_routes', {'city': 'Porto'})]
tool: 17°C, light rain until 2pm
tool: ["Riverside path to Foz (8 km, flat)", "Park loop (5 km)"]
ai: Yes, after 2pm: it's 17°C with light rain until then. Try the flat 8 km riverside path to Foz.The prebuilt pieces do the routine work:
ToolNode(tools)finds the tool calls in the last AI message, runs them (in parallel when there are several) and returns aToolMessagefor each.tools_conditionis the routing function:"tools"if the last message has tool calls, otherwise the end.MessagesStatewith itsadd_messagesreducer keeps the whole conversation, including tool calls and results.
The system prompt is added inside the agent node rather than stored in the state, so it's always first and never duplicated.
The loop in plain Python, with a guard
A hand-built graph makes it easy to add your own control. Here a stuck model keeps searching, and a guard stops it after three tool rounds:
# The agent graph in plain Python: agent -> (tool calls? -> tools -> agent) -> end,
# plus a guard that a custom graph makes easy: stop after too many tool rounds.
def scripted_model(messages):
"""A stuck model: it keeps searching with slightly different words and never answers."""
n = sum(1 for m in messages if m["role"] == "tool")
return {"role": "ai", "content": "", "tool_calls": [{"name": "search", "args": {"q": f"bike routes porto {n}"}}]}
def tools(message):
return [{"role": "tool", "content": f"3 results for {c['args']['q']!r}"} for c in message["tool_calls"]]
def tools_condition(state):
return "tools" if state["messages"][-1].get("tool_calls") else "END"
def run(question, max_tool_rounds=3):
state = {"messages": [{"role": "user", "content": question}], "tool_rounds": 0}
node = "agent"
while node != "END":
if node == "agent":
state["messages"].append(scripted_model(state["messages"]))
node = tools_condition(state)
if node == "tools" and state["tool_rounds"] >= max_tool_rounds: # the guard
state["messages"].pop() # drop the tool request we won't run: unanswered
# tool calls make the next model request invalid
state["messages"].append({"role": "ai", "content": "Sorry, I couldn't finish that. "
"I've passed your question to a colleague."})
node = "END"
elif node == "tools":
state["messages"] += tools(state["messages"][-1])
state["tool_rounds"] += 1
node = "agent"
return state
final = run("Suggest a bike route in Porto")
for m in final["messages"]:
print(f"{m['role']:>5}: {m['content'] or m['tool_calls'][0]['args']}")Notice the guard removes the last tool request before apologising. A conversation containing a tool call with no matching result is invalid for most model APIs, so the next request would fail.
When tools fail
By default, ToolNode only turns invalid-argument errors into messages; any other exception stops the graph. With handle_tool_errors=True, every exception becomes an error message the model can read and react to:
from langchain_core.messages import AIMessage
from langchain_core.tools import tool
from langgraph.graph import START, MessagesState, StateGraph
from langgraph.prebuilt import ToolNode
@tool
def get_order(order_id: str) -> str:
"""Look up an order by its ID."""
if not order_id.startswith("A-"):
raise ValueError(f"Order IDs start with 'A-', got {order_id!r}")
return f"Order {order_id}: shipped yesterday"
builder = StateGraph(MessagesState)
builder.add_node("tools", ToolNode([get_order], handle_tool_errors=True)) # errors become messages
builder.add_edge(START, "tools")
graph = builder.compile()
calls = AIMessage(content="", tool_calls=[
{"name": "get_order", "args": {"order_id": "A-881"}, "id": "c1"},
{"name": "get_order", "args": {"order_id": "881"}, "id": "c2"}, # a bad argument
])
for m in graph.invoke({"messages": [calls]})["messages"][1:]:
print(m.tool_call_id, "|", m.status, "|", m.content)c1 | success | Order A-881: shipped yesterday
c2 | error | Error: ValueError("Order IDs start with 'A-', got '881'")
Please fix your mistakes.The model sees what went wrong and can retry with A-881. Write error messages for the model: say what was wrong and what a correct value looks like.
Hand-built graph or create_agent?
create_agent from LangChain (see the LangChain course) builds this same loop for you, with middleware for limits, retries, approvals and summaries. LangGraph's older create_react_agent is deprecated in favour of it. Choose:
create_agentfor a standard tool-calling agent, adding middleware as needed.- A hand-built graph when the agent is one part of a larger flow, or you need extra nodes: a planning step before the loop, a validation step after it, approval before certain tools, or routing between several agents.
Common mistakes
Write tools_condition, the routing function that decides whether an agent graph runs tools or finishes.
def tools_condition(state):
# Return "tools" if the LAST message has a non-empty "tool_calls" list, otherwise "END".
# (Some messages have no "tool_calls" key at all.)
pass
print(tools_condition({"messages": [{"role": "user", "content": "Hi"},
{"role": "ai", "content": "", "tool_calls": [{"name": "search"}]}]}))
print(tools_condition({"messages": [{"role": "ai", "content": "Done!", "tool_calls": []}]}))
print(tools_condition({"messages": [{"role": "ai", "content": "Hello!"}]}))
In the agent graph, what does tools_condition decide?
Summary
- An agent is a graph: agent node, tools node, a conditional edge and an edge back.
ToolNoderuns tool calls;tools_conditionroutes to tools or the end;MessagesStatekeeps the conversation.- Use
handle_tool_errors=Trueso tool failures become messages the model can recover from. - Add guards and set a recursion limit; never leave tool calls without results.
- Use
create_agentfor standard agents and hand-built graphs for custom flows.
Next: checkpoints and persistence.
Finished reading? Tick it off to track your progress.