使用 Hindsight 为 AutoGen Agent 接入持久化长期记忆:retain / recall / reflect 集成指南

使用 Hindsight 为 AutoGen Agent 接入持久化长期记忆:retain / recall / reflect 集成指南 使用 Hindsight 为 AutoGen Agent 接入持久化长期记忆retain / recall / reflect 集成指南【免费下载链接】hindsightHindsight: Agent Memory That Learns项目地址: https://gitcode.com/GitHub_Trending/hindsight2/hindsight导读本文讲解如何在 AutoGenautogen-agentchat的AssistantAgent中接入 Hindsight 的持久化长期记忆能力通过hindsight-autogen提供的三个FunctionTool实例hindsight_retain、hindsight_recall、hindsight_reflect让 Agent 在跨会话场景下存储、检索并综合已有记忆。读完本文你将掌握该集成包的安装方式、三种记忆工具的底层调用链、基于 Tag 的记忆隔离方案、全局配置与参数优先级规则以及错误处理与多 Agent 团队的生产级用法。一、集成包概览与核心特性hindsight-autogen是 Hindsight 面向 AutoGen 的官方集成包位于仓库的 hindsight-integrations/autogen 目录其作用是把 Hindsight 的 retain存储/ recall检索/ reflect综合三大 API 封装为 AutoGen 标准的FunctionTool可直接传入AssistantAgent(tools[...])。核心特性与 autogen.md 所述一致Memory Tools以 AutoGenFunctionTool形式提供 retain、recall、reflect 三个记忆工具Async-Native底层直接调用 Hindsight 客户端的aretain/arecall/areflect异步方法天然适配 AutoGen 的异步运行时Selective Tools通过include_retain/include_recall/include_reflect开关只挂载需要的工具Tag-Based Scoping用标签按主题、会话或用户隔离记忆Global Configuration通过configure()一次性配置之后可在任意位置创建工具。关联文档AutoGen Persistent Memory with Hindsightsidebar_position: 12。包内变更历史请查阅 Changelog 中的 integrations/autogen 章节。二、安装与运行前置条件pip install hindsight-autogen autogen-agentchat autogen-ext[openai]依赖关系说明hindsight-autogen会自动拉入autogen-coreFunctionTool所在的基础库和hindsight-clientHindsight 的 Python 客户端autogen-agentchat提供AssistantAgentautogen-ext[openai]提供 OpenAI 模型客户端OpenAIChatCompletionClient。版本要求见 pyproject.toml 与文档 Requirements 一节Python 3.10autogen-core 0.4.0hindsight-client 0.4.0从源码结构看该包同时声明了autogen-agentchat0.4.0与pytest9.0.2等开发依赖并在pyproject.toml中为端到端测试标记了requires_real_llm需要真实 Hindsight 服务与not requires_real_llm可在无外部依赖时运行的确定性测试两类测试桶。运行前提需要一个可访问的 Hindsight 实例——可以是本地自托管参考仓库根目录 README.md 的 Quick Start默认地址http://localhost:8888也可以是 Hindsight Cloud。三、快速开始给 AssistantAgent 装上记忆完整示例与 autogen.md 的 Quick Start 一致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(bank_iduser-123) model_client OpenAIChatCompletionClient(modelgpt-4o) tools create_hindsight_tools(clientclient, bank_iduser-123) agent AssistantAgent( nameassistant, model_clientmodel_client, toolstools, ) # Store a memory result await agent.run(taskRemember that I prefer dark mode) print(result.messages[-1].content) # Hindsight processes retained content asynchronously (fact extraction, # entity resolution, embeddings). A brief pause ensures memories are # searchable before the next recall. In production, this delay is only # needed when retain and recall happen back-to-back in the same script. await asyncio.sleep(3) # Recall it later result await agent.run(taskWhat are my UI preferences?) print(result.messages[-1].content) # Clean up await client.aclose() await model_client.close() asyncio.run(main())要点说明create_hindsight_tools(clientclient, bank_iduser-123)返回一个list[FunctionTool]可直接展开传给AssistantAgent(tools[...])bank_id是必填参数指定操作哪个记忆库memory bank示例先用acreate_bank创建了该库记住await asyncio.sleep(3)的注释提醒retain 提交后Hindsight 服务端是异步加工内容的事实抽取、实体解析、向量化嵌入若在同一脚本里紧跟 recall短暂等待能保证记忆已可被检索生产环境中只有当 retain 与 recall 背靠背发生时才有此需要。Jupyter Notebook 提示在 Notebook 中无需asyncio.run()直接在每个 cell 里用await即可因为 Notebook 本身已存在活动事件循环。三个记忆工具的行为定义Agent 会获得三个可调用工具其名称与职责对应 tools.py 中的三个内部 async 函数工具名职责输入参数返回hindsight_retain把信息存入长期记忆重要事实、用户偏好、决策、跨会话需记住的内容content: strMemory stored successfully.hindsight_recall在长期记忆中搜索相关信息返回编号列表query: str编号列表如1. User likes Python无结果时返回No relevant memories found.hindsight_reflect基于记忆综合出有条理、有推理的回答而非原始事实列表query: str综合后的文本空结果时返回No relevant memories found.底层实现细节可在 tools.py 中核对retain 工具会把tags、metadata、document_id当显式传入时一并透传给client.aretain(...)recall 工具默认透传budget与max_tokens仅在配置了recall_tags时才带上tags与tags_match并支持types事实类型过滤与include_entitiesreflect 工具默认透传budgetmax_tokens回退到max_tokens可通过reflect_max_tokens单独覆盖支持context、response_schema其标签过滤默认回退到 recall 的标签配置。单元测试对上述行为有完整覆盖例如 test_tools.py 验证了 recall 的编号输出、空结果兜底、budget/max_tokens/tags/types/include_entities 的透传以及HindsightError抛出。四、按需选择工具Selective Tools并非每个 Agent 都需要全部三个工具。通过include_*开关裁剪tools create_hindsight_tools( clientclient, bank_iduser-123, include_retainTrue, include_recallTrue, include_reflectFalse, # Omit reflect )在 tools.py 中每个开关对应一段独立的 append 逻辑全部置为False时返回空列表。测试 test_tools.py 逐项验证了“只含 retain”“只含 recall”“只含 reflect”“全部排除”四种裁剪结果以及默认返回三个工具且顺序固定为[hindsight_retain, hindsight_recall, hindsight_reflect]。五、全局配置configure() 一次配置、随处创建如果不想在每次调用时都显式传 client可以用configure()设置全局默认from hindsight_autogen import configure, create_hindsight_tools configure( hindsight_api_urlhttp://localhost:8888, api_keyyour-api-key, # Or set HINDSIGHT_API_KEY env var budgetmid, # Recall budget: low/mid/high max_tokens4096, # Max tokens for recall results tags[env:prod], # Tags for stored memories recall_tags[scope:global], # Tags to filter recall recall_tags_matchany, # Tag match mode ) # Now create tools without passing client — uses global config tools create_hindsight_tools(bank_iduser-123)全局配置的底层实现见 config.pyconfigure()返回并保存一个HindsightAutoGenConfigdataclass 到模块级全局变量api_key未显式传入时会回退读取HINDSIGHT_API_KEY环境变量默认 API URL 为https://api.hindsight.vectorize.ioCloud 生产地址reset_config()可清空全局配置测试用例中用于隔离状态。客户端解析逻辑在 _client.py解析顺序为显式传入的client优先 → 显式hindsight_api_url/api_key→ 全局configure()配置 → 默认 URL 与HINDSIGHT_API_KEY环境变量自建客户端时固定设置timeout30.0与 User-Agenthindsight-autogen/versionAPI key 在构造阶段是可选的缺 key 只会在真正发起调用时失败因此即使完全不调用configure()只要设置好HINDSIGHT_API_KEY环境变量工具也能正常工作对应测试 test_tools.py。参数优先级规则从 tools.py 可以确认工具的默认值解析优先级为函数显式参数 全局configure()配置 内置默认值budget默认mid、max_tokens默认4096、recall_tags_match默认any。测试 test_tools.py 验证了“显式budget覆盖全局configure的budget”这一行为。六、用 Tags 做记忆隔离Memory ScopingTags 用于按主题、会话或用户对记忆进行分区实现“写入时打标、读取时过滤”的隔离# Store memories tagged by source tools create_hindsight_tools( clientclient, bank_iduser-123, tags[source:chat, session:abc], recall_tags[source:chat], recall_tags_matchany, )tagsretain 写入时附加的标签env:prod、source:chat、session:abc等 key:value 风格recall_tagsrecall 检索时的过滤标签recall_tags_match标签匹配模式可取any/all/any_strict/all_strict。reflect 也有独立的reflect_tags/reflect_tags_match默认回退到 recall 的对应配置见 tools.py。测试 test_tools.py 与 test_tools.py 分别验证了 recall 与 reflect 的标签透传。七、生产实践模式7.1 错误处理工具失败时会抛出HindsightError定义于 errors.pyAutoGen 会将其作为工具错误呈现给 Agent。在 tools.py 中三个工具均采用“先原样重抛HindsightError其余异常包装为HindsightError(f{op} failed: {e})”的策略因此可以统一捕获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})7.2 Bank 生命周期管理记忆库应在首次使用前创建用完后按需清理。acreate_bank是幂等操作async def main(): client Hindsight(base_urlhttp://localhost:8888) # Create bank (idempotent) await client.acreate_bank(bank_iduser-123) tools create_hindsight_tools(clientclient, bank_iduser-123) # ... use tools ... # Optional: delete bank when no longer needed await client.adelete_bank(bank_iduser-123)端到端测试 test_e2e.py 正是遵循这一生命周期livefixture 创建带随机后缀的 bank测试结束在 finally 中删除并关闭 client。该测试文件默认跳过通过HINDSIGHT_API_URL指向可达服务后才会运行并完整覆盖了 retain→recall 往返、reflect 综合回答、空库 recall 兜底三类场景。7.3 多 Agent 团队独立记忆 vs 共享记忆既可以为每个 Agent 分配独立记忆库也可以让整个团队共享一个库# Per-agent memory researcher_tools create_hindsight_tools(clientclient, bank_idresearcher-memory) writer_tools create_hindsight_tools(clientclient, bank_idwriter-memory) # Shared team memory shared_tools create_hindsight_tools( clientclient, bank_idteam-shared, tags[team:content], )结合 Tags 能力还可以在共享库内再做细粒度分区例如同一团队库内用team:research与team:writing标签隔离职责范围。八、API 参考8.1create_hindsight_tools()签名见 tools.py所有参数均为关键字参数*之后返回list[FunctionTool]。参数默认说明bank_id必填Hindsight 记忆库 IDclientNone预配置的 Hindsight 客户端优先使用hindsight_api_urlNoneAPI 地址未提供 client 时使用api_keyNoneAPI 密钥未提供 client 时使用budgetmidrecall/reflect 的预算级别low/mid/highmax_tokens4096recall 结果的最大 token 数tagsNoneretain 存储时附加的标签recall_tagsNonerecall 检索时的过滤标签recall_tags_matchany标签匹配模式any/all/any_strict/all_strictretain_metadataNoneretain 操作的默认 metadata 字典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综合工具参数在三个工具中的透传行为均已由 test_tools.py 逐项断言如retain_metadata见 L189-L201、reflect_response_schema见 L398-L413。8.2configure()参数默认说明hindsight_api_url生产 APIhttps://api.hindsight.vectorize.ioHindsight API 地址api_keyHINDSIGHT_API_KEY环境变量认证用 API 密钥budgetmid默认 recall 预算级别max_tokens4096默认 recall 最大 token 数tagsNoneretain 操作的默认标签recall_tagsNonerecall 的默认过滤标签recall_tags_matchany默认标签匹配模式包级导出见 __init__.py包括create_hindsight_tools、configure、get_config、reset_config、HindsightAutoGenConfig与HindsightError。九、小结与延伸阅读hindsight-autogen用极小的接入成本一次create_hindsight_tools调用就把 Hindsight 的异步记忆能力注入 AutoGen 的AssistantAgentretain 负责沉淀recall 负责检索reflect 负责综合tags 负责隔离configure()负责全局化HindsightError负责错误边界。若要继续深入可在当前仓库查看集成包完整源码hindsight-integrations/autogen含 tools.py、config.py、_client.py单元测试hindsight-integrations/autogen/tests/test_tools.py端到端测试hindsight-integrations/autogen/tests/test_e2e.py需HINDSIGHT_API_URL指向可用实例依赖与版本约束hindsight-integrations/autogen/pyproject.toml其他框架集成可参考 hindsight-integrations/README.md 中的集成列表AutoGen 位列其中。【免费下载链接】hindsightHindsight: Agent Memory That Learns项目地址: https://gitcode.com/GitHub_Trending/hindsight2/hindsight创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考