Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Ai Supabase Store Laravel Package

symfony/ai-supabase-store

Supabase vector store integration for Symfony AI Store using PostgreSQL pgvector. Connect your Symfony AI apps to Supabase vector columns and the match_documents RPC for similarity search, with links to Supabase docs and Symfony AI contribution/resources.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package Add the package to your Laravel project via Composer:

    composer require symfony/ai-supabase-store
    

    For Laravel, ensure you have the Symfony Bridge installed (if not using Symfony directly):

    composer require symfony/http-client symfony/options-resolver
    
  2. Configure Supabase Connection Publish the package’s configuration (if available) or manually set up Supabase credentials in .env:

    SUPABASE_URL=your-supabase-url
    SUPABASE_KEY=your-supabase-key
    SUPABASE_VECTOR_TABLE=your_vector_table
    
  3. Set Up Supabase Table Create a table in Supabase with a vector column (pgvector extension required):

    CREATE TABLE documents (
        id BIGSERIAL PRIMARY KEY,
        content TEXT,
        embedding vector(1536), -- Adjust dimension to your embedding size
        metadata JSONB
    );
    

    Enable the match_documents RPC function (refer to Supabase’s pgvector guide).

  4. First Use Case: Store and Query Embeddings Use the store in a Laravel service or controller:

    use Symfony\Component\AI\Store\StoreInterface;
    use Symfony\Component\AI\Store\SupabaseStore;
    
    // Initialize the store (Laravel-specific adaptation)
    $store = new SupabaseStore(
        new \Symfony\Component\AI\Store\SupabaseClient(
            env('SUPABASE_URL'),
            env('SUPABASE_KEY')
        ),
        env('SUPABASE_VECTOR_TABLE')
    );
    
    // Store an embedding
    $store->add([
        'id' => 'doc1',
        'embedding' => $embeddingArray, // Your 1536-dim vector
        'metadata' => ['source' => 'user_upload', 'tags' => ['ai', 'laravel']],
    ]);
    
    // Query similar embeddings
    $results = $store->query($queryEmbedding, limit: 5, filter: ['source' => 'user_upload']);
    

Implementation Patterns

Workflows

  1. RAG Pipeline Integration Combine with Laravel AI tools (e.g., symfonycasts/laravel-ai) for Retrieval-Augmented Generation:

    // Retrieve context for LLM prompt
    $context = $store->query($userQueryEmbedding, limit: 3);
    $prompt = "Answer based on: " . implode("\n", $context) . "\n\nUser: {$userQuery}";
    
    // Use Laravel AI to generate response
    $response = app(\SymfonyCast\Laravel\Ai\Services\OpenAI::class)->complete($prompt);
    
  2. Semantic Search Replace keyword search with vector similarity:

    // Generate embedding for search query (e.g., using `symfonycasts/laravel-ai`)
    $queryEmbedding = app(\SymfonyCast\Laravel\Ai\Services\OpenAI::class)->embed("Laravel AI packages");
    
    // Fetch top 5 similar documents
    $results = $store->query($queryEmbedding, limit: 5);
    
  3. Hybrid Filtering Combine metadata filters with vector search:

    $results = $store->query(
        $embedding,
        filter: ['tags' => ['ai'], 'source' => 'documentation'],
        limit: 10
    );
    

Integration Tips

  • Laravel Service Container Bind the store to Laravel’s container for dependency injection:

    // In AppServiceProvider
    $this->app->singleton(StoreInterface::class, function ($app) {
        return new SupabaseStore(
            new \Symfony\Component\AI\Store\SupabaseClient(
                env('SUPABASE_URL'),
                env('SUPABASE_KEY')
            ),
            env('SUPABASE_VECTOR_TABLE')
        );
    });
    
  • Batch Operations Use Laravel’s DB::transaction for atomic batch inserts:

    DB::transaction(function () use ($store, $embeddings) {
        foreach ($embeddings as $embedding) {
            $store->add($embedding);
        }
    });
    
  • Caching Layer Cache frequent queries (e.g., with Laravel Cache):

    $cacheKey = "search:{$userQueryHash}";
    $results = cache()->remember($cacheKey, now()->addMinutes(5), function () use ($store, $embedding) {
        return $store->query($embedding, limit: 5);
    });
    
  • Event-Driven Updates Trigger updates via Laravel events (e.g., after document creation):

    // In DocumentCreated event listener
    $store->add([
        'id' => $document->id,
        'embedding' => $document->embedding,
        'metadata' => $document->metadata,
    ]);
    

Gotchas and Tips

Pitfalls

  1. Supabase RPC Limitations

    • The match_documents RPC has default limits (e.g., 100MB payload). Exceeding these may fail silently or return partial results.
    • Workaround: Split large batches into smaller chunks or use Supabase’s REST API as a fallback.
  2. Embedding Dimension Mismatch

    • Ensure your embedding vectors match the table’s vector(N) column. Mismatches cause errors or corrupt data.
    • Debugging: Check Supabase logs or enable Laravel’s query logging:
      DB_LOG_QUERIES=true
      
  3. Filter Syntax Quirks

    • The filter parameter uses SQL-like syntax but is passed as a JSON object. Nested filters may not work as expected.
    • Example: Use flat structures like ['tags' => ['ai']] instead of nested arrays.
  4. Connection Timeouts

    • Supabase API timeouts (default: 30s) can occur for large queries. Increase PHP’s timeout if needed:
      ini_set('default_socket_timeout', 60);
      
  5. Laravel-Symfony DI Conflicts

    • Symfony’s StoreInterface may conflict with Laravel’s autowiring. Explicitly type-hint the interface:
      public function __construct(private StoreInterface $store) {}
      

Debugging

  • Enable Supabase Logging Add this to your Supabase client initialization:

    $client = new \Symfony\Component\AI\Store\SupabaseClient(
        env('SUPABASE_URL'),
        env('SUPABASE_KEY'),
        ['log' => true] // Enable RPC logging
    );
    
  • Check RPC Execution Verify the match_documents RPC is working in Supabase’s SQL editor:

    SELECT match_documents(
        'documents',
        '[1.2, 3.4, ...]', -- Your embedding vector
        'cosine_distance',
        'id, content, metadata',
        5,
        '{}' -- Filters as JSON
    );
    
  • Laravel Query Logging Enable logging for Supabase queries:

    \DB::enableQueryLog();
    $results = $store->query($embedding);
    \Log::debug(\DB::getQueryLog());
    

Extension Points

  1. Custom Distance Metrics Extend the store to support non-default distance metrics (e.g., euclidean):

    class CustomSupabaseStore extends SupabaseStore {
        public function query($embedding, array $options = []) {
            $options['distance'] = $options['distance'] ?? 'euclidean';
            return parent::query($embedding, $options);
        }
    }
    
  2. Fallback to REST API Override RPC calls for better error handling:

    class ResilientSupabaseStore extends SupabaseStore {
        protected function callRpc($rpcName, array $args) {
            try {
                return parent::callRpc($rpcName, $args);
            } catch (\Exception $e) {
                // Fallback to REST API
                return $this->callSupabaseApi($rpcName, $args);
            }
        }
    }
    
  3. Laravel Model Integration Create a model wrapper for seamless ORM usage:

    class Document extends Model {
        public function embeddings() {
            return $this->hasMany(DocumentEmbedding::class);
        }
    
        public function addToVectorStore() {
            $store = app(StoreInterface::class);
            $store->add([
                'id' => $this->id,
                'embedding' => $this->embeddings->first()->vector,
                'metadata' => $this->toArray(),
            ]);
        }
    }
    
  4. Async Processing Use Laravel Queues for non-blocking operations:

    class AddEmbed
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity