SuperAPI AI 工具集

ai-persistence/stores

智能体与模型

查看项目

更新于 10-16 18:00

技能介绍

用途:@tanstack/ai-persistence 只提供契约,不提供数据库后端。适配器是一个带 stores 映射的对象,你按自己已有的数据库实现所需 store,再交给 withPersistence。核心不会检查你的表结构,schema 完全由你决定。开发与测试可用 memoryPersistence(),持久化部分需自行编写适配器。

主要能力:通过 defineAIPersistence 定义持久化形状,stores 只接受 messages、runs、interrupts、metadata 四个键,其他键(如 locks、sandbox 实例映射)会在运行时抛 Unknown AIPersistence store key。形状分 ChatTranscriptPersistence、ChatWithInterruptsPersistence、ChatPersistence 三种。

契约要点:MessageStore 的 loadThread 只传 threadId 时返回完整数组(未知线程返回 [],绝不返回 null),saveThread 是整体替换而非追加。RunStore 必需 createOrResume、update、get、findActiveRun;可选 listByThread、listByParentRun、listReclaimable,缺失会禁用对应功能,且需在一致性测试中通过 skipMethods 声明。RunStatus 中 interrupted 是人工介入暂停,非终态,不能与 aborted 混淆。RunRecord 的 sandboxKey、detachedSince、cancelRequested、driverEpoch 四个字段必须完整往返,update 需用 'field' in patch 判断,以区分“清空字段”和“未提及字段”。InterruptStore 的 create 始终生成 pending,list* 按 requestedAt 升序。MetadataStore 以 (namespace, key) 两字段标识,不可用冒号拼接。时间戳在存储记录中用 epoch 毫秒,离开持久化层用 ISO-8601 字符串。

使用方式:用 defineMessageStore、defineRunStore、defineInterruptStore、defineMetadataStore 为各 store 标注类型;一致性测试用 runPersistenceConformance('sqlite', () => persistence, { skipMethods: ['runs.listByThread'] })。

限制:RunError 不从 @tanstack/ai-persistence 再导出,需从 @tanstack/ai 导入。不要用裸 AIPersistence 标注工厂,否则 withPersistence 与 reconstructChat 会拒绝。不要在 RunStore 中留桩方法,能力层级应在 store 层声明。具体各数据库适配配方见 ai-persistence/build-{drizzle,prisma,cloudflare,custom}-adapter,完整 node:sqlite 实现见 examples/ts-react-chat/src/lib/sqlite-persistence.ts。