2024-09-03 00:09:15 +01:00
|
|
|
|
|
|
|
|
"""
|
|
|
|
|
Accepts entity/vector pairs and writes them to a Qdrant store.
|
|
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
from qdrant_client import QdrantClient
|
|
|
|
|
from qdrant_client.models import PointStruct
|
|
|
|
|
from qdrant_client.models import Distance, VectorParams
|
|
|
|
|
import uuid
|
2025-08-18 20:56:09 +01:00
|
|
|
import logging
|
2024-09-03 00:09:15 +01:00
|
|
|
|
2025-04-22 20:21:38 +01:00
|
|
|
from .... base import DocumentEmbeddingsStoreService
|
2025-09-20 16:00:37 +01:00
|
|
|
from .... base import AsyncProcessor, Consumer, Producer
|
|
|
|
|
from .... base import ConsumerMetrics, ProducerMetrics
|
|
|
|
|
from .... schema import StorageManagementRequest, StorageManagementResponse, Error
|
|
|
|
|
from .... schema import vector_storage_management_topic, storage_management_response_topic
|
2024-09-03 00:09:15 +01:00
|
|
|
|
2025-08-18 20:56:09 +01:00
|
|
|
# Module logger
|
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
2025-04-22 20:21:38 +01:00
|
|
|
default_ident = "de-write"
|
2024-09-03 00:09:15 +01:00
|
|
|
|
|
|
|
|
default_store_uri = 'http://localhost:6333'
|
|
|
|
|
|
2025-04-22 20:21:38 +01:00
|
|
|
class Processor(DocumentEmbeddingsStoreService):
|
2024-09-03 00:09:15 +01:00
|
|
|
|
|
|
|
|
def __init__(self, **params):
|
|
|
|
|
|
|
|
|
|
store_uri = params.get("store_uri", default_store_uri)
|
2025-02-08 11:45:52 +00:00
|
|
|
api_key = params.get("api_key", None)
|
2024-09-03 00:09:15 +01:00
|
|
|
|
|
|
|
|
super(Processor, self).__init__(
|
|
|
|
|
**params | {
|
|
|
|
|
"store_uri": store_uri,
|
2025-02-08 11:45:52 +00:00
|
|
|
"api_key": api_key,
|
2024-09-03 00:09:15 +01:00
|
|
|
}
|
|
|
|
|
)
|
|
|
|
|
|
2025-04-22 20:21:38 +01:00
|
|
|
self.qdrant = QdrantClient(url=store_uri, api_key=api_key)
|
2024-09-03 00:09:15 +01:00
|
|
|
|
2025-09-20 16:00:37 +01:00
|
|
|
# Set up storage management if base class attributes are available
|
|
|
|
|
# (they may not be in unit tests)
|
|
|
|
|
if hasattr(self, 'id') and hasattr(self, 'taskgroup') and hasattr(self, 'pulsar_client'):
|
|
|
|
|
# Set up metrics for storage management
|
|
|
|
|
storage_request_metrics = ConsumerMetrics(
|
|
|
|
|
processor=self.id, flow=None, name="storage-request"
|
|
|
|
|
)
|
|
|
|
|
storage_response_metrics = ProducerMetrics(
|
|
|
|
|
processor=self.id, flow=None, name="storage-response"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
# Set up consumer for storage management requests
|
|
|
|
|
self.storage_request_consumer = Consumer(
|
|
|
|
|
taskgroup=self.taskgroup,
|
|
|
|
|
client=self.pulsar_client,
|
|
|
|
|
flow=None,
|
|
|
|
|
topic=vector_storage_management_topic,
|
|
|
|
|
subscriber=f"{self.id}-storage",
|
|
|
|
|
schema=StorageManagementRequest,
|
|
|
|
|
handler=self.on_storage_management,
|
|
|
|
|
metrics=storage_request_metrics,
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
# Set up producer for storage management responses
|
|
|
|
|
self.storage_response_producer = Producer(
|
|
|
|
|
client=self.pulsar_client,
|
|
|
|
|
topic=storage_management_response_topic,
|
|
|
|
|
schema=StorageManagementResponse,
|
|
|
|
|
metrics=storage_response_metrics,
|
|
|
|
|
)
|
|
|
|
|
|
2025-10-06 17:54:26 +01:00
|
|
|
async def start(self):
|
|
|
|
|
"""Start the processor and its storage management consumer"""
|
|
|
|
|
await super().start()
|
|
|
|
|
if hasattr(self, 'storage_request_consumer'):
|
|
|
|
|
await self.storage_request_consumer.start()
|
|
|
|
|
if hasattr(self, 'storage_response_producer'):
|
|
|
|
|
await self.storage_response_producer.start()
|
|
|
|
|
|
2025-04-22 20:21:38 +01:00
|
|
|
async def store_document_embeddings(self, message):
|
2024-09-03 00:09:15 +01:00
|
|
|
|
2025-10-06 17:54:26 +01:00
|
|
|
# Validate collection exists before accepting writes
|
|
|
|
|
collection = (
|
|
|
|
|
"d_" + message.metadata.user + "_" +
|
|
|
|
|
message.metadata.collection
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
if not self.qdrant.collection_exists(collection):
|
|
|
|
|
error_msg = (
|
|
|
|
|
f"Collection {message.metadata.collection} does not exist. "
|
|
|
|
|
f"Create it first with tg-set-collection."
|
|
|
|
|
)
|
|
|
|
|
logger.error(error_msg)
|
|
|
|
|
raise ValueError(error_msg)
|
|
|
|
|
|
2025-04-22 20:21:38 +01:00
|
|
|
for emb in message.chunks:
|
2025-01-04 21:51:28 +00:00
|
|
|
|
|
|
|
|
chunk = emb.chunk.decode("utf-8")
|
|
|
|
|
if chunk == "": return
|
|
|
|
|
|
|
|
|
|
for vec in emb.vectors:
|
|
|
|
|
|
2025-04-22 20:21:38 +01:00
|
|
|
self.qdrant.upsert(
|
2025-01-04 21:51:28 +00:00
|
|
|
collection_name=collection,
|
|
|
|
|
points=[
|
|
|
|
|
PointStruct(
|
|
|
|
|
id=str(uuid.uuid4()),
|
|
|
|
|
vector=vec,
|
|
|
|
|
payload={
|
|
|
|
|
"doc": chunk,
|
|
|
|
|
}
|
2024-09-03 00:09:15 +01:00
|
|
|
)
|
2025-01-04 21:51:28 +00:00
|
|
|
]
|
|
|
|
|
)
|
2024-09-03 00:09:15 +01:00
|
|
|
|
|
|
|
|
@staticmethod
|
|
|
|
|
def add_args(parser):
|
|
|
|
|
|
2025-04-22 20:21:38 +01:00
|
|
|
DocumentEmbeddingsStoreService.add_args(parser)
|
2024-09-03 00:09:15 +01:00
|
|
|
|
|
|
|
|
parser.add_argument(
|
|
|
|
|
'-t', '--store-uri',
|
|
|
|
|
default=default_store_uri,
|
2025-02-08 11:45:52 +00:00
|
|
|
help=f'Qdrant URI (default: {default_store_uri})'
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
parser.add_argument(
|
|
|
|
|
'-k', '--api-key',
|
|
|
|
|
default=None,
|
|
|
|
|
help=f'Qdrant API key (default: None)'
|
2024-09-03 00:09:15 +01:00
|
|
|
)
|
|
|
|
|
|
2025-10-06 17:54:26 +01:00
|
|
|
async def on_storage_management(self, message, consumer, flow):
|
2025-09-20 16:00:37 +01:00
|
|
|
"""Handle storage management requests"""
|
2025-10-06 17:54:26 +01:00
|
|
|
request = message.value()
|
|
|
|
|
logger.info(f"Storage management request: {request.operation} for {request.user}/{request.collection}")
|
2025-09-20 16:00:37 +01:00
|
|
|
|
|
|
|
|
try:
|
2025-10-06 17:54:26 +01:00
|
|
|
if request.operation == "create-collection":
|
|
|
|
|
await self.handle_create_collection(request)
|
|
|
|
|
elif request.operation == "delete-collection":
|
|
|
|
|
await self.handle_delete_collection(request)
|
2025-09-20 16:00:37 +01:00
|
|
|
else:
|
|
|
|
|
response = StorageManagementResponse(
|
|
|
|
|
error=Error(
|
|
|
|
|
type="invalid_operation",
|
2025-10-06 17:54:26 +01:00
|
|
|
message=f"Unknown operation: {request.operation}"
|
2025-09-20 16:00:37 +01:00
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
await self.storage_response_producer.send(response)
|
|
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
logger.error(f"Error processing storage management request: {e}", exc_info=True)
|
|
|
|
|
response = StorageManagementResponse(
|
|
|
|
|
error=Error(
|
|
|
|
|
type="processing_error",
|
|
|
|
|
message=str(e)
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
await self.storage_response_producer.send(response)
|
|
|
|
|
|
2025-10-06 17:54:26 +01:00
|
|
|
async def handle_create_collection(self, request):
|
|
|
|
|
"""Create a Qdrant collection for document embeddings"""
|
|
|
|
|
try:
|
|
|
|
|
collection_name = f"d_{request.user}_{request.collection}"
|
|
|
|
|
|
|
|
|
|
if self.qdrant.collection_exists(collection_name):
|
|
|
|
|
logger.info(f"Qdrant collection {collection_name} already exists")
|
|
|
|
|
else:
|
|
|
|
|
# Create collection with default dimension (will be recreated with correct dim on first write if needed)
|
|
|
|
|
# Using a placeholder dimension - actual dimension determined by first embedding
|
|
|
|
|
self.qdrant.create_collection(
|
|
|
|
|
collection_name=collection_name,
|
|
|
|
|
vectors_config=VectorParams(
|
|
|
|
|
size=384, # Default dimension, common for many models
|
|
|
|
|
distance=Distance.COSINE
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
logger.info(f"Created Qdrant collection: {collection_name}")
|
|
|
|
|
|
|
|
|
|
# Send success response
|
|
|
|
|
response = StorageManagementResponse(error=None)
|
|
|
|
|
await self.storage_response_producer.send(response)
|
|
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
logger.error(f"Failed to create collection: {e}", exc_info=True)
|
|
|
|
|
response = StorageManagementResponse(
|
|
|
|
|
error=Error(
|
|
|
|
|
type="creation_error",
|
|
|
|
|
message=str(e)
|
|
|
|
|
)
|
|
|
|
|
)
|
|
|
|
|
await self.storage_response_producer.send(response)
|
|
|
|
|
|
|
|
|
|
async def handle_delete_collection(self, request):
|
2025-09-20 16:00:37 +01:00
|
|
|
"""Delete the collection for document embeddings"""
|
|
|
|
|
try:
|
2025-10-06 17:54:26 +01:00
|
|
|
collection_name = f"d_{request.user}_{request.collection}"
|
2025-09-20 16:00:37 +01:00
|
|
|
|
|
|
|
|
if self.qdrant.collection_exists(collection_name):
|
|
|
|
|
self.qdrant.delete_collection(collection_name)
|
|
|
|
|
logger.info(f"Deleted Qdrant collection: {collection_name}")
|
|
|
|
|
else:
|
|
|
|
|
logger.info(f"Collection {collection_name} does not exist, nothing to delete")
|
|
|
|
|
|
|
|
|
|
# Send success response
|
|
|
|
|
response = StorageManagementResponse(
|
|
|
|
|
error=None # No error means success
|
|
|
|
|
)
|
|
|
|
|
await self.storage_response_producer.send(response)
|
2025-10-06 17:54:26 +01:00
|
|
|
logger.info(f"Successfully deleted collection {request.user}/{request.collection}")
|
2025-09-20 16:00:37 +01:00
|
|
|
|
|
|
|
|
except Exception as e:
|
|
|
|
|
logger.error(f"Failed to delete collection: {e}")
|
|
|
|
|
raise
|
|
|
|
|
|
2024-09-03 00:09:15 +01:00
|
|
|
def run():
|
|
|
|
|
|
2025-04-22 20:21:38 +01:00
|
|
|
Processor.launch(default_ident, __doc__)
|
2024-09-03 00:09:15 +01:00
|
|
|
|