Minimal RAG in PHP

A simplified Retrieval-Augmented Generation example without an external vector DB

A minimal educational RAG pipeline in pure PHP: keep precomputed document embeddings in arrays, score them with cosine similarity, retrieve Top-K documents, build context, and pass this context to an LLM API.

Example of code:

 
<?php

$documents 
= [
    [
'id' => 1'text' => 'Contract termination is possible by agreement of the parties'],
    [
'id' => 2'text' => 'The contract may be terminated unilaterally'],
];

$embeddings = [
    
=> [0.120.880.44],
    
=> [0.100.900.40],
];

function 
cosineSimilarity(array $a, array $b): float
{
    
$dot $normA $normB 0.0;

    foreach (
$a as $i => $v) {
        
$dot += $v $b[$i];
        
$normA += $v $v;
        
$normB += $b[$i] * $b[$i];
    }

    return 
$dot / (sqrt($normA) * sqrt($normB));
}

$queryText 'Is it possible to terminate a contract unilaterally?';
$queryEmbedding = [0.110.890.42];

$scores = [];
foreach (
$embeddings as $id => $vector) {
    
$scores[$id] = cosineSimilarity($queryEmbedding$vector);
}