Course Content
LangChain Mastery
7 sections · 109 lessons
How do you implement a chain with dynamic routing in LangChain?
What you need to know
1from typing import Literal2from pydantic import BaseModel3from langchain_core.runnables import RunnableLambda, RunnablePassthrough45class Route(BaseModel):6 topic: Literal["billing", "technical", "other"]78router = router_prompt | small_llm.with_structured_output(Route)910def pick_chain(x: dict):11 return {"billing": billing_chain,12 "technical": tech_chain}.get(x["route"].topic, general_chain)1314routed = RunnablePassthrough.assign(route=router) | RunnableLambda(pick_chain)15routed.invoke({"question": "I was charged twice for March"})- The router uses a small, fast model; classification is an easy task.
Literallimits the output to three labels, so the model cannot return "Billing issue" or "refunds".pick_chainreturns a Runnable, and LangChain invokes it with the same input. The.get(..., general_chain)default catches anything unexpected.
The RunnableBranch form
1from langchain_core.runnables import RunnableBranch23branch = RunnableBranch(4 (lambda x: x["route"].topic == "billing", billing_chain),5 (lambda x: x["route"].topic == "technical", tech_chain),6 general_chain, # default, required7)8routed = RunnablePassthrough.assign(route=router) | branchConditions are checked in order; the first true one wins. It is more verbose than a function but shows the routes clearly in one place.
Other ways to route
| Method | When |
|---|---|
| LLM classifier (above) | Topics need understanding of the text |
| Embedding similarity to example questions | Many routes, low latency, no extra LLM call |
| Plain rules (keywords, user plan) | The signal is simple and exact |
| An agent choosing tools | The path depends on results, not just the question |
A real-life example
A real-estate firm's WhatsApp assistant receives enquiries for new flats, resale, rentals and home loans. One general prompt handled all of them and often quoted new-project prices to people asking about rent. The team added a router with five labels (new_project, resale, rental, home_loan, other), each routed to its own prompt and listings retriever. The router runs on a small model and adds about 250 milliseconds. On 600 labelled messages, routing accuracy was 94%; most errors were rental versus resale, so the team added examples of both to the router prompt. The other route sends the chat to a human agent, which catches roughly 4% of messages.
Follow-up questions to expect
- "What happens if the router is wrong?" — The wrong chain answers; reduce this with a default route, a confidence threshold that sends unsure cases to a general chain, and regular checks of logged routes.
- "
RunnableBranchor a function?" — Both work; a function returning a Runnable is shorter and easier to read with many routes. - "Router or agent?" — A router decides once at the start; an agent decides repeatedly as it goes. Use a router when one decision is enough.