Hindsight × SmolAgents 集成指南:用 retain / recall / reflect 为 Agent 赋予持久记忆
Hindsight × SmolAgents 集成指南用 retain / recall / reflect 为 Agent 赋予持久记忆【免费下载链接】hindsightHindsight: Agent Memory That Learns项目地址: https://gitcode.com/GitHub_Trending/hindsight2/hindsight导读Hindsight 是一个会学习的 Agent 记忆系统而hindsight-smolagents是它在 Hugging Face SmolAgents 生态中的官方集成包。本文以 hindsight-integrations/smolagents/README.md 为主线结合仓库内 tools.py、config.py 与测试源码完整讲解安装、三件套记忆工具Retain 存储 / Recall 检索 / Reflect 综合、系统提示词注入、全局配置与客户端解析优先级让你能直接照抄代码给 SmolAgents Agent 加上跨会话的长期记忆。一、集成包定位给 SmolAgents 的三件记忆工具SmolAgents 本身是无状态的每个会话结束后Agent 就忘记了之前说过的话、用户的偏好和已经做出的决定。hindsight-smolagents通过 SmolAgents 原生的Tool基类模式把 Hindsight 的持久记忆能力封装成三个可直接挂载到 Agent 上的工具工具名底层操作作用hindsight_retainHindsightretain把重要事实、用户偏好、决策等存储到长期记忆hindsight_recallHindsightrecall按语义相似度搜索长期记忆返回编号列表hindsight_reflectHindsightreflect基于记忆综合出一个经过推理的回答而非原始事实罗列该包的核心特性对应源码 tools.py 与 pyproject.toml原生 Tool 子类三个类分别继承smolagents.Tool声明了name、description、inputs与output_type能被 SmolAgents 的CodeAgent/ToolCallingAgent直接识别记忆指令Memory Instructions提供memory_instructions()在构造期预检索记忆并格式化为文本供注入 Agent 的system_prompt工厂函数create_hindsight_tools()一次调用创建全部或部分工具且所有工具共享同一个 Hindsight 客户端实例全局配置configure()一次配置后续所有工具免传连接参数也支持直接传入预构建的Hindsight客户端。二、安装与环境要求pip install hindsight-smolagents根据 pyproject.toml 的声明包依赖与运行环境如下Python 3.10官方分类器覆盖 3.10 / 3.11 / 3.12smolagentsHugging Face 的轻量 Agent 框架提供Tool基类与CodeAgenthindsight-client 0.4.0Hindsight 的 Python 客户端提供Hindsight类及retain/recall/reflect/create_bank等方法一个可访问的 Hindsight API 服务可以是 Hindsight Cloud也可以是本地自托管的服务。需要说明的是API 连接默认指向 Hindsight Cloudhttps://api.hindsight.vectorize.io仓库中另提供自托管方案本地开发可用 scripts/dev/start-api.sh 启动 API 服务容器化部署可参考 docker/docker-compose 下的各编排文件如 external-pg、pg_search 等完整安装步骤可查阅仓库根目录 README.md。三、快速开始10 行代码接入记忆from smolagents import CodeAgent, HfApiModel from hindsight_smolagents import create_hindsight_tools tools create_hindsight_tools( bank_iduser-123, hindsight_api_urlhttps://api.hindsight.vectorize.io, api_keyhsk_..., # 或设置 HINDSIGHT_API_KEY 环境变量 ) agent CodeAgent( toolstools, modelHfApiModel(), ) agent.run(Remember that I prefer dark mode) agent.run(What are my preferences?)第一轮对话中Agent 调用hindsight_retain把偏好深色模式写入记忆库第二轮对话即使属于全新会话Agent 也能通过hindsight_recall或hindsight_reflect取回该偏好从而正确回答我的偏好是什么。bank_id是记忆库的唯一标识通常按用户维度划分如user-123不同bank_id之间记忆相互隔离。自托管本地开发如果你在用 scripts/dev/start-api.sh 在本地运行 Hindsight把hindsight_api_url指向本地服务即可tools create_hindsight_tools( bank_iduser-123, hindsight_api_urlhttps://api.hindsight.vectorize.io, # 替换为你本地服务的地址 )注意包内默认 URL 是生产环境地址本地开发时务必显式覆盖hindsight_api_url否则请求会打到云端。四、记忆指令Memory Instructions把记忆预注入系统提示词SmolAgents 没有像某些框架那样的记忆自动注入机制因此hindsight-smolagents提供memory_instructions()在 Agent 构造阶段同步执行一次 recall把命中的记忆格式化成字符串由你手动拼进system_promptfrom hindsight_smolagents import create_hindsight_tools, memory_instructions tools create_hindsight_tools( bank_iduser-123, hindsight_api_urlhttps://api.hindsight.vectorize.io, ) memories memory_instructions( bank_iduser-123, hindsight_api_urlhttps://api.hindsight.vectorize.io, ) agent CodeAgent( toolstools, modelHfApiModel(), system_promptfYou are a helpful assistant.\n\n{memories}, )从源码看tools.pymemory_instructions()的默认行为是使用默认查询relevant context about the user与预算budgetlow执行client.recall(...)截取前max_results5条结果用Relevant memories:\n前缀 编号列表格式化任何异常都被静默吞掉并返回空字符串——记忆注入失败绝不应阻塞 Agent 启动这是刻意的容错设计测试 test_tools.py 中test_returns_empty_on_exception验证了这一点若未配置客户端或 URL则抛出HindsightErrorNo Hindsight API URL configured这是唯一会向外暴露的异常路径。memory_instructions() 参数速查参数默认值说明bank_id必填Hindsight 记忆库 IDclientNone预配置的 Hindsight 客户端优先hindsight_api_urlNoneAPI 地址未传 client 时使用api_keyNoneAPI 密钥未传 client 时使用queryrelevant context about the user记忆注入用的检索查询budgetlow检索预算等级low/mid/highmax_results5注入的最大记忆条数max_tokens4096检索结果的最大 token 数prefixRelevant memories:\n记忆列表前拼接的文本tagsNone过滤检索结果的标签tags_matchany标签匹配模式五、三个记忆工具的原理与使用5.1 HindsightRetainTool存储记忆hindsight_retain接收单个字符串输入content把信息写入长期记忆from hindsight_smolagents import HindsightRetainTool retain_tool HindsightRetainTool( bank_iduser-123, hindsight_api_urlhttps://api.hindsight.vectorize.io, )从 tools.py 可以看到两个值得注意的实现细节自动建库首次调用forward()前工具会先调用client.create_bank(bank_id..., namebank_id)并通过self._created_banks集合在会话内去重确保一个会话中只建库一次对应测试test_retain_creates_bank/test_retain_creates_bank_only_once容错建库若建库抛异常例如库已存在会被捕获并视为成功不阻断后续 retain对应测试test_retain_bank_already_exists。forward(content)最终调用client.retain(bank_id..., content..., tags...)成功返回字符串Memory stored successfully.失败时统一包装为HindsightError已是HindsightError的异常原样透传并记录 error 日志。所有异常统一在 errors.py 中定义。5.2 HindsightRecallTool检索记忆hindsight_recall接收查询字符串query返回编号列表形式的记忆文本from hindsight_smolagents import HindsightRecallTool recall_tool HindsightRecallTool( bank_iduser-123, hindsight_api_urlhttps://api.hindsight.vectorize.io, budgetmid, # 检索预算low/mid/high max_tokens4096, # 结果最大 token 数 recall_tags[scope:global], # 过滤标签 recall_tags_matchany, # 标签匹配模式 )其forward()调用client.recall(...)对应底层客户端实现 hindsight_client.py然后把response.results逐条格式化为1. text\n2. text...无结果或results为None时返回No relevant memories found.。值得注意的是标签匹配模式的语义源自底层客户端的类型定义anyOR包含无标签项、allAND包含无标签项、any_strictOR排除无标签项、all_strictAND排除无标签项。hindsight-smolagents默认取any。5.3 HindsightReflectTool综合记忆hindsight_reflect接收问题query让 Hindsight 基于记忆库综合出有推理的回答而非返回原始事实from hindsight_smolagents import HindsightReflectTool reflect_tool HindsightReflectTool( bank_iduser-123, hindsight_api_urlhttps://api.hindsight.vectorize.io, budgetmid, )其forward()调用client.reflect(bank_id..., query..., budget...)底层实现见 hindsight_client.py返回response.text若文本为空或None回退为No relevant memories found.。适合基于我了解的信息总结一下…… / 推断一下……这类需要综合推理的提问。六、直接使用单个工具类工厂函数不是唯一入口你也可以把工具类实例直接塞进tools列表自由组合from hindsight_smolagents import HindsightRetainTool, HindsightRecallTool agent CodeAgent( tools[ HindsightRetainTool( bank_iduser-123, hindsight_api_urlhttps://api.hindsight.vectorize.io, ), HindsightRecallTool( bank_iduser-123, hindsight_api_urlhttps://api.hindsight.vectorize.io, ), ], modelHfApiModel(), )七、按需选择工具create_hindsight_tools()提供三个开关参数默认全部为True。当你的场景只需要部分能力时例如只存不查、或只查不存显式关闭多余工具可以减小 Agent 的工具面、降低误调用概率tools create_hindsight_tools( bank_iduser-123, hindsight_api_urlhttps://api.hindsight.vectorize.io, enable_retainTrue, enable_recallTrue, enable_reflectFalse, # 关闭 reflect )测试 test_tools.py 验证了四种组合默认创建 3 个工具、仅 retain、仅 recall、仅 reflect、以及全部关闭时返回空列表。三个工具各自拥有独立的namehindsight_retain/hindsight_recall/hindsight_reflect便于 Agent 区分调用。八、全局配置一次配置处处使用当多个 Agent 或多次创建工具时反复传 URL / key 很繁琐。configure()把连接参数与默认值写入进程级全局配置之后创建工具只需传bank_idfrom hindsight_smolagents import configure, create_hindsight_tools configure( hindsight_api_urlhttps://api.hindsight.vectorize.io, # Hindsight Cloud默认值 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 的实现可以看到几个关键机制默认 URLDEFAULT_HINDSIGHT_API_URL https://api.hindsight.vectorize.io环境变量回退api_key未显式传入时自动读取HINDSIGHT_API_KEY环境变量test_configure_reads_api_key_from_env验证配置即数据类配置存为HindsightSmolAgentsConfigdataclass 实例configure()返回该实例get_config()读取当前配置reset_config()清空全局配置重复配置覆盖多次调用configure()会整体替换旧配置实例而非增量合并。configure() 参数速查参数默认值说明hindsight_api_urlHindsight Cloudhttps://api.hindsight.vectorize.ioHindsight API 地址api_keyHINDSIGHT_API_KEY环境变量认证密钥budgetmid默认检索预算等级max_tokens4096默认检索最大 token 数tagsNoneretain 操作默认附加的标签recall_tagsNonerecall 操作默认过滤的标签recall_tags_matchany默认标签匹配模式verboseFalse是否启用详细日志create_hindsight_tools() 参数速查参数默认值说明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标签匹配模式enable_retainTrue是否包含 retain 工具enable_recallTrue是否包含 recall 工具enable_reflectTrue是否包含 reflect 工具九、客户端解析优先级源码级细节无论走工厂函数、单个工具类还是memory_instructions()最终都会经过 tools.py 中的_resolve_client()来解析Hindsight客户端。结合测试 test_tools.py 的用例解析优先级可归纳为显式传入的client优先只要client非Nonehindsight_api_url与api_key一律被忽略未传 client 时url 显式 hindsight_api_url or 全局配置的 urlkey 显式 api_key or 全局配置的 key显式参数覆盖全局配置如test_explicit_url_overrides_config构造客户端时Hindsight(base_urlurl, timeout30.0)若 key 存在则追加api_keykey兜底校验既没有 client、也没有任何 URL包括configure()未设置默认值时→ 抛出HindsightError(No Hindsight API URL configured. ...)。另外注意create_hindsight_tools()内部只解析一次客户端并让三个工具共享同一个实例测试test_shares_client_across_tools断言三个工具的_client是同一对象避免重复创建连接。十、错误处理与故障排查统一异常类型所有记忆操作失败都会以HindsightError定义于 errors.py向 Agent 暴露原始异常已记录在hindsight_smolagents的 logger 中Retain failed/Recall failed/Reflect failed前缀。记忆指令静默降级memory_instructions()在 recall 失败时返回空字符串保证 Agent 正常启动。建库自动容错retain 首次调用自动建库库已存在等异常不会阻断写入。连接缺失最常见的报错是No Hindsight API URL configured此时请检查是否传了client/hindsight_api_url或先调用configure()。本地 vs 云端务必确认hindsight_api_url指向的环境本地自托管或 Hindsight Cloud与你的api_key匹配。十一、测试覆盖与质量保障仓库为集成包提供了完整的单元测试test_tools.py覆盖客户端解析优先级显式 client 参数 全局配置、三个工具的属性与forward()行为含编号格式化、空结果回退、tags/budget/max_tokens 透传、异常包装与日志、工厂函数的工具组合、记忆指令的格式化与容错test_config.py覆盖默认值、环境变量读取、显式参数覆盖环境变量、配置替换与重置。运行测试在hindsight-integrations/smolagents目录下pip install -e .[dev] pytest十二、小结hindsight-smolagents用最符合 SmolAgents 生态的方式原生Tool子类 工厂函数把 Hindsight 的持久记忆能力封装成了开箱即用的三个工具retain存储、recall检索、reflect综合再辅以memory_instructions()的提示词预注入与configure()的全局配置。无论是个人助手记住用户偏好还是业务 Agent 跨会话记住领域知识这套集成都能在几分钟内完成接入。更多参考集成包源码hindsight-integrations/smolagents/hindsight_smolagents/底层 Python 客户端hindsight-clientretain/recall/reflect/create_bank的完整签名自托管部署仓库根目录 README.md 与 docker/docker-compose 编排文件、scripts/dev/start-api.sh【免费下载链接】hindsightHindsight: Agent Memory That Learns项目地址: https://gitcode.com/GitHub_Trending/hindsight2/hindsight创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考