LCEL & ChainsLesson 5

Route Between LLMs

Multi-LLM Workflows called mini, then gpt-4o on every invoke. This lesson calls one or the other. Tags in COMPLEX_TAGS (form, table, …) go to detail_chain with gpt-4o. Everything else goes to simple_chain with mini. RunnableBranch picks the path.

Compared to Multi-LLM Workflows

Last lesson ran pick and explain back to back. This lesson checks tag first and runs one chain.

Multi-LLM Workflow

pick_chain  →  mini
explain     →  gpt-4o

Both steps run every time.

Route Between LLMs

if tag in COMPLEX_TAGS:
    detail_chain  →  gpt-4o
else:
    simple_chain  →  mini

One branch per invoke.
Multi-LLM runs both steps. Here only one chain runs per invoke.

RunnableBranch

List (condition, chain) tuples, then pass the default chain last. First True condition wins. LangChain routing docs.

Input with tag=form:

input

{ "tag": "form" }

condition

tag in COMPLEX_TAGS?

yes

detail_chain

gpt-4o

no

simple_chain

gpt-4o-mini

form is in COMPLEX_TAGS, so detail_chain runs. simple_chain does not.

simple_chain and detail_chain

Two separate pipes: short prompt + mini, longer prompt + gpt-4o. The router passes {"tag": "..."} to whichever chain matches.

TagBranchModel
a, p, imgsimple_chaingpt-4o-mini
form, table, selectdetail_chaingpt-4o
Edit COMPLEX_TAGS in the script to change which tags use gpt-4o.
route_between_llms_demo.py
"""route_between_llms_demo.py"""
from langchain_core.runnables import RunnableBranch
simple_chain = simple_prompt | mini | parser
detail_chain = detail_prompt | pro | parser
router = RunnableBranch(
(lambda x: x["tag"] in COMPLEX_TAGS, detail_chain),
simple_chain,
router.invoke({"tag": "form"})

Run the script

venv active, from the project folder:

python route_between_llms_demo.py
PowerShell — (.venv) active
(.venv) PS C:\projects\langchain-course> python route_between_llms_demo.py
tag=a
The <a> tag links to another page.
tag=form
The <form> tag holds inputs and a submit button. action sets the URL. Example: <form action="/search">…</form>
tag=p
The <p> tag wraps a paragraph.
tag=table
<table> holds rows (<tr>) and cells (<td>). Example: <table><tr><td>Name</td></tr></table>
a and p hit mini. form and table hit gpt-4o.

route_between_llms_demo.py

RunnableBranch — mini or gpt-4o

Download .py
Save into your project folder from Project Setup.

What's Next

Next lesson: Output Formatting (StrOutputParser and PydanticOutputParser).