File size: 6,833 Bytes
837bf6a
0a0ff45
 
837bf6a
0a0ff45
 
 
 
 
 
 
 
837bf6a
0a0ff45
837bf6a
0a0ff45
 
837bf6a
0a0ff45
837bf6a
0a0ff45
837bf6a
0a0ff45
837bf6a
 
 
 
 
0a0ff45
837bf6a
0a0ff45
 
 
 
837bf6a
 
 
 
 
0a0ff45
 
 
837bf6a
 
0a0ff45
 
837bf6a
0a0ff45
 
837bf6a
0a0ff45
 
837bf6a
 
 
0a0ff45
 
 
837bf6a
 
0a0ff45
837bf6a
 
 
0a0ff45
 
 
 
 
 
 
 
 
 
837bf6a
0a0ff45
837bf6a
 
0a0ff45
 
837bf6a
 
 
 
 
0a0ff45
837bf6a
0a0ff45
 
 
 
 
 
 
 
837bf6a
 
 
 
 
0a0ff45
 
837bf6a
 
 
 
 
0a0ff45
 
837bf6a
0a0ff45
 
837bf6a
 
 
0a0ff45
 
 
 
 
 
 
837bf6a
 
0a0ff45
 
 
837bf6a
 
 
0a0ff45
 
837bf6a
0a0ff45
837bf6a
0a0ff45
 
837bf6a
 
 
 
 
0a0ff45
 
 
837bf6a
 
 
0a0ff45
 
837bf6a
0a0ff45
 
837bf6a
0a0ff45
 
 
837bf6a
 
 
 
 
 
 
 
 
 
 
0a0ff45
 
837bf6a
 
 
 
 
0a0ff45
 
837bf6a
 
 
0a0ff45
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
import os
from typing import List, Dict, Any
import hashlib
from datetime import datetime

class VectorStoreManager:
    def __init__(self, persist_directory="./data/chroma_db", model_name="all-MiniLM-L6-v2"):
        self.persist_directory = persist_directory
        os.makedirs(persist_directory, exist_ok=True)
        
        # Initialize embedding model
        try:
            from sentence_transformers import SentenceTransformer
            self.embedding_model = SentenceTransformer(model_name)
            self.embedding_available = True
            print(f"βœ… Loaded embedding model: {model_name}")
        except Exception as e:
            print(f"⚠️ Could not load embedding model: {e}")
            self.embedding_model = None
            self.embedding_available = False
        
        # Initialize ChromaDB with NEW API (correct way)
        try:
            import chromadb
            print("πŸ”„ Initializing ChromaDB with new API...")
            
            # NEW: Simple persistent client
            self.client = chromadb.PersistentClient(path=persist_directory)
            
            # Get or create collection
            self.collection = self.client.get_or_create_collection(
                name="knowledge_base",
                metadata={"hnsw:space": "cosine"}
            )
            
            self.chroma_available = True
            print(f"βœ… ChromaDB initialized successfully!")
            print(f"βœ… Collection: {self.collection.name}")
            print(f"βœ… Collection count: {self.collection.count()}")
            
        except Exception as e:
            print(f"❌ Error initializing vector store: {e}")
            import traceback
            traceback.print_exc()
            self.client = None
            self.collection = None
            self.chroma_available = False
    
    def is_ready(self) -> bool:
        return self.embedding_available and self.chroma_available
    
    def generate_embedding(self, text: str) -> List[float]:
        if not self.embedding_available:
            # Return dummy embedding
            return [0.1] * 384
        
        try:
            return self.embedding_model.encode(text).tolist()
        except:
            return [0.1] * 384
    
    def add_documents(self, documents: List[Dict]) -> bool:
        print(f"πŸ“₯ Attempting to add {len(documents)} documents to vector store")
        
        if not self.is_ready():
            print("❌ Vector store not ready")
            return False
        
        try:
            ids = []
            embeddings = []
            metadatas = []
            documents_text = []
            
            for i, doc in enumerate(documents):
                text = doc.get("text", doc.get("content", ""))
                if not text or not text.strip():
                    print(f"⚠️ Document {i}: Empty text, skipping")
                    continue
                
                # Truncate very long text
                if len(text) > 10000:
                    text = text[:10000]
                    print(f"πŸ“ Document {i}: Truncated to 10,000 chars")
                
                # Generate unique ID
                doc_id = f"doc_{i}_{hashlib.md5(text.encode()).hexdigest()[:8]}"
                ids.append(doc_id)
                
                # Generate embedding
                embedding = self.generate_embedding(text)
                embeddings.append(embedding)
                
                # Store metadata
                metadata = doc.get("metadata", {})
                metadata.update({
                    "text_length": len(text),
                    "processed_at": datetime.now().isoformat(),
                    "source": metadata.get("source", "unknown")
                })
                metadatas.append(metadata)
                
                # Store text (truncated for display)
                display_text = text[:200] + "..." if len(text) > 200 else text
                documents_text.append(display_text)
                
                print(f"βœ… Prepared document {i}: {len(text)} chars")
            
            if not ids:
                print("❌ No valid documents to add")
                return False
            
            print(f"πŸ“Š Adding {len(ids)} documents to collection...")
            
            # Add to collection using new API
            self.collection.add(
                ids=ids,
                embeddings=embeddings,
                metadatas=metadatas,
                documents=documents_text
            )
            
            print(f"πŸŽ‰ Successfully added {len(ids)} documents to vector store!")
            print(f"πŸ“ˆ Total documents in collection: {self.collection.count()}")
            return True
            
        except Exception as e:
            print(f"❌ Error adding documents: {str(e)}")
            import traceback
            traceback.print_exc()
            return False
    
    def similarity_search(self, query: str, k: int = 3) -> List[Dict]:
        if not self.is_ready():
            print("⚠️ Vector store not ready, returning simulated results")
            # Return simulated results
            return [
                {
                    "document": "This is a simulated response. Upload documents to get real answers.",
                    "score": 0.95,
                    "metadata": {"source": "demo", "type": "simulated"}
                }
            ]
        
        try:
            print(f"πŸ” Searching for: '{query}'")
            
            # Generate query embedding
            query_embedding = self.generate_embedding(query)
            
            # Query the collection
            results = self.collection.query(
                query_embeddings=[query_embedding],
                n_results=min(k, 5),
                include=["documents", "metadatas", "distances"]
            )
            
            if not results["documents"] or not results["documents"][0]:
                print("⚠️ No results found in vector store")
                return []
            
            formatted_results = []
            for doc, meta, distance in zip(
                results["documents"][0],
                results["metadatas"][0],
                results["distances"][0]
            ):
                formatted_results.append({
                    "document": doc,
                    "metadata": meta,
                    "score": 1 - distance if distance else 0.9
                })
            
            print(f"βœ… Found {len(formatted_results)} relevant documents")
            return formatted_results
            
        except Exception as e:
            print(f"❌ Search error: {str(e)}")
            import traceback
            traceback.print_exc()
            return []