向量数据库
从 Delphi 连接到向量数据库,用于语义搜索、RAG 和 AI 应用程序。支持 Pinecone 等。
从 Delphi 连接到向量数据库,用于语义搜索、RAG 和 AI 应用程序。支持 Pinecone 等。
将文本存储为高维嵌入,并按含义而非关键词检索最相关的段落。
向量数据库存储由嵌入模型生成的数值嵌入,让您能够找到与查询向量最接近的条目。这是语义搜索和检索增强生成(RAG)的基础,您可以使用从自有文档中提取的段落来为大型语言模型提供依据,而不仅仅依赖模型在训练期间记忆的内容。
sgcWebSockets 提供两个可互换的向量存储后端,它们共享同一个基础组件 TsgcAIDatabaseVector,因此您可以在两者之间切换而无需更改导入或查询代码。将任一后端与 TsgcAIOpenAIEmbeddings 组件配对,即可将原始文本转换为向量并直接推送到存储中。
何时使用哪一个:当您希望零基础设施且数据可以轻松容纳在本机上时,选择文件后端。当索引较大、必须跨进程或用户共享,或需要扩展到单台主机之外时,选择 Pinecone。
将向量存储分配给 TsgcAIOpenAIEmbeddings 组件的 Database 属性,然后调用 CreateEmbeddingsFromFile 在单个批处理中嵌入并导入整个文档。在内部,每个块都通过存储从 TsgcAIDatabaseVector 继承的 BeginAddData / AddData / EndAddData 序列添加,因此从您代码的角度来看,文件后端和 Pinecone 后端的行为完全相同。
在查询时,您使用 GetEmbedding 嵌入用户的问题,并将生成的向量传递给 QueryData,它会返回按余弦相似度排序的最近匹配项。将这些段落作为上下文反馈给聊天模型,您就拥有了一个可用的 RAG 管道:答案基于您自己的数据,并由您掌控引用。同样的方法还支持对知识库的语义搜索、去重、推荐和聚类,所有这些都无需离开 Delphi 或 C++ Builder。
使用任一后端导入语料库并查询最近邻。
uses
sgcAI, sgcAI_OpenAI_Embeddings,
sgcAI_DB_Vector, sgcAI_DB_Vector_File, sgcAI_DB_Vector_Pinecone;
var
Embeddings: TsgcAIOpenAIEmbeddings;
DBFile: TsgcAIDatabaseVectorFile;
DBPinecone: TsgcAIDatabaseVectorPinecone;
begin
Embeddings := TsgcAIOpenAIEmbeddings.Create(nil);
Embeddings.OpenAIOptions.ApiKey := 'sk-...';
// Local file-based vector store
DBFile := TsgcAIDatabaseVectorFile.Create(nil);
DBFile.VectorFileOptions.InputFilename := 'corpus.sgcif';
DBFile.VectorFileOptions.VectorFilename := 'corpus.sgcvf';
Embeddings.Database := DBFile;
Embeddings.CreateEmbeddingsFromFile('docs.txt');
// Or push to the Pinecone cloud index
DBPinecone := TsgcAIDatabaseVectorPinecone.Create(nil);
DBPinecone.PineconeOptions.ApiKey := 'pc-...';
DBPinecone.PineconeIndexOptions.IndexName := 'sgc-embeddings';
Embeddings.Database := DBPinecone;
// Query the nearest neighbour for an arbitrary text
Results := Embeddings.Database.QueryData(
Embeddings.GetEmbedding('what is sgcWebSockets?', ''));
end;