5  The Agent Decides

The agent node in Chapter 4 was a placeholder: it printed a line and returned {}. Here is the job we promised it — look at the question and choose what happens next. For the first time, the flow branches.

A conditional edge lets the graph pick its next node at runtime. The node still doesn’t jump — it writes a decision into state, and a routing function turns that decision into a destination.

The agent never calls search_docs or generate. It writes one field, route, and stops. A small function reads that field and tells the runtime which edge to take.

5.1 What we’re building

The same bot, with retrieval now optional: a question that needs the docs goes through search_docs; a throwaway greeting skips straight to generate.

flowchart LR
    START(["START"]) --> agent{"agent"}
    agent -.->|route = search| search("search_docs") --> generate("generate")
    agent -.->|route = answer| generate
    generate --> END(["END"])

Two paths leave agent; one is taken each run.

5.2 The state grows

The agent needs somewhere to record its decision, so we add route.

from typing import NotRequired, TypedDict


class State(TypedDict):
    question: str                  # input, set by the caller
    route: NotRequired[str]        # written by agent: "search" or "answer"
    docs: NotRequired[list[str]]   # written by search_docs (only on the search branch)
    answer: NotRequired[str]       # written by generate

docs is now written on one branch only. That comes back to bite us in generate, and we deal with it there.

5.3 The agent makes a decision

The agent reads the question and writes a route. No real model yet; a keyword check stands in for the LLM we wire up in Part II.

def agent_node(state: State) -> dict:
    question = state["question"]

    # Stand-in for an LLM: if the question looks like it needs the docs, search.
    keywords = ("how", "why", "configure", "error", "set up", "install")
    need_search = any(kw in question.lower() for kw in keywords)

    route = "search" if need_search else "answer"
    print(f"[agent] decided: {route}  (question: {question})")

    # Only the decision is written. Where we go next is the router's job.
1    return {"route": route}
1
A state update like Chapter 3’s return {"answer": ...}. The agent’s opinion about what happens next is data, sitting in state until someone acts on it.

5.4 The routing function

That someone is the routing function:

def route_after_agent(state: State) -> str:
    return state["route"]

It is not a node. It reads state, returns a string, and the runtime looks that string up in the mapping to pick the next node. It runs at the tail of agent’s own turn, after agent’s update is merged and before the superstep ends. That timing is why state["route"] is there to read, and why the router never shows up as a step of its own. (It may also return a list of keys, in which case every one of them runs next: a conditional edge can fan out as well as choose. Chapter 10 uses that, alongside Command — see Section 10.6.)

On its own the function does nothing, because nothing calls it. What gives it its job is add_conditional_edges, the one call in the wiring that takes a function where every other edge takes a node name:

builder.add_conditional_edges("agent", route_after_agent, {"search": "search_docs", "answer": "generate"})

Read it as three answers to three questions. After which node? "agent". Who decides? route_after_agent, called with the state as soon as agent’s update has been merged. What does each decision mean? The mapping: the string the router returns is looked up here, and the node it maps to runs next. A plain add_edge("agent", "search_docs") answers only the first question and fixes the answer to the third; this call leaves the third open until run time, and that is the whole difference between a pipeline and a graph that chooses. Section 5.5 puts the call in its place among the other edges.

NoteDeep Dive: why not just decide and jump in one function?

The routing function could inspect question and choose a destination directly, with no route field at all. Keep them apart. The agent stays a question-in, decision-out function you can unit-test with a dict; the router stays a side-effect-free one-liner. And the graph’s shape stays declarative data — the mapping table below — instead of hiding inside an if in a node body, where you won’t see it when you add retry or checkpointing later.

5.5 Wiring the branch

search_docs keeps its Chapter 4 contract — question in, docs out — with the printed line and the document strings tightened a little:

def search_docs_node(state: State) -> dict:
    question = state["question"]
    print("[search_docs] retrieving…")
    docs = [
        f"Config Manual: setup notes for “{question}”",
        f"FAQ: “{question}”",
    ]
    return {"docs": docs}

generate needs one small change, made right after the wiring.

Everything is a normal edge except the one leaving agent, which is the add_conditional_edges call from Section 5.4, now in its place:

from langgraph.graph import StateGraph, START, END

builder = StateGraph(State)
builder.add_node("agent", agent_node)
builder.add_node("search_docs", search_docs_node)
builder.add_node("generate", generate_node)

builder.add_edge(START, "agent")

builder.add_conditional_edges(
    "agent",
    route_after_agent,
    {
        "search": "search_docs",   # decision "search" → run search_docs
        "answer": "generate",      # decision "answer" → skip straight to generate
    },
)

builder.add_edge("search_docs", "generate")
builder.add_edge("generate", END)

graph = builder.compile()

flowchart TD
    START(["START"]) --> agent{"agent"}
    agent -.->|search| search_docs("search_docs")
    agent -.->|answer| generate("generate")
    search_docs --> generate --> END(["END"])

Read the mapping as a switchboard: "search" plugs into search_docs, "answer" plugs into generate and hops over retrieval entirely. The two ordinary edges underneath (search_docs → generate → END) rejoin the branches: whichever way we went, we end up generating an answer.

WarningGotcha: two plain edges make a fan-out, not a choice

It is tempting to “branch” with two ordinary edges:

builder.add_edge("agent", "search_docs")   # NOT a choice —
builder.add_edge("agent", "generate")       # this runs BOTH

That does not pick one. LangGraph treats every plain edge out of a node as unconditional, so it runs search_docs and generate — both branches at once. Worse, generate runs twice, because the search_docs → generate edge is still in place: once immediately from agent with no docs yet, and again after search_docs retrieves, the second run overwriting the first one’s answer. (Fan-out is a useful pattern later in the book; it is just not what you want here.)

To take one of several paths, you need add_conditional_edges and a routing function. Plain edges mean “always”; a conditional edge means “choose.”

5.6 Generating from either branch

Branching leaves generate reachable with or without docs — on the answer path, search_docs never ran.

def generate_node(state: State) -> dict:
    # absent on the "answer" branch: nothing wrote it
1    docs = state.get("docs", [])
    if docs:
        body = "\n".join(f"  - {d}" for d in docs)
        answer = f"(from the docs)\n{body}"
    else:
        answer = f"(answered directly) I can help with: {state['question']}"
    print("[generate] writing the answer")
    return {"answer": answer}
1
A plain state["docs"] would raise KeyError on the answer branch; .get hands back an empty list instead and generate adapts.

Chapter 4 cured the same symptom by reordering the edges. Here you can’t — the answer branch is supposed to skip search_docs. Once a field is written on only some paths, every downstream reader must cope with its absence.

5.7 Running it

We run two questions through the same graph and watch them take different paths.

if __name__ == "__main__":
    for q in ["How do I configure Kafka in Spring Boot?", "Hello there!"]:
        print(f"\n===== question: {q} =====")
        result = graph.invoke({"question": q})
        print("answer:", result["answer"])

===== question: How do I configure Kafka in Spring Boot? =====
[agent] decided: search  (question: How do I configure Kafka in Spring Boot?)
[search_docs] retrieving…
[generate] writing the answer
answer: (from the docs)
  - Config Manual: setup notes for “How do I configure Kafka in Spring Boot?”
  - FAQ: “How do I configure Kafka in Spring Boot?”

===== question: Hello there! =====
[agent] decided: answer  (question: Hello there!)
[generate] writing the answer
answer: (answered directly) I can help with: Hello there!

The second run has no [search_docs] line. The router sent "Hello there!" straight to generate.

TipTry it: flip the route, then teach a new trigger

Try "Deploy this service": with the current keywords it routes to answer. Add "deploy" to keywords, re-run the same question, and watch it switch to search. No edge changed — the decision logic lives in the node.

5.8 What we learned

  • A conditional edge chooses the next node at runtime, from a routing function’s return value: add_conditional_edges(source, router, path_map). The deciding node still doesn’t jump — it writes route and returns.
  • Plain edges fan out; conditional edges choose. Two ordinary edges out of a node run both targets. (A router that returns a list of keys fans out too; Chapter 10 uses that.)
  • Optional fields need defensive reads. Once docs is written on only one branch, generate must use state.get("docs", []), not state["docs"].

The graph can now choose, but only ever moves forward. Next we let an edge point backward. The graph loops, so the agent can act, look at the result, and decide whether to go around again — the act-observe-retry shape most agents take.

New pieces in this chapter

Piece Usage
API
StateGraph.add_conditional_edges() Pick the next node at runtime from a routing function’s return value. builder.add_conditional_edges("agent", route_after_agent, {…}); plain edges fan out — only this chooses (and, returning a list of keys, it can fan out too)
add_conditional_edges(path_map=…) Third argument (path_map) mapping each possible routing-function return value to a destination node. {"search": "search_docs", "answer": "generate"}; an unmapped return value raises KeyError at run time

Code in this chapter

File What it runs
code/ch03_conditional_edges.py The agent writes a decision, a routing function reads it, and a conditional edge turns it into the next node.

Challenge

🥉 Bronze — add a third branch

Give the agent a clarify route for questions too short to act on — empty, or under a few characters — which deserve neither a search nor a direct answer.

Add a clarify node that asks the user to rephrase, one more entry in the mapping table, and an edge from clarify to END. Three destinations now, and the two that already worked are untouched.

Confirm all three paths with "", "Thanks a lot!", and "How do I configure X?".

office hours Worked solution with tests: code/answers/ch03_three_way_route.py.

🥈 Silver — handle an unknown route

Have the agent write "Search" (capital S) — a string that isn’t a key in the mapping — and the graph raises KeyError at run time. Now guard against it: fold any unrecognized decision back to a safe default.

Once a real LLM writes route in Part II, it can emit a label you didn’t map. Structured output (Chapter 12) narrows the odds but doesn’t remove them, and this one line is the difference between a fallback and a crash.

office hours Worked solution with tests: code/answers/ch03_safe_router.py.