Redis®*: Node.js中的RAG流程示例
本文件是向量搜索与RAG指南的一部分。您可以在这里查看完整指南:使用Redis进行语义搜索、推荐和检索增强生成(RAG)。
👋 欢迎来到 Stackhero 文档!
Stackhero 提供即开即用的 Redis cloud 解决方案,带来多项优势,包括:
- 集成
Redis Commander网页界面。- 无限制的消息大小与传输。
- 只需一键即可轻松完成更新。
- 依托专属私有基础设施,实现卓越性能与强大安全性。
节省时间,简化您的工作流程:只需 5 分钟即可体验 Stackhero 的 Redis cloud hosting 方案!
import { createClient, SCHEMA_FIELD_TYPE, SCHEMA_VECTOR_FIELD_ALGORITHM } from 'redis';
const client = createClient({ url: process.env.STACKHERO_REDIS_URL_TLS });
await client.connect();
const DIMENSIONS = 1536;
const toBytes = embedding => Buffer.from(new Float32Array(embedding).buffer);
// 1. 启动时仅需创建一次索引
try {
await client.ft.create(
'chunksIndex',
{
content: SCHEMA_FIELD_TYPE.TEXT,
documentId: SCHEMA_FIELD_TYPE.TAG,
embedding: {
type: SCHEMA_FIELD_TYPE.VECTOR,
ALGORITHM: SCHEMA_VECTOR_FIELD_ALGORITHM.HNSW,
TYPE: 'FLOAT32',
DIM: DIMENSIONS,
DISTANCE_METRIC: 'COSINE'
}
},
{ ON: 'HASH', PREFIX: 'chunk:' }
);
}
catch (error) {
if (!error.message.includes('Index already exists')) {
throw error;
}
}
// 2. 索引您的片段(embedding由模型提供方生成)
async function indexChunk({ id, documentId, content, embedding }) {
await client.hSet(`chunk:${id}`, {
content,
documentId,
embedding: toBytes(embedding)
});
}
// 3. 检索与问题最接近、且限定在某一文档内的片段
async function retrieve({ questionEmbedding, documentId, count = 5 }) {
const results = await client.ft.search(
'chunksIndex',
`(@documentId:{${documentId}})=>[KNN ${count} @embedding $queryVector AS score]`,
{
PARAMS: { queryVector: toBytes(questionEmbedding) },
SORTBY: 'score',
RETURN: [ 'content', 'score' ],
DIALECT: 2
}
);
return results.documents.map(({ value }) => value.content);
}
// 4. 将检索结果作为上下文传递给模型
const context = await retrieve({ questionEmbedding, documentId: 'doc42' });
const prompt = `Answer using only this context:\n\n${context.join('\n\n')}\n\nQuestion: ${question}`;