PHPackages                             codewithkyrian/chromadb-php - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Database &amp; ORM](/categories/database)
4. /
5. codewithkyrian/chromadb-php

ActiveLibrary[Database &amp; ORM](/categories/database)

codewithkyrian/chromadb-php
===========================

A PHP client for the Chroma Open Source Embedding Database

1.0.0(6mo ago)82317.9k↓50.7%14[1 issues](https://github.com/CodeWithKyrian/chromadb-php/issues)7MITPHPPHP ^8.1CI passing

Since Dec 31Pushed 6mo ago4 watchersCompare

[ Source](https://github.com/CodeWithKyrian/chromadb-php)[ Packagist](https://packagist.org/packages/codewithkyrian/chromadb-php)[ RSS](/packages/codewithkyrian-chromadb-php/feed)WikiDiscussions main Synced 1w ago

READMEChangelog (6)Dependencies (8)Versions (9)Used By (7)

ChromaDB PHP
============

[](#chromadb-php)

**A customized, framework-agnostic PHP library for interacting with [Chroma](https://github.com/chroma-core/chroma) vector database seamlessly.**

[![Total Downloads](https://camo.githubusercontent.com/43fbfb2bf9961c8fc9b2f4923d2c2d2566e60729e9335e586932c41b8e380cd5/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f636f6465776974686b797269616e2f6368726f6d6164622d7068702e737667)](https://packagist.org/packages/codewithkyrian/chromadb-php)[![Latest Version on Packagist](https://camo.githubusercontent.com/29c3a0232b31df74baac3b03f63e4eb679823040090177969d24c53ea5c4be6c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f636f6465776974686b797269616e2f6368726f6d6164622d7068702e737667)](https://packagist.org/packages/codewithkyrian/chromadb-php)[![MIT Licensed](https://camo.githubusercontent.com/5e25f857ea70d6e61023befad1d4195a9196c47ce3e73e4ef77a0d8e2e2e98f3/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d6d69742d626c75652e737667)](https://github.com/CodeWithKyrian/chromadb-php/blob/main/LICENSE)[![GitHub Tests Action Status](https://github.com/CodeWithKyrian/chromadb-php/actions/workflows/test.yml/badge.svg)](https://github.com/CodeWithKyrian/chromadb-php/actions/workflows/test.yml)

> **Note:** This package is framework-agnostic. If you use **Laravel**, check out [chromadb-laravel](https://github.com/CodeWithKyrian/chromadb-laravel) for a tailored experience.

Introduction
------------

[](#introduction)

[Chroma](https://www.trychroma.com/) is an open-source vector database designed to be fast, scalable, and reliable. ChromaDB PHP allows you to interact with Chroma servers seamlessly. It provides a fluent, type-safe API for managing collections, documents, and embeddings, making it easy to build LLM-powered applications in PHP.

Requirements
------------

[](#requirements)

- PHP 8.1 or higher
- ChromaDB 1.0 or higher

Installation
------------

[](#installation)

```
composer require codewithkyrian/chromadb-php
```

Configuration &amp; Setup
-------------------------

[](#configuration--setup)

### Running ChromaDB

[](#running-chromadb)

You need a running ChromaDB instance.

**Docker (Recommended):**

```
docker run -p 8000:8000 chromadb/chroma
```

**Chroma CLI:**

```
chroma run --path /path/to/data
```

### Connectivity

[](#connectivity)

Connect to your Chroma server. The default connection is `http://localhost:8000`.

```
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();
```

Embedding Functions
-------------------

[](#embedding-functions)

ChromaDB uses embedding functions to convert text into vectors. You can define which function a collection uses upon creation.

Embedding functions are linked to a collection and used when you call `add`, `update`, `upsert` or `query`. If you add documents *without* embeddings, it is used to generate them automatically. If you query using text, it is used to convert your query text into a vector for search.

The library provides lightweight wrappers around popular embedding providers for ease of use:

- `OpenAIEmbeddingFunction`
- `JinaEmbeddingFunction`
- `HuggingFaceEmbeddingServerFunction`
- `OllamaEmbeddingFunction`
- `MistralAIEmbeddingFunction`

Example:

```
use Codewithkyrian\ChromaDB\Embeddings\OpenAIEmbeddingFunction;

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

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

### Custom Functions

[](#custom-functions)

You can create your own embedding function by implementing `Codewithkyrian\ChromaDB\Embeddings\EmbeddingFunction`.

```
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, ...], ...];
    }
};
```

Collections
-----------

[](#collections)

Collections are where you store and categorize your embeddings and documents. All operations are performed on a specific collection.

```
// 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');
```

Adding Data
-----------

[](#adding-data)

You can add items to a collection using the structured `Record` class or raw arrays. Both methods represent the same data:

- **IDs** (Required): Unique string identifier.
- **Embeddings**: Vector representation (float array).
- **Documents**: Raw text content.
- **Metadatas**: Key-value pairs for filtering.

### Using Arrays

[](#using-arrays)

You can pass a parallel arrays of IDs, embeddings, metadatas, etc. This is useful for bulk operations.

```
$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]
    ]
);
```

### Using Records (Fluent API)

[](#using-records-fluent-api)

The `Record` class provides a fluent interface for building items. It mirrors the array structure but in an object-oriented way.

```
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]
    ),
]);
```

If you provide `documents` but *omit* `embeddings`, Chroma uses the collection's **Embedding Function** to generate them. This is useful if you have an external embedding function or if you want to manually control the embedding process. When providing just embeddings and not documents, it's assumed you're storing the documents elsewhere and associating the provided embeddings with those documents using the `ids` or any other metadata.

> If the supplied embeddings are not the same dimension as the embeddings already indexed in the collection, an exception will be raised.

Retrieval (`get` and `peek`)
----------------------------

[](#retrieval-get-and-peek)

Retrieve specific items by ID or filtered metadata without generating embeddings.

### Get

[](#get)

Fetch specific items.

```
use Codewithkyrian\ChromaDB\Types\Includes;

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

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

// Fetch items as Record objects
$records = $items->asRecords();
```

### Peek

[](#peek)

Preview the first `n` items in the collection.

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

### Specifying Return Data (`include`)

[](#specifying-return-data-include)

Both `get` and `query` allow you to specify what data to return using the `include` parameter.

```
use Codewithkyrian\ChromaDB\Types\Includes;

$collection->get(
    ids: ['id1'],
    include: [
        Includes::Documents, // Return the document text
        Includes::Metadatas, // Return the metadata
        Includes::Embeddings // Return the vector
    ]
);
```

> **Note:** `Includes::Distances` is only available when **Querying**, not when using `get()`.

Querying (Vector Search)
------------------------

[](#querying-vector-search)

Querying is about finding items *semantically similar* to your input. Chroma performs a vector search to find the nearest neighbors. ChromaDB-PHP also provides a powerful, fluent query builder for filtering by metadata and document content.

### Query by Text

[](#query-by-text)

Provide text strings. Chroma embeds them using the collection's Embedding Function and finds the nearest neighbors.

```
$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();
```

### Query by Embeddings

[](#query-by-embeddings)

Provide raw vectors. Useful if you compute embeddings externally.

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

### Specifying Return Data (`include`)

[](#specifying-return-data-include-1)

By default, queries return IDs, Embeddings, Metadatas, and Distances. You can customize this using the `Includes` enum to optimize performance.

```
use Codewithkyrian\ChromaDB\Types\Includes;

$collection->query(
    queryTexts: ['How do I use PHP with Chroma?'],
    nResults: 5,
    include: [
        Includes::Documents, // Return the actual text content
        Includes::Distances // Return the similarity score
    ]
);
```

### Metadata Filtering (`where`)

[](#metadata-filtering-where)

You can filter search results based on metadata of the items. The library provides a fluent **Builder** for safety, but also supports raw arrays.

### Supported Comparisons

[](#supported-comparisons)

```
// 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']]
]]
```

#### Usage

[](#usage)

```
$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']]
    ]]
);
```

### Full Text Search (`whereDocument`)

[](#full-text-search-wheredocument)

Used to filter based on the text content of the document itself. This supports **substring matching** and **Regex**. You can also use the fluent builder or array syntax.

#### Supported Comparisons

[](#supported-comparisons-1)

```
// 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']]
]]
```

#### Usage

[](#usage-1)

```
$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']
    ]]
);
```

Updating Data
-------------

[](#updating-data)

Use `update` to modify existing items (fails if ID missing) or `upsert` to update-or-create. Just like adding, you can either pass an array of records, or a parallel array of IDs, documents, and metadatas.

```
// 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']]
);
```

Deleting Data
-------------

[](#deleting-data)

Delete by IDs or by filter.

```
// 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'));
```

Examples
--------

[](#examples)

- **[`basic-usage`](examples/basic-usage)** - Simple example demonstrating basic operations: connecting, adding documents, and querying
- **[`document-chunking-cloud`](examples/document-chunking-cloud)** - Document chunking, embedding, and storage in Chroma Cloud with semantic search

Testing
-------

[](#testing)

Run the test suite using Pest.

```
composer test
```

License
-------

[](#license)

MIT License. See [LICENSE](LICENSE) for more information.

###  Health Score

53

—

FairBetter than 96% of packages

Maintenance68

Regular maintenance activity

Popularity50

Moderate usage in the ecosystem

Community26

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 84.8% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~141 days

Recently: every ~161 days

Total

6

Last Release

185d ago

Major Versions

0.4.0 → 1.0.02025-12-06

### Community

Maintainers

![](https://www.gravatar.com/avatar/146c2eb02350558d165083e0018f5377f15f0e71493439c93ee60e7c7ac97fc1?d=identicon)[CodeWithKyrian](/maintainers/CodeWithKyrian)

---

Top Contributors

[![CodeWithKyrian](https://avatars.githubusercontent.com/u/48791154?v=4)](https://github.com/CodeWithKyrian "CodeWithKyrian (56 commits)")[![BlackyDrum](https://avatars.githubusercontent.com/u/111639941?v=4)](https://github.com/BlackyDrum "BlackyDrum (7 commits)")[![chr-hertel](https://avatars.githubusercontent.com/u/2852185?v=4)](https://github.com/chr-hertel "chr-hertel (2 commits)")[![OliverIost](https://avatars.githubusercontent.com/u/12759510?v=4)](https://github.com/OliverIost "OliverIost (1 commits)")

---

Tags

phpsearchdatabasesemanticvectorsopen-sourceembeddingchromachromadb

###  Code Quality

TestsPest

### Embed Badge

![Health badge](/badges/codewithkyrian-chromadb-php/health.svg)

```
[![Health](https://phpackages.com/badges/codewithkyrian-chromadb-php/health.svg)](https://phpackages.com/packages/codewithkyrian-chromadb-php)
```

###  Alternatives

[codewithkyrian/chromadb-laravel

ChromaDB Laravel is a Laravel client for the Chroma Open Source Embedding Database

144.1k](/packages/codewithkyrian-chromadb-laravel)[telnyx/telnyx-php

Official Telnyx PHP SDK — APIs for Voice, SMS, MMS, WhatsApp, Fax, SIP Trunking, Wireless IoT, Call Control, and more. Build global communications on Telnyx's private carrier-grade network.

35729.6k2](/packages/telnyx-telnyx-php)[kreait/firebase-php

Firebase Admin SDK

2.5k42.7M83](/packages/kreait-firebase-php)[tempest/framework

The PHP framework that gets out of your way.

2.2k31.1k11](/packages/tempest-framework)[flow-php/flow

PHP ETL - Extract Transform Load - Data processing framework

84735.1k](/packages/flow-php-flow)[laudis/neo4j-php-client

Neo4j-PHP-Client is the most advanced PHP Client for Neo4j

185671.3k41](/packages/laudis-neo4j-php-client)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
