from sqlmodel import select, func from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy import text from typing import List, Dict, Any, Optional from uuid import UUID, uuid4 from datetime import datetime from app.models.knowledge import KnowledgeBase from app.services.embeddings import get_embedding_service from app.core.logging import get_logger logger = get_logger(__name__) # OpenAI text-embedding-3-small has 8192 token limit # Multilingual text (Russian) uses ~2 tokens per char CHUNK_SIZE = 3000 # ~6000 tokens per chunk - safe margin CHUNK_OVERLAP = 300 # Overlap between chunks for context continuity def chunk_text(text: str, chunk_size: int = CHUNK_SIZE, overlap: int = CHUNK_OVERLAP) -> List[str]: """ Split large text into overlapping chunks for embedding. Args: text: Text to split chunk_size: Max size of each chunk in characters overlap: Overlap between consecutive chunks Returns: List of text chunks """ if len(text) <= chunk_size: return [text] chunks = [] start = 0 while start < len(text): end = start + chunk_size # Try to break at sentence or paragraph boundary if end < len(text): # Look for sentence ending within last 200 chars for sep in ['\n\n', '\n', '. ', '! ', '? ']: last_sep = text[max(start, end - 200):end].rfind(sep) if last_sep != -1: end = max(start, end - 200) + last_sep + len(sep) break chunk = text[start:end].strip() if chunk: chunks.append(chunk) # Move start with overlap start = end - overlap if end < len(text) else len(text) return chunks class VectorStoreService: """Service for managing vector embeddings and semantic search.""" def __init__(self): self.embedding_service = get_embedding_service() async def add_knowledge( self, session: AsyncSession, tenant_id: UUID, content: str, source_type: str = "manual", source_file: Optional[str] = None, category: Optional[str] = None, tags: Optional[str] = None ) -> KnowledgeBase: """ Add knowledge to the vector store. Auto-chunks large texts into multiple entries. Args: session: Database session tenant_id: Tenant UUID (CRITICAL for multitenancy) content: Text content to store source_type: Type of source (manual, pdf, website, api) source_file: Optional source file name category: Optional category tags: Optional comma-separated tags Returns: Created KnowledgeBase entry (first one if chunked) """ # Auto-chunk large texts chunks = chunk_text(content) if len(chunks) > 1: # Multiple chunks - use batch add entries = await self.add_knowledge_batch( session=session, tenant_id=tenant_id, chunks=chunks, source_type=source_type, source_file=source_file, category=category ) return entries[0] if entries else None # Single chunk - normal add embedding_vector = self.embedding_service.embed_text(content) # Convert to pgvector format (string representation) embedding_str = str(embedding_vector) # Use raw SQL to insert with proper vector casting knowledge_id = uuid4() now = datetime.utcnow() query = text(""" INSERT INTO knowledge_base (id, tenant_id, content_chunk, embedding, source_type, source_file, source_url, category, tags, is_active, created_at, updated_at) VALUES (CAST(:id AS uuid), CAST(:tenant_id AS uuid), :content_chunk, CAST(:embedding AS vector), :source_type, :source_file, :source_url, :category, :tags, :is_active, :created_at, :updated_at) """) await session.execute(query, { "id": str(knowledge_id), "tenant_id": str(tenant_id), "content_chunk": content, "embedding": embedding_str, "source_type": source_type, "source_file": source_file, "source_url": None, "category": category, "tags": tags, "is_active": True, "created_at": now, "updated_at": now }) await session.commit() # Fetch and return the created entry result = await session.execute( select(KnowledgeBase).where(KnowledgeBase.id == knowledge_id) ) knowledge = result.scalar_one() return knowledge async def add_knowledge_batch( self, session: AsyncSession, tenant_id: UUID, chunks: List[str], source_type: str = "manual", source_file: Optional[str] = None, category: Optional[str] = None ) -> List[KnowledgeBase]: """ Add multiple knowledge chunks efficiently. Args: session: Database session tenant_id: Tenant UUID chunks: List of text chunks source_type: Type of source source_file: Optional source file category: Optional category Returns: List of created KnowledgeBase entries """ # Generate embeddings in batch (faster) embeddings_vectors = self.embedding_service.embed_batch(chunks) logger.info(f"📥 Created {len(embeddings_vectors)} embeddings for tenant {tenant_id}, source: {source_file}") # Insert using raw SQL with vector casting knowledge_ids = [] now = datetime.utcnow() query = text(""" INSERT INTO knowledge_base (id, tenant_id, content_chunk, embedding, source_type, source_file, source_url, category, tags, is_active, created_at, updated_at) VALUES (CAST(:id AS uuid), CAST(:tenant_id AS uuid), :content_chunk, CAST(:embedding AS vector), :source_type, :source_file, :source_url, :category, :tags, :is_active, :created_at, :updated_at) """) for content, embedding_vector in zip(chunks, embeddings_vectors): knowledge_id = uuid4() knowledge_ids.append(knowledge_id) embedding_str = str(embedding_vector) await session.execute(query, { "id": str(knowledge_id), "tenant_id": str(tenant_id), "content_chunk": content, "embedding": embedding_str, "source_type": source_type, "source_file": source_file, "source_url": None, "category": category, "tags": None, "is_active": True, "created_at": now, "updated_at": now }) await session.commit() # Fetch and return created entries result = await session.execute( select(KnowledgeBase).where(KnowledgeBase.id.in_(knowledge_ids)) ) knowledge_entries = list(result.scalars().all()) return knowledge_entries async def semantic_search( self, session: AsyncSession, tenant_id: UUID, query: str, top_k: int = 5, category: Optional[str] = None, min_similarity: float = 0.0 # Removed filter - show all results sorted by relevance ) -> List[Dict[str, Any]]: """ Search knowledge base using semantic similarity. Args: session: Database session tenant_id: Tenant UUID (CRITICAL - only search within tenant) query: Search query text top_k: Number of results to return category: Optional filter by category min_similarity: Minimum cosine similarity threshold Returns: List of relevant knowledge chunks with similarity scores """ # Generate query embedding query_embedding = self.embedding_service.embed_text(query) query_embedding_str = str(query_embedding) # Build SQL query with vector similarity using raw SQL # Using pgvector's cosine distance operator (<=>) sql = text(""" SELECT id, content_chunk, source_type, source_file, category, tags, 1 - (embedding <=> CAST(:query_embedding AS vector)) as similarity FROM knowledge_base WHERE tenant_id = CAST(:tenant_id AS uuid) AND is_active = true {:category_filter} ORDER BY embedding <=> CAST(:query_embedding AS vector) LIMIT :top_k """) # Add category filter if provided if category: sql = text(str(sql).replace( "{:category_filter}", "AND category = :category" )) params = { "query_embedding": query_embedding_str, "tenant_id": str(tenant_id), "category": category, "top_k": top_k } else: sql = text(str(sql).replace("{:category_filter}", "")) params = { "query_embedding": query_embedding_str, "tenant_id": str(tenant_id), "top_k": top_k } result = await session.execute(sql, params) rows = result.fetchall() logger.info(f"🔍 Semantic search for '{query[:30]}...' found {len(rows)} raw results for tenant {tenant_id}") # Format results results = [] for row in rows: similarity = float(row.similarity) if similarity >= min_similarity: results.append({ "id": str(row.id), "content": row.content_chunk, "similarity": similarity, "category": row.category, "source_type": row.source_type, "source_file": row.source_file, "tags": row.tags }) logger.info(f"🔍 After min_similarity filter: {len(results)} results (threshold: {min_similarity})") return results async def get_context_for_query( self, session: AsyncSession, tenant_id: UUID, query: str, max_tokens: int = 2000 ) -> str: """ Get relevant context from knowledge base for a query. Combines multiple chunks into a single context string. Args: session: Database session tenant_id: Tenant UUID query: User query max_tokens: Approximate max tokens (chars/4) Returns: Combined context string """ results = await self.semantic_search( session=session, tenant_id=tenant_id, query=query, top_k=10, min_similarity=0.6 ) if not results: return "No relevant information found in knowledge base." # Combine chunks up to max_tokens context_parts = [] total_chars = 0 max_chars = max_tokens * 4 # Rough approximation for result in results: content = result["content"] if total_chars + len(content) > max_chars: break context_parts.append(f"[Relevance: {result['similarity']:.2f}] {content}") total_chars += len(content) return "\n\n".join(context_parts) def get_vector_store() -> VectorStoreService: """Get vector store service instance.""" return VectorStoreService()