浅谈 RAG 并基于 NodeJS 实现基础向量检索服务

浅谈 RAG 并基于 NodeJS 实现基础向量检索服务
浅谈 RAG 并基于 NodeJS 实现基础向量检索服务一、RAG 技术原理为什么需要向量检索大语言模型LLM虽然强大但存在两个致命短板知识截止日期和幻觉问题。检索增强生成Retrieval-Augmented Generation, RAG通过外部知识库动态注入上下文成为解决上述问题的工业级方案。其核心流程可拆解为三步1.离线索引将文档切块Chunking通过嵌入模型Embedding Model转化为高维向量存入向量数据库。2.在线检索将用户查询编码为向量在向量空间中用相似度算法如余弦相似度召回最相关的 Top-K 片段。3.增强生成将检索到的上下文拼接到 Prompt 中交给 LLM 生成回答。这里的核心难点在于向量检索的效率与精度。本文不依赖外部向量数据库而是用 NodeJS 从零实现一个轻量级向量检索服务聚焦于索引构建与近似最近邻ANN搜索。### 二、基础架构设计内存向量索引为了便于理解我们设计一个纯内存的向量索引支持以下功能- 向量维度固定如 384 维对应常见 MiniLM 嵌入模型。- 支持批量插入与单条查询。- 采用暴力搜索Brute Force即线性扫描所有向量计算余弦相似度适合小规模数据集10万条。为什么不用 HNSW 或 FAISS 这些库实现复杂如多层图、PQ 量化本文聚焦原理暴力搜索是最直观的基线方法。生产环境可替换为hnswlib-node或pgvector。### 三、实现基础向量索引首先定义向量存储类包含插入、检索、序列化方法javascript// vectorStore.jsclass VectorStore { constructor(dimension 384) { this.dimension dimension; this.vectors []; // 存储向量数组 this.documents []; // 存储原始文档 this.ids []; // 存储文档 ID } // 插入文档及其向量 add(id, text, vector) { if (vector.length ! this.dimension) { throw new Error(向量维度必须为 ${this.dimension}); } this.ids.push(id); this.documents.push(text); this.vectors.push(vector); } // 余弦相似度计算向量已归一化时等价于内积 cosineSimilarity(a, b) { let dot 0, normA 0, normB 0; for (let i 0; i a.length; i) { dot a[i] * b[i]; normA a[i] * a[i]; normB b[i] * b[i]; } return dot / (Math.sqrt(normA) * Math.sqrt(normB)); } // 检索 Top K 相似向量 search(queryVector, k 3) { if (queryVector.length ! this.dimension) { throw new Error(查询向量维度不匹配); } const scores this.vectors.map(vec this.cosineSimilarity(queryVector, vec)); // 获取 Top K 索引降序 const topIndices scores .map((score, idx) ({ score, idx })) .sort((a, b) b.score - a.score) .slice(0, k) .map(item item.idx); return topIndices.map(idx ({ id: this.ids[idx], text: this.documents[idx], score: scores[idx] })); }}module.exports VectorStore;### 四、实现本地嵌入模型服务真实场景中我们需要将文本转化为向量。为了不引入 Python 环境本文使用xenova/transformers纯 JavaScript 实现的 Transformer 库加载轻量级模型all-MiniLM-L6-v2384 维。该模型在 NodeJS 中运行无外部依赖。javascript// embedder.jsconst { pipeline } require(xenova/transformers);class Embedder { constructor() { this.extractor null; } // 初始化嵌入模型延迟加载 async initialize() { if (!this.extractor) { // 使用小型嵌入模型输出 384 维向量 this.extractor await pipeline(feature-extraction, Xenova/all-MiniLM-L6-v2); } } // 将文本转换为向量自动归一化 async embed(text) { if (!this.extractor) { await this.initialize(); } const output await this.extractor(text, { pooling: mean, normalize: true }); // 将 Tensor 转换为普通数组 return Array.from(output.data); }}module.exports Embedder;### 五、构建 RAG 查询服务现在将向量存储与嵌入模型组合搭建一个简易的 HTTP 服务提供/search端点。这里使用 NodeJS 原生http模块避免额外依赖。javascript// server.jsconst http require(http);const VectorStore require(./vectorStore);const Embedder require(./embedder);(async () { const store new VectorStore(384); const embedder new Embedder(); await embedder.initialize(); // 预置示例知识库 const docs [ { id: 1, text: RAG 通过检索增强大模型生成能力 }, { id: 2, text: 向量数据库适合高效存储和查询嵌入向量 }, { id: 3, text: NodeJS 可以构建轻量级 AI 服务 }, { id: 4, text: 余弦相似度衡量两个向量的方向一致性 } ]; // 批量插入文档 for (const doc of docs) { const vector await embedder.embed(doc.text); store.add(doc.id, doc.text, vector); console.log(已索引文档 ${doc.id}); } // 创建 HTTP 服务 const server http.createServer(async (req, res) { if (req.method GET req.url.startsWith(/search)) { const query new URL(req.url, http://localhost:3000).searchParams.get(q); if (!query) { res.writeHead(400, { Content-Type: application/json }); res.end(JSON.stringify({ error: 缺少查询参数 q })); return; } const queryVector await embedder.embed(query); const results store.search(queryVector, 2); res.writeHead(200, { Content-Type: application/json }); res.end(JSON.stringify({ query, results })); } else { res.writeHead(404); res.end(Not Found); } }); server.listen(3000, () { console.log(向量检索服务已启动: http://localhost:3000); });})();### 六、测试与效果演示运行服务后用curl测试查询bash# 启动服务node server.js# 查询与“大模型生成”相关的内容curl http://localhost:3000/search?q大模型如何生成回答预期输出相似度分数可能略有不同json{ query: 大模型如何生成回答, results: [ { id: 1, text: RAG 通过检索增强大模型生成能力, score: 0.82 }, { id: 3, text: NodeJS 可以构建轻量级 AI 服务, score: 0.41 } ]}可以看到检索结果正确召回最相关的文档。若需接入 LLM只需将结果拼接入 Prompt例如javascriptconst prompt 基于以下知识回答\n${results.map(r r.text).join(\n)}\n问题${query};### 七、优化方向与生产实践本文实现的是基础版本生产环境需考虑1.索引优化暴力搜索复杂度为 O(N)当文档量超过百万级应改用 HNSW Hierarchical Navigable Small World图索引实现对数级检索。2.分块策略文档切块大小影响检索精度需结合句边界、段落结构动态切分。3.混合检索结合关键词BM25与向量检索提升术语匹配的准确性。4.持久化使用node:fs定期将向量序列化到磁盘或接入 Redis 等外部存储。### 八、总结本文从 RAG 的技术原理出发剖析了向量检索在其中的核心作用。通过 NodeJS 实现了一个零依赖的内存向量检索服务包含文档嵌入、余弦相似度计算、Top-K 检索及 HTTP API并演示了如何将其集成到 RAG 流水线中。虽然基础版性能有限但完整展示了从文本到向量的转换、存储与检索的闭环流程。读者可在此基础上替换为更高效的索引算法如 HNSW或接入真实 LLM构建完整的知识增强问答系统。—延伸思考如果希望进一步降低延迟可以尝试将向量二进制化Binary Quantization或使用 Product Quantization 压缩向量维度但会牺牲一定精度。RAG 系统的工程化是一个权衡艺术理解底层原理是优化性能的第一步。