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