ARTICLE · INTELLIGENCE

战地情报 · 详情页

来自尧图项目组的一线实战观察与深度解析

Hindsight × AG2 集成指南:为 AutoGen 社区分支 Agent 接入跨会话持久化记忆

Hindsight × AG2 集成指南:为 AutoGen 社区分支 Agent 接入跨会话持久化记忆 Hindsight × AG2 集成指南为 AutoGen 社区分支 Agent 接入跨会话持久化记忆【免费下载链接】hindsightHindsight: Agent Memory That Learns项目地址: https://gitcode.com/GitHub_Trending/hindsight2/hindsight本文档基于仓库中 hindsight-docs/docs-integrations/ag2.md 编写并结合 hindsight-integrations/ag2 下的源码、测试与打包配置展开介绍如何为 AG2AutoGen 社区分支Agent 接入 Hindsight 持久化记忆系统。导读AG2 是 AutoGen 的社区分支框架其多 Agent 协作模型非常灵活但默认不提供跨会话的长期记忆。本文讲解如何通过hindsight-ag2集成包用一行代码为 AG2 Agent 注册retain记忆写入、recall记忆检索、reflect记忆反思三个工具让 Agent 在多次对话之间持续记住用户偏好、事实与决策。读完本文你将掌握安装步骤、全局配置与按工具集覆盖参数的方法、GroupChat 共享记忆的搭建以及从源码层面理解三个工具背后的 Hindsight API 调用链与配置优先级规则。功能特性一览Drop-in 工具register_hindsight_tools()一行同时注册 retain / recall / reflect 三个工具AG2 原生兼容工具是带Annotated类型提示的普通 Python 函数与 AG2 的register_for_llm/register_for_execution注册模式完全匹配GroupChat 支持多个 Agent 可以共享同一个 memory bank实现团队级统一记忆按需选择工具通过include_retain/include_recall/include_reflect只注册需要的子集配置简单灵活既可全局配置一次也可在每次创建工具集时按需覆盖。安装pip install hindsight-ag2从 hindsight-integrations/ag2/pyproject.toml 可以看到本包的版本与依赖约束requires-python 3.10依赖ag20.9.0、hindsight-client0.4.0也就是说除了 Python 3.10 与 AG2 之外你还需要一个正在运行的 Hindsight API 服务本地可通过docker compose部署或使用托管服务工具的每个调用都会通过hindsight-client走 HTTP 请求。快速开始把记忆工具挂到 Agent 上只需几步from autogen import AssistantAgent, UserProxyAgent, LLMConfig from hindsight_ag2 import register_hindsight_tools llm_config LLMConfig(api_typeopenai, modelgpt-4o-mini) with llm_config: assistant AssistantAgent( nameassistant, system_messageYou are a helpful assistant with long-term memory., ) user_proxy UserProxyAgent( nameuser, human_input_modeNEVER, ) # Register Hindsight memory tools on both agents register_hindsight_tools( assistant, user_proxy, bank_idmy-bank, hindsight_api_urlhttp://localhost:8888, ) # The assistant can now use hindsight_retain, hindsight_recall, hindsight_reflect result user_proxy.initiate_chat( assistant, messageRemember that I prefer Python over JavaScript., )执行后assistant 就获得了跨会话记忆能力hindsight_retain把「偏好 Python」写入 bank下一次对话时hindsight_recall能把它搜出来hindsight_reflect还能基于历史记忆给出综合回答。工作原理三个工具背后的 Hindsight APIregister_hindsight_tools内部调用create_hindsight_tools()实现见 hindsight-integrations/ag2/hindsight_ag2/tools.py默认生成三个函数工具底层 Hindsight 操作行为说明hindsight_retain(content)retain(bank_id, content, ...)把原始文本交给 Hindsight由服务端自动抽取事实facts、实体entities与关系后存储hindsight_recall(query)recall(bank_id, query, ...)Hindsight 执行语义搜索、BM25、图谱遍历与重排返回编号后的匹配记忆列表hindsight_reflect(query)reflect(bank_id, query, ...)Hindsight 基于 bank 的 disposition 特征把相关记忆综合成有推理依据的回答源码视角工具函数的真实形态在 tools.py 中hindsight_retain的关键实现如下def hindsight_retain( content: Annotated[ str, The information to store in long-term memory. Include important facts, user preferences, decisions, or anything that should be remembered across conversations., ], ) - str: retain_kwargs: dict[str, Any] {bank_id: bank_id, content: content} if effective_tags: retain_kwargs[tags] effective_tags if retain_metadata: retain_kwargs[metadata] retain_metadata if retain_document_id: retain_kwargs[document_id] retain_document_id resolved_client.retain(**retain_kwargs) return Memory stored successfully.可以看到几个关键设计参数描述内嵌在类型提示里Annotated[str, ...]中的说明文字会由 AG2 读取并生成 LLM 可见的 tool schema帮助模型理解「该存什么」。测试 tests/test_tools.py 的TestAnnotatedTypes正是用get_type_hints(..., include_extrasTrue)验证了三个工具的参数都带有__metadata__。可选参数按需注入只有显式传入tags/metadata/document_id时才加入请求体保证默认调用足够轻量。统一异常封装底层 client 抛出的任何异常都会被记录日志并重新包装为HindsightError见 hindsight-integrations/ag2/hindsight_ag2/errors.py返回给 AG2 的错误信息带Retain failed: ...前缀便于 Agent 识别失败原因。hindsight_recalltools.py内部会组装bank_id/query/budget/max_tokens并按需附带tagstags_match、types、include_entities最后把response.results渲染成「1. 记忆文本 / 2. 记忆文本 …」的编号列表返回若结果为空则返回No relevant memories found.。hindsight_reflecttools.py则把context、max_tokens缺省回退到effective_max_tokens、response_schema、tags/tags_match缺省回退到 recall 的对应值传给reflect最终返回response.text。客户端如何被解析工具并不直接 new client而是经由 hindsight-integrations/ag2/hindsight_ag2/_client.py 的resolve_client()按优先级解析显式传入的client优先通常是调用方已配置好的Hindsight实例显式传入的hindsight_api_url/api_key全局配置configure()中设置的值环境变量HINDSIGHT_API_KEY仅对 api_key 生效。客户端默认timeout30.0并携带User-Agent: hindsight-ag2/version版本号取自包元数据见 _client.py。若以上路径都解析不到 URL会直接抛出HindsightError: No Hindsight API URL configured...——这一点在test_raises_without_client_or_config中有对应测试。配置详解全局配置configurefrom hindsight_ag2 import configure configure( hindsight_api_urlhttp://localhost:8888, api_keyyour-key, # or set HINDSIGHT_API_KEY env var budgetmid, # low / mid / high max_tokens4096, tags[source:ag2], # default tags for retain )configure()的实现位于 hindsight-integrations/ag2/hindsight_ag2/config.py它把参数组装为HindsightAG2Config数据类存入模块级全局变量。值得注意的默认值hindsight_api_url默认指向生产环境https://api.hindsight.vectorize.ioapi_key未传时自动回退读取环境变量HINDSIGHT_API_KEYbudget默认midmax_tokens默认4096recall_tags_match默认any。配套的get_config()返回当前全局配置reset_config()将其重置为None测试用例在每个用例前后调用它们以保证隔离。按工具集覆盖create_hindsight_tools构造函数参数优先于全局配置。全局配置适合「一次设置、处处使用」而按工具集覆盖适合「同一进程里多个 Agent 需要不同记忆策略」的场景from hindsight_ag2 import create_hindsight_tools tools create_hindsight_tools( bank_idmy-bank, hindsight_api_urlhttp://localhost:8888, budgethigh, max_tokens8192, tags[team:alpha], )从源码tools.py可以看到完整的生效优先级显式参数 全局配置(configure) 内置默认值(mid / 4096 / any)例如effective_budget budget if budget is not None else (config.budget if config else mid)。test_config_budget_used_when_no_explicit与test_explicit_budget_overrides_config两个测试分别验证了「配置兜底」与「显式覆盖」两条路径。API Referencecreate_hindsight_tools 全部参数下表来自原文档参数名与源码签名一一对应tools.py参数默认值说明bank_id必填Hindsight 记忆库memory bankIDclientNone预配置的Hindsight客户端优先级最高hindsight_api_url来自全局配置Hindsight API 地址api_key来自全局配置API 密钥budgetmidrecall / reflect 的检索预算low/mid/highmax_tokens4096recall 结果的最大 token 数tagsNoneretain 写入记忆时附加的标签recall_tagsNonerecall 检索时用于过滤的标签recall_tags_matchany标签匹配模式any/all/any_strict/all_strictretain_metadataNoneretain 操作的元数据字典retain_document_idNoneretain 的文档 ID用于分组 / 更新已有记忆recall_typesNone过滤的事实类型world / experience / observationrecall_include_entitiesFalserecall 结果是否包含实体信息reflect_contextNonereflect 操作的额外上下文reflect_max_tokens取max_tokensreflect 结果的最大 token 数reflect_response_schemaNone约束 reflect 输出格式的 JSON Schemareflect_tags取recall_tagsreflect 使用的记忆过滤标签reflect_tags_match取recall_tags_matchreflect 的标签匹配模式include_retainTrue是否包含 retain 工具include_recallTrue是否包含 recall 工具include_reflectTrue是否包含 reflect 工具典型用法示例只做记忆存储include_recallFalse, include_reflectFalse限定检索范围recall_tags[scope:user], recall_tags_matchall让 reflect 输出结构化 JSONreflect_response_schema{type: object, properties: {summary: {type: string}}}。对应行为均有测试覆盖test_include_retain_only、test_recall_passes_tags、test_reflect_passes_max_tokens_and_response_schema等可在 hindsight-integrations/ag2/tests/test_tools.py 中查阅。GroupChat多个 Agent 共享一份记忆多 Agent 协作时让 researcher 与 writer 读写同一个 bank即可实现「谁存的事实大家都能用」from autogen import AssistantAgent, UserProxyAgent, GroupChat, GroupChatManager, LLMConfig from hindsight_ag2 import register_hindsight_tools llm_config LLMConfig(api_typeopenai, modelgpt-4o-mini) with llm_config: researcher AssistantAgent(nameresearcher, system_messageYou research topics.) writer AssistantAgent(namewriter, system_messageYou write content.) executor UserProxyAgent(nameexecutor, human_input_modeNEVER) # All agents share the same memory bank for agent in [researcher, writer]: register_hindsight_tools(agent, executor, bank_idteam-memory) group_chat GroupChat(agents[researcher, writer, executor], messages[]) manager GroupChatManager(groupchatgroup_chat)核心在于所有 Agent 使用同一个bank_id。记忆的隔离与共享完全由 bank 维度控制这与 Hindsight 的多租户模型一致不同团队用不同 bank 互不干扰同一团队共享一个 bank 实现知识复用。executorUserProxyAgent负责实际执行工具调用因此也被传入register_hindsight_tools。手动注册完全控制注册方式register_hindsight_tools实际上只是「创建工具 自动注册」的便捷封装。需要完全掌控注册过程时可以拆开做from hindsight_ag2 import create_hindsight_tools tools create_hindsight_tools( bank_idmy-bank, hindsight_api_urlhttp://localhost:8888, ) for tool_fn in tools: assistant.register_for_llm(descriptiontool_fn.__doc__)(tool_fn) user_proxy.register_for_execution()(tool_fn)这段代码的语义对应register_hindsight_tools的源码实现tools.py对每个工具函数调用agent.register_for_llm(descriptiontool_fn.__doc__)让 LLM 侧感知工具及其用途描述再调用executor.register_for_execution()让执行侧可以运行该函数。手动方式下你可以只为特定 Agent 注册工具子集自定义description默认使用函数 docstring把工具注册到任意两个 agent 组合不限于 assistant/user_proxy。测试test_registers_all_tools验证了默认会注册 3 个工具且两边的注册次数均为 3test_registers_with_docstring_descriptions验证每个register_for_llm调用都带上了非空 description。模块导出与错误处理包的公共 API 集中在 hindsight-integrations/ag2/hindsight_ag2/init.py导出了from .config import HindsightAG2Config, configure, get_config, reset_config from .errors import HindsightError from .tools import create_hindsight_tools, register_hindsight_tools即configure/get_config/reset_config配置管理、HindsightAG2Config配置数据类、HindsightError统一异常、create_hindsight_tools/register_hindsight_tools工具工厂与注册。错误处理方面三个工具对底层调用的异常处理模式完全一致见 tools.pyexcept Exception as e: logger.error(Retain failed: %s, e) raise HindsightError(fRetain failed: {e}) from e底层网络错误、认证失败、服务端异常都会被包装成HindsightError抛出避免原始异常类型泄漏到 AG2 的工具执行层。测试中test_retain_raises_hindsight_error、test_recall_raises_hindsight_error、test_reflect_raises_hindsight_error分别用RuntimeError模拟底层故障验证了这一行为。快速验证与测试仓库在 hindsight-integrations/ag2/tests/test_tools.py 中提供了完整的单元测试覆盖工具默认数量与命名、按开关裁剪工具、Annotated类型提示、参数透传tags/metadata/document_id/budget/max_tokens/types/include_entities/context/response_schema、配置回退与覆盖、错误封装、自动注册行为等。克隆仓库后可在包目录运行cd hindsight-integrations/ag2 uv run pytest环境要求小结Python 3.10ag2 0.9.0一个正在运行的 Hindsight API 服务hindsight_api_url指向其地址本地默认常为http://localhost:8888认证需要时通过api_key参数或HINDSIGHT_API_KEY环境变量提供。满足以上条件后你的 AG2 Agent 即可获得「会学习」的长期记忆跨会话记住用户、跨 Agent 共享知识、按需对历史记忆进行推理与综合。【免费下载链接】hindsightHindsight: Agent Memory That Learns项目地址: https://gitcode.com/GitHub_Trending/hindsight2/hindsight创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
RELATED READING

延伸阅读

更多一线实战笔记与深度复盘,助您持续精进