随着强大 AI 模型(如 GPT-5、Gemini 2.5 Pro)的崛起,能充分利用这些模型的 agentic 框架也越来越多。这类框架通过抽象掉诸多繁琐环节,使与 AI 模型协作更简单,例如处理 tool-calling(工具调用)、agentic state handling(智能体状态管理)、human-in-the-loop(人类参与闭环)等。
因此,本文将深入介绍可用的 agentic AI 框架之一:LangGraph。我会用它来开发一个简单的 agentic 应用,通过若干步骤展示 agentic AI 包的优势。文末也会讨论使用 LangGraph 及其他类似 agentic 框架的优缺点。
本文没有任何来自 LangGraph 的赞助。我之所以选择它,是因为它足够流行。当然,还有很多其他选择,例如:
- LangChain
- LlamaIndex
- CrewAI
为什么需要 agentic 框架?
市面上有很多旨在让应用开发更容易的包。但在不少情况下,它们产生了相反效果:让代码更晦涩、生产环境表现不佳、调试也更困难。
然而,关键在于找到那些能通过抽象样板代码而真正简化应用的包。这个原则在创业圈常被这样概括:
专注于解决你要解决的那个“确切问题”。其他(已经被解决的问题)都应交给现成应用去处理。
需要 agentic 框架的原因是它能抽象掉许多你不想亲自处理的复杂性:
- 维护 state(状态)。不仅是消息历史,还包括执行 RAG 时收集的所有信息(RAG 保留英文以示专业术语)
- Tool usage(工具使用)。你不需要自己编写执行工具的逻辑。更好的做法是定义好工具,让 agentic 框架负责如何调用(尤其适用于并行与异步的工具调用)
因此,使用 agentic 框架可以抽离大量复杂细节,让你把精力集中在产品的核心部分。
LangGraph 基础
要开始实现 LangGraph,我首先阅读了它的文档:https://langchain-ai.github.io/langgraph/concepts/why-langgraph/,重点包括:
- 基本 chatbot(聊天机器人)实现
- 工具使用
- 维护与更新 state(状态)
顾名思义,LangGraph 基于“图”的构建,并在每次请求时执行该图。你可以在图中定义:
- State(状态):即保存在内存中的当前信息
- Nodes(节点):通常是 LLM 或工具调用,例如判断用户意图或回答用户问题
- Edges(边):条件逻辑决定下一个要去的节点
这些都源自基本的图论思想。
实现一个 workflow
我认为最好的学习方式之一就是自己动手试。因此,我将用 LangGraph 实现一个简单的 workflow。你可以在 workflow 文档中学习如何构建这些流程,这些文档借鉴了 Anthropic 的 Building effective agents 博文(这是我最喜欢的关于 agents 的文章之一,我在很多早期文章中都提到过,非常推荐阅读)。
我会做一个简单的应用,使用户可以:
- 创建带文本的文档
- 删除文档
- 在文档中搜索
为此,我会创建如下 workflow:
- 识别用户意图。他们是想创建文档、删除文档,还是搜索文档?
- 根据第 1 步的结果,分别为每种意图执行不同流程。
当然,你也可以直接定义好所有工具,让 agent 自由地执行创建/删除/搜索文档的操作。但如果你希望根据意图执行更多动作,那么先做一次意图分类的路由会更合适。
加载 imports 和 LLM
首先,我会加载所需的 imports 和将使用的 LLM。这里我用的是 AWS Bedrock,但你也可以使用其他服务商,详见本教程第 3 步:https://langchain-ai.github.io/langgraph/tutorials/get-started/1-build-basic-chatbot/#__tabbed_1_1
"""Make a document handler workflow where a user cancreate a new document to the database (currently just a dictionary)delete a document from the databaseask a question about a document"""from typing_extensions import TypedDict, Literalfrom langgraph.checkpoint.memory import InMemorySaverfrom langgraph.graph import StateGraph, START, ENDfrom langgraph.types import Command, interruptfrom langchain_aws import ChatBedrockConversefrom langchain_core.messages import HumanMessage, SystemMessagefrom pydantic import BaseModel, Fieldfrom IPython.display import display, Imagefrom dotenv import load_dotenvimport osload_dotenv()
aws_access_key_id = os.getenv("AWS_ACCESS_KEY_ID") or ""aws_secret_access_key = os.getenv("AWS_SECRET_ACCESS_KEY") or ""
os.environ["AWS_ACCESS_KEY_ID"] = aws_access_key_idos.environ["AWS_SECRET_ACCESS_KEY"] = aws_secret_access_key
llm = ChatBedrockConverse( model_id="us.anthropic.claude-3-5-haiku-20241022-v1:0", # this is the model id (added us. before id in platform) region_name="us-east-1", aws_access_key_id=aws_access_key_id, aws_secret_access_key=aws_secret_access_key,
)
document_database: dict[str, str] = {} # a dictionary with key: filename, value: text in document
我还把“数据库”定义成了一个文件字典。在生产环境中,你当然会使用真正的数据库;不过本教程中我们做了简化。
定义图
接下来定义图。我先创建一个 Router(路由器)对象,用来把用户的 prompt 分类为三种意图之一:
- add_document
- delete_document
- ask_document
## Define stateclass State(TypedDict): input: str decision: str | None output: str | None# Schema for structured output to use as routing logicclass Route(BaseModel): step: Literal["add_document", "delete_document", "ask_document"] = Field( description="The next step in the routing process" )# Augment the LLM with schema for structured outputrouter = llm.with_structured_output(Route)def llm_call_router(state: State): """Route the user input to the appropriate node""" # Run the augmented LLM with structured output to serve as routing logic decision = router.invoke( [ SystemMessage( content="""Route the user input to one of the following 3 intents: - 'add_document' - 'delete_document' - 'ask_document' You only need to return the intent, not any other text. """ ), HumanMessage(content=state["input"]), ] ) return {"decision": decision.step}# Conditional edge function to route to the appropriate nodedef route_decision(state: State): # Return the node name you want to visit next if state["decision"] == "add_document": return "add_document_to_database_tool" elif state["decision"] == "delete_document": return "delete_documen…