autosnippet
Version:
Extract code patterns into a knowledge base for AI coding assistants
103 lines (102 loc) • 3.41 kB
TypeScript
/**
* MemoryRetriever — 记忆检索与 Prompt 生成
*
* 从 PersistentMemory.js 提取的检索逻辑。
* 负责:
* - 三维打分检索 (Generative Agents: recency × importance × relevance)
* - 简单文本搜索
* - Prompt section 生成 (预算感知)
* - Memory.js 兼容层: load(), append()
*
* @module MemoryRetriever
*/
import type { MemoryEmbeddingStore } from './MemoryEmbeddingStore.js';
import type { DeserializedMemory } from './MemoryStore.js';
import { MemoryStore } from './MemoryStore.js';
/** 带评分的记忆检索结果 */
export interface ScoredMemory extends DeserializedMemory {
_score: number;
_recency: number;
_relevance: number;
}
/** 检索选项 */
export interface RetrieveOptions {
limit?: number;
source?: string;
type?: string;
}
/** Prompt section 生成选项 */
export interface PromptSectionOptions {
source?: string;
query?: string;
limit?: number;
tokenBudget?: number;
}
/** Memory.load 兼容选项 */
export interface LoadOptions {
source?: string;
}
/** Memory.append 兼容入口 */
export interface AppendEntry {
type?: string;
content: string;
source?: string;
ttl?: number | null;
}
/** 嵌入函数签名 — 异步向量嵌入 (返回 float[] 向量) */
export type EmbeddingFn = (text: string) => Promise<number[]>;
export declare class MemoryRetriever {
#private;
/** @param [opts.embeddingFn] 向量嵌入函数 (异步) */
constructor(store: MemoryStore, opts?: {
embeddingFn?: EmbeddingFn;
embeddingStore?: MemoryEmbeddingStore;
});
/**
* 综合检索: recency × importance × relevance
*
* 借鉴 Generative Agents 的三维打分模型:
* score = α * recency + β * importance + γ * relevance
*
* @param query 查询文本
* @returns 按 score 降序排列
*/
retrieve(query: string, { limit, source, type }?: RetrieveOptions): Promise<ScoredMemory[]>;
/** 简单文本搜索 (不打分, 用于去重检查) */
search(content: string, { limit }?: {
limit?: number | undefined;
}): DeserializedMemory[];
/**
* 生成供系统提示词的记忆摘要 (预算感知)
*
* @returns Markdown 格式
*/
toPromptSection({ source, query, limit, tokenBudget, }?: PromptSectionOptions): Promise<string>;
/** 兼容 Memory.load() — 返回最近 N 条记忆 */
load(limit?: number, { source }?: LoadOptions): {
ts: string;
type: string;
content: string;
source: string;
importance: number;
}[];
/** 兼容 Memory.append() — 添加一条记忆 (自动去重) */
append(entry: AppendEntry): void;
/** 设置向量嵌入函数 */
setEmbeddingFunction(fn: EmbeddingFn | null): void;
/** 获取当前嵌入函数 */
getEmbeddingFunction(): EmbeddingFn | null;
/**
* 为所有缺少 embedding 的记忆批量生成向量嵌入
* @param batchSize 每批数量 (默认 20)
* @returns 成功嵌入的记忆数
*/
embedAllMemories(batchSize?: number): Promise<number>;
/**
* 使用嵌入函数计算语义相关性 (余弦相似度)
* @param query 查询文本
* @param content 记忆内容
* @returns 相似度分数 或 null
*/
computeEmbeddingRelevance(query: string, content: string): Promise<number | null>;
}