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. 將片段(chunk)建立索引(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. 將查詢結果作為context傳給您的模型
const context = await retrieve({ questionEmbedding, documentId: 'doc42' });
const prompt = `請僅根據以下context作答:\n\n${context.join('\n\n')}\n\n問題:${question}`;