File size: 11,302 Bytes
10d6a86
ae92cb7
 
10d6a86
 
 
 
 
 
ae92cb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10d6a86
 
ae92cb7
10d6a86
 
ae92cb7
 
10d6a86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae92cb7
10d6a86
 
 
 
 
ae92cb7
10d6a86
 
 
ae92cb7
10d6a86
 
 
 
 
 
ae92cb7
10d6a86
ae92cb7
 
10d6a86
 
 
 
ae92cb7
10d6a86
79b8126
ae92cb7
 
 
 
 
 
 
 
 
 
 
10d6a86
 
ae92cb7
 
 
 
 
 
 
10d6a86
 
 
 
 
 
 
 
 
 
 
ae92cb7
 
 
10d6a86
 
 
 
ae92cb7
10d6a86
ae92cb7
10d6a86
ae92cb7
10d6a86
 
ae92cb7
10d6a86
 
 
 
 
 
 
ae92cb7
10d6a86
 
 
ae92cb7
10d6a86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ae92cb7
10d6a86
 
 
 
 
ae92cb7
10d6a86
 
 
 
 
ae92cb7
10d6a86
 
 
 
 
ae92cb7
10d6a86
 
 
 
 
 
 
 
 
 
 
ae92cb7
10d6a86
 
 
 
ae92cb7
10d6a86
ae92cb7
10d6a86
 
 
 
 
ae92cb7
10d6a86
 
 
 
 
 
ae92cb7
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
import os, logging
from app.engine.logger import logger

from typing import List, Any
import pandas as pd 
from weaviate.classes.config import Property, DataType

from .weaviate_interface_v4 import WeaviateWCS, WeaviateIndexer

from ..settings import parquet_file
from weaviate.classes.query import Filter
from torch import cuda

if os.path.exists('.we_are_local'):
    COLLECTION = 'MultiRAG_local_mr'
else:
    COLLECTION = 'MultiRAG'

class dummyWeaviate:
    """ Created to pass on HF since I had again the client creation issue 
        Temporary solution
    """
    def __init__(self, 
                 endpoint: str=None,
                 api_key: str=None,
                 model_name_or_path: str='sentence-transformers/all-MiniLM-L6-v2',
                 embedded: bool=False,
                 openai_api_key: str=None,
                 skip_init_checks: bool=False,
                 **kwargs
                ):
        return
    
    def _connect(self) -> None:
        return
    
    def _client(self):
        return
    
    def create_collection(self,
                          collection_name: str,
                          properties: list[Property],
                          description: str=None,
                          **kwargs
                          ) -> None:
        return
    
    def show_all_collections(self, 
                             detailed: bool=False,
                             max_details: bool=False
                             ) -> list[str] | dict:
        return ['abc', 'def']
    
    def show_collection_config(self, collection_name: str):
        return
    
    def show_collection_properties(self, collection_name: str):
        return
    
    def delete_collection(self, collection_name: str):
        return
    
    def get_doc_count(self, collection_name: str):
        return
    
    def keyword_search(self,
                       request: str,
                       collection_name: str,
                       query_properties: list[str]=['content'],
                       limit: int=10,
                       filter: Filter=None,
                       return_properties: list[str]=None,
                       return_raw: bool=False
                       ):
        return
    
    def vector_search(self,
                      request: str,
                      collection_name: str,
                      limit: int=10,
                      return_properties: list[str]=None,
                      filter: Filter=None,
                      return_raw: bool=False,
                      device: str='cuda:0' if cuda.is_available() else 'cpu'
                      ):
        return

    def hybrid_search(self,
                      request: str,
                      collection_name: str,
                      query_properties: list[str]=['content'],
                      alpha: float=0.5,
                      limit: int=10,
                      filter: Filter=None,
                      return_properties: list[str]=None,
                      return_raw: bool=False,
                      device: str='cuda:0' if cuda.is_available() else 'cpu'
                     ):
        return

class VectorStore:
    def __init__(self, model_path: str = 'sentence-transformers/all-mpnet-base-v2'):
        # we can create several instances to test various models, especially if we finetune one
        
        self.MultiRAG_properties = [  
                Property(name='file',
                         data_type=DataType.TEXT,
                         description='Name of the file',
                         index_filterable=True,
                         index_searchable=True),
                # Property(name='keywords',
                #          data_type=DataType.TEXT_ARRAY,
                #          description='Keywords associated with the file',
                #          index_filterable=True,
                #          index_searchable=True),
                Property(name='content',
                         data_type=DataType.TEXT,
                         description='Splits of the article',
                         index_filterable=True,
                         index_searchable=True),
              ]

        self.class_name = "MultiRAG_all-mpnet-base-v2"

        self.class_config = {'classes': [

                            {"class": self.class_name,
                            
                            "description": "multiple types of docs", 
                            
                            "vectorIndexType": "hnsw", 
                            
                            # Vector index specific app.settings for HSNW
                            "vectorIndexConfig": {                   
                                
                                    "ef": 64,  # higher is better quality vs slower search
                                    "efConstruction": 128, # higher = better index but slower build
                                    "maxConnections": 32,  # max conn per layer - higher = more memory
                            },

                            "vectorizer": "none",

                            "properties": self.MultiRAG_properties}
                            ]
        }

        self.model_path = model_path

        try:
            self.api_key = os.environ.get('FINRAG_WEAVIATE_API_KEY')
            logger(f"API key: {self.api_key[:5]}")
            self.url = os.environ.get('FINRAG_WEAVIATE_ENDPOINT')
            logger(f"URL: {self.url[8:15]}")
            self.client = WeaviateWCS(
                    endpoint=self.url, 
                    api_key=self.api_key, 
                    model_name_or_path=self.model_path,
                    )
            assert self.client._client.is_live(), "Weaviate is not live"
            assert self.client._client.is_ready(), "Weaviate is not ready"
            logger(f"Weaviate client created")
        except Exception as e:
            # raise Exception(f"Could not create Weaviate client: {e}")
            self.client = dummyWeaviate()  # used when issue with HF client creation, to continue on HF
            logger(f"Could not create Weaviate client: {e}")

        # if we fail these tests 'VectorStore' object has no attribute 'client'
        # it's prob not the env var but the model missing
        # assert self.client._client.is_live(), "Weaviate is not live"
        # assert self.client._client.is_ready(), "Weaviate is not ready"
        # careful with accessing '_client' since the weaviate helper usually closes the connection every time
        
        self.indexer = None
        
        self.create_collection()
    
    @property
    def collections(self):
        
        return self.client.show_all_collections()
        
    def create_collection(self, 
                          collection_name: str=COLLECTION, 
                          description: str='Documents'):

        self.collection_name = collection_name
        if collection_name not in self.collections:
            self.client.create_collection(collection_name=collection_name, 
                                          properties=self.MultiRAG_properties, 
                                          description=description)
            # self.collection_name = collection_name
        else:
            logger(f"Collection {collection_name} already exists")


    def empty_collection(self, collection_name: str=COLLECTION) -> bool:
        
        # not in the library yet, so I simply delete and recreate it
        if collection_name in self.collections:
            self.client.delete_collection(collection_name=collection_name)
            self.create_collection()
            return True
        else:
            logger(f"Collection {collection_name} doesn't exist")
            return False


    def index_data(self, data: List[dict]= None, collection_name: str=COLLECTION):
        
        if self.indexer is None:
            self.indexer = WeaviateIndexer(self.client)
        
        if data is None:
            # use the parquet file, otherwise use the data passed
            data = pd.read_parquet(parquet_file).to_dict('records')
            # the parquet file was created/incremented when a new article was uploaded
            # it is a dataframe with columns: file, content, content_embedding
            # and reflects exactly the data that we want to index at all times
        self.status = self.indexer.batch_index_data(data, collection_name, 256)
        
        self.num_errors, self.error_messages, self.doc_ids = self.status
        
        # in this case with few articles, we don't tolerate errors
        # batch_index_data already tests errors against a threshold
        # assert self.num_errors == 0, f"Errors: {self.num_errors}"
        
        
    def keyword_search(self, 
                       query: str, 
                       limit: int=5, 
                       return_properties: List[str]=['file', 'content'],
                       alpha=None  # dummy parameter to match the hybrid_search signature
                       ) -> List[str]:
        response = self.client.keyword_search(
                                request=query,
                                collection_name=self.collection_name,
                                query_properties=['file', 'content'], 
                                limit=limit,
                                filter=None,  
                                return_properties=return_properties,
                                return_raw=False)
        
        return [(res['file'], res['content'], res['score']) for res in response]
    
    
    def vector_search(self, 
                      query: str, 
                      limit: int=5, 
                      return_properties: List[str]=['file', 'content'],
                      alpha=None  # dummy parameter to match the hybrid_search signature
                      ) -> List[str]:
        
        response = self.client.vector_search(
                                request=query,
                                collection_name=self.collection_name,
                                limit=limit,
                                filter=None,  
                                return_properties=return_properties,
                                return_raw=False)
        
        return [(res['file'], res['content'], res['score']) for res in response]
    
    
    def hybrid_search(self, 
                      query: str, 
                      limit: int=10, 
                      alpha=0.5,  # higher = more vector search
                      return_properties: List[str]=['file', 'content']
                      ) -> List[str]:

        response = self.client.hybrid_search(
                                request=query,
                                collection_name=self.collection_name,
                                query_properties=['file', 'content'],
                                alpha=alpha,  
                                limit=limit,
                                filter=None,  
                                return_properties=return_properties,
                                return_raw=False)
        
        return [(res['file'], res['content'], res['score']) for res in response]