""" Re-indexing Utility for Embedding Provider Transitions. Run this script after switching AI_IMAGE_PROVIDER or AI_TEXT_PROVIDER to ensure all existing vectors are compatible with the new provider. """ import asyncio from sqlalchemy import select from core.database import async_session_factory from models.ticket import Ticket from models.attachment import Attachment from core.llm import get_text_embeddings, get_image_embeddings from core.logging import get_logger logger = get_logger(__name__) async def reindex_all(): """Iterate and re-index all searchable entities.""" async with async_session_factory() as db: # 1. Re-index Tickets (Text) logger.info("Re-indexing Ticket Text Embeddings...") text_model = get_text_embeddings() ticket_stmt = select(Ticket).where(Ticket.deleted_at.is_(None)) tickets = (await db.execute(ticket_stmt)).scalars().all() for ticket in tickets: try: content = f"{ticket.title}\n\n{ticket.description}" ticket.embedding = await text_model.aembed_query(content) db.add(ticket) except Exception as e: logger.error(f"Failed to re-index ticket {ticket.id}: {e}") # 2. Re-index Attachments (Image) logger.info("Re-indexing Image Attachments...") img_model = get_image_embeddings() att_stmt = select(Attachment).where( Attachment.content_type.like("image/%"), Attachment.deleted_at.is_(None) ) attachments = (await db.execute(att_stmt)).scalars().all() for att in attachments: try: # Assuming path is locally accessible or URL is valid # Use source_url if Markdown-extracted, or storage_path img_input = att.source_url or att.storage_path att.embedding = await img_model.aembed_query(img_input) db.add(att) except Exception as e: logger.error(f"Failed to re-index attachment {att.id}: {e}") await db.commit() logger.info("Re-indexing complete.") if __name__ == "__main__": asyncio.run(reindex_all())