Langchain之embedding model & vector store

27 阅读2分钟

Embedding model

Embedding model是指文本的向量化表示,类似于自然语言处理中的word embedding,向量化表示结果仍保留文本的上下文关系,通过数学运算,可以执行多种操作。
Langchain中提供了embedding基础类,类中提供两种方法,embedding documents和embedding a query。

const embedding = new OllamaEmbeddings({
    baseUrl:"http://localhost:11434",
    model:"llama3.1"
});
// 将字符串表示为向量化
const res = await embedding.embedQuery("Hello world");
// res结果为一个向量
[
   -0.006947435,   -0.019121876,  0.0057178806, -0.00090470485,   0.019433834,
    0.020392384,    0.007810885,  -0.008234128,   -0.012977161,   0.021774717,
  0.00013950953,   -0.007489872,   0.012296211,    0.016452614,   0.011953101,
  ... more items
]
// embedding documents
const documentRes = await embeddings.embedDocuments(["Hello world", "Bye bye"]);

cache embedding results

存储向量结果,避免重复计算,langchain提供了CacheBackedEmbeddings,不过不推荐使用该方法进行长时间存储。

const embedding = new OllamaEmbeddings({
    baseUrl: 'http://localhost:11434',
    model: 'llama3.1',
  });
 
const memoryStore = new InMemoryStore();
// 需要提供三个变量,embedding model、存储embedding的缓存、cache embedding对应的key
const cacheBackedEMbeddings = CacheBackedEmbeddings.fromBytesStore(
    embedding,
    memoryStore,
    {
      // 因为是key-value存储,所以key值的设定需要确保不和其他缓存冲突
      namespace: embedding.model,
    }
);
// 使用faiss-node测试缓存是否生效
// docs -> 处理好的文档拆分数据
let time = Date.now();
const vectorstore = await FaissStore.fromDocuments(
    docs,
    cacheBackedEmbeddings
);
console.log(`Initial creation time: ${Date.now() - time}ms`); 
// Initial creation time: 3919ms

time = Date.now();
const vectorstore2 = await FaissStore.fromDocuments(
    docs,
    cacheBackedEmbeddings
);
// 使用缓存后,几乎没有耗时
console.log(`Cached creation time: ${Date.now() - time}ms`); 
//Cached creation time: 4ms

除了memory Store,还有RedisByteStore,可以使用redis储存数据。

Vector store

vector store的作用在于,可以存储向量化数据,并对数据进行相关性搜索,例如对文档提问,可以检索出和问题相关性最高的内容。

MemoryVectorStore

使用memoryVectorStore,还有其他的store可以进行选择, 可以根据使用场景去具体选择。

const vectorStore = await MemoryVectorStore.fromDocuments(docs, embedding);
const result = await vectorStore.similaritySearch('video', 1);

faiss-node

使用faiss向量数据库

// splitDoc 处理好的分块数据
const vectorStore = await FaissStore.fromDocuments(splitDoc, embedding);
const dir = './data/db';
// 将向量化结果存储在路径下
await vectorStore.save(dir);
// 读取存储的数据
const dir = './data/db';
const embedding = new OllamaEmbeddings({
    baseUrl: 'http://localhost:11434',
    model: 'llama3.1',
});
const vectorStore = await FaissStore.load(dir, embedding);
const result = await vectorStore.similaritySearch(
    'What is the most important thing to do?',
    1
);
// result
[
  {
    pageContent: // some content,
    metadata: { source: './data/example.txt', loc: [Object] }
  }
]