flowchart LR
START(["START"]) --> agent{"agent"}
agent -.->|route = search| search("search_docs")
agent -.->|route = web| web("web_search")
agent -.->|route = generate| generate("generate")
search --> agent
web --> agent
generate --> END(["END"])
7 Tool Nodes

Up to now the wiring was the interesting part and the node bodies were placeholders. search_docs handed back two made-up strings in every chapter since Chapter 4. This chapter gives it a real body — it looks something up in a keyed knowledge base — and makes web_search, the fallback for the questions the docs don’t cover, at least answer about the question it was asked. Still a stub, but a stub with a contract. Then it lets the agent route to whichever one it needs.
A tool is just a node. A capability is an ordinary node with a clear contract — read some state, do the work, write results back — and the agent routes to it the way it already routes to anything else.
There is no tool-specific wrapper in this chapter. A tool is a Python function with the same signature as every node you’ve written. (LangGraph does ship a prebuilt ToolNode, and LangChain a @tool decorator; both are for LLM-driven tool-calling, and they arrive in Part II.)
7.1 What we’re building
The doc-bot in Chapter 6 already had both tools, as placeholders: search_docs and web_search each returned the same two strings whatever the question was. This chapter gives them something to do. search_docs looks the question up in a small keyed knowledge base (our stand-in for the vector store that arrives in Part III), and can come back empty. web_search is still a stand-in for the open web, but it now reads the question and answers about it. The agent tries the docs first. If they come back empty, it falls back to the web. Once it has material, it generates.
That shape is the loop from Chapter 6, unchanged. The agent sits in the middle, each tool returns to it, and the agent decides what to reach for next.
7.2 The state grows a slot per tool
Each tool writes its own field, so the reader downstream can tell where a result came from. docs is written by search_docs, web_results by web_search.
from typing import NotRequired, TypedDict
class State(TypedDict):
question: str # input, set by the caller
route: NotRequired[str] # written by agent: search|web|generate
docs: NotRequired[list[str]] # written by search_docs (may be empty)
web_results: NotRequired[list[str]] # written by web_search
iterations: NotRequired[int] # loop counter the agent keeps (Ch4)
answer: NotRequired[str] # written by generateEvery tool-written field is NotRequired, because on any given run some tools run and some don’t. iterations is the loop counter from Chapter 6.
7.3 The tools
Each tool is a node with a one-line contract: what it reads, what it writes.

search_docs reads question and writes docs. Unlike the stub in earlier chapters, it actually looks something up in a keyed knowledge base — a dict from topic to documents. A hit returns realistic content; a miss returns an empty list. That empty list is a real answer: “we have nothing on this.”
KNOWLEDGE_BASE: dict[str, list[str]] = {
"kafka": [
"Kafka Manual: use spring.kafka.listener.type=batch "
"to enable batch consumption.",
"Kafka FAQ: batch consumers need max-poll-records tuning.",
],
"redis": [
"Redis Manual: set the connection pool via spring.data.redis.*.",
],
# No "python" topic: the second question below will miss.
}
def search_docs_node(state: State) -> dict:
question = state["question"].lower() # lowercase for matching
print("[search_docs] searching the knowledge base:", state["question"])
hits: list[str] = []
# Any topic whose keyword appears in the question contributes its docs.
for topic, docs in KNOWLEDGE_BASE.items():
if topic in question:
hits.extend(docs)
print(f"[search_docs] {len(hits)} hit(s)")
return {"docs": hits} # may be emptyweb_search reads question and writes web_results. It stays a stub, but its contract (question in, results out) is the shape a real external search would keep.
def web_search_node(state: State) -> dict:
question = state["question"]
print("[web_search] falling back to a web search:", question)
# Pretend the open web always turns up something.
results = [f"[web] community thread about “{question}”"]
return {"web_results": results}When you eventually wire web_search to something real, reach for a search API built for agents, not a raw search-engine scrape. The two hand back very different things.
- A traditional search / SERP API (SerpAPI’s or Serper’s search endpoints,1 or scraping Google or Bing yourself) returns a page of links and snippets meant for a human to click. You still have to fetch each page, strip the HTML and ads, and judge relevance — work the model shouldn’t be doing.
- An agent-native search API hands the model material it can use directly, but read each product’s contract, because “agent-native” covers two different outputs. Some return page content instead of links. Brave’s LLM-context endpoint returns extracted passages with source metadata, and Exa’s search request can ask for each result’s text, highlights or a summary; Tavily is in this group. Others return a search-grounded answer. Perplexity’s Sonar answers from the web with citations (a separate Search API returns the material itself), and Linkup picks between
searchResultsand asourcedAnswerper call. Exa also searches by meaning — its index encodes documents as learned embeddings — and its pipelines can combine that with keyword retrieval.2
That is why the contract here — question in, ready-to-use web_results out — matches the content-returning kind of agent search API and not a SERP scrape. The stub keeps the shape; a real service just fills it with better material.
Once a real service is behind this node, whatever comes back is untrusted input. The moment a model reads it, it can be steered by it, so treat tool output the way you treat user input.
7.4 The contract is what makes a tool swappable
search_docs promises “give me a question, I’ll put docs in the state.” The rest of the graph neither knows nor cares that today it’s a dict lookup. In Part III we replace the dict with a real vector store, and no edge, router, or other node has to change. The contract (fields read, fields written) is the seam the rest of the graph is bolted to; the implementation floats behind it.
The contract cuts both ways. Swap in a web body that returns a string where the graph expects a list:
def web_search_node(state: State) -> dict:
return {"web_results": "[web] community thread"} # a str, not a listRun the Python question and nothing complains at the seam. The agent prints web=22 (the length of the string), decides it has material, and routes to generate. That node dies with TypeError: can only concatenate list (not "str") to list — one node after the one that broke the contract. The TypedDict does not check at run time (Chapter 3), so a tool that writes the wrong shape is caught by whoever reads it next, if at all.
What a tool is (a node with a contract) and who decides to use it (here, your agent, via the route it writes) are separate questions. Part II hands the second one to the model; the tool underneath stays this shape.

7.5 The agent picks a tool
The agent’s job hasn’t changed since Chapter 5: look at state, write a route, stop. What has changed since Chapter 6 is that the decision now turns on a tool’s result. The agent searches the local docs first, and falls back to the web only if that search came back empty. That small degrade strategy is only possible because search_docs does real work now.
def agent_node(state: State) -> dict:
docs = state.get("docs", [])
web = state.get("web_results", [])
1 searched_docs = "docs" in state # have we tried the local docs yet?
searched_web = "web_results" in state # ...and have we tried the web yet?
if not searched_docs:
route = "search" # haven't searched locally yet
elif len(docs) == 0 and not searched_web:
route = "web" # local search missed — fall back to web
else:
route = "generate" # have material (hit/web) -> answer
print(f"[agent] docs={len(docs)} web={len(web)} -> {route}")
return {"route": route, "iterations": state.get("iterations", 0) + 1}- 1
-
Key presence, not truthiness:
"docs" in statedistinguishes “we searched and found nothing” (docspresent but empty) from “we haven’t searched yet” (docsabsent), and the routing hinges on that difference. The same guard onweb_resultsmeans a web body that legitimately returns no results still counts as “already tried,” so the agent won’t loop on it.
The agent still never calls a tool; it writes a string.
If you’ve seen LangChain’s @tool decorator and bind_tools, put them aside for this chapter. That machinery lets the language model choose a tool and emit a call, which your code then executes — the decision lives inside the model.
What we’re building is different. Our tools are plain graph nodes, and you decide which one runs by writing a route and wiring a conditional edge. The model isn’t even in the room yet.
Both approaches are useful, and they solve the same problem from opposite ends — one gives you control, the other gives the model reach. We put them side by side in the tool-calling chapter in Part II, once a real LLM is doing the deciding.
7.6 Generating from whatever ran
Before we wire the graph, one node is still missing: generate. It collects results from every tool that ran. Each tool writes its own field and any field may be absent, so it reads with defaults.
def generate_node(state: State) -> dict:
# A tool that didn't run leaves its field absent.
docs = state.get("docs", [])
web = state.get("web_results", [])
sources = docs + web
if sources:
body = "\n".join(f" - {s}" for s in sources)
answer = f"Answer (from {len(sources)} source(s)):\n{body}"
else:
answer = "Sorry, I couldn't find anything relevant."
return {"answer": answer}7.7 Wiring it
Plain edges for the fixed steps, one add_conditional_edges for the three-way choice, and two back-edges so each tool returns to the agent. The router is the same one-liner:
def route_after_agent(state: State) -> str:
return state["route"]from langgraph.graph import StateGraph, START, END
builder = StateGraph(State)
builder.add_node("agent", agent_node)
builder.add_node("search_docs", search_docs_node)
builder.add_node("web_search", web_search_node)
builder.add_node("generate", generate_node)
builder.add_edge(START, "agent")
builder.add_conditional_edges(
"agent",
route_after_agent,
{
"search": "search_docs", # try the internal docs
"web": "web_search", # fall back to the open web
"generate": "generate", # enough material — answer
},
)
builder.add_edge("search_docs", "agent")
builder.add_edge("web_search", "agent")
builder.add_edge("generate", END)
graph = builder.compile()flowchart TD
START(["START"]) --> agent{"agent"}
agent -.->|search| search_docs("search_docs")
agent -.->|web| web_search("web_search")
agent -.->|generate| generate("generate")
search_docs --> agent
web_search --> agent
generate --> END(["END"])
Adding a tool is adding a node and a mapping entry.
7.8 Running it
Two questions, chosen to take the two different paths. The first names a topic the knowledge base knows; the second doesn’t, so the agent falls back to the web. recursion_limit=10 is Chapter 6’s fuse. This graph needs four supersteps on the Kafka path and six on the Python one, and the fuse has to sit above that count, not on it. The limit is checked before the step that would exceed it, so six supersteps need a limit of at least seven.
if __name__ == "__main__":
for q in [
"How do I configure Kafka batch consumers?",
"How do I write a Python decorator?",
]:
print(f"\n===== question: {q} =====")
result = graph.invoke({"question": q}, config={"recursion_limit": 10})
print("--- answer ---")
print(result["answer"])
===== question: How do I configure Kafka batch consumers? =====
[agent] docs=0 web=0 -> search
[search_docs] searching the knowledge base: How do I configure Kafka batch consumers?
[search_docs] 2 hit(s)
[agent] docs=2 web=0 -> generate
--- answer ---
Answer (from 2 source(s)):
- Kafka Manual: use spring.kafka.listener.type=batch to enable batch consumption.
- Kafka FAQ: batch consumers need max-poll-records tuning.
===== question: How do I write a Python decorator? =====
[agent] docs=0 web=0 -> search
[search_docs] searching the knowledge base: How do I write a Python decorator?
[search_docs] 0 hit(s)
[agent] docs=0 web=0 -> web
[web_search] falling back to a web search: How do I write a Python decorator?
[agent] docs=0 web=1 -> generate
--- answer ---
Answer (from 1 source(s)):
- [web] community thread about “How do I write a Python decorator?”
Follow the [agent] lines. That is the agent reassessing after each tool. The Kafka question hits the docs (2 hit(s)) and goes straight to generate. The Python question searches, finds nothing (0 hit(s)), loops back, the agent sees the miss and routes to web_search, and only then generates. Same graph, two different routes through the tools — chosen at runtime by what each tool wrote into state.
Add a third tool and watch it ripple. A search_faq_node reads question and writes a new faq field, and because faq is new, touching one node isn’t enough. The producer and every consumer of that field have to move together:
- Add
faq: NotRequired[list[str]]toState. Skip this and the schema silently drops what the node returns — the field never reaches anyone. - Register the node, add the mapping entry
"faq": "search_faq", and a back-edge toagent. - Teach
agentwhen to route there and how to tell it already ran (searched_faq = "faq" in state), the way it already does for docs and web — otherwise it either never picksfaqor loops waiting for a key that route would have set. - Have
generatefoldfaqinto itssources, or the hit is fetched and then ignored.
Give it a question the local docs miss but the FAQ covers, and assert the answer is built from the FAQ entry. Route faq ahead of web when you teach agent about it: this chapter’s web_search stub turns something up for any question, so a run that reaches the web never comes back empty and the FAQ never gets its turn. That is a contract change: a new field, producer to consumer, moving as a unit.
Then try the reverse: change search_docs’s body to look up a different topic (drop "kafka", add "python") and re-run the Python question. The routing doesn’t move; only the hit does. The body changes while the contract stays fixed — the seam from The contract is what makes a tool swappable.
7.9 What we learned
- A tool is just a node. In Part I there’s no tool-specific wrapper: a capability is an ordinary node with the same signature as every node you’ve written. (The prebuilt
ToolNodeand@tooldecorator arrive in Part II.) - A tool’s contract is the fields it reads and writes. Keep the contract fixed and you can swap the body freely (a dict today, a real vector search in Part III) without touching the graph.
- The agent picks a tool the way it picks anything: it writes a
route. Routing to a tool is the conditional-edge routing from Chapter 5, and reassessing after each tool is the loop from Chapter 6. - A tool’s result can drive the next decision. Because
search_docsreally looks something up, the agent can tell a hit from a miss and fall back to the web only when it needs to. - These are graph nodes you route to, not LLM-native tool-calling. Who decides to use a tool is a separate axis from what a tool is — we’ll compare the two head-to-head once a real model joins in Part II.
Our doc-bot can now branch, loop, and reach for tools — but every run starts from a blank slate. Invoke it, get an answer, and the graph forgets everything. In the next chapter we give it a memory: checkpoints save the full state after each step, so a run can be paused and resumed, recover from a mid-run failure, or be picked up right where it left off.
New pieces in this chapter
No new pieces in this chapter — it composes ones you already know.
Code in this chapter
| File | What it runs |
|---|---|
code/ch05_tool_nodes.py |
Two tools as ordinary nodes with one contract, and an agent that routes to whichever the state says it needs. |
Challenge
🥈 Silver — turn the fallback ladder into data
The agent hard-codes its strategy with if / elif: try the docs, fall back to the web on a miss. Add a third tool and you edit the ladder again.
Generalize it: put the tools in a priority list — [("docs", …), ("faq", …), ("web", …)] — and have the agent walk it, trying the next tool only when the current one comes back empty, and stopping the moment one has a hit. Now reordering or adding a tool is editing a list, and the agent’s logic never changes.
Prove it with three questions: one the docs answer (stops at tier 1), one only the FAQ knows (walks past docs), and one only the web has (falls through both).
Worked solution with tests: code/answers/ch05_tool_priority.py.
SerpAPI organic results: https://serpapi.com/organic-results; Serper: https://serper.dev/.↩︎
Exa on neural search: https://exa.ai/blog/how-to-build-nextgen-search; on combining dense and sparse retrieval: https://exa.ai/blog/composing-a-search-engine.↩︎

