PHP code example of codewithkyrian / chromadb-php

1. Go to this page and download the library: Download codewithkyrian/chromadb-php 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/ */

    

codewithkyrian / chromadb-php example snippets


use Codewithkyrian\ChromaDB\ChromaDB;

// Basic Connection
$client = ChromaDB::local()->connect();

// Custom Host/Port
$client = ChromaDB::local()
    ->withHost('http://your-server-ip')
    ->withPort(8000)
    ->withTenant('my-tenant')
    ->withDatabase('production_db')
    ->connect();

// Chroma Cloud / Authentication
$client = ChromaDB::cloud('your-api-key')
    ->withTenant('tenant-id')
    ->connect();

use Codewithkyrian\ChromaDB\Embeddings\OpenAIEmbeddingFunction;

$ef = new OpenAIEmbeddingFunction('your-openai-api-key');

$collection = $client->createCollection(
    name: 'knowledge-base',
    embeddingFunction: $ef
);

use Codewithkyrian\ChromaDB\Embeddings\EmbeddingFunction;

$ef = new class implements EmbeddingFunction {
    public function generate(array $texts): array {
        // Call your model API here and return float[][]
        return [[0.1, 0.2, ...], ...];
    }
};

// Create (throws if exists)
$collection = $client->createCollection('my-collection', $ef);

// Get (throws if missing)
$collection = $client->getCollection('my-collection');

// Get or Create =
$collection = $client->getOrCreateCollection('my-collection', $ef);

// Fork (creates a copy of an existing collection)
// Note: Forking is only supported for Chroma Cloud, not local Chroma instances
$forkedCollection = $client->forkCollection('my-collection', 'my-collection-fork', $ef);

// Delete
$client->deleteCollection('my-collection');

$collection->add(
    ids: ['id1', 'id2'],
    documents: ['This is a document about PHP.', 'ChromaDB is great for AI.'],
    embeddings: [[0.1, 0.2, 0.3], [0.9, 0.8, 0.7]],
    metadatas: [
        ['category' => 'development', 'author' => 'Kyrian'],
        ['category' => 'ai', 'is_published' => true]
    ]
);

use Codewithkyrian\ChromaDB\Types\Record;

$collection->add([
    // Fluent Factory style
    Record::make('id4')
        ->withDocument('This is a document about PHP.')
        ->withEmbedding([0.1, 0.2, 0.3])
        ->withMetadata(['category' => 'development', 'author' => 'Kyrian']),

    // Constructor style
    new Record(
        id: 'id7',
        document: 'ChromaDB is great for AI.',
        embedding: [0.9, 0.8, 0.7],
        metadata: ['category' => 'ai', 'is_published' => true]
    ),
]);

use Codewithkyrian\ChromaDB\Types\Includes;

// Fetch by ID
$item = $collection->get(ids: ['id1']);

// Fetch filtered items (Metadata Filter)
$items = $collection->get(
    where: ['category' => 'php'], 
    

$preview = $collection->peek(limit: 5);

use Codewithkyrian\ChromaDB\Types\Includes;

$collection->get(
    ids: ['id1'],
    , // Return the metadata
        Includes::Embeddings // Return the vector
    ]
);

$results = $collection->query(
    queryTexts: ['How do I use PHP with Chroma?'], 
    nResults: 5 // Return top 5 matches
);

// Get results as ScoredRecord objects
// Returns ScoredRecord[][] (one array of results per query text)
$records = $results->asRecords();

$results = $collection->query(
    queryEmbeddings: [[0.1, 0.2, ...]], 
    nResults: 5
);

use Codewithkyrian\ChromaDB\Types\Includes;

$collection->query(
    queryTexts: ['How do I use PHP with Chroma?'], 
    nResults: 5,
    

// Equals
Where::field('category')->eq('news');
['category' => ['$eq' => 'news']];

// Not Equals
Where::field('status')->ne('archived');
['status' => ['$ne' => 'archived']];

// Greater Than
Where::field('views')->gt(100);
['views' => ['$gt' => 100]];

// Less Than
Where::field('rating')->lt(5);
['rating' => ['$lt' => 5]];

// Greater Than or Equal To
Where::field('views')->gte(100);
['views' => ['$gte' => 100]];

// Less Than or Equal To
Where::field('rating')->lte(5);
['rating' => ['$lte' => 5]];

// List inclusion
Where::field('tag')->in(['php', 'laravel']);
['tag' => ['$in' => ['php', 'laravel']]];

// List exclusion
Where::field('tag')->nin(['php', 'laravel']);
['tag' => ['$nin' => ['php', 'laravel']]];

// Logical AND
Where::all(
    Where::field('category')->eq('code'),
    Where::field('language')->eq('php')
) ;
['$and' => [
    ['category' => ['$eq' => 'code']],
    ['language' => ['$eq' => 'php']]
]]

// Logical OR
Where::any(
    Where::field('category')->eq('code'),
    Where::field('language')->eq('php')
) ;
['$or' => [
    ['category' => ['$eq' => 'code']],
    ['language' => ['$eq' => 'php']]
]]

$collection->query(
    queryTexts: ['How do I use PHP with Chroma?'], 
    nResults: 5,
    where: Where::field('category')->eq('code')
);

$collection->query(
    queryTexts: ['How do I use PHP with Chroma?'], 
    nResults: 5,
    where: ['category' => ['$eq' => 'code']]
);

$collection->query(
    queryTexts: ['How do I use PHP with Chroma?'], 
    nResults: 5,
    where: Where::all(
        Where::field('category')->eq('code'),
        Where::field('language')->eq('php')
    )
);

$collection->query(
    queryTexts: ['How do I use PHP with Chroma?'], 
    nResults: 5,
    where: ['$and' => [
        ['category' => ['$eq' => 'code']],
        ['language' => ['$eq' => 'php']]
    ]]
);

// Substring (Contains)
Where::document()->contains('search term')
['$contains' => 'search term']

// Substring (Not Contains)
Where::document()->notContains('spam')
['$not_contains' => 'spam']

// Regex Matching
Where::document()->matches('^PHP 8\.[0-9]+')
['$regex' => '^PHP 8\.[0-9]+']

Where::document()->notMatches('deprecated')
['$not_regex' => 'deprecated']

// Logical OR
Where::any(
    Where::document()->contains('php'),
    Where::document()->contains('laravel')
)
['$or' => [
    ['document' => ['$contains' => 'php']],
    ['document' => ['$contains' => 'laravel']]
]]

// Logical AND
Where::all(
    Where::document()->contains('php'),
    Where::document()->contains('laravel')
)
['$and' => [
    ['document' => ['$contains' => 'php']],
    ['document' => ['$contains' => 'laravel']]
]]

$collection->query(
    queryTexts: ['How do I use PHP with Chroma?'], 
    nResults: 5,
    whereDocument: Where::document()->contains('php')
);

$collection->query(
    queryTexts: ['How do I use PHP with Chroma?'], 
    nResults: 5,
    whereDocument: ['$contains' => 'php']
);

$collection->query(
    queryTexts: ['How do I use PHP with Chroma?'], 
    nResults: 5,
    whereDocument: Where::any(
        Where::document()->contains('php'),
        Where::document()->contains('laravel')
    )
);

$collection->query(
    queryTexts: ['How do I use PHP with Chroma?'], 
    nResults: 5,
    whereDocument: ['$or' => [
        ['$contains' => 'php'],
        ['$contains' => 'laravel']
    ]]
);

// Update using Records
$collection->update([
    Record::make('id1')->withMetadata(['updated' => true])
]);

// Upsert using Arrays
$collection->upsert(
    ids: ['id_new'],
    documents: ['New document content'],
    metadatas: [['created' => 'now']]
);

// Delete specific items
$collection->delete(['id1', 'id2']);

// Delete all items matching a filter
$collection->delete(where: Where::field('category')->eq('outdated'));

// Delete all items matching a document content filter
$collection->delete(whereDocument: Where::document()->contains('outdated'));
bash
composer