Spaces:
No application file
No application file
File size: 2,162 Bytes
9e8f2ae | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | # app/qdrant_client.py
from qdrant_client import QdrantClient
from qdrant_client.models import Distance, VectorParams
from app.config import settings
# OpenAI text-embedding-3-small produces 1536-dimensional vectors
EMBEDDING_DIMENSION = 1536
# Initialize Qdrant client
qdrant_client = QdrantClient(
url=settings.QDRANT_URL,
api_key=settings.QDRANT_API_KEY,
)
COLLECTION_NAME = "book_embeddings"
def init_qdrant_collection(recreate: bool = False):
"""Initialize Qdrant collection if it doesn't exist (or recreate if flagged)"""
try:
# Check if collection exists
collections = qdrant_client.get_collections().collections
collection_names = [col.name for col in collections]
if recreate and COLLECTION_NAME in collection_names:
qdrant_client.delete_collection(collection_name=COLLECTION_NAME)
print(f"Deleted existing Qdrant collection: {COLLECTION_NAME} (for dimension fix)")
if COLLECTION_NAME not in collection_names:
# Create collection with vector configuration
qdrant_client.create_collection(
collection_name=COLLECTION_NAME,
vectors_config=VectorParams(
size=EMBEDDING_DIMENSION, # OpenAI text-embedding-3-small dimension
distance=Distance.COSINE
)
)
print(f"Created Qdrant collection: {COLLECTION_NAME}")
else:
# Verify dimensions match (optional safety check)
info = qdrant_client.get_collection(COLLECTION_NAME)
if info.config.params.vectors.size != EMBEDDING_DIMENSION:
raise ValueError(
f"Collection {COLLECTION_NAME} has wrong size {info.config.params.vectors.size}; "
f"expected {EMBEDDING_DIMENSION}. Recreate with flag."
)
print(f"Qdrant collection already exists with correct dims: {COLLECTION_NAME}")
except Exception as e:
print(f"Warning: Could not initialize Qdrant collection: {e}")
def get_qdrant_client():
"""Dependency to get Qdrant client"""
return qdrant_client
|