Certainly! Below is a Python script to run a Chroma server using FastAPI without ClickHouse. This script will allow you to create and manage collections, add embeddings, and query them.
chroma_server.py
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from typing import List, Dict, Union
import numpy as np
from collections import defaultdict
app = FastAPI(title="Chroma Vector Database")
# Middleware to allow CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# In-memory storage for collections and embeddings
collections = defaultdict(list)
@app.get("/")
def read_root():
return {"status": "Chroma server running"}
@app.get("/api/v1/health")
def health_check():
return {"status": "healthy"}
@app.post("/api/v1/collections")
def create_collection(collection_name: str):
if collection_name in collections:
raise HTTPException(status_code=400, detail="Collection already exists")
collections[collection_name] = []
return {"status": "collection created", "collection_name": collection_name}
@app.delete("/api/v1/collections/{collection_name}")
def delete_collection(collection_name: str):
if collection_name not in collections:
raise HTTPException(status_code=404, detail="Collection not found")
del collections[collection_name]
return {"status": "collection deleted", "collection_name": collection_name}
@app.post("/api/v1/collections/{collection_name}/add")
def add_embeddings(collection_name: str, embeddings: List[List[float]], ids: Union[List[str], None] = None):
if collection_name not in collections:
raise HTTPException(status_code=404, detail="Collection not found")
if ids is None:
ids = [str(i) for i in range(len(embeddings))]
if len(embeddings) != len(ids):
raise HTTPException(status_code=400, detail="Number of embeddings and ids must match")
for embedding, id in zip(embeddings, ids):
collections[collection_name].append({"id": id, "embedding": np.array(embedding)})
return {"status": "embeddings added", "count": len(embeddings)}
@app.post("/api/v1/collections/{collection_name}/query")
def query_embeddings(collection_name: str, query_embeddings: List[List[float]], top_k: int = 10):
if collection_name not in collections:
raise HTTPException(status_code=404, detail="Collection not found")
results = []
for query_embedding in query_embeddings:
query_embedding = np.array(query_embedding)
distances = []
for item in collections[collection_name]:
distance = np.linalg.norm(query_embedding - item["embedding"])
distances.append((item["id"], distance))
distances.sort(key=lambda x: x[1])
top_results = distances[:top_k]
results.append(top_results)
return {"results": results}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
Explanation
-
FastAPI Setup:
FastAPI is used to create the API.
CORSMiddleware is added to allow cross-origin requests.
-
In-Memory Storage:
collections is a dictionary where each key is a collection name and the value is a list of embeddings.
-
Endpoints:
- Root Endpoint: Returns a simple message indicating the server is running.
- Health Check: Returns a message indicating the server is healthy.
- Create Collection: Creates a new collection. If the collection already exists, it returns an error.
- Delete Collection: Deletes a collection. If the collection does not exist, it returns an error.
- Add Embeddings: Adds embeddings to a collection. If the collection does not exist, it returns an error. It also allows for optional IDs for each embedding.
- Query Embeddings: Queries the embeddings in a collection. It returns the top
k closest embeddings for each query embedding.
-
Running the Server:
- The server is run using
uvicorn on 0.0.0.0 (all interfaces) and port 8000.
Running the Script
To run the script, execute the following command in your terminal:
python chroma_server.py
This will start the FastAPI server, and you can access it at http://localhost:8000.
Testing the API
You can use tools like curl or Postman to test the API. Here are some example requests:
-
Create Collection:
curl -X POST "http://localhost:8000/api/v1/collections" -H "Content-Type: application/json" -d '{"collection_name": "test_collection"}'
-
Add Embeddings:
curl -X POST "http://localhost:8000/api/v1/collections/test_collection/add" -H "Content-Type: application/json" -d '{"embeddings": [[0.1, 0.2, 0.3], [0.4, 0.5, 0.6]]}'
-
Query Embeddings:
curl -X POST "http://localhost:8000/api/v1/collections/test_collection/query" -H "Content-Type: application/json" -d '{"query_embeddings": [[0.1, 0.2, 0.3]], "top_k": 2}'