1. LangGraph框架概述与核心价值
LangGraph作为2025-2026年大模型开发领域的重要框架,其核心设计理念是将复杂的工作流建模为有向图结构。这种设计模式特别适合处理需要多步骤协作、状态管理和动态决策的AI应用场景。与传统的线性流程相比,LangGraph提供了更灵活的流程控制和更强大的状态管理能力。
在实际开发中,我发现LangGraph尤其擅长解决以下几类问题:
- 复杂对话系统:需要维护对话历史、上下文状态的多轮交互场景
- 工具调用链:需要按特定顺序调用多个工具并处理中间结果的流程
- 人工审核流程:需要在自动化流程中插入人工干预点的业务场景
- 多代理协作:需要协调多个专业Agent共同完成复杂任务的系统
需要模型API调用? 免费领10W Token,多模型网关一键接入 Claude、DeepSeek 等主流模型。
2. 环境配置与版本管理
2.1 安装与验证
在开始使用LangGraph前,需要确保Python环境版本≥3.8。以下是推荐的安装命令组合:
bash复制# 基础包(必须)
pip install langgraph==1.0.8 langchain-core==1.0.0 langchain-openai==1.0.0
# 可选组件(按需安装)
pip install langchain-anthropic==1.0.0 # 如需使用Claude模型
pip install langgraph-supervisor==1.0.0 # 多代理协调功能
pip install langchain-community==1.0.0 # 社区贡献的工具和集成
版本验证是项目启动的关键步骤。我建议创建专门的验证脚本:
python复制# version_check.py
import langgraph, langchain_core
print(f"LangGraph: {langgraph.__version__}") # 应输出1.0.8
print(f"LangChain Core: {langchain_core.__version__}") # 应输出1.0.0
2.2 开发环境建议
根据我的项目经验,推荐以下开发配置:
- IDE:VS Code + Jupyter插件(适合交互式调试)
- 调试工具:LangSmith(官方可视化调试平台)
- 版本控制:使用requirements.txt严格锁定依赖版本
- 测试策略:为每个Node编写单元测试,利用Checkpointing功能保存测试状态
3. 核心概念深度解析
3.1 状态(State)设计模式
State是LangGraph中最重要的数据结构之一。良好的状态设计能大幅提升工作流的可维护性。以下是经过实战验证的设计模式:
python复制from typing import TypedDict, Annotated
from langgraph.graph.message import add_messages
class ResearchAgentState(TypedDict):
"""研究型Agent的推荐状态结构"""
messages: Annotated[list, add_messages] # 自动合并的消息历史
current_task: str # 当前任务描述
research_data: dict # 收集的研究数据
approval_status: bool # 审批状态
error_info: dict # 错误信息容器
关键设计原则:
- 使用TypedDict明确字段类型
- 重要字段添加类型注解(如Annotated)
- 分离业务数据和系统状态
- 包含错误处理专用字段
3.2 节点(Node)实现规范
节点是实现业务逻辑的基本单元。这是我总结的节点开发规范:
python复制def data_processing_node(state: ResearchAgentState) -> dict:
"""
标准节点实现模板
遵循以下规范:
1. 函数名明确表达节点职责
2. 类型注解完整
3. 详细的docstring
4. 错误处理机制
5. 返回状态更新字典
"""
try:
# 业务逻辑实现
processed = complex_data_transform(state["research_data"])
# 返回状态更新
return {
"research_data": processed,
"current_task": "data_processed"
}
except Exception as e:
return {
"error_info": {
"node": "data_processing_node",
"error": str(e),
"timestamp": datetime.now().isoformat()
},
"current_task": "error_handling"
}
3.3 边(Edge)与流程控制
LangGraph提供了灵活的流程控制机制。以下是条件边的进阶用法示例:
python复制from langgraph.graph import StateGraph, END
def advanced_router(state: ResearchAgentState) -> str:
"""智能路由决策函数"""
if state.get("error_info"):
return "error_handler"
match state["current_task"]:
case "data_collected":
return "data_processing"
case "data_processed":
if needs_human_review(state["research_data"]):
return "human_review"
return "auto_approve"
case _:
return END
# 构建带条件分支的工作流
workflow = StateGraph(ResearchAgentState)
workflow.add_node("data_collection", data_collection_node)
workflow.add_node("data_processing", data_processing_node)
workflow.add_node("human_review", human_review_node)
workflow.add_node("auto_approve", auto_approve_node)
workflow.add_node("error_handler", error_handler_node)
workflow.add_conditional_edges(
"data_collection",
advanced_router,
{
"data_processing": "data_processing",
"human_review": "human_review",
"auto_approve": "auto_approve",
"error_handler": "error_handler",
END: END
}
)
4. 实战案例:研究型多代理系统
4.1 系统架构设计
我们构建一个由三个专业Agent组成的自动化研究系统:
- 研究员Agent:负责信息收集和分析
- 验证员Agent:负责事实核查
- 写作Agent:负责报告生成
python复制class ResearchSystemState(TypedDict):
research_topic: str
collected_data: dict
verified_facts: list
draft_report: str
current_phase: Literal["research", "verification", "writing"]
approval_required: bool
4.2 节点实现细节
研究员Agent的核心节点实现:
python复制def research_agent(state: ResearchSystemState) -> dict:
"""执行深度研究的节点实现"""
search_query = build_search_query(state["research_topic"])
sources = identify_reliable_sources(search_query)
research_results = {}
for source in sources:
data = fetch_source_content(source)
analyzed = analyze_content(data)
research_results[source] = analyzed
return {
"collected_data": research_results,
"current_phase": "verification",
"approval_required": any(
len(r["citations"]) < 2
for r in research_results.values()
)
}
4.3 工作流组装与优化
使用新特性Command API简化复杂流程:
python复制from langgraph.types import Command
def verification_agent(state: ResearchSystemState) -> Command:
"""带智能路由的验证节点"""
if not state["collected_data"]:
return Command(
update={"error": "No data to verify"},
goto="error_handler"
)
verification_results = []
needs_human_check = False
for source, data in state["collected_data"].items():
verified = verify_facts(data)
verification_results.append(verified)
if verified["confidence"] < 0.8:
needs_human_check = True
if needs_human_check and state["approval_required"]:
return Command(
update={"verified_facts": verification_results},
goto="human_approval"
)
return Command(
update={"verified_facts": verification_results},
goto="writing_phase"
)
5. 2025-2026新特性深度应用
5.1 Command API最佳实践
Command API彻底改变了工作流设计模式。以下是典型应用场景:
python复制def content_moderation_node(state) -> Command:
"""内容审核节点示例"""
moderation_result = moderate_content(state["user_input"])
match moderation_result["decision"]:
case "approve":
return Command(
update={"status": "approved"},
goto="publish"
)
case "edit":
return Command(
update={
"required_edits": moderation_result["reasons"],
"status": "needs_revision"
},
goto="editing"
)
case "reject":
return Command(
update={
"rejection_reasons": moderation_result["reasons"],
"status": "rejected"
},
goto="notification"
)
# 工作流配置大幅简化
workflow.add_node("moderation", content_moderation_node)
workflow.add_node("publish", publish_node)
workflow.add_node("editing", editing_node)
workflow.add_node("notification", notification_node)
workflow.set_entry_point("moderation") # 节点内部处理路由
5.2 interrupt()的实战应用
interrupt()实现了真正的人机协作。这是邮件审批系统的完整示例:
python复制def email_approval_workflow():
class EmailState(TypedDict):
draft: dict
approvals: dict
status: str
def drafting(state: EmailState) -> Command:
draft = generate_draft(state["requirements"])
return Command(
update={"draft": draft},
goto="approval_loop"
)
def approval_loop(state: EmailState) -> Command:
approvers = get_approvers(state["draft"]["type"])
for role, person in approvers.items():
response = interrupt(
target=person,
message={
"type": "approval_request",
"draft": state["draft"],
"deadline": "24h"
}
)
state["approvals"][role] = response
if response["decision"] == "reject":
return Command(goto="revision")
return Command(goto="final_send")
workflow = StateGraph(EmailState)
workflow.add_node("drafting", drafting)
workflow.add_node("approval_loop", approval_loop)
workflow.add_node("revision", revision_node)
workflow.add_node("final_send", sending_node)
workflow.set_entry_point("drafting")
return workflow.compile(checkpointer=PostgresSaver.from_conn_string(DB_URL))
5.3 性能优化技巧
Node Caching和Deferred Nodes的组合使用可以显著提升复杂工作流的性能:
python复制def configure_optimized_workflow():
workflow = StateGraph(ResearchState)
# 启用缓存的节点
workflow.add_node(
"data_analysis",
heavy_analysis_node,
cache=True,
cache_key=lambda s: f"analysis_{hash(s['research_query'])}",
cache_config={
"ttl": 3600,
"max_size": 1000
}
)
# 延迟执行的聚合节点
workflow.add_node(
"report_generation",
generate_report_node,
deferred=True
)
# 并行数据收集分支
workflow.add_node("web_scraping", scraping_node)
workflow.add_node("api_query", api_node)
workflow.add_node("db_lookup", db_node)
# 聚合节点等待所有数据源
workflow.add_edge("web_scraping", "report_generation")
workflow.add_edge("api_query", "report_generation")
workflow.add_edge("db_lookup", "report_generation")
return workflow
6. 调试与性能调优
6.1 LangSmith集成
LangSmith是调试LangGraph应用的神器。配置方法:
python复制import os
os.environ["LANGCHAIN_TRACING_V2"] = "true"
os.environ["LANGCHAIN_PROJECT"] = "My_Research_Agent"
os.environ["LANGCHAIN_API_KEY"] = "your_api_key"
# 在代码中关键点添加跟踪
from langsmith import trace
def critical_node(state):
with trace("data_validation"):
result = validate_data(state["data"])
log_validation_metrics(result)
return {"validation_result": result}
6.2 性能监控指标
建议监控以下关键指标:
- 节点执行时间:识别性能瓶颈
- 缓存命中率:评估缓存效果
- 条件分支分布:优化路由逻辑
- 中断处理延迟:人工审批效率
python复制from prometheus_client import start_http_server, Summary
NODE_EXECUTION_TIME = Summary(
'node_execution_seconds',
'Time spent processing nodes'
)
@NODE_EXECUTION_TIME.time()
def monitored_node(state):
# 节点实现...
pass
# 启动监控服务器
start_http_server(8000)
7. 安全设计与合规实践
7.1 输入验证模式
所有外部输入必须经过严格验证:
python复制from pydantic import BaseModel, validator
class ResearchInput(BaseModel):
topic: str
max_sources: int
allowed_domains: list[str]
@validator('topic')
def validate_topic(cls, v):
if len(v) > 100:
raise ValueError("Topic too long")
if any(c in v for c in "<>{}[]"):
raise ValueError("Invalid characters")
return v.strip()
def safe_entry_node(state):
try:
validated = ResearchInput.parse_obj(state["user_input"])
return {"validated_input": validated.dict()}
except Exception as e:
return {"error": str(e), "goto": "input_error"}
7.2 权限控制策略
实现基于角色的访问控制:
python复制def role_checker(state):
user_role = state["user"]["role"]
required_roles = {
"data_export": ["admin", "analyst"],
"system_config": ["admin"],
"view_reports": ["viewer", "analyst", "admin"]
}
if user_role not in required_roles.get(state["current_node"], []):
return Command(
update={"error": "Unauthorized"},
goto="security_error"
)
return state
8. 生产环境部署指南
8.1 容器化配置
推荐使用Docker部署:
dockerfile复制# langgraph-app.dockerfile
FROM python:3.9-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
ENV LANGGRAPH_ENV=production
# 使用gunicorn作为WSGI服务器
CMD ["gunicorn", "-w 4", "-k uvicorn.workers.UvicornWorker", "app:server"]
8.2 高可用配置
yaml复制# docker-compose.yml
version: '3.8'
services:
langgraph:
image: my-langgraph-app
deploy:
replicas: 4
resources:
limits:
cpus: '2'
memory: 2G
environment:
PG_CHECKPOINTER_URL: postgresql://user:pass@postgres/checkpoints
postgres:
image: postgres:14
volumes:
- pg_data:/var/lib/postgresql/data
environment:
POSTGRES_PASSWORD: securepassword
volumes:
pg_data:
9. 典型问题解决方案
9.1 状态冲突处理
python复制def conflict_resolver(current, new):
"""自定义状态合并策略"""
merged = current.copy()
# 消息列表特殊处理
if isinstance(current.get("messages"), list):
merged["messages"] = current["messages"] + new.get("messages", [])
# 原子计数器处理
if "counter" in current:
merged["counter"] = current["counter"] + new.get("counter", 0)
# 普通字段更新
for k, v in new.items():
if k not in ["messages", "counter"]:
merged[k] = v
return merged
workflow = StateGraph(State, conflict_resolver=conflict_resolver)
9.2 超时处理机制
python复制from concurrent.futures import TimeoutError
import functools
def timeout(seconds=30):
def decorator(func):
@functools.wraps(func)
def wrapper(state):
with ThreadPoolExecutor(max_workers=1) as executor:
future = executor.submit(func, state)
try:
return future.result(timeout=seconds)
except TimeoutError:
return {
"error": f"Timeout after {seconds} seconds",
"goto": "timeout_handler"
}
return wrapper
return decorator
@timeout(45)
def long_running_node(state):
# 可能长时间运行的节点
pass
10. 进阶开发技巧
10.1 动态工作流生成
python复制def dynamic_workflow_creator(task_type):
workflow = StateGraph(State)
# 基础节点
workflow.add_node("start", start_node)
workflow.add_node("final", final_node)
# 动态添加任务特定节点
if task_type == "research":
workflow.add_node("data_gather", research_node)
workflow.add_edge("start", "data_gather")
workflow.add_edge("data_gather", "final")
elif task_type == "analysis":
workflow.add_node("preprocess", preprocess_node)
workflow.add_node("analyze", analysis_node)
workflow.add_edge("start", "preprocess")
workflow.add_edge("preprocess", "analyze")
workflow.add_edge("analyze", "final")
return workflow.compile()
10.2 工作流版本迁移
python复制def migrate_workflow_v0_to_v1(old_graph):
"""将旧版工作流迁移到支持Command API的新版本"""
new_graph = StateGraph(old_graph.state_type)
# 转换节点
for name, node in old_graph.nodes.items():
if hasattr(node, "old_style_router"):
# 转换为Command风格
def new_node(state):
result = node(state)
next_node = node.old_style_router(state)
return Command(update=result, goto=next_node)
new_graph.add_node(name, new_node)
else:
new_graph.add_node(name, node)
# 保留其他配置
new_graph.entry_point = old_graph.entry_point
return new_graph
11. 生态系统集成
11.1 与LangChain集成
python复制from langchain_core.tools import tool
from langchain.agents import AgentExecutor
@tool
def research_tool(query: str) -> str:
"""研究工具集成示例"""
workflow = get_research_workflow()
result = workflow.invoke({"query": query})
return result["summary"]
agent = create_react_agent(
llm=ChatAnthropic(model="claude-3"),
tools=[research_tool]
)
agent_executor = AgentExecutor(agent=agent, tools=[research_tool])
11.2 外部API集成模式
python复制def api_integration_node(state):
"""处理外部API集成的推荐模式"""
try:
# 1. 准备请求
request = build_api_request(state)
# 2. 调用API(带重试机制)
response = retry_api_call(
api_endpoint,
payload=request,
max_retries=3,
timeout=30
)
# 3. 处理响应
validated = validate_response(response)
return {
"api_data": validated,
"status": "api_success"
}
except Exception as e:
return {
"error": format_api_error(e),
"status": "api_failure",
"goto": "api_error_handler"
}
12. 测试策略与质量保障
12.1 单元测试模式
python复制import pytest
from langgraph.checkpoint.memory import MemorySaver
@pytest.fixture
def test_workflow():
workflow = create_sample_workflow()
return workflow.compile(checkpointer=MemorySaver())
def test_node_execution(test_workflow):
# 测试单个节点
test_state = {"input": "test"}
result = test_workflow.nodes["process_node"](test_state)
assert "processed" in result
assert len(result["processed"]) > 0
def test_workflow_integration(test_workflow):
# 测试完整工作流
final_state = test_workflow.invoke({"start_data": "value"})
assert final_state["final_result"] == "expected_outcome"
12.2 负载测试方案
python复制import locust
from locust import task, between
class LangGraphUser(locust.HttpUser):
wait_time = between(1, 5)
@task
def execute_workflow(self):
# 测试REST API接口
self.client.post("/execute", json={
"workflow": "research",
"input": {"topic": "AI trends"}
})
@task(3)
def query_status(self):
# 测试状态查询
self.client.get("/status/workflow123")
13. 性能优化深度策略
13.1 节点级优化
python复制from functools import lru_cache
@lru_cache(maxsize=1000)
def expensive_computation(input):
"""缓存昂贵计算结果的节点"""
# 复杂计算逻辑
return result
def optimized_node(state):
# 使用缓存键
cache_key = hash(state["input"])
result = expensive_computation(cache_key)
return {"result": result}
13.2 工作流级优化
python复制def configure_optimized_workflow():
workflow = StateGraph(State)
# 并行独立节点
workflow.add_node("data_fetch", fetch_node)
workflow.add_node("user_lookup", user_node)
# 聚合节点
workflow.add_node("report_gen", report_node, deferred=True)
# 并行执行路径
workflow.add_edge(START, "data_fetch")
workflow.add_edge(START, "user_lookup")
# 聚合点
workflow.add_edge("data_fetch", "report_gen")
workflow.add_edge("user_lookup", "report_gen")
# 编译配置
return workflow.compile(
cache_config={
"backend": "redis",
"ttl": 3600
},
optimization_level="O3" # 最高优化级别
)
14. 安全加固方案
14.1 输入净化处理
python复制from bleach import clean
from markdown import markdown
def sanitize_input(raw_input: str) -> str:
"""多层次的输入净化"""
# 1. HTML净化
cleaned = clean(raw_input)
# 2. 换行符标准化
normalized = cleaned.replace("\r\n", "\n")
# 3. 长度限制
if len(normalized) > 10000:
raise ValueError("Input too long")
# 4. 敏感词过滤
if contains_sensitive_terms(normalized):
raise ValueError("Sensitive content detected")
return normalized
def safe_content_node(state):
try:
clean_input = sanitize_input(state["user_input"])
return {"processed_input": clean_input}
except ValueError as e:
return {"error": str(e), "goto": "input_error"}
14.2 审计日志集成
python复制import logging
from logging.handlers import SysLogHandler
audit_logger = logging.getLogger("langgraph_audit")
audit_logger.setLevel(logging.INFO)
audit_logger.addHandler(SysLogHandler(address='/dev/log'))
def audited_node(state):
"""带完整审计记录的节点"""
audit_logger.info(
f"Node execution started by {state.get('user')}",
extra={
"state": sanitize_for_log(state),
"timestamp": datetime.now().isoformat()
}
)
try:
result = business_logic(state)
audit_logger.info("Node completed successfully")
return result
except Exception as e:
audit_logger.error(f"Node failed: {str(e)}")
raise
15. 监控与可观测性
15.1 指标监控体系
python复制from prometheus_client import Counter, Histogram
NODE_EXECUTIONS = Counter(
'node_executions_total',
'Total node executions',
['node_name']
)
EXECUTION_TIME = Histogram(
'node_execution_seconds',
'Node execution time',
['node_name'],
buckets=[0.1, 0.5, 1, 2, 5]
)
def monitored_node(state):
start_time = time.time()
NODE_EXECUTIONS.labels(node_name="my_node").inc()
try:
result = actual_node_logic(state)
EXECUTION_TIME.labels(node_name="my_node").observe(time.time() - start_time)
return result
except Exception:
EXECUTION_TIME.labels(node_name="my_node").observe(time.time() - start_time)
raise
15.2 分布式追踪
python复制from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
trace.set_tracer_provider(TracerProvider())
tracer = trace.get_tracer(__name__)
# 配置OTLP导出器
otlp_exporter = OTLPSpanExporter(endpoint="http://collector:4317")
trace.get_tracer_provider().add_span_processor(
BatchSpanProcessor(otlp_exporter)
)
def traced_node(state):
with tracer.start_as_current_span("node_operation") as span:
span.set_attributes({
"user": state.get("user"),
"input_size": len(str(state.get("input")))
})
result = node_logic(state)
span.set_attribute("result_status", result["status"])
return result
16. 扩展性与插件开发
16.1 自定义节点类型
python复制from langgraph.graph import Node
class DatabaseNode(Node):
"""自定义数据库操作节点"""
def __init__(self, connection_string):
self.conn = create_db_connection(connection_string)
super().__init__(self._execute)
def _execute(self, state):
# 使用连接池执行查询
query = build_query(state)
result = self.conn.execute(query)
return {"db_result": result.to_dict()}
def close(self):
self.conn.close()
# 使用自定义节点
workflow.add_node("db_query", DatabaseNode("postgresql://user:pass@localhost/db"))
16.2 工作流插件系统
python复制# plugin_registry.py
PLUGINS = {}
def register_plugin(name):
def decorator(plugin_cls):
PLUGINS[name] = plugin_cls
return plugin_cls
return decorator
@register_plugin("sentiment_analysis")
class SentimentPlugin:
def __init__(self, workflow):
self.workflow = workflow
def install(self):
self.workflow.add_node("sentiment", self.analyze)
# 修改工作流连接...
def analyze(self, state):
# 实现情感分析逻辑
return {"sentiment": analyze_text(state["text"])}
# 应用插件
workflow = StateGraph(State)
SentimentPlugin(workflow).install()
17. 多语言集成方案
17.1 外部服务桥接
python复制import grpc
class GRPCIntegrationNode:
"""gRPC服务集成节点"""
def __init__(self, stub_class, endpoint):
channel = grpc.insecure_channel(endpoint)
self.stub = stub_class(channel)
def __call__(self, state):
request = self._build_request(state)
response = self.stub.Process(request)
return self._parse_response(response)
def _build_request(self, state):
# 转换状态为gRPC请求
pass
def _parse_response(self, response):
# 解析gRPC响应
pass
# 使用示例
workflow.add_node(
"fraud_detection",
GRPCIntegrationNode(FraudServiceStub, "fraud:50051")
)
17.2 WebAssembly集成
python复制import wasmtime
class WasmNode:
"""WASM模块执行节点"""
def __init__(self, wasm_file):
self.engine = wasmtime.Engine()
self.module = wasmtime.Module.from_file(self.engine, wasm_file)
self.store = wasmtime.Store(self.engine)
self.instance = wasmtime.Instance(self.store, self.module, [])
def __call__(self, state):
# 序列化状态
input_data = json.dumps(state).encode()
# 分配内存并写入输入
malloc = self.instance.exports["malloc"]
free = self.instance.exports["free"]
process = self.instance.exports["process"]
ptr = malloc(len(input_data))
memory = self.instance.exports["memory"]
memory.write(ptr, input_data)
# 调用WASM函数
out_ptr = process(ptr, len(input_data))
# 读取结果
result_size = int.from_bytes(memory.read(out_ptr, 4), 'little')
result_data = memory.read(out_ptr + 4, result_size)
# 释放内存
free(ptr)
free(out_ptr)
return json.loads(result_data.decode())
# 使用示例
workflow.add_node("wasm_transform", WasmNode("transform.wasm"))
18. 大规模部署架构
18.1 分布式执行引擎
python复制from celery import Celery
app = Celery('langgraph_tasks', broker='redis://redis:6379/0')
@app.task(bind=True)
def execute_node(self, node_name, state, checkpoint_id=None):
"""分布式节点执行任务"""
workflow = load_workflow_from_registry()
node = workflow.nodes[node_name]
try:
result = node(state)
save_checkpoint(checkpoint_id, result)
return result
except Exception as e:
self.retry(exc=e, countdown=60)
def distributed_invoke(workflow_name, input_state):
"""分布式工作流执行"""
workflow = load_workflow(workflow_name)
checkpoint_id = create_checkpoint(input_state)
# 启动初始节点
execute_node.delay(
workflow.entry_point,
input_state,
checkpoint_id
)
return checkpoint_id
18.2 容错与恢复机制
python复制def resilient_workflow_execution(workflow, initial_state):
"""带自动恢复的工作流执行"""
checkpoint_id = str(uuid.uuid4())
checkpointer.save_checkpoint(checkpoint_id, initial_state)
current_node = workflow.entry_point
state = initial_state
while current_node != END:
try:
node = workflow.nodes[current_node]
# 尝试执行节点(带超时)
result = run_with_timeout(
node,
state,
timeout=workflow.timeouts.get(current_node, 30)
)
# 处理路由
if isinstance(result, Command):
state.update(result.update)
current_node = result.goto
else:
state.update(result)
current_node = workflow.edges[current_node]
# 保存检查点
checkpointer.save_checkpoint(checkpoint_id, state)
except Exception as e:
# 从检查点恢复
recovered = checkpointer.recover_checkpoint(checkpoint_id)
state = recovered.state
current_node = recovered.node
# 重试逻辑
if recovered.retry_count < 3:
recovered.retry_count += 1
continue
else:
workflow.error_handler.handle(e, state)
break
return state
19. 成本优化策略
19.1 LLM调用优化
python复制def optimized_llm_node(state):
"""智能LLM调用优化节点"""
llm = ChatAnthropic(model="claude-3-haiku") # 成本较低的模型
# 检查是否可以使用缓存
cache_key = hash_query(state["messages"])
if cached := llm_cache.get(cache_key):
return {"response": cached}
# 检查是否可以简化查询
if can_use_short_prompt(state):
prompt = build_short_prompt(state)
else:
prompt = build_full_prompt(state)
# 流式处理减少延迟
response = []
for chunk in llm.stream(prompt):
response.append(chunk)
if len(response) > 1000: # 提前终止
break
full_response = "".join(response)
llm_cache.set(cache_key, full_response, ttl=3600)
return {"response": full_response}
19.2 资源调度算法
python复制class ResourceAwareScheduler:
"""智能资源调度器"""
def __init__(self, workflow):
self.workflow = workflow
self.node_profiles = self._profile_nodes()
def _profile_nodes(self):
# 分析各节点资源需求
return {
name: self._estimate_resources(node)
for name, node in workflow.nodes.items()
}
def schedule(self, state):
"""智能调度节点执行顺序"""
# 实现基于资源可用性的调度逻辑
if current_cpu_usage() > 80:
return self._schedule_lightweight_nodes_first(state)
else:
return self._default_schedule(state)
def optimize_workflow(self):
"""离线工作流优化"""
# 重新排列节点顺序
# 合并轻量级节点
# 预计算可能的分支
20. 演进路线与未来方向
20.1 自适应工作流
python复制class SelfOptimizingWorkflow:
"""能自我优化的工作流实现"""
def __init__(self, initial_workflow):
self.workflow = initial_workflow
self.performance_data = defaultdict(list)
def record_metrics(self, node_name, execution_time, success):
"""收集性能指标"""
self.performance_data[node_name].append({
"timestamp": time.time(),
"execution_time": execution_time,
"success": success
})
def analyze_and_optimize(self):
"""分析指标并优化工作流"""
# 识别性能瓶颈
bottlenecks = [
name for name, data in self.performance_data.items()
if np.mean([d["execution_time"] for d in data]) > 2.0 # 超过2秒的节点
]
# 实施优化
for node_name in bottlenecks:
if self._can_optimize(node_name):
self._apply_optimization(node_name)
def _apply_optimization(self, node_name):
"""应用具体优化策略"""
# 实现缓存
# 算法优化
# 节点拆分等
20.2 增强学习集成
python复制class RLEnhancedNode:
"""使用
