LangGraph add_conditional_edges 完整详解

LangGraph add_conditional_edges 完整详解

一、基础语法

python

运行

复制代码
workflow.add_conditional_edges(
    source: str,                # 起始节点名
    path_fn: Callable,          # 路由判断函数
    path_map: Dict[str, str]    # 返回值 → 目标节点映射
)

作用:条件分支跳转,同一个节点执行完后,根据函数返回值走不同分支,类似 if/else。

二、参数拆解

  1. source 条件边的起点节点,字符串,如 "analyze"。

  2. path_fn(路由函数 router) 接收完整 state,返回一个字符串(分支标识):

    python

    运行

    复制代码
    def router(state):
        if state["is_quick"]:
            return "quick"
        else:
            return "detailed"
  3. path_map 映射字典 {返回值: 目标节点}

    • key:router 函数返回的字符串
    • value:要跳转的节点名称 所有 router 可能返回的值,都必须在字典里定义,否则报错。

你上一段代码补全示例

python

运行

复制代码
def router(state):
    if state["quick_mode"]:
        return "quick"
    return "detailed"

workflow.add_conditional_edges(
    "analyze",
    router,
    {
        "quick": "quick_node",
        "detailed": "detailed_node"
    }
)

三、两种简写模式

模式 1:显式映射(推荐,可读性高)

python

运行

复制代码
workflow.add_conditional_edges(
    "start",
    branch_func,
    {"a": "node_a", "b": "node_b"}
)

模式 2:隐式映射(返回值 = 节点名,省略字典)

如果路由返回的字符串刚好等于目标节点名,可以不传 path_map:

python

运行

复制代码
workflow.add_conditional_edges("analyze", router)
# 等价于 {"quick":"quick", "detailed":"detailed"}

对应你最初的代码场景,最简写法:

python

运行

复制代码
workflow.add_conditional_edges("analyze", router)

四、完整可运行最小示例

python

运行

复制代码
from langgraph.graph import StateGraph
from typing import TypedDict

# 1. 定义状态
class State(TypedDict):
    content: str
    quick_mode: bool

# 2. 节点函数
def analyze(state: State):
    return state

def quick(state: State):
    print("执行快速流程")
    return state

def detailed(state: State):
    print("执行详细流程")
    return state

# 3. 路由函数
def route_analyze(state: State):
    if state["quick_mode"]:
        return "quick"
    return "detailed"

# 4. 构建图
builder = StateGraph(State)
builder.add_node("analyze", analyze)
builder.add_node("quick", quick)
builder.add_node("detailed", detailed)

# 条件分支核心代码
builder.add_conditional_edges(
    source="analyze",
    path_fn=route_analyze,
    path_map={
        "quick": "quick",
        "detailed": "detailed"
    }
)

# 入口
builder.set_entry_point("analyze")
graph = builder.compile()

# 测试
graph.invoke({"content": "test", "quick_mode": True})
graph.invoke({"content": "test", "quick_mode": False})

五、常见用法拓展

1. 多分支(3 个及以上分支)

python

运行

复制代码
def multi_router(state):
    if state["type"] == "search":
        return "search"
    elif state["type"] == "write":
        return "write"
    return "review"

builder.add_conditional_edges(
    "plan",
    multi_router,
    {
        "search": "search_node",
        "write": "write_node",
        "review": "review_node"
    }
)

2. 条件边指向结束节点 END

python

运行

复制代码
from langgraph.graph import END

builder.add_conditional_edges(
    "check",
    exit_router,
    {"finish": END, "continue": "loop_node"}
)

3. 循环逻辑(自环条件分支)

适合 Agent 多轮思考,判断是否还要继续调用工具:

python

运行

复制代码
def tool_router(state):
    if state["need_tool"]:
        return "tool"
    return "end"

builder.add_conditional_edges(
    "agent",
    tool_router,
    {"tool": "tool", "end": END}
)
# tool执行完再回到agent
builder.add_edge("tool", "agent")

六、常见踩坑

  1. router 返回值不在 path_map 的 key 里 → KeyError 所有可能返回的字符串必须全部写入映射字典。
  2. 节点名写错 path_map 的 value 必须是已经 add_node 注册过的节点。
  3. 路由函数必须接收完整 state 参数,不能无参。
  4. 条件边只能有一个起点,一个 add_conditional_edges 对应一个 source。
相关推荐
Maiko Star8 天前
【HM-LG】Think In LangGraph
langgraph
谙弆悕博士10 天前
多智能体架构详解:层级树状架构(分级主从型)
运维·架构·大模型·agent·多智能体·langgraph·层级树状
Maiko Star10 天前
*【HM-LG】LangGraph基本概念和入门
langgraph
谙弆悕博士10 天前
多智能体架构详解:网状去中心化架构(Mesh对等P2P)
人工智能·架构·去中心化·p2p·多智能体·智能体·langgraph
学无止境小袁同学12 天前
LangGraph 深度指南
语言模型·框架·agent·并发·上下文·langgraph·长期记忆
典学长编程12 天前
LangGraph 快速入门:从 StateGraph 到 ReAct Agent
python·有向图·无向图·langgraph·react agent·stategraph
大可不必了13 天前
06 langgraph运行三要素State Node Edge
langgraph
M--Y14 天前
LangGraph 架构基石:持久化与运行控制
python·langchain·大模型·llm·持久化·langgraph
M--Y15 天前
LangGraph 工作流模式
开发语言·javascript·python·langchain·大模型·llm·langgraph
承渊政道20 天前
LangChainAI应用开发框架【LangChain与LangGraph介绍】
langchain·大模型·langgraph·ai应用开发