Generative AIby Dhruv Narang

The Problem: Not Every Path Is Straight

Sometimes the next step depends on what happened.

The issue
After the reviewer, the graph must either stop or go back to the writer.
The first try
A normal edge from reviewer to writer: the graph loops forever. A normal edge to END: it never loops.
Why it fails
A normal edge always goes to the same place. The right path depends on the state: is the post approved?
The fix
A conditional edge: a small function reads the state and says where to go next.

Conditional Edges: A Router Function

A normal edge always goes to the same place. A conditional edge asks a function where to go.

def quality_gate(state:State):
    if state["is_approved"]:
        return END
    elif state["attempt"] >=3:
        return END
    else:
        return "writer"

graph.add_conditional_edges("reviewer",quality_gate)
STARTwriterreviewerENDapproved, or 3 attempts: ENDotherwise: back to writer
The function
Reads the state and returns the name of the next node, or END.
Conditional edge
add_conditional_edges("reviewer", quality_gate): after reviewer finishes, call quality_gate and go where it says.
In your loop
Approved, or 3 attempts used: END. Otherwise: back to writer.
The code is from your 01_iterative.py. The full loop is built in the Loops lesson.

One Source, Many Paths

The same call can choose between more than two paths.

def route_query(state:State) -> str:
    """Traffic officer: routes to academic_rag, fee_rag, or general."""
    if state["query_type"] == "academic":
        return "academic_rag"
    elif state["query_type"] == "fee":
        return "fee_rag"
    else:
        return "general"

workflow.add_conditional_edges("classifier", route_query)
workflow.add_edge("academic_rag", "response")
workflow.add_edge("fee_rag", "response")
workflow.add_edge("general", "response")
STARTclassifierroute_queryacademic_ragfee_raggeneralresponseEND
The router
route_query returns academic_rag, fee_rag or general. The same call handles three paths.
Back together
The three paths each have a normal edge to one response node.
The code is from your 01_conditional_rag.py. You will build it in the Conditional RAG lesson.

Quick Revision

The whole lesson on one page.

Nodes
add_node(name, function)
A node is a function with a name. The arrows use the name.
Edges
add_edge, and conditional edges
add_edge(from, to) is always the same path. A conditional edge asks a function which node is next. START and END mark the ends.
Run it
compile, then invoke
compile() makes the app. invoke(state) runs it and returns the final state.
LangGraph docsGraph API