Hindsight 为 OpenAI Agents 注入长期记忆:hindsight-openai-agents 集成实战与演进解析
Hindsight 为 OpenAI Agents 注入长期记忆hindsight-openai-agents 集成实战与演进解析【免费下载链接】hindsightHindsight: Agent Memory That Learns项目地址: https://gitcode.com/GitHub_Trending/hindsight2/hindsight本篇文章以 hindsight-docs/src/pages/changelog/integrations/openai-agents.md 的版本记录为主线结合 hindsight-integrations/openai-agents 集成包的完整源码、README 与测试系统讲解如何基于 Hindsight 为 OpenAI Agents SDK 的 Agent 添加持久化长期记忆包含 retain/recall/reflect 三工具的使用、memory_instructions()记忆自动注入、全局配置与标签作用域、生产级错误处理与多 Agent 工作流并逐版本解读 0.1.0 → 0.1.2 的功能演进。读完本文你将掌握在 Python 3.10 环境中为 OpenAI Agents Agent 接入 Hindsight 记忆后端并安全上生产的完整方案。一、集成包是什么为 OpenAI Agents 提供的记忆工具层hindsight-openai-agents是 Hindsight 官方维护的 OpenAI Agents SDK 集成包pyproject.toml 中声明为 Beta 状态、MIT 许可。它的核心职责在包 docstring 中写得很清楚init.pyProvidesFunctionToolinstances that give OpenAI agents long-term memory via Hindsights retain/recall/reflect APIs.也就是说它不是一套独立的记忆系统而是把 Hindsight 的持久化记忆能力包装成 OpenAI Agents SDK 原生支持的FunctionTool让 Agent 通过工具调用的方式完成记忆的存储retain、检索recall与综合reflect。一个 Agent 默认获得三个工具工具名职责底层 APIhindsight_retain将信息存入长期记忆Hindsight.aretain()hindsight_recall检索与查询相关的记忆事实Hindsight.arecall()hindsight_reflect基于记忆综合出有推理的回答Hindsight.areflect()三个工具的完整实现位于 tools.py均通过function_tool装饰器生成可直接传给Agent(tools[...])。运行前提有两个一个正在运行的 Hindsight 实例可通过 Docker 自托管或使用 Hindsight Cloud以及 Python 3.10。安装命令如下pip install hindsight-openai-agents openai-agentshindsight-openai-agents会自动拉取openai-agents与hindsight-client两个依赖见 pyproject.toml 的 dependenciesopenai-agents0.7.0、hindsight-client0.4.0。二、快速上手一次完整的记住-召回闭环集成包 README 给出的 Quick Start 是一个可以直接运行的asyncio程序README.mdimport asyncio from agents import Agent, Runner from hindsight_client import Hindsight from hindsight_openai_agents import create_hindsight_tools async def main(): client Hindsight(base_urlhttp://localhost:8888) await client.acreate_bank(bank_iduser-123) tools create_hindsight_tools(clientclient, bank_iduser-123) agent Agent( nameassistant, instructionsYou are a helpful assistant with long-term memory. Use hindsight_retain to store important facts. Use hindsight_recall to search memory before answering., toolstools, ) # Store a memory result await Runner.run(agent, Remember that I prefer dark mode) print(result.final_output) # 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 Runner.run(agent, What are my UI preferences?) print(result.final_output) # Clean up await client.aclose() asyncio.run(main())这段代码揭示了集成的几个关键用法Bank 先行在使用任何工具前通过client.acreate_bank(bank_iduser-123)创建记忆库。bank_id是create_hindsight_tools()的唯一必填参数工具的所有操作都作用在该记忆库上。工具即记忆入口create_hindsight_tools(client..., bank_id...)返回的FunctionTool列表直接作为Agent(tools...)传入Agent 在对话中自行决定何时调用哪个记忆工具。异步索引延迟retain 后 Hindsight 会在后台异步完成事实抽取fact extraction、实体解析entity resolution与向量化embeddings因此示例中 retain 与 recall 背靠背执行时等待了 3 秒。README 特别注明该延迟只在同一脚本中先存后查时需要生产中一般不需要。从源码看hindsight_retain实际构造的调用参数是bank_id content并可选附加tags、metadata、document_idtools.pyhindsight_recall则传入bank_id query budget max_tokens并把返回结果格式化为带编号的事实列表tools.py。三、memory_instructions()免工具调用的记忆自动注入create_hindsight_tools让 Agent 显式调用记忆工具但还有一种更无感的方案通过memory_instructions()在每一轮对话自动把相关记忆注入系统提示词。from hindsight_openai_agents import create_hindsight_tools, memory_instructions agent Agent( nameassistant, instructionsmemory_instructions( clientclient, bank_iduser-123, base_instructionsYou are a helpful assistant with long-term memory., ), toolscreate_hindsight_tools( clientclient, bank_iduser-123, include_recallFalse, # recall handled by memory_instructions ), )memory_instructions()返回一个与 OpenAI Agents SDKAgent(instructions...)兼容的异步可调用对象。它的工作方式tools.py每次 Agent 运行前内部调用arecall()检索与query默认relevant context about the user相关的记忆将命中的记忆按prefix默认\n\nRelevant memories:\n拼接到base_instructions之后返回若召回失败或没有结果优雅降级为仅返回base_instructions不会中断 Agent 运行通过max_results控制注入的记忆条数上限默认 5 条避免提示词膨胀。因为记忆已经注入系统提示词配套使用时应关闭hindsight_recall工具include_recallFalse避免重复检索。这一点在 0.1.1 版本中被正式写入 README 与 API 参考文档。四、工具选择与全量配置参考4.1 按需裁剪工具并非每个 Agent 都需要全部三个记忆工具create_hindsight_tools提供了三个开关tools create_hindsight_tools( clientclient, bank_iduser-123, include_retainTrue, include_recallTrue, include_reflectFalse, # Omit reflect )单元测试 test_tools.py 验证了默认返回 3 个工具、工具顺序为[hindsight_retain, hindsight_recall, hindsight_reflect]、以及任意组合裁剪的行为。4.2 参数配置参考表完整继承自 README参数默认值说明bank_id必填Hindsight 记忆库 IDclientNone预配置的 Hindsight client优先使用hindsight_api_urlNoneAPI 地址未提供 client 时使用api_keyNoneAPI 密钥未提供 client 时使用budgetmidrecall/reflect 预算级别low/mid/highmax_tokens4096recall 结果的最大 token 数tagsNone存储记忆时附加的标签recall_tagsNone检索记忆时用于过滤的标签recall_tags_matchany标签匹配模式any/all/any_strict/all_strictretain_metadataNoneretain 操作的默认元数据字典retain_document_idNoneretain 的默认 document_id用于分组/覆盖记忆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综合工具参数优先级遵循显式参数 全局配置 内置默认值的三级回退规则这在 tools.py 与测试 test_tools.pyTestConfigFallback中都有体现。五、全局配置configure()与后端解析逻辑当项目中多个 Agent 都要使用记忆时逐个传client会显得冗余。集成包提供了进程级全局配置from hindsight_openai_agents 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 tools create_hindsight_tools(bank_iduser-123)configure()的实现位于 config.py内部维护一个全局HindsightOpenAIAgentsConfig单例并提供get_config()读取、reset_config()重置。需要注意几个细节默认后端是 CloudDEFAULT_HINDSIGHT_API_URL https://api.hindsight.vectorize.io这是 0.1.2 版本默认使用 Cloud 后端的直接体现。不传任何 URL 时工具会默认连到 Hindsight Cloud自托管用户必须显式覆盖 URL。API Key 环境变量回退configure(api_key...)未传时会回退读取HINDSIGHT_API_KEY环境变量HINDSIGHT_API_KEY_ENV。无 configure() 也能工作_client.py的resolve_client()_client.py解析 client 的顺序是显式client参数 → 显式 URL/Key → 全局配置 → 默认 Cloud URL 环境变量 Key。同时它会注入user_agenthindsight-openai-agents/version与 30 秒默认超时。API Key 构造期可选文档明确说明 Key 缺失时构造不会失败只在真正发起调用时报错方便本地开发先跑通。test_config.py0.1.1 版本新增系统覆盖了这些行为默认值、全参数配置、环境变量回退、显式参数覆盖环境变量、以及 reset 语义。六、用 Tags 做记忆作用域隔离Hindsight 支持给记忆打标签集成包把这一能力映射为tags存储时打标与recall_tags检索时过滤两组参数可用于按主题、会话或用户隔离记忆# 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, )标签匹配模式recall_tags_match支持四种取值any、all、any_strict、all_strict默认any见 config.py 的TagsMatch类型。对应地reflect 操作也有独立的reflect_tags/reflect_tags_match不设置时默认跟随 recall 的标签配置。从源码可以看到标签是如何被传递的tools.py当recall_tags非空时arecall()会同时携带tags与tags_matchmemory_instructions()也有同等的tags/tags_match参数。七、生产模式错误处理、Bank 生命周期与多 Agent 工作流0.1.1 版本在 README 中新增了 Production Patterns 章节覆盖三个生产关键场景。7.1 错误处理三个工具内部都做了 try/except 包装异常会被转换为带上下文的HindsightErrorerrors.py例如Retain failed: connection refused。随后由 OpenAI Agents SDK 自动捕获工具异常并作为错误字符串返回给 Agent让 Agent 自己决定如何继续——而不是让整个对话崩溃from hindsight_openai_agents.errors import HindsightError # The agent will see error messages and can decide how to proceed result await Runner.run(agent, What do you remember about me?) print(result.final_output)单元测试也验证了这条链路test_tools.py当aretain抛出RuntimeError时工具返回的错误字符串包含Retain failed。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)7.3 多 Agent 工作流既可以给每个 Agent 独立的记忆库也可以让多个 Agent 共享一个记忆库并用标签区分# Per-agent memory researcher_tools create_hindsight_tools(clientclient, bank_idresearcher-memory) writer_tools create_hindsight_tools(clientclient, bank_idwriter-memory) # Shared memory across agents shared_tools create_hindsight_tools( clientclient, bank_idteam-shared, tags[team:content], )八、版本演进解读0.1.0 → 0.1.1 → 0.1.2集成包的完整演进记录在 hindsight-docs/src/pages/changelog/integrations/openai-agents.md结合仓库代码可以还原每次发布的实际内容8.1 v0.1.0集成诞生Features新增对 OpenAI Agents SDK 的集成为 Hindsight 的 AI 记忆工作流提供支持。这是集成的第一个版本奠定了create_hindsight_tools retain/recall/reflect 三工具的基础形态。8.2 v0.1.1文档、配置与生产模式补全Improvements包含四项均可在当前仓库中找到对应物修正 openai-agents SDK 版本要求pyproject.toml与 README 的 Requirements 均声明openai-agents 0.7.0将memory_instructions()加入 README 与 API 参考即本文第三节介绍的记忆自动注入能力tools.pyREADME 新增 Production Patterns 章节即错误处理、Bank 生命周期与多 Agent 工作流README 的 Production Patterns 一节新增专门的test_config.py覆盖默认值、configure()全参数、环境变量回退与reset_config()重置test_config.py。8.3 v0.1.2默认 Cloud 后端与门禁化 E2E 测试Improvements通过默认使用 Cloud 后端提升集成可靠性并加入带真实 LLM 分桶real-LLM bucketing的门禁端到端测试。默认 Cloud 后端config.py中DEFAULT_HINDSIGHT_API_URL https://api.hindsight.vectorize.io且test_tools.py的test_defaults_to_cloud_without_config显式断言无 client、无配置、无显式 URL 时构造的Hindsight客户端使用默认 Cloud URL 且不带 api_keytest_tools.py。门禁 E2E 测试test_e2e.py 会先探测HINDSIGHT_API_URL/health端点默认http://localhost:8888不可达时整体跳过同时整个模块打上requires_real_llmmarker真实 LLM 分桶默认被 PR CI 通过-m not requires_real_llm排除需要时用-m requires_real_llm单独运行。该 marker 的说明定义在 pyproject.toml 的[tool.pytest.ini_options]中。E2E 测试覆盖了 retain→recall 往返、reflect 综合、空库 recall、以及memory_instructions记忆注入四条真实链路每条都使用随机命名的临时 bank 并在结束后清理保证测试可重复且不污染数据。九、测试体系与可靠性保障集成包的测试分两层见hindsight-integrations/openai-agents/tests/确定性单元测试test_config.py、test_tools.py使用 mock 的Hindsightclient 验证工具注册、参数透传、标签/预算/token 传递、实体输出、错误字符串回退、全局配置回退与覆盖等行为不依赖任何外部服务可在 CI 中稳定运行门禁 E2E 测试test_e2e.py要求真实的 Hindsight 实例由HINDSIGHT_API_URL指向通过/health探活自动跳过并归入requires_real_llm分桶与普通 PR CI 隔离。这种单元测试保确定性 E2E 验证真实链路的双层设计正是 0.1.2 版本所强调的可靠性保障的核心机制。十、总结从 0.1.0 到 0.1.2hindsight-openai-agents走完了一条从能用到好用的演进三个记忆工具让 OpenAI Agents Agent 原生获得持久记忆能力memory_instructions()把记忆注入从显式工具调用简化为自动上下文全局配置、标签作用域与生产模式章节解决了多 Agent、多用户场景的落地问题默认 Cloud 后端与门禁 E2E 测试则保障了开箱即用的可靠性与回归质量。如果你想深入了解实现细节推荐按此顺序阅读仓库源码README.md → tools.py三工具与记忆注入实现→ config.py配置与默认值→ _client.py后端解析→ test_e2e.py真实链路验证。【免费下载链接】hindsightHindsight: Agent Memory That Learns项目地址: https://gitcode.com/GitHub_Trending/hindsight2/hindsight创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考