十年匠心定制 · 商业建站与技术教学双线并行 咨询热线:400-886-1026 service@lmnt.cn
ARTICLE DETAIL

资讯详情

深耕网站建设与运营推广的一线实战洞察。

Hindsight × OpenAI Agents:用 hindsight-openai-agents 为 Agent 接入持久化长期记忆

Hindsight × OpenAI Agents:用 hindsight-openai-agents 为 Agent 接入持久化长期记忆 Hindsight × OpenAI Agents用 hindsight-openai-agents 为 Agent 接入持久化长期记忆【免费下载链接】hindsightHindsight: Agent Memory That Learns项目地址: https://gitcode.com/GitHub_Trending/hindsight2/hindsight本篇技术指南围绕 Hindsight 仓库中hindsight-integrations/openai-agents集成hindsight-openai-agentsPython 包展开讲解如何让基于 OpenAI Agents SDK 构建的 Agent 获得跨会话的长期记忆能力——存储、检索与综合记忆。读者将掌握该集成的三大记忆工具hindsight_retain/hindsight_recall/hindsight_reflect、自动注入记忆的memory_instructions()、全局配置与标签隔离方案以及面向生产的错误处理与多 Agent 工作流设计并了解其版本演进脉络0.1.0 → 0.1.2。一、集成概览与版本演进hindsight-openai-agents是 Hindsight 官方提供的 OpenAI Agents SDK 集成包它把 Hindsight 的 retain存储/ recall检索/ reflect综合能力封装成 OpenAI Agents SDK 标准的FunctionTool实例直接传给Agent(tools[...])即可使用。它依赖openai-agents0.7.0与hindsight-client0.4.0要求 Python 3.10见 pyproject.toml。关联文档是skills/hindsight-docs/references/changelog/integrations/openai-agents.md它记录了该集成的三个版本版本类型核心变更0.1.0Features首次加入与 OpenAI Agents SDK 的集成为 Hindsight 的 AI 记忆工作流提供FunctionTool支持0.1.1Improvements修正 openai-agents SDK 版本要求在 README 与 API 参考中补充memory_instructions()README 新增 Production Patterns 章节错误处理、bank 生命周期、多 Agent 工作流新增test_config.py覆盖 defaults、configure、env var 回退与 reset0.1.2Improvements默认改用 Cloud 后端提升集成可靠性并新增带真实 LLM 分桶的门控端到端测试从源码看0.1.2 中_client.py定义的DEFAULT_HINDSIGHT_API_URL https://api.hindsight.vectorize.io正是“默认 Cloud 后端”的实现——当调用方既未传入 client 也未调用configure()时工具会自动回退到该默认 API 地址同时包版本号已升至0.1.2见_version.py与 pyproject.toml与 changelog 的 0.1.2 条目一致。测试侧pyproject.toml 中定义了requires_real_llmmarker用于标记需要真实 Hindsight 服务与 LLM 的端到端测试与 changelog 所述“gated end-to-end tests with real-LLM bucketing”对应。二、安装与前置条件前置条件一个运行中的 Hindsight 实例自托管如通过 Docker Compose 部署或使用 Hindsight CloudPython 3.10。安装命令pip install hindsight-openai-agents openai-agentshindsight-openai-agents会自动拉入openai-agents与hindsight-client两个依赖。在仓库中集成源码位于hindsight-integrations/openai-agents/包结构如下config.py全局配置configure/get_config/reset_configtools.py工具工厂create_hindsight_tools与memory_instructions_client.pyHindsight client 解析逻辑errors.py统一异常HindsightErrortests/test_config.py、test_tools.py、test_e2e.py。三、快速开始让 Agent 拥有记忆最简用法如下完整示例见 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, ) # 存储一条记忆 result await Runner.run(agent, Remember that I prefer dark mode) print(result.final_output) # Hindsight 会异步处理 retained 内容事实抽取、实体解析、向量化。 # 短暂等待确保记忆可被检索到生产环境中仅当 retain 与 recall 在同一脚本中背靠背执行时才需要该延迟。 await asyncio.sleep(3) # 之后检索 result await Runner.run(agent, What are my UI preferences?) print(result.final_output) # 清理 await client.aclose() asyncio.run(main())create_hindsight_tools()默认返回三个工具test_tools.py的test_returns_three_tools_by_default与test_tool_names验证了这一点工具名作用hindsight_retain将信息存入长期记忆事实、用户偏好、决策、任何需要跨会话记住的内容hindsight_recall检索长期记忆中的相关事实返回带编号的记忆列表hindsight_reflect基于记忆综合生成有推理依据的答案而非返回原始事实片段从tools.py的源码实现看三个工具内部通过function_tool装饰器封装分别调用 Hindsight client 的aretain、arecall、areflect异步方法所有异常都被捕获并包装为HindsightError抛出便于上层统一处理。四、自动注入记忆memory_instructions()与其依赖 Agent 主动调用hindsight_recallmemory_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 已由 memory_instructions 处理 ), )memory_instructions()返回一个与 OpenAI Agents SDKAgent(instructions...)兼容的异步可调用对象SDK 的 instructions 接受str | Callable | None。每一轮运行时它会从 Hindsight 检索相关记忆并追加到base_instructions之后如果 recall 失败或没有命中则优雅回退到纯base_instructions。这正是 0.1.1 changelog 中“将memory_instructions()加入 README 与 API 参考”所指的能力。其内部实现见tools.py支持以下可调参数参数默认值说明queryrelevant context about the user检索记忆时使用的查询语句max_results5注入到提示词中的最多记忆条数prefix\n\nRelevant memories:\n记忆列表前插入的文本前缀budget/max_tokens取全局配置检索预算与 token 上限tags/tags_match取全局配置检索时的标签过滤五、按需选择工具只保留需要的工具避免 Agent 工具过载tools create_hindsight_tools( clientclient, bank_iduser-123, include_retainTrue, include_recallTrue, include_reflectFalse, # 省略 reflect )三个include_*开关分别控制 retain / recall / reflect 工具的生成tools.py中对应if include_retain:/if include_recall:/if include_reflect:分支test_tools.py的test_include_retain_only、test_include_recall_only、test_include_reflect_only、test_no_tools_when_all_excluded对四种组合均有覆盖。六、全局配置configure()当多个 Agent 共享同一套连接与默认参数时可全局配置一次from hindsight_openai_agents import configure, create_hindsight_tools configure( hindsight_api_urlhttp://localhost:8888, api_keyyour-api-key, # 或设置 HINDSIGHT_API_KEY 环境变量 budgetmid, # recall 预算low/mid/high max_tokens4096, # recall 结果最大 token 数 tags[env:prod], # 存储记忆时附加的标签 recall_tags[scope:global], # recall 时用于过滤的标签 recall_tags_matchany, # 标签匹配模式 ) # 之后无需传 client 即可创建工具 tools create_hindsight_tools(bank_iduser-123)配置解析与优先级源码级从config.py看全局配置是一个HindsightOpenAIAgentsConfigdataclass包含以下默认值DEFAULT_HINDSIGHT_API_URL https://api.hindsight.vectorize.ioHINDSIGHT_API_KEY_ENV HINDSIGHT_API_KEY环境变量名DEFAULT_BUDGET midDEFAULT_MAX_TOKENS 4096DEFAULT_RECALL_TAGS_MATCH anyconfigure()的 API key 解析遵循“显式参数 环境变量”的优先级resolved_key api_key or os.environ.get(HINDSIGHT_API_KEY_ENV)test_config.py中的test_configure_reads_api_key_from_env与test_configure_explicit_overrides_env分别验证了 env 回退与显式覆盖两种行为。在_client.py的resolve_client()中client 解析优先级为显式传入的client 显式hindsight_api_url/api_keyconfigure()的全局配置 默认 URL HINDSIGHT_API_KEY环境变量。构造 client 时还会附带timeout30.0与user_agenthindsight-openai-agents/{version}。因此即使完全不调用configure()只要设置了HINDSIGHT_API_KEY环境变量工具也能直接使用这也是 0.1.2 默认 Cloud 后端行为的落点。test_config.py还覆盖了get_config()未配置时返回None、reset_config()清空全局配置等行为。七、用标签隔离记忆Memory Scoping标签可以将记忆按主题、会话或用户进行分区# 按来源给存储的记忆打标签 tools create_hindsight_tools( clientclient, bank_iduser-123, tags[source:chat, session:abc], recall_tags[source:chat], recall_tags_matchany, )tags存储retain时附加到记忆上的标签recall_tags检索recall时用于过滤的标签recall_tags_match标签匹配模式可取any/all/any_strict/all_strict默认any。create_hindsight_tools()中所有标签/预算/最大 token 参数都遵循“显式参数优先否则回退全局配置最后使用模块级默认值”的取值链见tools.py中effective_tags、effective_recall_tags、effective_budget等的计算逻辑。八、配置参数参考表create_hindsight_tools()支持的完整参数如下与 README 中 Configuration Reference 一致并补充了源码中的默认值行为参数默认值说明bank_id必填Hindsight 记忆库bankIDclientNone预配置的 Hindsight clienthindsight_api_urlNoneAPI URL未提供 client 时使用api_keyNoneAPI key未提供 client 时使用budgetmidrecall/reflect 预算级别low/mid/highmax_tokens4096recall 结果的最大 token 数tagsNone存储记忆时应用的标签recall_tagsNone检索时用于过滤的标签recall_tags_matchany标签匹配模式any/all/any_strict/all_strictretain_metadataNoneretain 操作的默认 metadata 字典retain_document_idNoneretain 的默认 document_id用于分组/upsert 记忆recall_typesNone过滤的事实类型world / experience / observationrecall_include_entitiesFalse检索结果是否包含实体信息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实现细节hindsight_retain成功时返回Memory stored successfully.hindsight_recall返回带编号的记忆列表如1. ...、2. ...开启recall_include_entities时每行追加[entities: ...]无结果时返回No relevant memories found.hindsight_reflect返回综合后的文本答案无结果时同样返回No relevant memories found.。九、生产模式错误处理、Bank 生命周期与多 Agent 工作流这一章节是 0.1.1 changelog 中“README 新增 Production Patterns 章节”的直接内容。错误处理工具会把错误以工具错误结果的形式暴露给 AgentOpenAI Agents SDK 会自动捕获工具抛出的异常并将其转换为错误字符串返回给 Agent让 Agent 自行决定如何继续from hindsight_openai_agents.errors import HindsightError # Agent 会看到错误消息并决定如何继续 result await Runner.run(agent, What do you remember about me?) print(result.final_output)底层实现中所有工具体都用try/except包裹统一抛出errors.py定义的HindsightError。Bank 生命周期在使用前创建 bank、使用完毕后清理async def main(): client Hindsight(base_urlhttp://localhost:8888) # 创建 bank幂等 await client.acreate_bank(bank_iduser-123) tools create_hindsight_tools(clientclient, bank_iduser-123) # ... 使用工具 ... # 可选不再需要时删除 bank await client.adelete_bank(bank_iduser-123)多 Agent 工作流可以为每个 Agent 分配独立记忆库或让多个 Agent 共享同一记忆库# 按 Agent 隔离记忆 researcher_tools create_hindsight_tools(clientclient, bank_idresearcher-memory) writer_tools create_hindsight_tools(clientclient, bank_idwriter-memory) # 跨 Agent 共享记忆 shared_tools create_hindsight_tools( clientclient, bank_idteam-shared, tags[team:content], )十、版本演进背后的工程细节综合 changelog 与仓库源码可以看到该集成包的演进逻辑0.1.0建立 retain / recall / reflect 三个工具的核心能力对应tools.py的create_hindsight_tools。0.1.1补齐工程化细节——修正 SDK 版本要求openai-agents0.7.0、文档与 API 参考对齐memory_instructions()、新增 Production Patterns 章节、新增test_config.py覆盖 defaults、configure、env var 回退与 reset 四个维度。0.1.2默认指向 Cloud 后端_client.py中DEFAULT_HINDSIGHT_API_URL并引入requires_real_llmmarker 门控端到端测试把“需要真实 LLM 服务”的测试与确定性的 PR-CI 单元测试隔离-m not requires_real_llm排除-m requires_real_llm单独运行。结语通过hindsight-openai-agentsOpenAI Agents SDK 开发者可以用最小成本为 Agent 补齐长期记忆能力三个开箱即用的FunctionTool、每轮自动注入记忆的memory_instructions()、全局配置与标签隔离以及清晰的错误处理与多 Agent 设计模式。从 0.1.0 到 0.1.2 的演进也展示了一个集成包从“能用”到“工程可靠”的完整路径。更多细节可继续阅读hindsight-integrations/openai-agents/README.md、config.py与tools.py以及完整的集成包 changelogskills/hindsight-docs/references/changelog/integrations/目录下各集成页面。【免费下载链接】hindsightHindsight: Agent Memory That Learns项目地址: https://gitcode.com/GitHub_Trending/hindsight2/hindsight创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表