AI Hints
Home›LangChain Tutorial›Passthrough, Routing, Fallbacks
LangChain · Lesson 23 of 120

Routing

Choosing a path.

⏱ 2 min read▶ Video at 24:07🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

Customers ask Riverside Books very different things. Some ask about orders, and some want book recommendations. Each kind of question deserves a different prompt. Routing sends each input down the right path.

Routing
From the video: Routing
  • Orders or recommendations
  • Different prompts
  • Route each question

A model-powered router

First, a small chain classifies the question as orders or books. Then a normal Python function picks the right chain for that label. Run it. The question about a parcel goes to the orders chain, and the request for a thriller goes to the books chain. Each answer has the right style.

router.pypython
from langchain.chat_models import init_chat_model
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

model = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
make = lambda t: ChatPromptTemplate.from_template(t) | model | StrOutputParser()

classify = make("Is this about 'orders' or 'books'? One word.\n{q}")
orders = make("You handle orders. Reply in one calm sentence: {q}")
books = make("You recommend books. One plain line: title - a 6-word pitch. {q}")

def route(q):
    label = classify.invoke({"q": q}).strip().lower()
    chain = orders if "order" in label else books
    return label, chain.invoke({"q": q})

for q in ["Where is my parcel?", "I want a gripping thriller."]:
    print(route(q))
Output
('orders', 'Your parcel is currently in transit and is scheduled to arrive by the
estimated delivery date provided in your tracking information.')
('books', 'The Silent Patient - Trapped mute wife hides murderous truth.')

Ways to route

There are a few ways to route. Simple keyword rules, which are fast and free. A model as a classifier, as here, which understands meaning. Or a structured output classifier, which we'll meet soon, and which always returns a valid label. Agents, later in the course, take routing even further.

keyvalue
Rulesfast, free, brittle
Model classifierunderstands meaning
Structured labelsalways valid
Agentschoose tools themselves

Summary

Routing classifies the input, then sends it to the right chain. A plain Python function can do the choosing. Next, coping when model calls fail.

Key takeaways
  • Classify
  • Pick a chain
  • Answer in the right style
Next up: Fallbacks and Retries — when calls fail