Valkey: Un pipeline RAG en Node.js

Cette documentation fait partie du guide Recherche vectorielle et RAG. Consultez le guide complet ici : Recherche sémantique, recommandations et retrieval-augmented generation avec Valkey.

👋 Bienvenue sur la documentation de Stackhero !

Stackhero propose une solution Valkey cloud prête à l'emploi qui offre de nombreux avantages, notamment :

  • Interface web Valkey Admin incluse.
  • Taille des messages et transferts illimités.
  • Mises à jour simplifiées en un clic.
  • Performance optimale et sécurité renforcée grâce à une infrastructure privée et dédiée.

Gagnez du temps et simplifiez-vous la vie : il suffit de 5 minutes pour essayer la solution Valkey cloud hosting de Stackhero !

Valkey utilise le même protocole que Redis, vous pouvez donc utiliser n'importe quel client compatible Redis.

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. Créez l'index une seule fois, au démarrage
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. Indexez vos segments (embedding fourni par votre modèle)
async function indexChunk({ id, documentId, content, embedding }) {
  await client.hSet(`chunk:${id}`, {
    content,
    documentId,
    embedding: toBytes(embedding)
  });
}

// 3. Récupérez les segments les plus proches d'une question, restreints à un document
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. Fournissez-les à votre modèle comme contexte
const context = await retrieve({ questionEmbedding, documentId: 'doc42' });
const prompt = `Répondez uniquement en utilisant ce contexte :\n\n${context.join('\n\n')}\n\nQuestion : ${question}`;