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