【langgraph 从入门到精通graphApi 篇】生产部署与性能优化

📅 2026/7/19 16:22:17 👁️ 阅读次数 📝 编程学习
【langgraph 从入门到精通graphApi 篇】生产部署与性能优化

第 12 章:生产部署与性能优化

12.1 本章目标

学完本章你将能够:

  1. 了解 LangGraph Platform 和 LangGraph Server 的部署方式
  2. 掌握生产环境的 Checkpointer 和 Store 配置
  3. 学会错误处理、重试和并发控制
  4. 了解监控、日志和成本优化策略

12.2 核心概念

生产部署架构

监控

数据库

LangGraph Server

客户端

Web/App 客户端

API Server
:2024

langgraph_sdk

PostgreSQL
Checkpointer + Store

LangSmith
追踪 + 监控

开发 vs 生产
对比维度开发环境生产环境
CheckpointerMemorySaverPostgresSaver
StoreInMemoryStorePostgresStore
LLM 调用直连 API加缓存 + 重试
错误处理打印日志结构化日志 + 告警
部署方式langgraph devlanggraph deploy或 Docker
监控LangSmith 集成

12.3 实战

实战 1:langgraph.json 项目配置
{"graphs":{"agent":"./agent.py:graph"},"store":{"index":{"embed":"openai:text-embeddings-3-small","dims":1536,"fields":["$"]}},"env":{"OPENAI_API_KEY":"your-api-key"}}
实战 2:Postgres 持久化配置
importosfromlanggraph.checkpoint.postgresimportPostgresSaverfromlanggraph.store.postgresimportPostgresStoreimportpsycopg2# 连接数据库conn=psycopg2.connect(os.environ["DATABASE_URL"])# 配置 Checkpointercheckpointer=PostgresSaver(conn)checkpointer.setup()# 创建表和索引# 配置 Storestore=PostgresStore(conn)store.setup()# 编译图graph=builder.compile(checkpointer=checkpointer,store=store,)
实战 3:SDK 远程调用
fromlanggraph_sdkimportget_client# 连接到 LangGraph Serverclient=get_client(url="http://localhost:2024")# 流式调用asyncforchunkinclient.runs.stream(None,# thread_id(None = 无状态)"agent",# assistant_id(对应 langgraph.json 中的 graphs key)input={"messages":[{"role":"human","content":"你好,帮我查询订单"}]},):print(chunk.event,chunk.data)
实战 4:错误重试策略
fromlanggraph.typesimportRetryPolicy# 在 add_node 时配置重试builder.add_node("api_call",api_node,retry_policy=RetryPolicy(max_attempts=3,# 最多重试 3 次initial_interval=1.0,# 首次重试等待 1 秒backoff_factor=2,# 指数退避因子(1s → 2s → 4s)retry_on=Exception,# 重试的错误类型),)

12.4 API 速查

API完整签名入参说明返回值说明
langgraph devCLI 命令开发服务器启动本地开发服务器
langgraph deployCLI 命令部署部署到 LangSmith Cloud
get_client(url)get_client(url: str)url: 服务地址ClientSDK 客户端
RetryPolicy(max_attempts, ...)RetryPolicy(max_attempts, initial_interval, backoff_factor)max_attempts: 最大重试次数;initial_interval: 初始等待秒数;backoff_factor: 退避因子RetryPolicy节点重试策略
PostgresSaver(conn).setup().setup()初始化数据库表结构

12.5 错误与避坑指南

坑 1:生产环境用 MemorySaver
# ❌ 生产环境错误写法checkpointer=MemorySaver()# 服务重启后所有对话状态丢失!# ✅ 生产环境正确写法fromlanggraph.checkpoint.postgresimportPostgresSaver checkpointer=PostgresSaver(conn)checkpointer.setup()
坑 2:未设置数据库连接池
# ❌ 错误:单连接,高并发时瓶颈conn=psycopg2.connect(DATABASE_URL)checkpointer=PostgresSaver(conn)# ✅ 正确:使用连接池frompsycopg2.poolimportThreadedConnectionPool pool=ThreadedConnectionPool(minconn=5,maxconn=20,dsn=DATABASE_URL)checkpointer=PostgresSaver(pool)
坑 3:忽略工具调用超时
# ❌ 错误:工具调用可能无限等待@tooldefexternal_api(query:str)->str:response=requests.get(...)# 没有超时设置returnresponse.text# ✅ 正确:设置超时 + 重试@tooldefexternal_api(query:str)->str:try:response=requests.get(...,timeout=10)returnresponse.textexceptrequests.Timeout:return"服务暂时不可用,请稍后重试"

12.6 最佳实践总结

  1. 开发用langgraph dev,生产用langgraph deploy或 Docker:环境统一
  2. 使用 PostgresSaver + PostgresStore 持久化:高可用、支持并发
  3. 关键节点设置 RetryPolicy:自动重试 + 指数退避
  4. 集成 LangSmith 监控:追踪每次 LLM 调用和图执行
  5. 工具调用设置超时:防止外部服务拖垮整个 Agent

附录 A:完整 API 速查手册

A.1 图构建 API

API导入路径签名说明
StateGraphlanggraph.graphStateGraph(state_schema)创建状态图构建器
add_nodeStateGraph 方法.add_node(name, action)注册节点
add_edgeStateGraph 方法.add_edge(start, end)添加普通边
add_conditional_edgesStateGraph 方法.add_conditional_edges(source, path, path_map)添加条件边
add_sequenceStateGraph 方法.add_sequence(nodes)批量添加顺序节点
compileStateGraph 方法.compile(checkpointer, store, ...)编译为可执行图
STARTlanggraph.graph常量"__start__"图入口
ENDlanggraph.graph常量"__end__"图出口

A.2 State 与 Reducer API

API导入路径说明
TypedDicttyping定义 State 的推荐方式
Annotatedtyping_extensions声明字段的 Reducer
add_messageslanggraph.graph消息专用 Reducer
operator.addoperator数值/列表累加 Reducer
MessagesStatelanggraph.graph预构建的 messages State

A.3 消息 API

API导入路径说明
HumanMessagelangchain_core.messages用户消息
AIMessagelangchain_core.messagesAI 回复
ToolMessagelangchain_core.messages工具执行结果
SystemMessagelangchain_core.messages系统提示词

A.4 工具 API

API导入路径说明
@toollangchain_core.tools将函数标记为工具
ToolNodelanggraph.prebuilt自动处理工具调用
tools_conditionlanggraph.prebuilt判断是否有 tool_calls
create_react_agentlanggraph.prebuilt预构建 Agent

A.5 持久化 API

API导入路径说明
MemorySaverlanggraph.checkpoint.memory内存 Checkpointer
SqliteSaverlanggraph.checkpoint.sqliteSQLite Checkpointer
PostgresSaverlanggraph.checkpoint.postgresPostgres Checkpointer
InMemoryStorelanggraph.store.memory内存 Store
PostgresStorelanggraph.store.postgresPostgres Store

A.6 流程控制 API

API导入路径说明
interruptlanggraph.types暂停执行
Commandlanggraph.types动态控制流程
Sendlanggraph.types并行分发
RetryPolicylanggraph.types重试策略
Runtimelanggraph.runtime运行时上下文

A.7 流式输出 API

API导入路径说明
.stream()CompiledGraph 方法同步流式
.astream()CompiledGraph 方法异步流式
.stream_events()CompiledGraph 方法v3 事件流式
get_stream_writerlanggraph.config自定义流式事件