在JavaScript+LangChain的SupabaseVectorStore中实现带Metadata的记忆功能问题
解决对话记忆存储时添加指定Metadata的问题
问题原因
默认的VectorStoreRetrieverMemory在保存对话历史时,生成的Document对象不会携带自定义Metadata,导致存入Supabase数据库时metadata字段为空。
解决方案:自定义记忆类重写保存逻辑
通过继承VectorStoreRetrieverMemory并重写saveContext方法,手动为对话历史文档添加指定的Metadata。
步骤1:创建自定义记忆类
import { VectorStoreRetrieverMemory, Document } from "langchain/memory"; class CustomVectorStoreMemory extends VectorStoreRetrieverMemory { constructor(fields) { super(fields); // 接收传入的自定义Metadata this.customMetadata = fields.customMetadata || {}; } async saveContext(inputValues, outputValues) { // 提取对话的输入和输出内容 const input = inputValues[this.memoryKeyInput || "input"]; const output = outputValues[this.memoryKeyOutput || "output"]; // 构造带自定义Metadata的对话文档 const conversationDoc = new Document({ pageContent: `Human: ${input}\nAI: ${output}`, metadata: this.customMetadata }); // 将文档存入向量存储 await this.vectorStore.addDocuments([conversationDoc]); } }
步骤2:替换原记忆初始化代码
使用自定义的CustomVectorStoreMemory替代默认的VectorStoreRetrieverMemory,并传入需要的Metadata:
// 原vectorStore初始化代码保持不变 const vectorStore = await SupabaseVectorStore.fromExistingIndex( new OpenAIEmbeddings(), { client: SUPABASE_CLIENT, tableName: 'documents', queryName: 'match_documents_with_filters', filter: { email: 'abc@gmail.com' }, } ); // 初始化自定义记忆,传入指定的Metadata const memory = new CustomVectorStoreMemory({ vectorStoreRetriever: vectorStore.asRetriever(5), memoryKey: 'history', returnDocs: false, customMetadata: { email: 'abc@gmail.com' } // 这里设置要添加的Metadata });
步骤3:验证效果
运行对话逻辑后,Supabase的documents表中新增的对话历史记录会带有指定的metadata字段,后续通过filter查询时,能正确筛选出该用户的所有相关数据(包括原始文档和对话历史)。
内容的提问来源于stack exchange,提问作者fishmeisterFTW
相关产品推荐
相关产品推荐

