Redis®*: Node.js中的RAG流程示例

本文档属于向量搜索与RAG指南的一部分。您可以在此处查看完整指南:使用Redis实现语义搜索、推荐系统和检索增强生成(RAG)

👋 欢迎查阅 Stackhero 文档!

Stackhero 提供即开即用的 Redis cloud 解决方案,带来多项优势,包括:

  • 集成 Redis Commander Web 管理界面
  • 无限制的消息大小与传输。
  • 一键完成升级,操作便捷。
  • 基于专属私有基础设施,实现卓越性能与强大安全性

节省时间简化运维:仅需 5 分钟即可体验 Stackhero 的 Redis cloud 托管 方案!

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 = `请仅使用以下上下文回答:\n\n${context.join('\n\n')}\n\n问题:${question}`;