Valkey: Node.js 的 RAG 流程範例

此文件屬於向量搜尋與 RAG指南的一部分。請在此處查看完整指南:使用 Valkey 進行語意搜尋、推薦系統及檢索增強生成(Retrieval-Augmented Generation)

👋 歡迎瀏覽 Stackhero 文件!

Stackhero 提供即開即用的 Valkey cloud 方案,帶來多項優勢,包括:

  • 已包含 Valkey Admin 網頁管理介面
  • 無限訊息大小及傳輸量。
  • 一鍵輕鬆完成更新
  • 專屬私有基礎設施提供最佳效能及強大安全性

節省時間簡化您的工作流程:只需 5 分鐘即可體驗 Stackhero 的 Valkey cloud hosting 方案!

Valkey 採用與 Redis 相同的協議,因此您可以使用任何 Redis 相容的 client。

import { createClient, SCHEMA_FIELD_TYPE, SCHEMA_VECTOR_FIELD_ALGORITHM } from 'redis';

const client = createClient({ url: process.env.STACKHERO_VALKEY_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]`,
    { PARAMS: { queryVector: toBytes(questionEmbedding) } }
  );

  return results.documents.map(({ value }) => value.content);
}

// 4. 將這些片段作為 context 傳給您的模型
const context = await retrieve({ questionEmbedding, documentId: 'doc42' });
const prompt = `Answer using only this context:\n\n${context.join('\n\n')}\n\nQuestion: ${question}`;