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 = [
1 => [0.12, 0.88, 0.44],
2 => [0.10, 0.90, 0.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.11, 0.89, 0.42];
$scores = [];
foreach ($embeddings as $id => $vector) {
$scores[$id] = cosineSimilarity($queryEmbedding, $vector);
}