Give the Graph a Tool
A model on its own can only write. Give it tools and it can ask for work to be done: look something up, compute a value, read a record. In a graph, that becomes a loop between two nodes: a model node that decides which tool it needs, and a tool node that runs it and hands the result back, round and round until the model has what it needs to answer. Knowing what ends that loop, and what stops it when it would not end, is what makes such a graph safe to run.
A tool is a typed function with a description
A model never runs your code. What it receives is a short written definition of each tool, and from that definition alone it decides whether a tool fits the request and what to pass to it. So a tool needs three things the model can read: a name to call it by, a description that says when it is useful, and a schema of its arguments, which says which arguments exist and what type each one has.
LangChain builds all three from an ordinary Python function with the @tool decorator. The function name becomes the tool name, the docstring becomes the description, and the type hints become the argument schema.
from langchain.tools import tool
@tool
def get_weather(city: str) -> str:
"""Return the current weather for a city.
Use it when the user asks about weather or temperature."""
return f"It is sunny and 21 degrees in {city}."
print(get_weather.name) # get_weather
print(get_weather.description) # Return the current weather for a city. ...| Part of the tool | Taken from | What the model uses it for |
|---|---|---|
| Name | the function name, or the first argument of @tool("...") | to say which tool it wants |
| Description | the docstring, or description="..." | to decide when the tool fits |
| Argument schema | the type hints, or args_schema=... | to fill in valid arguments |
The type hints are required, because without them there is no schema. For arguments that need more than a simple type, args_schema accepts a Pydantic model or a JSON schema.
The description deserves the same care as documentation you write for a colleague. It is the only thing the model chooses by, so a vague one leads to a tool called at the wrong moment, or never called at all.
Two smaller rules: tool names read best in snake_case, and two parameter names, config and runtime, are reserved and cannot be used as tool arguments.
True or false?
The model reads the body of the function to decide whether a tool fits the request.
False. The model only sees the name, the description and the argument schema. The body runs later, in your code, and the model never sees it.
Removing the type hint from an argument breaks the schema the model receives.
True. The type hints are what the argument schema is built from, so the decorator requires them.
Binding tools to a chat model
A tool definition is useless until the model receives it with every request. bind_tools attaches the definitions to a chat model and returns a new model object that sends them along each time it is invoked. The original model is left unchanged.
model_with_tools = model.bind_tools([get_weather])
reply = model_with_tools.invoke("What is the weather in Lisbon?")
print(reply.tool_calls)The reply is still an AI message, but it can now take one of two shapes. When the model can answer directly, the message carries text and its tool_calls list is empty. When it wants a tool, the message carries one or more tool calls instead: requests to run a tool with given arguments. Each tool call is a small dictionary.
| Key | Example | Meaning |
|---|---|---|
| name | get_weather | which bound tool to run |
| args | {"city": "Lisbon"} | the arguments, shaped by the schema |
| id | call_1 | a label the result must quote back |
Two details shape everything that follows. First, a tool call is only a request: nothing has run yet, and your code decides what to do with it. Second, one reply can hold several tool calls at once, for example the weather in two cities, because most models that support tool calling may request several calls in parallel by default. Some providers let you switch this off when you bind the tools.
By default the model chooses freely whether to call a tool and which one. A tool_choice argument can force a call, but then the model calls a tool even when none of them fits the request, so free choice is the usual setting for a loop.
True or false?
After bind_tools, the chat model runs get_weather itself whenever it decides to.
False. Binding only sends the definitions. The model returns a request in tool_calls, and your code (or a tool node) runs the function.
A single AI message can ask for the same tool twice with different arguments.
True. One reply may carry several tool calls, each with its own id, so each one needs its own answer.
The tool node runs every call
Something has to turn those requests into results. In a graph, that is the job of a tool node: a node that reads the last message in the state, runs every tool call it carries, and returns one tool message per call.
A tool message holds the result as text, together with a tool_call_id. That field must equal the id of the call it answers. On its next turn, the model uses the id to match each result to its request, which matters as soon as one reply holds several calls.
Written by hand, a tool node is a short loop. It looks each tool up by name, calls it with the arguments the model chose, and wraps every result in a tool message.
from langchain.messages import ToolMessage
from langgraph.graph import MessagesState
tools = [get_weather]
tools_by_name = {t.name: t for t in tools}
def tool_node(state: MessagesState):
results = []
for call in state["messages"][-1].tool_calls:
tool = tools_by_name[call["name"]]
observation = tool.invoke(call["args"])
results.append(
ToolMessage(content=observation, tool_call_id=call["id"])
)
return {"messages": results}MessagesState is a ready-made state with a single messages key whose reducer appends new messages, so the returned tool messages land after the AI message that asked for them.
LangGraph also ships this node ready-made: ToolNode, imported from langgraph.prebuilt. ToolNode([get_weather]) does the same work and adds a few things a hand-written loop leaves out: it runs several calls in parallel, and it can pass graph data to a tool that declares it needs some.
ToolNode also handles errors, and its default treats two kinds differently. When the model supplies invalid arguments, the error goes back to the model as a message, so it can try again. When the tool itself raises an error while it runs, that error is raised again and stops the run, unless the handle_tool_errors option says otherwise.
True or false?
If the last AI message carries three tool calls, the tool node should return three tool messages.
True. Each call gets its own answer, linked by tool_call_id, so the model can match every result to its request.
By default ToolNode catches every exception a tool raises and hands it to the model as text.
False. By default it only turns invalid-argument errors into a message. An exception raised inside the tool is raised again unless handle_tool_errors is set.
The loop and what ends it
The two nodes now need wiring. After the tool node has run, the model has to see the results, so a plain edge leads from the tool node back to the model node. An edge back to an earlier node makes a cycle: the graph can visit the same nodes many times in one run.
A loop needs a way out, and here the model provides it. After every model turn, a conditional edge looks at the newest message. If it carries tool calls, the run goes to the tool node. If it carries none, the model has answered, and the run goes to the end. The stop condition is therefore the model asking for no tool.
- START
- model calls the chat model
- tools runs the tool calls
- END
- START to model
- model to tools: has tool calls
- tools to model: results
- model to END: no tool calls
from langgraph.graph import MessagesState, StateGraph, START, END
def call_model(state: MessagesState):
return {"messages": [model_with_tools.invoke(state["messages"])]}
def should_continue(state: MessagesState):
if state["messages"][-1].tool_calls:
return "tools"
return END
builder = StateGraph(MessagesState)
builder.add_node("model", call_model)
builder.add_node("tools", tool_node)
builder.add_edge(START, "model")
builder.add_conditional_edges("model", should_continue, ["tools", END])
builder.add_edge("tools", "model")
graph = builder.compile()One run then reads as a conversation between the two nodes, with every message added to the state on the way. The model asks, the tools answer, and the model asks again or answers.
- Caller
- model node
- tool node
- Caller to model node: human message
- model node to tool node: AI message, 2 tool calls
- tool node to model node: 2 tool messages
- model node to Caller: AI message, text only
The routing function above is common enough that LangGraph provides it as tools_condition, also in langgraph.prebuilt. It returns the literal string "tools" when the last AI message has tool calls and the end otherwise, so it only fits when the tool node is named tools (the default name of ToolNode), or when you give the conditional edge a map from its values to your node names.
True or false?
In this graph, the loop ends when the tool node has no more tools to run.
False. The tool node always leads back to the model. The loop ends at the conditional edge after the model, when its reply carries no tool calls.
Without the edge from the tool node back to the model, the model would never see the tool results.
True. The results sit in the state, but only another model turn reads them and turns them into an answer.
Workflows, agents, and both in one graph
A graph without a loop has paths that code fixes in advance. Even with a branch, the code chooses among a few known routes, and every run takes one of them. A graph like that is a workflow: its steps and their order are decided when you write it.
The loop is different. How many laps it takes, which tools it calls and in what order are decided by the model during the run. That is what makes it an agent: a model performing actions with tools in a feedback loop, choosing its own steps. You still decide which tools exist and how the model is instructed; the model decides how to use them.
Each style has its place. A workflow is predictable and easy to test, which suits a task whose steps are known. An agent copes with requests whose steps cannot be known in advance, at the price of less predictable paths. A graph does not force a choice, because the loop is just two nodes and three edges: it can sit inside a larger graph whose other parts stay fixed.
- START
- check input fixed step
- model
- tools
- format reply fixed step
- END
- START to check input
- check input to model
- model to tools: tool calls
- tools to model
- model to format reply: no tool calls
- format reply to END
Here the first and last steps run on every request in the same order, while the middle is an agent. Fixed steps around a loop are a common way to keep the parts that must always happen (validating input, shaping the output) out of the model's hands.
True or false?
A graph with a conditional edge is an agent, because the path is chosen at run time.
False. A branch among known routes is still a workflow. It becomes an agent when a model chooses its own steps, such as which tools to call and how often.
One graph can hold fixed workflow steps and an agent loop side by side.
True. The loop is ordinary nodes and edges, so fixed nodes can run before and after it in the same graph.
The recursion limit stops a loop that will not stop
The stop condition depends on the model. If it keeps asking for tools, for example because a tool keeps returning something unhelpful, the loop goes round again and again, and with a live model every lap costs a request. LangGraph guards against this with the recursion limit: a cap on how many steps one run may take.
A step here is one round of the graph's execution, called a super-step. Nodes that run one after another take separate steps, and nodes that run at the same time share one. In the model and tool loop, each node runs alone, so every lap uses two steps: one for the model and one for the tools. The limit counts these steps, not model calls or tool calls.
The limit is set per run, as the top-level key recursion_limit in the run's config (not inside configurable). When a run reaches the limit before it has finished, LangGraph stops the graph and raises GraphRecursionError, which the caller can catch like any other exception. A run that needs exactly as many steps as the limit is stopped too, so the limit must be at least one more than the steps a run takes.
from langchain.messages import HumanMessage
from langgraph.errors import GraphRecursionError
try:
result = graph.invoke(
{"messages": [HumanMessage("What is the weather in Lisbon?")]},
{"recursion_limit": 6},
)
print(result["messages"][-1].content)
except GraphRecursionError:
print("Stopped: the run took too many steps without an answer.")The default limit in current LangGraph is very high, so it will not end a runaway loop quickly on its own. Choose a limit that fits the task: enough laps for the most tools a reasonable answer needs, plus a margin. When the error appears in a graph that should finish in a few steps, it usually means a cycle with a stop condition that is never met. For a graph that should end gracefully instead of failing, LangGraph also offers a state key that tells a routing function how many steps remain, so the run can divert to a final node before the limit.
True or false?
With a recursion limit of 6, the model can be called at most 6 times in the model and tool loop.
False. The limit counts steps of the whole graph. Each lap is a model step and a tool step, so far fewer than 6 model calls fit.
The recursion limit is passed with each run, so two runs of the same compiled graph can use different limits.
True. It is a key of the config given to invoke or stream, not part of the graph built at compile time.
Ready-made agents and when to write the graph yourself
A model node, a tool node, a conditional edge on tool calls and an edge back is the shape of almost every tool-calling agent, so LangChain offers it built for you. create_agent, from langchain.agents, takes a model, a list of tools and a system prompt, and returns a compiled LangGraph graph with this same loop inside: a node named model and a tool node built on ToolNode. It is invoked, streamed and limited like any graph you compile yourself. Older material shows create_react_agent from langgraph.prebuilt for this; it is deprecated in favour of create_agent.
The ready-made agent is the quicker choice when a standard loop is all a task needs. Writing the graph by hand pays off when you want control the standard loop does not give you: fixed steps before or after the loop, custom routing such as sending some tool results to a different node, your own handling of tool errors, or a state with more keys than the messages. Because the two are the same structure, starting with one and moving to the other later changes little about how the loop behaves.
| What the task needs | A good fit |
|---|---|
| a model, some tools, a loop until it answers | create_agent |
| fixed steps before or after the loop | a hand-written graph |
| routing that depends on more than tool calls | a hand-written graph |
| a state with keys beyond the messages, read by several nodes | a hand-written graph |
True or false?
create_agent returns a compiled LangGraph graph, so a recursion limit can be set on its runs too.
True. It builds the same model and tool loop on the LangGraph runtime, and its runs take the same config.
A ready-made agent works in a different way from a hand-written model and tool loop.
False. It is the same loop of a model node and a tool node, assembled for you. Writing it by hand changes how much you control, not how it works.