关于 chroma
Chroma 是面向 LLM 应用的开源嵌入数据库,可用于 RAG 和语义搜索。它支持带元数据的文档存储、相似度查询、本地持久化及服务端模式。
主要功能
- 01嵌入集合与文档存储
- 02带元数据筛选的相似度搜索
- 03本地持久化存储
- 04可配置嵌入函数
- 05支持客户端连接的服务端模式
适用场景
- 01构建 RAG 应用
- 02对文档进行语义搜索
- 03存储并检索带元数据的嵌入文档
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ kalarislabs/ research-agent-skills --skill chroma安装后在 Claude Code 中输入/chroma确认已加载。
附带文件references/integration.md
详细介绍
Chroma - 开源嵌入数据库
用于构建带记忆功能的大模型应用的 AI 原生数据库。
何时使用 Chroma
适合使用 Chroma 的场景:
- 构建 RAG(检索增强生成)应用
- 需要本地部署/可自托管的向量数据库
- 希望使用开源解决方案(Apache 2.0)
- 在笔记本中进行原型开发
- 对文档进行语义搜索
- 存储带元数据的嵌入
指标:
- 1,900+ 个分叉
- v1.3.3(稳定版,每周发布)
- Apache 2.0 许可证
可改用以下替代方案:
- Pinecone:托管云服务,自动扩缩容
- FAISS:纯相似度搜索,不支持元数据
- Weaviate:面向生产环境的 ML 原生数据库
- Qdrant:高性能,基于 Rust
快速开始
安装
# Python
pip install chromadb
# JavaScript/TypeScript
npm install chromadb @chroma-core/default-embed
基本用法(Python)
import chromadb
# Create client
client = chromadb.Client()
# Create collection
collection = client.create_collection(name="my_collection")
# Add documents
collection.add(
documents=["This is document 1", "This is document 2"],
metadatas=[{"source": "doc1"}, {"source": "doc2"}],
ids=["id1", "id2"]
)
# Query
results = collection.query(
query_texts=["document about topic"],
n_results=2
)
print(results)
核心操作
1. 创建集合
# Simple collection
collection = client.create_collection("my_docs")
# With custom embedding function
from chromadb.utils import embedding_functions
openai_ef = embedding_functions.OpenAIEmbeddingFunction(
api_key="your-key",
model_name="text-embedding-3-small"
)
collection = client.create_collection(
name="my_docs",
embedding_function=openai_ef
)
# Get existing collection
collection = client.get_collection("my_docs")
# Delete collection
client.delete_collection("my_docs")
2. 添加文档
# Add with auto-generated IDs
collection.add(
documents=["Doc 1", "Doc 2", "Doc 3"],
metadatas=[
{"source": "web", "category": "tutorial"},
{"source": "pdf", "page": 5},
{"source": "api", "timestamp": "2025-01-01"}
],
ids=["id1", "id2", "id3"]
)
# Add with custom embeddings
collection.add(
embeddings=[[0.1, 0.2, ...], [0.3, 0.4, ...]],
documents=["Doc 1", "Doc 2"],
ids=["id1", "id2"]
)
3. 查询(相似度搜索)
# Basic query
results = collection.query(
query_texts=["machine learning tutorial"],
n_results=5
)
# Query with filters
results = collection.query(
query_texts=["Python programming"],
n_results=3,
where={"source": "web"}
)
# Query with metadata filters
results = collection.query(
query_texts=["advanced topics"],
where={
"$and": [
{"category": "tutorial"},
{"difficulty": {"$gte": 3}}
]
}
)
# Access results
print(results["documents"]) # List of matching documents
print(results["metadatas"]) # Metadata for each doc
print(results["distances"]) # Similarity scores
print(results["ids"]) # Document IDs
4. 获取文档
# Get by IDs
docs = collection.get(
ids=["id1", "id2"]
)
# Get with filters
docs = collection.get(
where={"category": "tutorial"},
limit=10
)
# Get all documents
docs = collection.get()
5. 更新文档
# Update document content
collection.update(
ids=["id1"],
documents=["Updated content"],
metadatas=[{"source": "updated"}]
)
6. 删除文档
# Delete by IDs
collection.delete(ids=["id1", "id2"])
# Delete with filter
collection.delete(
where={"source": "outdated"}
)
持久化存储
# Persist to disk
client = chromadb.PersistentClient(path="./chroma_db")
collection = client.create_collection("my_docs")
collection.add(documents=["Doc 1"], ids=["id1"])
# Data persisted automatically
# Reload later with same path
client = chromadb.PersistentClient(path="./chroma_db")
collection = client.get_collection("my_docs")
嵌入函数
默认(Sentence Transformers)
# Uses sentence-transformers by default
collection = client.create_collection("my_docs")
# Default model: all-MiniLM-L6-v2
OpenAI
from chromadb.utils import embedding_functions
openai_ef = embedding_functions.OpenAIEmbeddingFunction(
api_key="your-key",
model_name="text-embedding-3-small"
)
collection = client.create_collection(
name="openai_docs",
embedding_function=openai_ef
)
HuggingFace
huggingface_ef = embedding_functions.HuggingFaceEmbeddingFunction(
api_key="your-key",
model_name="sentence-transformers/all-mpnet-base-v2"
)
collection = client.create_collection(
name="hf_docs",
embedding_function=huggingface_ef
)
自定义嵌入函数
from chromadb import Documents, EmbeddingFunction, Embeddings
class MyEmbeddingFunction(EmbeddingFunction):
def __call__(self, input: Documents) -> Embeddings:
# Your embedding logic
return embeddings
my_ef = MyEmbeddingFunction()
collection = client.create_collection(
name="custom_docs",
embedding_function=my_ef
)
元数据筛选
# Exact match
results = collection.query(
query_texts=["query"],
where={"category": "tutorial"}
)
# Comparison operators
results = collection.query(
query_texts=["query"],
where={"page": {"$gt": 10}} # $gt, $gte, $lt, $lte, $ne
)
# Logical operators
results = collection.query(
query_texts=["query"],
where={
"$and": [
{"category": "tutorial"},
{"difficulty": {"$lte": 3}}
]
} # Also: $or
)
# Contains
results = collection.query(
query_texts=["query"],
where={"tags": {"$in": ["python", "ml"]}}
)
LangChain 集成
from langchain_chroma import Chroma
from langchain_openai import OpenAIEmbeddings
from langchain.text_splitter import RecursiveCharacterTextSplitter
# Split documents
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000)
docs = text_splitter.split_documents(documents)
# Create Chroma vector store
vectorstore = Chroma.from_documents(
documents=docs,
embedding=OpenAIEmbeddings(),
persist_directory="./chroma_db"
)
# Query
results = vectorstore.similarity_search("machine learning", k=3)
# As retriever
retriever = vectorstore.as_retriever(search_kwargs={"k": 5})
LlamaIndex 集成
from llama_index.vector_stores.chroma import ChromaVectorStore
from llama_index.core import VectorStoreIndex, StorageContext
import chromadb
# Initialize Chroma
db = chromadb.PersistentClient(path="./chroma_db")
collection = db.get_or_create_collection("my_collection")
# Create vector store
vector_store = ChromaVectorStore(chroma_collection=collection)
storage_context = StorageContext.from_defaults(vector_store=vector_store)
# Create index
index = VectorStoreIndex.from_documents(
documents,
storage_context=storage_context
)
# Query
query_engine = index.as_query_engine()
response = query_engine.query("What is machine learning?")
服务端模式
# Run Chroma server
# Terminal: chroma run --path ./chroma_db --port 8000
# Connect to server
import chromadb
from chromadb.config import Settings
client = chromadb.HttpClient(
host="localhost",
port=8000,
settings=Settings(anonymized_telemetry=False)
)
# Use as normal
collection = client.get_or_create_collection("my_docs")
最佳实践
- 使用持久化客户端 - 避免重启后丢失数据
- 添加元数据 - 便于筛选和跟踪
- 批量操作 - 一次添加多篇文档
- 选择合适的嵌入模型 - 平衡速度与质量
- 使用筛选条件 - 缩小搜索范围
- 使用唯一 ID - 避免冲突
- 定期备份 - 复制 chroma_db 目录
- 监控集合大小 - 按需扩容
- 测试嵌入函数 - 确保质量
- 在生产环境中使用服务端模式 - 更适合多用户使用
性能
| 操作 | 延迟 | 说明 |
|---|---|---|
| 添加 100 篇文档 | ~1-3s | 包含嵌入 |
| 查询(前 10 条) | ~50-200ms | 取决于集合大小 |
| 元数据筛选 | ~10-50ms | 正确建立索引时速度快 |
资源
- GitHub:https://github.com/chroma-core/chroma ⭐ 24,300+
- 文档:https://docs.trychroma.com
- Discord:https://discord.gg/MMeYNTmh3x
- 版本:1.3.3+
- 许可证:Apache 2.0
Agent 操作流程
- 检查环境。 确认语料、嵌入模型和向量存储的版本,以及索引的存放位置。
- 明确输入。 根据数据或用户确认格式、标识符和参数。凡是会改变结果的值,不要猜测,应先询问。
- 先运行小规模版本。 为一小部分数据建立索引,并使用已知的问题—段落对测试检索。
- 按照上述说明和参考资料执行完整任务。
- 验证结果。 在带标签的数据集上测量 recall@k;答案只能引用检索到的段落。
- 汇报。 说明运行了什么(版本、命令、参数)、检查了什么,以及仍有哪些不确定之处。
| 如果发生这种情况 | 请这样做 |
|---|---|
| 检索返回无关内容块 | 重新调整分块方式,添加 BM25/混合搜索,或在更改生成器之前重新排序。 |
| 这些说明中的函数、标志或端点在已安装版本中不存在 | 查看已安装版本自身的文档(help()、--help、官方文档),进行调整并告知用户。切勿编造 API。 |
| 必需的输入、标识符或参数含糊不清 | 询问用户,或在运行前明确说明所采用的假设。 |
诚信规则
- 切勿捏造结果、参数、标识符、引用或统计数据。如果无法运行或验证某项内容,请如实说明。
- 答案必须来自检索到的文本;如果语料中没有答案,请说明。
- 将这里的版本特定信息视为可能已过时:请对照已安装版本的官方文档进行确认。
- 对于会产生费用、占用共享 GPU 或云配额、涉及个人或患者数据,或无法撤销的操作,执行前必须先询问。
相关技能
llamaindex:用于构建 RAG 大模型应用的数据框架。langchain:用于构建由大模型驱动、包含 Agent、链和 RAG 的应用的框架。qdrant-vector-search:用于 RAG 和语义搜索的高性能向量相似度搜索引擎。
评论
支持 Markdown