-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrag.py
More file actions
561 lines (459 loc) · 17.8 KB
/
rag.py
File metadata and controls
561 lines (459 loc) · 17.8 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
"""
Main RAG pipeline: retrieval and answer generation.
"""
from typing import Dict, List, Optional, Any
import logging
import config
import embeddings
import vector_store
import lang_utils
import translation
import google.generativeai as genai
logger = logging.getLogger(__name__)
if config.LLM_API_KEY:
genai.configure(api_key=config.LLM_API_KEY)
def extract_citations(answer: str, metadatas: List[Dict], chunks: List[str] = None) -> List[Dict]:
"""
Extract and parse citations from answer text, handling multiple formats.
Supports:
- Single citations: [1]
- Comma-separated: [1, 2] or [1,2,3]
- Ranges: [1-3]
- Consecutive: [1][2]
Args:
answer: Generated answer text containing citations
metadatas: List of metadata dictionaries from retrieved chunks
chunks: Optional list of text chunks for logging cited paragraphs
Returns:
List of citation dictionaries with number, title, and section
"""
import re
citations = []
seen_nums = set()
# Match [1], [1, 2], [1-3], [1,2,3], etc.
raw_citations = re.findall(r'\[([\d\s,\-]+)\]', answer)
for raw in raw_citations:
# Parse comma-separated and ranges
parts = raw.replace(' ', '').split(',')
for part in parts:
if '-' in part:
# Handle range like "1-3"
try:
start, end = part.split('-')
for num in range(int(start), int(end) + 1):
seen_nums.add(num)
except ValueError:
pass
else:
# Single number
try:
seen_nums.add(int(part))
except ValueError:
pass
# Build citations list (sorted for consistent ordering)
for num in sorted(seen_nums):
idx = num - 1
if 0 <= idx < len(metadatas):
citations.append({
'number': str(num),
'title': metadatas[idx].get('title', 'Unknown'),
'section': metadatas[idx].get('section', 'body')
})
if chunks and idx < len(chunks):
logger.debug(f"Citation [{num}] refers to paragraph: {chunks[idx][:200]}...")
return citations
def retrieve_context(
user_query: str,
top_k: int = None,
filter_dict: Optional[Dict[str, Any]] = None,
collection=None
) -> Dict[str, Any]:
"""
Retrieve relevant context for a user query.
Args:
user_query: User's question
top_k: Number of chunks to retrieve (default from config)
filter_dict: Optional metadata filter
collection: ChromaDB collection (uses default if None)
Returns:
Dictionary with:
- 'chunks': List of retrieved text chunks (empty if no documents)
- 'metadatas': List of metadata dicts
- 'distances': List of similarity distances
- 'formatted_context': Formatted context string for LLM
- 'chunks_used': Number of chunks actually used in formatted context
"""
if top_k is None:
top_k = config.DEFAULT_TOP_K
if collection is None:
collection = vector_store.get_or_create_collection()
# Check if collection is empty
if collection.count() == 0:
logger.warning("No documents indexed in collection")
return {
'chunks': [],
'metadatas': [],
'distances': [],
'formatted_context': '',
'chunks_used': 0
}
# Embed the query
query_embedding = embeddings.embed_query(user_query)
# Search vector store
results = vector_store.search(
query_embedding=query_embedding,
top_k=top_k,
filter_dict=filter_dict,
collection=collection
)
# Check if search returned results
if not results['documents']:
logger.warning(f"No results found for query: {user_query[:50]}")
return {
'chunks': [],
'metadatas': [],
'distances': [],
'formatted_context': '',
'chunks_used': 0
}
# Format context for LLM
formatted_context, chunks_used = format_context(
chunks=results['documents'],
metadatas=results['metadatas']
)
return {
'chunks': results['documents'],
'metadatas': results['metadatas'],
'distances': results['distances'],
'formatted_context': formatted_context,
'chunks_used': chunks_used
}
def format_context(chunks: List[str], metadatas: List[Dict]) -> str:
"""
Format retrieved chunks into a context string for the LLM.
Args:
chunks: List of text chunks
metadatas: List of metadata dictionaries
Returns:
Formatted context string with citations
"""
context_parts = []
total_length = 0
chunks_used = 0
for i, (chunk, metadata) in enumerate(zip(chunks, metadatas), 1):
# Enforce maximum number of chunks
if chunks_used >= config.MAX_CONTEXT_CHUNKS:
break
# Format: [i] Title - Section: chunk text
title = metadata.get('title', 'Unknown')
section = metadata.get('section', 'body')
# Build context part FIRST to get accurate length
context_part = f"[{i}] {title} - {section}:\n{chunk}\n"
# Check if adding this would exceed length limit
if total_length + len(context_part) > config.MAX_CONTEXT_LENGTH:
break
context_parts.append(context_part)
total_length += len(context_part)
chunks_used += 1
return "\n".join(context_parts), chunks_used
def build_prompt(
user_query: str,
context: str,
target_lang: str,
strategy: str = "A"
) -> str:
"""
Build the prompt for the LLM.
Args:
user_query: User's question
context: Formatted context from retrieval
target_lang: Target language code (e.g., 'hi', 'ta')
strategy: "A" for multilingual LLM, "B" for English + translation
Returns:
Complete prompt string
"""
if strategy == "B":
lang_name = "English"
else:
# Get language name
lang_name = lang_utils.get_language_name(target_lang)
# Guard against garbled names
if not lang_name.isascii() and lang_name == target_lang:
lang_name = f"{target_lang} (language code)"
return config.QUERY_PROMPT_TEMPLATE.format(
context=context,
question=user_query,
language=lang_name
)
def llm_generate(prompt: str, max_tokens: int = None) -> str:
"""
Generate response from LLM using Google Gemini API.
Args:
prompt: The complete prompt to send to the LLM
max_tokens: Maximum tokens to generate
Returns:
Generated text response
Raises:
ValueError: If API key is not configured
Exception: If API call fails
"""
if max_tokens is None:
max_tokens = config.LLM_MAX_TOKENS
# Check if API key is configured
if not config.LLM_API_KEY:
raise ValueError(
"Google Gemini API key not configured. "
"Please set LLM_API_KEY environment variable or in .env file."
)
# Safety settings - set to BLOCK_NONE for scientific content
safety_settings = [
{
"category": "HARM_CATEGORY_HARASSMENT",
"threshold": "BLOCK_NONE"
},
{
"category": "HARM_CATEGORY_HATE_SPEECH",
"threshold": "BLOCK_NONE"
},
{
"category": "HARM_CATEGORY_SEXUALLY_EXPLICIT",
"threshold": "BLOCK_NONE"
},
{
"category": "HARM_CATEGORY_DANGEROUS_CONTENT",
"threshold": "BLOCK_NONE"
},
]
# Create model with generation config and system instruction
generation_config = {
"temperature": config.LLM_TEMPERATURE,
"max_output_tokens": max_tokens,
}
model = genai.GenerativeModel(
model_name=config.LLM_MODEL_NAME,
generation_config=generation_config,
safety_settings=safety_settings,
system_instruction=config.SYSTEM_PROMPT
)
try:
# Generate response
response = model.generate_content(prompt)
# Check if response has text
if hasattr(response, 'text') and response.text:
return response.text
# Handle blocked or empty responses
if hasattr(response, 'candidates') and response.candidates:
candidate = response.candidates[0]
# Check finish reason
if hasattr(candidate, 'finish_reason'):
finish_reason = candidate.finish_reason
# Try to get partial text if available
if hasattr(candidate, 'content') and hasattr(candidate.content, 'parts'):
parts_text = []
for part in candidate.content.parts:
if hasattr(part, 'text'):
parts_text.append(part.text)
if parts_text:
return ''.join(parts_text)
# If no text, raise error with finish reason
raise Exception(
f"Response blocked or incomplete. Finish reason: {finish_reason}. "
f"This may be due to safety filters or token limits."
)
# If we get here, no valid response
raise Exception("No response generated from Gemini API")
except Exception as e:
logger.error(f"Error calling Gemini API: {e}")
raise
def answer_question_strategy_a(
user_query: str,
top_k: int = None,
filter_dict: Optional[Dict] = None
) -> Dict[str, Any]:
"""
Answer question using Strategy A: Direct multilingual LLM.
Args:
user_query: User's question in any language
top_k: Number of chunks to retrieve
filter_dict: Optional metadata filter
Returns:
Dictionary with:
- 'answer': Generated answer in user's language
- 'language': Detected language code
- 'language_name': Native language name
- 'chunks_used': Number of context chunks used
- 'citations': List of cited papers
"""
# Detect language
detected_lang = lang_utils.detect_language(user_query)
if not detected_lang:
detected_lang = "en" # Default to English
lang_name = lang_utils.get_language_name(detected_lang)
logger.info(f"Detected language: {lang_name} ({detected_lang})")
# Retrieve context
logger.info("Retrieving relevant context...")
context_data = retrieve_context(user_query, top_k, filter_dict)
# Handle empty collection
if context_data['chunks_used'] == 0:
logger.warning("No documents available for answering question")
# Translate the no documents response if it's an indicative language
no_docs_msg = config.NO_DOCUMENTS_RESPONSE
if detected_lang != "en" and lang_utils.is_indic_language(detected_lang):
try:
no_docs_msg = translation.translate_from_english(no_docs_msg, detected_lang)
except Exception:
pass # Fallback to English if translation fails
return {
'answer': no_docs_msg,
'language': detected_lang,
'language_name': lang_name,
'chunks_used': 0,
'citations': []
}
logger.info(f"Retrieved {len(context_data['chunks'])} chunks, using {context_data['chunks_used']}")
# Build prompt
prompt = build_prompt(
user_query=user_query,
context=context_data['formatted_context'],
target_lang=detected_lang,
strategy="A"
)
# Generate answer
logger.info("Generating answer...")
answer = llm_generate(prompt)
# Extract citations using robust parser
citations = extract_citations(answer, context_data['metadatas'], context_data.get('chunks'))
return {
'answer': answer,
'language': detected_lang,
'language_name': lang_name,
'chunks_used': context_data['chunks_used'],
'citations': citations
}
def answer_question_strategy_b(
user_query: str,
top_k: int = None,
filter_dict: Optional[Dict] = None
) -> Dict[str, Any]:
"""
Answer question using Strategy B: English reasoning + translation.
Args:
user_query: User's question in any language
top_k: Number of chunks to retrieve
filter_dict: Optional metadata filter
Returns:
Dictionary with same structure as strategy_a
"""
# Detect language
detected_lang = lang_utils.detect_language(user_query)
if not detected_lang:
detected_lang = "en"
lang_name = lang_utils.get_language_name(detected_lang)
logger.info(f"Detected language: {lang_name} ({detected_lang})")
# Translate query to English if needed
if detected_lang != "en" and lang_utils.is_indic_language(detected_lang):
logger.info("Translating query to English...")
english_query = translation.translate_to_english(user_query, detected_lang)
logger.info(f"English query: {english_query}")
else:
english_query = user_query
# Retrieve context using English query
logger.info("Retrieving relevant context...")
context_data = retrieve_context(english_query, top_k, filter_dict)
# Handle empty collection
if context_data['chunks_used'] == 0:
logger.warning("No documents available for answering question")
no_docs_msg = config.NO_DOCUMENTS_RESPONSE
if detected_lang != "en" and lang_utils.is_indic_language(detected_lang):
try:
# Translate the no documents response
no_docs_msg = translation.translate_from_english(no_docs_msg, detected_lang)
except Exception:
pass # Fallback to English
return {
'answer': no_docs_msg,
'language': detected_lang,
'language_name': lang_name,
'chunks_used': 0,
'citations': []
}
logger.info(f"Retrieved {len(context_data['chunks'])} chunks, using {context_data['chunks_used']}")
# Build prompt for English answer
prompt = build_prompt(
user_query=english_query,
context=context_data['formatted_context'],
target_lang="en",
strategy="B"
)
# Generate answer in English
logger.info("Generating answer in English...")
english_answer = llm_generate(prompt)
# Extract citations from ENGLISH answer (before translation) using robust parser
citations = extract_citations(english_answer, context_data['metadatas'], context_data.get('chunks'))
# Translate answer to target language if needed
if detected_lang != "en" and lang_utils.is_indic_language(detected_lang):
logger.info(f"Translating answer to {lang_name}...")
answer = translation.translate_from_english(english_answer, detected_lang)
else:
answer = english_answer
return {
'answer': answer,
'language': detected_lang,
'language_name': lang_name,
'chunks_used': context_data['chunks_used'],
'citations': citations,
'english_answer': english_answer # Include for debugging
}
def answer_question(
user_query: str,
strategy: str = "A",
top_k: int = None,
filter_dict: Optional[Dict] = None
) -> Dict[str, Any]:
"""
Main entry point: Answer a user's question in their language.
Args:
user_query: User's question in any supported language
strategy: "A" for multilingual LLM, "B" for English + translation
top_k: Number of chunks to retrieve
filter_dict: Optional metadata filter (e.g., {"year": 2023})
Returns:
Dictionary with answer, language info, and citations
"""
if strategy == "A":
return answer_question_strategy_a(user_query, top_k, filter_dict)
elif strategy == "B":
return answer_question_strategy_b(user_query, top_k, filter_dict)
else:
raise ValueError(f"Invalid strategy: {strategy}. Must be 'A' or 'B'")
if __name__ == "__main__":
# Test retrieval (without LLM)
import logging
logging.basicConfig(
level=logging.INFO,
format='%(levelname)s: %(message)s'
)
logger.info("Testing RAG Pipeline (Retrieval Only)")
logger.info("=" * 60)
test_query = "What is the treatment for diabetes?"
logger.info(f"\nQuery: {test_query}")
logger.info("\nRetrieving context...")
try:
context_data = retrieve_context(test_query, top_k=3)
if context_data['chunks_used'] == 0:
logger.warning("No documents found. Please ingest PDFs first.")
else:
logger.info(f"\nRetrieved {len(context_data['chunks'])} chunks, using {context_data['chunks_used']}:")
logger.info("-" * 60)
logger.info(context_data['formatted_context'])
logger.info("\n" + "=" * 60)
logger.info("Retrieval test successful!")
logger.info("\nTo test full answer generation:")
logger.info("1. Ensure Gemini API key is configured in .env")
logger.info("2. Run: python examples/example_query.py")
logger.info("3. Or start the API server: python start_server.py")
except Exception as e:
logger.error(f"\nError: {e}")
logger.info("\nMake sure you have:")
logger.info("1. Ingested some PDFs (run: python ingest.py)")
logger.info("2. Installed all dependencies (pip install -r requirements.txt)")