File size: 6,282 Bytes
1813edc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Qdrant Manager - Vector database client for RAG persistence and retrieval
Manages collections, embeddings, and search operations
"""

from qdrant_client import QdrantClient
from qdrant_client.models import Distance, VectorParams, PointStruct
from typing import List, Dict, Any, Optional
from uuid import uuid4
from backend.config import settings


class QdrantManager:
    """Singleton for managing Qdrant vector database"""
    
    _instance = None
    _client = None
    
    def __new__(cls):
        if cls._instance is None:
            cls._instance = super().__new__(cls)
            cls._instance._initialized = False
        return cls._instance
    
    def __init__(self):
        if not self._initialized:
            # Initialize Qdrant client
            self.client = QdrantClient(
                url=settings.qdrant_url,
                api_key=settings.qdrant_api_key
            )
            self._initialized = True
            self._ensure_collections()
    
    def _ensure_collections(self):
        """Create collections if they don't exist"""
        collections = [
            settings.kb_collection_name,
            settings.history_collection_name
        ]
        
        for collection_name in collections:
            try:
                # Try to get collection info
                self.client.get_collection(collection_name)
            except Exception:
                # Create if doesn't exist
                self.client.create_collection(
                    collection_name=collection_name,
                    vectors_config=VectorParams(
                        size=settings.vector_dimension,
                        distance=Distance.COSINE
                    )
                )
                print(f"✅ Created collection: {collection_name}")
    
    def add_to_kb(self, documents: List[Dict[str, Any]]) -> None:
        """
        Add documents to knowledge base collection
        
        Args:
            documents: List of dicts with 'id', 'text', 'embedding' keys
        """
        from rag.embedding_manager import embedding_manager
        
        points = []
        for doc in documents:
            embedding = embedding_manager.embed(doc['text'])
            point = PointStruct(
                id=int(uuid4().int % (10**8)),
                vector=embedding,
                payload={
                    "text": doc['text'],
                    "source": doc.get('source', 'unknown'),
                    "document_id": doc.get('document_id', str(uuid4()))
                }
            )
            points.append(point)
        
        self.client.upsert(
            collection_name=settings.kb_collection_name,
            points=points
        )
        print(f"✅ Added {len(documents)} documents to KB collection")
    
    def search_kb(self, query: str, limit: int = 3) -> List[Dict[str, Any]]:
        """
        Search knowledge base
        
        Args:
            query: Search query text
            limit: Number of results to return
            
        Returns:
            List of similar documents
        """
        from rag.embedding_manager import embedding_manager
        
        query_embedding = embedding_manager.embed(query)
        
        results = self.client.query_points(
            collection_name=settings.kb_collection_name,
            query=query_embedding,
            limit=limit
        ).points
        
        return [
            {
                "text": r.payload['text'],
                "source": r.payload.get('source', 'unknown'),
                "score": r.score
            }
            for r in results
        ]
    
    def search_history(self, query: str, customer_id: str, limit: int = 3) -> List[Dict[str, Any]]:
        """
        Search customer history with customer_id filter
        
        Args:
            query: Search query text
            customer_id: Filter by customer
            limit: Number of results
            
        Returns:
            List of similar history records for customer
        """
        from rag.embedding_manager import embedding_manager
        
        query_embedding = embedding_manager.embed(query)
        
        results = self.client.query_points(
            collection_name=settings.history_collection_name,
            query=query_embedding,
            limit=limit,
            query_filter={
                "must": [
                    {
                        "key": "customer_id",
                        "match": {"value": customer_id}
                    }
                ]
            }
        ).points
        
        return [
            {
                "text": r.payload['text'],
                "customer_id": r.payload.get('customer_id'),
                "interaction_type": r.payload.get('interaction_type'),
                "score": r.score
            }
            for r in results
        ]
    
    def add_to_history(self, customer_id: str, text: str, interaction_type: str) -> None:
        """
        Add conversation to customer history
        
        Args:
            customer_id: Customer identifier
            text: Conversation text
            interaction_type: Type of interaction (e.g., 'complaint', 'refund_request')
        """
        from rag.embedding_manager import embedding_manager
        
        embedding = embedding_manager.embed(text)
        point = PointStruct(
            id=int(uuid4().int % (10**8)),
            vector=embedding,
            payload={
                "customer_id": customer_id,
                "text": text,
                "interaction_type": interaction_type,
                "timestamp": str(__import__('datetime').datetime.now())
            }
        )
        
        self.client.upsert(
            collection_name=settings.history_collection_name,
            points=[point]
        )
    
    def get_collection_info(self, collection_name: str) -> Dict[str, Any]:
        """Get collection statistics"""
        info = self.client.get_collection(collection_name)
        return {
            "name": collection_name,
            "points_count": info.points_count,
            "vectors_count": info.vectors_count
        }


# Global singleton instance
qdrant_manager = QdrantManager()