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。
相关推荐
Joy T1 天前
Agent 开源项目全景解析(下):LlamaIndex、Dify、FastGPT 与真实工程选型
langchain·开源·框架·agent·springai·langgraph·mcp
寻道码路4 天前
大模型工程化实战(一):概率坍塌的救赎 - 给LLM输出加锁
大模型·agent·langgraph·ai工程化·llm确定性
weixin_471383035 天前
07 LangGraph 集成 RAG
python·langchain·agent·langgraph
Tbisnic6 天前
LangChain的 六大核心组件与 RAG 知识库构建
人工智能·python·ai·langchain·rag·langgraph
zl_dfq7 天前
LangGraph 之 【持久化能力】(线程级\跨会话持久化、重放更新状态、get_state、PostgresSaver、PostgreasStore)
langgraph
梦想画家10 天前
让 Agent 自己跑到终点线:Goal 模式智能体实战
智能体·langgraph·goal模式
喜欢的名字被抢了11 天前
langgraph教程系列-07-让人介入-人在回路
langgraph
糖果店的幽灵11 天前
大模型测评DeepEval快速入门-安全与通用指标详解
人工智能·安全·langgraph·大模型测评·deepeval
喜欢的名字被抢了13 天前
langgraph教程系列-06-让流程可暂停 - 持久化与 checkpoint
agent·langgraph
喜欢的名字被抢了13 天前
langgraph教程系列-05-给 agent 装上手脚 - 工具调用
agent·教程·langgraph