How do you generate embeddings from strings using the AI SDK in Laravel 13?

In Laravel 13, you can generate embeddings from strings using the AI SDK is Str::of() method. The SDK provides a convenient toEmbeddings() macro on Laravel is Stringable class, which makes the process a one-liner.

Here is how to generate an embedding for a single string:

use IlluminateSupportStr;

$embedding = Str::of( Napa Valley has great wine. )->toEmbeddings();

The toEmbeddings() method returns the vector as an array of floats. If you need to work with multiple strings at once, you can use the Embeddings facade with the for() method, which accepts an array of strings and generates embeddings for each one.

Storing and Using Embeddings

In a real application, you will typically store the generated vector in your database alongside the original text. Laravel 13 supports vector columns natively, particularly with PostgreSQL is pgvector extension. A typical migration for a document model might look like this:

Schema::create( documents , function (Blueprint $table) {
   $table->id();
   $table->string( notitle );
   $table->text( content );
   $table->vector( embedding , dimensions: 1536)->index();
   $table->timestamps();
});

When processing documents, it is recommended to generate embeddings inside a queued job rather than during an HTTP request. Embedding generation can take several seconds, and offloading it to a queue keeps your application responsive.

use IlluminateSupportStr;

$embedding = Str::of($document->content)->toEmbeddings();
$document->update([ embedding => $embedding]);

Once your embeddings are stored, you can use Laravel is query builder methods like whereVectorSimilarTo() to perform semantic searches, finding records whose vector representations are closest to a given query string or pre-computed vector.

Key Considerations

Caching: Embeddings are computationally expensive and rarely change for identical text. You can enable caching globally in config/ai.php or per request by passing cache: true to toEmbeddings() to avoid redundant API calls.
Dimensions: Different embedding models produce vectors of different sizes (dimensions). The toEmbeddings() macro uses your provider is default dimension size. If you need a specific size, you can use the Embeddings facade with the dimensions() method.
Testing: The AI SDK includes faking support. You can use Embeddings::fake() to test embedding-related logic without making real API calls.

12 Views