Structured Routing
A model decides.
Keyword routing breaks easily. I'd like my money back doesn't contain the word refund. A model can understand the meaning, and choose the route. Structured output makes its choice reliable.

- Keywords break
- Models understand meaning
- Structured output
A model as the router
The route class allows exactly three values, using literal. The classify node asks the model to pick one, with structured output, and saves it. A conditional edge reads the saved route, and picks the node. Run it. Each message reaches the right team, even without obvious keywords.
from typing import Literal, TypedDict
from pydantic import BaseModel
from langchain.chat_models import init_chat_model
from langgraph.graph import StateGraph, START
class Route(BaseModel):
team: Literal["orders", "books", "refunds"]
router = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0).with_structured_output(Route)
class State(TypedDict):
message: str
team: str
def classify(s): return {"team": router.invoke(f"Which team handles this? {s['message']}").team}
b = StateGraph(State); b.add_node(classify); b.add_edge(START, "classify")
for team in ["orders", "books", "refunds"]: b.add_node(team, lambda s, t=team: {"team": t + " team"})
b.add_conditional_edges("classify", lambda s: s["team"])
for m in ["My parcel hasn't turned up", "Any good fantasy series?", "I'd like my money back"]:
print(f"{m:<28}->", b.compile().invoke({"message": m})["team"])My parcel hasn't turned up -> orders team Any good fantasy series? -> books team I'd like my money back -> refunds team
Model routing tips
Use a small, fast model for routing, at temperature zero. Limit its answer with literal, so it can only choose real routes. Add an other route, for messages that fit nowhere. And test the router with tricky examples.
| key | value |
|---|---|
| Small model | fast and cheap |
| Literal | only real routes |
| 'other' | for misfits |
| Test | tricky wording |
Summary
A model with structured output can route by meaning, not keywords. Literal keeps its choices valid. Next, a quiz on agents.
Key takeaways- with_structured_output
- Literal routes
- Conditional edge