LangGraph与大模型工作流开发指南

📅 2026/7/22 7:16:49
LangGraph与大模型工作流开发指南
1. LangGraph与大模型工作流开发基础LangGraph作为LangChain生态中的重要扩展正在重新定义大模型工作流的构建方式。与传统的线性链式调用不同LangGraph引入了有状态的工作流概念让智能体开发进入了全新的阶段。1.1 核心概念解析LangGraph的核心创新在于将智能体工作流建模为状态机state machine。开发者可以定义状态State包含智能体运行过程中的所有关键信息节点Node对状态进行操作的基本单元边Edge控制节点之间的流转逻辑这种设计模式解决了传统LangChain工作流的几个关键限制无法处理循环逻辑传统Chain是DAG结构而现实任务常需要迭代优化状态管理困难中间结果需要在不同步骤间传递控制流不灵活难以实现条件分支和并行执行1.2 环境搭建与基础配置开始使用LangGraph前需要准备Python环境建议3.8并安装必要依赖pip install langgraph langchain基础项目结构建议/project-root │── /agents # 智能体实现 │ └── population_agent.py │── /tools # 自定义工具 │ └── calculator.py │── /schemas # 类型定义 │ └── state.py └── main.py # 入口文件典型的状态定义示例schemas/state.pyfrom typing import TypedDict, List, Annotated import operator class AgentState(TypedDict): user_input: str pending_tasks: List[str] completed_tasks: Annotated[List[str], operator.add] current_step: int final_output: str2. 构建有状态工作流2.1 状态图设计与实现构建LangGraph工作流的核心是StateGraph类。开发流程通常包括定义状态结构如上文的AgentState创建节点函数构建状态图并设置流转逻辑基础示例from langgraph.graph import StateGraph # 初始化状态图 workflow StateGraph(AgentState) # 添加节点 workflow.add_node(analyze, analyze_input) workflow.add_node(execute, execute_tools) # 设置入口点 workflow.set_entry_point(analyze) # 添加边关系 workflow.add_edge(analyze, execute) workflow.add_edge(execute, analyze) # 形成循环 # 添加条件边 def should_continue(state: AgentState) - str: return end if state.get(final_output) else continue workflow.add_conditional_edge( analyze, should_continue, {end: END, continue: execute} ) # 编译工作流 agent workflow.compile()2.2 节点函数设计要点节点函数是工作流的执行单元设计时需注意输入输出规范def node_function(state: AgentState) - dict: 接收当前状态返回状态更新字典 返回的字典会与原始状态合并根据字段的合并策略 return {key: value}常见节点类型规划节点Plan决定下一步行动执行节点Execute调用工具或LLM验证节点Validate检查结果质量终节节点Finalize生成最终输出错误处理模式def safe_node(state: AgentState) - dict: try: # 正常逻辑 return {result: success_data} except Exception as e: # 错误处理 return { error: str(e), retry_count: state.get(retry_count, 0) 1 }3. 高级工作流模式3.1 并行执行与分支控制LangGraph支持通过条件边实现复杂控制流# 分支示例 def route_based_on_type(state: AgentState) - str: if state[task_type] research: return research_flow elif state[task_type] calculation: return calc_flow else: return default_flow workflow.add_conditional_edge( classify, route_based_on_type, { research_flow: research_node, calc_flow: calculation_node, default_flow: generic_node } )并行执行模式# 添加多个并行节点 workflow.add_node(search_web, web_search) workflow.add_node(query_db, database_query) # 从决策节点分叉 workflow.add_edge(decide, search_web) workflow.add_edge(decide, query_db) # 合并节点需定义合并逻辑 def merge_results(state: AgentState) - dict: web_result state.get(web_data, []) db_result state.get(db_data, []) return {combined: web_result db_result} workflow.add_node(merge, merge_results) workflow.add_edge(search_web, merge) workflow.add_edge(query_db, merge)3.2 记忆与状态持久化LangGraph提供多种记忆管理方案会话记忆短期from langgraph.checkpoint.memory import MemorySaver memory MemorySaver() agent workflow.compile(checkpointermemory) # 使用thread_id区分会话 result agent.invoke( {input: 查询法国人口}, config{configurable: {thread_id: user123}} )外部存储长期from langgraph.checkpoint.sqlite import SqliteSaver # 使用SQLite持久化状态 checkpointer SqliteSaver.from_conn_string(:memory:) agent workflow.compile(checkpointercheckpointer)自定义记忆策略class CustomMemory: def __init__(self): self.store {} def save(self, thread_id, state): self.store[thread_id] state def load(self, thread_id): return self.store.get(thread_id) custom_memory CustomMemory()4. 生产环境最佳实践4.1 可观测性实现完善的监控体系应包括日志记录import logging logger logging.getLogger(langgraph.agent) def logged_node(state: AgentState) - dict: logger.info(fProcessing state: {state}) try: result some_operation(state) logger.debug(fOperation succeeded: {result}) return {data: result} except Exception as e: logger.error(fOperation failed: {e}) return {error: str(e)}追踪集成from opentelemetry import trace tracer trace.get_tracer(agent.tracer) def traced_node(state: AgentState) - dict: with tracer.start_as_current_span(node_operation): # 节点逻辑 return {result: data}性能指标from prometheus_client import Counter, Histogram REQUEST_COUNT Counter(agent_requests, Total API requests) LATENCY Histogram(agent_latency, Request latency in seconds) LATENCY.time() def monitored_node(state: AgentState) - dict: REQUEST_COUNT.inc() # 节点逻辑 return {result: data}4.2 错误处理与恢复健壮的智能体应包含以下容错机制重试策略from tenacity import retry, stop_after_attempt, wait_exponential retry(stopstop_after_attempt(3), waitwait_exponential(multiplier1, min4, max10)) def unreliable_operation(input): # 可能失败的操作 return result熔断机制from circuitbreaker import circuit circuit(failure_threshold5, recovery_timeout30) def critical_node(state: AgentState) - dict: # 关键节点逻辑 return {output: data}状态回滚def transactional_node(state: AgentState) - dict: snapshot dict(state) # 保存状态快照 try: # 尝试操作 return {new_data: updated} except Exception: # 失败时恢复快照 return {error: Operation failed, **snapshot}4.3 性能优化技巧节点并行化from concurrent.futures import ThreadPoolExecutor def parallel_node(state: AgentState) - dict: with ThreadPoolExecutor() as executor: futures { web: executor.submit(search_web, state[query]), db: executor.submit(query_db, state[query]) } return { key: future.result() for key, future in futures.items() }LLM调用优化# 使用流式响应减少等待时间 from langchain_core.runnables import RunnableLambda streaming_chain RunnableLambda( lambda x: streaming_llm.invoke(x[input]) ) # 在节点中使用 def streaming_node(state: AgentState) - dict: chunks [] for chunk in streaming_chain.stream(state): chunks.append(chunk) yield {partial: chunk} # 渐进式返回 return {full_response: .join(chunks)}缓存策略from langchain.cache import SQLiteCache import langchain # 全局缓存 langchain.llm_cache SQLiteCache(database_path.langchain.db) # 或针对特定节点 from functools import lru_cache lru_cache(maxsize100) def expensive_operation(input): # 计算密集型操作 return result5. 智能体开发进阶5.1 多智能体协作模式LangGraph支持构建多智能体系统主从架构master_workflow StateGraph(AgentState) worker_workflow StateGraph(AgentState) # 主智能体分配任务 def assign_task(state: AgentState) - dict: subtasks break_down_task(state[input]) return {subtasks: subtasks} # 工作智能体处理任务 def process_subtask(state: AgentState) - dict: result worker_agent.invoke(state[subtask]) return {partial_result: result} # 结果聚合 def aggregate_results(state: AgentState) - dict: parts state[collected_results] return {final_output: combine_results(parts)}平等协作# 定义不同角色的智能体 analyst_workflow StateGraph(AgentState) # 分析型 researcher_workflow StateGraph(AgentState) # 研究型 validator_workflow StateGraph(AgentState) # 验证型 # 协调节点 def coordinate(state: AgentState) - dict: analysis analyst.invoke(state) research researcher.invoke(analysis) validation validator.invoke(research) return {stage: complete, **validation}5.2 工具集成与管理高效的工具管理策略动态工具注册tool_registry {} def register_tool(name, func, descNone): tool_registry[name] { function: func, description: desc or name } def tool_node(state: AgentState) - dict: tool_name state[selected_tool] if tool_name not in tool_registry: return {error: fUnknown tool: {tool_name}} tool tool_registry[tool_name] try: result tool[function](state[tool_input]) return {tool_output: result} except Exception as e: return {error: str(e)}工具版本控制class ToolVersion: def __init__(self, func, version, is_defaultFalse): self.func func self.version version self.is_default is_default tool_versions { search: [ ToolVersion(search_v1, 1.0), ToolVersion(search_v2, 2.0, True) ] } def get_tool(name, versionNone): versions tool_versions.get(name, []) if not versions: return None if version: return next((v for v in versions if v.version version), None) else: return next((v for v in versions if v.is_default), versions[0])5.3 长期记忆实现构建智能体的长期记忆系统向量存储集成from langchain.vectorstores import FAISS from langchain.embeddings import HuggingFaceEmbeddings embedding HuggingFaceEmbeddings() vectorstore FAISS.load_local(memory_store, embedding) def remember_facts(state: AgentState) - dict: docs vectorstore.similarity_search(state[query]) return {related_memories: [doc.page_content for doc in docs]} def record_memory(state: AgentState) - dict: if important_fact in state: vectorstore.add_texts([state[important_fact]]) return {}记忆摘要机制from langchain.chains.summarize import load_summarize_chain summarizer load_summarize_chain(llm, chain_typemap_reduce) def summarize_memories(state: AgentState) - dict: if len(state[chat_history]) 10: # 当历史记录过长时 summary summarizer.run(state[chat_history]) return { chat_summary: summary, chat_history: [] # 清空历史 } return {}记忆检索优化def retrieve_relevant_memories(state: AgentState) - dict: query state.get(current_query) if not query: return {} # 多路召回 keyword_results keyword_search(query) vector_results vectorstore.similarity_search(query) temporal_results recent_memories(query) # 去重与排序 combined unique_combine( keyword_results, vector_results, temporal_results ) return {context_memories: combined[:5]} # 返回最相关的5条在实际项目中这些技术可以组合使用来构建强大的智能体系统。关键是根据具体需求选择合适的设计模式并通过充分的测试确保系统的稳定性和可靠性。