-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
2068 lines (1694 loc) · 78.4 KB
/
Copy pathapp.py
File metadata and controls
2068 lines (1694 loc) · 78.4 KB
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
import os
import requests
from typing import Optional, Dict
import openai
import chainlit as cl
from helpers import *
from llama_index.core import (
Settings,
SimpleDirectoryReader,
VectorStoreIndex,
StorageContext,
load_index_from_storage,
)
from llama_index.llms.openai import OpenAI
from llama_index.embeddings.openai import OpenAIEmbedding
from llama_index.core.query_engine import SimpleMultiModalQueryEngine
from llama_index.core.llama_dataset.generator import RagDatasetGenerator
from llama_index.core.evaluation import (
RetrieverEvaluator,
QueryResponseEvaluator,
)
from llama_index.core.node_parser import SentenceSplitter
from llama_index.core.embeddings import resolve_embed_model
# from llama_index.core.utils import cosine_similarity - Removed..why LlamaIndex, why?
from sklearn.metrics.pairwise import cosine_similarity
import numpy as np
from llama_index.core.schema import NodeWithScore
from llama_index.vector_stores.chroma import ChromaVectorStore
from chromadb import PersistentClient
from chromadb.config import Settings as ChromaSettings
from ocr_tesseract import ocr_generator
from image_extractor import extract_images_from_pdf
from weather import weather_keywords, detect_tense_simple
from llama_index.tools.weather import OpenWeatherMapToolSpec
from textwrap import shorten
from collections import defaultdict, Counter
import re
import json
import asyncio
from datetime import datetime
import csv
from statistics import mean
import zipfile
import glob
from pathlib import Path
from decimal import Decimal # Retrieval Metrics are not int or float...
from tenacity import (
retry,
wait_random_exponential,
stop_after_attempt,
retry_if_exception_type,
)
# API KEYS
ENABLE_USER_ENV = os.getenv("ENABLE_USER_ENV", "false").lower() == "true"
OPENAI_TOKEN: Optional[str] = os.getenv("OPENAI_API_KEY")
HF_TOKEN: Optional[str] = os.getenv("HUGGING_FACE_TOKEN")
OPENWEATHER_TOKEN: Optional[str] = os.getenv("OPENWEATHER_API_KEY")
TOP_K_RESULTS = int(os.getenv("TOP_K_RETRIEVAL_RESULTS", 5))
# Authentication and OAuth2 (Auth0)
ENABLE_AUTH = os.getenv("ENABLE_AUTH", "false").lower() == "true"
CHAINLIT_AUTH_SECRET = os.getenv("CHAINLIT_AUTH_SECRET", "")
OAUTH_AUTH0_CLIENT_ID = os.getenv("OAUTH_AUTH0_CLIENT_ID", "")
OAUTH_AUTH0_CLIENT_SECRET = os.getenv("OAUTH_AUTH0_CLIENT_SECRET", "")
OAUTH_AUTH0_DOMAIN = os.getenv("OAUTH_AUTH0_DOMAIN", "")
# Decoupled Retrieval & Synthesis Configuration
ENABLE_DECOUPLED_SYNTHESIS = (
os.getenv("ENABLE_DECOUPLED_SYNTHESIS", "false").lower() == "true"
)
CHUNK_GROUP_FIELD = os.getenv("CHUNK_GROUP_FIELD", "parent_id")
CHUNK_SYNTHESIS_MIN = int(os.getenv("CHUNK_SYNTHESIS_MIN", 1))
CHUNK_SYNTHESIS_MAX = int(os.getenv("CHUNK_SYNTHESIS_MAX", 6))
CHUNK_SYNTHESIS_ORDERED = os.getenv("CHUNK_SYNTHESIS_ORDERED", "true").lower() == "true"
# Evaluation Logging Configuration
ENABLE_SESSION_EVAL = os.getenv("ENABLE_SESSION_EVAL", "false").lower() == "true"
EVAL_FOLDER = os.getenv("EVAL_OUTPUT_DIR", "./evals")
EVAL_TRIGGER_KEYWORD = os.getenv("EVAL_TRIGGER_KEYWORD", "!freeze_eval").strip().lower()
EVAL_MAX_LOGGED_QUERIES = int(os.getenv("EVAL_MAX_LOGGED_QUERIES", 0)) # 0 = unlimited
EVAL_ZIP_EXPORT = os.getenv("EVAL_ZIP_EXPORT", "false").lower() == "true"
# Evaluation Trigger Commands
EVAL_REPLAY_ENABLED = os.getenv("EVAL_REPLAY_ENABLED", "true").lower() == "true"
EVAL_REPLAY_TOP_K = int(os.getenv("EVAL_REPLAY_TOP_K", 3))
EVAL_REPLAY_TRIGGER = os.getenv("EVAL_REPLAY_TRIGGER", "!replay_eval").strip().lower()
# Evaluation List Settings
EVAL_LIST_ENABLED = os.getenv("EVAL_LIST_ENABLED", "true").lower() == "true"
EVAL_LIST_TRIGGER = os.getenv("EVAL_LIST_TRIGGER", "!list_evals").strip().lower()
# Evaluation Comparison Settings
EVAL_COMPARE_ENABLED = os.getenv("EVAL_COMPARE_ENABLED", "true").lower() == "true"
EVAL_COMPARE_TRIGGER = (
os.getenv("EVAL_COMPARE_TRIGGER", "!compare_eval").strip().lower()
)
# Evaluation Listing Interaction
EVAL_LIST_TRIGGER = os.getenv("EVAL_LIST_TRIGGER", "!list_evals").strip().lower()
EVAL_LIST_LIMIT = int(os.getenv("EVAL_LIST_LIMIT", 10))
EVAL_LIST_FORMAT = os.getenv("EVAL_LIST_FORMAT", "both").lower()
# Optional filters for QA dataset generation
ENABLE_QA_DATASET_GENERATION = (
os.getenv("ENABLE_QA_DATASET_GENERATION", "false").lower() == "true"
)
QA_NUM_QUESTIONS = int(os.getenv("QA_NUM_QUESTIONS", 1))
QA_SOURCE_FILE_FILTER = os.getenv("QA_SOURCE_FILE_FILTER", "").strip() or None
QA_EMBEDDING_MODE_FILTER = os.getenv("QA_EMBEDDING_MODE_FILTER", "").strip() or None
QA_MATCH_THRESHOLD = float(os.getenv("QA_MATCH_THRESHOLD", 0.85))
RETRIEVAL_DEBUG_MODE = os.getenv("RETRIEVAL_DEBUG", "false").lower() == "true"
if ENABLE_AUTH:
@cl.password_auth_callback
def auth_callback(username: str, password: str) -> Optional[cl.User]:
"""
Authenticate users using a username and password.
This callback is triggered when Chainlit is configured to use
password-based authentication (ENABLE_AUTH=true) and no OAuth provider
is active. It validates the provided credentials and returns a User object
if authentication succeeds.
Args:
username (str): The username entered by the user.
password (str): The password entered by the user.
Returns:
Optional[cl.User]: A Chainlit User object if the credentials are valid;
otherwise, None to deny access.
"""
# Replace this logic with real auth if needed
if username == "admin" and password == "1234":
return cl.User(identifier="admin", metadata={"role": "admin"})
return None
@cl.oauth_callback
def oauth_callback(
provider_id: str,
token: str,
raw_user_data: Dict[str, str],
default_user: cl.User,
) -> Optional[cl.User]:
"""
Process and customize user authentication via OAuth providers.
This callback is called after a user has successfully authenticated
via a configured OAuth provider (e.g., Auth0, GitHub, Google). It allows
you to inspect or modify the default user object before granting access.
Args:
provider_id (str): The identifier of the OAuth provider (e.g., "auth0").
token (str): The access token issued by the OAuth provider.
raw_user_data (Dict[str, str]): Raw profile data returned by the provider.
default_user (cl.User): The default user constructed by Chainlit.
Returns:
Optional[cl.User]: The final Chainlit User object to be used for the session;
return None to deny access.
"""
return default_user
def debug_log(*args, **kwargs):
if RETRIEVAL_DEBUG_MODE:
print(*args, **kwargs)
def load_embedding_config(config_path="./embeddings_openai_persistence.json"):
try:
with open(config_path, "r", encoding="utf-8") as f:
cfg = json.load(f)
model = cfg.get("model", "text-embedding-3-small")
dimensions = cfg.get("dimensions")
use_dimensions = cfg.get("use_dimensions", False)
return model, dimensions if use_dimensions else None
except Exception as e:
print(f"\033[91m[ERROR]\033[0m Failed to load config.json: {e}")
return "text-embedding-3-small", None
# Set default LLM and embedding model
llm = OpenAI(model="gpt-4o", temperature=0.0)
model_name, custom_dims = load_embedding_config()
embed_model = OpenAIEmbedding(
model=model_name,
dimensions=custom_dims,
)
Settings.llm = llm
Settings.embed_model = embed_model
def load_last_chroma_collection_config(
config_path="./embeddings_openai_persistence.json",
):
"""
Loads the last used ChromaDB collection and persistence path from the CLI config file.
Args:
config_path (str): Path to the CLI config file of Embeddings using OpenAI API utility (default: embeddings_openai_persistence.json)
Returns:
dict: {
"chromadb_collection_name": str or None,
"chromadb_persistence_path": str
}
"""
try:
with open(config_path, "r", encoding="utf-8") as f:
config = json.load(f)
return {
"chromadb_collection_name": config.get("chromadb_collection_name"),
"chromadb_persistence_path": config.get(
"chromadb_persistence_path", "./data/chromadb"
),
}
except Exception as e:
print(f"\033[91m[ERROR]\033[0m Failed to load CLI config: {e}")
return {}
# Path and collection for ChromaDB
cli_chroma_config = load_last_chroma_collection_config()
CHROMA_PATH = cli_chroma_config.get("chromadb_persistence_path", "./data/chromadb")
CHROMA_COLLECTION = cli_chroma_config.get(
"chromadb_collection_name", "MarineEngineeringManuals"
)
# Connect to ChromaDB and load pre-generated index
def load_chromadb_index():
print("\033[94m[INFO]\033[0m Connecting to ChromaDB...")
# Load embedding model + dimension config
model_name, expected_dimensions = load_embedding_config()
client = PersistentClient(
path=CHROMA_PATH,
settings=ChromaSettings(anonymized_telemetry=False),
)
collections = client.list_collections()
if CHROMA_COLLECTION not in collections:
raise ValueError(
f"\033[91m[ERROR]\033[0m Collection '{CHROMA_COLLECTION}' not found in {CHROMA_PATH}."
)
chroma_collection = client.get_collection(name=CHROMA_COLLECTION)
result = chroma_collection.get()
doc_ids = result["ids"]
doc_metadatas = result.get("metadatas", [])
doc_texts = result.get("documents", [])
doc_count = len(doc_ids)
# Check dimensionality mismatch
if expected_dimensions:
actual_dim = chroma_collection.metadata.get("dimension")
if actual_dim and actual_dim != expected_dimensions:
print(
f"\033[93m[WARNING]\033[0m Embedding dimension mismatch: "
f"ChromaDB = {actual_dim}, Config = {expected_dimensions}\n"
)
# Check for duplicate custom_ids
duplicates = [item for item, count in Counter(doc_ids).items() if count > 1]
if duplicates:
print(
f"\033[93m[WARNING]\033[0m Duplicate custom_id(s) found: "
f"{', '.join(duplicates[:5])}{'...' if len(duplicates) > 5 else ''}\n"
)
# Check for missing or incomplete metadata
missing_meta = 0
for md in doc_metadatas:
if not md or not isinstance(md, dict):
missing_meta += 1
elif not all(key in md for key in ["embedding_mode", "model"]):
missing_meta += 1
if missing_meta > 0:
print(
f"\033[93m[WARNING]\033[0m {missing_meta} entries have missing or incomplete metadata.\n"
)
# Check for all document fields empty
empty_doc_count = sum(1 for doc in doc_texts if not doc or not doc.strip())
warning_flag = empty_doc_count == len(doc_texts) and doc_count > 0
# --- Group Overview ---
print(
f"\033[92m[SUCCESS]\033[0m Connected to collection: '{CHROMA_COLLECTION}'"
+ (" \033[91m[!]\033[0m" if warning_flag else "")
)
print(f"\033[90m ├── Documents loaded:\033[0m {doc_count}")
# Group and print preview
show_group_preview = os.getenv("GROUP_PREVIEW_ENABLED", "true").lower() == "true"
group_preview_limit = int(os.getenv("GROUP_PREVIEW_LIMIT", 5))
if show_group_preview:
group_stats = defaultdict(
lambda: {"pages": set(), "chunks": set(), "modes": set()}
)
orphaned_chunks = set()
all_ids_set = set(doc_ids)
for idx, doc_id in enumerate(doc_ids):
metadata = doc_metadatas[idx] if idx < len(doc_metadatas) else {}
match = re.match(r"^(.*)_page_(\d+)(?:_chunk_(\d+))?$", doc_id)
if match:
group_id = match.group(1)
page_id = f"{group_id}_page_{match.group(2)}"
is_chunk = match.group(3) is not None
else:
group_id = doc_id.split("_page_")[0]
page_id = doc_id
is_chunk = "_chunk_" in doc_id
embedding_mode = metadata.get("embedding_mode", "unknown")
parent_id = metadata.get("parent_id")
if is_chunk:
group_stats[group_id]["chunks"].add(doc_id)
group_stats[group_id]["pages"].add(page_id)
group_stats[group_id]["modes"].add("chunked")
# Check if parent exists only in mixed mode
if "full" in group_stats[group_id]["modes"]:
if parent_id and parent_id not in all_ids_set:
orphaned_chunks.add(doc_id)
else:
group_stats[group_id]["pages"].add(page_id)
group_stats[group_id]["modes"].add("full")
print(f"\033[90m ├── Document Groups:\033[0m {len(group_stats)}")
for idx, (group_id, stats) in enumerate(sorted(group_stats.items())):
if idx >= group_preview_limit:
break
pages = len(stats["pages"])
chunks = len(stats["chunks"])
mode = "+".join(sorted(stats["modes"]))
print(f" ├─ {group_id} ({pages} pages, {chunks} chunks, mode: {mode})")
if len(group_stats) > group_preview_limit:
print(
f" └─ ...and {len(group_stats) - group_preview_limit} more groups."
)
if orphaned_chunks:
print(
f"\033[93m[WARNING]\033[0m Found {len(orphaned_chunks)} orphaned chunks with missing parent_id links.\n"
)
print(f"\033[90m └── Vector DB path:\033[0m {CHROMA_PATH}\n")
if warning_flag:
print(
"\033[93m[WARNING]\033[0m All document fields are empty strings. "
"You may have loaded embeddings without associated text. "
"Synthesis or semantic responses may be incomplete.\n"
)
if doc_count == 0:
print(
"\033[93m[WARNING]\033[0m Collection is empty. Semantic queries will be skipped.\n"
)
return None
vector_store = ChromaVectorStore(chroma_collection=chroma_collection)
storage_context = StorageContext.from_defaults(vector_store=vector_store)
index = VectorStoreIndex.from_vector_store(
vector_store=vector_store, storage_context=storage_context
)
return index
index = load_chromadb_index()
@retry(
wait=wait_random_exponential(min=1, max=60), # exponential backoff between retries
stop=stop_after_attempt(6), # give up after 6 failed attempts
retry=retry_if_exception_type(
(openai.RateLimitError, openai.APIError, openai.Timeout)
),
)
def safe_generate_dataset(generator):
"""
Safely generates a QA dataset using RagDatasetGenerator with built-in retry logic.
This function wraps `generate_dataset_from_nodes()` with automatic retries
to handle transient errors from the OpenAI API, such as rate limits,
timeouts, or server-side failures.
Retries use exponential backoff with jitter (random wait between 1 and 60 seconds),
and will give up after 6 failed attempts.
Args:
generator (RagDatasetGenerator): The QA dataset generator instance.
Returns:
List[GeneratedQuestionAnswerPair]: List of generated QA pairs.
Raises:
openai.error.OpenAIError: If the operation fails even after retries.
"""
return generator.generate_dataset_from_nodes()
def generate_qa_dataset(
num_questions=1,
embedding_mode_filter: Optional[str] = None,
source_file_filter: Optional[str] = None,
):
"""
Generate a synthetic QA dataset from ChromaDB-stored nodes using LlamaIndex's RagDatasetGenerator.
This function retrieves all nodes from the currently loaded ChromaDB index and applies optional filters
to restrict the dataset to specific types of content (e.g., only chunked embeddings or specific manuals).
It constructs document nodes and generates synthetic QA pairs using RagDatasetGenerator.
Each QA pair contains a question and its expected reference chunk IDs for retrieval evaluation,
such as hit rate, precision, recall, MRR, etc.
Args:
num_questions (int): Number of synthetic questions to generate per chunk.
embedding_mode_filter (str, optional): If provided, only includes nodes with this embedding mode
(e.g., "chunked" or "full").
source_file_filter (str, optional): If provided, only includes nodes whose 'source_file' metadata
contains this string (e.g., a manual code like "MF-194").
Returns:
List[GeneratedQuestionAnswerPair]: A list of QA entries with queries and expected reference chunks.
"""
if not ENABLE_QA_DATASET_GENERATION:
print(
"\033[94m[INFO]\033[0m Synthetic QA dataset generation is currently disabled.\n"
"This dataset provides ground truth answers needed to evaluate retrieval metrics "
"(Hit Rate, MRR, Precision, Recall, NDCG). Without it, these metrics cannot be computed.\n\n"
"To enable generation, set `ENABLE_QA_DATASET_GENERATION=true` in your environment variables. "
"You can also use `QA_SOURCE_FILE_FILTER` or `QA_EMBEDDING_MODE_FILTER` to limit the scope."
)
return []
if index is None:
raise RuntimeError(
"Index is not loaded. Ensure ChromaDB collection is connected."
)
# Access nodes directly from ChromaVectorStore
vector_store = getattr(index, "_vector_store", None)
if not isinstance(vector_store, ChromaVectorStore):
raise RuntimeError("This QA generator only supports ChromaVectorStore.")
# Retrieve all node ids and then nodes from the ChromaDB index
all_node_ids = vector_store._collection.get()["ids"]
all_nodes = vector_store.get_nodes(all_node_ids)
# dd(all_nodes)
# TEMP DEBUGGING BLOCK:
print(
f"\033[90m[DEBUG]\033[0m Total nodes retrieved from ChromaVectorStore: {len(all_nodes)}"
)
for i, node in enumerate(all_nodes[:3]): # Print first 3 nodes
print(f"\033[90m[DEBUG]\033[0m Node {i} metadata: {node.metadata}")
# Apply optional filters
filtered_nodes = []
for node in all_nodes:
metadata = node.metadata or {}
if (
embedding_mode_filter
and metadata.get("embedding_mode") != embedding_mode_filter
):
continue
source_field = metadata.get("source_file", "")
# Fallback: infer from custom_id if missing (for full mode)
if not source_field:
custom_id = getattr(node, "node_id", "") or getattr(node, "id_", "")
if custom_id:
base = custom_id.split("_page_")[0].strip()
if base:
source_field = f"{base}.md"
# Use substring matching for source_file_filter
if (
source_file_filter
and source_file_filter.lower() not in source_field.lower()
):
continue
filtered_nodes.append(node)
# dd(filtered_nodes)
print(
f"\033[90m[DEBUG]\033[0m Using {len(filtered_nodes)} filtered nodes from ChromaDB for QA generation."
)
if not filtered_nodes:
raise RuntimeError("No nodes matched the specified filters.")
generator = RagDatasetGenerator(
nodes=filtered_nodes,
num_questions_per_chunk=num_questions,
)
return safe_generate_dataset(generator)
def find_closest_qa_query(
user_query: str, qa_lookup: dict, threshold: Optional[float] = None
):
"""
Find the closest matching query in the QA lookup using semantic similarity.
This function compares the user's query against the keys in `qa_lookup` by
computing cosine similarity between their OpenAI embeddings. It selects the
most semantically similar QA question above a given threshold.
Reason:
The Retriever Evaluator of LlamaIndex works by comparing retrieved chunk IDs
against ground-truth expected IDs derived from a synthetic QA dataset,
which are keyed by exact question strings.
However, exact string matching is too brittle for synthetic QA evaluation.
The user's phrasing is unlikely to match generated questions exactly.
Semantic (fuzzy) matching ensures we can align the user's intent with
the most relevant synthetic QA example to evaluate retrieval accuracy,
even when the query is paraphrased or reworded.
This approach improves robustness of evaluation metrics like Hit Rate,
MRR, Precision, Recall, and NDCG — especially when working with
small benchmark manuals like MF-194 that help avoid OpenAI rate limits.
Args:
user_query (str): The query submitted by the user.
qa_lookup (dict): Mapping of QA questions to expected node IDs.
threshold (float, optional): Minimum cosine similarity required for a match.
If None, uses QA_MATCH_THRESHOLD from .env.
Returns:
tuple[str, list[str]]: The matched QA question and its expected IDs,
or (None, None) if no match meets the threshold.
"""
if not qa_lookup:
return None, None
if threshold is None:
threshold = QA_MATCH_THRESHOLD
user_vec = embed_model.get_text_embedding(user_query)
user_vec = np.array(user_vec).reshape(1, -1)
best_match = None
best_score = -1
print("\n\033[90m[DEBUG]\033[0m Cosine similarity scores to each QA:")
for known_query in qa_lookup.keys():
known_vec = embed_model.get_text_embedding(known_query)
known_vec = np.array(known_vec).reshape(1, -1)
score = cosine_similarity(user_vec, known_vec)[0][0]
print(f" → {score:.4f} | {known_query[:80]}...")
if score > best_score:
best_score = score
best_match = known_query
print(f"\033[90m[DEBUG]\033[0m Best match score: {best_score:.4f}")
print(f"\033[90m[DEBUG]\033[0m Best matched QA: {best_match}")
if best_score >= threshold:
return best_match, qa_lookup[best_match]
return None, []
# Log top-k results with score and metadata
def log_top_k_results(nodes, k=5):
ANSI_BLUE = "\033[94m"
ANSI_GREEN = "\033[92m"
ANSI_GRAY = "\033[90m"
ANSI_RESET = "\033[0m"
print(
f"\n{ANSI_BLUE}[INFO]{ANSI_RESET} Top {min(k, len(nodes))} Retrieved Chunks:\n"
)
for idx, node in enumerate(nodes[:k], 1):
score = getattr(node, "score", "N/A")
node_id = getattr(node, "id_", "Unknown")
metadata = node.metadata or {}
model = metadata.get("model", "N/A")
tokens = metadata.get("token_count", "N/A")
source_file = metadata.get("source_file", "N/A")
snippet = shorten(str(getattr(node, "text", "")), width=100, placeholder="...")
print(f"{ANSI_GREEN}[Node {idx}]{ANSI_RESET}")
print(f" ├─ ID: {node_id}")
print(f" ├─ Score: {score}")
print(f" ├─ Model: {model}")
print(f" ├─ Tokens: {tokens}")
print(f" ├─ File: {source_file}")
print(f' └─ Content Snippet: {ANSI_GRAY}"{snippet}"{ANSI_RESET}\n')
# Debug content comparison: fallback from metadata["document"] or metadata["documents"]
doc_fallback = metadata.get("document") or metadata.get("documents")
if not getattr(node, "text", "").strip():
print(
f" └─ Content Snippet (metadata.document): {ANSI_GRAY}[EMPTY]{ANSI_RESET}\n"
)
else:
doc_snippet = shorten(doc_fallback or "", width=100, placeholder="...")
print(
f' └─ Content Snippet (metadata.document): {ANSI_GRAY}"{doc_snippet}"{ANSI_RESET}\n'
)
def summarize_eval_data(eval_data):
"""
Computes key statistics, response quality metrics, and averaged retrieval metrics
from the evaluation dataset.
Returns:
dict: Summary including average top-k score, most common elements,
averaged retriever metrics (hit_rate, precision, etc.),
and response evaluation metrics.
"""
summary = {
"total_queries": len(eval_data),
"average_top_k_score": 0.0,
"average_response_score": None,
"response_pass_rate": None,
"common_response_feedback": [],
"most_common_chunks": [],
"most_common_sources": [],
"most_common_models": [],
"matched_manual_queries": 0,
"unmatched_manual_queries": 0,
}
scores = []
response_scores = []
response_passes = []
feedback_counter = Counter()
chunk_counter = Counter()
source_counter = Counter()
model_counter = Counter()
metrics_accumulator = {
"hit_rate": [],
"mrr": [],
"precision": [],
"recall": [],
"ap": [],
"ndcg": [],
}
for entry in eval_data:
if entry.get("matched_manual") is True:
summary["matched_manual_queries"] += 1
else:
summary["unmatched_manual_queries"] += 1
for result in entry.get("top_k_results", []):
try:
score = float(result.get("score", 0))
scores.append(score)
except ValueError:
continue
chunk_id = result.get("id")
source_file = result.get("source_file", "N/A")
model = result.get("model", "N/A")
chunk_counter[chunk_id] += 1
source_counter[source_file] += 1
model_counter[model] += 1
# Aggregate retrieval metrics
retrieval_metrics = entry.get("retriever_metrics", {})
if isinstance(retrieval_metrics, dict):
for metric in metrics_accumulator.keys():
val = retrieval_metrics.get(metric)
if isinstance(val, (float, int, Decimal)):
metrics_accumulator[metric].append(val)
# Aggregate response quality metrics
response = entry.get("response_quality", {})
if isinstance(response, dict):
score = response.get("score")
if isinstance(score, (float, int)):
response_scores.append(score)
passed = response.get("passing")
if isinstance(passed, bool):
response_passes.append(passed)
feedback = response.get("feedback")
if feedback:
feedback_counter[feedback] += 1
# Compute summary stats
if scores:
summary["average_top_k_score"] = round(mean(scores), 4)
if response_scores:
summary["average_response_score"] = round(mean(response_scores), 4)
if response_passes:
pass_rate = sum(response_passes) / len(response_passes)
summary["response_pass_rate"] = round(pass_rate, 4)
if feedback_counter:
summary["common_response_feedback"] = feedback_counter.most_common(3)
for metric, values in metrics_accumulator.items():
if values:
summary[f"average_{metric}"] = round(mean(values), 4)
summary["most_common_chunks"] = chunk_counter.most_common(5)
summary["most_common_sources"] = source_counter.most_common(5)
summary["most_common_models"] = model_counter.most_common(5)
return summary
def group_chunks_for_synthesis(
nodes, group_field="parent_id", min_size=1, max_size=6, ordered=True
):
grouped = defaultdict(list)
for node in nodes:
group_id = node.metadata.get(group_field)
if group_id:
grouped[group_id].append(node)
synthesis_units = []
for group_id, chunks in grouped.items():
if not (min_size <= len(chunks) <= max_size):
continue
if ordered:
chunks.sort(key=lambda x: x.metadata.get("chunk_index", 0))
merged_text = "\n".join(chunk.text for chunk in chunks if chunk.text)
synthesis_units.append((group_id, merged_text))
return synthesis_units
class LLMResponseWrapper:
"""
Simple wrapper to make a plain string `response_text` compatible with LlamaIndex's
response evaluators, which expect a `.response` attribute on the response object.
This is useful when you are using raw LLM completions (like OpenAI.complete())
and want to evaluate the response using:
- QueryResponseEvaluator.evaluate_response()
- FaithfulnessEvaluator.evaluate_response()
- AnswerRelevancyEvaluator.evaluate_response()
Example:
wrapper = LLMResponseWrapper("This is a response.")
evaluator.evaluate_response(query, wrapper)
"""
def __init__(self, response: str, source_nodes=None):
self.response = response
self.source_nodes = source_nodes or []
@cl.set_starters
async def set_starters():
"""
Define suggested chat starters for new users.
These will appear as buttons in the UI before the first message.
"""
return [
cl.Starter(
label="Tell me about Fe/Cu ion systems",
message="Can you explain how Fe/Cu ion systems work on ships?",
icon="./public/wrench-starter.svg"
),
cl.Starter(
label="Browse service manuals",
message="Show me the available marine service manuals.",
icon="./public/book-starter.svg"
),
cl.Starter(
label="What's the weather like in Singapore?",
message="What's the weather like in Singapore right now?",
icon="./public/weather-starter.svg"
)
]
@cl.on_chat_start
async def start():
print(f"\033[90m[DEBUG]\033[0m Top-K retrieval log threshold: {TOP_K_RESULTS}")
# Initialize evaluation dataset for the session
cl.user_session.set("eval_data", [])
cl.user_session.set("eval_start_time", datetime.now().isoformat())
# Initialize placeholder for synthetic QA lookup - Will be lazily populated on first semantic query if benchmarking is needed.
cl.user_session.set("qa_lookup", None)
if ENABLE_USER_ENV:
# Retrieve user-specific environment variables
user_env = cl.user_session.get("env")
openai_token = user_env.get("OPENAI_API_KEY")
if not openai_token:
await cl.Message(
content="No OpenAI API key was provided. Please restart and enter your key to proceed."
).send()
return
else:
# Retrieve project environment variables
openai_token = os.getenv("OPENAI_API_KEY")
# Store in session for downstream use
cl.user_session.set("openai_token", openai_token)
# Set up models dynamically
llm = OpenAI(model="gpt-4o", temperature=0.0, api_key=openai_token)
embed_model = OpenAIEmbedding(model="text-embedding-3-small", api_key=openai_token)
Settings.llm = llm
Settings.embed_model = embed_model
# Check for short-term context toggle
enable_context = os.getenv("ENABLE_CHAT_HISTORY_CONTEXT", "false").lower() == "true"
cl.user_session.set("enable_chat_history", enable_context)
if enable_context:
cl.user_session.set("chat_history", []) # Initialize empty list
## Commented out because otherwise the starters were ignored
# await cl.Message(
# author="MarinEnGPT",
# content="Hello! I am MarinEnGPT, an AI Assistant specialized in Marine Engineering Service Manuals.\n\nSelect one of the suggestions below to get started.",
# ).send()
@cl.on_chat_resume
async def on_chat_resume(thread):
"""
Restore the previous chat session when a user returns.
Args:
thread (ThreadDict): A dictionary containing messages and metadata from the previous session.
"""
print(
f"\033[90m[DEBUG]\033[0m Resuming thread with {len(thread['steps'])} messages."
)
# Reinitialize session state
cl.user_session.set("chat_history", [])
cl.user_session.set("eval_data", [])
cl.user_session.set("eval_start_time", datetime.now().isoformat())
# Retrieve OpenAI token
if ENABLE_USER_ENV:
user_env = cl.user_session.get("env", {})
openai_token = user_env.get("OPENAI_API_KEY")
else:
openai_token = os.getenv("OPENAI_API_KEY")
cl.user_session.set("openai_token", openai_token)
# Restore short-term chat history if enabled
enable_context = os.getenv("ENABLE_CHAT_HISTORY_CONTEXT", "false").lower() == "true"
cl.user_session.set("enable_chat_history", enable_context)
if enable_context:
restored_chat = []
for step in thread["steps"]:
if step.get("type") == "user_message":
restored_chat.append(
{"role": "user", "content": step.get("output", "")}
)
elif step.get("type") == "assistant_message":
restored_chat.append(
{"role": "assistant", "content": step.get("output", "")}
)
cl.user_session.set("chat_history", restored_chat)
await cl.Message(
author="System",
content="Welcome back. Your previous conversation has been restored.",
).send()
@cl.action_callback("view_as_image")
async def view_as_image(action: cl.Action):
"""Callback to display references as images."""
references = action.payload.get("references", [])
IMAGE_BASE_PATH = os.getenv("IMAGE_BASE_PATH", "./data/images/")
seen_pages = set()
elements = []
for idx, ref in enumerate(references, 1):
node_id = ref.get("id")
# Normalize to base page ID: strip "_chunk_#" if present
base_id = re.sub(r"_chunk_\d+$", "", node_id)
if base_id in seen_pages:
continue # Skip duplicates
seen_pages.add(base_id)
# Path: ./data/images/{group_id}/{base_id}.png
group_id = base_id.split("_page_")[0]
image_path = os.path.join(IMAGE_BASE_PATH, group_id, f"{base_id}.png")
if os.path.exists(image_path):
elements.append(
cl.Image(
path=image_path,
name=f"Reference Image {idx}",
display="inline",
size="medium",
)
)
else:
await cl.Message(
content=f"Warning: Image for reference {idx} not found at {image_path}."
).send()
if elements:
await cl.Message(
content="Here are the references as images:", elements=elements
).send()
else:
await cl.Message(
content="No images available for the selected references."
).send()
@cl.action_callback("view_as_markdown")
async def view_as_markdown(action: cl.Action):
"""Callback to display references as markdown."""
references = action.payload.get("references", [])
for idx, ref in enumerate(references, 1):
source_file = ref.get("source_file", "Unknown source")
document_snippet = ref.get("text", "")[:500] # Adjust snippet length as needed
reference_message = f"**Reference {idx}:**\n\n"
reference_message += f"Source: `{source_file}`\n\n"
reference_message += f'Snippet: "{document_snippet}..."\n\n'
await cl.Message(content=reference_message).send()
@cl.action_callback("skip_references")
async def skip_references(action: cl.Action):
"""Callback to handle skipping references."""
await cl.Message(content="References have been skipped.").send()
def format_eval_summary(summary: dict) -> list[str]:
lines = [
f"Total Queries: {summary.get('total_queries', 0)}",
f"Matched Manual Queries: {summary.get('matched_manual_queries', 0)}",
f"Unmatched Manual Queries: {summary.get('unmatched_manual_queries', 0)}",
f"Average Top-K Score: {summary.get('average_top_k_score', 0.0)}",
]
if summary.get("average_response_score") is not None:
lines.append(f"Average Response Score: {summary['average_response_score']}")
if summary.get("response_pass_rate") is not None:
percent = round(summary["response_pass_rate"] * 100, 2)
lines.append(f"Response Pass Rate: {percent}%")
if summary.get("common_response_feedback"):
lines.append("Most Common Feedback:")
for fb, count in summary["common_response_feedback"]:
lines.append(f" - {fb} ({count}x)")
# Add retrieval metrics if they exist
metric_keys = ["hit_rate", "mrr", "precision", "recall", "ap", "ndcg"]
has_metrics = any(f"average_{k}" in summary for k in metric_keys)
if has_metrics:
lines.append("\nAverage Retrieval Metrics:")
for metric in metric_keys:
key = f"average_{metric}"