How to run several LangGraph graphs behind a single chat endpoint, letting an LLM decide which one handles each turn, and handing control back when a structured flow finishes.
Everything below was measured against langgraph 1.2.9 in this repo. Where a claim was checked, the check is described — several of these behaviours are the opposite of what the documentation led me to expect.
Working implementation: app/graphs/supervisor.py. Endpoint: POST /api/chat.
user: what is 2+2?
bot : 4 <- free chat, LLM answers
user: I want to buy car insurance
bot : Step 1 of 4 — which car are we insuring? <- LLM classified intent, handed off
user: 2019 Volvo XC40
bot : Step 2 of 4 — how many years have you held a full licence?
...
user: monthly
bot : All four steps done. 2019 Volvo XC40, 12 years licensed, comprehensive cover,
paying monthly. <- flow finished, control handed back
user: what car did I just insure?
bot : 2019 Volvo XC40 <- free chat again, with the flow's
result in the model's context
One endpoint, one thread_id, three graphs. The user never picks a mode.
Four independent choices. This repo's pick is marked, but none of them is the only defensible answer.
| Option | Trade-off |
|---|---|
| LLM intent classification ← chosen | Natural — "sort out my motor cover" works. But on a 4-bit local model the classifier is unreliable, so it needs a forgiving parse and a fallback. |
| Keyword match | Deterministic, free, debuggable. Never fires on phrasing you did not anticipate. |
| Both — keywords first, LLM fallback | Best accuracy. Two routing paths to reason about when something misroutes. |
Explicit commands (/insurance) |
Zero ambiguity, no model call. Not conversational. |
The classifier here is deliberately forgiving:
answer = str(reply.content).strip().lower()
for label, mode in INTENTS.items():
if label in answer: # substring, not equality
return mode
return None # unrecognised -> free chatA 4-bit model will not reliably emit a bare label. Demanding exact output would turn a one-turn misroute into a crash. There is a test for the case where the model replies with something unparseable.
| Option | Trade-off |
|---|---|
| Free chat from message one ← chosen | Cleanest supervisor demo. Any gate would swallow the first message before the router ever saw it. |
| A mandatory gate first (e.g. collect a name) | Preserves an onboarding step, but the gate competes with the router for message one. |
| Make the gate a flow like any other | Most consistent — every flow triggers on intent. Changes the app's opening behaviour entirely. |
| Option | Trade-off |
|---|---|
| Hand back to free chat ← chosen | The full round trip. Requires the flow's result to reach the model's context, which is a real design constraint (see below). |
| Stay in the flow, replaying its summary | Simpler; the handoff only goes one direction and never returns. |
| Option | Verdict |
|---|---|
| Parent graph, flows as subgraphs ← chosen | Idiomatic LangGraph. Works, but only with the state-sharing rule below, which is not obvious. |
| Dispatcher above LangGraph (pick a compiled graph per request in the HTTP layer) | Keeps graphs completely independent. But each graph has its own message history, so a finished flow's result never reaches the chat model's context. That kills decision 3. |
| One flat graph, flows as node groups | No subgraph subtleties at all. The flows stop being separately reusable graphs. |
interrupt() inside each flow |
The textbook human-in-the-loop pattern. Requires resuming with Command(resume=...), so the API must distinguish a fresh message from a resume and the frontend must track which state it is in. Rejected for the same reason the original spec rejected it. |
There is nothing to click and no command to type. Every message goes to the router when no flow is already running, and the model classifies it.
Measured against Qwen3-VL-8B-Instruct-MLX-4bit through POST /api/chat:
| Message | Lands in |
|---|---|
| "I want car insurance" | insurance |
| "sort out my motor cover" | insurance |
| "insure my car" | insurance |
| "quote me for the volvo" | insurance |
| "here is my address" | address |
| "I moved house" | address |
| "what is 2+2?" | free chat |
Two of those are the reason to prefer an LLM classifier over keyword matching: "sort out my motor cover" and "quote me for the volvo" both route correctly and neither contains the word insurance. No keyword list written in advance would have caught them.
The reply is matched by substring, not equality:
answer = str(reply.content).strip().lower()
for label, mode in INTENTS.items():
if label in answer: # tolerates "The answer is INSURANCE."
return mode
return None # nothing matched -> free chatTo change what triggers a flow, edit CLASSIFY_PROMPT and INTENTS in
app/graphs/supervisor.py. That is the entire surface.
Measured misroute: "where do I live?" enters the address flow, which then starts asking for your street address. The user asked a question about stored data; the classifier saw the topic "address" and handed off.
This is not a tuning problem so much as a category error in the approach — a one-word classification cannot distinguish "I want to give you X" from "tell me about X". Mitigations, none implemented here:
- Have the classifier emit an intent and a direction (
PROVIDEvsQUERY). - Confirm before entering a flow: "Sounds like you want to update your address — start now?"
- Only enter a flow from an explicit affirmative, treating classification as a suggestion.
This is the sharpest edge in the current design, and it compounds the misroute above.
route_entry returns state.mode or "router", so once a flow has control the router is
skipped entirely. Every subsequent message is fed to the flow. Typing "never mind" during
the address flow does not cancel anything — it gets banked as your street address.
The only exits are completing the flow, or starting a new thread (reloading the page).
Fixing it means checking for cancel intent before the flow runs, which puts a model call
back on every in-flow turn — the cost the mode shortcut exists to avoid. A cheap
compromise is a literal keyword check (cancel, stop, never mind) in route_entry,
deterministic and free, at the cost of making those words unusable as answers.
Each of these was hit for real while building this. Every one produced passing tests and broken behaviour, or the reverse.
This is the big one.
The appeal of subgraphs is that a child can keep fields the parent never declares. That is true within one invocation. It is false across turns:
A subgraph that runs to
ENDis re-entered fresh next time. Fields the parent does not declare have nowhere to live in the parent's checkpoint, so they are gone.
Symptom: the flow restarts from step one on every turn, while every standalone test of that flow passes, because standalone it has its own checkpointer.
Fix: the parent state must declare every field the flows need to persist. Here the supervisor inherits them:
class SupervisorState(CarInsuranceState, AddressState):
mode: Mode | None = None
...This is why sharing everything is load-bearing rather than lazy. If you genuinely need
private child state across turns, you need interrupt() so the subgraph stays suspended
rather than completing.
Once the parent inherits every flow's state, two flows that both call a field awaiting
silently become one field, and answering one flow drives the other.
Fix: namespace per flow — insurance_step, address_field. Same for properties:
is_complete on both flows resolved by MRO to whichever came first in the bases list, which
is a bug that type checkers will not catch. They are now insurance_complete and
address_complete.
astream(...) |
Chunks emitted from inside a subgraph |
|---|---|
| default | 0 |
subgraphs=True |
all of them, namespaced ns=('insurance:<uuid>',) |
Without the flag, every handed-off flow renders as a blank reply in the browser while
the graph runs perfectly and all tests pass. See app/routers.py.
The classifier is an LLM call like any other, so stream_mode="messages" emits it — and the
user sees the word INSURANCE appear in the chat before the real reply.
Fix: filter on node name in the SSE generator.
SILENT_NODES = {"router"}
...
if metadata.get("langgraph_node") in SILENT_NODES:
continueThere is a test asserting the classification never reaches the browser.
A correction to a belief that shaped the earlier design in this repo. It is often said that
stream_mode="messages" emits only real LLM tokens. In langgraph 1.2.9, an AIMessage
appended to the messages channel by a node is also emitted.
That is useful — a summary appended for context streams to the user for free — but it means
writing the same text to both get_stream_writer() and messages emits it twice. That
bug shipped here and was only caught by driving the real server.
Rule of thumb used in this repo:
- Prompts and progress →
get_stream_writer(), never intomessages. They are UI text; keeping them out means the model's context stays clean. - Results that the model must remember → append to
messagesonly. They stream anyway.
┌──────────────────────────────┐
POST /api/chat ──▶│ supervisor (parent graph) │
│ state: messages, mode, │
│ + every flow's fields│
└──────────────┬───────────────┘
│
mode set? ────────────┼──────────── no ──▶ router (LLM classify)
│ │ │
│ │ ┌─────┴─────┬──────────┐
▼ ▼ ▼ ▼ ▼
(stay in flow) insurance ◀─────────── chat address (fallback)
│ │ │
flow_complete? │ │
│ │ ▼ │
finish END END END
│ (awaiting user)
▼
mode = None
(back to free chat)
Key rules encoded in the routing:
- A flow in control keeps it.
route_entryreturnsstate.mode or "router", so the router never re-classifies mid-flow. Without this, answering "comprehensive" during step 3 gets classified as a fresh intent. - A finished flow is not re-enterable.
route_after_routerchecks completion and falls through to chat. Without this, saying "what car did I just insure?" re-enters the completed quote and replays its summary instead of answering the question. - Completion is signalled by a shared key. A flow sets
flow_complete; thefinishnode clears it along withmode.
- Write the graph in
app/graphs/<name>.pywith its own Pydantic state. Namespace any field that might collide (<name>_step, notawaiting). - Give it a
flow_complete: boolfield and set it when done. - Append its result to
messageswhen finished — that is what puts it in the model's context after handoff. Do not also write it to the stream writer. - Accept
checkpointer=Noneinbuild_graphso it inherits the parent's when mounted. - Add the state to
SupervisorState's bases, the label toINTENTS, the node to the graph, and the completion property to thedonemap inroute_after_router. - Extend
CLASSIFY_PROMPTwith the new label.
Step 5 is the awkward one: five edits in the supervisor for one flow. That is the honest cost of the merged-state approach, and it is the first thing that would need addressing if this grew beyond a handful of flows.
- No
interrupt(), so flows cannot be paused mid-node — only between turns. - No cancellation. A flow can only be escaped by completing it — see "There is no way out of a flow" above. Worth adding before real use.
- No confidence threshold. The classifier's answer is taken as-is; there is no "did you mean?" confirmation step before entering a flow, which is what makes the topic-vs-intent misroute above land the user in a flow they did not ask for.
- Classification costs a model call on every free-chat turn, doubling latency and load versus a keyword pre-filter.