ARTICLE DETAIL

资讯详情

深耕编程入门与网站建设的一线实战洞察。

给 AutoGen 智能体装上跨会话持久化记忆:hindsight-autogen 的 retain / recall / reflect 三工具实战指南

给 AutoGen 智能体装上跨会话持久化记忆:hindsight-autogen 的 retain / recall / reflect 三工具实战指南 给 AutoGen 智能体装上跨会话持久化记忆hindsight-autogen 的 retain / recall / reflect 三工具实战指南【免费下载链接】hindsightHindsight: Agent Memory That Learns项目地址: https://gitcode.com/GitHub_Trending/hindsight2/hindsight本篇技术指南围绕 Hindsight 官方提供的hindsight-autogen集成包讲解如何用三个 AutoGen 原生FunctionToolhindsight_retain、hindsight_recall、hindsight_reflect为AssistantAgent赋予跨会话长期记忆。读完本文你将掌握从启动 Hindsight 服务、安装集成、创建记忆库bank到按用户隔离、用 tag 圈定作用域、按 budget 权衡速度与深度的完整实战方案并能对照源码理解每个参数在底层如何被透传给 Hindsight API。TL;DRAutoGen 智能体没有内置的跨会话记忆每次运行会话状态都会重置只有会话内的聊天历史hindsight-autogen为AssistantAgent提供三个FunctionTool实例hindsight_retain存储、hindsight_recall检索、hindsight_reflect综合推理一次pip install把tools[...]传给 agent 即完成接入无需子类化或自定义 agent 类型支持连接 Hindsight Cloud或在本机自托管 Hindsight 服务问题AutoGen 的会话内聊天历史不是记忆AutoGen 为AssistantAgent提供的是会话内的聊天历史——本质上只是一份消息列表它不会从对话中抽取事实、不会随时间累积知识进程一退出就全部消失。它对单个会话内连续追问够用但对以下场景远远不够一个需要记住你的技术栈、偏好和既往决策的编码助手一个需要从历次群聊group chat中保留知识的协调者coordinator智能体一个需要在几十次对话中持续掌握你账户历史的支持客服智能体这类需求要求系统具备三个能力从对话中抽取结构化事实、随时间构建知识、按语义检索相关上下文。这正是 Hindsight 提供的而hindsight-autogen把它接入了 AutoGen 的工具系统。架构三个 FunctionTool零侵入接入AutoGen AssistantAgent(tools[...]) └─ Hindsight FunctionTools (via create_hindsight_tools) ├─ hindsight_retain → Hindsight retain │ (fact extraction, entity resolution, knowledge graph) ├─ hindsight_recall → Hindsight recall │ (semantic BM25 graph temporal retrieval) └─ hindsight_reflect → Hindsight reflect (synthesize a reasoned answer from all memories)这些工具是autogen_core.tools.FunctionTool的实例见 工具工厂实现直接传给AssistantAgent(tools[...])。不需要子类化、不需要自定义 agent 类型就是标准 AutoGen 工具调用。底层上Hindsight 在 retain 时抽取结构化事实、识别实体、构建知识图谱在 recall 时并行运行四路检索策略语义向量、BM25 关键词、图谱遍历、时间维度并用 cross-encoder 重排融合结果。Step 1启动 Hindsight自托管方式单机一体包内置 Postgres、嵌入模型与重排模型pip install hindsight-all export HINDSIGHT_API_LLM_API_KEYYOUR_OPENAI_KEY hindsight-api服务默认运行在http://localhost:8888。仓库还提供了 Docker 独立部署方式见 docker/standalone/start-all.sh 与 hindsight-all 包说明。也可以直接使用 Hindsight Cloud跳过自托管。Step 2安装集成包pip install hindsight-autogen autogen-agentchat autogen-ext[openai]依赖关系见 pyproject.tomlhindsight-autogen会连带安装autogen-core0.4.0与hindsight-client0.4.0autogen-agentchat提供AssistantAgentautogen-ext[openai]提供 OpenAI 模型客户端OpenAIChatCompletionClient要求 Python 3.10Step 3创建记忆库并组装 agent记忆库bank必须先创建再使用。AutoGen agent 是异步的因此整个流程包在asyncio.run()中import asyncio from autogen_agentchat.agents import AssistantAgent from autogen_ext.models.openai import OpenAIChatCompletionClient from hindsight_client import Hindsight from hindsight_autogen import create_hindsight_tools async def main(): client Hindsight(base_urlhttp://localhost:8888) await client.acreate_bank(user-123, nameUser 123 Memory) model_client OpenAIChatCompletionClient(modelgpt-4o-mini) tools create_hindsight_tools( clientclient, bank_iduser-123, tags[source:chat], budgetmid, ) agent AssistantAgent( nameassistant, model_clientmodel_client, toolstools, reflect_on_tool_useTrue, system_message( You are a helpful assistant with long-term memory. Use hindsight_retain to store important facts the user shares. Use hindsight_recall to search memory before answering questions. ), ) # Session 1: store preferences result await agent.run( taskIm a data scientist. I use Python, SQL, and VS Code with dark mode., ) # Wait for Hindsight to finish processing (fact extraction is async) await asyncio.sleep(3) # Session 2: recall from memory (same bank, memory persists) result await agent.run( taskWhat IDE do I use?, ) print(result.messages[-1].content) # → You use VS Code with dark mode. # Clean up await client.aclose() await model_client.close() asyncio.run(main())三个工具、一个记忆库。记忆之所以跨会话持久是因为它存在 Hindsight 中而不是存在 agent 里。仓库的端到端测试验证了同样的 retain → recall → reflect 闭环见 test_e2e.py其中对retain 后立即 recall的异步处理延迟还专门实现了轮询等待逻辑。Jupyter Notebook 提示在 Notebook 中无需asyncio.run()单元格本身已有事件循环直接await即可。三个工具的源码级解析create_hindsight_tools的完整实现位于 hindsight_autogen/tools.py。三个工具都是内部闭包函数包装成FunctionTool把参数透传给hindsight_client的异步方法hindsight_retain(content)—— 存储记忆。把bank_id与content传给client.aretain()若配置了tags、retain_metadata、retain_document_id会一并带上成功返回Memory stored successfully.任何非HindsightError异常会被包装为HindsightError(Retain failed: ...)抛出tools.py。hindsight_recall(query)—— 检索记忆。调用client.arecall()透传budget与max_tokens可选tags/tags_match、types事实类型、include_entities。结果以带编号的列表返回1. ...\n2. ...无结果时返回No relevant memories found.tools.py。单元测试验证了编号输出与空结果兜底行为test_tools.py。hindsight_reflect(query)—— 综合推理。调用client.areflect()可选透传context、max_tokens未指定时回退到max_tokens、response_schemaJSON Schema 约束结构化输出、reflect_tags/reflect_tags_match未指定时回退到recall_tags/recall_tags_match。返回response.text为空时兜底No relevant memories found.tools.py。create_hindsight_tools 完整参数参考参数默认值说明bank_id必填Hindsight 记忆库 IDclientNone预配置的 Hindsight 客户端优先使用hindsight_api_urlNoneAPI 地址未提供 client 时使用api_keyNoneAPI 密钥未提供 client 时使用budgetmidrecall/reflect 预算级别low/mid/highmax_tokens4096recall 结果的最大 token 数tagsNoneretain 存储记忆时附加的标签recall_tagsNone检索时用于过滤的标签recall_tags_matchany标签匹配模式any/all/any_strict/all_strictretain_metadataNoneretain 的默认元数据字典retain_document_idNoneretain 的默认 document_id用于分组/upsert 记忆recall_typesNone要过滤的事实类型world/experience/observationrecall_include_entitiesFalserecall 结果中是否包含实体信息reflect_contextNonereflect 操作的附加上下文reflect_max_tokensNonereflect 结果最大 token 数默认回退到max_tokensreflect_response_schemaNone约束 reflect 输出格式的 JSON Schemareflect_tagsNonereflect 使用的记忆过滤标签默认回退到recall_tagsreflect_tags_matchNonereflect 的标签匹配模式默认回退到recall_tags_matchinclude_retainTrue是否包含 retain存储工具include_recallTrue是否包含 recall检索工具include_reflectTrue是否包含 reflect综合工具上述默认值与类型定义见 hindsight_autogen/config.pyDEFAULT_BUDGETmid、DEFAULT_MAX_TOKENS4096、DEFAULT_RECALL_TAGS_MATCHany。按需裁剪工具并非每个 agent 都需要全部三个工具可以用include_*开关只保留所需子集tools create_hindsight_tools( clientclient, bank_iduser-123, include_retainTrue, include_recallTrue, include_reflectFalse, # 不包含 reflect )单元测试对三种单工具组合及全部排除返回空列表均有覆盖test_tools.py。全局配置 configure() 与客户端解析与其每次调用都传 client不如用configure()配置一次之后任何地方创建工具都会自动继承from hindsight_autogen import configure, create_hindsight_tools configure( hindsight_api_urlhttp://localhost:8888, api_keyyour-api-key, # 或设置 HINDSIGHT_API_KEY 环境变量 budgetmid, # 检索预算low/mid/high max_tokens4096, # recall 结果最大 token 数 tags[env:prod], # 存储记忆时的标签 recall_tags[scope:global], # 检索过滤标签 recall_tags_matchany, # 标签匹配模式 ) # 之后无需再传 client tools create_hindsight_tools(bank_iduser-123)客户端解析的优先级与兜底逻辑实现在 hindsight_autogen/_client.py可以总结为显式传入的client优先其次取configure()配置的 URL 与 api_key都没有时回退到生产默认地址https://api.hindsight.vectorize.io常量DEFAULT_HINDSIGHT_API_URLapi_key 还会直接读取HINDSIGHT_API_KEY环境变量——即使从未调用过configure()只要设置了环境变量即可工作客户端统一设置 30 秒超时并携带hindsight-autogen/version的 User-Agent 用于服务端识别。对应的测试用例test_tools.py验证了无配置默认云地址从环境变量读取密钥回退全局配置显式 URL 覆盖配置四条路径。按用户隔离的记忆库与 tag 作用域把bank_id参数化即可实现按用户隔离每个库完全独立杜绝跨用户数据泄漏def create_agent_for_user(user_id: str) - AssistantAgent: tools create_hindsight_tools( clientclient, bank_idfuser-{user_id}, ) return AssistantAgent( nameassistant, model_clientOpenAIChatCompletionClient(modelgpt-4o-mini), toolstools, )用 tag 圈定记忆范围可以按主题、会话或来源给记忆打标签并在检索时只召回匹配的标签# 按来源打标签存储 tools create_hindsight_tools( clientclient, bank_iduser-123, tags[source:chat, session:abc], recall_tags[source:chat], recall_tags_matchany, )recall_tags_match支持四种匹配模式anyOR 匹配、包含未打标签记忆、allAND 匹配、包含未打标签记忆、any_strictOR 匹配、排除未打标签记忆、all_strictAND 匹配、排除未打标签记忆。hindsight_client的底层实现还额外支持exact集合相等模式与tag_groups布尔组合过滤见 hindsight_client.py不过在create_hindsight_tools层面目前暴露的是前四种。生产模式要点错误处理工具失败时抛出HindsightErrorAutoGen 会将其作为工具错误呈递给 agent。可以包裹 agent 调用做优雅降级from hindsight_autogen.errors import HindsightError try: result await agent.run(taskWhat do you remember about me?) except HindsightError as e: print(fMemory operation failed: {e})记忆库生命周期先建库、用后清理。acreate_bank是幂等的可以安全重复调用await client.acreate_bank(bank_iduser-123) # ... 使用工具 ... await client.adelete_bank(bank_iduser-123) # 不再需要时删除多 agent 团队每个 agent 独享记忆库或让整个团队共享一个库并靠 tag 分区# 按 agent 隔离 researcher_tools create_hindsight_tools(clientclient, bank_idresearcher-memory) writer_tools create_hindsight_tools(clientclient, bank_idwriter-memory) # 团队共享 shared_tools create_hindsight_tools( clientclient, bank_idteam-shared, tags[team:content], )什么时候该用、什么时候不该用推荐使用面向重复用户的 agent—— 客服机器人、编码助手、个人 AI需要跨会话记住偏好与历史共享记忆的多 agent 团队—— 协调者把群聊发现存入记忆让后续会话一开始就带上下文长期运行的工作流—— 跨数天/数周处理数据、需要增量累积知识的 agent个性化—— 任何记住用户能随时间提升质量的场景明确不要用仅需会话内上下文—— 单个会话内记得住就行AutoGen 内置聊天历史更简单且零额外延迟不要为了用而用文档检索RAG—— 需要对文档库做向量检索时请用专用向量库。Hindsight 是面向随时间学习的事实的记忆系统不是文档存储无状态一次性任务—— 批处理、一次性查询等按设计无状态的 agent持久化记忆只添复杂度没有收益延迟敏感的热路径—— 每次记忆操作都多一次网络往返。当亚 100ms 响应比个性化更重要时跳过它陷阱与边界情况记忆库必须先存在。在 agent 启动前调用await client.acreate_bank(bank_id, name...)否则 retain/recall 会失败。异步处理延迟。hindsight_retain之后Hindsight 会异步处理内容——抽取事实、解析实体、生成 embedding。若 retain 后立刻 recall新记忆可能还不可检索。实测通常 1-3 秒仓库的 e2e 测试用轮询最多 12 次、每次间隔 1 秒来规避这一点test_e2e.py。生产环境中只有同一脚本里 retain 与 recall 背靠背时才需要这个等待。预算调优。默认budgetmid在速度与深度之间取得平衡延迟敏感的 agent 用low需要深度分析时用high。budget 控制运行多少路检索策略以及做多少重排。reflect 与 recall 的分工。原始事实用hindsight_recall如What IDE do I use?综合归纳用hindsight_reflect如Based on everything you know, what should I prioritize?。reflect 更慢但会产出基于完整知识图谱的推理式回答。与现有方案的对比vs. AutoGen 聊天历史聊天历史在会话内保存原始消息不抽取事实、不泛化、会话一结束就消失。Hindsight 抽取结构化事实、去重、只检索相关内容——它压缩知识而不是堆积 token。vs. 纯向量库如 Pinecone、Weaviate、Chroma向量库只提供 embedding 相似度检索。Hindsight 并行运行四路检索语义、BM25、图谱遍历、时间维度并做 cross-encoder 重排同时抽取实体、解析指代、构建知识图谱——它是记忆引擎不是数据库。仓库中多路检索与重排的实现可见 hindsight-api-slim 的 recall 相关测试 与 test_recall_pipeline_toggles.py。vs. 其他框架集成如果不用 AutoGen 而是用 LlamaIndex、LangGraph、CrewAI 或 Pydantic AIHindsight 为每个框架都提供了专门集成仓库源码位于 hindsight-integrations/llamaindex、hindsight-integrations/langgraph、hindsight-integrations/crewai、hindsight-integrations/pydantic-ai 目录下每个目录都带 README、示例与配套测试。总结hindsight-autogen通过传给AssistantAgent(tools[...])的FunctionTool实例为 AutoGen 智能体提供持久化记忆三个工具hindsight_retain存储、hindsight_recall检索、hindsight_reflect综合兼容任何 AutoGenAssistantAgent单 agent 或多 agent 团队均可用按用户划分的 bank 实现记忆隔离用 tag 圈定作用域用 budget 权衡速度与深度后续可以尝试本地试跑pip install hindsight-all hindsight-autogen autogen-agentchat autogen-ext[openai]然后运行上文完整示例深入源码工具实现、全局配置、客户端解析、单元测试、端到端测试探索其他集成LlamaIndex、LangGraph、Pydantic AI、CrewAI【免费下载链接】hindsightHindsight: Agent Memory That Learns项目地址: https://gitcode.com/GitHub_Trending/hindsight2/hindsight创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表