DEV Community

Ehtesham Ali
Ehtesham Ali

Posted on

1 1 1 1

How to Build a Vector Database with SQLite in laravel for LLM's

Building a Vector Database with SQLite in Laravel for LLMs on Windows requires configuring SQLite with vector support (via sqlite-vss or pgvector alternative), integrating it with Laravel, and using it for vector search. Here’s a step-by-step guide:

Step 1: Install SQLite with Vector Support
SQLite doesn’t natively support vector storage, but you can enable it using the sqlite-vss extension.

1.1 Download SQLite with Vector Support
Download the latest SQLite3 binary from SQLite’s official site.
Download the sqlite-vss extension from here.

1.2 Enable the sqlite-vss Extension
Place sqlite-vss.dll (Windows) or .so (Linux/macOS) in your project directory.
Load the extension in Laravel by modifying your database configuration.

Step 2: Configure Laravel to Use SQLite
Open the .env file and set up SQLite:

DB_CONNECTION=sqlite
DB_DATABASE=database/database.sqlite
Enter fullscreen mode Exit fullscreen mode

Create the SQLite database file:

mkdir database
touch database/database.sqlite
Enter fullscreen mode Exit fullscreen mode

Ensure config/database.php has SQLite configured:

'sqlite' => [
    'driver' => 'sqlite',
    'database' => env('DB_DATABASE', database_path('database.sqlite')),
    'prefix' => '',
    'foreign_key_constraints' => true,
],
Enter fullscreen mode Exit fullscreen mode

Step 3: Create a Migration for Vector Storage
Create a migration for storing vector embeddings:

php artisan make:migration create_embeddings_table
Enter fullscreen mode Exit fullscreen mode

Edit the migration file:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class CreateEmbeddingsTable extends Migration
{
    public function up()
    {
        Schema::create('embeddings', function (Blueprint $table) {
            $table->id();
            $table->string('text');
            $table->json('embedding'); // Store vector as JSON
            $table->timestamps();
        });

        // Load the SQLite extension
        DB::statement("SELECT load_extension('sqlite-vss')");

        // Create a vector index for fast search
        DB::statement("CREATE VIRTUAL TABLE vss_index USING vss(embedding(1536))"); // Example: OpenAI embedding size 1536
    }

    public function down()
    {
        Schema::dropIfExists('embeddings');
    }
}
Enter fullscreen mode Exit fullscreen mode

Run the migration:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

Step 4: Insert and Query Vector Data

4.1 Insert Vector Data

Modify Embedding.php model:

use Illuminate\Database\Eloquent\Model;

class Embedding extends Model
{
    protected $fillable = ['text', 'embedding'];
    protected $casts = ['embedding' => 'array']; // Convert JSON to array
}
Enter fullscreen mode Exit fullscreen mode

Store embeddings in Laravel:

use App\Models\Embedding;

Embedding::create([
    'text' => 'Hello world',
    'embedding' => json_encode([0.1, 0.2, 0.3, ..., 0.9]) // Example vector
]);
Enter fullscreen mode Exit fullscreen mode

Step 5: Perform Vector Search

To perform a similarity search:

use Illuminate\Support\Facades\DB;

$vector = json_encode([0.1, 0.2, 0.3, ..., 0.9]); // Example query vector

$result = DB::select("SELECT text, vss_distance(embedding, ?) as distance FROM embeddings ORDER BY distance LIMIT 5", [$vector]);

return response()->json($result);
Enter fullscreen mode Exit fullscreen mode

Bonus: Generate Vectors using OpenAI

If you're working with LLM embeddings (like OpenAI), install openai-php:

composer require openai-php/client
Enter fullscreen mode Exit fullscreen mode

Then, generate embeddings:

use OpenAI\Client;

$client = new Client('your-openai-api-key');

$response = $client->embeddings()->create([
    'model' => 'text-embedding-ada-002',
    'input' => 'Hello world',
]);

$embedding = $response->json()['data'][0]['embedding'];

Embedding::create([
    'text' => 'Hello world',
    'embedding' => json_encode($embedding)
]);
Enter fullscreen mode Exit fullscreen mode

Conclusion
Now you have a working Vector Database in SQLite inside Laravel, supporting vector storage and similarity search—ideal for LLM applications like retrieval-augmented generation (RAG).

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs