-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrun_SQuAI.py
More file actions
1889 lines (1587 loc) · 75.9 KB
/
run_SQuAI.py
File metadata and controls
1889 lines (1587 loc) · 75.9 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
#!/usr/bin/env python3
"""
Enhanced 4-Agent RAG System with Question Splitting and Parallel Processing
- Agent 1: Question Splitter
- Agent 2: Answer Generator from abstracts
- Agent 3: Document Evaluator
- Agent 4: Final Answer Generator with citations
"""
import plyvel
import argparse
import json
import time
import datetime
import os
from tqdm import tqdm
import logging
import numpy as np
import random
import string
import re
from typing import List, Tuple, Dict, Any, Optional
import sqlite3
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed, ProcessPoolExecutor
import multiprocessing as mp
from performance_monitor import monitor, time_block
# Import configuration
from config import E5_INDEX_DIR, BM25_INDEX_DIR, DB_PATH
# Your existing logging setup (unchanged)
def get_unique_log_filename():
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
random_str = "".join(random.choices(string.ascii_lowercase + string.digits, k=6))
return f"logs/enhanced_4agent_rag_{timestamp}_{random_str}.log"
os.makedirs("logs", exist_ok=True)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
handlers=[logging.FileHandler(get_unique_log_filename()), logging.StreamHandler()],
)
logger = logging.getLogger("Enhanced_4Agent_RAG")
# Import the hybrid retriever components
from hybrid_retriever import Retriever
class QuestionSplitter:
"""
Agent 1: Intelligent Question Splitting Agent
Detects complex queries with multiple sub-questions and splits them appropriately
"""
def __init__(self, agent_model):
self.agent = agent_model
logger.info("Agent 1 (Question Splitter) initialized")
def _create_splitting_prompt(self, query: str) -> str:
"""Create prompt for question splitting analysis (JSON output)"""
return f"""You are an intelligent question analyzer. Decide whether a user query should be split into multiple sub-questions for separate retrieval.
Split when:
- The query asks about multiple distinct topics joined by "and" / "also"
- The query asks to compare concepts (e.g., "difference between X and Y")
- The query mixes a comparison with an evaluation (e.g., "which is better")
- The query asks about a concept AND its implications, effects, or applications
Do not split:
- Simple definitional questions ("What is X?")
- Multiple aspects of the same concept ("How does attention work in transformers")
- Short clarifications
Output strictly valid JSON in this exact schema, and nothing else:
{{"split": true|false, "sub_questions": ["...", "..."]}}
Rules:
- If "split" is false, "sub_questions" must be an empty list.
- If "split" is true, "sub_questions" must contain 2 or more self-contained questions.
- For "compare X and Y and which is better" style queries, produce three sub-questions: explain X, explain Y, and the comparison/evaluation.
Examples:
Query: "What is reinforcement learning?"
{{"split": false, "sub_questions": []}}
Query: "What is the difference between dense and sparse retrieval and which is better for RAG?"
{{"split": true, "sub_questions": ["What is dense retrieval?", "What is sparse retrieval?", "Which retrieval method is better suited for RAG systems?"]}}
Now analyze this query and output only the JSON object:
Query: "{query}"
"""
def analyze_and_split(self, query: str) -> Tuple[bool, List[str]]:
"""
Analyze query and split into sub-questions if beneficial
Always uses LLM for accurate analysis
Returns:
Tuple of (should_split: bool, sub_questions: List[str])
"""
# Handle time_block if it exists (for compatibility)
try:
# Check if time_block is available
if 'time_block' in globals():
with time_block("agent1_question_splitting"):
return self._perform_split_analysis(query)
else:
return self._perform_split_analysis(query)
except:
# Fallback if time_block causes any issues
return self._perform_split_analysis(query)
def _perform_split_analysis(self, query: str) -> Tuple[bool, List[str]]:
"""
Internal method to perform the actual split analysis using LLM
"""
logger.info(f"Agent 1: Analyzing query for splitting: {query}")
# Basic validation - only skip extremely short queries
if len(query.strip()) < 10: # Less than 10 characters is too short
logger.info("Query too short for meaningful splitting")
return False, []
try:
# Always use LLM for analysis (no heuristics)
logger.info("Using LLM to analyze if query should be split...")
prompt = self._create_splitting_prompt(query)
response = self.agent.generate(prompt)
# Parse response
should_split, sub_questions = self._parse_splitting_response(response, query)
if should_split:
logger.info(f"Agent 1: LLM decided to split into {len(sub_questions)} sub-questions: {sub_questions}")
else:
logger.info("Agent 1: LLM decided no splitting needed")
return should_split, sub_questions
except Exception as e:
logger.error(f"Error in LLM splitting analysis: {e}", exc_info=True)
# On error, don't split
return False, []
def _parse_splitting_response(self, response: str, original_query: str) -> Tuple[bool, List[str]]:
"""Parse the LLM JSON response for splitting decision.
Expected schema: {"split": bool, "sub_questions": [str, ...]}
On any failure, logs the raw response and returns (False, []) so the
pipeline safely falls back to treating the query as a single question.
"""
raw = (response or "").strip()
if not raw:
logger.warning("Agent 1: Empty response from LLM")
return False, []
# Extract the first JSON object from the response. Robust to leading/
# trailing prose, code fences, or "Output:" prefixes the model may add.
json_match = re.search(r"\{[\s\S]*?\}", raw)
if not json_match:
logger.warning(f"Agent 1: No JSON object found in response. Raw: {raw[:300]!r}")
return False, []
try:
parsed = json.loads(json_match.group(0))
except json.JSONDecodeError as e:
logger.warning(f"Agent 1: JSON decode failed ({e}). Raw: {raw[:300]!r}")
return False, []
should_split = bool(parsed.get("split", False))
sub_questions = parsed.get("sub_questions", [])
if not isinstance(sub_questions, list):
logger.warning(f"Agent 1: sub_questions is not a list: {sub_questions!r}")
return False, []
if not should_split:
return False, []
# Normalize and validate
valid_questions = []
for q in sub_questions:
if not isinstance(q, str):
continue
q = q.strip()
if len(q) > 10:
if not q.endswith("?"):
q = q + "?"
valid_questions.append(q)
if len(valid_questions) < 2:
logger.info(
f"Agent 1: split=true but only {len(valid_questions)} valid sub-questions; keeping original"
)
return False, []
return True, valid_questions
def _quick_split_check(self, query: str) -> bool:
"""
DEPRECATED: Keep for backward compatibility but not used
This method is kept in case other parts of the code reference it
"""
# Always return False since we're using LLM directly now
return False
class PaperTitleExtractor:
"""
Utility class for extracting paper titles from document text
IMPROVED: Handles LevelDB storage format where title is on second line
"""
@staticmethod
def extract_title_from_text(doc_text: str, doc_id: str) -> str:
"""
Extract paper title from document text using multiple patterns
IMPROVED: Handles "Content for [paper_id]:\n[Title]" format from LevelDB
"""
try:
# Method 1: NEW - Handle LevelDB format: "Content for [paper_id]:\n[Title]"
leveldb_pattern = r"Content for [^:]*:\s*\n([^\n]+)"
match = re.search(leveldb_pattern, doc_text)
if match:
title_candidate = match.group(1).strip()
# Validate it looks like a title (not abstract or other content)
if (
len(title_candidate) > 10
and len(title_candidate) < 300
and not title_candidate.lower().startswith(
("abstract:", "introduction:", "the abstract", "in this", "we ")
)
):
logger.debug(
f"Extracted title from LevelDB format: {title_candidate[:50]}..."
)
return title_candidate
# Method 2: Look for title in first few lines (for direct title format)
lines = doc_text.split("\n")
for i, line in enumerate(lines[:5]):
line = line.strip()
# Skip empty lines and common headers
if not line or line.lower().startswith(
("content for", "time taken", "opening")
):
continue
# Check if this line looks like a title
if (
len(line) > 10
and len(line) < 300
and not line.lower().startswith(
(
"abstract:",
"introduction:",
"the abstract",
"in this",
"we ",
"this paper",
"{",
)
)
and not re.match(r"^\d+", line) # Not starting with numbers
and not line.endswith(":") # Not a section header
and line.count(" ") >= 2
): # At least 3 words
logger.debug(f"Extracted title from line {i+1}: {line[:50]}...")
return line
# Method 3: Look for "Content for [paper_id]:" pattern (legacy)
content_pattern = r"Content for [^:]*:\s*\n([^\n]+)"
match = re.search(content_pattern, doc_text)
if match:
title_candidate = match.group(1).strip()
if len(title_candidate) > 10 and len(title_candidate) < 300:
title_candidate = re.sub(r'^["\']|["\']$', "", title_candidate)
title_candidate = re.sub(r"^\W+|\W+$", "", title_candidate)
if len(title_candidate) > 10:
return title_candidate
# Method 4: Look for "Title. {" pattern
title_brace_pattern = r"^([^.]+)\.\s*\{"
match = re.search(title_brace_pattern, doc_text.strip(), re.MULTILINE)
if match:
title_candidate = match.group(1).strip()
if (
len(title_candidate) > 10
and len(title_candidate) < 300
and not title_candidate.lower().startswith(
("the ", "this ", "in ", "we ", "abstract", "introduction")
)
):
title_candidate = re.sub(r'^["\']|["\']$', "", title_candidate)
if len(title_candidate) > 10:
return title_candidate
# Method 5: Extract from cleaned first sentence
clean_text = re.sub(r"\{[^}]*\}", "", doc_text)
clean_text = re.sub(r"Content for [^:]+:\s*", "", clean_text)
clean_text = clean_text.strip()
first_sentence = clean_text.split("\n")[0].strip()
if ". {" in first_sentence:
first_sentence = first_sentence.split(". {")[0].strip()
elif ". " in first_sentence and len(first_sentence.split(". ")[0]) < 200:
first_sentence = first_sentence.split(". ")[0].strip()
if (
len(first_sentence) > 15
and len(first_sentence) < 300
and not first_sentence.lower().startswith(
(
"content for",
"time taken",
"opening",
"the ",
"this ",
"in ",
"we ",
"abstract",
"introduction",
)
)
and not re.match(r"^\d+", first_sentence)
):
return first_sentence
# Method 6: Try JSON metadata
if "{" in doc_text and '"title"' in doc_text:
try:
json_match = re.search(r'\{.*?"title".*?\}', doc_text, re.DOTALL)
if json_match:
json_str = json_match.group(0)
metadata = json.loads(json_str)
if "title" in metadata and len(metadata["title"]) > 10:
return metadata["title"]
except:
pass
# Fallback: use first substantial line
for line in lines[:5]:
line = line.strip()
if len(line) > 15 and len(line) < 200:
return line[:150] + "..." if len(line) > 150 else line
return f"Document {doc_id}"
except Exception as e:
logger.debug(f"Error extracting title for {doc_id}: {e}")
return f"Document {doc_id}"
@staticmethod
def format_title_for_log(title: str, max_length: int = 80) -> str:
"""Format title for logging with length limit"""
if len(title) <= max_length:
return title
return title[: max_length - 3] + "..."
@staticmethod
def extract_paper_sections(
full_text: str, max_chars_per_section: int = 10000
) -> Dict[str, str]:
"""
Extract key sections from full paper text for better context utilization
Args:
full_text: The full paper text
max_chars_per_section: Limit for introduction and conclusion extraction (abstract is kept full)
Returns:
Dict with 'title', 'abstract', 'introduction', 'conclusion' keys
Note: Abstract is returned in full (no artificial limits)
"""
sections = {}
# Extract title (first line after "Content for")
title_match = re.search(r"Content for [^:]*:\s*\n([^\n]+)", full_text)
if title_match:
sections["title"] = title_match.group(1).strip()
# Extract abstract (keep full abstract - they're naturally short and important)
abstract_match = re.search(
r"abstract:\s*(.+?)(?:\n\n|\nintroduction|\nrelated work|\nmethodology)",
full_text,
re.IGNORECASE | re.DOTALL,
)
if abstract_match:
abstract_text = abstract_match.group(1).strip()
# Keep full abstract - no artificial limits since they're naturally concise
sections["abstract"] = abstract_text
# Extract introduction (can be long and informative)
intro_match = re.search(
r"(?:^|\n)introduction[:\n]\s*(.+?)(?:\n\n[A-Z]|\nrelated work|\nmethodology|\nconclusion)",
full_text,
re.IGNORECASE | re.DOTALL,
)
if intro_match:
intro_text = intro_match.group(1).strip()
sections["introduction"] = intro_text[:max_chars_per_section]
# Extract conclusion (moderate length, important summary)
conclusion_match = re.search(
r"(?:^|\n)conclusion[s]?[:\n]\s*(.+?)(?:\n\n[A-Z]|\nreferences|\nacknowledgments|$)",
full_text,
re.IGNORECASE | re.DOTALL,
)
if conclusion_match:
conclusion_text = conclusion_match.group(1).strip()
sections["conclusion"] = conclusion_text[:max_chars_per_section]
return sections
class EnhancedCitationHandler:
"""Enhanced citation handler with proper metadata extraction and context passages"""
# Class-level cache: resolved index_dir -> {paper_id: metadata}.
# The arXiv metadata is read-only and identical across queries, so we parse
# the (potentially multi-GB) JSONL files at most once per process. Without
# this, every call to answer_query was re-parsing them, costing ~82s/query
# on the demo (BM25_INDEX_DIR contains a 7.5 GB corpus.jsonl).
_arxiv_papers_cache: Dict[str, Dict] = {}
def __init__(self, index_dir: str = "test_index"):
self.doc_to_citation = {}
self.citation_to_doc = {}
self.next_citation_num = 1
self.index_dir = Path(index_dir)
# Load arXiv papers for better metadata (cached across instances)
self.arxiv_papers = self._get_or_load_arxiv_papers()
# Connect to metadata database
self.metadata_db = self._connect_metadata_db()
def _get_or_load_arxiv_papers(self):
try:
key = str(self.index_dir.resolve())
except Exception:
key = str(self.index_dir)
cache = EnhancedCitationHandler._arxiv_papers_cache
if key not in cache:
t0 = time.time()
cache[key] = self._load_arxiv_papers()
logger.info(
f"Loaded arxiv_papers metadata from {key}: "
f"{len(cache[key])} entries in {time.time() - t0:.1f}s (cached)"
)
return cache[key]
def _connect_metadata_db(self):
"""Connect to metadata database"""
try:
import sqlite3
db_path = self.index_dir / "index_store.db"
conn = sqlite3.connect(str(db_path))
conn.row_factory = sqlite3.Row
return conn
except:
return None
def _load_arxiv_papers(self):
"""Load arXiv papers for metadata extraction"""
papers = {}
try:
jsonl_files = list(self.index_dir.glob("*.jsonl"))
for jsonl_file in jsonl_files:
with open(jsonl_file, "r") as f:
for line in f:
try:
paper = json.loads(line.strip())
paper_id = paper.get("paper_id", "")
metadata = paper.get("metadata", {})
title = metadata.get("title", "Unknown Title")
authors = metadata.get("authors", "Unknown")
# Extract year from versions
year = "Unknown"
versions = paper.get("versions", [])
if versions:
created = versions[0].get("created", "")
year_match = re.search(r"(\d{4})", created)
if year_match:
year = year_match.group(1)
# Format authors properly
if "authors_parsed" in paper:
authors_list = paper["authors_parsed"]
if authors_list and len(authors_list) > 0:
first_author = authors_list[0]
if len(first_author) >= 2:
formatted_author = (
f"{first_author[0]}, {first_author[1][0]}."
if first_author[1]
else first_author[0]
)
if len(authors_list) > 1:
authors = f"{formatted_author} et al."
else:
authors = formatted_author
papers[paper_id] = {
"title": title,
"authors": authors,
"year": year,
"paper_id": paper_id,
"abstract": paper.get("abstract", {}).get("text", ""),
}
except:
continue
return papers
except:
return {}
def _extract_document_title_improved(self, doc_text: str, doc_id: str) -> str:
"""Use the PaperTitleExtractor for consistency"""
return PaperTitleExtractor.extract_title_from_text(doc_text, doc_id)
def _extract_paper_info(
self, doc_text: str, doc_id: str, metadata: Dict = None
) -> Dict:
"""Enhanced paper metadata extraction with improved title extraction"""
paper_info = {
"title": "Unknown Title",
"authors": "Unknown",
"venue": "arXiv",
"year": "Unknown",
"paper_id": doc_id,
}
try:
# Use improved title extraction
paper_info["title"] = self._extract_document_title_improved(
doc_text, doc_id
)
# Extract from JSON in document text
if "{" in doc_text and '"metadata"' in doc_text:
try:
json_match = re.search(r'\{.*?"metadata".*?\}', doc_text, re.DOTALL)
if json_match:
json_str = json_match.group(0)
paper_data = json.loads(json_str)
if "metadata" in paper_data:
meta = paper_data["metadata"]
if "authors" in meta:
paper_info["authors"] = meta["authors"]
if "paper_id" in paper_data:
paper_info["paper_id"] = paper_data["paper_id"]
# Extract year from versions
if "versions" in paper_data and paper_data["versions"]:
created = paper_data["versions"][0].get("created", "")
year_match = re.search(r"(\d{4})", created)
if year_match:
paper_info["year"] = year_match.group(1)
logger.debug(
f"Extracted metadata from JSON in text for {doc_id}"
)
except Exception as e:
logger.debug(f"JSON parsing failed for {doc_id}: {e}")
# Match with loaded arXiv papers by paper_id
if doc_id in self.arxiv_papers:
arxiv_data = self.arxiv_papers[doc_id]
# Update info but keep improved title if it's better
if (
paper_info["title"] == "Unknown Title"
or paper_info["title"] == f"Document {doc_id}"
):
paper_info["title"] = arxiv_data["title"]
if paper_info["authors"] == "Unknown":
paper_info["authors"] = arxiv_data["authors"]
if paper_info["year"] == "Unknown":
paper_info["year"] = arxiv_data["year"]
logger.debug(
f"Enhanced metadata for {doc_id} from arXiv papers database"
)
# Final cleanup
if len(paper_info["title"]) > 150:
paper_info["title"] = paper_info["title"][:150] + "..."
# Ensure we have a paper_id
if not paper_info["paper_id"]:
paper_info["paper_id"] = doc_id
except Exception as e:
logger.debug(f"Error extracting metadata for {doc_id}: {e}")
return paper_info
def _basic_text_cleaning(self, text: str) -> str:
"""Basic text cleaning for citation context"""
# Remove JSON-like section markers
text = re.sub(r"'section':\s*'[^']*',\s*'text':\s*'", "", text)
text = re.sub(r"^\s*\{.*?'text':\s*'", "", text)
text = re.sub(r"\{[^}]*\}", "", text)
# Remove technical markup
text = re.sub(r"\{\{[^}]+\}\}", "[REF]", text)
text = re.sub(r"\$[^$]+\$", "[MATH]", text)
text = re.sub(r"\\[a-zA-Z]+\{[^}]*\}", "[LATEX]", text)
# Clean whitespace
text = re.sub(r"\s+", " ", text)
text = re.sub(r"\n\s*\n", "\n\n", text)
return text.strip()
def _extract_context_passage(
self, answer_text: str, document_text: str, citation_num: int
) -> str:
"""Extract specific sentence(s) used in the answer plus context"""
try:
# Clean the document text first
try:
from text_cleaner import DocumentTextCleaner
cleaner = DocumentTextCleaner()
clean_doc_text = cleaner.clean_for_citation_matching(document_text)
except ImportError:
clean_doc_text = self._basic_text_cleaning(document_text)
# NEW: Remove the [TOP xxx chars]: and [BOTTOM xxx chars]: prefixes
clean_doc_text = re.sub(r'\[TOP \d+ chars\]:\s*', '', clean_doc_text)
clean_doc_text = re.sub(r'\[BOTTOM \d+ chars\]:\s*', '', clean_doc_text)
# Find all sentences in the clean document
sentences = re.split(r"[.!?]+", clean_doc_text)
sentences = [s.strip() for s in sentences if len(s.strip()) > 15]
# Look for content that appears in the answer near this citation
citation_pattern = f"\\[{citation_num}\\]"
citation_matches = list(re.finditer(citation_pattern, answer_text))
if not citation_matches:
# Fallback: return first few clean sentences
return (
". ".join(sentences[:2]) + "."
if sentences
else clean_doc_text[:200] + "..."
)
# For each citation, find the preceding text that likely came from this document
relevant_sentences = set()
for match in citation_matches:
# Get text before this citation (up to 150 chars back)
start_pos = max(0, match.start() - 150)
context_text = answer_text[start_pos : match.start()].strip()
# Find the sentence in context_text that likely came from the document
context_sentences = re.split(r"[.!?]+", context_text)
for context_sent in context_sentences[
-2:
]: # Last 1-2 sentences before citation
if len(context_sent.strip()) < 15:
continue
# Find similar sentences in the document
context_words = set(context_sent.lower().split())
for i, doc_sent in enumerate(sentences):
doc_words = set(doc_sent.lower().split())
# Check word overlap
overlap = len(context_words.intersection(doc_words))
overlap_ratio = overlap / max(len(context_words), 1)
if overlap_ratio > 0.25 or overlap > 4: # Good match
# Add this sentence plus context (±1 sentence)
start_idx = max(0, i - 1)
end_idx = min(len(sentences), i + 2)
for j in range(start_idx, end_idx):
relevant_sentences.add(j)
if relevant_sentences:
# Sort and build context passage
sorted_indices = sorted(relevant_sentences)
context_parts = [sentences[i] for i in sorted_indices]
result = ". ".join(context_parts) + "."
# Limit length
if len(result) > 500:
result = result[:500] + "..."
return result
# Fallback: return beginning of clean document
fallback = ". ".join(sentences[:2]) + "."
return fallback if len(fallback) < 300 else fallback[:300] + "..."
except Exception as e:
logger.debug(f"Error extracting context passage: {e}")
# Simple fallback with basic cleaning
clean_text = self._basic_text_cleaning(document_text)
return clean_text[:200] + "..." if len(clean_text) > 200 else clean_text
def format_references(self, answer_text: str = None) -> str:
"""Format references with proper metadata and context passages"""
if not self.citation_to_doc:
return ""
# Get all available citations
citations_to_show = set(self.citation_to_doc.keys())
# If answer text provided, filter to only used citations
if answer_text:
citation_matches = re.findall(r"\[(\d+)\]", answer_text)
used_citations = set(int(num) for num in citation_matches)
if used_citations:
citations_to_show = used_citations.intersection(
set(self.citation_to_doc.keys())
)
if not citations_to_show:
return ""
references = []
for citation_num in sorted(citations_to_show):
reference=[]
doc_info = self.citation_to_doc[citation_num]
paper_info = doc_info["paper_info"]
# Format academic reference
reference.append(f"[{citation_num}]")
# Add title in quotes
title = paper_info["title"].replace('Title:', "").replace('"', "").replace("'", "")
reference.append(title)
# Add venue and year with paper ID
if paper_info.get("paper_id") and paper_info["paper_id"] != "Unknown":
if str(paper_info["paper_id"]).startswith("arXiv:"):
reference.append(paper_info['paper_id'])
else:
reference.append(f"arXiv:{paper_info['paper_id']}")
else:
reference.append(f"{paper_info['venue']}")
# Add context passage with actual sentences used
if answer_text:
context_passage = self._extract_context_passage(
answer_text, doc_info["text"], citation_num
)
else:
context_passage = (
doc_info["text"][:300] + "..."
if len(doc_info["text"]) > 300
else doc_info["text"]
)
reference.append(context_passage)
references.append(reference)
return references
def add_document(self, doc_text: str, doc_id: str, metadata: Dict = None) -> int:
"""Add a document and return its citation number"""
if doc_id not in self.doc_to_citation:
citation_num = self.next_citation_num
self.doc_to_citation[doc_id] = citation_num
paper_info = self._extract_paper_info(doc_text, doc_id, metadata)
self.citation_to_doc[citation_num] = {
"doc_id": doc_id,
"paper_info": paper_info,
"text": doc_text,
}
self.next_citation_num += 1
logger.debug(
f"Added document {doc_id} as citation [{citation_num}]: {paper_info['title'][:50]}..."
)
return citation_num
else:
return self.doc_to_citation[doc_id]
def get_citation_map(self) -> Dict[str, int]:
"""Get mapping from doc_id to citation number"""
return self.doc_to_citation.copy()
class Enhanced4AgentRAG:
"""
Enhanced 4-Agent RAG System with Question Splitting, Parallel Processing, and Context Management
"""
def __init__(
self,
retriever,
agent_model=None,
n=0.0,
falcon_api_key=None,
index_dir="test_index",
max_workers=4,
max_context_chars=200000,
):
"""Initialize with enhanced 4-agent architecture and context management"""
self.retriever = retriever
self.n = n
self.index_dir = index_dir
self.max_workers = max_workers
self.max_context_chars = max_context_chars # ~50K tokens; well within Gemma-4-31B's 200K window
logger.info(f"Context limit set to {max_context_chars} characters")
# Initialize agents
if isinstance(agent_model, str):
if "falcon" in agent_model.lower() and falcon_api_key:
from api_agent import FalconAgent
self.agent1 = FalconAgent(falcon_api_key) # Question Splitter
self.agent2 = FalconAgent(falcon_api_key) # Answer Generator
self.agent3 = FalconAgent(falcon_api_key) # Document Evaluator
self.agent4 = FalconAgent(falcon_api_key) # Final Answer Generator
logger.info("Using Falcon agents with API for all four agent roles")
elif os.environ.get("SCADS_API_KEY"):
# Use SCADS AI API for all agents (CPU-friendly, no local GPU needed)
from scads_agent import ScadsAgent
agent = ScadsAgent(model=agent_model)
self.agent1 = agent
self.agent2 = agent
self.agent3 = agent
self.agent4 = agent
logger.info(f"Using ScadsAgent with model {agent_model} for all four agent roles")
else:
from local_agent import LLMAgent
from config import USE_GPU
device = "cuda" if USE_GPU else "cpu"
precision = "bfloat16" if USE_GPU else "float32"
self.agent1 = LLMAgent(agent_model, device=device, precision=precision) # Question Splitter
self.agent2 = LLMAgent(agent_model, device=device, precision=precision) # Answer Generator
self.agent3 = LLMAgent(agent_model, device=device, precision=precision) # Document Evaluator
self.agent4 = LLMAgent(agent_model, device=device, precision=precision) # Final Answer Generator
logger.info(f"Using local LLM agents ({device}) with model {agent_model}")
else:
self.agent1 = agent_model # Question Splitter
self.agent2 = agent_model # Answer Generator
self.agent3 = agent_model # Document Evaluator
self.agent4 = agent_model # Final Answer Generator
logger.info("Using pre-initialized agent for all four agent roles")
# Initialize question splitter
self.question_splitter = QuestionSplitter(self.agent1)
# Thread pool for parallel processing
self.executor = ThreadPoolExecutor(max_workers=max_workers)
# Enhanced pre-warming
logger.info("Enhanced 4-agent pre-warming...")
try:
# Warm up retriever
dummy_abstracts = self.retriever.retrieve_abstracts("test", top_k=1)
logger.info("Retriever pre-warmed")
# Warm up agents
if hasattr(self.agent1, "generate"):
self.agent1.generate("test")
logger.info("All agents pre-warmed")
except Exception as e:
logger.warning(f"Pre-warming had issues: {e}")
def _estimate_tokens(self, text: str) -> int:
"""Rough token estimation: ~4 chars per token"""
return len(text) // 4
def _create_agent2_prompt(self, query, document):
"""Agent-2 prompt: Answer generation from abstracts"""
return f"""You are a reliable AI assistant. Answer the question using the provided document.
Document: {document}
Question: {query}
Answer:"""
def _create_agent3_prompt(self, query, document, answer):
"""Agent-3 prompt: Document evaluation"""
return f"""Evaluate whether a retrieved document is relevant and supportive for answering a question. Given the Document, Question, and an LLM Answer, judge whether both conditions hold:
(1) The Document provides specific information relevant to the Question.
(2) The LLM Answer is grounded in the Document.
Answer with "Yes" or "No".
Document: {document}
Question: {query}
LLM Answer: {answer}
Is this document relevant and supportive for answering the question?"""
def _prepare_documents_for_agent4(
self,
full_texts: List[Tuple[str, str]],
citation_handler,
was_split: bool = False,
) -> List[str]:
"""
Prepare documents for Agent 4 with dynamic context length management
Args:
full_texts: List of (document_text, doc_id) tuples
citation_handler: Citation handler instance
was_split: Whether the original question was split into sub-questions
Returns:
List of formatted document strings ready for the prompt
"""
docs_with_citations = []
total_chars = 0
documents_used = 0
# Dynamic context allocation - top + bottom extraction approach
if was_split:
# Conservative: Target ~4K total per paper
top_chars = 10000 # Top of paper (title, abstract, intro start)
bottom_chars = 6000 # Bottom of paper (conclusion, results)
strategy = "CONSERVATIVE (split questions)"
target_per_paper = "~4K"
else:
# Generous: Target ~8K total per paper
top_chars = 20000 # More from top (title, abstract, intro)
bottom_chars = 12000 # More from bottom (conclusion, results)
strategy = "GENEROUS (single question)"
target_per_paper = "~8K"
logger.info(
f"Preparing documents for Agent 4 (context limit: {self.max_context_chars} chars)"
)
logger.info(
f" Context strategy: {strategy} - targeting {target_per_paper} chars per paper"
)
logger.info(
f" Extraction: TOP({top_chars} chars) + BOTTOM({bottom_chars} chars) + Title"
)
for i, (doc_text, doc_id) in enumerate(full_texts):
# New approach: Extract from top and bottom of paper
condensed_content = []
# Extract title first (if available)
title = PaperTitleExtractor.extract_title_from_text(doc_text, doc_id)
if title and not title.startswith("Document "):
condensed_content.append(f"Title: {title}")
# Remove "Content for [paper_id]:" line and other metadata for cleaner extraction
clean_text = doc_text
# Remove the "Content for" line
clean_text = re.sub(r"Content for [^:]*:\s*\n", "", clean_text)
# Remove any leading whitespace/newlines
clean_text = clean_text.strip()
# TOP EXTRACTION: Get beginning of paper (naturally includes abstract, intro start)
top_text = clean_text[:top_chars]
if len(clean_text) > top_chars:
# Find a good breaking point (end of sentence)
break_point = top_text.rfind(". ")
if (
break_point > top_chars * 0.8
): # If we find a sentence end in the last 20%
top_text = top_text[: break_point + 1]
else:
top_text += "..."
condensed_content.append(f"[TOP {len(top_text)} chars]: {top_text}")
# BOTTOM EXTRACTION: Get end of paper (naturally includes conclusion, results)
if (