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.
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_modelfrom langchain_core.prompts import ChatPromptTemplatefrom langchain_core.output_parsers import StrOutputParsermodel = 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.')
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.