13  Tool-Calling

Until now the model, where there was one, chose a string: search, web, generate. Your graph did everything else — it knew which tools existed, wired each edge, and could force “always search the docs before answering.” That control has a price: every new capability is a new node, a new route, and a new branch in the agent’s prompt. Native tool-calling changes only the deciding half. The model emits the tool call itself, name and arguments; your code (or the framework’s) still dispatches it, runs it, appends the result, and decides whether to loop. The @tool and bind_tools that Chapter 7 told you to set aside arrive here, where a real LLM is doing the deciding.

In Chapter 7 your graph chose the route. In Chapter 12 the model chose it, from a fixed list, and your graph mapped the choice to a node. Here the model produces a tool name and arguments; your code — or the framework’s — still executes the call and hands the result back for the model to continue.

The two are not beginner and advanced versions of one thing. They trade control for reach, and the Gotcha after the hand-written loop shows what that trade costs on a real question.

13.1 What we’re building

The same doc-bot, the same two tools — search_docs over a small keyed knowledge base, web_search as the fallback — but a completely different control structure. There is no agent node writing a route now. There is a model that may emit a tool call, a tools step that runs whatever it emitted, and a single back-edge so the result returns to the model to keep going. The loop runs until the model stops asking for tools and just answers.

%%{init: {'securityLevel': 'loose', 'flowchart': {'diagramPadding': 24}, 'themeCSS': 'foreignObject{overflow:visible}span.bot{display:flex;justify-content:flex-start;align-items:flex-start;width:100%;height:0;overflow:visible;line-height:0}span.bot img{display:block!important;width:18px!important;height:18px!important;padding:2px;background:#fff;border-radius:50%;box-shadow:0 0 0 1px #999}span.bot.r img{margin:0;transform:translate(-24px,-24px)}span.bot.d{justify-content:center}span.bot.d img{margin-top:-50%;transform:translateY(-24px)}'}}%%
flowchart LR
    START(["START"]) --> model{"<span class='bot d'><img src='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiMzMzMiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48cGF0aCBkPSJNMTIgOFY0SDgiLz48cmVjdCB3aWR0aD0iMTYiIGhlaWdodD0iMTIiIHg9IjQiIHk9IjgiIHJ4PSIyIi8+PHBhdGggZD0iTTIgMTRoMiIvPjxwYXRoIGQ9Ik0yMCAxNGgyIi8+PHBhdGggZD0iTTE1IDEzdjIiLz48cGF0aCBkPSJNOSAxM3YyIi8+PC9zdmc+'/></span>model"}
    model -.->|has tool_calls| tools["tools"]
    model -.->|no tool_calls| END(["END"])
    tools --> model

Next to the diamond-in-the-middle picture from Chapter 7 the topology rhymes: something decides, tools run, control returns. The decider is no longer a node you wrote with an if / elif ladder or a prompt you spelled out; it is the model choosing off a menu.

13.2 Teaching the model what it can call: @tool + bind_tools

Before a model can call a tool it has to know the tool exists, what it’s for, and what arguments it takes. LangChain’s @tool decorator packages an ordinary Python function into that description:

from langchain_core.tools import tool


1@tool
2def search_docs(query: str) -> str:
    """Search the internal technical-documentation knowledge base. Use this
    whenever the user asks how to configure something, about an error message, or
3    how to do a technical task."""
    q = query.lower()
    hits: list[str] = []
    for topic, docs in KNOWLEDGE_BASE.items():
        if topic in q:
            hits.extend(docs)
    return "\n".join(hits) if hits else "No matching local documents."


@tool
def web_search(query: str) -> str:
    """Search the open web. Use this when the local docs come up empty, or the
    question is about something recent."""
    # PLACEHOLDER: not a real web search — a canned string so the loop has something
    # to run, and it stays a stub for the whole book.
    return f"[web] community thread about “{query}” (example result)"
1
Three parts of the function below become three parts of the tool’s schema, and the model reads all three.
2
The function name becomes the tool’s name; the type hint (query: str) becomes the argument schema, which is how the model knows to send a string called query.
3
The docstring becomes the tool’s description: the model’s primary instruction for whether and when to reach for it.

Print what LangChain extracted and you see what the model will be shown:

print("name       :", search_docs.name)
# .description keeps the docstring's newlines and indentation; collapse to one line
print("description:", " ".join(search_docs.description.split()))
print("args       :", search_docs.args)
name       : search_docs
description: Search the internal technical-documentation knowledge base. Use this whenever the user asks how to configure something, about an error message, or how to do a technical task.
args       : {'query': {'title': 'Query', 'type': 'string'}}

That docstring is not a comment for the next programmer — it is a prompt. This is the same lesson as Field(description=...) in Chapter 12: anything that lands in a schema the model reads is prompt, and deserves the care you’d give one. “Use this whenever the user asks how to configure something” is an instruction that steers the model’s choice; a lazy “searches docs” would tell it far less.

Now the model — the same local connection block from Chapter 12 that every model-backed Part II chapter opens with:

from langchain_openai import ChatOpenAI

llm = ChatOpenAI(
    base_url="http://localhost:1234/v1",  # your local server, not the OpenAI cloud
    api_key="lm-studio",                   # the local server ignores the key
    model="openai/gpt-oss-20b",            # gpt-oss on purpose here — see the Gotcha below
    temperature=0,                         # 0 = as reproducible as a real model gets
)

One of two deliberate exceptions to the book’s usual model (the other is Chapter 16): the rest of Part II runs on Qwen3.8 27B1 (Chapter 2), but this chapter uses gpt-oss-20b2. Its readiness to reach for a tool on its own judgment — as the Gotcha below shows — is what makes the give-up-control lesson concrete. A more literal model would dutifully search the local docs first and bury the point.

gpt-oss-20b Qwen3.8 27B
What it is OpenAI’s open-weight model, 21B mixture-of-experts (~3.6B active per token) Alibaba’s dense 27B hybrid model
How it is run here A reasoning model, thinking on A reasoning model with the thinking switched off (Chapter 10’s reasoning_effort="none")
With tools Reaches for the tool its judgment prefers Follows the instruction as written

Having decorated the functions, we bind_tools them onto the model:

llm_with_tools = llm.bind_tools([search_docs, web_search])

bind_tools does not give the model the power to run anything. It attaches the tools’ schemas to every request, so the model can now emit a tool call: a small structured object saying “call search_docs with query='...'.” Running the function is still your code’s job, and the next section does that running by hand so the split is visible.

NoteDeep Dive: two independent axes — packaging vs. orchestration

It’s tempting to file “graph node” and “tool” as rival ways to do the same thing. They aren’t rivals: they answer two different questions.

  • How is the capability packaged? As an inlined graph node (Part I’s search_docs_node), an in-process @tool (this chapter), or a cross-process MCP service (Part III). Where the code lives, and who can reuse it.
  • Who orchestrates the call? You — a route and a conditional edge, as in Chapter 7 and Chapter 12 — or the model, via a native tool call (this chapter). Who decides.

Put the two axes on a grid and every cell is reachable:

Rows are Axis A (how the capability is packaged); columns are Axis B (who orchestrates the call). The two are orthogonal, so any row pairs with any column.
You route it The model calls it
Graph node (inline) Part I’s routed search_docs (Chapter 7) Section 12.5’s router: the model writes route, the edge obeys
@tool (in-process) a @tool called from a node: search_docs.invoke({…}) buys the schema and reuse search_docs as a @tool — this chapter
MCP (cross-process) plain code calling session.call_tool(…) — Chapter 25’s raw client an MCP tool the model calls (Part III)

13.3 Seeing the mechanic: a hand-written loop

create_agent can assemble the whole model↔︎tools loop in one line, and we’ll get there. First, the loop by hand, with no LangGraph at all: the bound model, a dictionary to find tools by name, and a while loop.

One thing changes shape here, and it stays changed for the rest of the book. Chapter 12 handed the model a string. A tool-calling model is handed a conversation: an ordered list of messages, each tagged with who said it. The user’s turn is a HumanMessage; ("user", question) is the short form of one, and it normalises to the type name human, which is what you will see when you inspect it later. The model’s reply comes back as an AIMessage — still a message, still from the model, even when what it contains is a request to call a tool rather than an answer. A tool’s result goes back into the same list as a ToolMessage. The whole loop is this list growing, and the model being shown all of it each time.

from langchain_core.messages import ToolMessage

tools_by_name = {"search_docs": search_docs, "web_search": web_search}


def run(question: str, max_tool_turns: int = 5) -> None:
    print(f"\n===== question: {question} =====")
    messages: list = [("user", question)]

    turns = 0
    while True:
        ai = llm_with_tools.invoke(messages)
        messages.append(ai)

1        if not ai.tool_calls:
            print(f"  [model] final answer: {excerpt(ai.content)}")
            return

        turns += 1
2        if turns > max_tool_turns:
            print(f"  [code]  hit max_tool_turns={max_tool_turns}; stopping")
            return

        for tc in ai.tool_calls:
            print(f"  [model] calls {tc['name']}(query={tc['args'].get('query')!r})")
            tool = tools_by_name[tc["name"]]
3            result = tool.invoke(tc["args"])
            print(f"  [code]  ran {tc['name']} -> {result!r}")
4            messages.append(ToolMessage(content=result, tool_call_id=tc["id"]))
1
An empty tool_calls list means the model is done and ai.content is the answer.
2
A budget, so a model that keeps asking for tools can’t spin forever: the hand-loop version of the recursion_limit fuse from Chapters 4 and 10.
3
Code executes the tool, not the model. Your code reads the name, looks up the real function, and calls it with the arguments the model supplied.
4
The result goes back as a ToolMessage, tagged with the call’s id so the model can match result to request; then the loop runs again.

(excerpt: first line, trimmed — Chapter 12. It also keeps a code fence in a long answer from closing the book’s output block early.)

Trace the data through one turn. The model returns an AIMessage. If its tool_calls list is not empty, each entry is a plain dict — {"name": "search_docs", "args": {"query": "..."}, "id": "...", "type": "tool_call"} — that the model wrote, and the loop reads the first three keys. It is text and structure, not an executed function. The model sees the result and either calls another tool or answers.

Annotation 3, result = tool.invoke(tc["args"]), is why the loop is written out. The model never runs search_docs. It only asks for it. A model emitting a tool call is filling out a request form; someone else has to act on the form.

Run it on three questions — one the docs cover, one they don’t, and one that needs no tool at all (python code/ch11_handwritten_loop.py). As Chapter 12 noted, this is one representative run: the free text varies, and — since the model owns the choice now — the tools it picks can vary too.

===== question: How do I configure Kafka batch consumers? =====
  [model] calls search_docs(query='Kafka batch consumers configuration')
  [code]  ran search_docs -> 'Kafka Manual: use spring.kafka.listener.type=batch to enable batch consumption.\nKafka FAQ: batch consumers need max-poll-records tuning.'
  [model] final answer: ### Configuring Kafka Batch Consumers ...

===== question: How do I write a Python decorator? =====
  [model] calls web_search(query='Python decorator example how to write a decorator')
  [code]  ran web_search -> '[web] community thread about “Python decorator example how to write a decorator” (example result)'
  [model] final answer: ### Quick answer ...

===== question: What is the capital of France? =====
  [model] final answer: The capital of France is **Paris**.

The Kafka question triggered search_docs and stopped; the Python question went straight to web_search without trying search_docs; the capital question called nothing and answered directly. In Chapter 12 the topology was fixed and only the route varied. Here the model decides how many tool calls a turn has, in what order, and whether there are any.

WarningGotcha: tool-calling is flexible, but you give up control

The run above is the trade in miniature. search_docs’s docstring says to use it whenever the user asks how to do a technical task, and “how do I write a Python decorator” is exactly that — the model skipped it anyway, on its own judgment that the local docs would not help. It happened to be right; it never checked. The capital question it answered with no tool at all. For a general chatbot that is the smart move; for a support bot whose whole promise is “answers come only from our documentation,” it is the promise broken.

The two approaches split cleanly. Open-ended tasks, where you want the model to compose tools cleverly and can tolerate improvising, are tool-calling’s home. Strict, auditable flows — “must retrieve before answering,” “never touch the web on a billing question” — still belong to graph nodes, where control is a property of the edges and not of the model’s mood. Real systems mix both: tool-calling for the open parts, hard-wired graph for the parts that must not drift.

13.4 Letting the framework run the loop: ToolNode + tools_condition

The hand-written loop was worth writing once, but you don’t want to maintain that for tc in ai.tool_calls block in every project. LangGraph ships it as a prebuilt node, ToolNode, plus a prebuilt router, tools_condition. What they do not do is decide the loop’s shape: you still wire the model↔︎tools cycle yourself.

Two pieces are new. First, the state. A tool-calling loop is a growing transcript — user message, AI message with tool calls, tool results, next AI message — so a run normally grows this list. LangGraph’s prebuilt MessagesState is built for that: one field, messages, with the add_messages reducer, which merges by ID. It normally appends a new message, and replaces an existing one when a later message reuses its ID. (MessagesState is one of four state shapes; the other three are Chapter 14’s subject. It’s the simplest state that works with ToolNode, not the only one.)

Second, ToolNode and tools_condition:

  • ToolNode(tools) is the hand-written for-loop as a node. It reads the last message’s tool_calls, runs each one, and appends a ToolMessage per result. One thing it does not do is swallow your bugs: a bad-arguments fault (the model sent quiery=) becomes a ToolMessage the model can read and retry from, but an exception raised inside the tool body propagates and ends the run. ToolNode(tools, handle_tool_errors=…) is where you change that: pass True, or a function from the exception to a string, and the exception becomes a ToolMessage too. This book leaves the default: Chapter 21 handles failure one level up, at the node — retry it, route around it, degrade — rather than inside the tool call.
  • tools_condition is a prebuilt routing function: if the last message has tool_calls, route to the "tools" node; otherwise route to END. It is the if not ai.tool_calls test from the hand-written loop, expressed as an edge.

You assemble them into the loop from “What we’re building”: START → model, a conditional edge out of model, and — the piece you must not forget — a back-edge tools → model so results return to the model.

from langgraph.graph import START, MessagesState, StateGraph
from langgraph.prebuilt import ToolNode, tools_condition

tools = [search_docs, web_search]
llm_with_tools = llm.bind_tools(tools)


def call_model(state: MessagesState) -> dict:
    return {"messages": [llm_with_tools.invoke(state["messages"])]}


builder = StateGraph(MessagesState)
builder.add_node("model", call_model)
builder.add_node("tools", ToolNode(tools))
builder.add_edge(START, "model")
builder.add_conditional_edges("model", tools_condition)
builder.add_edge("tools", "model")             # the back-edge: results return to model
graph = builder.compile()

%%{init: {'securityLevel': 'loose', 'flowchart': {'diagramPadding': 24}, 'themeCSS': 'foreignObject{overflow:visible}span.bot{display:flex;justify-content:flex-start;align-items:flex-start;width:100%;height:0;overflow:visible;line-height:0}span.bot img{display:block!important;width:18px!important;height:18px!important;padding:2px;background:#fff;border-radius:50%;box-shadow:0 0 0 1px #999}span.bot.r img{margin:0;transform:translate(-24px,-24px)}span.bot.d{justify-content:center}span.bot.d img{margin-top:-50%;transform:translateY(-24px)}'}}%%
flowchart TD
    START(["START"]) --> model{"<span class='bot d'><img src='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiMzMzMiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48cGF0aCBkPSJNMTIgOFY0SDgiLz48cmVjdCB3aWR0aD0iMTYiIGhlaWdodD0iMTIiIHg9IjQiIHk9IjgiIHJ4PSIyIi8+PHBhdGggZD0iTTIgMTRoMiIvPjxwYXRoIGQ9Ik0yMCAxNGgyIi8+PHBhdGggZD0iTTE1IDEzdjIiLz48cGF0aCBkPSJNOSAxM3YyIi8+PC9zdmc+'/></span>model"}
    model -.->|has tool_calls| tools["tools"]
    model -.->|no tool_calls| END(["END"])
    tools --> model

You still wire the loop, so you can still change it: put an approval node between model and tools, or a second conditional edge that refuses to end before a search has run. What you no longer write is the body of the tools step: no dictionary lookup, no .invoke, no ToolMessage construction.

tools_condition reads the last message and routes — the “route” is now just “did the model emit a tool call?” Run the same two doc-bot questions through it (python code/ch11_react_agent.py):

===== question: How do I configure Kafka batch consumers? =====
  [model] calls search_docs(query='Kafka batch consumers configuration')
  [tools] returned 'Kafka Manual: use spring.kafka.listener.type=batch to enable batch consumption.\nKafka FAQ: batch consumers need max-poll-records tuning.'
  [model] final: ### Configuring Kafka Batch Consumers ...

===== question: How do I write a Python decorator? =====
  [model] calls web_search(query='Python decorator example how to write a decorator')
  [tools] returned '[web] community thread about “Python decorator example how to write a decorator” (example result)'
  [model] final: ### Quick answer ...

The tool calls match the hand-written loop’s; the execute-and-append is ToolNode’s job now.

13.5 The whole loop in one line: create_agent

The model node, the ToolNode, the tools_condition router, the back-edge: nearly every tool-calling agent needs that assembly, and LangChain packages it as a single call in the langchain package (pip install langchain==1.4.4, the one addition to our install):

from langchain.agents import create_agent

react = create_agent(llm, [search_docs, web_search])

That line binds the tools to the model internally (so you pass the bare llm), adds the model node and a ToolNode, wires tools_condition, and closes the back-edge. On the same two questions:

===== question: How do I configure Kafka batch consumers? =====
  [model] calls search_docs(query='Kafka batch consumers configuration')
  [tools] returned 'Kafka Manual: use spring.kafka.listener.type=batch to enable batch consumption.\nKafka FAQ: batch consumers need max-poll-records tuning.'
  [model] final: ### Configuring Kafka Batch Consumers ...

===== question: How do I write a Python decorator? =====
  [model] calls web_search(query='Python decorator example how to write a decorator')
  [tools] returned '[web] community thread about “Python decorator example how to write a decorator” (example result)'
  [model] final: ### Quick answer ...

The loop it implements is the ReAct pattern (reason, then act, then observe, and repeat), which is why the variable is still called react, and why older code calls the constructor create_react_agent. It is the fastest way to stand up a tool-calling agent and the one that shows you the least of what is underneath.

NoteDeep Dive: create_agent and create_react_agent

LangGraph code written before late 2025 used from langgraph.prebuilt import create_react_agent. It still imports on our pinned 1.2.19, but call it and it warns (LangGraphDeprecatedSinceV10) that it “has been moved to langchain.agents”, with removal slated for LangGraph 2.0 — a move not to a newer LangGraph but to the langchain package, which since its own 1.0 is an agent harness built on LangGraph.

Both constructors compile to the StateGraph + ToolNode loop this chapter just hand-wired. Ask each for its graph and only one node’s name differs:

list(create_react_agent(llm, tools=tools).get_graph().nodes)
# ['__start__', 'agent', 'tools', '__end__']
list(create_agent(llm, tools).get_graph().nodes)
# ['__start__', 'model', 'tools', '__end__']

create_agent returns the same CompiledStateGraph type, so invoke, stream, checkpointer= and get_graph() work as before. What it adds is one seam the old constructor never had: middleware=, a list of hook objects run around the model call and around each tool call (Chapter 19). response_format= carries over — but not unchanged. create_react_agent bolted structured output on as an extra node, generate_structured_response, a second model call after the loop finished; create_agent folds it into the model node and picks the mechanism itself. The system message moved too, from prompt= to system_prompt=.

TipTry it: add a tool and let the model discover it

Write a third @tool — a multiply(a: int, b: int) -> int that returns a * b — with a clear docstring like “Multiply two integers. Use this for any arithmetic multiplication the user asks.” (Keep it a typed, constrained tool; never route a model-supplied string through eval, which would hand the model arbitrary code execution.) Add it to the tools list you pass to create_agent, leave the rest alone, and ask “What is 19 times 23?” Watch the trace: in a representative run the model reaches for multiply(a=19, b=23), your code returns 437, and the model answers from that — even though you wired no route to the new tool. You added a capability by describing it; the docstring did the routing. In Chapter 7 a new tool also meant a new edge and a new mapping entry.

13.6 What a tool may see that the model may not: ToolRuntime

Look again at what Section 13.2 printed for search_docs:

args       : {'query': {'title': 'Query', 'type': 'string'}}

One argument, because the function has one parameter. The rule behind that line is simple, and stays invisible until it bites: every parameter you declare becomes something the model writes. For query that is the whole point. For the next thing a real tool needs, it is a hole.

Say the search should cover only the documents this user is cleared to read. The obvious move is to ask for the user:

@tool
def search_docs(query: str, user_id: str) -> str:   # don't
    ...

user_id is now in the schema, so the model fills it in — the model decides whose documents you read. That is not the model misbehaving; you put a user_id field in front of it and it wrote one. The same objection disposes of the other candidates: a database handle has no JSON schema to write, a request deadline is not the model’s business, and the conversation so far is already sitting in the graph’s state, where re-typing it would only give the model a chance to get it wrong.

What all of those have in common is that they come from the run, not from the model’s reasoning. ToolRuntime is the road they travel. The example takes the simplest of them — the conversation so far, which the graph already holds — because a run can prove the model never retyped it:

from langchain.tools import ToolRuntime


@tool
1def conversation_so_far(runtime: ToolRuntime) -> str:
    """Report the questions the user has already asked in this conversation.
    Use this when the user refers back to something they asked earlier."""
2    asked = [m.content for m in runtime.state["messages"] if m.type == "human"]
    return " | ".join(asked) if asked else "(nothing yet)"
1
That is the entire convention: a parameter typed ToolRuntime. No Annotated wrapper, no argument to the decorator — the annotation alone is what makes the tool executor fill it in, and what keeps it off the model’s menu. Name it runtime, as every official example does; the type is what the machinery actually reads.
2
state is the same graph state the nodes read — MessagesState here, so messages is the conversation this tool was called from the middle of.

The tool has a parameter, and the model is told about none of it:

print("search_docs.args         :", search_docs.args)
print("conversation_so_far.args :", conversation_so_far.args)
search_docs.args         : {'query': {'title': 'Query', 'type': 'string'}}
conversation_so_far.args : {}

An empty schema is not a broken tool. It is a tool that needs nothing from the model. Hand both to create_agent, then ask something that points backwards:

  [model] calls conversation_so_far({})
  [tools] returned 'How do I configure Kafka batch consumers? | What have I asked you so far?'
  [model] final: Here’s a quick recap of the two things you’ve asked about so far ...

The model requested conversation_so_far({}), the only call the schema permits, and the tool answered out of two turns of history that were never written into the call. The executor supplied runtime, and the tool read the questions from the graph’s state. That is the split the section opened with. Arguments are the model’s to write; what the run knows arrives by another road, and the model cannot reach it. The user id this section began with travels the same road under a different name (it is a per-run value, not graph state), and Section 14.8 introduces runtime.context for exactly those.

Six of the nine attributes on runtime matter to this book, and five of them are chapters you have not read yet — this section is where the wire gets attached:

On runtime What it holds Met in
state the graph state as of this call here
context per-run values you pass at invoke time — a user id belongs here, not in the schema Section 14.8
store memory that outlives the thread Section 17.7
stream_writer progress emitted from inside the tool Section 18.5
tool_call_id this call’s id — the one a ToolMessage has to echo back Section 13.4
config the RunnableConfig for the run, tags and callbacks included Chapter 24

The other three are tools (every tool the agent was handed, so one tool can enumerate its siblings), execution_info (thread, run, task and checkpoint ids, plus which attempt this is — useful once Section 21.2 is retrying nodes), and server_info, which is None unless you are running on LangGraph Server.

NoteDeep Dive: two runtimes, and one schema that tells you the wrong thing

ToolRuntime is not Runtime. The next chapter introduces Runtime[Context], which LangGraph injects into nodes and middleware (Section 14.8); ToolRuntime is injected into tools, and carries four things a node has no use for: state (a node is handed its state directly), config, tool_call_id, and tools. The five they share are context, store, stream_writer, execution_info and server_info. It is not a superset in the other direction either: Runtime carries previous, control and heartbeat, which a tool never sees. langchain.tools.ToolRuntime is a re-export of langgraph.prebuilt.tool_node.ToolRuntime — one class, two import paths, and the langchain.tools one is what to write.

One surface disagrees with the others. .args, and the schema bind_tools actually puts on the wire, both drop the runtime parameter. The raw args_schema keeps it:

print(list(conversation_so_far.args_schema.model_fields))
# ['runtime']

That is construction plumbing, not the wire format — and on a tool whose only parameter is the runtime, it is alarming to read. When the question is what will the model be shown, ask .args.

13.7 Five levels of control

Everything in this chapter, and Chapter 7 before it, is one mechanic seen at five levels of abstraction. The levels differ in who writes the code that runs the tool.

These are really two axes, not one ranking: how much loop code you hand-write, and where you can still intercept. They pull in opposite directions at the bottom.

Level Who runs the tool Loop code you write Where you can intercept
Graph node (Chapter 7) it’s a node; you route to it agent + router + conditional edge every node boundary — you wrote them
Hand-written loop you, tool.invoke(args) the whole while loop anywhere in your own loop
ToolNode + tools_condition ToolNode reads tool_calls and runs them the wiring, not the loop body the node boundaries around ToolNode
create_agent(model, tools) fully automatic none — one line nothing, until you add hooks
create_agent(model, tools, middleware=[...]) automatic, with hooks none — one line plus middleware the hooks middleware re-exposes

Reading down the first axis you write less loop code. But the last row does not give up control — it buys some back. ToolNode is the stove: hand it a ticket and it cooks, but it doesn’t take orders, decide the menu, or run the loop. create_agent is the whole restaurant, and it contains a ToolNode; the two are not the same thing. Level 5 is that restaurant with a franchise manual: you still write no loop, but middleware re-opens specific seams — intercepting the order before it reaches the model, or the ticket before it reaches the stove — the same node boundaries you have been writing by hand since Chapter 6. So a middleware agent has more interception than the bare one-liner, not less. When the one-liner misbehaves, the table tells you which rung to drop down to; rung five gets a chapter of its own (Chapter 19).

13.8 Before moving on

One debugging habit carries forward: when a trace shows a tool call and the answer still looks made up, check what the tool returned before you blame the model — our web_search stub returns nothing real.

Every graph in Part II has assumed a particular shape of state: the hand-routed bots used a TypedDict with a field per tool, this chapter’s hand-wired graph the prebuilt MessagesState. The next chapter steps back to the state itself: the four ways to declare it, and which one to reach for when — and with them the typed per-run Context that runtime.context has been holding a seat for.

New pieces in this chapter

Piece Usage
Type
ToolMessage The message that carries a tool’s result back to the model. ToolMessage(content=result, tool_call_id=tc["id"]); the id lets the model match result to request
MessagesState Prebuilt state: one messages field with an ID-aware append reducer. StateGraph(MessagesState); the simplest state that works with ToolNode, not the only one
ToolNode The hand-written run-the-tool-calls block as a prebuilt node. builder.add_node("tools", ToolNode(tools)); runs each tool_call, appends a ToolMessage per result
ToolRuntime What the tool may see and the model may not: state, context, store, stream writer, this call’s id. def my_tool(query: str, runtime: ToolRuntime); the annotation is what gets it injected and kept out of the model’s schema — runtime is the conventional name, not a required one
API
@tool Decorator that packages a plain function as a tool schema: name, arg types, docstring. @tool on def search_docs(query: str) -> str:; the docstring is a prompt — it steers when the model reaches for it
ChatOpenAI.bind_tools() Attach tool schemas to every request so the model can emit tool calls. llm.bind_tools([search_docs, web_search]); grants the power to ask, never to run
tool.invoke() On a @tool object: code executes the tool with the args the model wrote. tool.invoke(tc["args"]); the model only emits the call — this line is the only place the function runs
tools_condition Prebuilt router: tool calls pending → "tools", otherwise → END. builder.add_conditional_edges("model", tools_condition); don’t forget the back-edge tools → model
create_agent The whole model↔︎tools loop assembled in one call. from langchain.agents import create_agent; create_agent(llm, [search_docs, web_search]); replaces langgraph.prebuilt.create_react_agent, deprecated since LangGraph 1.0
create_agent(system_prompt=…) Keyword arg: a system message for the prebuilt agent. create_agent(llm, tools, system_prompt="You must call search_docs …"); persuades, doesn’t enforce
create_agent(middleware=…) The seam the old constructor lacked: hooks around the model and tool calls (langchain.agents.middleware). Named here; used in later chapters. response_format= exists on both, but the new one folds it into the model node instead of adding one

Code in this chapter

File What it runs
code/ch11_handwritten_loop.py Native tool-calling with the loop written out: bind_tools, the tool calls the model emits, and your code running them.
code/ch11_react_agent.py The same loop handed to the framework – ToolNode and tools_condition, then create_agent in one line.
code/ch11_tool_runtime.py ToolRuntime: the parameters the framework injects, which the model never sees and cannot choose.

Challenge

🥉 Bronze — convention over configuration

Rename the ToolNode — builder.add_node("toolbox", ToolNode(tools)), with the back-edge fixed to match — and re-run. You will not get as far as the question: compile() itself refuses. The router line builder.add_conditional_edges("model", tools_condition) never mentioned the node by name, and now it cannot find it:

ValueError: At 'model' node, 'tools_condition' branch found unknown target 'tools'

Repair that twice. First keep the name "toolbox" and hand the router a path map — add_conditional_edges("model", tools_condition, {"tools": "toolbox", END: END}). Then delete the map and rename the node back.

Both repairs have to leave the run clean: put the same question through each one and check the trace for the tool call and a finished answer instead of the ValueError. Then say which of the two owes the framework an explicit map, and why the other is allowed to stay silent.

Hints: the trap is in tools_condition’s signature, not only its body (langgraph.prebuilt.tool_node; inspect.getsource prints both) — stripped of the docstring and state-format juggling it is:

def tools_condition(state, messages_key: str = "messages") -> Literal["tools", "__end__"]:
    ...
    if hasattr(ai_message, "tool_calls") and len(ai_message.tool_calls) > 0:
        return "tools"
    return "__end__"

The convention is declared twice over, which is what makes it a convention rather than a hard-coded name: tools_condition promises Literal["tools", "__end__"], and ToolNode.__init__ itself defaults to name="tools". (There is a third: the router reads state["messages"] by default — the field MessagesState happens to provide.)

The load-bearing part is the return annotation. LangGraph reads Literal["tools", "__end__"] at build time to learn every destination the branch might name, and checks each against the registered nodes — which is why the failure above is a ValueError from compile() and not a surprise mid-run.

Drop the annotation from a router of your own and, at first, nothing breaks: the identical body compiles and takes the identical route, because at runtime the branch is resolved from whatever string the function actually returned. What you gave up shows up in two other places. The drawn graph loses the branch — get_graph() then reports a plain model -> __end__ edge and never mentions tools at all, so every picture of your agent is quietly wrong. And the build-time check is gone, so the day a target is misspelled there is no ValueError to read: the run stops instead, logging wrote to unknown channel branch:to:toolbox, ignoring it and ending after the first node.

That trade is convention over configuration, with the annotation as the contract: follow the expected names and the pieces wire themselves; deviate and you owe an explicit mapping.

🥈 Silver — catch the model answering from thin air

Ask the create_agent bot the question the Gotcha flagged — one it can answer from its own knowledge, like "What is the capital of France?" — and confirm from the trace that it calls no tool. Then pass system_prompt="You must call search_docs before answering. Never answer from your own knowledge." and re-run: the model may now search first every time, but what you hold is a stronger nudge, not a guarantee — the Chapter 12 lesson again. The only structural “always search first” is the Chapter 7 graph, where your router, not the model, decides every hop.

office hours Worked solution with tests: code/answers/ch11_forced_tool.py.


  1. Model card: https://huggingface.co/Qwen/Qwen3.8-27B.↩︎

  2. Model card: https://huggingface.co/openai/gpt-oss-20b.↩︎