Chroma Server with FastAPI
Here's a Python script to run a Chroma server using FastAPI:
from chromadb import Client
from chromadb.config import Settings
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
import uvicorn
import logging
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Configure Chroma settings
settings = Settings(
chroma_server_host="0.0.0.0",
chroma_server_http_port=8000,
persist_directory="./chroma_data"
)
# Initialize FastAPI app
app = FastAPI(title="Chroma Vector Database")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Initialize Chroma client
client = Client(settings)
# Define request/response models
class CreateCollectionRequest(BaseModel):
name: str
metadata: dict = {}
class AddEmbeddingsRequest(BaseModel):
ids: list[str]
embeddings: list[list[float]]
metadatas: list[dict] = []
documents: list[str] = []
class QueryRequest(BaseModel):
query_embeddings: list[list[float]]
n_results: int = 10
# API Endpoints
@app.get("/health")
def health_check():
return {"status": "healthy"}
@app.post("/collections")
def create_collection(request: CreateCollectionRequest):
try:
collection = client.create_collection(
name=request.name,
metadata=request.metadata
)
return {"collection": collection.name}
except Exception as e:
logger.error(f"Error creating collection: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.post("/collections/{collection_name}/add")
def add_embeddings(collection_name: str, request: AddEmbeddingsRequest):
try:
collection = client.get_collection(name=collection_name)
collection.add(
ids=request.ids,
embeddings=request.embeddings,
metadatas=request.metadatas,
documents=request.documents
)
return {"status": "success"}
except Exception as e:
logger.error(f"Error adding embeddings: {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.post("/collections/{collection_name}/query")
def query_embeddings(collection_name: str, request: QueryRequest):
try:
collection = client.get_collection(name=collection_name)
results = collection.query(
query_embeddings=request.query_embeddings,
n_results=request.n_results
)
return results
except Exception as e:
logger.error(f"Error querying embeddings: {e}")
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
uvicorn.run(
"chroma_server:app",
host="0.0.0.0",
port=8000,
reload=True
)
Key Features:
- Uses FastAPI for building the REST API
- Chroma client configured with local persistence
- CORS enabled for cross-origin requests
- Basic error handling and logging
- API endpoints for:
- Health check
- Creating collections
- Adding embeddings
- Querying embeddings
Running the Server:
- Save this script as
chroma_server.py
- Install required packages:
pip install chromadb fastapi uvicorn
- Run the server:
python chroma_server.py
- The server will be available at
http://localhost:8000
Testing the API:
You can test the API using tools like curl or Postman. For example:
# Create collection
curl -X POST \
http://localhost:8000/collections \
-H 'Content-Type: application/json' \
-d '{"name": "test_collection"}'
# Add embeddings
curl -X POST \
http://localhost:8000/collections/test_collection/add \
-H 'Content-Type: application/json' \
-d '{"ids": ["id1", "id2"], "embeddings": [[0.1, 0.2], [0.3, 0.4]]}'
# Query embeddings
curl -X POST \
http://localhost:8000/collections/test_collection/query \
-H 'Content-Type: application/json' \
-d '{"query_embeddings": [[0.1, 0.2]], "n_results": 5}'