返回顶部
7*24新情报

LangGraph实战:如何用20行代码实现带记忆的多步Agent

[复制链接]
wwlwxd 显示全部楼层 发表于 4 分钟前 |阅读模式 打印 上一主题 下一主题
兄弟们,最近在折腾AI Agent开发,发现LangGraph这个框架真的有点东西。它不像LangChain那样“黑盒”,而是用有向图来编排Agent的每一步,可控性极高。

今天分享一个**带状态记忆的多步Agent**实现思路。核心是定义“节点”(Node)和“边”(Edge)。比如你要做一个文档问答Agent,需要“意图识别→检索→生成回答”三步。

用LangGraph,你可以这样写:
```python
from langgraph.graph import StateGraph, END
graph = StateGraph(state_schema=AgentState)
graph.add_node("intent", intent_router)  # 节点1:意图识别
graph.add_node("retrieve", retriever)    # 节点2:检索
graph.add_node("generate", generator)    # 节点3:生成
graph.set_entry_point("intent")
graph.add_conditional_edges("intent", decide_next, {"retrieve": "retrieve", "END": END})
graph.add_edge("retrieve", "generate")
graph.add_edge("generate", END)
app = graph.compile()
```

**技术细节**:
- 状态(state)是全局字典,节点间共享数据,天然支持多轮对话记忆。
- 条件边(conditional_edges)让你能根据LLM输出动态决定下一步,比如意图不明确时重新提问。
- 实测在GPT-4o上,这类结构化Agent比单一Prompt调用节省20%的token(因为不再重复传递历史)。

**避坑指南**:
1. 节点函数必须返回一个dict更新state,别漏了。
2. 复杂任务建议用`MessageGraph`(消息图)替代`StateGraph`,对对话场景更友好。

社区里已经有人基于这个框架做了AutoGPT的简化版,代码不到100行。感兴趣的朋友可以试试,有问题直接回帖。
回复

使用道具 举报

default_avator1
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver·手机版·闲社网·闲社论坛·羊毛社区· 多链控股集团有限公司 · 苏ICP备2025199260号-1

Powered by Discuz! X5.0   © 2024-2025 闲社网·线报更新论坛·羊毛分享社区·http://xianshe.com

p2p_official_large
快速回复 返回顶部 返回列表