AI / LangGraph LangChain Interview questions
How does routing work in LCEL?
Routing in LCEL means directing an input to one of several sub-chains based on a condition. The two main tools are RunnableBranch (declarative) and a plain Python function returning a Runnable (imperative).
RunnableBranch — takes a list of (condition, runnable) pairs and a default. The first condition that evaluates to True determines which runnable handles the input:
from langchain_core.runnables import RunnableBranch router = RunnableBranch( (lambda x: "sql" in x["topic"].lower(), sql_chain), (lambda x: "python" in x["topic"].lower(), python_chain), general_chain, # default ) result = router.invoke({"topic": "How do I write a SQL JOIN?"}) # Routes to sql_chain
Lambda-based routing — a custom function that returns the appropriate runnable based on the classification output from an earlier chain step:
def route(info): if info["topic"] == "science": return science_chain return general_chain full_chain = classify_chain | RunnableLambda(route)
A common production pattern is to first run a fast, cheap classification chain that returns a topic label, then route to specialised chains accordingly. This avoids sending every request through a heavyweight model.
More Related questions...