当前位置: 首页 > news >正文

从零构建智能对话助手:LangGraph + ReAct 实现具备记忆功能的 AI 智能体

随着人工智能技术的快速发展,构建能够自主推理和执行复杂任务的智能体系统已成为当前研究的热点。ReAct(Reasoning + Action)智能体作为一种突破性的架构模式,成功地将语言模型的推理能力与外部工具的行动能力有机结合,为解决复杂的现实世界问题提供了新的技术路径。

在传统的语言模型应用中,模型往往局限于纯文本生成,无法与外部环境进行有效交互。而 ReAct 智能体通过引入工具调用机制,使模型能够在推理过程中动态获取信息、执行计算、访问数据库等,从而大幅扩展了其应用边界。这种"思考-行动-观察"的循环模式,使 AI 系统具备了类似人类的问题解决能力。

LangGraph 作为专门为构建智能体工作流而设计的开源框架,通过图结构和状态管理机制,极大地简化了复杂智能体系统的开发过程。其独特的节点-边架构不仅提供了清晰的逻辑组织方式,还支持记忆持久化、条件分支和循环执行等高级特性,为开发者提供了强大的技术支撑。

本文将从理论基础到实践应用,系统性地介绍如何使用 LangGraph 构建具备记忆能力的 ReAct 智能体。通过详细的代码示例和技术分析,读者将深入理解智能体的工作原理,掌握从基础工作流到高级记忆系统的完整实现方法,为构建下一代智能应用奠定坚实的技术基础。

ReAct 和LangGraph

ReAct(Reasoning + Action)智能体是一种先进的 AI 工作流模式,其核心特征包括:认知推理能力,允许模型进行显式思维过程;工具使用能力,实现与外部系统的交互;迭代执行机制,通过循环处理直至目标达成。

这种迭代循环架构使大型语言模型能够处理比单纯推理更为复杂的问题场景。研究表明,OpenAI 的 ChatGPT 智能体能够执行超过 20 个步骤的推理和工具使用链,成功完成行程规划和代码调试等复杂任务。

LangGraph 通过状态机和图结构的设计理念,简化了这类循环系统的构建过程。在该框架中,每个节点代表特定的功能模块(推理或行动),边则定义了状态转换的逻辑规则。

LangGraph 关键技术组件

MessagesState 状态管理机制是 LangGraph 的核心状态模式,采用包含消息列表的 TypedDict 结构,负责存储用户输入、模型响应和工具输出。该状态在所有节点间共享,确保了记忆的连续性。

节点系统将每个可调用单元(如模型调用函数或工具执行函数)抽象为图中的独立节点。节点通过返回更新的状态信息(如新生成的消息)来实现状态的前向传递。

边连接机制定义了节点间的转换逻辑,支持循环构建(如工具到智能体的往返)、条件分支以及停止条件的设定。

ToolExecutor 工具执行器提供了在 LangGraph 环境内动态执行 LangChain 工具的能力,为连接外部函数(API 接口或计算器等)到推理流程提供了便利。

记忆循环系统通过 MessagesState 携带完整的对话历史,实现了多跳推理能力。这种循环记忆机制是智能决策的技术基础。

环境配置与模型初始化

本文 deepseek-r1-distill-llama-70b 模型,该模型在成本效益和响应速度方面表现优异。

 from dotenv import load_dotenv  from langchain_groq import ChatGroq  # 从环境变量加载 API 密钥load_dotenv()  import os  os.environ['GROQ_API_KEY'] = os.getenv("GROQ_API_KEY")  # 初始化语言模型model = ChatGroq(model="deepseek-r1-distill-llama-70b")

基础 LangGraph 工作流实现

首先构建一个仅包含模型调用的基础图结构,以演示 LangGraph 的基本工作原理。

 from langgraph.graph import StateGraph, MessagesState  from langchain_core.messages import AIMessage  # 定义模型调用函数def call_model(state: MessagesState):  response = model.invoke(state["messages"])  return {"messages": [response]}  # 构建单节点图结构workflow = StateGraph(MessagesState)  workflow.add_node("mybot", call_model)  workflow.set_entry_point("mybot")  workflow.set_finish_point("mybot")  # 编译并执行工作流app = workflow.compile()  # 测试执行app.invoke({"messages": ["hi hello how are you?"]})

该基础架构的可视化表示如下:

执行结果展示了标准的消息交互模式,包含完整的元数据信息和使用统计:

 {'messages': [HumanMessage(content='hi hello how are you?', additional_kwargs={}, response_metadata={}, id='8a3041ee-c4b9-4c2c-8c8a-833c4e0df493'),  AIMessage(content="<think>\n\n</think>\n\nHello! I'm just a virtual assistant, so I don't have feelings, but I'm here and ready to help you with whatever you need. How are *you* doing? 😊", additional_kwargs={}, response_metadata={'token_usage': {'completion_tokens': 44, 'prompt_tokens': 9, 'total_tokens': 53, 'completion_time': 0.208219107, 'prompt_time': 0.001028351, 'queue_time': 0.055764798000000004, 'total_time': 0.209247458}, 'model_name': 'deepseek-r1-distill-llama-70b', 'system_fingerprint': 'fp_1bbe7845ec', 'finish_reason': 'stop', 'logprobs': None}, id='run--dc778aeb-e1e8-42f5-86dd-5dc48b563ca8-0', usage_metadata={'input_tokens': 9, 'output_tokens': 44, 'total_tokens': 53})]}

工具集成与推理-行动机制

工具系统使智能体能够执行具体操作而非仅限于思维过程。这些工具可以是任何使用 LangChain

@tool

装饰器封装的 Python 函数,从而使大型语言模型能够在执行过程中动态发现和调用它们。

以下展示了一个自定义天气查询工具的实现:

 from langchain_core.tools import tool  # 定义天气查询工具@tool  def weather_tool(query:str):  '''获取指定地区天气和温度信息的自定义工具'''if "delhi" in query.lower():  return "the temp is 45 degree and sunny"  return "the temp is 25 degree and cloudy"

ReAct 智能体节点构建

在定义自定义工具后,需要将其与大型语言模型集成,并在 LangGraph 节点内实现调用机制。

工具绑定和节点实现的技术流程如下:

 from langgraph.graph import StateGraph, MessagesState  # 工具注册与模型绑定tools = [weather_tool]  llm_with_tool = model.bind_tools(tools)  # 定义工具感知的 LangGraph 节点def weather_tool_with_llm(state:MessagesState):  question=state["messages"]  response=llm_with_tool.invoke(question)  return {"messages":[response]}

LangGraph ReAct 图架构设计

智能体与工具之间的流程连接通过 LangGraph 的图结构实现,包含路由逻辑和状态管理:

 from langgraph.graph import END, START  from langgraph.prebuilt import ToolNode  from langgraph.graph import StateGraph, MessagesState  # 路由决策函数def router_function(state:MessagesState):  messages = state["messages"][-1]  if messages.tool_calls:  return "tools"  return END  workflow = StateGraph(MessagesState)  # 工具节点初始化tool_node = ToolNode(tools)  # ReAct 循环架构定义workflow.add_node("LLM_with_Tool", weather_tool_with_llm)  workflow.add_node("tools",tool_node)  workflow.set_entry_point("LLM_with_Tool")  workflow.add_conditional_edges("LLM_with_Tool",   router_function,   {"tools":"tools",  END:END})  # 工作流编译app = workflow.compile()

该架构的图形表示展示了智能体的决策流程:

系统测试与性能评估

通过完整的 ReAct 循环测试来验证系统功能:

 # 系统调用测试response=app.invoke({"messages":["what is a weather in bengaluru?"]})  print(response["messages"][-1].content)

测试结果显示:

 'the temp is 25 degree and cloudy'

技术分析:当智能体接收查询时,首先对消息进行推理分析,判断是否需要工具支持,随后调用相应的工具函数并获取响应。

在当前配置下,智能体直接返回工具的原始输出,未对结果进行进一步的处理或重新表述。这意味着最终响应可能缺乏大型语言模型的额外上下文分析或内容总结。

反馈循环机制实现

为了提升智能体的自然交互能力,使其不仅能够使用工具,还能对工具输出进行反思和处理,系统引入了反馈循环机制。

通过建立从工具节点到 LLM 节点的连接,系统允许大型语言模型处理工具返回的结果,从而生成更具上下文相关性和可读性的响应,而非简单重复工具的原始输出。

# 建立反馈循环连接
workflow.add_edge("tools","LLM_with_Tool")  # 重新编译更新后的工作流
app2=workflow.compile()

更新后的系统架构如下图所示:

流式输出

通过流式输出机制观察各节点的处理结果:

# 流式输出测试
for output in app2.stream({"messages":["what is a weather in new delhi?"]}):  for key,value in output.items():  print(f"here is output from {key}")  print("_______")  print(value)  print("\n")

结果:

here is output from LLM_with_Tool  
_______  
{'messages': [AIMessage(content='', additional_kwargs={'tool_calls': [{'id': 'yxdmhxgdv', 'function': {'arguments': '{"query":"New Delhi"}', 'name': 'weather_tool'}, 'type': 'function'}]}, response_metadata={'token_usage': {'completion_tokens': 166, 'prompt_tokens': 137, 'total_tokens': 303, 'completion_time': 0.678175683, 'prompt_time': 0.008853151, 'queue_time': 0.052611508, 'total_time': 0.687028834}, 'model_name': 'deepseek-r1-distill-llama-70b', 'system_fingerprint': 'fp_1bbe7845ec', 'finish_reason': 'tool_calls', 'logprobs': None}, id='run--af6be495-07c4-4551-b3ae-2fbb0b9aed06-0', tool_calls=[{'name': 'weather_tool', 'args': {'query': 'New Delhi'}, 'id': 'yxdmhxgdv', 'type': 'tool_call'}], usage_metadata={'input_tokens': 137, 'output_tokens': 166, 'total_tokens': 303})]}  here is output from tools  
_______  
{'messages': [ToolMessage(content='the temp is 45 degree and sunny', name='weather_tool', id='b4ac8613-c2ae-4ea2-93f0-76c83878746e', tool_call_id='yxdmhxgdv')]}  here is output from LLM_with_Tool  
_______  
{'messages': [AIMessage(content="The temperature in New Delhi is 45 degrees and sunny. It's quite hot, so make sure to stay hydrated and take precautions against the heat!", additional_kwargs={}, response_metadata={'token_usage': {'completion_tokens': 166, 'prompt_tokens': 195, 'total_tokens': 361, 'completion_time': 0.744271226, 'prompt_time': 0.012172002, 'queue_time': 0.052512237, 'total_time': 0.756443228}, 'model_name': 'deepseek-r1-distill-llama-70b', 'system_fingerprint': 'fp_1bbe7845ec', 'finish_reason': 'stop', 'logprobs': None}, id='run--c55aa443-d399-4eec-8cb6-0fe9c8a11ce9-0', usage_metadata={'input_tokens': 195, 'output_tokens': 166, 'total_tokens': 361})]}

记忆系统集成

现有系统以独立方式处理每条消息,缺乏对历史交互的记忆能力。对于实际的多轮对话应用,记忆功能是必不可少的技术要求,它使智能体能够维持上下文连续性,回溯历史信息,并构建连贯的对话体验。

LangGraph 通过检查点机制提供了内置的记忆支持。系统采用 MemorySaver 组件在执行步骤间持久化和重用消息历史。

from langgraph.checkpoint.memory import MemorySaver  # 记忆检查点初始化
memory = MemorySaver()  # 记忆增强型工作流构建
workflow=StateGraph(MessagesState)  
workflow.add_node("llmwithtool",weather_tool_with_llm)  
workflow.add_node("mytools",tool_node)  
workflow.add_edge(START,"llmwithtool")  
workflow.add_conditional_edges("llmwithtool",  router_function,  {"tools":"mytools",  END:END})  
workflow.add_edge("mytools","llmwithtool")  # 编译支持记忆的图结构
app3=workflow.compile(checkpointer=memory)

集成记忆功能后的系统架构:

记忆功能验证测试

通过配置会话标识符进行记忆功能测试:

config = {"configurable": {"thread_id": 1}}  
events=app3.stream(  {"messages":["what is a weather in new delhi?"]},  config=config,stream_mode="values"  )  for event in events:  event["messages"][-1].pretty_print()

第一次查询的执行结果:

================================[ Human Message [=================================  
what is a weather in new delhi?  
==================================[Ai Message [==================================  
Tool Calls:  weather_tool (h7y2qwt2p)  Call ID: h7y2qwt2p  Args:  query: New Delhi  
=================================[ Tool Message [=================================  
Name: weather_tool  the temp is 45 degree and sunny  
==================================[ Ai Message [==================================  The weather in New Delhi is 45 degrees and sunny. 🌞

进行第二次不同地区的查询:

events=app3.stream(  {"messages":["what is a weather in indore?"]},config=config,stream_mode="values"  )  for event in events:  event["messages"][-1].pretty_print()

第二次查询结果:

================================[ Human Message [=================================  
what is a weather in indore?  
==================================[ Ai Message [==================================  
Tool Calls:  weather_tool (p1ybyef1v)  Call ID: p1ybyef1v  Args:  query: Indore  
=================================[ Tool Message [=================================  
Name: weather_tool  the temp is 25 degree and cloudy  
==================================[ Ai Message [==================================  
Tool Calls:  weather_tool (2002908j2)  Call ID: 2002908j2  Args:  query: Indore  
=================================[ Tool Message [=================================  
Name: weather_tool  the temp is 25 degree and cloudy  
==================================[ Ai Message [==================================  The weather in Indore is 25 degrees and cloudy. ☁️

最后测试系统的记忆能力,验证其对历史信息的回溯能力:

events=app3.stream(  {"messages":["in which city the temp was 25 degree?"]},config=config,stream_mode="values"  )  for event in events:  event["messages"][-1].pretty_print()

记忆验证结果:

================================[ Human Message [=================================  
in which city the temp was 25 degree?  
==================================[ Ai Message [==================================  The city where the temperature was 25 degrees is Indore.

总结

本文通过系统性的技术实现,展示了基于 LangGraph 的 ReAct 智能体构建方法。主要技术成果包括:ReAct 智能体核心概念的深入理解及其在复杂问题解决中的优势;基于 LangGraph 框架的智能体架构设计,实现了推理与工具使用的有机结合;推理-行动循环机制的技术实现,支持多步骤问题解决流程;记忆系统的集成,实现了多轮对话中的上下文感知能力;工具结果反馈机制的建立,提升了响应的智能化水平;自定义工具开发方法,为系统扩展提供了技术基础。

通过这些技术组件的整合,开发者现在具备了构建更智能、模块化和可扩展的 AI 智能体系统的技术能力。

https://avoid.overfit.cn/post/1cb48e82fdef47609f1d632502475dcb

作者:Aayushi_Sharma

http://www.dtcms.com/a/291871.html

相关文章:

  • Spring Boot 整合 Redis 实现发布/订阅(含ACK机制 - 事件驱动方案)
  • 【Autosar】RTE(Runtime Environment)层详解
  • lspci/setpci用法小结
  • Day 18:推断聚类后簇的类型
  • 支付网关系统前后端鉴权方案
  • LLaMA-Mesh:语言模型驱动的3D内容生成革命
  • LLaMA-Factory相关参数说明
  • VRRP-虚拟路由器冗余协议
  • 微调LLaMA 7B
  • Python通关秘籍(五)数据结构——元组
  • Apache Ignite扫描查询
  • 【机器学习深度学习】微调量化与模型导出量化:区分与应用
  • 苹果app应用ipa文件程序开发后如何运行到苹果iOS真机上测试?
  • 深度学习-算子
  • TI DLP3010光机与相机触发使用指南
  • halcon手眼标定z方向实操矫正
  • CAN基础知识
  • 基于 KeepAlived + HAProxy 搭建 RabbitMQ 高可用负载均衡集群
  • 92套毕业相册PPT模版
  • 【菜狗处理脏数据】对很多个不同时间序列数据的文件聚类—20250722
  • JavaWeb学习打卡11(session(会话)、cookie(甜点)详解)
  • 云服务器进行安全防护的必要性
  • [C++11]范围for循环/using使用
  • 录音智能转写:如何实现一键转写、灵活下载!
  • Kubernetes服务发布基础
  • 【C语言进阶】枚举和联合
  • thinkbook14+指针消失的解决方法 + Windows常见快捷键
  • 四大组件:ContentProvider学习
  • linux用户态各定时器抖动测试
  • java day16