File size: 43,630 Bytes
690700c
 
 
 
 
 
 
 
 
61a1e05
690700c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61a1e05
 
 
690700c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61a1e05
 
 
 
 
 
 
690700c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ac3f1c
690700c
61a1e05
3ac3f1c
457e6be
 
61a1e05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3ac3f1c
61a1e05
3ac3f1c
61a1e05
 
 
 
 
 
 
 
 
 
 
 
457e6be
61a1e05
3ac3f1c
61a1e05
 
457e6be
61a1e05
457e6be
 
61a1e05
457e6be
61a1e05
 
 
 
457e6be
 
61a1e05
457e6be
61a1e05
 
 
 
457e6be
61a1e05
 
 
 
3ac3f1c
61a1e05
 
 
 
 
 
 
 
 
 
 
690700c
61a1e05
 
690700c
 
 
 
 
457e6be
61a1e05
690700c
61a1e05
3ac3f1c
 
61a1e05
 
 
 
690700c
 
3ac3f1c
 
690700c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61a1e05
 
 
 
690700c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61a1e05
 
690700c
61a1e05
 
 
690700c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
61a1e05
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
"""
Custom Retriever with E5-Base-V2 and FAISS
Trained with InfoNCE + Triplet Loss for banking domain

This is adapted from your RAG.py with:
- CustomSentenceTransformer (e5-base-v2)
- Mean pooling + L2 normalization
- FAISS vector search
- Module-level caching (load once on startup)
- βœ… Compatible with v2 FAISS format
"""

import os
import json
import pickle
import torch
import torch.nn as nn
import torch.nn.functional as F
import faiss
import numpy as np
from typing import List, Dict, Optional
from transformers import AutoTokenizer, AutoModel

from app.config import settings


# ============================================================================
# CUSTOM SENTENCE TRANSFORMER (From RAG.py)
# ============================================================================

class CustomSentenceTransformer(nn.Module):
    """
    Custom SentenceTransformer matching your training code.
    Uses e5-base-v2 with mean pooling and L2 normalization.
    
    Training Details:
    - Base model: intfloat/e5-base-v2
    - Loss: InfoNCE + Triplet Loss
    - Pooling: Mean pooling on last hidden state
    - Normalization: L2 normalization
    """
    
    def __init__(self, model_name: str = "intfloat/e5-base-v2"):
        super().__init__()
        # Load pre-trained e5-base-v2 encoder
        self.encoder = AutoModel.from_pretrained(model_name)
        self.tokenizer = AutoTokenizer.from_pretrained(model_name)
        self.config = self.encoder.config
    
    def forward(self, input_ids, attention_mask):
        """
        Forward pass through BERT encoder.
        
        Args:
            input_ids: Tokenized input IDs
            attention_mask: Attention mask for padding
        
        Returns:
            torch.Tensor: L2-normalized embeddings (shape: [batch_size, 768])
        """
        # Get BERT outputs
        outputs = self.encoder(input_ids=input_ids, attention_mask=attention_mask)
        
        # Mean pooling - same as training
        # Take hidden states from last layer
        token_embeddings = outputs.last_hidden_state
        
        # Expand attention mask to match token embeddings shape
        input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
        
        # Sum embeddings (weighted by attention mask) and divide by sum of mask
        embeddings = torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(
            input_mask_expanded.sum(1), min=1e-9
        )
        
        # L2 normalize embeddings - same as training
        embeddings = F.normalize(embeddings, p=2, dim=1)
        
        return embeddings
    
    def encode(
        self, 
        sentences: List[str], 
        batch_size: int = 32, 
        convert_to_numpy: bool = True,
        show_progress_bar: bool = False
    ) -> np.ndarray:
        """
        Encode sentences using the same method as training.
        Adds 'query: ' prefix for e5-base-v2 compatibility.
        
        Args:
            sentences: List of sentences to encode
            batch_size: Batch size for encoding
            convert_to_numpy: Whether to convert to numpy array
            show_progress_bar: Whether to show progress bar
        
        Returns:
            np.ndarray: Encoded embeddings (shape: [num_sentences, 768])
        """
        self.eval()  # Set model to evaluation mode
        
        # Handle single string input
        if isinstance(sentences, str):
            sentences = [sentences]
        
        # Add 'query: ' prefix for e5-base-v2 (required by model)
        # Handle None values and empty strings
        processed_sentences = []
        for sentence in sentences:
            if sentence is None:
                processed_sentences.append("query: ")  # Default empty query
            elif isinstance(sentence, str):
                processed_sentences.append(f"query: {sentence.strip()}")
            else:
                processed_sentences.append(f"query: {str(sentence)}")
        
        all_embeddings = []
        
        # Encode in batches
        with torch.no_grad():  # No gradient computation
            for i in range(0, len(processed_sentences), batch_size):
                batch_sentences = processed_sentences[i:i + batch_size]
                
                # Tokenize batch
                tokens = self.tokenizer(
                    batch_sentences,
                    truncation=True,
                    padding=True,
                    max_length=128,  # Same as training
                    return_tensors='pt'
                ).to(next(self.parameters()).device)
                
                # Get embeddings
                embeddings = self.forward(tokens['input_ids'], tokens['attention_mask'])
                
                # Convert to numpy if requested
                if convert_to_numpy:
                    embeddings = embeddings.cpu().numpy()
                
                all_embeddings.append(embeddings)
        
        # Combine all batches
        if convert_to_numpy:
            all_embeddings = np.vstack(all_embeddings)
        else:
            all_embeddings = torch.cat(all_embeddings, dim=0)
        
        return all_embeddings


# ============================================================================
# CUSTOM RETRIEVER MODEL (Wrapper)
# ============================================================================

class CustomRetrieverModel:
    """
    Wrapper for your custom trained retriever model.
    Handles both knowledge base documents and query encoding.
    """
    
    def __init__(self, model_path: str, device: str = "cpu"):
        """
        Initialize retriever model.
        
        Args:
            model_path: Path to trained model weights (.pth file)
            device: Device to load model on ('cpu' or 'cuda')
        """
        self.device = device
        
        # Create model instance
        self.model = CustomSentenceTransformer("intfloat/e5-base-v2").to(device)
        
        # Load your trained weights
        try:
            state_dict = torch.load(model_path, map_location=device)
            self.model.load_state_dict(state_dict)
            print(f"βœ… Custom retriever model loaded from {model_path}")
        except Exception as e:
            print(f"❌ Failed to load custom model: {e}")
            print("πŸ”„ Using base e5-base-v2 model (not trained)...")
        
        # Set to evaluation mode
        self.model.eval()
    
    def encode_documents(self, documents: List[str], batch_size: int = 32) -> np.ndarray:
        """
        Encode knowledge base documents.
        These are the responses/instructions we're retrieving.
        
        Args:
            documents: List of document texts
            batch_size: Batch size for encoding
        
        Returns:
            np.ndarray: Document embeddings (shape: [num_docs, 768])
        """
        return self.model.encode(documents, batch_size=batch_size, convert_to_numpy=True)
    
    def encode_query(self, query: str) -> np.ndarray:
        """
        Encode user query for retrieval.
        
        Args:
            query: User query text
        
        Returns:
            np.ndarray: Query embedding (shape: [1, 768])
        """
        return self.model.encode([query], convert_to_numpy=True)


# ============================================================================
# MODULE-LEVEL CACHING (Load once on import)
# ============================================================================

# Global variables for caching
RETRIEVER_MODEL: Optional[CustomRetrieverModel] = None
FAISS_INDEX: Optional[faiss.Index] = None
KB_DATA: Optional[List[Dict]] = None


# ============================================================================
# βœ… UPDATED: COMPATIBLE FAISS LOADING (SUPPORTS V2 FORMAT)
# ============================================================================

def load_retriever() -> CustomRetrieverModel:
    """
    Load custom retriever model (called once on startup).
    Downloads from HuggingFace Hub if not present locally.
    Uses module-level caching - model stays in RAM.
    
    Returns:
        CustomRetrieverModel: Loaded retriever model
    """
    global RETRIEVER_MODEL
    
    if RETRIEVER_MODEL is None:
        # Download model from HF Hub if needed (for deployment)
        settings.download_model_if_needed(
            hf_filename="models/best_retriever_model.pth",
            local_path=settings.RETRIEVER_MODEL_PATH
        )
        
        print(f"Loading custom retriever from {settings.RETRIEVER_MODEL_PATH}...")
        
        RETRIEVER_MODEL = CustomRetrieverModel(
            model_path=settings.RETRIEVER_MODEL_PATH,
            device=settings.DEVICE
        )
        
        print("βœ… Retriever model loaded and cached")
    
    return RETRIEVER_MODEL


def load_faiss_index():
    """
    βœ… UPDATED: Load FAISS index with v2 format compatibility.
    
    Supports multiple formats:
    - v2 format (dict with version info) - RECOMMENDED
    - Old tuple format (index_bytes, kb_data)
    - Legacy format (direct FAISS object) - will show warning
    
    Downloads from HuggingFace Hub if not present locally.
    Uses module-level caching - loaded once on startup.
    
    Returns:
        tuple: (faiss.Index, List[Dict]) - FAISS index and KB data
    """
    global FAISS_INDEX, KB_DATA
    
    if FAISS_INDEX is None or KB_DATA is None:
        # Download FAISS index from HF Hub if needed (for deployment)
        settings.download_model_if_needed(
            hf_filename="models/faiss_index.pkl",
            local_path=settings.FAISS_INDEX_PATH
        )
        
        # Download knowledge base from HF Hub if needed (for deployment)
        settings.download_model_if_needed(
            hf_filename="data/final_knowledge_base.jsonl",
            local_path=settings.KB_PATH
        )
        
        print(f"Loading FAISS index from {settings.FAISS_INDEX_PATH}...")
        
        try:
            # Load pickled data
            with open(settings.FAISS_INDEX_PATH, 'rb') as f:
                data = pickle.load(f)
            
            print(f"πŸ“¦ Pickle loaded successfully")
            
            # ========================================================================
            # FORMAT 1: v2 Dictionary Format (RECOMMENDED)
            # ========================================================================
            if isinstance(data, dict) and data.get('format_version') == 'v2':
                print("πŸ“¦ Detected v2 format (compatible)")
                try:
                    FAISS_INDEX = faiss.deserialize_index(data['index_bytes'])
                    KB_DATA = data['kb_data']
                    print(f"βœ… FAISS index loaded successfully")
                    print(f"   Vectors: {FAISS_INDEX.ntotal}")
                    print(f"   KB docs: {len(KB_DATA)}")
                    print(f"   Dimension: {data.get('dimension', 'unknown')}")
                    print(f"   Built with FAISS: {data.get('faiss_version', 'unknown')}")
                    print(f"   Current FAISS: {faiss.__version__}")
                except Exception as e:
                    print(f"❌ Failed to deserialize v2 format: {e}")
                    raise RuntimeError(
                        f"Failed to load v2 FAISS index: {e}\n"
                        f"Please rebuild using: python build_faiss_index.py"
                    )
            
            # ========================================================================
            # FORMAT 2: Old Tuple Format (index_bytes, kb_data)
            # ========================================================================
            elif isinstance(data, tuple) and len(data) == 2:
                first_item, KB_DATA = data
                
                # Check if first item is bytes (serialized index)
                if isinstance(first_item, bytes):
                    print("πŸ“¦ Detected old tuple format with bytes (attempting conversion)")
                    try:
                        FAISS_INDEX = faiss.deserialize_index(first_item)
                        print(f"βœ… FAISS index deserialized from bytes")
                        print(f"   Vectors: {FAISS_INDEX.ntotal}")
                        print(f"   KB docs: {len(KB_DATA)}")
                    except Exception as e:
                        print(f"❌ Failed to deserialize index bytes: {e}")
                        raise RuntimeError(
                            f"Failed to deserialize FAISS index: {e}\n"
                            f"Please rebuild using: python build_faiss_index.py"
                        )
                
                # Otherwise it's a direct FAISS object (LEGACY - DANGEROUS!)
                else:
                    print(f"πŸ“¦ Detected old tuple format with direct object")
                    print(f"⚠️ WARNING: Direct FAISS objects are not compatible across versions")
                    
                    # Try to use it, but expect it might fail
                    try:
                        FAISS_INDEX = first_item
                        # Test if it works
                        num_vectors = FAISS_INDEX.ntotal
                        print(f"βœ… FAISS index appears valid ({num_vectors} vectors)")
                        print(f"   KB docs: {len(KB_DATA)}")
                        print(f"⚠️ However, this format may break across FAISS versions")
                        print(f"πŸ”§ Recommended: Rebuild using: python build_faiss_index.py")
                    except Exception as e:
                        print(f"❌ FAISS index object is corrupted: {e}")
                        print(f"   This usually means FAISS version mismatch")
                        raise RuntimeError(
                            f"FAISS index is corrupted or incompatible (version mismatch).\n"
                            f"Error: {e}\n\n"
                            f"πŸ”§ SOLUTION: Rebuild FAISS index using:\n"
                            f"   python build_faiss_index.py\n"
                        )
            
            # ========================================================================
            # FORMAT 3: Unknown Format
            # ========================================================================
            else:
                print(f"❌ Unknown pickle format: {type(data)}")
                if isinstance(data, dict):
                    print(f"   Dict keys: {list(data.keys())}")
                raise ValueError(
                    f"Unrecognized pickle format: {type(data)}.\n"
                    f"Please rebuild using: python build_faiss_index.py"
                )
            
            # Final validation
            if FAISS_INDEX is None or KB_DATA is None:
                raise RuntimeError("Failed to load FAISS index or KB data")
            
            print(f"βœ… FAISS index ready: {FAISS_INDEX.ntotal} vectors")
            print(f"βœ… Knowledge base ready: {len(KB_DATA)} documents")
            
        except FileNotFoundError:
            print(f"❌ FAISS index file not found: {settings.FAISS_INDEX_PATH}")
            print(f"⚠️ Make sure models are uploaded to HuggingFace Hub: {settings.HF_MODEL_REPO}")
            raise
        except RuntimeError:
            raise  # Re-raise our custom error with instructions
        except Exception as e:
            print(f"❌ Unexpected error loading FAISS index: {e}")
            import traceback
            traceback.print_exc()
            raise RuntimeError(
                f"Failed to load FAISS index: {e}\n"
                f"Please rebuild using: python build_faiss_index.py"
            )
    
    return FAISS_INDEX, KB_DATA


def retrieve_documents(
    query: str, 
    top_k: int = None, 
    min_similarity: float = None
) -> List[Dict]:
    """
    Retrieve top-k documents for a query using custom retriever + FAISS.
    
    Args:
        query: User query text
        top_k: Number of documents to retrieve (default from config)
        min_similarity: Minimum similarity threshold (default from config)
    
    Returns:
        List[Dict]: Retrieved documents with scores
            Each dict contains:
            - instruction: FAQ question
            - response: FAQ answer
            - category: Document category
            - intent: Document intent
            - score: Similarity score (0-1)
            - rank: Rank in results (1-indexed)
            - faq_id: Document ID
    """
    # Use config defaults if not provided
    if top_k is None:
        top_k = settings.TOP_K
    if min_similarity is None:
        min_similarity = settings.SIMILARITY_THRESHOLD
    
    # Validate query
    if not query or query.strip() == "":
        print("⚠️ Empty query provided")
        return []
    
    try:
        # Load models (cached, no overhead after first call)
        retriever = load_retriever()
        index, kb = load_faiss_index()
        
        # Step 1: Encode query
        query_embedding = retriever.encode_query(query)
        
        # Step 2: Normalize for cosine similarity
        faiss.normalize_L2(query_embedding)
        
        # Step 3: Search in FAISS index
        similarities, indices = index.search(query_embedding, top_k)
        
        # Step 4: Check similarity threshold for top result
        if similarities[0][0] < min_similarity:
            print(f"🚫 NO_FETCH (similarity: {similarities[0][0]:.3f} < {min_similarity})")
            return []
        
        print(f"βœ… FETCH (similarity: {similarities[0][0]:.3f} >= {min_similarity})")
        
        # Step 5: Format results
        results = []
        for rank, (similarity, idx) in enumerate(zip(similarities[0], indices[0])):
            if idx < len(kb):
                doc = kb[idx]
                results.append({
                    'instruction': doc.get('instruction', ''),
                    'response': doc.get('response', ''),
                    'category': doc.get('category', 'Unknown'),
                    'intent': doc.get('intent', 'Unknown'),
                    'score': float(similarity),
                    'rank': rank + 1,
                    'faq_id': doc.get('faq_id', f'doc_{idx}')
                })
        
        return results
    
    except RuntimeError as e:
        # Handle our custom errors with clear messages
        print(f"❌ Retrieval error: {e}")
        return []
    except Exception as e:
        print(f"❌ Unexpected retrieval error: {e}")
        import traceback
        traceback.print_exc()
        return []


def format_context(retrieved_docs: List[Dict], max_context_length: int = None) -> str:
    """
    Format retrieved documents into context string for LLM.
    Prioritizes by score and limits total length.
    
    Args:
        retrieved_docs: List of retrieved documents
        max_context_length: Maximum context length in characters
    
    Returns:
        str: Formatted context string
    """
    if max_context_length is None:
        max_context_length = settings.MAX_CONTEXT_LENGTH
    
    if not retrieved_docs:
        return ""
    
    context_parts = []
    current_length = 0
    
    for doc in retrieved_docs:
        # Create context entry with None checks
        instruction = doc.get('instruction', '') or ''
        response = doc.get('response', '') or ''
        category = doc.get('category', 'N/A') or 'N/A'
        
        context_entry = f"[Rank {doc['rank']}, Score: {doc['score']:.3f}]\n"
        context_entry += f"Q: {instruction}\n"
        context_entry += f"A: {response}\n"
        context_entry += f"Category: {category}\n\n"
        
        # Check length limit
        if current_length + len(context_entry) > max_context_length:
            break
        
        context_parts.append(context_entry)
        current_length += len(context_entry)
    
    return "".join(context_parts)


# ============================================================================
# USAGE EXAMPLE (for reference)
# ============================================================================
"""
# In your service file:

from app.ml.retriever import retrieve_documents, format_context

# Retrieve documents
docs = retrieve_documents("What is my account balance?", top_k=5)

# Format context for LLM
context = format_context(docs)

# Use context in LLM prompt
prompt = f"Context: {context}\n\nQuestion: {query}\n\nAnswer:"
"""





























# """
# Custom Retriever with E5-Base-V2 and FAISS
# Trained with InfoNCE + Triplet Loss for banking domain

# This is adapted from your RAG.py with:
# - CustomSentenceTransformer (e5-base-v2)
# - Mean pooling + L2 normalization
# - FAISS vector search
# - Module-level caching (load once on startup)
# """

# import os
# import json
# import pickle
# import torch
# import torch.nn as nn
# import torch.nn.functional as F
# import faiss
# import numpy as np
# from typing import List, Dict, Optional
# from transformers import AutoTokenizer, AutoModel

# from app.config import settings


# # ============================================================================
# # CUSTOM SENTENCE TRANSFORMER (From RAG.py)
# # ============================================================================

# class CustomSentenceTransformer(nn.Module):
#     """
#     Custom SentenceTransformer matching your training code.
#     Uses e5-base-v2 with mean pooling and L2 normalization.
    
#     Training Details:
#     - Base model: intfloat/e5-base-v2
#     - Loss: InfoNCE + Triplet Loss
#     - Pooling: Mean pooling on last hidden state
#     - Normalization: L2 normalization
#     """
    
#     def __init__(self, model_name: str = "intfloat/e5-base-v2"):
#         super().__init__()
#         # Load pre-trained e5-base-v2 encoder
#         self.encoder = AutoModel.from_pretrained(model_name)
#         self.tokenizer = AutoTokenizer.from_pretrained(model_name)
#         self.config = self.encoder.config
    
#     def forward(self, input_ids, attention_mask):
#         """
#         Forward pass through BERT encoder.
        
#         Args:
#             input_ids: Tokenized input IDs
#             attention_mask: Attention mask for padding
        
#         Returns:
#             torch.Tensor: L2-normalized embeddings (shape: [batch_size, 768])
#         """
#         # Get BERT outputs
#         outputs = self.encoder(input_ids=input_ids, attention_mask=attention_mask)
        
#         # Mean pooling - same as training
#         # Take hidden states from last layer
#         token_embeddings = outputs.last_hidden_state
        
#         # Expand attention mask to match token embeddings shape
#         input_mask_expanded = attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
        
#         # Sum embeddings (weighted by attention mask) and divide by sum of mask
#         embeddings = torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(
#             input_mask_expanded.sum(1), min=1e-9
#         )
        
#         # L2 normalize embeddings - same as training
#         embeddings = F.normalize(embeddings, p=2, dim=1)
        
#         return embeddings
    
#     def encode(
#         self, 
#         sentences: List[str], 
#         batch_size: int = 32, 
#         convert_to_numpy: bool = True,
#         show_progress_bar: bool = False
#     ) -> np.ndarray:
#         """
#         Encode sentences using the same method as training.
#         Adds 'query: ' prefix for e5-base-v2 compatibility.
        
#         Args:
#             sentences: List of sentences to encode
#             batch_size: Batch size for encoding
#             convert_to_numpy: Whether to convert to numpy array
#             show_progress_bar: Whether to show progress bar
        
#         Returns:
#             np.ndarray: Encoded embeddings (shape: [num_sentences, 768])
#         """
#         self.eval()  # Set model to evaluation mode
        
#         # Handle single string input
#         if isinstance(sentences, str):
#             sentences = [sentences]
        
#         # Add 'query: ' prefix for e5-base-v2 (required by model)
#         # Handle None values and empty strings
#         processed_sentences = []
#         for sentence in sentences:
#             if sentence is None:
#                 processed_sentences.append("query: ")  # Default empty query
#             elif isinstance(sentence, str):
#                 processed_sentences.append(f"query: {sentence.strip()}")
#             else:
#                 processed_sentences.append(f"query: {str(sentence)}")
        
#         all_embeddings = []
        
#         # Encode in batches
#         with torch.no_grad():  # No gradient computation
#             for i in range(0, len(processed_sentences), batch_size):
#                 batch_sentences = processed_sentences[i:i + batch_size]
                
#                 # Tokenize batch
#                 tokens = self.tokenizer(
#                     batch_sentences,
#                     truncation=True,
#                     padding=True,
#                     max_length=128,  # Same as training
#                     return_tensors='pt'
#                 ).to(next(self.parameters()).device)
                
#                 # Get embeddings
#                 embeddings = self.forward(tokens['input_ids'], tokens['attention_mask'])
                
#                 # Convert to numpy if requested
#                 if convert_to_numpy:
#                     embeddings = embeddings.cpu().numpy()
                
#                 all_embeddings.append(embeddings)
        
#         # Combine all batches
#         if convert_to_numpy:
#             all_embeddings = np.vstack(all_embeddings)
#         else:
#             all_embeddings = torch.cat(all_embeddings, dim=0)
        
#         return all_embeddings


# # ============================================================================
# # CUSTOM RETRIEVER MODEL (Wrapper)
# # ============================================================================

# class CustomRetrieverModel:
#     """
#     Wrapper for your custom trained retriever model.
#     Handles both knowledge base documents and query encoding.
#     """
    
#     def __init__(self, model_path: str, device: str = "cpu"):
#         """
#         Initialize retriever model.
        
#         Args:
#             model_path: Path to trained model weights (.pth file)
#             device: Device to load model on ('cpu' or 'cuda')
#         """
#         self.device = device
        
#         # Create model instance
#         self.model = CustomSentenceTransformer("intfloat/e5-base-v2").to(device)
        
#         # Load your trained weights
#         try:
#             state_dict = torch.load(model_path, map_location=device)
#             self.model.load_state_dict(state_dict)
#             print(f"βœ… Custom retriever model loaded from {model_path}")
#         except Exception as e:
#             print(f"❌ Failed to load custom model: {e}")
#             print("πŸ”„ Using base e5-base-v2 model (not trained)...")
        
#         # Set to evaluation mode
#         self.model.eval()
    
#     def encode_documents(self, documents: List[str], batch_size: int = 32) -> np.ndarray:
#         """
#         Encode knowledge base documents.
#         These are the responses/instructions we're retrieving.
        
#         Args:
#             documents: List of document texts
#             batch_size: Batch size for encoding
        
#         Returns:
#             np.ndarray: Document embeddings (shape: [num_docs, 768])
#         """
#         return self.model.encode(documents, batch_size=batch_size, convert_to_numpy=True)
    
#     def encode_query(self, query: str) -> np.ndarray:
#         """
#         Encode user query for retrieval.
        
#         Args:
#             query: User query text
        
#         Returns:
#             np.ndarray: Query embedding (shape: [1, 768])
#         """
#         return self.model.encode([query], convert_to_numpy=True)


# # ============================================================================
# # MODULE-LEVEL CACHING (Load once on import)
# # ============================================================================

# # Global variables for caching
# RETRIEVER_MODEL: Optional[CustomRetrieverModel] = None
# FAISS_INDEX: Optional[faiss.Index] = None
# KB_DATA: Optional[List[Dict]] = None





# # =============================================================================================
# # Latest version given by perplexity, should work, if not then use one of the other versions.
# # =============================================================================================

# def load_retriever() -> CustomRetrieverModel:
#     """
#     Load custom retriever model (called once on startup).
#     Downloads from HuggingFace Hub if not present locally.
#     Uses module-level caching - model stays in RAM.
    
#     Returns:
#         CustomRetrieverModel: Loaded retriever model
#     """
#     global RETRIEVER_MODEL
    
#     if RETRIEVER_MODEL is None:
#         # Download model from HF Hub if needed (for deployment)
#         settings.download_model_if_needed(
#             hf_filename="models/best_retriever_model.pth",
#             local_path=settings.RETRIEVER_MODEL_PATH
#         )
        
#         print(f"Loading custom retriever from {settings.RETRIEVER_MODEL_PATH}...")
        
#         RETRIEVER_MODEL = CustomRetrieverModel(
#             model_path=settings.RETRIEVER_MODEL_PATH,
#             device=settings.DEVICE
#         )
        
#         print("βœ… Retriever model loaded and cached")
    
#     return RETRIEVER_MODEL









# # ===========================================================================
# # This version is used in the code, atleast for localhost testing
# # ===========================================================================

# # def load_retriever() -> CustomRetrieverModel:
# #     """
# #     Load custom retriever model (called once on startup).
# #     Uses module-level caching - model stays in RAM.
    
# #     Returns:
# #         CustomRetrieverModel: Loaded retriever model
# #     """
# #     global RETRIEVER_MODEL
    
# #     if RETRIEVER_MODEL is None:
# #         print(f"Loading custom retriever from {settings.RETRIEVER_MODEL_PATH}...")
# #         RETRIEVER_MODEL = CustomRetrieverModel(
# #             model_path=settings.RETRIEVER_MODEL_PATH,
# #             device=settings.DEVICE
# #         )
# #         print("βœ… Retriever model loaded and cached")
    
# #     return RETRIEVER_MODEL

# # ==================================================================================================
# # Latest version given by perplexity, should work, if not then use one of the other versions.
# # ==================================================================================================
# def load_faiss_index():
#     """
#     Load FAISS index + knowledge base from pickle file.
#     Downloads from HuggingFace Hub if not present locally.
#     Uses module-level caching - loaded once on startup.
    
#     Returns:
#         tuple: (faiss.Index, List[Dict]) - FAISS index and KB data
#     """
#     global FAISS_INDEX, KB_DATA
    
#     if FAISS_INDEX is None or KB_DATA is None:
#         # Download FAISS index from HF Hub if needed (for deployment)
#         settings.download_model_if_needed(
#             hf_filename="models/faiss_index.pkl",
#             local_path=settings.FAISS_INDEX_PATH
#         )
        
#         # Download knowledge base from HF Hub if needed (for deployment)
#         settings.download_model_if_needed(
#             hf_filename="data/final_knowledge_base.jsonl",
#             local_path=settings.KB_PATH
#         )
        
#         print(f"Loading FAISS index from {settings.FAISS_INDEX_PATH}...")
        
#         try:
#             # Load pickled data
#             with open(settings.FAISS_INDEX_PATH, 'rb') as f:
#                 loaded_data = pickle.load(f)
            
#             print(f"πŸ“¦ Pickle loaded successfully")
            
#             # βœ… Handle both formats: (index, kb_data) OR (index_bytes, kb_data)
#             if isinstance(loaded_data, tuple) and len(loaded_data) == 2:
#                 first_item, KB_DATA = loaded_data
                
#                 # Check if first item is bytes (new format) - SAFE to check
#                 if isinstance(first_item, bytes):
#                     print("πŸ“¦ Detected new format (serialized bytes)")
#                     FAISS_INDEX = faiss.deserialize_index(first_item)
#                     print(f"βœ… FAISS index deserialized successfully")
                
#                 # Otherwise assume it's old format and try to use it
#                 else:
#                     print(f"πŸ“¦ Detected old format (attempting to use directly)")
                    
#                     # ❌ DON'T use hasattr() - it crashes on corrupted FAISS!
#                     # Instead, try to use it and catch errors
#                     try:
#                         FAISS_INDEX = first_item
#                         # Test if it works by accessing ntotal
#                         num_vectors = FAISS_INDEX.ntotal
#                         print(f"βœ… FAISS index is valid ({num_vectors} vectors)")
#                     except Exception as e:
#                         print(f"❌ FAISS index object is corrupted: {e}")
#                         print(f"⚠️ This pickle was created with incompatible FAISS version")
#                         print(f"")
#                         print(f"πŸ”§ SOLUTION: Rebuild FAISS index using:")
#                         print(f"   python build_faiss_index.py")
#                         print(f"")
#                         raise RuntimeError(
#                             f"FAISS index is corrupted or incompatible (FAISS version mismatch). "
#                             f"Please rebuild using: python build_faiss_index.py"
#                         )
#             else:
#                 raise ValueError(f"Invalid pickle format: expected tuple, got {type(loaded_data)}")
            
#             print(f"βœ… FAISS index loaded: {FAISS_INDEX.ntotal} vectors")
#             print(f"βœ… Knowledge base loaded: {len(KB_DATA)} documents")
            
#         except FileNotFoundError:
#             print(f"❌ FAISS index file not found: {settings.FAISS_INDEX_PATH}")
#             print(f"⚠️ Make sure models are uploaded to HuggingFace Hub: {settings.HF_MODEL_REPO}")
#             raise
#         except RuntimeError:
#             raise  # Re-raise our custom error
#         except Exception as e:
#             print(f"❌ Failed to load FAISS index: {e}")
#             import traceback
#             traceback.print_exc()
#             raise
    
#     return FAISS_INDEX, KB_DATA



# # ==================================================================================================
# # Second Latest version given by perplexity, should work, if not then use one of the other versions.
# # ==================================================================================================

# # def load_faiss_index():
# #     """
# #     Load FAISS index + knowledge base from pickle file.
# #     Downloads from HuggingFace Hub if not present locally.
# #     Uses module-level caching - loaded once on startup.
    
# #     Returns:
# #         tuple: (faiss.Index, List[Dict]) - FAISS index and KB data
# #     """
# #     global FAISS_INDEX, KB_DATA
    
# #     if FAISS_INDEX is None or KB_DATA is None:
# #         # Download FAISS index from HF Hub if needed (for deployment)
# #         settings.download_model_if_needed(
# #             hf_filename="models/faiss_index.pkl",
# #             local_path=settings.FAISS_INDEX_PATH
# #         )
        
# #         # Download knowledge base from HF Hub if needed (for deployment)
# #         settings.download_model_if_needed(
# #             hf_filename="data/final_knowledge_base.jsonl",
# #             local_path=settings.KB_PATH
# #         )
        
# #         print(f"Loading FAISS index from {settings.FAISS_INDEX_PATH}...")
        
# #         try:
# #             # Load pickled FAISS index + KB data
# #             with open(settings.FAISS_INDEX_PATH, 'rb') as f:
# #                 FAISS_INDEX, KB_DATA = pickle.load(f)
            
# #             print(f"βœ… FAISS index loaded: {FAISS_INDEX.ntotal} vectors")
# #             print(f"βœ… Knowledge base loaded: {len(KB_DATA)} documents")
            
# #         except FileNotFoundError:
# #             print(f"❌ FAISS index file not found: {settings.FAISS_INDEX_PATH}")
# #             print(f"⚠️ Make sure models are uploaded to HuggingFace Hub: {settings.HF_MODEL_REPO}")
# #             raise
# #         except Exception as e:
# #             print(f"❌ Failed to load FAISS index: {e}")
# #             raise
    
# #     return FAISS_INDEX, KB_DATA



# # ===========================================================================
# # This version is used in the code, atleast for localhost testing
# # ===========================================================================

# # def load_faiss_index():
# #     """
# #     Load FAISS index + knowledge base from pickle file.
# #     Uses module-level caching - loaded once on startup.
    
# #     Returns:
# #         tuple: (faiss.Index, List[Dict]) - FAISS index and KB data
# #     """
# #     global FAISS_INDEX, KB_DATA
    
# #     if FAISS_INDEX is None or KB_DATA is None:
# #         print(f"Loading FAISS index from {settings.FAISS_INDEX_PATH}...")
        
# #         try:
# #             # Load pickled FAISS index + KB data
# #             with open(settings.FAISS_INDEX_PATH, 'rb') as f:
# #                 FAISS_INDEX, KB_DATA = pickle.load(f)
            
# #             print(f"βœ… FAISS index loaded: {FAISS_INDEX.ntotal} vectors")
# #             print(f"βœ… Knowledge base loaded: {len(KB_DATA)} documents")
        
# #         except FileNotFoundError:
# #             print(f"❌ FAISS index file not found: {settings.FAISS_INDEX_PATH}")
# #             print("⚠️  You need to create the FAISS index first!")
# #             raise
        
# #         except Exception as e:
# #             print(f"❌ Failed to load FAISS index: {e}")
# #             raise
    
# #     return FAISS_INDEX, KB_DATA


# # ============================================================================
# # RETRIEVAL FUNCTIONS
# # ============================================================================

# def retrieve_documents(
#     query: str, 
#     top_k: int = None, 
#     min_similarity: float = None
# ) -> List[Dict]:
#     """
#     Retrieve top-k documents for a query using custom retriever + FAISS.
    
#     Args:
#         query: User query text
#         top_k: Number of documents to retrieve (default from config)
#         min_similarity: Minimum similarity threshold (default from config)
    
#     Returns:
#         List[Dict]: Retrieved documents with scores
#             Each dict contains:
#             - instruction: FAQ question
#             - response: FAQ answer
#             - category: Document category
#             - intent: Document intent
#             - score: Similarity score (0-1)
#             - rank: Rank in results (1-indexed)
#             - faq_id: Document ID
#     """
#     # Use config defaults if not provided
#     if top_k is None:
#         top_k = settings.TOP_K
#     if min_similarity is None:
#         min_similarity = settings.SIMILARITY_THRESHOLD
    
#     # Validate query
#     if not query or query.strip() == "":
#         print("⚠️ Empty query provided")
#         return []
    
#     # Load models (cached, no overhead after first call)
#     retriever = load_retriever()
#     index, kb = load_faiss_index()
    
#     try:
#         # Step 1: Encode query
#         query_embedding = retriever.encode_query(query)
        
#         # Step 2: Normalize for cosine similarity
#         faiss.normalize_L2(query_embedding)
        
#         # Step 3: Search in FAISS index
#         similarities, indices = index.search(query_embedding, top_k)
        
#         # Step 4: Check similarity threshold for top result
#         if similarities[0][0] < min_similarity:
#             print(f"🚫 NO_FETCH (similarity: {similarities[0][0]:.3f} < {min_similarity})")
#             return []
        
#         print(f"βœ… FETCH (similarity: {similarities[0][0]:.3f} >= {min_similarity})")
        
#         # Step 5: Format results
#         results = []
#         for rank, (similarity, idx) in enumerate(zip(similarities[0], indices[0])):
#             if idx < len(kb):
#                 doc = kb[idx]
#                 results.append({
#                     'instruction': doc.get('instruction', ''),
#                     'response': doc.get('response', ''),
#                     'category': doc.get('category', 'Unknown'),
#                     'intent': doc.get('intent', 'Unknown'),
#                     'score': float(similarity),
#                     'rank': rank + 1,
#                     'faq_id': doc.get('faq_id', f'doc_{idx}')
#                 })
        
#         return results
    
#     except Exception as e:
#         print(f"❌ Retrieval error: {e}")
#         import traceback
#         traceback.print_exc()
#         return []


# def format_context(retrieved_docs: List[Dict], max_context_length: int = None) -> str:
#     """
#     Format retrieved documents into context string for LLM.
#     Prioritizes by score and limits total length.
    
#     Args:
#         retrieved_docs: List of retrieved documents
#         max_context_length: Maximum context length in characters
    
#     Returns:
#         str: Formatted context string
#     """
#     if max_context_length is None:
#         max_context_length = settings.MAX_CONTEXT_LENGTH
    
#     if not retrieved_docs:
#         return ""
    
#     context_parts = []
#     current_length = 0
    
#     for doc in retrieved_docs:
#         # Create context entry with None checks
#         instruction = doc.get('instruction', '') or ''
#         response = doc.get('response', '') or ''
#         category = doc.get('category', 'N/A') or 'N/A'
        
#         context_entry = f"[Rank {doc['rank']}, Score: {doc['score']:.3f}]\n"
#         context_entry += f"Q: {instruction}\n"
#         context_entry += f"A: {response}\n"
#         context_entry += f"Category: {category}\n\n"
        
#         # Check length limit
#         if current_length + len(context_entry) > max_context_length:
#             break
        
#         context_parts.append(context_entry)
#         current_length += len(context_entry)
    
#     return "".join(context_parts)


# # ============================================================================
# # USAGE EXAMPLE (for reference)
# # ============================================================================
# """
# # In your service file:

# from app.ml.retriever import retrieve_documents, format_context

# # Retrieve documents
# docs = retrieve_documents("What is my account balance?", top_k=5)

# # Format context for LLM
# context = format_context(docs)

# # Use context in LLM prompt
# prompt = f"Context: {context}\n\nQuestion: {query}\n\nAnswer:"
# """