PHP code example of helgesverre / chromadb

1. Go to this page and download the library: Download helgesverre/chromadb library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

helgesverre / chromadb example snippets


use HelgeSverre\Chromadb\Chromadb;

// Initialize client with direct instantiation
$chromadb = new Chromadb(
    token: 'test-token-chroma-local-dev',
    host: 'http://localhost',
    port: '8000'
);

// Create a collection
$response = $chromadb->collections()->create('my_collection');
$collectionId = $response->json('id');

// Add documents with embeddings
$chromadb->items()->add(
    collectionId: $collectionId,
    ids: ['doc1', 'doc2'],
    embeddings: [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]],
    documents: ['Document 1', 'Document 2']
);

// Query the collection
$results = $chromadb->items()->query(
    collectionId: $collectionId,
    queryEmbeddings: [[0.1, 0.2, 0.3]],
    nResults: 10
);

use HelgeSverre\Chromadb\Facades\Chromadb;

// Using the Facade (configuration loaded from config/chromadb.php)
$response = Chromadb::client()->collections()->create('my_collection');

// Create a new collection with optional metadata
$chromadb->collections()->create(
    name: 'my_collection',
);

// Create a collection with metadata and configuration
$chromadb->collections()->create(
    name: 'my_collection',
    metadata: ['description' => 'My collection'],
    configuration: [
        'hnsw:space' => 'cosine',
        'hnsw:construction_ef' => 100,
        'hnsw:M' => 16
    ]
);

// Count the number of collections
$chromadb->collections()->count();

// Retrieve a specific collection by name
$chromadb->collections()->get(
    collectionName: 'my_collection'
);

// Delete a collection by name
$chromadb->collections()->delete(
    collectionName: 'my_collection'
);

// Update a collection's name and/or metadata
$chromadb->collections()->update(
    collectionId: '3ea5a914-e2ab-47cb-b285-8e585c9af4f3',
    newName: 'new_collection_name',
    newMetadata: ['updated' => 'true']
);

// List all collections
$collections = $chromadb->collections()->list();

// List collections with pagination
$collections = $chromadb->collections()->list(
    limit: 10,
    offset: 0
);

// Fork a collection (create a copy)
$chromadb->collections()->fork(
    collectionId: '3ea5a914-e2ab-47cb-b285-8e585c9af4f3',
    newName: 'my_collection_copy'
);

// Get collection by CRN (Collection Resource Name)
$chromadb->collections()->getByCrn(
    crn: 'crn:chroma:collection:default_tenant:default_database:3ea5a914-e2ab-47cb-b285-8e585c9af4f3'
);

// Add items to a collection with embeddings, metadata, and documents
$chromadb->items()->add(
    collectionId: '3ea5a914-e2ab-47cb-b285-8e585c9af4f3',
    ids: ['item1', 'item2'],
    embeddings: [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]],
    documents: ['doc1', 'doc2']
);

// Update items in a collection with new embeddings, metadata, and documents
$chromadb->items()->update(
    collectionId: '3ea5a914-e2ab-47cb-b285-8e585c9af4f3',
    ids: ['item1', 'item2'],
    embeddings: [[0.7, 0.8, 0.9], [1.0, 1.1, 1.2]],
    documents: ['new_doc1', 'new_doc2']
);

// Upsert items in a collection (insert if not exist, update if exist)
$chromadb->items()->upsert(
    collectionId: '3ea5a914-e2ab-47cb-b285-8e585c9af4f3',
    ids: ['item'],
    embeddings: [[0.5, 0.6, 0.7]],
    metadatas: [['title' => 'metadata']],
    documents: ['document']
);

// Retrieve specific items from a collection by their IDs
$chromadb->items()->get(
    collectionId: '3ea5a914-e2ab-47cb-b285-8e585c9af4f3',
    ids: ['item1', 'item2']
);

// Delete specific items from a collection by their IDs
$chromadb->items()->delete(
    collectionId: '3ea5a914-e2ab-47cb-b285-8e585c9af4f3',
    ids: ['item1', 'item2']
);

// Count the number of items in a collection
$chromadb->items()->count(
    collectionId: '3ea5a914-e2ab-47cb-b285-8e585c9af4f3'
);

// Query items in a collection based on embeddings, texts, and other filters
$chromadb->items()->query(
    collectionId: '3ea5a914-e2ab-47cb-b285-8e585c9af4f3',
    queryEmbeddings: [[0.8, 0.8, 0.8]],
    include: ['documents', 'metadatas', 'distances'],
    nResults: 5
);

// Hybrid search with multiple search strategies
// Note: search() orted filter operators:
// $eq, $ne, $gt, $gte, $lt, $lte, $in, $nin, $and, $or, $not, $contains

// Create a new database
$chromadb->database()->create(name: 'production');

// Get database information
$response = $chromadb->database()->get(database: 'production');

// List all databases in the current tenant
$databases = $chromadb->database()->list();

// List databases with pagination
$databases = $chromadb->database()->list(
    limit: 10,
    offset: 0
);

// Delete a database
$chromadb->database()->delete(database: 'old_database');

// Work with a specific database
$productionDb = $chromadb->withDatabase('production');
$stagingDb = $chromadb->withDatabase('staging');

// Create a new tenant
$chromadb->tenant()->create(name: 'customer_acme');

// Get tenant information
$response = $chromadb->tenant()->get(tenant: 'customer_acme');

// Update tenant configuration
$chromadb->tenant()->update(
    tenantName: 'customer_acme',
    resourceName: 'acme-corp-resource'
);

// Check server health
$response = $chromadb->server()->healthcheck();

// Get heartbeat (nanosecond timestamp)
$response = $chromadb->server()->heartbeat();

// Get server version
$version = $chromadb->server()->version();

// Get pre-flight checks information
$response = $chromadb->server()->preFlightChecks();

// Get current user identity and permissions
$response = $chromadb->server()->identity();
$userId = $response->json('user_id');
$tenant = $response->json('tenant');
$databases = $response->json('databases');

// Reset the server (⚠️ WARNING: Deletes all data)
$success = $chromadb->server()->reset();

// Create tenant-specific clients
$tenant1Client = $chromadb->withTenant('customer_a');
$tenant2Client = $chromadb->withTenant('customer_b');

// Operations are automatically isolated
$tenant1Collections = $tenant1Client->collections()->list();
$tenant2Collections = $tenant2Client->collections()->list();

// Switch database context
$productionClient = $chromadb
    ->withTenant('my_org')
    ->withDatabase('production');

// Attach a function to a collection
$response = $chromadb->collections()->attachFunction(
    collectionId: '3ea5a914-e2ab-47cb-b285-8e585c9af4f3',
    name: 'my-stats',
    functionId: 'statistics',
    outputCollection: 'stats-output',
    params: ['key' => 'value'] // optional
);

// Get attached function details
$response = $chromadb->collections()->getAttachedFunction(
    collectionId: '3ea5a914-e2ab-47cb-b285-8e585c9af4f3',
    functionName: 'my-stats'
);

// Detach a function from a collection
$response = $chromadb->collections()->detachFunction(
    collectionId: '3ea5a914-e2ab-47cb-b285-8e585c9af4f3',
    functionName: 'my-stats',
    deleteOutput: true // optionally delete the output collection
);

return [
    'token' => env('CHROMADB_TOKEN'),
    'host' => env('CHROMADB_HOST', 'http://localhost'),
    'port' => env('CHROMADB_PORT', '8000'),

    'tenant' => env('CHROMADB_TENANT', 'default_tenant'),
    'database' => env('CHROMADB_DATABASE', 'default_database'),

    'embeddings' => [
        'default' => env('CHROMADB_EMBEDDING_PROVIDER', 'openai'),
        'providers' => [
            'openai' => [
                'api_key' => env('OPENAI_API_KEY'),
                'model' => env('OPENAI_EMBEDDING_MODEL', 'text-embedding-3-small'),
                'dimensions' => env('OPENAI_EMBEDDING_DIMENSIONS', null), // Optional: reduce dimensions
                'organization' => env('OPENAI_ORGANIZATION', null), // Optional: organization ID
            ],
            'voyage' => [
                'api_key' => env('VOYAGE_API_KEY'),
                'model' => env('VOYAGE_EMBEDDING_MODEL', 'voyage-3.5'),
                'input_type' => env('VOYAGE_INPUT_TYPE', 'document'), // 'document' or 'query'
            ],
            'mistral' => [
                'api_key' => env('MISTRAL_API_KEY'),
                'model' => env('MISTRAL_EMBEDDING_MODEL', 'mistral-embed'),
            ],
            'jina' => [
                'api_key' => env('JINA_API_KEY'),
                'model' => env('JINA_EMBEDDING_MODEL', 'jina-embeddings-v3'),
                'task' => env('JINA_TASK', null), // Optional: 'retrieval.query', 'retrieval.passage', 'text-matching'
                'dimensions' => env('JINA_EMBEDDING_DIMENSIONS', null), // Optional: reduce dimensions
            ],
            'ollama' => [
                'base_url' => env('OLLAMA_BASE_URL', 'http://localhost:11434'),
                'model' => env('OLLAMA_EMBEDDING_MODEL', 'all-minilm'),
            ],
        ],
    ],
];

use HelgeSverre\Chromadb\Facades\Chromadb;

// Access through Facade (uses config automatically)
$collections = Chromadb::client()->collections()->list();
$response = Chromadb::client()->collections()->create('my_collection');

use HelgeSverre\Chromadb\Chromadb;

class MyController
{
    public function __construct(private Chromadb $chromadb)
    {
        // $chromadb is automatically configured from config/chromadb.php
    }

    public function index()
    {
        $collections = $this->chromadb->collections()->list();
        return view('collections.index', compact('collections'));
    }
}

use HelgeSverre\Chromadb\Embeddings\Embeddings;

// Create embedder from Laravel config
$embedder = Embeddings::fromConfig('openai');

// Or use the default provider from config
$embedder = Embeddings::fromConfig(); // Uses CHROMADB_EMBEDDING_PROVIDER

use HelgeSverre\Chromadb\Embeddings\Embeddings;

// Create embedder with direct instantiation
$embedder = Embeddings::openai(
    apiKey: 'sk-your-api-key',
    model: 'text-embedding-3-small'
);

// Generate embeddings
$documents = [
    'The quick brown fox jumps over the lazy dog',
    'Vector databases enable semantic search',
];

$embeddings = $embedder->generate($documents);

// Add to ChromaDB
$chromadb->items()->add(
    collectionId: $collectionId,
    ids: ['doc1', 'doc2'],
    embeddings: $embeddings,
    documents: $documents
);

use HelgeSverre\Chromadb\Embeddings\Embeddings;

// Create embedder from Laravel config (mbedder = Embeddings::fromConfig(); // Uses CHROMADB_EMBEDDING_PROVIDER

$embeddings = $embedder->generate($documents);

// Create an embedding function
$embedder = new OpenAIEmbeddings(apiKey: 'sk-...');

// Configure client with embedder
$chromadb = $chromadb->withEmbeddings($embedder);

// Add documents with automatic embeddings
$chromadb->items()->addWithEmbeddings(
    collectionId: $collectionId,
    documents: ['Document 1', 'Document 2'],
    embeddingFunction: null,  // Optional: override default embedding function
    ids: ['doc1', 'doc2'],    // Optional: auto-generated if null
    metadatas: [['type' => 'article'], ['type' => 'blog']]  // Optional
);

// Query with text (automatic embedding) - basic usage
$results = $chromadb->items()->queryWithText(
    collectionId: $collectionId,
    queryText: 'search query',
    nResults: 10
);

// Query with text - advanced usage with override and filters
$mistralEmbedder = new MistralEmbeddings(
    apiKey: 'your-mistral-key',
    model: 'mistral-embed'
);

$results = $chromadb->items()->queryWithText(
    collectionId: $collectionId,
    queryText: 'machine learning',
    embeddingFunction: $mistralEmbedder,  // Override default embedder
    nResults: 10,
    

use HelgeSverre\Chromadb\Embeddings\OpenAIEmbeddings;
use HelgeSverre\Chromadb\Embeddings\Embeddings;

// Direct instantiation
$embedder = new OpenAIEmbeddings(
    apiKey: 'sk-your-api-key',
    model: 'text-embedding-3-small',  // Default
    dimensions: 1536,                 // Optional: dimension reduction
    organization: 'org-123'           // Optional: organization ID
);

// Or using factory
$embedder = Embeddings::openai(
    apiKey: 'sk-your-api-key',
    model: 'text-embedding-3-small'
);

// Supported models:
// - text-embedding-3-small (1536 dims, efficient)
// - text-embedding-3-large (3072 dims, best quality)
// - text-embedding-ada-002 (1536 dims, legacy)

use HelgeSverre\Chromadb\Embeddings\VoyageAIEmbeddings;

$embedder = new VoyageAIEmbeddings(
    apiKey: 'your-voyage-api-key',
    model: 'voyage-3.5',      // Default
    inputType: 'document'     // 'document' or 'query'
);

// Or using factory
$embedder = Embeddings::voyage(
    apiKey: 'your-voyage-api-key',
    model: 'voyage-3.5'
);

// Supported models:
// - voyage-3.5 (efficient, 8M TPM)
// - voyage-3-large (best quality)
// - voyage-code-3 (optimized for code)
// - voyage-finance-2 (financial domain)
// - voyage-law-2 (legal domain)

use HelgeSverre\Chromadb\Embeddings\MistralEmbeddings;

$embedder = new MistralEmbeddings(
    apiKey: 'your-mistral-api-key',
    model: 'mistral-embed'  // Default (1024 dimensions)
);

// Or using factory
$embedder = Embeddings::mistral(
    apiKey: 'your-mistral-api-key',
    model: 'mistral-embed'
);

use HelgeSverre\Chromadb\Embeddings\JinaEmbeddings;

$embedder = new JinaEmbeddings(
    apiKey: 'your-jina-api-key',
    model: 'jina-embeddings-v3',           // Default
    task: 'retrieval.query',               // Optional: task type
    dimensions: 1024                       // Optional: dimension reduction
);

// Or using factory
$embedder = Embeddings::jina(
    apiKey: 'your-jina-api-key',
    model: 'jina-embeddings-v3'
);

// Supported models:
// - jina-embeddings-v3 (570M, 1024 dims, multilingual)
// - jina-embeddings-v2-base-en (137M, 768 dims, English)
// - jina-embeddings-v2-small-en (33M, 512 dims, English)
// - jina-clip-v2 (885M, 1024 dims, multimodal)
//
// Optional task types:
// - retrieval.query
// - retrieval.passage
// - text-matching

use HelgeSverre\Chromadb\Embeddings\OllamaEmbeddings;

$embedder = new OllamaEmbeddings(
    model: 'all-minilm',                    // Default
    baseUrl: 'http://localhost:11434',     // Default
    timeout: 60                             // Default timeout in seconds
);

// Or using factory
$embedder = Embeddings::ollama(
    model: 'all-minilm',
    baseUrl: 'http://localhost:11434'
);

// Supported models (any Ollama model):
// - all-minilm (lightweight, default)
// - nomic-embed-text (high quality)
// - mxbai-embed-large (larger model)
// - snowflake-arctic-embed (specialized)

use function HelgeSverre\Chromadb\Embeddings\embeddings_openai;
use function HelgeSverre\Chromadb\Embeddings\embeddings_voyage;
use function HelgeSverre\Chromadb\Embeddings\embeddings_mistral;
use function HelgeSverre\Chromadb\Embeddings\embeddings_jina;
use function HelgeSverre\Chromadb\Embeddings\embeddings_ollama;

// Generate embeddings using helper functions
$embeddings = embeddings_openai(
    texts: ['Document 1', 'Document 2'],
    apiKey: 'sk-your-api-key',
    model: 'text-embedding-3-small'
);

$embeddings = embeddings_voyage(
    texts: ['Document 1', 'Document 2'],
    apiKey: 'your-voyage-key',
    model: 'voyage-3.5'
);

$embeddings = embeddings_mistral(
    texts: ['Document 1', 'Document 2'],
    apiKey: 'your-mistral-key'
);

$embeddings = embeddings_jina(
    texts: ['Document 1', 'Document 2'],
    apiKey: 'your-jina-key',
    model: 'jina-embeddings-v3'
);

$embeddings = embeddings_ollama(
    texts: ['Document 1', 'Document 2'],
    model: 'all-minilm',
    baseUrl: 'http://localhost:11434'
);

// Use directly with ChromaDB
$chromadb->items()->add(
    collectionId: $collectionId,
    ids: ['doc1', 'doc2'],
    embeddings: embeddings_openai(
        texts: ['Document 1', 'Document 2'],
        apiKey: 'sk-your-api-key'
    ),
    documents: ['Document 1', 'Document 2']
);

use HelgeSverre\Chromadb\Embeddings\EmbeddingFunction;

class MyCustomEmbeddings implements EmbeddingFunction
{
    public function __construct(
        private string $apiKey,
        private string $model = 'my-model'
    ) {}

    /**
     * Generate embeddings for the given texts.
     *
     * @param array<string> $texts Array of text strings to embed
     * @return array<array<float>> 2D array where each element is an embedding vector
     */
    public function generate(array $texts): array
    {
        $embeddings = [];

        foreach ($texts as $text) {
            // Your custom embedding logic here
            $vector = $this->callYourEmbeddingAPI($text);
            $embeddings[] = $vector;
        }

        return $embeddings;
    }

    private function callYourEmbeddingAPI(string $text): array
    {
        // Call your embedding service
        // Return array of floats, e.g., [0.1, 0.2, 0.3, ...]
        return [];
    }
}

// Use your custom embedder
$embedder = new MyCustomEmbeddings(apiKey: 'your-key');
$chromadb = $chromadb->withEmbeddings($embedder);

namespace HelgeSverre\Chromadb\Embeddings;

interface EmbeddingFunction
{
    /**
     * Generate embeddings for the given texts.
     *
     * @param array<string> $texts An array of text strings to embed
     * @return array<array<float>> A 2D array where each element is an embedding vector
     * @throws \HelgeSverre\Chromadb\Exceptions\EmbeddingException
     */
    public function generate(array $texts): array;
}

$blogPosts = [
    [
        'title' => 'Exploring Laravel',
        'summary' => 'A deep dive into Laravel frameworks...',
        'tags' => 'PHP, Laravel, Web Development'
    ],
    [
        'title' => 'Introduction to React',
        'summary' => 'Understanding the basics of React and how it revolutionizes frontend development.',
        'tags' => 'JavaScript, React, Frontend'
    ],
];

$summaries = array_column($blogPosts, 'summary');
$embeddingsResponse = OpenAI::client('sk-your-openai-api-key')
    ->embeddings()
    ->create([
        'model' => 'text-embedding-ada-002',
        'input' => $summaries,
    ]);

foreach ($embeddingsResponse->embeddings as $embedding) {
    $blogPosts[$embedding->index]['vector'] = $embedding->embedding;
}

$createCollectionResponse = $chromadb->collections()->create(
    name: 'blog_posts',
);

$collectionId = $createCollectionResponse->json('id');

foreach ($blogPosts as $post) {
    // Extract embedding from post (v2 API metadata cannot contain arrays)
    $embedding = $post['vector'];
    unset($post['vector']); // Remove from metadata

    $chromadb->items()->add(
        collectionId: $collectionId,
        ids: [$post['title']],
        embeddings: [$embedding],
        metadatas: [$post]
    );
}

$searchResponse = OpenAI::client('sk-your-openai-api-key')
    ->embeddings()
    ->create([
        'model' => 'text-embedding-ada-002',
        'input' => 'laravel framework',
    ]);

$searchEmbedding = $searchResponse->embeddings[0]->embedding;

$searchResponse = $chromadb->items()->query(
    collectionId: $collectionId,
    queryEmbeddings: [$searchEmbedding],
    nResults: 3,
    atas as $index => $metadata) {
    echo "Title: " . $metadata['title'] . "\n";
    echo "Summary: " . $metadata['summary'] . "\n";
    echo "Tags: " . $metadata['tags'] . "\n\n";
}
bash
php artisan vendor:publish --tag="chromadb-config"