Provides Chroma Python client patterns — collection creation and configuration, add/upsert/query, metadata and document filtering syntax, and embedding function integration. Use when the user asks to "set up ChromaDB", "create a Chroma collection", "add embeddings to ChromaDB", "query ChromaDB", "search vectors", "semantic search with ChromaDB", "filter ChromaDB results", "ChromaDB metadata filtering", "configure Chroma", "use ChromaDB persistent client", "delete from ChromaDB", or when writing any code that interacts with the chromadb Python package. Does not cover the JavaScript client, Chroma Cloud, choosing an embedding model, or general RAG architecture.
72
90%
Does it follow best practices?
Run evals on this skill
Adds up to 20 points to the overall score
Passed
No findings from the security scan
This skill covers the Chroma Python client API (the chromadb package) for creating collections, storing records with embeddings, and querying with semantic search and metadata filtering.
import chromadb
client = chromadb.Client()Data is lost when the process exits. Use for testing and prototyping.
client = chromadb.PersistentClient(path="./chroma_data")Data is saved to disk at the specified path. Use for local applications and development.
client = chromadb.HttpClient(host="localhost", port=8000)Connects to a standalone Chroma server. Use for production deployments.
collection = client.get_or_create_collection(
name="my_collection",
embedding_function=embedding_fn,
configuration={"hnsw": {"space": "cosine"}},
)get_or_create_collection — idempotent; creates if absent, returns existing if present. configuration applies only on creation: against an existing collection it is ignored silently, so the returned collection keeps whatever space it was built with. Read collection.configuration["hnsw"] back if the metric matters, and recreate the collection to change it.create_collection — raises if the collection already exists.get_collection — raises if the collection does not exist.client.list_collections() # list all collections
client.delete_collection("my_collection") # delete by name
collection.count() # number of recordscollection.add(
ids=["id1", "id2", "id3"],
documents=["First document", "Second document", "Third document"],
metadatas=[
{"source": "web", "year": 2024},
{"source": "api", "year": 2024},
{"source": "manual", "year": 2023},
],
)ids — required, must be unique strings. An ID that already exists is skipped silently: no exception, no warning, and the stored record is left untouched. Use upsert whenever the data may already be indexed.documents — raw text; Chroma uses the collection's embedding function to generate embeddings.metadatas — optional dict per record for filtering.collection.add(
ids=["id1", "id2"],
embeddings=[[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]],
metadatas=[{"source": "precomputed"}, {"source": "precomputed"}],
documents=["doc one", "doc two"], # optional when embeddings provided
)collection.upsert(
ids=["id1", "id2", "id3"],
documents=["new content 1", "new content 2", "new content 3"],
metadatas=[{"version": 2}, {"version": 2}, {"version": 2}],
)Inserts records if the ID does not exist; updates if it does. Prefer upsert over add when re-indexing data that may already exist.
results = collection.query(
query_texts=["search phrase"],
n_results=5,
)Returns a dict that always has the keys ids, embeddings, documents, uris, included, data, metadatas, distances. Fields not requested via include are present but set to None; results["included"] lists which fields were populated. Each populated value is a list of lists (one inner list per query). Lower distance = more similar.
Important: query() returns nested lists, while get() returns flat lists. This is a common source of bugs:
# query() — nested: results["ids"] == [["id1", "id2"]]
# get() — flat: results["ids"] == ["id1", "id2"]results = collection.query(
query_embeddings=[[0.1, 0.2, 0.3]],
n_results=10,
)includeresults = collection.query(
query_texts=["search phrase"],
n_results=5,
include=["documents", "metadatas", "distances"],
)Valid include values: "documents", "metadatas", "distances", "embeddings". The Include type also accepts "uris" and "data", which only apply to multimodal collections (images, audio) and are out of this skill's text-only scope.
include does not remove keys from the result — every key is always present, and unrequested ones are None. Check results["included"] to learn what was populated; "embeddings" in results is always True and tells you nothing.
results = collection.get(
ids=["id1", "id2"],
include=["documents", "metadatas"],
)results = collection.get(
where={"source": "web"},
include=["documents", "metadatas"],
)Filters are applied via where (metadata) and where_document (text content) parameters on both query and get.
| Operator | Type | Example |
|---|---|---|
$eq | Equality | {"status": {"$eq": "active"}} |
$ne | Inequality | {"status": {"$ne": "archived"}} |
$gt | Greater than | {"price": {"$gt": 100}} |
$gte | Greater or equal | {"rating": {"$gte": 4.5}} |
$lt | Less than | {"price": {"$lt": 50}} |
$lte | Less or equal | {"count": {"$lte": 10}} |
$in | In list | {"category": {"$in": ["a", "b"]}} |
$nin | Not in list | {"tag": {"$nin": ["spam"]}} |
$contains | Array contains | {"tags": {"$contains": "python"}} |
$not_contains | Array excludes | {"tags": {"$not_contains": "draft"}} |
Shorthand: {"key": "value"} is equivalent to {"key": {"$eq": "value"}}.
# AND
where={"$and": [{"category": "electronics"}, {"price": {"$gte": 500}}]}
# OR
where={"$or": [{"category": "electronics"}, {"category": "wearables"}]}results = collection.query(
query_texts=["search"],
where_document={"$contains": "specific phrase"},
)For complete filter operator details and advanced patterns, consult references/api-reference.md.
Chroma supports pluggable embedding functions. Set the embedding function when creating a collection — it is used automatically for add, update, upsert, and query operations.
from chromadb.utils.embedding_functions import SentenceTransformerEmbeddingFunction
ef = SentenceTransformerEmbeddingFunction(model_name="all-MiniLM-L6-v2")
collection = client.get_or_create_collection("my_col", embedding_function=ef)from chromadb.utils.embedding_functions import OpenAIEmbeddingFunction
ef = OpenAIEmbeddingFunction(model_name="text-embedding-3-small")
collection = client.create_collection("my_col", embedding_function=ef)Requires the openai package and an API key. The key is read from
CHROMA_OPENAI_API_KEY — note the CHROMA_ prefix, which is the default for
every hosted provider wrapper (CHROMA_COHERE_API_KEY,
CHROMA_HUGGINGFACE_API_KEY, …). The unprefixed OPENAI_API_KEY is still
honoured and takes precedence when set, even over an explicit
api_key_env_var. To read from somewhere else:
ef = OpenAIEmbeddingFunction(
model_name="text-embedding-3-small",
api_key_env_var="MY_OPENAI_KEY", # persisted with the collection
)Passing api_key="sk-…" inline also works but raises a DeprecationWarning
and is deliberately not stored in the collection configuration, so the key
is lost the next time the collection is opened. Prefer an environment variable.
If no embedding_function is specified, Chroma uses its built-in default (all-MiniLM-L6-v2 via ONNX). This is suitable for prototyping but should be replaced with a purpose-chosen model for production.
Set via the space key of the configuration argument at creation time:
| Metric | Value | Use case |
|---|---|---|
| Cosine | "cosine" | Normalized embeddings (most common) |
| L2 (Euclidean) | "l2" | Default; raw distance |
| Inner product | "ip" | Pre-normalized, dot-product similarity |
collection = client.create_collection(
name="my_col",
configuration={"hnsw": {"space": "cosine"}},
)The pre-1.x form metadata={"hnsw:space": "cosine"} still works and produces
the same configuration. The metric cannot be changed afterwards — modify
rejects it, so switching metrics means recreating the collection.
For HNSW tuning parameters and advanced configuration, consult references/patterns.md.
collection.update(
ids=["id1"],
documents=["updated content"],
metadatas=[{"version": 3}],
)Only provided fields are updated. Omitted fields remain unchanged.
collection.delete(ids=["id1", "id2"])
collection.delete(where={"status": "archived"})
collection.delete(where_document={"$contains": "deprecated"})sample = collection.peek(limit=5) # returns a sample of records (default 10)Useful for inspecting collection contents during development.
| Symptom | Cause | Fix |
|---|---|---|
add silently does nothing | The ID already exists — the write is dropped with no error and no warning | Use upsert when re-indexing; count() will not move and the stored record keeps its old content |
| Dimension mismatch | Embedding size differs from collection | Ensure consistent embedding model |
ValueError on delete | No criteria given | Provide ids, where, or where_document |
ValueError: Embedding function <name> not found on the first add, query or collection.configuration access after get_collection (which itself returns normally) | A custom embedding function's class is not registered in this process | Import the module that defines it and decorate the class with @register_embedding_function |
Collection expecting embedding with dimension of N, got 384 after reopening | Collection was created with a legacy custom embedding function, so Chroma fell back to the default ONNX model | Give the function name() / get_config() / build_from_config(), or pass it to get_collection every time |
Chroma stores the configuration of the embedding function with the
collection, so get_collection rebuilds it automatically and passing
embedding_function again is optional. This works for the built-in wrappers
(OpenAI, SentenceTransformer, Cohere, …) and for custom functions that
implement name(), get_config() and build_from_config() — those are saved
as {"type": "known", "name": …, "config": {…}}.
A custom function that implements only __call__ is saved as
{"type": "legacy"} and cannot be rebuilt. Reopening that collection silently
falls back to the default ONNX model, which is where the wrong-results and
dimension-mismatch failures come from. Either upgrade the function (see
references/api-reference.md) or pass it on every get_collection call.
For detailed API documentation and advanced patterns, consult:
references/api-reference.md — Complete method signatures, all filter operators with examples, include options, result structurereferences/patterns.md — Batch ingestion, metadata schema design, HNSW tuning, collection lifecycle, common query patterns, error handlingprovectus/awos-recruitment
ce6a3ea
If you maintain this skill, you can claim it as your own. Once claimed, you can manage eval scenarios, bundle related skills, attach documentation or rules, and ensure cross-agent compatibility.