ARTICLE DETAIL

资讯详情

深耕编程入门与网站建设的一线实战洞察。

Hindsight AI SDK 集成指南:基于 Changelog 解读 @vectorize-io/hindsight-ai-sdk 的持久化记忆接入与版本演进

Hindsight AI SDK 集成指南:基于 Changelog 解读 @vectorize-io/hindsight-ai-sdk 的持久化记忆接入与版本演进 Hindsight AI SDK 集成指南基于 Changelog 解读 vectorize-io/hindsight-ai-sdk 的持久化记忆接入与版本演进【免费下载链接】hindsightHindsight: Agent Memory That Learns项目地址: https://gitcode.com/GitHub_Trending/hindsight2/hindsight本篇文章以仓库中 Vercel AI SDK Changelog 为核心骨架结合 AI SDK 集成完整文档、集成包源码 与 测试用例系统讲解vectorize-io/hindsight-ai-sdk如何为 Vercel AI SDK 应用注入长期记忆能力以及 0.4.20 → 0.5.1 三个版本的关键演进与背后实现原理。读完本文你将掌握五个记忆工具的完整用法、构造函数选项语义、四种典型接入场景以及类型兼容性修复的来龙去脉。一、Changelog 总览一条记忆集成能力的演进主线官方 Changelog 页面以 Vercel AI SDK Changelog 为标题副标题明确其定位vectorize-io/hindsight-ai-sdk — memory integration for Vercel AI SDK。目前共收录 3 个版本演进脉络清晰版本类型核心变更0.4.20里程碑首次引入 AI SDK 集成为 TypeScript 客户端增加 Deno 兼容性改进 AI SDK 工具支持修复影响集成的依赖安全漏洞0.5.0兼容性改进与 Hindsight Client v0.5.2 的兼容性避免使用 AI SDK 时出现集成不匹配0.5.1类型修复修复 AI-SDK reflection 工具类型定义使其与 OpenAPI 规范一致集成行为更可靠从版本节奏可以看出该集成包在功能落地0.4.20之后将工作重心转向生态兼容与客户端版本对齐与规范对齐与 OpenAPI 类型一致——这正是生产级集成库的典型演化路径。下文将依次深入每一个版本并联动源码解释其实际影响。二、v0.4.20AI SDK 集成诞生与 Deno 兼容0.4.20 是该集成包的起点包含四项变更分别对应四个 Commit1. 新增 AI SDK 集成7e339e16集成包位于仓库hindsight-integrations/ai-sdk目录package.json声明其名称为vectorize-io/hindsight-ai-sdk版本 0.5.1描述为 Hindsight memory integration for Vercel AI SDK - Give your AI agents persistent, human-like memory许可证为 MIT。关键工程约束peerDependenciesai ^6.0.0、zod ^3.0.0 || ^4.0.0即面向 AI SDK 6.x 及现代 Zod 版本enginesnode 22模块格式ESMtype: module通过tsup构建出dist/index.js与类型声明dist/index.d.ts源码结构极简src/index.ts仅做导出聚合全部实现集中在 src/tools/index.ts。2. Deno 兼容性72c25c97为 TypeScript 客户端增加 Deno 兼容。集成包在package.json中提供了专门的测试脚本test:denodeno test --no-check --allow-all --unstable-sloppy-imports src/tools/index.test.ts并附带 deno.json 与deno.lock同时提供 vitest-compat.ts 辅助测试环境适配——说明该集成不仅服务于 Node.js也面向 Deno 运行时。3. 工具支持改进d06a0259Improve AI SDK tool support to make integrations more capable and reliable——对应到源码即createHindsightTools返回的五个标准 AI SDKtool对象每个都带有完整的description、inputSchemaZod与execute实现。默认的工具描述在 src/tools/index.ts 中定义retainStore information in long-term memory. Use this when information should be remembered for future interactions, such as user preferences, facts, experiences, or important context.recallSearch memory for relevant information. Use this to find previously stored information that can help personalize responses or provide context.reflectAnalyze memories to form insights and generate contextual answers...getMentalModel检索由记忆综合出的心智模型mental model比检索原始记忆更快更高效getDocument按 ID 精确检索文档应用状态、用户画像等需要精确取回的结构化数据。4. 依赖安全修复b6a4f17cSecurity fixes by resolving dependency vulnerabilities affecting the integration. 对应到 package.json 中的overrides字段可以看到对rollup、picomatch、vite、postcss等构建链依赖的版本锁定与升级如vite 8.0.5、postcss 8.5.23 9.0.0这正是该 Commit 在工程层面的落地痕迹。三、v0.5.0与 Hindsight Client v0.5.2 的兼容性对齐0.5.0 只做一件事改进与 Hindsight Client v0.5.2 的兼容性防止使用 AI SDK 时出现集成不匹配Commitbca87412。其根源可以从 src/tools/index.ts 中定义的HindsightClient接口看出端倪集成包并不直接依赖具体的客户端实现而是声明了一个结构性接口structural interface要求客户端提供retain、recall、reflect、getMentalModel、getDocument五个方法。只要官方 TypeScript 客户端vectorize-io/hindsight-client的方法签名随版本演进发生任何参数或返回类型变动集成就需要同步适配——0.5.0 正是完成这一同步。从测试角度看index.test.ts 使用mockClient对五个方法全部vi.fn()打桩来验证调用关系这意味着任何满足该接口的对象都能驱动这些工具包括自定义 HTTP 客户端。这一点为灵活客户端设计提供了测试级证据。四、v0.5.1reflection 工具类型定义对齐 OpenAPI 规范最新版本 0.5.1 修复了AI-SDK reflection 工具的类型定义与 OpenAPI 规范不一致的问题Commit3d6b3805目的是让集成行为更可靠。reflection 工具在实现上对应reflect工具及其依赖的类型体系。对照源码可以定位到具体的类型定义ReflectResponsesrc/tools/index.tstext 可选的based_onReflectBasedOnL77-L81嵌套的memoriesReflectFact[]、mental_models含id/text/context、directives含id/name/contentReflectFactL65-L72text、type、context、occurred_start/end等字段。这些结构直接对应后端 OpenAPI 中/reflect端点的响应 schema。该版本修复意味着此前 AI SDK 侧的类型声明与后端 OpenAPI 返回结构存在字段命名如based_on与basedOn或可空性差异可能导致类型断言出错修复后前端 TypeScript 类型与后端规范严格对齐。配套的测试也覆盖了这些字段的透传行为例如 index.test.ts 中 should pass through based_on with mental_models and directives 验证memories、mental_models、directives三个嵌套结构被完整返回以及 should handle null based_onL324-L335验证空响应场景。类型修复与行为测试相互印证正是更可靠集成行为的保证。五、安装与快速开始集成文档docs-integrations/ai-sdk.mdx给出的安装命令npm install vectorize-io/hindsight-ai-sdk vectorize-io/hindsight-client ai集成包 README 补充了zod依赖。最简接入示例来自 READMEimport { HindsightClient } from vectorize-io/hindsight-client; import { createHindsightTools } from vectorize-io/hindsight-ai-sdk; import { generateText } from ai; import { anthropic } from ai-sdk/anthropic; // 1. 初始化 Hindsight 客户端 const hindsightClient new HindsightClient({ apiUrl: http://localhost:8000, }); // 2. 创建记忆工具 const tools createHindsightTools({ client: hindsightClient }); // 3. 配合 AI SDK 使用 const result await generateText({ model: anthropic(claude-sonnet-4-20250514), tools, system: You have long-term memory. Use: - recall to search past conversations - retain to remember important information - reflect to synthesize insights from memories, prompt: Remember that Alice loves hiking and prefers spicy food, }); console.log(result.text);在未启动 Hindsight 服务时可先用嵌入式模式在本地拉起 API见 hindsight-embed 与集成包 READMEuvx hindsight-embedlatest -p myapp daemon start # API 默认地址 http://localhost:8000六、五个记忆工具职责划分与参数语义集成包注册五个工具。设计上有一个核心原则bankId在创建时固定Agent 无法更改语义输入记什么、查什么交给 Agent基础设施关切预算、标签、异步模式由应用在构造时决定。工具职责总览工具Agent 提供构造函数控制retaincontent、documentId、timestamp、contextasync、tags、metadatarecallquery、queryTimestampbudget、types、maxTokens、includeEntities、includeChunksreflectquery、contextbudgetgetMentalModelmentalModelId—getDocumentdocumentId—这一分工在源码中体现得十分明确。以retain为例L275-L286Agent 可见的 Zod schema 只含content必填、documentId、timestamp、context四个语义字段而tags、metadata、async通过闭包从构造选项注入完全不出现在inputSchema中L343-L350。recall同理Agent 只能传query与queryTimestampL289-L295检索预算、事实类型过滤等由应用锁定。测试用例 index.test.ts 中 should always use the bankId from constructor options 专门验证了bankId的强制固定行为从测试层面确认了该设计约束。返回结构要点recall返回{ results, entities? }RecallResult含id/text/type/entities/context/occurred_start/occurred_end/mentioned_at/document_id/metadata/chunk_id开启includeEntities后返回EntityState实体 ID、规范化名称、观察列表reflect返回{ text, basedOn? }text为空时兜底为No insights available yet.L388getMentalModel返回{ content, name, updatedAt }content为空时兜底No content available yet.getDocument找不到文档时返回null测试见 L413-L420。七、四种典型接入场景1. 与generateText搭配单轮文本生成来自 示例代码 的generate-text片段import { generateText } from ai; import { openai } from ai-sdk/openai; const { text } await generateText({ model: openai(gpt-4o), tools, maxSteps: 5, // 允许多轮工具调用循环 system: You are a helpful assistant with long-term memory., prompt: Remember that I prefer dark mode and large fonts., });maxSteps: 5让模型可以在一次generateText内自主完成检索 → 回答 → 记忆的多次工具调用。2. 与streamText搭配流式输出import { streamText } from ai; const result streamText({ model: openai(gpt-4o), tools, maxSteps: 5, system: You are a helpful assistant with long-term memory., prompt: What are my display preferences?, }); for await (const chunk of result.textStream) { process.stdout.write(chunk); }3. 与ToolLoopAgent搭配自主 Agent 循环ToolLoopAgent是 AI SDK 6 提供的显式工具循环抽象配合stepCountIs限定最大步数import { generateText, ToolLoopAgent, stepCountIs } from ai; import { openai } from ai-sdk/openai; import { HindsightClient } from vectorize-io/hindsight-client; import { createHindsightTools } from vectorize-io/hindsight-ai-sdk; const client new HindsightClient({ baseUrl: process.env.HINDSIGHT_API_URL! }); const agent new ToolLoopAgent({ model: openai(gpt-4o), tools: createHindsightTools({ client, bankId: user-123 }), stopWhen: stepCountIs(10), system: You are a helpful assistant with long-term memory., }); const result await agent.generate({ prompt: Remember that my favorite editor is Neovim, });4. 在 Next.js Route Handler 中按请求隔离用户多用户场景多用户应用的关键技巧在每个请求处理函数内部创建tools让每次请求闭包捕获正确的bankId通常是userId避免跨用户串号// app/api/chat/route.ts import { streamText } from ai; import { openai } from ai-sdk/openai; import { HindsightClient } from vectorize-io/hindsight-client; import { createHindsightTools } from vectorize-io/hindsight-ai-sdk; const hindsightClient new HindsightClient({ baseUrl: process.env.HINDSIGHT_API_URL!, }); export async function POST(req: Request) { const { messages, userId } await req.json(); // 每次请求都创建 tools闭包捕获当前用户的 bankId const tools createHindsightTools({ client: hindsightClient, bankId: userId, }); return streamText({ model: openai(gpt-4o), tools, maxSteps: 5, system: You are a helpful assistant with long-term memory., messages, }).toDataStreamResponse(); }八、构造函数选项详解createHindsightTools的完整选项如下除client与bankId外全部可选源码定义见 HindsightToolsOptionsconst tools createHindsightTools({ client, bankId: userId, retain: { async: true, // fire-and-forget不等待写入完成默认 false tags: [env:prod, app:support], // 附加到每条记忆的标签 metadata: { version: 2.0 }, // 附加到每条记忆的元数据 }, recall: { budget: high, // 检索深度low | mid | high默认 mid types: [experience, world], // 事实类型过滤默认全部 maxTokens: 2048, // 返回 token 上限默认 API 默认值 includeEntities: true, // 包含实体观察默认 false includeChunks: true, // 包含原始源块默认 false }, reflect: { budget: mid, // 综合深度默认 mid maxTokens: 2048, // 响应 token 上限 }, });各工具选项语义汇总完整表格见 集成文档retain选项类型默认说明asyncbooleanfalsefire-and-forget不等待摄取完成tagsstring[]—附加到每条记忆的标签metadataRecordstring, string—附加到每条记忆的元数据descriptionstring内置覆盖展示给模型的工具描述recall选项类型默认说明budgetlow \| mid \| highmid控制检索深度与延迟types(world \| experience \| observation)[]全部限制返回的事实类型maxTokensnumberAPI 默认限制返回总 tokenincludeEntitiesbooleanfalse结果中包含实体观察includeChunksbooleanfalse结果中包含原始源块descriptionstring内置覆盖工具描述reflect选项类型默认说明budgetlow \| mid \| highmid控制综合深度与延迟maxTokensnumberAPI 默认响应最大 tokendescriptionstring内置覆盖工具描述源码中的BudgetSchema即z.enum([low, mid, high])L7FactTypeSchema为z.enum([world, experience, observation])L13。测试 should accept low/mid/high budget valuesL486-L502验证了三个预算档位全部被接受而 should default recall budget to mid 与 should default reflect budget to midL459-L484从测试侧固化了mid默认值。九、源码级实现原理1. 参数分区设计createHindsightTools的核心思想是构造期锁定基础设施参数、执行期只暴露语义参数构造选项retainOpts、recallOpts、reflectOpts等通过闭包捕获每个工具用 Zod 定义 Agent 可见的inputSchemaexecute内将 Agent 输入与构造选项合并后调用client对应方法L337-L352 等。这样设计的好处是多租户场景下应用可以在不同请求/用户间以不同预算、标签策略创建工具实例而模型始终只操心该记什么、该查什么。2. 错误传播工具不吞异常客户端抛出的错误会原样向上传播由 AI SDK 的工具调用机制处理。测试 index.test.ts 的 error handling 段 分别验证了retain、recall、reflect的异常传播行为。3. 默认值与兜底recall、reflect的budget默认mid在execute中通过?? mid显式兜底L364、L384recall的includeEntities/includeChunks默认falsereflect空文本与getMentalModel空内容均有友好兜底文案避免把空串交给模型。十、从 Changelog 到落地工程启示回看三版 Changelog可以提炼出集成库进入稳定期的三条工程准则功能先行兼容跟进0.4.20 → 0.5.0先保证核心能力可用再随下游客户端hindsight-client版本演进同步适配规范对齐即可靠性0.5.1类型定义与后端 OpenAPI 规范对齐从编译期消灭行为偏差——这也是为什么ReflectBasedOn、ReflectFact等结构会在源码与测试中同时被严格约束可移植性与供应链安全0.4.20支持 Node.js 与 Deno 双运行时通过overrides锁定构建链依赖版本。对于希望为 Vercel AI SDK 应用接入持久化记忆的开发者推荐的落地路径是先在本地用hindsight-embed启动 API参照 集成文档 与 完整示例 跑通generateText场景再按多用户需求将createHindsightTools移入请求处理函数、以userId作为bankId最后依据响应延迟与 token 成本调整recall/reflect的budget与maxTokens。若需深入验证各工具的参数透传与边界行为可直接阅读 工具实现源码 与 Vitest 测试套件并以npm test或npm run test:deno在本地复现。【免费下载链接】hindsightHindsight: Agent Memory That Learns项目地址: https://gitcode.com/GitHub_Trending/hindsight2/hindsight创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表