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。
相关推荐
新知图书15 小时前
RAG之生成技术
人工智能·agent·ai agent·智能体·langgraph
新知图书18 小时前
智能体基础架构
人工智能·agent·ai agent·智能体·langgraph
伊布拉西莫21 天前
LangGraph State / Config / Input / Output Schema 深度解析
langgraph
茉莉玫瑰花茶24 天前
综合案例 - AI 智能租房助手 [ 4 ]
数据库·python·ai·langgraph
眠りたいです25 天前
LangChainv1:agent快速上手与中间件认识
人工智能·python·中间件·langchain·langgraph
张彦峰ZYF1 个月前
LangGraph Tool Calling 入门:从 @tool 到完整调用链
人工智能·大模型·agent·langgraph·tool calling
骑士雄师1 个月前
13.如何根据Rannable对象创建工具
langgraph
Irissgwe1 个月前
十、LangGraph能力详解:工作流的常见模式
python·langchain·ai编程·工作流·langgraph
Irissgwe1 个月前
十、LangGraph能力详解:LangGraph 的其他特性
python·ai·langchain·langgraph