AI Hints
Home›LangGraph Tutorial›Agent Practice and Routing
LangGraph · Lesson 38 of 120

Structured Routing

A model decides.

⏱ 2 min read▶ Video at 39:54🎓 Free
Watch this lesson in the LangGraph courseWatch on YouTube ↗Full LangGraph course

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.

Structured Routing
From the video: Structured Routing
  • 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.

model_router.pypython
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"])
Output
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.

keyvalue
Small modelfast and cheap
Literalonly real routes
'other'for misfits
Testtricky 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
Next up: Agents Quiz — test yourself