AI Hints
Home›LangGraph Tutorial›Safe Loops and Practice
LangGraph · Lesson 18 of 120

Practice: Order Router

Branches.

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

Let's practise. A customer message arrives. If it mentions stock, check the shelf. If it mentions a refund, send it to the refunds team. Otherwise, say we'll reply soon. One graph, three branches.

Practice: Order Router
From the video: Practice: Order Router
  • One message
  • Three branches
  • Practise routing

The order router

Route picks a branch from keywords. The stock branch finds a book title in the message, and checks the shelf. The refund and fallback branches write fixed replies. Run it. Each message takes its own branch, and gets a sensible reply.

order_router.pypython
from typing import TypedDict
from langgraph.graph import StateGraph, START
STOCK = {"Dune": 3, "Circe": 0, "Emma": 5}

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

def route(s):
    m = s["message"].lower()
    return "stock" if "stock" in m else "refund" if "refund" in m else "fallback"
def stock(s):
    title = next((t for t in STOCK if t.lower() in s["message"].lower()), None)
    return {"reply": f"{title}: {STOCK[title]} in stock" if title else "Which book?"}
b = StateGraph(State); b.add_node(stock); b.add_conditional_edges(START, route)
b.add_node("refund", lambda s: {"reply": "Passed to our refunds team."})
b.add_node("fallback", lambda s: {"reply": "Thanks! We'll reply soon."})
for m in ["Is Emma in stock?", "I need a refund", "Do you do gift wrap?"]:
    print(f"{m:<22}->", b.compile().invoke({"message": m})["reply"])
Output
Is Emma in stock?     -> Emma: 5 in stock
I need a refund       -> Passed to our refunds team.
Do you do gift wrap?  -> Thanks! We'll reply soon.

What you practised

You used a state, nodes, a routing function from start, and lambdas for tiny nodes. Try adding a delivery branch, or a loop that asks again when the title is missing.

keyvalue
Routefrom START
Nodesstock, refund, fallback
Lambdasfor tiny nodes
Trya delivery branch

Summary

One routing function sent each message down the right branch. Next, reducers, which control how updates combine.

Key takeaways
  • Route by keyword
  • Three branches
  • Sensible replies
Next up: Reducers — combining updates