2026年7月9日 周四晚上19:30,报名腾讯会议了解“如何构建自进化的动态知识库(Brain)”(限30人)
免费POC, 零成本试错
FDE知识库

FDE知识库

学习大模型的前沿技术与行业落地应用


收藏

如何用 LangGraph 构建高效的 Agentic 系统

发布日期:2025-11-21 08:47:38 浏览次数: 2480
作者:AI大模型观察站

微信搜一搜,关注“AI大模型观察站”

推荐语

探索LangGraph如何简化AI工作流开发,释放Agentic框架的真正潜力。

核心内容:
1. Agentic框架的核心优势与必要性分析
2. LangGraph基础架构与关键组件解析
3. 实战案例展示与同类框架对比评估

杨芳贤
53AI创始人/腾讯云(TVP)最具价值专家
本文介绍如何用 LangGraph 创建强大的 agentic workflows。图片由 ChatGPT 生成。

随着强大 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
该图展示了你可以用 LangGraph 实现的一个高级 AI workflow 示例。该 workflow 包含若干路由步骤,每步会通向不同的函数处理器,以更有效地处理用户请求。图片由作者制作。

为什么需要 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. 识别用户意图。他们是想创建文档、删除文档,还是搜索文档?
  2. 根据第 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 can
create a new document to the database (currently just a dictionary)
delete a document from the database
ask a question about a document
"""

from typing_extensions import TypedDict, Literal
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.graph import StateGraph, START, END
from langgraph.types import Command, interrupt
from langchain_aws import ChatBedrockConverse
from langchain_core.messages import HumanMessage, SystemMessage
from pydantic import BaseModel, Field
from IPython.display import display, Image
from dotenv import load_dotenv
import os
load_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_id
os.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 state
class State(TypedDict):
    inputstr
    decision: str | None
    output: str | None

# Schema for structured output to use as routing logic
class 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 output
router = 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 node
def 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_document_from_database_tool"
    elif state["decision"] == "ask_document":
        return "ask_document_tool"

这里我定义了 state,用来存储用户输入、路由器的决策(三种意图之一),并强制 LLM 做结构化输出。结构化输出能确保模型只返回这三种意图之一。

接着,我会定义本例使用的三个工具,每个意图对应一个工具。

# Nodes
def add_document_to_database_tool(state: State):
    """Add a document to the database. Given user query, extract the filename and content for the document. If not provided, will not add the document to the database."""

user_query = state["input"]
    # extract filename and content from user query
    filename_prompt = f"Given the following user query, extract the filename for the document: {user_query}. Only return the filename, not any other text."
    output = llm.invoke(filename_prompt)
    filename = output.content
    content_prompt = f"Given the following user query, extract the content for the document: {user_query}. Only return the content, not any other text."
    output = llm.invoke(content_prompt)
    content = output.content
    # add document to database
    document_database[filename] = content
    return {"output"f"Document {filename} added to database"}

def delete_document_from_database_tool(state: State):
    """Delete a document from the database. Given user query, extract the filename of the document to delete. If not provided, will not delete the document from the database."""
    user_query = state["input"]
    # extract filename from user query
    filename_prompt = f"Given the following user query, extract the filename of the document to delete: {user_query}. Only return the filename, not any other text."
    output = llm.invoke(filename_prompt)
    filename = output.content
    # delete document from database if it exsits, if not retunr info  about failure 
    if filename not in document_database:
        return {"output"f"Document {filename} not found in database"}
    document_database.pop(filename)
    return {"output"f"Document {filename} deleted from database"}

def ask_document_tool(state: State):
    """Ask a question about a document. Given user query, extract the filename and question for the document. If not provided, will not ask the question about the document."""
    user_query = state["input"]
    # extract filename and question from user query
    filename_prompt = f"Given the following user query, extract the filename of the document to ask a question about: {user_query}. Only return the filename, not any other text."
    output = llm.invoke(filename_prompt)
    filename = output.content
    question_prompt = f"Given the following user query, extract the question to ask about the document: {user_query}. Only return the question, not any other text."
    output = llm.invoke(question_prompt)
    question = output.content
    # ask question about document
    if filename not in document_database:
        return {"output"f"Document {filename} not found in database"}
    result = llm.invoke(f"Document: {document_database[filename]}\n\nQuestion: {question}")
    return {"output"f"Document query result: {result.content}"}

最后,我们用节点和边来构建图:

# Build workflow
router_builder = StateGraph(State)

# Add nodes
router_builder.add_node("add_document_to_database_tool", add_document_to_database_tool)
router_builder.add_node("delete_document_from_database_tool", delete_document_from_database_tool)
router_builder.add_node("ask_document_tool", ask_document_tool)
router_builder.add_node("llm_call_router", llm_call_router)
# Add edges to connect nodes
router_builder.add_edge(START, "llm_call_router")
router_builder.add_conditional_edges(
    "llm_call_router",
    route_decision,
    {  # Name returned by route_decision : Name of next node to visit
        "add_document_to_database_tool""add_document_to_database_tool",
        "delete_document_from_database_tool""delete_document_from_database_tool",
        "ask_document_tool""ask_document_tool",
    },
)
router_builder.add_edge("add_document_to_database_tool", END)
router_builder.add_edge("delete_document_from_database_tool", END)
router_builder.add_edge("ask_document_tool", END)

# Compile workflow
memory = InMemorySaver()
router_workflow = router_builder.compile(checkpointer=memory)
config = {"configurable": {"thread_id""1"}}

# Show the workflow
display(Image(router_workflow.get_graph().draw_mermaid_png()))

最后的显示函数会渲染出如下图所示的图结构:

现在你可以按不同意图来试跑这个 workflow 了。

添加文档:

user_input = "Add the document 'test.txt' with content 'This is a test document' to the database"
state = router_workflow.invoke({"input": user_input}, config)
print(state["output"]

# -> Document test.txt added to database

搜索文档:

user_input = "Give me a summary of the document 'test.txt'"
state = router_workflow.invoke({"input": user_input}, config)
print(state["output"])

# -> A brief, generic test document with a simple descriptive sentence.

删除文档:

user_input = "Delete the document 'test.txt' from the database"
state = router_workflow.invoke({"input": user_input}, config)
print(state["output"])

# -> Document test.txt deleted from database

很好!可以看到 workflow 在不同路由下都能正常工作。你也可以随意增加更多意图,或为每个意图增加更多节点,构建更复杂的 workflow。

更强的 agentic 用例

agentic workflows 与完全的 agentic applications 之间的差异有时会让人困惑。为区分这两个术语,我引用 Anthropic 的 Building effective agents 一文中的说法:

Workflows 是通过预定义的代码路径来编排 LLM 和工具的系统;而 Agents 是由 LLM 动态地指挥其自身流程与工具使用、并持续控制任务完成方式的系统。

大多数使用 LLM 解决的问题都会采用 workflow 模式,因为大多数问题(以我的经验)是预定义的,并且应该有一套预设的防护栏可遵循。例如在上面的添加/删除/搜索文档场景中,你完全应该先定义意图分类器,并基于不同意图设定好后续流程。

但有时你也需要更自主的 agentic 用例。比如 Cursor 想要一个 coding agent,它能在你的代码中搜索、在线查阅最新文档,并修改你的代码。在这些情况下,预先定义好固定的 workflows 很困难,因为可能出现的场景极为多样。

如果你想打造更自主人格的 agentic 系统,可以在这里了解更多:https://langchain-ai.github.io/langgraph/concepts/agentic_concepts/

LangGraph 优缺点

优点

我认为 LangGraph 有三点主要优点:

  • 上手简单
  • 开源
  • 让代码更简洁

LangGraph 的安装和快速试跑都很简单,尤其是参考其官方文档,或把文档喂给 Cursor 并提示它实现特定 workflows 时更是如此。

此外,LangGraph 的代码是开源的,这意味着无论提供它的公司如何变化或做何决策,你都能继续运行代码。对于要上生产环境的项目,这一点至关重要。最后,LangGraph 还显著简化了大量代码,并抽象掉许多你原本需要在 Python 里亲自处理的逻辑。

缺点

不过,我在实现过程中也发现了一些不足:

  • 仍然存在令人意外的样板代码量
  • 会遇到 LangGraph 特有的错误

在实现自定义 workflow 时,我感觉仍需添加不少样板代码。尽管代码量确实比从零开始实现要少,但为了构建一个相对简单的 workflow,我也写了比预期更多的代码。我认为部分原因在于:LangGraph 希望把自己定位为比(例如)LangChain 更低代码(这点我认为是好的,因为以我个人观点,LangChain 抽象得过多,反而让调试更难)。

此外,与很多第三方包一样,在集成 LangGraph 时你会遇到特有问题。例如,我想预览自己创建的 workflow 的图时,就遇到了与 draw_mermaid_png 函数相关的问题。使用外部包时碰到这类错误在所难免,这始终是在“包提供的有用抽象”与“可能遭遇的各种 bug”之间做权衡。

总结

总体而言,在处理 agentic 系统时,我觉得 LangGraph 是个很有用的包。先做意图分类、再根据意图进入不同流程来搭建我想要的 workflow,这个过程相对简单。此外,我认为 LangGraph 在“不把所有逻辑都抽象掉(避免代码被遮蔽、便于调试)”与“确实抽象掉我不想亲自处理的复杂性”之间找到了不错的平衡。采用这类 agentic 框架有利有弊,而我认为判断取舍的最好方式,就是亲自实现一些简单的 workflows 试一试。

53AI,企业落地大模型首选服务商

产品:场景落地咨询+大模型应用平台+行业解决方案

承诺:免费POC验证,效果达标后再合作。零风险落地应用大模型,已交付160+中大型企业

联系我们

售前咨询
186 6662 7370
预约演示
185 8882 0121

微信扫码

添加专属顾问

回到顶部

加载中...

扫码咨询

扫码登录
登录即表示您同意《53AI网站服务协议》
服务协议

欢迎您使用【53AI 官方网站】(以下简称“本网站”或“我们”)。本《会员服务协议》(以下简称“本协议”)是您(以下简称“会员”或“用户”)与【深圳市博思协创网络科技有限公司】之间关于注册、登录及使用本网站会员服务所订立的法律协议。

在您注册或登录前,请务必审慎阅读、充分理解各条款内容,特别是免除或限制责任的条款、知识产权条款、争议解决条款等。此类条款将以加粗形式提示您注意。 当您通过微信公众号授权、手机验证码验证或其他方式成功登录本网站时,即视为您已完全理解并同意接受本协议的全部内容。

一、 定义

本网站:指由【深圳市博思协创网络科技有限公司】运营的,域名为【53ai.com】的网站及相关移动端页面。

会员服务:指本网站向注册会员提供的知识库文章查阅、内容检索及其他相关增值服务。

知识库内容:指本网站发布的包括但不限于文字、图表、数据、研究报告、行业分析等数字化内容资源。

二、 账号注册与登录

登录方式:本网站支持以下登录方式,您可根据实际情况选择:

微信公众号授权登录:您同意将您的微信OpenID信息授权给本网站,用于创建或关联会员账号。

手机验证码登录:您需提供真实有效的手机号码,并通过短信验证码完成身份验证与登录/注册。

账号安全:您的账号仅限您本人使用,禁止赠与、借用、租用、转让或售卖。因您保管不善导致的账号被盗、密码泄露等损失,由您自行承担。

实名认证:根据相关法律法规要求,我们可能要求您在特定功能下完成实名认证。如您拒绝提供,可能无法使用部分或全部服务。

未成年人保护:若您未满18周岁,请在法定监护人的陪同下阅读本协议,并在征得监护人同意后使用本服务。

三、 服务内容与规范

知识库查阅权限:会员登录后,有权按照其会员等级对应的权限范围,在线浏览、检索本网站知识库中的相关文章及内容。

服务变更:我们有权根据业务发展需要,调整、变更或终止部分服务内容,并将以网站公告、公众号消息等方式提前通知。

禁止行为:您在使用服务时不得实施以下行为:

利用技术手段批量爬取、下载、转存知识库内容;

将知识库内容用于商业目的或未经授权地向第三方传播;

干扰本网站正常运行或侵犯其他用户合法权益;

发布违法违规信息或从事违反公序良俗的活动。

四、 知识产权声明

权利归属:本网站知识库中的排版设计、软件代码等内容的知识产权均归【公司全称】或原权利人所有,受《中华人民共和国著作权法》等法律保护。

有限许可:本网站授予会员一项非独占、不可转让、不可转授权的普通许可,仅限于个人学习、研究之目的在线查阅知识库内容。

侵权追责:未经书面许可,任何单位或个人不得以任何形式复制、转载、摘编、镜像、汇编或以其他方式使用上述内容。一经发现,我们保留追究其法律责任的权利。

五、 个人信息保护

我们重视对您个人信息的保护。关于我们如何收集、使用、存储和保护您的个人信息,请单独阅读 《隐私政策》。

您通过微信公众号授权或手机号验证所提供的信息,我们将严格按照《个人信息保护法》的规定处理,仅用于身份识别、服务提供及安全验证等必要用途。

您可以随时通过网站设置或联系客服行使查阅、更正、删除个人信息及撤回授权同意的权利。

六、 免责声明

内容准确性:知识库内容仅供参考,不构成专业建议。我们不对其完整性、准确性、时效性作任何明示或暗示的保证,您应自行判断并承担使用风险。

不可抗力:因自然灾害、政策法规变化、网络故障、第三方平台接口异常(如微信接口维护、运营商短信通道故障)等不可抗力导致的服务中断或延迟,我们不承担违约责任。

第三方链接:本网站可能包含指向第三方网站的链接,该等网站的内容和服务不受我们控制,请您自行甄别风险。

七、 违约责任

如您违反本协议约定,我们有权视情节采取警告、限制功能、暂停服务、注销账号等措施,并保留要求赔偿损失的权利。

如因您的违约行为导致我们遭受行政处罚、第三方索赔或商誉损失,您应承担全部赔偿责任(包括但不限于罚款、赔偿金、律师费、公证费等)。

八、 法律适用与争议解决

本协议的订立、执行和解释均适用中华人民共和国大陆地区法律。

因本协议产生的或与本协议有关的任何争议,双方应友好协商解决;协商不成的,任何一方均可向【公司所在地】有管辖权的人民法院提起诉讼。

九、 其他

本协议构成双方就本服务达成的完整协议,取代此前任何口头或书面约定。

本协议任一条款被认定为无效或不可执行的,不影响其他条款的效力。

我们对本协议享有最终解释权,并在法律允许的范围内保留随时修改的权利。修改后的协议一经公布即生效,继续使用服务即视为同意修订内容。


已查阅