Route between actions
Every turn starts with the same question: what is the user trying to do? An intent router answers that with one small LLM call and writes the answer into state["intent"]. Everything downstream reads that field to decide which branch of the graph runs.
The intent router as a graph entry point
The router is the one node every turn hits first. Conditional edges send the turn to the right branch based on state["intent"].
async def intent_router(state: BookingState) -> BookingState:
system = (
"You classify patient messages for a healthcare booking assistant. "
"Respond with strict JSON: {\"intent\": one of "
"[book, list, cancel, smalltalk, unknown]}."
)
prompt = (
"Message: "
+ state.get("user_message", "")
+ "\nReturn JSON only."
)
data = await _llm_json(prompt, system)
intent = data.get("intent") or "unknown"
state["intent"] = intent
_record_event(state, "intent_router", {"intent": intent})
return stateThe router prompt lists allowed intents and demands JSON. The node writes one slot (intent), records one event for tracing, and returns. No branching logic lives inside the node. Routing is the graph layer's job.
def route_from_intent(state: BookingState) -> str:
intent = state.get("intent")
if intent == "book":
if state.get("symptom"):
return "match_specialty"
return "collect_symptoms"
return "smalltalk"
graph.add_conditional_edges(
"intent_router",
route_from_intent,
{
"collect_symptoms": "collect_symptoms",
"match_specialty": "match_specialty",
"smalltalk": "smalltalk",
},
)The routing function is pure Python. It reads state["intent"] and returns the name of the next node. LangGraph wires that return value to a real node through the add_conditional_edges mapping.
Because plain text responses drift. "Sure, I think the user wants to book an appointment." is not parseable. JSON with a known key and a known value set is parseable, loggable, and easy to validate. It also lets you extend the contract later, for example adding a confidence score, without rewriting the parser.
Quiz: Quiz
Loading practice…