尧图网络 高端网站定制 · 原创设计
免费咨询热线
400-888-6620
免费获取方案
LlamaIndex 持久化记忆集成指南:用 Hindsight 为 Agent 构建跨会话长期记忆
LlamaIndex 持久化记忆集成指南用 Hindsight 为 Agent 构建跨会话长期记忆【免费下载链接】hindsightHindsight: Agent Memory That Learns项目地址: https://gitcode.com/GitHub_Trending/hindsight2/hindsight本篇技术指南讲解如何在 LlamaIndex 生态中接入 Hindsighthindsight-llamaindex包为 ReActAgent 等 Agent 提供跨会话的持久化长期记忆。你将掌握两条互补的接入路径——基于BaseMemory接口的全自动记忆以及基于BaseToolSpec的 Agent 主动记忆工具retain/recall/reflect并学会通过 mission、tags、budget 等参数完成生产级配置。文中所有参数与行为均以仓库内实现源码与测试用例为准。集成概览两种互补的记忆模式hindsight-llamaindex在 hindsight-integrations/llamaindex 目录下实现它围绕 Hindsight 的三类核心记忆操作构建retain存储把用户偏好、决策、项目上下文等信息写入长期记忆recall检索根据当前问题召回相关记忆片段reflect反思基于记忆库中的事实合成连贯、有推理的答案。对应地该包对外提供两种使用模式模式实现类驱动方式适用场景自动记忆HindsightMemory实现 LlamaIndexBaseMemory每轮对话自动 retain、自动 recall 注入上下文想让 Agent 开箱即忘不掉的最简方案主动工具HindsightToolSpec继承 LlamaIndexBaseToolSpecAgent 自主决定何时调用 retain/recall/reflect需要显式控制记忆行为的复杂 Agent两种模式共享同一套客户端解析逻辑见 hindsight-integrations/llamaindex/hindsight_llamaindex/_client.py与全局配置系统可以混合使用。安装与依赖pip install hindsight-llamaindex根据 hindsight-integrations/llamaindex/pyproject.toml 的声明包要求Python 3.10llama-index-core 0.11.0hindsight-client 0.4.0使用前需要有一个可访问的 Hindsight 服务端。本地自托管时通常通过Hindsight(base_urlhttp://localhost:8888)指定地址若未显式提供任何地址客户端解析逻辑会回退到默认云端地址DEFAULT_HINDSIGHT_API_URL见 config.py此时建议设置HINDSIGHT_API_KEY环境变量。模式一自动记忆BaseMemoryHindsightMemory是接入成本最低的方式消息在每一轮对话中自动存储相关记忆在每轮输入前自动召回并作为 system message 注入上下文。调用方式是在agent.run(..., memorymemory)时传入而不是在构造 Agent 时传入import asyncio from hindsight_client import Hindsight from hindsight_llamaindex import HindsightMemory from llama_index.core.agent import ReActAgent from llama_index.llms.openai import OpenAI async def main(): client Hindsight(base_urlhttp://localhost:8888) memory HindsightMemory.from_client( clientclient, bank_iduser-123, missionTrack user preferences and project context, ) agent ReActAgent(tools[], llmOpenAI(modelgpt-4o)) response await agent.run(Remember that I prefer dark mode, memorymemory) print(response) asyncio.run(main())自动记忆的工作机制HindsightMemory遵循 Mem0 类 LlamaIndex 集成的经典模式本地会话缓冲区 跨会话长期记忆。其生命周期由 memory.py 中的BaseMemory接口方法驱动事件发生什么Agent 接收输入aget(input)向 Hindsight 召回相关记忆以 system message 形式前置到消息列表Agent 产生输出aput(message)将消息 retain 到 Hindsight供未来召回新会话开始通过 recall 获得历史记忆本地对话缓冲区从空开始源码中有几个值得注意的实现细节召回查询的自动回退_recall_query()在未显式传入input时会回退到本地缓冲区中最近一条 USER 消息作为召回查询。这一点对llama_index.core.agent.workflow.ReActAgent等 workflow 式 Agent 至关重要——它们主路径调用aget()时不传input参数若无此回退自动召回将永远不触发对应测试见 test_memory.py。ReAct 推理痕迹清洗_extract_clean_content()会用正则识别 assistant 消息中的Thought:/Action:/Observation:推理痕迹仅提取最后一个Answer:块存入记忆若纯推理且无答案则跳过 retain避免把工具调用日志污染进记忆库测试见 test_memory.py。USER 消息则原样存储。本地缓冲区裁剪put()/aput()在追加消息后按chat_history_limit裁剪超出部分丢弃最旧消息reset()仅清空本地缓冲区不会删除 Hindsight 中的记忆。故障静默降级retain/recall 失败仅记录日志并返回空结果绝不向上抛异常——记忆服务不可用时 Agent 依然能正常工作。HindsightMemory.from_client()参数参数类型默认值说明clientHindsight必填Hindsight 客户端实例bank_idstr必填记忆库Memory BankIDmissionstrNone记忆库使命描述首次使用时自动创建 bankcontextstrllamaindexretain 操作的来源标签budgetstrmid召回预算等级low/mid/highmax_tokensint4096召回结果的最大 token 数tagslist[str]Noneretain 操作附加的标签recall_tagslist[str]None召回时的标签过滤条件recall_tags_matchstrany标签匹配模式system_promptstr(内置模板)记忆 system message 模板必须包含{memories}占位符chat_history_limitint100本地缓冲区的最大消息数内置 system prompt 模板为见 memory.pyBelow are relevant memories from previous conversations: {memories} Use these memories to provide more personalized and contextual responses.召回结果会以- 记忆文本的列表形式填充{memories}再包装成SYSTEM角色消息。如果某轮召回为空则不注入 system message避免空模板污染上下文。其他构造方式from_url 与 from_defaults除from_client外HindsightMemory还提供两种工厂方法from_url(hindsight_api_url, bank_id, api_key..., ...)无需预先构造客户端内部以base_url和 30 秒超时直接创建Hindsight实例见 memory.py。from_defaults(bank_id, ...)走与工具工厂完全一致的共享客户端解析路径——既不传client也不传 URL 时回退到默认云端地址并读取HINDSIGHT_API_KEY环境变量对应测试见 test_memory.py。模式二Agent 主动记忆工具BaseToolSpec当需要 Agent 自行判断何时该记、何时该查时用HindsightToolSpec把 retain/recall/reflect 暴露成 LlamaIndex 工具。快速开始Tool Specimport asyncio from hindsight_client import Hindsight from hindsight_llamaindex import HindsightToolSpec from llama_index.llms.openai import OpenAI from llama_index.core.agent import ReActAgent async def main(): client Hindsight(base_urlhttp://localhost:8888) spec HindsightToolSpec( clientclient, bank_iduser-123, missionTrack user preferences, ) tools spec.to_tool_list() agent ReActAgent(toolstools, llmOpenAI(modelgpt-4o)) response await agent.run(Remember that I prefer dark mode) print(response) asyncio.run(main())快速开始工厂函数from hindsight_llamaindex import create_hindsight_tools tools create_hindsight_tools( clientclient, bank_iduser-123, missionTrack user preferences, )选择要暴露的工具工具按需裁剪有两种等价写法# 方式一to_tool_list() 指定函数 tools spec.to_tool_list(spec_functions[recall_memory, reflect_on_memory]) # 方式二工厂函数开关 tools create_hindsight_tools( clientclient, bank_iduser-123, include_retainTrue, include_recallTrue, include_reflectFalse, )工具名与语义如下均同时提供同步与异步实现异步版本供 ReActAgent 等异步 Agent 使用同步版本作为兜底见 tools.py工具作用返回retain_memory(content)将信息写入长期记忆成功/失败提示字符串recall_memory(query)检索相关记忆带编号的记忆列表无结果时返回No relevant memories found.reflect_on_memory(query)基于记忆合成有推理的答案反思文本三个工具都包含完整的方法名与 docstring 元数据可作为 LLM 的 function schemacreate_hindsight_tools的include_*三个开关都设为False时会返回空列表测试见 test_tools.py。全局配置 configure()通过configure()设置连接与默认值之后创建工具/记忆时即可省略重复参数from hindsight_llamaindex import configure configure( hindsight_api_urlhttp://localhost:8888, api_keyyour-api-key, # 或设置 HINDSIGHT_API_KEY 环境变量 budgetmid, tags[source:llamaindex], contextmy-app, missionTrack user preferences, ) # 无需再传 client/url tools create_hindsight_tools(bank_iduser-123)配置对象HindsightLlamaIndexConfig见 config.py支持的字段包括hindsight_api_url、api_key、budget、max_tokens、tags、recall_tags、recall_tags_match、context、mission、verbose。配置解析遵循显式参数 全局配置 内置默认值的优先级链例如configure(budgethigh)后未显式传budget的HindsightToolSpec会继承high而显式传入的值总是覆盖全局配置测试见 test_tools.py。API key 的解析还支持纯环境变量路径即使从未调用configure()resolve_client()也会直接读取HINDSIGHT_API_KEY环境变量见 _client.py因此只设环境变量即可跑通是受测试保护的行为。HindsightToolSpec()完整参数参数类型默认值说明bank_idstr必填要操作的 Hindsight 记忆库clientHindsightNone预配置的 Hindsight 客户端hindsight_api_urlstrNoneAPI 地址未提供 client 时使用api_keystrNoneAPI key未提供 client 时使用budgetstrNone→mid召回/反思预算low、mid、highmax_tokensintNone→4096召回结果最大 token 数tagslist[str]None存储记忆时附加的标签recall_tagslist[str]None召回结果过滤标签recall_tags_matchstrNone→any标签匹配any、all、any_strict、all_strictretain_metadatadict[str, str]Noneretain 操作的默认元数据retain_document_idstrNoneretain 的文档 ID未设置时自动生成{session}-{timestamp}retain_contextstrllamaindexretain 操作的来源标签recall_typeslist[str]None事实类型过滤world、experience、observationrecall_include_entitiesboolFalse召回结果是否包含实体信息reflect_contextstrNonereflect 操作的额外上下文reflect_max_tokensintNonereflect 结果最大 token缺省时取max_tokensreflect_response_schemadictNone约束 reflect 输出的 JSON schemareflect_tagslist[str]Nonereflect 标签缺省时取recall_tagsreflect_tags_matchstrNonereflect 标签匹配缺省时取recall_tags_matchmissionstrNone记忆库使命首次使用时自动创建 bank自动生成的document_id实际格式为{session_id}-{uuid_hex_12}其中session_id是实例化时生成的 8 位随机串见 tools.py测试通过-分隔符与 12 位后缀校验该格式见 test_tools.py。生产模式Production Patterns记忆库使命Bank Missionmission 为记忆引擎提供事实抽取的语义上下文。设置后bank 会在首次使用时自动创建若已存在则静默跳过创建幂等# 工具模式 spec HindsightToolSpec( clientclient, bank_iduser-123, missionTrack user coding preferences, project context, and technical decisions, ) # 自动记忆模式 memory HindsightMemory.from_client( clientclient, bank_iduser-123, missionTrack user coding preferences, project context, and technical decisions, )源码层面_ensure_bank()/_aensure_bank()在首次 retain/recall 前以create_bank(bank_id, name, mission)创建/更新 bank创建失败如已存在仅记录 debug 日志并继续后续操作。这一幂等行为有测试专门保护连续 retain 与 recall 只触发一次create_bank见 test_memory.py、test_tools.py。mission 也可通过configure()全局设置工具构造时自动继承。用 Tags 做记忆作用域隔离在多用户、多会话共用一个服务端的场景下用 tags 把记忆按来源/会话隔离spec HindsightToolSpec( clientclient, bank_iduser-123, tags[source:chat, session:abc], # 应用到所有 retain recall_tags[source:chat], # 只召回 chat 来源的记忆 recall_tags_matchany, )标签匹配模式any/all/any_strict/all_strict控制多个标签的命中逻辑reflect 若未单独指定reflect_tags/reflect_tags_match会继承recall_tags/recall_tags_match见 tools.py测试见 test_tools.py。错误处理两种模式都采用优雅降级策略所有操作包裹在 try/except 中失败时记录日志并返回友好提示如Failed to store memory: ...而不是抛出异常打断 Agent 主流程。这意味着即使 Hindsight 服务不可用Agent 也能继续对话只是暂时失去记忆能力。测试分别覆盖了 retain、recall、reflect 三种故障场景见 test_tools.py、test_memory.py。工具 自动记忆组合使用自动记忆负责无感的上下文注入显式工具则留给 Agent 做主动反思两者分工最合理from hindsight_llamaindex import create_hindsight_tools, HindsightMemory # 自动记忆负责上下文增强 memory HindsightMemory.from_client(clientclient, bank_iduser-123) # 显式工具只保留 reflect避免与自动记忆职责重叠 tools create_hindsight_tools( clientclient, bank_iduser-123, include_retainFalse, # memory 已自动处理 retain include_recallFalse, # memory 已自动处理 recall include_reflectTrue, # Agent 仍可显式反思 ) agent ReActAgent(toolstools, llmllm) # 通过 run() 传入 memory response await agent.run(What should I prioritize?, memorymemory)客户端解析与超时设计工具与记忆适配器共用resolve_client()见 hindsight-integrations/llamaindex/hindsight_llamaindex/_client.py其解析顺序为显式传入的client优先否则取显式hindsight_api_url/api_key否则回退到configure()的全局配置否则使用DEFAULT_HINDSIGHT_API_URL与HINDSIGHT_API_KEY环境变量。构造客户端时还会附带hindsight-llamaindex/{version}形式的 User-Agent 标识。超时按操作类型分别设定秒retain 15s、recall 10s、reflect 30s、bank 创建 15s、默认 30s。这意味着复杂反思允许更长的等待时间而高频召回查询限制在 10 秒内返回避免拖慢 Agent 决策链路。验证与测试仓库为该集成提供了三层测试覆盖目录 hindsight-integrations/llamaindex/teststest_memory.py自动记忆的构造方式、put/get 行为、本地缓冲区裁剪、ReAct 痕迹清洗、mission 幂等创建test_tools.py三个工具的调用参数透传、错误降级、配置回退链、以及与ReActAgentMockLLM的兼容性工具同时具备同步_fn与异步_async_fntest_e2e.py端到端联调标记为requires_real_llm需要真实 Hindsight 服务与 LLM 密钥从确定性 CI 中排除。其中工具能被 ReActAgent 直接接受与FunctionTool.call() 能正确触发 retain/recall两类测试见 test_tools.py直接证明了该集成与 LlamaIndex 生态的即插即用性。小结hindsight-llamaindex为 LlamaIndex Agent 提供了从零成本自动记忆到完全显式控制的完整光谱HindsightMemory让每一轮对话自动沉淀与召回HindsightToolSpec/create_hindsight_tools把记忆能力变成 Agent 手边的工具configure()与客户端解析链则保证了自托管与云端两种部署形态的平滑切换。配合 mission、tags 与超时设计你可以为多租户、多会话的生产环境构建真正会学习的 Agent 记忆层。进一步可阅读 hindsight-integrations/llamaindex/README.md 获取精简速览或在 hindsight-clients/python 中了解底层hindsight-client的完整 API。【免费下载链接】hindsightHindsight: Agent Memory That Learns项目地址: https://gitcode.com/GitHub_Trending/hindsight2/hindsight创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
RELATED

相关推荐

AI超级员工系统:企业营销数字化转型的核心技术解析

AI超级员工系统:企业营销数字化转型的核心技术解析

1. AI超级员工系统:企业营销的智能革命去年我帮一家电商客户做营销系统升级时,他们团队5个人每天要处理200条客户咨询、制作30条短视频、追踪50个潜在客户。三个月后上了创客兔系统,同样工作量现在只需要1个运营AI就能搞定。这种效率跃迁正是…

📅 2026/9/13 9:44:38
多域AD管理工具选型:从原生工具失效到平台化治理

多域AD管理工具选型:从原生工具失效到平台化治理

/* MD / 富文本中的 .toc(含博客园搬家等嵌套结构);.toc-box 在侧栏,不受影响 */#content_views .toc,/* 编辑器常在目录前后插入空 p(:empty 仍占 20px),一并去掉避免顶空隙 */#content_views.markdown_views > p:empty:has(+ .toc),#content_views.markdown_views …

📅 2026/9/13 9:39:38
Cyclone FPGA UART FIFO自收发实战:跨时钟域与Quartus 9.0兼容

Cyclone FPGA UART FIFO自收发实战:跨时钟域与Quartus 9.0兼容

简介:本资源是一套基于Cyclone系列FPGA实现UART串口自收发通信的完整Verilog工程,面向数字电路与FPGA初学者及嵌入式通信开发学习者,解决串口协议底层实现、FIFO缓存设计与跨时钟域数据交互等核心实践问题。压缩包共222个文件,含3…

📅 2026/9/13 9:39:38
MORE NEWS

更多资讯

📰

Claude Code如何重塑工程师工作方式与技能转型

1. Claude Code如何重塑工程师的工作方式作为Anthropic内部最早接触Claude Code的工程师之一,我亲历了这款工具如何彻底改变我们的工作流程。最显著的变化是:我们不再需要亲自编写大部分代码,而是转变为"AI代理管理者"的角色。每天…

📰

在 LangChain.js 中使用 Ollama:@langchain/ollama 集成包完整实战指南

在 LangChain.js 中使用 Ollama:langchain/ollama 集成包完整实战指南 【免费下载链接】langchainjs The agent engineering platform 项目地址: https://gitcode.com/GitHub_Trending/la/langchainjs 导读 langchain/ollama 是 LangChain.js 官方提供的 Ol…

📰

Kafka与RocketMQ在日志采集中的性能对比与选型指南

1. 日志采集场景的技术挑战与选型考量 日志采集作为现代分布式系统的基础设施,面临着三大核心挑战:海量数据吞吐、实时性要求、系统可靠性。我曾参与过一个日均日志量超过20TB的电商平台项目,最初使用RocketMQ作为日志传输通道,但…

📰

题目:幂数加密

附件内容:8842101220480224404014224202480122先了解幂数加密幂数加密是一种基于二进制幂次表示法的加密方法。由于英文字母只有26个字母,通过使用2的0、1、2、3、4、5次幂可以表示31个单元。通过用二进制幂数表示字母序号数来加密。解密时,可…

📰

SpacetimeDB C++ 快速上手:5 分钟用 C++ 编写可编译为 WebAssembly 的服务端模块

SpacetimeDB C 快速上手:5 分钟用 C 编写可编译为 WebAssembly 的服务端模块 【免费下载链接】SpacetimeDB Development at the speed of light 项目地址: https://gitcode.com/GitHub_Trending/sp/SpacetimeDB 本篇指南基于 SpacetimeDB 官方 C 快速入门文档…

📰

LCD12864指针式电子钟:51单片机图形绘制实战指南

简介:本资源是一套基于51单片机与Proteus仿真的指针式电子钟完整开发方案,面向嵌入式初学者、单片机课程设计学生及电子类实训教师,解决LCD图形化时钟界面设计、DS1302实时时钟驱动与软硬件协同仿真等典型实践难点。压缩包共36个文件&#xf…

TODAY

今日更新

THIS WEEK

本周精选

THIS MONTH

本月热门

读完文章,想聊聊您的网站?

告诉我们您的行业与需求,资深顾问一对一梳理方案与报价,全程免费。

📞 💬