资讯动态

Hindsight × Strands Agents 集成指南:用 retain / recall / reflect 为 Strands 智能体赋予长期记忆

发布时间:2026/9/15 13:43:19 来源:尧图企业网站定制
Hindsight × Strands Agents 集成指南用 retain / recall / reflect 为 Strands 智能体赋予长期记忆【免费下载链接】hindsightHindsight: Agent Memory That Learns项目地址: https://gitcode.com/GitHub_Trending/hindsight2/hindsight本指南围绕 Hindsight 官方提供的hindsight-strands集成包展开讲解如何通过 Strands Agents SDK 原生的tool模式为 Strands 智能体接入 Hindsight 的长期记忆能力——hindsight_retain存储、hindsight_recall检索、hindsight_reflect综合作答并覆盖快速接入、记忆注入、客户端生命周期管理、全局配置与底层实现原理。读完本文你将能够在自己的 Strands Agent 项目中直接落地可持久化的记忆机制并理解该集成包各版本演进背后的工程考量。集成定位让 Strands 智能体学会记忆Strands Agents SDK 是社区中一个以 Python 优先的智能体开发框架其核心模式是用tool装饰器把普通 Python 函数包装成可供Agent(tools[...])直接调用的工具。Hindsight 则是会学习的 Agent 记忆Agent Memory That Learns系统提供内存银行memory bank机制与 retain / recall / reflect 三大核心 API。hindsight-strands正是把两者缝合起来的桥梁它以原生tool函数的形式暴露 Hindsight 记忆能力因此无需修改 Strands 的上下文机制直接通过闭包捕获bank_id与客户端即可工作。在 hindsight-integrations/README.md 的 Agent 框架集成清单中Strands 与 LangGraph、LlamaIndex、CrewAI 等并列属于 Hindsight 官方一等公民集成之一。包的基本信息可以从 pyproject.toml 确认Python 3.10依赖strands-agents与hindsight-client0.4.0当前版本为 0.1.3采用 MIT 许可证。快速开始三行代码接入长期记忆安装pip install hindsight-strands最小可用示例参照 strands 集成 README 的 Quick Start接入过程只需两个步骤创建记忆工具、交给 Agent。from strands import Agent from hindsight_strands import create_hindsight_tools tools create_hindsight_tools( bank_iduser-123, hindsight_api_urlhttps://api.hindsight.vectorize.io, api_keyhsk_..., # 或通过环境变量 HINDSIGHT_API_KEY 提供 ) agent Agent(toolstools) agent(Remember that I prefer dark mode) agent(What are my preferences?) tools.close() # 仅在 hindsight-strands 内部创建了客户端时需要关闭创建后Agent 就拥有三个可调用的记忆工具工具名作用参数hindsight_retain将信息写入长期记忆事实、偏好、决策、跨会话上下文contenthindsight_recall在长期记忆中检索相关事实返回编号列表queryhindsight_reflect基于记忆综合生成有推理依据的答案而非罗列原始事实query这三个工具的签名与行为可以直接在 tools.py 中看到hindsight_retain成功时返回Memory stored successfully.hindsight_recall无结果时返回No relevant memories found.有结果时按1. fact1\n2. fact2\n...编号输出hindsight_reflect优先返回综合文本空文本时回退到No relevant memories found.。本地自托管开发如果你通过./scripts/dev/start-api.sh在本地运行 Hindsight 服务把地址指向本地即可见 README 的 Self-hosting 小节tools create_hindsight_tools( bank_iduser-123, hindsight_api_urlhttp://localhost:8888, )本地模式下通常不需要显式传入 API key生产接入则推荐 Hindsight Cloud 或自建 Hindsight API 服务。记忆注入memory_instructions()预召回除了让 Agent 在对话中按需调用工具hindsight-strands还提供memory_instructions()在会话开始前同步执行一次 recall把命中的记忆拼装成字符串注入系统提示词。这在每次对话开始时自动携带用户历史上下文的场景下非常实用from hindsight_strands import create_hindsight_tools, memory_instructions tools create_hindsight_tools( bank_iduser-123, hindsight_api_urlhttps://api.hindsight.vectorize.io, api_keyhsk_..., ) memories memory_instructions( bank_iduser-123, hindsight_api_urlhttps://api.hindsight.vectorize.io, api_keyhsk_..., ) agent Agent( toolstools, system_promptfYou are a helpful assistant.\n\n{memories}, )从 tools.py 的实现看memory_instructions()默认输出格式为Relevant memories: 1. pref1 2. pref2值得注意的是它的容错设计任何异常都会被静默吞掉并返回空字符串return 注释明确说明instructions failures shouldnt block the agent——记忆注入失败不应阻塞智能体启动。对应的测试用例tests/test_tools.py中的test_returns_empty_on_exception验证了该行为。客户端生命周期管理谁创建谁关闭这是本集成最值得注意的工程细节也是 changelog v0.1.3 修复的核心问题。推荐的 FastAPI 生命周期模式README 推荐的模式是在应用 lifespan 中创建一个共享的 Hindsight 客户端通过client...显式传入所有权归应用关闭时调用await client.aclose()from contextlib import asynccontextmanager from fastapi import FastAPI from hindsight_client import Hindsight from hindsight_strands import create_hindsight_tools, memory_instructions asynccontextmanager async def lifespan(app: FastAPI): client Hindsight(base_urlhttp://localhost:8888, api_keytest-key) app.state.hindsight_client client try: yield finally: await client.aclose() app FastAPI(lifespanlifespan) app.post(/chat) async def chat(): client app.state.hindsight_client tools create_hindsight_tools(bank_iduser-123, clientclient) memories memory_instructions(bank_iduser-123, clientclient) ...内部创建客户端时的关闭义务反之如果直接把hindsight_api_url/api_key传给create_hindsight_tools()则客户端由集成内部创建并持有调用方需要在关闭阶段调用await tools.aclose()或tools.close()。围绕这一点源码中设计了一个专门的容器类HindsightTools(list)见 tools.py它是list的子类兼容Agent(tools[...])的列表传参方式记录owns_client标记区分客户端归属提供close()与aclose()仅当owns_clientTrue时才真正关闭内部客户端外部传入的客户端绝不会被误关同时实现上下文管理器协议with tools:/async with tools:会在退出时自动清理。这与 changelog v0.1.3 的 Bug Fix 一一对应该版本修复了Strands 集成未能正确关闭内部持有的 Hindsight 客户端的问题防止了资源泄漏与相关稳定性问题。测试 tests/test_tools.py 中test_close_closes_internally_owned_client与test_close_does_not_close_externally_owned_client分别验证了两种归属场景。客户端解析优先级_resolve_client()的解析逻辑同样位于 tools.py遵循明确优先级显式传入的client直接使用忽略 URL / keyowns_clientFalse否则取hindsight_api_url/api_key参数再回退到全局配置get_config()都没有 URL 时抛出HindsightError(No Hindsight API URL configured. ...)。内部创建客户端时固定传入timeout30.0并附带统一的user_agent。值得注意的是memory_instructions()内部创建的客户端在使用完毕后会自动关闭见finally分支测试test_closes_internally_created_client_on_success/on_exception验证了成功与异常两条路径都会关闭。按需选择工具组合不是每个场景都需要全部三个工具create_hindsight_tools()提供三个开关详见 README 的 Selecting Tools 小节tools create_hindsight_tools( bank_iduser-123, hindsight_api_urlhttp://localhost:8888, enable_retainTrue, enable_recallTrue, enable_reflectFalse, # 省略 reflect )测试覆盖了所有组合默认创建 3 个工具、仅 retain、仅 recall、仅 reflect、全部禁用时返回空列表见 tests/test_tools.py 的TestCreateHindsightTools类。全局配置configure()一次设置处处生效如果不想在每次调用时重复传连接信息可以用configure()设置全局默认值from hindsight_strands import configure, create_hindsight_tools configure( hindsight_api_urlhttp://localhost:8888, api_keyyour-api-key, # 或设置 HINDSIGHT_API_KEY 环境变量 budgetmid, # 召回预算low/mid/high max_tokens4096, # 召回结果的最大 token 数 tags[env:prod], # 存储记忆时附加的标签 recall_tags[scope:global], # 召回时用于过滤的标签 recall_tags_matchany, # 标签匹配模式any/all/any_strict/all_strict ) # 此后无需再传连接信息 tools create_hindsight_tools(bank_iduser-123)从 config.py 的实现可以确认几点细节API key 解析顺序显式api_key参数 HINDSIGHT_API_KEY环境变量 NoneAPI URL 缺省值为生产环境https://api.hindsight.vectorize.io配置以dataclass HindsightStrandsConfig形式保存在模块级全局变量中可通过get_config()读取、reset_config()重置每次调用configure()都会生成新的配置实例并替换旧值测试test_configure_replaces_previous_config验证了这一点在create_hindsight_tools()内部参数与全局配置的优先级为显式参数优先未传则回退全局配置如effective_tags、effective_budget、effective_max_tokens等测试test_retain_explicit_tags_override_config验证了显式标签覆盖全局配置的行为。配置参考三个核心 API 的完整参数表create_hindsight_tools()参数默认值说明bank_id必填Hindsight 记忆银行 IDclientNone预配置的 Hindsight 客户端由调用方管理生命周期hindsight_api_urlNoneAPI 地址传入则集成内部创建并持有客户端api_keyNoneAPI 密钥未传 client 时使用budgetmidrecall/reflect 预算级别low/mid/highmax_tokens4096recall 结果的最大 token 数tagsNone存储记忆时附加的标签recall_tagsNone检索时用于过滤的标签recall_tags_matchany标签匹配模式enable_retainTrue是否包含 retain存储工具enable_recallTrue是否包含 recall检索工具enable_reflectTrue是否包含 reflect综合工具memory_instructions()参数默认值说明bank_id必填Hindsight 记忆银行 IDclientNone预配置的 Hindsight 客户端hindsight_api_urlNoneAPI 地址未传 client 时使用api_keyNoneAPI 密钥未传 client 时使用queryrelevant context about the user记忆注入的召回查询budgetlow召回预算级别max_results5最多注入的记忆条数max_tokens4096召回结果的最大 token 数prefixRelevant memories:\n记忆列表前追加的文本tagsNone过滤召回结果的标签tags_matchany标签匹配模式configure()参数默认值说明hindsight_api_url生产 APIHindsight API 地址api_keyHINDSIGHT_API_KEY环境变量API 认证密钥budgetmid默认召回预算级别max_tokens4096默认召回最大 token 数tagsNoneretain 操作的默认标签recall_tagsNone过滤召回的默认标签recall_tags_matchany默认标签匹配模式verboseFalse是否开启详细日志底层实现原理源码级解读闭包捕获与tool原生集成create_hindsight_tools()返回的每个工具都是闭包函数bank_id和解析后的客户端在构造时被捕获进闭包函数体直接用resolved_client.retain(...)、resolved_client.recall(...)、resolved_client.reflect(...)调用 hindsight-client 中的对应方法。这意味着工具与 Strands 的tool装饰器完全兼容无需修改 Agent 的上下文传递机制。线程池隔离事件循环一个值得展开的实现细节是_run_in_thread()Strands 在自己的 asyncio 事件循环中执行工具而 Hindsight 客户端内部也是 asyncio 实现包括asyncio.timeout在同一运行中的循环里嵌套会冲突。因此集成维护了一个max_workers4的ThreadPoolExecutor把同步调用提交到独立线程执行让每个调用拥有干净的事件循环tools.py 中对此有明确的注释说明。自动创建记忆银行_ensure_bank()在首次调用 retain 前会尝试client.create_bank(bank_idbid, namebid)并且用created_banks集合做去重保证同一客户端只创建一次若银行已存在抛出异常也会静默标记为已创建不影响后续写入。对应测试test_retain_creates_bank与test_retain_creates_bank_only_once验证了建库且仅建一次的行为。统一错误模型所有工具的错误都被收敛到自定义的HindsightError定义于 errors.py。从源码逻辑看若底层已抛出HindsightError则原样透传不包装其余异常则记录logger.error后包装为HindsightError重新抛出。测试test_retain_hindsight_error_not_wrapped与test_retain_failure_raises_hindsight_error分别覆盖了这两种路径。一致的 User-Agent从 tools.py 可以看到模块启动时通过importlib.metadata读取自身版本号取不到时回退0.0.0组装成hindsight-strands/{version}形式的_USER_AGENT并随内部创建的每个客户端请求发送。这正是 changelog v0.1.2 中所有 HTTP 请求携带一致 User-Agent改进的实现载体用于服务端兼容性与问题排查。测试test_creates_client_from_url等均断言了user_agent _USER_AGENT。PEP 561 类型标注支持v0.1.2 的另一项改进是为集成包补齐py.typed标记文件位于 hindsight_strands/py.typed使类型检查器如 mypy、pyright能够读取包内完整的类型标注——这也是hindsight_strands模块内所有函数签名均为显式类型注解如tools: list[Any]、bank_id: str的原因。版本演进从 0.1.1 到 0.1.3版本演进记录来自 strands 集成 Changelog其脉络与本集成包的成熟过程一致版本类型内容0.1.1Features新增 Strands Agents SDK 集成让 Hindsight 记忆工具可用于 Strands 智能体即本文介绍的全部功能起点0.1.2Improvements通过 PEP 561py.typed标记改进 Python 类型支持commitd054b8840.1.2Bug Fixes所有 HTTP 请求携带一致的 User-Agent提升兼容性与可排查性commit9372462e0.1.3Bug Fixes修复内部持有的 Hindsight 客户端未能正确关闭的问题防止资源泄漏与稳定性隐患commit2bfd7747可以看到从 0.1.1 的功能落地到 0.1.3 的生命周期修复版本演进的每一步都能在源码与测试中找到对应实现这也为使用方选择版本提供了参考若你长期运行长生命周期服务应优先使用包含客户端关闭修复的 0.1.3。运行前提与适用限制依据 pyproject.toml 与 README 的 Requirements 小节接入前需满足Python 3.10pyproject 声明支持 3.10 / 3.11 / 3.12安装strands-agents与hindsight-client0.4.0有一个可访问的 Hindsight API 服务可以是 Hindsight Cloud获取 API key也可以是本地自托管服务如./scripts/dev/start-api.sh启动的http://localhost:8888。另外需要注意memory_instructions()的默认召回预算为low区别于工具内 recall 的mid且结果数量受max_results默认 5限制适合作为系统提示词的轻量上下文而configure()仅在调用方显式调用后才生效未调用configure()时get_config()返回None此时必须显式传入client或hindsight_api_url否则会抛出HindsightError。理解这些边界能帮助你在 Strands 项目中更准确地组合记忆能力。【免费下载链接】hindsightHindsight: Agent Memory That Learns项目地址: https://gitcode.com/GitHub_Trending/hindsight2/hindsight创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价