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。
相关推荐
一只小bit5 小时前
LangGraph 子图使用和房源搜索Agent综合案例实现
机器学习·langchain·llm·langgraph
糖果店的幽灵1 天前
langgraph的 MessagesState 解读
java·开发语言·人工智能·windows·langgraph
辞忧九千七1 天前
MCP 协议完全指南:从原理到 LangGraph 集成,打造即插即用的 AI Agent 工具生态
agent·langgraph·mcp
糖果店的幽灵2 天前
langgraph分支之 - 动态分支(Dynamic Branch)
java·前端·javascript·人工智能·langgraph
一只小bit3 天前
LangGraph 记忆、人机交互、时间旅行和核心能力
机器学习·langchain·人机交互·langgraph
糖果店的幽灵3 天前
【langgraph 从入门到精通graphApi 篇】综合实战 —— 智能客服 Agent实战代码解读
人工智能·langgraph
糖果店的幽灵3 天前
langgraph的分支结构之 - 静态分支详解
java·服务器·数据库·langgraph
糖果店的幽灵3 天前
langgraph的四种state解析
java·前端·javascript·langgraph
糖果店的幽灵4 天前
【DeepAgents 从入门到精通】Context Management 上下文管理
java·人工智能·后端·spring·中间件·langgraph·deepagents
糖果店的幽灵5 天前
【langgraph 从入门到精通graphApi 篇】Checkpoint 持久化与状态管理
人工智能·langgraph