LangGraph1.0智能体开发:选择API

LangGraph提供两种不同的API用于构建智能体工作流:Graph API和Functional API。这两种 API 共享相同的底层运行时环境,且可在同一应用中搭配使用,但它们针对不同的使用场景和开发偏好设计。 本文旨在帮助开发者根据自身具体需求,了解何时应使用哪种API。

一、快速决策指南

当你需要以下功能时,使用图 API(Graph API):

  • 用于调试和文档记录的复杂工作流可视化
  • 支持多节点共享数据的显式状态管理
  • 包含多个决策点的条件分支
  • 后续需合并的并行执行路径
  • 可通过可视化呈现辅助理解的团队协作场景

当你需要以下功能时,使用函数式 API(Functional API):

  • 对现有过程式代码的改动最小化
  • 标准控制流(if/else 条件判断、循环、函数调用)
  • 无需显式状态管理的函数作用域状态
  • 更少模板代码(boilerplate)的快速原型开发
  • 仅含简单分支逻辑的线性工作流

二、详细对比

2.1 何时使用图 API(Graph API)

图API采用声明式方法(declarative approach),通过定义节点(nodes)、边(edges)和共享状态(shared state)来创建可视化的图结构(visual graph structure)。

1. 复杂决策树与分支逻辑

当你的工作流包含多个依赖于不同条件的决策点(decision points)时,图 API 能让这些分支清晰可见,且易于可视化呈现。

python 复制代码
# Graph API: Clear visualization of decision paths
from langgraph.graph import StateGraph
from typing import TypedDict

class AgentState(TypedDict):
    messages: list
    current_tool: str
    retry_count: int

def should_continue(state):
    if state["retry_count"] > 3:
        return "end"
    elif state["current_tool"] == "search":
        return "process_search"
    else:
        return "call_llm"

workflow = StateGraph(AgentState)
workflow.add_node("call_llm", call_llm_node)
workflow.add_node("process_search", search_node)
workflow.add_conditional_edges("call_llm", should_continue)

2. 跨多个组件的状态管理

当你需要在工作流的不同部分之间共享并协调状态时,图 API(Graph API)的显式状态管理(explicit state management)机制将发挥重要作用。

python 复制代码
# Multiple nodes can access and modify shared state
class WorkflowState(TypedDict):
    user_input: str
    search_results: list
    generated_response: str
    validation_status: str

def search_node(state):
    # Access shared state
    results = search(state["user_input"])
    return {"search_results": results}

def validation_node(state):
    # Access results from previous node
    is_valid = validate(state["generated_response"])
    return {"validation_status": "valid" if is_valid else "invalid"}

3. 带同步机制的并行处理

当你需要并行运行多个操作,随后再合并它们的结果时,图 API(Graph API)能自然地处理这一需求。

python 复制代码
# Parallel processing of multiple data sources
workflow.add_node("fetch_news", fetch_news)
workflow.add_node("fetch_weather", fetch_weather)
workflow.add_node("fetch_stocks", fetch_stocks)
workflow.add_node("combine_data", combine_all_data)

# All fetch operations run in parallel
workflow.add_edge(START, "fetch_news")
workflow.add_edge(START, "fetch_weather")
workflow.add_edge(START, "fetch_stocks")

# Combine waits for all parallel operations to complete
workflow.add_edge("fetch_news", "combine_data")
workflow.add_edge("fetch_weather", "combine_data")
workflow.add_edge("fetch_stocks", "combine_data")

4. 团队开发与文档编制

图 API(Graph API)的可视化特性,使得团队更易于理解、记录和维护复杂的工作流。

python 复制代码
# Clear separation of concerns - each team member can work on different nodes
workflow.add_node("data_ingestion", data_team_function)
workflow.add_node("ml_processing", ml_team_function)
workflow.add_node("business_logic", product_team_function)
workflow.add_node("output_formatting", frontend_team_function)

2.2 何时使用函数式 API(Functional API)

函数式 API 采用命令式方法(imperative approach),可将LangGraph功能集成到标准的过程式代码中。

1. 对现有过程式代码的改动最小化

当你已拥有使用标准控制流(standard control flow)的代码,且希望通过最少的重构(minimal refactoring)为其添加 LangGraph 功能时,适合使用函数式 API。

python 复制代码
# Functional API: Minimal changes to existing code
from langgraph.func import entrypoint, task

@task
def process_user_input(user_input: str) -> dict:
    # Existing function with minimal changes
    return {"processed": user_input.lower().strip()}

@entrypoint(checkpointer=checkpointer)
def workflow(user_input: str) -> str:
    # Standard Python control flow
    processed = process_user_input(user_input).result()

    if "urgent" in processed["processed"]:
        response = handle_urgent_request(processed).result()
    else:
        response = handle_normal_request(processed).result()

    return response

2. 具有简单逻辑的线性工作流

当你的工作流以顺序执行为主,且仅包含简单的条件逻辑时。

python 复制代码
@entrypoint(checkpointer=checkpointer)
def essay_workflow(topic: str) -> dict:
    # Linear flow with simple branching
    outline = create_outline(topic).result()

    if len(outline["points"]) < 3:
        outline = expand_outline(outline).result()

    draft = write_draft(outline).result()

    # Human review checkpoint
    feedback = interrupt({"draft": draft, "action": "Please review"})

    if feedback == "approve":
        final_essay = draft
    else:
        final_essay = revise_essay(draft, feedback).result()

    return {"essay": final_essay}

3. 快速原型开发

当你希望快速测试想法,且不想承担定义状态模式(state schemas)和图结构(graph structures)的额外开销时。

python 复制代码
@entrypoint(checkpointer=checkpointer)
def quick_prototype(data: dict) -> dict:
    # Fast iteration - no state schema needed
    step1_result = process_step1(data).result()
    step2_result = process_step2(step1_result).result()

    return {"final_result": step2_result}

4. 函数作用域内的状态管理

当你的状态天然适合限定在单个函数的作用域内,且无需进行大范围共享时。

python 复制代码
@task
def analyze_document(document: str) -> dict:
    # Local state management within function
    sections = extract_sections(document)
    summaries = [summarize(section) for section in sections]
    key_points = extract_key_points(summaries)

    return {
        "sections": len(sections),
        "summaries": summaries,
        "key_points": key_points
    }

@entrypoint(checkpointer=checkpointer)
def document_processor(document: str) -> dict:
    analysis = analyze_document(document).result()
    # State is passed between functions as needed
    return generate_report(analysis).result()

三、组合使用两种API

你可以在同一个应用中同时使用这两种 API。当系统的不同部分有不同需求时,这种方式会非常实用。

python 复制代码
from langgraph.graph import StateGraph
from langgraph.func import entrypoint

# Complex multi-agent coordination using Graph API
coordination_graph = StateGraph(CoordinationState)
coordination_graph.add_node("orchestrator", orchestrator_node)
coordination_graph.add_node("agent_a", agent_a_node)
coordination_graph.add_node("agent_b", agent_b_node)

# Simple data processing using Functional API
@entrypoint()
def data_processor(raw_data: dict) -> dict:
    cleaned = clean_data(raw_data).result()
    transformed = transform_data(cleaned).result()
    return transformed

# Use the functional API result in the graph
def orchestrator_node(state):
    processed_data = data_processor.invoke(state["raw_data"])
    return {"processed_data": processed_data}

四、API间的迁移

4.1 从函数式API迁移至图API

当你的函数式工作流变得复杂时,可按以下方式迁移至图 API:

python 复制代码
# Before: Functional API
@entrypoint(checkpointer=checkpointer)
def complex_workflow(input_data: dict) -> dict:
    step1 = process_step1(input_data).result()

    if step1["needs_analysis"]:
        analysis = analyze_data(step1).result()
        if analysis["confidence"] > 0.8:
            result = high_confidence_path(analysis).result()
        else:
            result = low_confidence_path(analysis).result()
    else:
        result = simple_path(step1).result()

    return result

# After: Graph API
class WorkflowState(TypedDict):
    input_data: dict
    step1_result: dict
    analysis: dict
    final_result: dict

def should_analyze(state):
    return "analyze" if state["step1_result"]["needs_analysis"] else "simple_path"

def confidence_check(state):
    return "high_confidence" if state["analysis"]["confidence"] > 0.8 else "low_confidence"

workflow = StateGraph(WorkflowState)
workflow.add_node("step1", process_step1_node)
workflow.add_conditional_edges("step1", should_analyze)
workflow.add_node("analyze", analyze_data_node)
workflow.add_conditional_edges("analyze", confidence_check)
# ... add remaining nodes and edges

4.2 从图API迁移至函数式API

当对于简单的线性流程而言,你的图结构变得过于复杂时

python 复制代码
# Before: Over-engineered Graph API
class SimpleState(TypedDict):
    input: str
    step1: str
    step2: str
    result: str

# After: Simplified Functional API
@entrypoint(checkpointer=checkpointer)
def simple_workflow(input_data: str) -> str:
    step1 = process_step1(input_data).result()
    step2 = process_step2(step1).result()
    return finalize_result(step2).result()

五、总结

当你需要对工作流结构进行显式控制、处理复杂分支、实现并行处理,或希望借助团队协作优势时,请选择图API(Graph API)。 当你希望以最少的改动为现有代码添加LangGraph功能、处理简单的线性工作流,或需要快速原型开发能力时,请选择函数式API(Functional API)。 两种 API 均提供相同的LangGraph核心功能(包括持久化、流式处理、人机协同、内存管理),但采用不同的范式进行封装,以适配不同的开发风格和使用场景。

相关推荐
好学且牛逼的马43 分钟前
【Java编程思想|15-泛型】
java·windows·python
G***T6911 小时前
Python项目实战
开发语言·python
HAPPY酷1 小时前
Flutter 开发环境搭建全流程
android·python·flutter·adb·pip
___波子 Pro Max.1 小时前
Python中if __name__ == “__main__“的作用
python
黑仔要睡觉1 小时前
Anaconda和Pycharm的卸载
开发语言·python
minhuan2 小时前
大模型应用:LangChain核心组件深度解析:llms与embeddings.3
langchain·embeddings·llms·大模型使用
ZhengEnCi2 小时前
P3H0-Python-os模块完全指南-操作系统接口与文件路径处理利器
python·操作系统
草莓熊Lotso2 小时前
Git 本地操作进阶:版本回退、撤销修改与文件删除全攻略
java·javascript·c++·人工智能·git·python·网络协议
想看一次满天星3 小时前
阿里140-语雀逆向分析
javascript·爬虫·python·语雀·阿里140