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 Chroma Db Store Laravel Package

symfony/ai-chroma-db-store

ChromaDB Store integration for Symfony AI Store. Use ChromaDB as a vector store to manage collections and run query/get operations for embeddings and similarity search. Includes links to Chroma docs plus Symfony AI contributing and issue/PR resources.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Install the Package:

    composer require symfony/ai-chroma-db-store
    

    Ensure symfony/ai (≥v0.8.0) is also installed.

  2. Configure ChromaDB: Add to .env:

    CHROMA_HOST=http://localhost:8000
    CHROMA_API_KEY=your_api_key_here
    CHROMA_COLLECTION=laravel_vectors
    
  3. Bind the Store: In AppServiceProvider@register():

    $this->app->bind(\Symfony\AI\Store\StoreInterface::class, function ($app) {
        return new \Symfony\AI\ChromaDbStore(
            host: env('CHROMA_HOST'),
            apiKey: env('CHROMA_API_KEY'),
            collection: env('CHROMA_COLLECTION')
        );
    });
    
  4. First Use Case: Store and query a vector in a Laravel controller:

    use Symfony\AI\Store\StoreInterface;
    
    public function storeVector(StoreInterface $store)
    {
        $vector = [0.1, 0.2, 0.3, 0.4]; // Example embedding
        $metadata = ['document_id' => 123, 'source' => 'user_guide'];
    
        // Store
        $store->add($vector, $metadata);
    
        // Query
        $results = $store->find($vector, limit: 3);
        return $results;
    }
    
  5. Test Locally: Spin up ChromaDB via Docker:

    docker run -p 8000:8000 chromadb/chroma
    

Implementation Patterns

Core Workflows

1. Vector CRUD

  • Insert:

    $store->add($vector, $metadata);
    

    Use for storing embeddings (e.g., from symfony/ai's EmbeddingGenerator).

  • Update:

    $store->update($id, $newVector, $newMetadata);
    

    Update existing vectors (e.g., retraining embeddings).

  • Delete:

    $store->remove($id);
    

    Remove vectors by ID (e.g., user deletion).

  • Bulk Operations:

    $store->addMany([[$vector1, $metadata1], [$vector2, $metadata2]]);
    

2. Querying with Filters

Combine vector similarity with metadata filters:

$results = $store->find(
    $queryVector,
    limit: 5,
    where: ['category' => 'tech', 'published' => true]
);
  • Filter Syntax: Use ChromaDB’s filter syntax (e.g., whereMetadata()).
  • Hybrid Search: Combine keyword and vector search by filtering post-retrieval.

3. Repository Pattern

Abstract ChromaDB calls in a Laravel repository:

namespace App\Repositories;

class VectorRepository {
    public function __construct(private StoreInterface $store) {}

    public function findSimilarDocuments($queryVector, int $limit = 3) {
        return $this->store->find($queryVector, limit: $limit);
    }

    public function storeDocumentEmbedding($vector, array $metadata) {
        $this->store->add($vector, $metadata);
    }
}

Register the repository in Laravel’s container:

$this->app->bind(VectorRepository::class, function ($app) {
    return new VectorRepository($app->make(StoreInterface::class));
});

4. Event-Driven Workflows

Dispatch Laravel events for ChromaDB operations:

use Illuminate\Support\Facades\Event;

$store->add($vector, $metadata);
Event::dispatch(new VectorStored($metadata));

Listen for events in EventServiceProvider:

protected $listen = [
    VectorStored::class => [
        \App\Listeners\LogVectorStorage::class,
        \App\Listeners\UpdateSearchIndex::class,
    ],
];

5. Batch Processing

Offload bulk operations to Laravel queues:

// Job: ProcessEmbeddingsJob
public function handle() {
    $vectors = $this->getVectorsFromDatabase();
    $this->store->addMany($vectors);
}

Dispatch the job:

ProcessEmbeddingsJob::dispatch();

Integration Tips

Laravel-Specific

  • Service Container: Always bind StoreInterface to ChromaDbStore for loose coupling.
  • Configuration: Use Laravel’s config('chroma') for host/API key settings:
    'chroma' => [
        'host' => env('CHROMA_HOST'),
        'api_key' => env('CHROMA_API_KEY'),
        'collection' => env('CHROMA_COLLECTION'),
    ],
    
  • Validation: Validate vectors/metadata before storing:
    use Illuminate\Support\Facades\Validator;
    
    $validator = Validator::make($metadata, [
        'document_id' => 'required|integer',
        'source' => 'required|string',
    ]);
    

ChromaDB-Specific

  • Collections: Treat collections like database tables:
    • Create collections on demand or via migrations.
    • Example: Use Laravel’s Artisan command to initialize:
      public function boot() {
          if (! $this->chromaCollectionExists()) {
              $this->createChromaCollection();
          }
      }
      
  • Metadata Schema: Define metadata fields upfront to avoid runtime errors.
  • Vector Dimensions: Ensure all vectors have the same dimension (e.g., 768 for sentence-transformers).

Performance

  • Caching: Cache frequent queries with Symfony’s cache or Laravel’s cache:
    $cacheKey = 'vector_query_' . md5(serialize($queryVector));
    $results = Cache::remember($cacheKey, now()->addMinutes(5), function () use ($store, $queryVector) {
        return $store->find($queryVector);
    });
    
  • Batching: Use addMany() for bulk inserts (e.g., during data migration).
  • Indexing: Leverage ChromaDB’s native indexing for metadata filters.

Gotchas and Tips

Pitfalls

  1. API Key Exposure:

    • Risk: Hardcoding CHROMA_API_KEY in .env may not be secure enough for production.
    • Fix: Use Laravel’s Vault or a secrets manager (e.g., AWS Secrets Manager).
  2. Vector Dimension Mismatch:

    • Risk: Storing vectors of inconsistent dimensions (e.g., 384 vs. 768) causes errors.
    • Fix: Validate dimensions before insertion:
      if (count($vector) !== config('chroma.vector_dimension')) {
          throw new \InvalidArgumentException('Vector dimension mismatch');
      }
      
  3. Filter Syntax Errors:

    • Risk: ChromaDB’s filter syntax differs from Laravel’s. Example:
      // ❌ Wrong (Laravel-style)
      $store->find($vector, where: ['category' => 'tech']);
      
      // ✅ Correct (ChromaDB-style)
      $store->find($vector, where: ['category' => 'tech', 'operator' => 'Equal']);
      
    • Fix: Refer to ChromaDB’s filter docs.
  4. Connection Timeouts:

    • Risk: ChromaDB API timeouts (e.g., 30s) may fail silently.
    • Fix: Configure Guzzle/Symfony HTTP client timeouts:
      $client = new \Symfony\Contracts\HttpClient\HttpClient([
          'timeout' => 60,
      ]);
      
  5. Collection Not Found:

    • Risk: Querying a non-existent collection throws an error.
    • Fix: Check collection existence before querying:
      if (! $this->chromaCollectionExists()) {
          $this->createChromaCollection();
      }
      
  6. Metadata Size Limits:

    • Risk: ChromaDB has metadata size limits (~100KB per document).
    • Fix: Store large metadata in a separate database (e.g., PostgreSQL) and reference IDs in ChromaDB.
  7. Symfony AI Version Mismatch:

    • Risk: Using an incompatible symfony/ai version breaks the store.
    • Fix: Pin versions in composer.json:
      "symfony/ai": "^0.8.0",
      "symfony/ai-chroma-db-store": "^0.8.0"
      

Debugging

  1. Enable Logging: Configure ChromaDB client logging:
    $client = new \Symfony\Contracts\HttpClient\HttpClient([
        'headers' => ['Authorization
    
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
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
christhompsontldr/laravel-inky