# 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