Skip to main content
The EmbeddingsBuilder provides a fluent interface for generating vector embeddings from text input. Embeddings can be used for semantic search, similarity comparison, and other vector-based operations.

Configuration Methods

model

Set the embedding model to use.
$builder->model('text-embedding-3-small')
$builder->model(new OpenAIEmbeddings('text-embedding-3-large'))
model
string|EmbeddingModel
required
The embedding model identifier string or EmbeddingModel instance
return
static
Returns the builder instance for method chaining

input

Set the text input to generate embeddings for.
$builder->input('The quick brown fox jumps over the lazy dog')
$builder->input(fn() => $article->content)
input
Closure|string
required
The text to embed, or a closure that returns the text
return
static
Returns the builder instance for method chaining

Callback Methods

onTokenStats

Set a callback for token usage statistics.
$builder->onTokenStats(function(TokenStats $stats) {
    echo "Tokens used: {$stats->total}";
})
onTokenStats
Closure(TokenStats): void|null
required
Closure that receives TokenStats with usage information
return
static
Returns the builder instance for method chaining

Execution Methods

get

Generate the embeddings for the configured input.
$embedded = $builder->get()
return
EmbeddedData
EmbeddedData instance containing the vector embeddings and metadata
throws
InvalidArgumentException
Thrown if input or model is not set before calling get()

Usage Example

use Mateffy\Magic;

// Simple usage with facade
$embedded = Magic::embeddings(
    input: 'Hello world',
    model: new OpenAIEmbeddings('text-embedding-3-small')
)->get();

// Advanced usage with builder
$embedded = Magic::embeddings()
    ->model('text-embedding-3-large')
    ->input(fn() => $document->content)
    ->onTokenStats(function($stats) {
        Log::info('Embedding tokens', ['total' => $stats->total]);
    })
    ->get();

// Access the embedding vector
$vector = $embedded->vector; // array of floats

Build docs developers (and LLMs) love