AI Hints
Home›LangGraph Tutorial›Branches and Loops
LangGraph · Lesson 14 of 120

Routing Functions

Decide with code.

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

A routing function can return any label you like. A path map then translates labels into node names. This keeps your routing logic readable, and lets you send some cases straight to the end.

Routing Functions
From the video: Routing Functions
  • Return a label
  • Path map → node
  • Or straight to END

Routing customer messages

Route looks for keywords, and returns a label. Refund, delivery, or other. The path map says which node handles each label. Other goes straight to the end, so nothing is written. Run it. Each message reaches the right team, and the last one gets no reply.

routing.pypython
from typing import TypedDict
from langgraph.graph import StateGraph, START, END

class State(TypedDict):
    message: str
    team: str

def route(s):
    text = s["message"].lower()
    if "refund" in text: return "refund"
    if "deliver" in text or "parcel" in text: return "delivery"
    return "other"

b = StateGraph(State)
b.add_node("refunds", lambda s: {"team": "Refunds team"})
b.add_node("shipping", lambda s: {"team": "Shipping team"})
b.add_conditional_edges(START, route, {"refund": "refunds", "delivery": "shipping", "other": END})
for msg in ["I want a refund", "Where is my parcel?", "Hello!"]:
    print(f"{msg:<22}->", b.compile().invoke({"message": msg}).get("team", "no team"))
Output
I want a refund       -> Refunds team
Where is my parcel?   -> Shipping team
Hello!                -> no team

Routing tips

Routing functions should be quick, and only read the state, never change it. Keep the labels short and clear. You can route straight from start, as we did here. And later, we'll let a model do the routing, for messages too varied for keywords.

keyvalue
Read onlynever change state
Labelsshort and clear
From STARTroute immediately
Latera model routes

Summary

Routing functions return labels, and a path map turns them into nodes, or end. Next, graphs that go round in loops.

Key takeaways
  • Return a label
  • Path map
  • END is allowed
Next up: Loops — going round again