%%{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"]) --> agent{"<span class='bot d'><img src='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiMzMzMiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48cGF0aCBkPSJNMTIgOFY0SDgiLz48cmVjdCB3aWR0aD0iMTYiIGhlaWdodD0iMTIiIHg9IjQiIHk9IjgiIHJ4PSIyIi8+PHBhdGggZD0iTTIgMTRoMiIvPjxwYXRoIGQ9Ik0yMCAxNGgyIi8+PHBhdGggZD0iTTE1IDEzdjIiLz48cGF0aCBkPSJNOSAxM3YyIi8+PC9zdmc+'/></span>agent"}
agent -.->|route = search| search("search_docs")
agent -.->|route = web| web("web_search")
agent -.->|route = generate| generate("<span class='bot r'><img src='data:image/svg+xml;base64,PHN2ZyB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHdpZHRoPSIyNCIgaGVpZ2h0PSIyNCIgdmlld0JveD0iMCAwIDI0IDI0IiBmaWxsPSJub25lIiBzdHJva2U9IiMzMzMiIHN0cm9rZS13aWR0aD0iMiIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbGluZWpvaW49InJvdW5kIj48cGF0aCBkPSJNMTIgOFY0SDgiLz48cmVjdCB3aWR0aD0iMTYiIGhlaWdodD0iMTIiIHg9IjQiIHk9IjgiIHJ4PSIyIi8+PHBhdGggZD0iTTIgMTRoMiIvPjxwYXRoIGQ9Ik0yMCAxNGgyIi8+PHBhdGggZD0iTTE1IDEzdjIiLz48cGF0aCBkPSJNOSAxM3YyIi8+PC9zdmc+'/></span>generate")
search --> agent
web --> agent
generate --> END(["END"])
12 A Real LLM

Every graph in Part I ran on hard-coded logic: the agent node was an if / elif ladder and generate was a string join. This chapter takes the doc-bot from Chapter 7 and puts a real language model behind those two nodes, running on your own machine through LM Studio. Everything else stays: the state, the edges, and the router are Chapter 7’s.
The orchestration doesn’t change when you plug in a real model — the model just becomes the biggest variable in the system.
12.1 Connecting a model
Part II talks to a model, but not a cloud one. The book runs a real model locally and for free with LM Studio (the setup from Chapter 2), which exposes an OpenAI-compatible endpoint on localhost. LangChain’s ChatOpenAI speaks that protocol, so connecting is four lines, and every model-backed Part II chapter reuses this block:
- 1
- Your own machine: no API key to buy and no per-token bill, all through Part II.
- 2
- The only line that changes when we swap models later in this chapter or point at a hosted provider at the end of it. Qwen3.8 27B1 is an open model that follows instructions cleanly.
- 3
- Qwen3.8 is a hybrid model: unless told otherwise it writes a chain of thought before every answer, slowly and out of sight. This line switches that off — these chapters want the answer — and Section 16.9 shows what the thinking does to a structured decision when it is left on. (The switch exists only for the catalogue install Chapter 2 asked for; a Hugging Face download of the same weights ignores it.)
Three things go wrong at this line, and from Python they look alike: a connection error, or a 400 with a sentence in it. The model is not loaded yet: LM Studio loads on the first request, so the first reply can take a minute, or come back as Failed to load model … Operation canceled when two requests race the load. Send it a one-line prompt first and the run then reproduces. The model was unloaded under you: a Model unloaded in the middle of a run means another request — an embedding model, a second chat model — pushed it out. That is not only memory: LM Studio’s default is to keep just the last model it loaded on demand, and a model loaded explicitly with lms load qwen/qwen3.8-27b is the one it will not evict. There is no room for two: Chapter 2’s note applies: run the model-backed examples one at a time, or pick a smaller chat model; a longer timeout fixes nothing. And if the local route is closed to you altogether, Appendix A points the whole book at a hosted model with one command.
langchain-openai is the first of the packages Part II adds (the Part II opener lists the others, each with its chapter) — the package Chapter 2’s smoke test listed as (not installed). Install it now, pinned to match Part I’s versions:
pip install langchain-openai==1.7.0The ==1.7.0 matters. A bare pip install langchain-openai pulls the latest release, which drags langchain-core up past the 1.6.9 Chapter 2 pinned. Chapter 2’s smoke test does not assert versions — it prints them — so nothing errors at install time. You just find the printed set no longer matches the book’s, on a dependency you never meant to move, and a later chapter can behave differently. Read those printed versions first when something drifts. Pinning keeps the set consistent; better still, install everything from the companion repo’s requirements.txt, which pins the whole dependency set together.
One more piece of shared setup. Every trace in Part II prints what the model said, and a real answer can run for paragraphs and carry code fences, so the printing goes through one helper that keeps the first line:
def excerpt(text: str, width: int = 140) -> str:
"""First line of a model answer, cut at a word boundary, with '...' if cut."""
first = text.strip().splitlines()[0] if text.strip() else ""
if len(first) <= width and first == text.strip():
return first
cut = first[:width].rsplit(" ", 1)[0] if len(first) > width else first
return cut.rstrip(" ,;:") + " ..."The ... is the signal: it only appears when something was cut, so an output block that ends without one is the model’s whole answer. Every model-backed chapter from here on reuses this, and the companion files carry a copy.
12.2 What we’re building
The doc-bot is the one from Chapter 7, unchanged in shape: the agent sits in the middle and routes to a tool, each tool returns to it, and once it has material it generates.
Everything in this chapter happens inside the agent diamond and the generate box. The robot stamp
is how we mark a node that calls into an LLM.
12.3 Two node bodies change, nothing else
Here is the agent node with a real model in it. Its job is the one it had in Chapter 7 — read the state, write a route, stop — but it hands the state to the model and asks for a decision. To keep a local model on the rails we tell it to answer with a single word, then read that word back:
def agent_node(state: State) -> dict:
docs = state.get("docs", [])
web = state.get("web_results", [])
searched_docs = "docs" in state
searched_web = "web_results" in state
prompt = f"""
You are the router for a documentation question-answering agent.
Look at the current state and decide the single next action.
Question: {state['question']}
Local documents found so far: {len(docs)}
Web results so far: {len(web)}
Already searched the local docs: {searched_docs}
Already searched the web: {searched_web}
Apply these rules top to bottom and act on the FIRST that matches; once
one matches, ignore the rules below it.
1. If you ALREADY have at least one source (local documents found > 0 OR
web results > 0), you have enough -> GENERATE. Do not search again,
even if the web has not been searched: one source is enough.
2. else if the local docs have not been searched yet -> SEARCH
3. else if the web has not been searched yet -> WEB
4. otherwise -> GENERATE
Reply with exactly one word: SEARCH, WEB, or GENERATE. Nothing else."""
reply = llm.invoke(prompt).content.strip().upper()
# Brittle free-text parsing: hunt for a keyword in whatever the model said.
if "SEARCH" in reply:
route = "search"
elif "WEB" in reply:
route = "web"
else:
route = "generate"
print(f"[agent] model said {reply!r} -> {route}")
return {"route": route, "iterations": state.get("iterations", 0) + 1}generate changes the same way — where Chapter 7 joined strings, it now asks the model to write from the sources the tools collected:
def generate_node(state: State) -> dict:
sources = state.get("docs", []) + state.get("web_results", [])
sources_text = "\n".join(f"- {s}" for s in sources) or "(no sources)"
prompt = f"""
Answer the user's question concisely, using only the sources
below. Do not invent anything.
Question: {state['question']}
Sources:
{sources_text}
Answer:"""
answer = llm.invoke(prompt).content.strip()
print("[generate] the model wrote an answer")
return {"answer": answer}Now do the diff in your head against Chapter 7. The node names, the routes, the route_after_agent function, every add_node / add_edge / add_conditional_edges call — the whole compiled graph — are unchanged. The only lines that changed are inside agent and generate. (The structured version below adds a single reason field to State.) LangChain is the capability inside a node; LangGraph is the orchestration between nodes. A model is a bigger, stranger node body than a dict lookup, and the graph sees only a node body.
PromptTemplate?
If you’ve come from LangChain tutorials, the f-string in agent_node may look naive — isn’t PromptTemplate the proper way to build prompts? Not here.
A prompt template is a composition tool. It belongs inside LangChain’s chain pipelines (LCEL), where a template is a Runnable you pipe into a model and a parser, partial-fill, serialize, or splice few-shot examples into. In this book the composition layer is the graph itself. A node body is plain Python, and the most direct way to build a string in plain Python is an f-string — transparent, printable, debuggable, nothing new to learn.
That’s the same boundary the preface drew: from the LangChain family this book takes ChatOpenAI and the message types, and leaves chains and LCEL on the shelf. LangGraph has no need of a template — every prompt in this book is a string you can print.
PromptTemplate starts paying rent when you want what f-strings don’t do: one template reused across nodes with declared input variables, partial-filled defaults, few-shot examples assembled on the fly, or prompts managed as data rather than code. If you reach that point, it slots into a node body without touching a single edge — like every other node-internal upgrade in this chapter.
Run the naive agent with the capable model on the Kafka question (python code/ch10_weak_model.py qwen/qwen3.8-27b):
===== model: qwen/qwen3.8-27b =====
question: How do I configure Kafka batch consumers?
[agent] model said 'SEARCH' -> search
[search_docs] 2 hit(s)
[agent] model said 'GENERATE' -> generate
[generate] the model wrote an answer
--- answer ---
To configure Kafka batch consumers, set `spring.kafka.listener.type=batch` and tune the `max-poll-records` setting.
Two decisions, search then generate: the path the hard-coded agent took, chosen this time by a model reading the state. The answer line passed through excerpt and came back without a ..., so that is the whole of what the model wrote.
Output now comes from a real, non-deterministic model, so the blocks in this chapter and the rest of Part II can’t be verbatim the way Part I’s were. Two things vary from run to run and machine to machine: the model’s free-text answers, and, as Section 12.4 shows, sometimes the route decisions themselves.
The book pins one representative run at temperature=0; your exact wording, and occasionally your exact path, will differ, and a long answer may be trimmed to an excerpt. What is fixed is your code: how each decision gets logged, and how the graph responds to it — a search route always runs search_docs and returns to agent, the fuse always trips at the recursion limit. Read a trace as one representative journey through a fixed machine, not a guaranteed transcript. Later chapters lean on this without repeating it.
A few sections and challenges go further and rest their whole demonstration on a model behaving a particular way. Those carry a bold On your machine. paragraph saying what we measured and what to do if your run disagrees — because with these the interesting outcome is often the one that didn’t match.
12.4 And how it fails
Now the same file with one line changed, the model id, pointed at a weak 7B: python code/ch10_weak_model.py with no argument selects qwen2.5-vl-7b-instruct, which is not on Chapter 2’s list — fetch it first (lms get qwen2.5-vl-7b-instruct, about 5 GB), or pass the id of any small chat model you already have as the one argument. One detail of the runnable file matters for reading the trace: it invokes the graph with Chapter 6’s fuse set low, so a loop shows itself in a few lines instead of a few minutes.
result = graph.invoke({"question": question}, {"recursion_limit": 8})Leave that out and the same GraphRecursionError still ends the run, but only after the default budget is spent — 10007 supersteps on the pinned version (Chapter 6), which is thousands of searches rather than four, and a 7B that takes seconds per call turns that into a wait long enough to look like a hang.
===== model: qwen2.5-vl-7b-instruct =====
question: How do I configure Kafka batch consumers?
[agent] model said 'SEARCH' -> search
[search_docs] 2 hit(s)
[agent] model said 'SEARCH' -> search
[search_docs] 2 hit(s)
[agent] model said 'SEARCH' -> search
[search_docs] 2 hit(s)
[agent] model said 'SEARCH' -> search
[search_docs] 2 hit(s)
!! GraphRecursionError: the agent looped until the fuse blew
After the first search the state holds two hits, and the prompt says in so many words: if local documents found > 0, GENERATE. The capable model read that rule and stopped after one search. The 7B reads the same rule with the same two hits in the state and says SEARCH again, and the graph does what it is told: route to search_docs, return to agent, route to search_docs, until recursion_limit raises GraphRecursionError (Chapter 6). Without that limit the process would spin until you killed it. (One practical note. LM Studio sometimes fails to load the 7B on demand, and the first request comes back as Operation canceled; send it a one-line prompt first, and the run then reproduces.)

Nothing in the orchestration is wrong. The edges are the ones that worked a moment ago, and the limit did its job. The model is wrong: it can’t hold a four-rule instruction while tracking the state. In Part I, behavior was a property of your graph. From here on it is a property of your graph and the model you drop into it.
It is tempting to answer a flaky agent with more machinery — more edges, more retries, a cleverer router. But the failure above isn’t an orchestration bug: the graph routed correctly every time, and the fuse kept the run from hanging. More graph complexity can’t make a bad decision good. What the orchestration layer can do about a weak model is different in kind — constrain the choice (structured output, next), validate the model’s output and fall back, swap in a stronger model, or move the decision back into code where it’s exact.
So when an agent misbehaves, the first question is which layer owns the problem — the wiring (yours) or the judgment (the model’s) — because the fixes live in different places, and pouring graph code onto a model problem just hides it.
12.5 A guaranteed-legal route: structured output
Even when the capable model behaves, look at how the naive agent reads its decision: if "SEARCH" in reply. That is string-guessing. If the model answers “I’ll search the docs,” the word “search” is there and we’re lucky; if it answers “Let me look that up,” we fall through to generate by accident. Free text is not a contract, and parsing it is a bug waiting for a wordier model.
LangChain’s with_structured_output replaces the guesswork with a schema. We describe the decision as a Pydantic model and bind it to the model:
from typing import Literal
from pydantic import BaseModel, Field
class Decision(BaseModel):
"""Choose the next action for a documentation question-answering agent."""
1 route: Literal["search", "web", "generate"] = Field(
description="Next action: search=look in the local docs, "
"web=search the open web, generate=write the answer now."
)
reason: str = Field(description="One short sentence explaining the choice.")
# method="json_schema" asks LM Studio to enforce the schema with response_format.
2decider = llm.with_structured_output(Decision, method="json_schema")- 1
-
A closed set of three legal values. The
Literalis what turns string-guessing into a contract. - 2
-
decider.invoke(prompt)returns aDecisionobject, never a sentence to parse.
(One housekeeping note: with_structured_output makes pydantic emit a benign serializer warning, so the runnable code/ch10_real_llm.py adds a single warnings.filterwarnings("ignore", message="Pydantic serializer warnings") line to silence just that line — the parsed result is unaffected.)
method="json_schema" is not a stylistic choice here — it is the one that works. There are three ways to ask, and they are not equally binding: json_mode only promises valid JSON, not your JSON; function_calling routes the request through the tool-calling machinery, which a local model steers far less firmly than a grammar does (Chapter 13 is a whole chapter of exactly that); and json_schema hands the server the schema to enforce through response_format.2
On a hosted API any of the three usually gets you a parsed object. On a local server, json_schema is the one that holds. And on LM Studio specifically the other two do not hold less firmly, they do not hold at all: the server rejects both before the model ever sees them, json_mode with 'response_format.type' must be 'json_schema' or 'text' and function_calling with Invalid tool_choice type: 'object'.
We spell the argument out even though we would get it anyway: langchain-openai has defaulted method to "json_schema" since 0.3.0, and the book pins 1.7.0. It is written down because it is load-bearing — on an older langchain-openai, or on another chat-model class, the default is "function_calling" and this same line silently changes mechanism. Chapter 2’s preflight.py checks that your server and model can do json_schema at all.
Keep the schema small, too. A weaker local model asked to fill a long, deeply nested schema can run out of room and hand back truncated JSON — valid-looking until it fails to parse. The Decision here is two fields: one Literal and one short string. If you extend it and start seeing parse errors, that is the first thing to cut back — a big schema is a common way to make a small model look broken.
With route guaranteed to be one of search, web, or generate, the agent gets simpler and safer at once:
def agent_node(state: State) -> dict:
docs = state.get("docs", [])
web = state.get("web_results", [])
searched_docs = "docs" in state
searched_web = "web_results" in state
prompt = f"""
You are the router for a documentation question-answering agent.
Decide the single next action from the state below.
Question: {state['question']}
Local documents found so far: {len(docs)}
Web results so far: {len(web)}
Already searched the local docs: {searched_docs}
Already searched the web: {searched_web}
Rules — read them in order and act on the FIRST whose condition is true; once a
rule matches, ignore every rule below it.
1. If you ALREADY have at least one source (local documents found > 0 OR web
results > 0), you have enough -> generate. Do NOT gather more: one source is
enough, even if the web has not been searched yet.
2. else if (already searched the local docs is False) -> search
3. else if (already searched the web is False) -> web
4. otherwise -> generate
Treat "already searched" as final: searching again cannot change a count that is
0, so never repeat a search that was already done."""
decision = decider.invoke(prompt)
print(f"[agent] docs={len(docs)} web={len(web)} -> {decision.route}"
f" ({excerpt(decision.reason)})") # reason trimmed for the trace
return {
"route": decision.route,
"reason": decision.reason,
"iterations": state.get("iterations", 0) + 1,
}Two different things are happening here, and only one of them is a guarantee. The Literal makes the route a legal enum: what reaches State is one of the three values or the call fails in front of you — no third outcome where an unknown string routes the graph. That is a property of the schema — and, on a local server, of the grammar enforcing it. Which legal value the model picks is still steered by the ordered rules in the prompt, and the schema does nothing for it. A weak model handed this schema returns a well-formed wrong answer. Keep the two apart when you read a trace: a parse error is a shape problem, and the schema fixes it; a loop is a choice problem, and the schema can’t.
The wiring is Chapter 7’s:
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", "web": "web_search", "generate": "generate"},
)
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"])
Field(description=...) is a prompt, not a comment
It is easy to read those Field(description=...) strings as documentation for the next programmer. They are also the prompt. When you call with_structured_output, LangChain turns the Pydantic model into JSON Schema and sends it to the model as part of the request. The model reads the descriptions and the class docstring and fills the fields accordingly. Print the schema and you can see the core of what gets sent — LangChain wraps it in a response_format envelope, but your descriptions travel inside it verbatim:
import json
print(json.dumps(Decision.model_json_schema(), indent=2)){
"description": "Choose the next action for a documentation question-answering agent.",
"properties": {
"route": {
"description": "Next action: search=look in the local docs, web=search the open web, generate=write the answer now.",
"enum": [
"search",
"web",
"generate"
],
"title": "Route",
"type": "string"
},
"reason": {
"description": "One short sentence explaining the choice.",
"title": "Reason",
"type": "string"
}
},
"required": [
"route",
"reason"
],
"title": "Decision",
"type": "object"
}
Every natural-language string you wrote is right there in the payload: the class docstring became the object’s description, each Field(description=...) became a field description, and the Literal became an enum. All of it is prompt. So write those descriptions as instructions, not notes — “search=look in the local docs” tells the model what the value means; “the route to take” would tell it nothing. The same is true of a @tool function’s docstring, which you’ll meet in Chapter 13: anything that lands in a schema the model sees is prompt, and deserves the care you’d give a prompt.
12.6 Running it
With the structured agent in place, run the same two questions Chapter 7 used — one the local docs answer, one they don’t:
===== question: How do I configure Kafka batch consumers? =====
[agent] docs=0 web=0 -> search (No sources found yet (0 local, 0 web) and local docs have not been searched, so Rule 2 applies: search local docs first.)
[search_docs] 2 hit(s)
[agent] docs=2 web=0 -> generate (Rule 1 matches: Local documents found is 2, which is greater than 0. Therefore, there is at least one source available, and the agent ...)
[generate] the model wrote an answer
--- answer ---
To configure Kafka batch consumers, set `spring.kafka.listener.type=batch` and tune the `max-poll-records` setting.
===== question: How do I write a Python decorator? =====
[agent] docs=0 web=0 -> search (No sources found yet (0 local, 0 web) and local docs have not been searched, so Rule 2 applies: search local docs first.)
[search_docs] 0 hit(s)
[agent] docs=0 web=0 -> web (No sources found yet (0 local, 0 web). Local docs have already been searched, so per Rule 2, we must search the web next.)
[web_search] falling back to a web search
[agent] docs=0 web=1 -> generate (Rule 1 matches: web results > 0 (1 result found). Sufficient source available to generate the answer.)
[generate] the model wrote an answer
--- answer ---
The provided source is a community thread about the topic, but it does not contain the specific steps or code for writing a Python ...
The Kafka question hits the docs and generates in two hops; the Python question misses, falls back to the web, and generates on the third: the two paths of Chapter 7, with the model’s own reason logged beside each route. That reason field is worth keeping: for a few extra tokens it gives you a human-readable note on each decision, which makes a trace far easier to inspect. (It’s the model’s own after-the-fact explanation, not a window into how it actually decided — treat it as a helpful log line, not proof.)
Look closely at rule 2 and the instruction to treat “already searched” as final. In Chapter 7, telling “searched and found nothing” apart from “haven’t searched yet” was a single trivial check — "docs" in state — and it never misfired. Hand that same judgment to a model and it becomes hard: a model sees found 0 and its instinct is to search again, looping right back to where the weak model got stuck.
The capable model gets it right, and the prompt spells the distinction out anyway. On the model this prompt was first tuned on (Qwen2.5 32B), dropping that sentence made even the capable model re-search an empty result; Qwen3.8 does not need the sentence, and the next model may again.
This is the tax of moving a decision from code into a model. A branch that was exact and free becomes a matter of persuasion — reliable enough with a good model and a careful prompt, but never the dead certainty of an in check. Weigh that before you replace a working if with an LLM call: you are trading guaranteed control for flexibility, and sometimes the if was the right tool.
12.7 Prompt tuning: a rule the model won’t skip
The clean two-hop on the Kafka question — search, then generate — did not come for free either. Rule 1 first read like its three neighbours, a condition and an arrow:
1. If local documents found > 0 -> GENERATE.
On the model this book was first written against — Qwen2.5 32B, the previous generation of the same family — the capable model searched, found two docs, and then, instead of generating, searched the web anyway:
[agent] model said 'SEARCH' -> search
[search_docs] 2 hit(s)
[agent] model said 'WEB' -> web
[web_search] falling back to a web search
[agent] model said 'GENERATE' -> generate
Read as written, the rules are a priority list — rule 1 matches first — but the model treated them as a checklist to finish: it had searched locally, the web was still unsearched, so it kept going. The answer came out right, but it cost an extra hop and a call to a tool it never needed.
The fix is not more clarity about the condition. Four wordings, everything else in the prompt identical, held at the same state — two docs found, the web not yet searched — and, in the last column, the same four wordings put to the book’s current model:
| Rule 1 | Qwen2.5 32B chose | Qwen3.8 27B chose | |
|---|---|---|---|
| 1 | If local documents found > 0 -> GENERATE. |
web | generate |
| 2 | If you ALREADY have at least one source, you have enough -> GENERATE. |
web | generate |
| 3 | …plus the condition: (local documents found > 0 OR web results > 0) |
web | generate |
| 4 | …plus a prohibition: Do not search again, even if the web has not been searched: one source is enough. |
generate | generate |
Rows 2 and 3 make the condition clearer and more explicit, and Qwen2.5 still goes to the web. The clause that moves it is the one in row 4, which names the thing it must not do. Three wordings of the condition left the route where it was; naming the alternative moved it — on this model, across these four prompts. That is the Gotcha above, seen from the other side: a distinction your if got for free has to be said out loud, and saying it in the positive is not enough.
The last column is the other half of the lesson. Qwen3.8 reads rule 1 as a priority rule under all four wordings and stops at the first source every time. The prohibition costs it nothing and buys it nothing. The rule ships with both halves anyway — the spelled-out condition for you, the prohibition for whichever model reads it next — because a prompt that only works on the model you tuned it on is a prompt that breaks on the next one.

So the shipped rule 1 carries both halves:
- If you ALREADY have at least one source (local documents found > 0 OR web results > 0), you have enough -> GENERATE. Do not search again, even if the web has not been searched: one source is enough.
With that, either model stops at the first source:
[agent] model said 'SEARCH' -> search
[search_docs] 2 hit(s)
[agent] model said 'GENERATE' -> generate
The model weighs your rules by how they are phrased; a rule that is easy to skip gets skipped, and the fix is usually a sharper sentence.
On your machine. Every cell in the table above was 5 for 5 at temperature=0, on qwen2.5-32b-instruct-mlx and on qwen/qwen3.8-27b — and the two columns disagree. That is the point: each column is a measurement of one model’s reading, not a property of LangGraph, and a later build of either model may draw the line somewhere else again. What transfers is the method: when a rule gets skipped, change one clause at a time and re-run, rather than rewriting the whole prompt and never learning which word did the work. Tuning the prompt buys reliability with a capable model; it never buys a guarantee, and the weak 7B ignores even the tightened rule (Section 12.4).
This chapter is bound to no vendor, LM Studio included — the book runs local models only to stay free and offline. To prove it, leave the entire graph alone and change just the connection block. Point ChatOpenAI at real OpenAI (drop base_url, and set api_key from your OPENAI_API_KEY environment variable instead of the "lm-studio" placeholder) and pick a hosted model id like "gpt-4o-mini":
import os
llm = ChatOpenAI(api_key=os.environ["OPENAI_API_KEY"], model="gpt-4o-mini",
temperature=0)Re-run the structured doc-bot. The [agent] ... -> route trace comes back from a different provider with no other line of the file changed. Any OpenAI-compatible endpoint (a cloud vendor, a colleague’s server, a different local runtime) is one connection block away.
One caveat for the structured step: with_structured_output(..., method="json_schema") needs an endpoint and model that support JSON Schema response_format. Most hosted providers and LM Studio do; a bare server that only speaks plain chat completions may need method="function_calling" or method="json_mode" instead. That is one argument inside agent; nothing outside the node notices.
12.8 The same shape elsewhere

Nothing in the node’s signature changed when a real model replaced the stub. Everything about how it fails did: it can be slow, it can time out, it can half-answer, and it can come back different on the same input. That gap — between a call that looks local and a call that is not — is the oldest lesson in distributed systems, written down as the fallacies of distributed computing.
There is a second axis that literature never had to cover, and it will cost you more. A remote call fails loudly: a timeout, a 500, a dropped connection, and every one of those is a signal you can retry on. A model call can succeed, return in time, be schema-valid, and still be wrong. No retry detects that, and no circuit breaker opens for it.
12.9 Before moving on
Two habits from this chapter carry through the rest of the book: when an agent misbehaves, read the wiring before you blame the judgment; and the schema guarantees the shape while the prompt steers the choice. One pointer for later: create_agent(response_format=...) in Chapter 13 handles structured output at the agent level, picking a ProviderStrategy or ToolStrategy for you. It reaches the same provider capability with_structured_output uses here, but it is not a wrapper over this call — the agent factory does its own binding, validation and message handling. What this chapter showed is the model-level API.
One thing is left unfinished. The model handle llm is a bare global here. Per-run dependencies — the model, a user_id, a database connection — belong in a typed channel beside State, never inside it. That is a State-schema question, and Chapter 14 settles it.
The model can decide now, but we still enumerated the three legal routes, wired each one to a graph node, and wrote the router that dispatches them. The next chapter hands the deciding to the model too: with LangChain’s @tool and native tool-calling, the model emits a tool call and the framework runs it and loops back — the same doc-bot, with the choice of tool moved into the model while the dispatch loop stays in the framework. We’ll put the two styles side by side and weigh what you gain and what you give up.
New pieces in this chapter
| Piece | Usage |
|---|---|
| Type | |
ChatOpenAI |
LangChain’s chat-model client for any OpenAI-compatible endpoint. ChatOpenAI(base_url=…, api_key=…, model=…, temperature=0); points at local LM Studio — no cloud, no bill |
BaseModel |
Pydantic base class for describing a structured-output schema. class Decision(BaseModel): …; the class docstring travels to the model as the schema’s description |
| API | |
ChatOpenAI.invoke() |
One model call: prompt in, message out. llm.invoke(prompt).content; invoke again (Chapter 1) — but the receiver is new: a model, not a graph |
Field |
Pydantic field carrying a description the model reads. route: Literal[…] = Field(description="search=look in the local docs, …"); a prompt, not a comment |
ChatOpenAI.with_structured_output() |
Bind a schema so calls return a parsed object, never raw text. llm.with_structured_output(Decision, method="json_schema"); the grammar-enforced method, and the one a local server actually holds to |
BaseModel.model_json_schema() |
Dump the JSON Schema that gets sent to the model. Decision.model_json_schema(); print it to see exactly what your descriptions became |
Code in this chapter
| File | What it runs |
|---|---|
code/ch10_real_llm.py |
The Chapter 5 doc-bot with a real model behind every node, routing on with_structured_output instead of parsing free text. |
code/ch10_weak_model.py |
The same program pointed at a weak 7B, which reads the same rules and loops until the fuse blows. |
Challenge
🥉 Bronze — does the schema save the weak model?
Take the structured doc-bot (code/ch10_real_llm.py) and point it at the weak 7B by changing the one model= line to "qwen2.5-vl-7b-instruct". Predict first, then run. route can only ever be one of the three: the schema becomes a grammar the server enforces, and whatever comes back is parsed through the Pydantic class on the way in, so an illegal value would raise rather than arrive. No garbage route, then — but does the run still finish?
Watch the trace and write down what you see. If it loops to GraphRecursionError, you have proved the point in one run: structured output enforced the shape (every route was legal) and did nothing for the choice (the model still picked search on a full result).
On your machine. This 7B looped, 3 runs out of 3, when we last measured it. If yours finishes instead, don’t stop — look at how. Count the sources in the state when it routed generate: a run that escapes the loop by answering from zero sources has not shown better judgment, it has found a different way to be wrong, and the Bronze’s point stands. A run that finishes with sources, on two clean passes, is a genuine disagreement worth writing down: your 7B held the state better than ours did, and the shape/judgment split is a claim to re-test on your own model.
Worked solution with tests: code/answers/ch10_weak_structured.py.
🥈 Silver — grade the docs, don’t just count them
Right now the agent falls back to the web only when search_docs returns zero hits. But a keyword hit isn’t the same as an answer: the docs might mention “Kafka” and still not address the question. Use structured output a second time to tell the difference.
Add a small grade_docs step (a node, or a branch inside agent) that, after a non-empty search, asks the model whether the retrieved docs actually answer the question, and route on that verdict — to the web even though docs were found, or onward when they hold up. This is the document-relevance-scoring idea that RAG leans on in Part III, built entirely from this chapter’s with_structured_output pattern. Hint: a two-field schema — a yes/no and a reason — is plenty.
Prove it with two questions whose keywords both hit the knowledge base: one the docs actually answer (grade yes → straight to generate) and one where the keyword matches but the content doesn’t (grade no → fall through to the web). The trace takes different paths on the strength of a judgment rather than a count, and you added a node and a schema without touching an edge you didn’t mean to.
Worked solution with tests: code/answers/ch10_doc_grader.py.
Model card: https://huggingface.co/Qwen/Qwen3.8-27B.↩︎
On LM Studio that enforcement is llama.cpp grammar sampling for GGUF models and Outlines for MLX models: https://lmstudio.ai/docs/developer/openai-compat/structured-output.↩︎

