Skip to content

附录


A. LangGraph API 速查表

图构建

API说明示例
StateGraph(State)创建状态图graph = StateGraph(MessagesState)
add_node(name, fn)添加节点graph.add_node("agent", agent_fn)
add_edge(a, b)添加普通边graph.add_edge("agent", "tools")
add_conditional_edges(node, fn)添加条件边graph.add_conditional_edges("agent", route_fn)
compile()编译图app = graph.compile(checkpointer=memory)
START入口虚拟节点graph.add_edge(START, "agent")
END出口虚拟节点return END

运行

API说明示例
invoke(input, config)同步运行result = app.invoke(data, config)
ainvoke(input, config)异步运行result = await app.ainvoke(data, config)
stream(input, config)流式运行for chunk in app.stream(data, config):
astream(input, config)异步流式async for chunk in app.astream(data, config):
astream_events(input, config)Token 级流式async for event in app.astream_events(data, config, version="v2"):

状态管理

API说明示例
get_state(config)获取当前状态state = app.get_state(config)
get_state_history(config)获取历史状态for s in app.get_state_history(config):
update_state(config, values)更新状态app.update_state(config, {"messages": [...]})

Checkpointer

Checkpointer导入适用场景
MemorySaverfrom langgraph.checkpoint.memory import MemorySaver开发调试
SqliteSaverfrom langgraph.checkpoint.sqlite import SqliteSaver单机部署
PostgresSaverfrom langgraph.checkpoint.postgres import PostgresSaver生产部署

预构建组件

组件导入说明
ToolNodefrom langgraph.prebuilt import ToolNode自动执行工具调用
create_react_agentfrom langgraph.prebuilt import create_react_agent一行创建 ReAct Agent
MessagesStatefrom langgraph.graph import MessagesState预定义的消息 State
interruptfrom langgraph.types import interrupt动态中断

Config 参数

python
config = {
    "configurable": {
        "thread_id": "xxx",           # 必填:会话标识
        "checkpoint_id": "xxx",       # 可选:指定 checkpoint
    },
    "recursion_limit": 25,            # 可选:循环次数上限
}

B. 常见报错与解决方案

1. Checkpointer requires a thread_id

错误:ValueError: Checkpointer requires one or more of the following keys: ['thread_id']

原因:启用了 Checkpointer 但调用 invoke() 时没传 config

python
# ❌
result = app.invoke(data)

# ✅
config = {"configurable": {"thread_id": "my_thread"}}
result = app.invoke(data, config=config)

2. GraphRecursionError

错误:GraphRecursionError: Recursion limit of 25 reached

原因:图循环超过了 recursion_limit(默认 25)。

解决

  • 检查条件边的路由函数是否有退出条件
  • 适当增大 recursion_limit
  • 在 State 中加 retry_count 手动控制

3. tool_calls 相关的 InvalidToolCall

错误:InvalidToolCall: Function 'xxx' not found

原因:LLM 产生的 tool_calls 中的工具名不在已注册的工具列表中。

解决

  • 检查 @tool 装饰器的函数名是否和 bind_tools 中一致
  • 确保 ToolNode(tools) 中的 tools 列表包含所有可能被调用的工具

4. ChannelError: messages

错误:ChannelError: Can't add to channel 'messages'

原因:节点返回的 messages 字段格式不对。

解决

python
# ❌ 返回字符串
return {"messages": "hello"}

# ✅ 返回消息列表
return {"messages": [AIMessage(content="hello")]}

5. State 字段未定义

错误:KeyError: 'xxx' is not a valid field

原因:节点返回了 State 中未定义的字段。

解决:确保节点返回的字典中的 key 都在 State 类型定义中存在。

6. 异步相关:RuntimeError: no running event loop

错误:RuntimeError: There is no current event loop in thread

原因:在同步环境中调用了异步 API。

解决

python
import asyncio

# 方法 1:用 asyncio.run
asyncio.run(app.ainvoke(data, config))

# 方法 2:在 async 函数中调用
async def main():
    result = await app.ainvoke(data, config)

C. 推荐学习资源

官方资源

资源链接说明
LangGraph 文档https://langchain-ai.github.io/langgraph/最权威的参考
LangGraph GitHubhttps://github.com/langchain-ai/langgraph源码和示例
LangGraph 教程https://langchain-ai.github.io/langgraph/tutorials/官方教程合集
LangSmithhttps://smith.langchain.com/追踪和调试平台
LangChain 文档https://python.langchain.com/LangChain 核心库文档

学习路径建议

入门阶段(1-2 天):
  本教程第 1-5 章 → 理解 Graph、State、Node、Edge、Tool

进阶阶段(2-3 天):
  本教程第 6-9 章 → 掌握持久化、HITL、多 Agent、Streaming

实战阶段(3-5 天):
  本教程第 10-11 章 → 自纠错 RAG + 生产部署
  → 然后把学到的用到自己的项目中

持续学习:
  关注 LangGraph GitHub 的更新
  阅读 LangChain Blog 的最新文章
  加入 LangChain Discord 社区

核心依赖版本参考

bash
pip install langgraph>=0.2.0
pip install langchain-core>=0.3.0
pip install langchain-deepseek>=0.1.0
pip install langchain-openai>=0.2.0   # OpenAI 兼容接口(通用)

# 可选
pip install langgraph-checkpoint-sqlite
pip install langgraph-checkpoint-postgres
pip install langsmith

感谢你的阅读! 这份教程从 LangGraph 的基本概念一直讲到生产部署,希望能帮助你快速掌握这个强大的 Agent 框架。如果你在实践中遇到问题,回来翻翻附录的速查表和常见报错解决方案——它们会是你最好的随身参考。

Happy Building! 🚀

坚持是一种品格