为 AG2 智能体接入 Hindsight 长期记忆:retain / recall / reflect 集成实战指南 为 AG2 智能体接入 Hindsight 长期记忆retain / recall / reflect 集成实战指南【免费下载链接】hindsightHindsight: Agent Memory That Learns项目地址: https://gitcode.com/GitHub_Trending/hindsight2/hindsight本篇指南以 Hindsight 官方 AG2 集成文档skills/hindsight-docs/references/sdks/integrations/ag2.md为主线结合仓库内 hindsight-integrations/ag2 的源码与测试系统讲解如何通过hindsight-ag2包为 AG2社区版 AutoGen fork智能体一键注册持久化记忆工具。读完本文你将掌握register_hindsight_tools()的完整用法、全局配置与逐工具覆盖机制、GroupChat 共享记忆方案以及工具底层的客户端解析、参数透传与错误处理原理。一、AG2 集成是什么AG2原 AutoGen 的社区 fork是一个多智能体对话框架智能体之间通过AssistantAgent、UserProxyAgent与GroupChat协作完成任务。AG2 智能体本身没有跨会话的持久记忆——每次会话结束后之前的对话上下文就丢失了。Hindsight 的 AG2 集成正是为了解决这一问题通过hindsight-ag2包把 Hindsight 的retain存储/ recall检索/ reflect综合推理三个能力封装成 AG2 原生工具函数注册到智能体上后智能体即可在多次对话之间保存、查询并综合使用长期记忆。这些工具直接调用 Hindsight API本地http://localhost:8888或云端地址存储的内容会在会话结束后持久保留。该集成包源码位于 hindsight-integrations/ag2当前版本 0.1.2作为hindsight-ag2发布见 hindsight-integrations/ag2/pyproject.toml。二、特性概览官方文档总结了该集成的五大特性其中前三项与源码实现一一对应Drop-in Tools开箱即用的工具——register_hindsight_tools()一行代码即可注册 retain、recall、reflect 三个工具。源码中该函数在创建工具后自动调用agent.register_for_llm()与executor.register_for_execution()见 hindsight-integrations/ag2/hindsight_ag2/tools.py。AG2-native原生兼容——工具是带Annotated类型提示的普通 Python 函数与 AG2 的register_for_llm/register_for_execution模式完全兼容AG2 依据Annotated元数据生成 LLM 可见的 tool schema。测试TestAnnotatedTypes通过get_type_hints(include_extrasTrue)验证了三个工具的参数都带有__metadata__见 hindsight-integrations/ag2/tests/test_tools.py。GroupChat Support——多个智能体可共享同一个记忆银行bank。Selective Tools——通过include_retain/include_recall/include_reflect开关按需裁剪工具集测试TestCreateHindsightTools验证了组合开关可精确控制返回的工具数量与名称。Simple Configuration——可全局configure()一次也可以在每次创建工具集时按参数覆盖。三、安装与运行前提pip install hindsight-ag2根据 hindsight-integrations/ag2/pyproject.toml 与集成 README 的声明运行前提为Python 3.10pyproject 中requires-python 3.10classifier 覆盖 3.10 / 3.11 / 3.12ag20.9.0hindsight-client0.4.0负责与 Hindsight API 通信的 Python 客户端一个运行中的 Hindsight API 服务本地默认端口 8888或配置为云端地址。注意hindsight-ag2与 AG2 框架包autogen命名空间下的 AG2 发行版是相互独立安装的两者都需要在环境中可用。四、快速开始一行代码注册记忆工具官方文档的 Quick Start 演示了最简接入流程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., )关键点说明register_hindsight_tools(agent, executor, ...)的第二个参数是执行者executor。AG2 的工具调用模型是LLM 声明意图、executor 实际执行agent.register_for_llm(...)让 LLM 看到工具并生成调用executor.register_for_execution()(tool_fn)让UserProxyAgent真正执行函数。两个角色缺一不可。bank_id是必填参数指定记忆银行memory bank——所有记忆按银行隔离不同业务场景可使用不同 bank。hindsight_api_url指向运行中的 Hindsight API 服务。执行上述代码后assistant 在对话中即可自主调用hindsight_retain、hindsight_recall、hindsight_reflect实现跨会话记忆的存取。五、工作原理三个工具与底层 API 的映射集成层本质上是三个薄封装函数把 AG2 工具调用翻译成 Hindsight Python 客户端的 API 调用。官方文档给出的映射表如下工具函数对应 Hindsight 操作行为hindsight_retain(content)retain(bank_id, content, ...)存储内容。Hindsight 会从原始文本中抽取事实facts、实体entities与关系relationshipshindsight_recall(query)recall(bank_id, query, ...)Hindsight 依次执行语义搜索、BM25、图谱遍历与重排序reranking返回编号的匹配记忆列表hindsight_reflect(query)reflect(bank_id, query, ...)Hindsight 基于所有相关记忆结合记忆银行的 disposition traits 综合推理出有依据的答案结合源码 hindsight-integrations/ag2/hindsight_ag2/tools.py可以进一步看到三个工具的实现细节retain默认只传bank_id与contenttags、metadata、document_id仅在配置了对应参数时才透传成功返回Memory stored successfully.。recall总是携带budget默认mid与max_tokens默认4096结果按1. text、2. text的编号列表返回无结果时返回No relevant memories found.。reflect携带budgetmax_tokens默认回退到effective_max_tokens即 reflect 未单独指定时沿用 recall 的 max_tokenstags/tags_match未单独指定时回退到 recall 的对应配置返回response.text为空时同样返回No relevant memories found.。三个工具的参数都用Annotated[str, ...]描述用途——例如 retain 的 content 参数描述为要存入长期记忆的信息包括重要事实、用户偏好、决策或任何需要跨会话记住的内容。AG2 会将这些元数据转换为 LLM 可见的 JSON Schema。六、配置详解全局配置与逐工具覆盖6.1 全局配置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()将参数封装成HindsightAG2Configdataclass 存为全局配置见 hindsight-integrations/ag2/hindsight_ag2/config.py。值得注意的默认值与回退逻辑hindsight_api_url缺省回退到DEFAULT_HINDSIGHT_API_URL https://api.hindsight.vectorize.io生产环境地址api_key会回退读取环境变量HINDSIGHT_API_KEYbudget默认mid可选low / mid / highmax_tokens默认4096recall_tags_match默认any可选any / all / any_strict / all_strict配置对象还带verbose字段用于开启详细日志。配套函数get_config()返回当前全局配置reset_config()将其重置为None。6.2 逐工具覆盖create_hindsight_tools构造器参数优先于全局配置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], )从 hindsight-integrations/ag2/hindsight_ag2/tools.py 可以看出严格的优先级解析顺序显式参数 全局配置 内置默认值。例如effective_budget budget if budget is not None else (config.budget if config else mid)——显式传budgethigh时覆盖全局配置未显式传但调过configure()时用全局值两者都没有时用mid。测试TestConfigDefaults完整覆盖了这一回退链。6.3 客户端解析当未传client时resolve_client()见 hindsight-integrations/ag2/hindsight_ag2/_client.py负责构造Hindsight客户端依次从显式参数、全局配置解析 URL 与 API key两者都拿不到 URL 时抛出HindsightError(No Hindsight API URL configured. ...)客户端统一设置timeout30.0与user_agenthindsight-ag2/{version}版本号来自包元数据便于服务端识别调用来源与排障。七、GroupChat 场景多智能体共享记忆银行在团队协作型对话中多个智能体共享同一个 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)这段代码把researcher与writer都注册到同一个bank_idteam-memory。研究员存入的调研事实写作者在后续对话中通过 recall / reflect 即可读取实现团队级共享长期记忆。执行者executor只需注册一次。八、手动注册完全掌控注册过程若需要对工具注册做细粒度控制例如自定义description、动态挑选工具可以先用create_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)这里descriptiontool_fn.__doc__把函数的 docstring 作为 AG2 注册时的工具描述——这正是register_hindsight_tools()内部自动完成的动作见 hindsight-integrations/ag2/hindsight_ag2/tools.py。测试TestRegisterHindsightTools.test_registers_with_docstring_descriptions验证了每个register_for_llm调用都携带非空 description。九、API 参考完整参数表9.1 配置函数函数说明configure(...)设置全局连接与默认配置返回HindsightAG2Configget_config()获取当前全局配置未配置时返回Nonereset_config()将全局配置重置为None9.2 create_hindsight_tools 参数以下为官方文档完整参数表默认值与源码实现一致参数默认值说明bank_id必填Hindsight 记忆银行 IDclientNone预先配置好的Hindsight客户端优先级最高hindsight_api_url来自全局配置Hindsight API 地址api_key来自全局配置API 密钥budgetmidrecall / reflect 预算等级low/mid/highmax_tokens4096recall 结果的最大 token 数tagsNone存储记忆时附加的标签recall_tagsNone检索时用于过滤的标签recall_tags_matchany标签匹配模式any/all/any_strict/all_strictretain_metadataNoneretain 操作的元数据字典retain_document_idNoneretain 的文档 ID用于分组/更新记忆recall_typesNone过滤的事实类型world/experience/observationrecall_include_entitiesFalse在 recall 结果中包含实体信息reflect_contextNonereflect 操作的附加上下文reflect_max_tokensmax_tokensreflect 结果的最大 token 数reflect_response_schemaNone约束 reflect 输出格式的 JSON Schemareflect_tagsrecall_tagsreflect 检索记忆的过滤标签reflect_tags_matchrecall_tags_matchreflect 的标签匹配模式include_retainTrue是否包含 retain 工具include_recallTrue是否包含 recall 工具include_reflectTrue是否包含 reflect 工具十、源码级深入错误处理、类型提示与工程质量10.1 统一的错误包装三个工具内部都用 try/except 包裹客户端调用并把任何异常统一包装为HindsightError定义于 hindsight-integrations/ag2/hindsight_ag2/errors.py错误消息分别以Retain failed: 、Recall failed: 、Reflect failed: 开头。测试分别用RuntimeError(connection refused)模拟底层故障并断言异常类型与消息前缀见 hindsight-integrations/ag2/tests/test_tools.py。这样上层 AG2 循环收到的是语义明确的领域异常而不是底层网络/序列化异常。10.2 PEP 561 类型信息与 User-Agent根据集成 changelogskills/hindsight-docs/references/changelog/integrations/ag2.mdv0.1.2 起随包分发 PEP 561 类型信息py.typed文件见 hindsight-integrations/ag2/hindsight_ag2/py.typedIDE 与 mypy 等工具可获得完整类型推断v0.1.2 起所有 HTTP 请求携带标识性 User-Agent 头即_client.py中构造的hindsight-ag2/{version}并修复了依赖中的高危安全漏洞v0.1.1 为首次发布引入了完整的 AG2 框架集成。10.3 测试覆盖单元测试 hindsight-integrations/ag2/tests/test_tools.py 共覆盖六个测试类可归纳为四类验证工具工厂行为默认返回 3 个工具、工具名顺序、include 开关组合、无 client/URL 时抛错参数透传tags、metadata、document_id、budget、max_tokens、types、include_entities、context、response_schema、tags/tags_match 均精确透传给 mock 客户端调用默认值与回退未显式指定时使用全局配置全局配置再回退到内置默认mid、4096注册行为register_hindsight_tools对每个工具调用一次register_for_llm与register_for_execution且 description 非空。十一、典型应用建议结合文档与源码可以给出如下落地建议按 bank 隔离记忆域个人助手用bank_iduser-{id}团队协作用共享bank_idteam-memory避免不同用户/场景的记忆互相污染。用标签做细粒度过滤存储时通过tags打标如source:ag2、scope:user检索时用recall_tagsrecall_tags_match精确圈定记忆范围reflect 默认继承 recall 的标签配置无需重复设置。按需裁剪工具只读场景可设include_retainFalse只做问答可只保留include_recallTrue减少 LLM 的工具选择面。用retain_document_id管理文档级记忆同一 document_id 的多次 retain 会被分组/更新适合按会话或按文档组织记忆该参数在工具调用时透传给 retain API。用reflect_response_schema约束输出需要结构化结论如 JSON 摘要时传入 JSON Schema让 reflect 按指定格式作答。结语hindsight-ag2用不到 300 行核心代码把 Hindsight 的持久记忆能力完整地桥接到 AG2 生态一行注册、全局配置、逐工具覆盖、GroupChat 共享配合 AG2 原生的Annotated工具模式与统一的HindsightError错误语义。若要继续深入可阅读集成源码 hindsight-integrations/ag2/hindsight_ag2/tools.py、测试 hindsight-integrations/ag2/tests/test_tools.py以及集成完整说明 hindsight-integrations/ag2/README.md。【免费下载链接】hindsightHindsight: Agent Memory That Learns项目地址: https://gitcode.com/GitHub_Trending/hindsight2/hindsight创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考