Getting text embedding

Minimal TransformersPHP example with Xenova/paraphrase-multilingual-MiniLM-L12-v2

A minimal example of generating a text embedding in PHP: build an embeddings pipeline, pass text to the model, and get the vector with normalize=true and pooling=mean.

Example of code:

 
<?php

use function Codewithkyrian\Transformers\Pipelines\pipeline;

$text = 'PHP is not only a web tool, but also an engineering tool.';
$embedding = [];
$embeddingError = null;

try {
    
$embedder = pipeline(task: 'embeddings', modelName: 'Xenova/paraphrase-multilingual-MiniLM-L12-v2');
    
$result = $embedder($text, normalize: true, pooling: 'mean');
    
$embedding = array_map(static fn ($v): float => (float) $v, $result[0]);
} catch (
Throwable $e) {
    
$embeddingError = $e->getMessage();
}