UNPKG

autosnippet

Version:

Extract code patterns into a knowledge base for AI coding assistants

59 lines (58 loc) 1.87 kB
/** * ContextualEnricher — 上下文增强管线 * * 基于 Anthropic Contextual Retrieval 论文 (2024-09) 的实现。 * 对每个 chunk 生成 50-100 token 的上下文前缀,使其嵌入时保留文档层面的语义。 * * 效果: retrieval failure rate 降低 35-67% (with reranking) * * 成本控制: * - 使用轻量模型 (Haiku/Gemini Flash) * - Prompt Caching: 同一文档不同 chunk 共享 system prompt 缓存 * - 增量模式: 只对新增/变更 chunk 做 enrichment * - 配置开关: contextualEnrich = false 时完全跳过 * * @module service/vector/ContextualEnricher */ export interface AiProviderLike { name?: string; chat(prompt: string, options?: { system?: string; maxTokens?: number; temperature?: number; }): Promise<string>; } export interface ChunkData { content: string; metadata: Record<string, unknown>; } export interface DocumentInfo { title: string; content: string; kind: string; sourcePath?: string; } export interface EnricherConfig { aiProvider: AiProviderLike; /** 缓存 enrichment 结果防止重复调用 */ cacheEnabled?: boolean; } export declare class ContextualEnricher { #private; constructor(config: EnricherConfig); /** * 为多个 chunks 生成上下文前缀 * * 策略: 将整篇文档作为 system prompt,逐 chunk 请求上下文描述。 * 利用 Prompt Caching: 文档只需编码一次,后续 chunk 查询只需增量 tokens。 * * @param document - 文档整体信息 * @param chunks - 分块后的内容数组 * @returns 带上下文前缀的 chunks */ enrichChunks(document: DocumentInfo, chunks: ChunkData[]): Promise<ChunkData[]>; /** 清除缓存 */ clearCache(): void; /** 当前缓存大小 */ get cacheSize(): number; }