aseelflihan commited on
Commit
5cb4c11
Β·
1 Parent(s): a556c58

feat: add token usage tracking and display, update sample questions for demo scenarios

Browse files
Files changed (4) hide show
  1. src/bio_rag/generator.py +12 -0
  2. static/index.html +6 -6
  3. static/js/app.js +2 -0
  4. web_app.py +7 -0
src/bio_rag/generator.py CHANGED
@@ -10,6 +10,12 @@ from .retriever import RetrievedPassage
10
 
11
  logger = logging.getLogger(__name__)
12
 
 
 
 
 
 
 
13
  # Switch to use Groq API instead of local Models
14
  class BiomedicalAnswerGenerator:
15
  """Generates answers using a biomedical LLM via Groq API."""
@@ -19,6 +25,7 @@ class BiomedicalAnswerGenerator:
19
  self._is_seq2seq = False
20
  self.client = Groq(api_key=os.getenv("GROQ_API_KEY"))
21
  logger.info("Loaded Groq API Generator with model: %s", self.model_name)
 
22
 
23
  def generate(self, question: str, passages: Iterable[RetrievedPassage]) -> str:
24
  passage_list = list(passages)
@@ -43,6 +50,11 @@ class BiomedicalAnswerGenerator:
43
  kwargs["response_format"] = {"type": "json_object"}
44
 
45
  response = self.client.chat.completions.create(**kwargs)
 
 
 
 
 
46
  return response.choices[0].message.content.strip()
47
  except Exception as e:
48
  logger.error("Error generating with Groq API: %s", e)
 
10
 
11
  logger = logging.getLogger(__name__)
12
 
13
+ class TokenUsage:
14
+ def __init__(self, prompt_tokens=0, completion_tokens=0):
15
+ self.prompt_tokens = prompt_tokens
16
+ self.completion_tokens = completion_tokens
17
+ self.total_tokens = prompt_tokens + completion_tokens
18
+
19
  # Switch to use Groq API instead of local Models
20
  class BiomedicalAnswerGenerator:
21
  """Generates answers using a biomedical LLM via Groq API."""
 
25
  self._is_seq2seq = False
26
  self.client = Groq(api_key=os.getenv("GROQ_API_KEY"))
27
  logger.info("Loaded Groq API Generator with model: %s", self.model_name)
28
+ self.last_usage = TokenUsage()
29
 
30
  def generate(self, question: str, passages: Iterable[RetrievedPassage]) -> str:
31
  passage_list = list(passages)
 
50
  kwargs["response_format"] = {"type": "json_object"}
51
 
52
  response = self.client.chat.completions.create(**kwargs)
53
+ if hasattr(response, 'usage') and response.usage:
54
+ self.last_usage = TokenUsage(
55
+ prompt_tokens=response.usage.prompt_tokens or 0,
56
+ completion_tokens=response.usage.completion_tokens or 0,
57
+ )
58
  return response.choices[0].message.content.strip()
59
  except Exception as e:
60
  logger.error("Error generating with Groq API: %s", e)
static/index.html CHANGED
@@ -90,13 +90,13 @@ Diabetes Domain Only
90
  <span class="suggestion-icon">πŸ’Š</span>
91
  <span class="suggestion-text">Is metformin safe for patients with kidney disease?</span>
92
  </button>
93
- <button class="suggestion-card" data-question="How does insulin resistance develop in type 2 diabetes?">
94
- <span class="suggestion-icon">πŸ§ͺ</span>
95
- <span class="suggestion-text">How does insulin resistance develop in type 2 diabetes?</span>
96
  </button>
97
- <button class="suggestion-card" data-question="Can type 2 diabetes be prevented through lifestyle changes?">
98
- <span class="suggestion-icon">πŸƒ</span>
99
- <span class="suggestion-text">Can type 2 diabetes be prevented through lifestyle changes?</span>
100
  </button>
101
  </div>
102
  </div>
 
90
  <span class="suggestion-icon">πŸ’Š</span>
91
  <span class="suggestion-text">Is metformin safe for patients with kidney disease?</span>
92
  </button>
93
+ <button class="suggestion-card" data-question="Is insulin dosage adjustment necessary for type 1 diabetic patients with severe renal impairment?">
94
+ <span class="suggestion-icon">⚠️</span>
95
+ <span class="suggestion-text">Insulin dosage for diabetics with renal impairment</span>
96
  </button>
97
+ <button class="suggestion-card" data-question="Are arterial stiffness and central arterial wave reflection associated with serum uric acid in patients with coronary artery disease?">
98
+ <span class="suggestion-icon">🚫</span>
99
+ <span class="suggestion-text">Test: Non-diabetes question (should be rejected)</span>
100
  </button>
101
  </div>
102
  </div>
static/js/app.js CHANGED
@@ -531,6 +531,8 @@ ${data.processing_stats ? `
531
  <div>πŸ“„ <strong>Passages Retrieved:</strong> ${data.processing_stats.passages_retrieved} β†’ Top ${Math.min(data.processing_stats.passages_retrieved, 10)} after RRF</div>
532
  <div>βœ‚οΈ <strong>Claims Decomposed:</strong> ${data.processing_stats.claims_verified}</div>
533
  <div>πŸ”¬ <strong>Total Evidence Evaluated:</strong> ${data.processing_stats.total_evidence_evaluated} (${data.processing_stats.claims_verified} claims Γ— ${data.processing_stats.evidence_per_claim} docs)</div>
 
 
534
  ${data.processing_stats.phase_times ? `
535
  <div style="margin-top:4px;">⏱️ <strong>Phase Times:</strong>
536
  Query Expansion: ${data.processing_stats.phase_times.query_expansion || 0}s β€’
 
531
  <div>πŸ“„ <strong>Passages Retrieved:</strong> ${data.processing_stats.passages_retrieved} β†’ Top ${Math.min(data.processing_stats.passages_retrieved, 10)} after RRF</div>
532
  <div>βœ‚οΈ <strong>Claims Decomposed:</strong> ${data.processing_stats.claims_verified}</div>
533
  <div>πŸ”¬ <strong>Total Evidence Evaluated:</strong> ${data.processing_stats.total_evidence_evaluated} (${data.processing_stats.claims_verified} claims Γ— ${data.processing_stats.evidence_per_claim} docs)</div>
534
+ ${data.processing_stats.token_usage ? `
535
+ <div>πŸͺ™ <strong>Tokens:</strong> Input: ${data.processing_stats.token_usage.prompt_tokens} β€’ Output: ${data.processing_stats.token_usage.completion_tokens} β€’ Total: ${data.processing_stats.token_usage.total_tokens}</div>` : ''}
536
  ${data.processing_stats.phase_times ? `
537
  <div style="margin-top:4px;">⏱️ <strong>Phase Times:</strong>
538
  Query Expansion: ${data.processing_stats.phase_times.query_expansion || 0}s β€’
web_app.py CHANGED
@@ -46,6 +46,7 @@ def ask_stream():
46
  try:
47
  _start_time = time.time()
48
  phase_times = {}
 
49
  yield f"data: {json_lib.dumps({'step': 0, 'status': 'active'})}\n\n"
50
  time.sleep(0.1)
51
  yield f"data: {json_lib.dumps({'step': 0, 'status': 'done'})}\n\n"
@@ -83,6 +84,11 @@ def ask_stream():
83
  _p3_start = time.time()
84
  original_answer = pipeline.generator.generate(question, passages)
85
  phase_times['generation'] = round(time.time() - _p3_start, 2)
 
 
 
 
 
86
  yield f"data: {json_lib.dumps({'step': 3, 'status': 'done'})}\n\n"
87
  time.sleep(0.1)
88
 
@@ -160,6 +166,7 @@ def ask_stream():
160
  'evidence_per_claim': 10,
161
  'total_evidence_evaluated': len(claims) * 10,
162
  'phase_times': phase_times,
 
163
  }
164
  }
165
  yield f"data: {json_lib.dumps({'complete': True, 'result': r})}\n\n"
 
46
  try:
47
  _start_time = time.time()
48
  phase_times = {}
49
+ token_stats = {'prompt_tokens': 0, 'completion_tokens': 0, 'total_tokens': 0}
50
  yield f"data: {json_lib.dumps({'step': 0, 'status': 'active'})}\n\n"
51
  time.sleep(0.1)
52
  yield f"data: {json_lib.dumps({'step': 0, 'status': 'done'})}\n\n"
 
84
  _p3_start = time.time()
85
  original_answer = pipeline.generator.generate(question, passages)
86
  phase_times['generation'] = round(time.time() - _p3_start, 2)
87
+ if hasattr(pipeline.generator, 'last_usage'):
88
+ u = pipeline.generator.last_usage
89
+ token_stats['prompt_tokens'] += u.prompt_tokens
90
+ token_stats['completion_tokens'] += u.completion_tokens
91
+ token_stats['total_tokens'] += u.total_tokens
92
  yield f"data: {json_lib.dumps({'step': 3, 'status': 'done'})}\n\n"
93
  time.sleep(0.1)
94
 
 
166
  'evidence_per_claim': 10,
167
  'total_evidence_evaluated': len(claims) * 10,
168
  'phase_times': phase_times,
169
+ 'token_usage': token_stats,
170
  }
171
  }
172
  yield f"data: {json_lib.dumps({'complete': True, 'result': r})}\n\n"