Spaces:
Running

File size: 12,261 Bytes
cd61bf7
 
 
 
 
 
 
 
 
6c54d29
 
 
cd61bf7
bb6cb4c
 
 
 
bdedbed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bdedbed
cd61bf7
 
 
 
 
 
 
 
 
 
 
bdedbed
cd61bf7
bdedbed
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53b9e11
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
df070a4
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c54d29
 
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c54d29
 
cd61bf7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
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()