Prabu17 commited on
Commit
ba3e106
·
verified ·
1 Parent(s): c539347

Upload folder using huggingface_hub

Browse files
Files changed (1) hide show
  1. app/grounding/grounding_validator.py +108 -75
app/grounding/grounding_validator.py CHANGED
@@ -7,7 +7,6 @@ and produces a grounded response with status and confidence.
7
  from __future__ import annotations
8
 
9
  import logging
10
- from concurrent.futures import ThreadPoolExecutor, as_completed
11
  from dataclasses import dataclass
12
  from typing import TYPE_CHECKING
13
 
@@ -63,6 +62,13 @@ _LLM_JUDGE_BATCH_SYSTEM = (
63
 
64
  _LLM_JUDGE_BATCH_USER = "Judge each claim below.\n\n{entries}"
65
 
 
 
 
 
 
 
 
66
 
67
  def _build_llm_judge_messages(
68
  claim: str,
@@ -202,47 +208,28 @@ class GroundingValidator:
202
  # Validate all cited claims. The LLM judge is called ONCE for the whole
203
  # batch (one round trip instead of one per claim — the per-claim judge
204
  # was the dominant query-latency cost). Claims the batch could not
205
- # verdict fall back to per-claim judging, then to the deterministic
206
- # validator.
207
  validated_claims: list[AnswerClaim] = []
208
  if raw_claims:
209
  batch_verdicts = self._batch_judge(raw_claims, citation_map)
210
  if batch_verdicts is None:
211
- # Batch unavailable — judge everything per-claim, concurrently
212
- # (I/O-bound HTTP calls).
213
- with ThreadPoolExecutor(max_workers=min(len(raw_claims), 8)) as pool:
214
- futures = {
215
- pool.submit(self._validate_claim, raw, citation_map, response.citations): idx
216
- for idx, raw in enumerate(raw_claims)
217
- }
218
- # Collect results in submission order to preserve claim sequence
219
- results: list[AnswerClaim | None] = [None] * len(raw_claims)
220
- for future in as_completed(futures):
221
- idx = futures[future]
222
- results[idx] = future.result()
223
- validated_claims = [r for r in results if r is not None]
224
- else:
225
- # Use batch verdicts where available; only claims the batch
226
- # could not verdict fall back to per-claim judging.
227
- missing = [
228
- (idx, raw)
229
- for idx, raw in enumerate(raw_claims)
230
- if raw.text not in batch_verdicts
231
  ]
232
- fallback: dict[int, AnswerClaim] = {}
233
- if missing:
234
- with ThreadPoolExecutor(max_workers=min(len(missing), 8)) as pool:
235
- futures = {
236
- pool.submit(
237
- self._validate_claim, raw, citation_map, response.citations
238
- ): idx
239
- for idx, raw in missing
240
- }
241
- for future in as_completed(futures):
242
- fallback[futures[future]] = future.result()
243
  validated_claims = [
244
- fallback.get(idx) or self._claim_from_verdict(raw, batch_verdicts[raw.text])
245
- for idx, raw in enumerate(raw_claims)
 
 
246
  ]
247
 
248
  # Calculate aggregate grounding status
@@ -284,11 +271,12 @@ class GroundingValidator:
284
  raw_claims: list[Claim],
285
  citation_map: dict[str, Citation],
286
  ) -> dict[str, dict] | None:
287
- """Judge all claims in ONE LLM call.
288
 
289
  Returns a map from claim text to verdict dict, or None when the batch
290
  path is unavailable (no LLM client, call failed, unparseable response).
291
- Claims missing from the returned map fall back to per-claim judging.
 
292
  """
293
  if self._llm_client is None or not self.config.use_llm_judge:
294
  return None
@@ -311,9 +299,44 @@ class GroundingValidator:
311
  if not entries:
312
  return None
313
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
314
  system_prompt, user_prompt = _build_llm_judge_batch_messages(entries)
315
  try:
316
- raw_response = self._llm_client.generate(
317
  system_prompt=system_prompt,
318
  user_prompt=user_prompt,
319
  evidence_context="",
@@ -325,7 +348,7 @@ class GroundingValidator:
325
  usage_label="grounding",
326
  )
327
  except Exception:
328
- logger.warning("Batched LLM judge call failed; falling back to per-claim", exc_info=True)
329
  return None
330
 
331
  parsed = _parse_llm_judge_response(raw_response.text)
@@ -335,19 +358,39 @@ class GroundingValidator:
335
  if not isinstance(verdicts, list):
336
  return None
337
 
 
 
 
338
  out: dict[str, dict] = {}
339
  for v in verdicts:
340
  if not isinstance(v, dict):
341
  continue
 
342
  raw_id = v.get("id")
343
- if raw_id is None:
344
- continue
345
- try:
346
- cid = int(raw_id)
347
- except (TypeError, ValueError):
348
- continue
349
- if 0 <= cid < len(raw_claims):
350
- out[raw_claims[cid].text] = v
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
351
  return out
352
 
353
  def _claim_from_verdict(self, raw: Claim, verdict: dict) -> AnswerClaim:
@@ -365,19 +408,23 @@ class GroundingValidator:
365
  reason=reason,
366
  )
367
 
368
- def _validate_claim(
369
  self,
370
  raw: Claim,
371
  citation_map: dict[str, Citation],
372
  all_citations: list[Citation],
373
  ) -> AnswerClaim:
374
- """Validate a single claim against its cited evidence.
375
-
376
- Returns an AnswerClaim with status and reason.
 
 
 
 
 
377
  """
378
  from app.generation.schemas import CitationStatus
379
 
380
- # If no citations, mark as unsupported with no reason
381
  if not raw.citation_ids:
382
  return AnswerClaim(
383
  claim=raw.text,
@@ -386,38 +433,24 @@ class GroundingValidator:
386
  reason="Claim has no citations.",
387
  )
388
 
389
- validated_statuses: list[CitationStatus] = []
390
  reasons: list[str] = []
391
-
392
  for cid in raw.citation_ids:
393
  citation = citation_map.get(cid)
394
  if citation is None:
395
- # Unknown citation ID
396
- validated_statuses.append(CitationStatus.UNSUPPORTED)
397
  reasons.append(f"Unknown citation ID: {cid}.")
398
  continue
399
-
400
- evidence_text = citation.text
401
- validation_result = self._do_validate(
402
- raw.text,
403
- evidence_text,
404
- cid,
405
- citation.section,
406
- None,
407
- )
408
- validated_statuses.append(validation_result.status)
409
- reasons.append(f"[{cid}] {validation_result.reason}")
410
-
411
- # Aggregate: best status wins
412
- overall_status = self._aggregate_statuses(validated_statuses)
413
- # Combine reasons
414
- combined_reason = " ".join(reasons) if reasons else None
415
 
416
  return AnswerClaim(
417
  claim=raw.text,
418
  citation_ids=raw.citation_ids,
419
- status=overall_status,
420
- reason=combined_reason,
421
  )
422
 
423
  def _do_validate(
 
7
  from __future__ import annotations
8
 
9
  import logging
 
10
  from dataclasses import dataclass
11
  from typing import TYPE_CHECKING
12
 
 
62
 
63
  _LLM_JUDGE_BATCH_USER = "Judge each claim below.\n\n{entries}"
64
 
65
+ # Max claims per batched judge call. Keeps the JSON response small enough that
66
+ # a long answer cannot truncate the tail of the verdict array (truncation was
67
+ # the original source of the per-claim fallback). 12 verdicts x ~256 tokens is
68
+ # comfortably inside the budget, and in practice a single chunk covers a whole
69
+ # answer, so this is a safety valve rather than the normal path.
70
+ _JUDGE_BATCH_CHUNK = 12
71
+
72
 
73
  def _build_llm_judge_messages(
74
  claim: str,
 
208
  # Validate all cited claims. The LLM judge is called ONCE for the whole
209
  # batch (one round trip instead of one per claim — the per-claim judge
210
  # was the dominant query-latency cost). Claims the batch could not
211
+ # verdict fall back to the DETERMINISTIC validator — never to more LLM
212
+ # calls, which would silently reintroduce the per-claim latency.
213
  validated_claims: list[AnswerClaim] = []
214
  if raw_claims:
215
  batch_verdicts = self._batch_judge(raw_claims, citation_map)
216
  if batch_verdicts is None:
217
+ # Batch unavailable (no LLM client, call failed, unparseable) —
218
+ # deterministic validation only. No LLM calls.
219
+ validated_claims = [
220
+ self._deterministic_claim(raw, citation_map, response.citations)
221
+ for raw in raw_claims
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
222
  ]
223
+ else:
224
+ # Use batch verdicts where available; claims the batch could
225
+ # not verdict get the deterministic verdict. A missing verdict
226
+ # is itself a quality signal (the judge dodged the claim), so
227
+ # treating it as unsupported is honest and keeps latency flat.
 
 
 
 
 
 
228
  validated_claims = [
229
+ self._claim_from_verdict(raw, batch_verdicts[raw.text])
230
+ if raw.text in batch_verdicts
231
+ else self._deterministic_claim(raw, citation_map, response.citations)
232
+ for raw in raw_claims
233
  ]
234
 
235
  # Calculate aggregate grounding status
 
271
  raw_claims: list[Claim],
272
  citation_map: dict[str, Citation],
273
  ) -> dict[str, dict] | None:
274
+ """Judge all claims in ONE (or a few) LLM calls.
275
 
276
  Returns a map from claim text to verdict dict, or None when the batch
277
  path is unavailable (no LLM client, call failed, unparseable response).
278
+ Claims missing from the returned map get the deterministic validator in
279
+ ``validate()`` — never another LLM call.
280
  """
281
  if self._llm_client is None or not self.config.use_llm_judge:
282
  return None
 
299
  if not entries:
300
  return None
301
 
302
+ out: dict[str, dict] = {}
303
+ # Split into chunks so one oversized response cannot be truncated
304
+ # (finish_reason=length silently drops trailing verdicts, which used to
305
+ # push every dropped claim back through a per-claim LLM call).
306
+ chunks = [entries[i:i + _JUDGE_BATCH_CHUNK] for i in range(0, len(entries), _JUDGE_BATCH_CHUNK)]
307
+ for chunk in chunks:
308
+ chunk_out = self._batch_judge_chunk(chunk, raw_claims)
309
+ if chunk_out is None:
310
+ # This whole chunk failed; its claims fall back deterministically.
311
+ continue
312
+ out.update(chunk_out)
313
+
314
+ requested = len(entries)
315
+ got = len(out)
316
+ if got != requested:
317
+ # Visible in the Space logs: a gap here means the judge omitted
318
+ # verdicts, so those claims are graded deterministically instead.
319
+ logger.info(
320
+ "Batched judge returned %d/%d verdicts; %d claim(s) fall back to "
321
+ "deterministic validation",
322
+ got,
323
+ requested,
324
+ requested - got,
325
+ )
326
+ return out
327
+
328
+ def _batch_judge_chunk(
329
+ self,
330
+ entries: list[dict],
331
+ raw_claims: list[Claim],
332
+ ) -> dict[str, dict] | None:
333
+ """Run one batched judge call for *entries*, returning claim_text->verdict."""
334
+ client = self._llm_client
335
+ if client is None:
336
+ return None
337
  system_prompt, user_prompt = _build_llm_judge_batch_messages(entries)
338
  try:
339
+ raw_response = client.generate(
340
  system_prompt=system_prompt,
341
  user_prompt=user_prompt,
342
  evidence_context="",
 
348
  usage_label="grounding",
349
  )
350
  except Exception:
351
+ logger.warning("Batched LLM judge call failed; using deterministic validation", exc_info=True)
352
  return None
353
 
354
  parsed = _parse_llm_judge_response(raw_response.text)
 
358
  if not isinstance(verdicts, list):
359
  return None
360
 
361
+ # id -> claim text, so a verdict can be matched by id OR by echoed text
362
+ # (models frequently renumber or echo the claim instead of the id).
363
+ by_id = {e["id"]: e["claim"] for e in entries}
364
  out: dict[str, dict] = {}
365
  for v in verdicts:
366
  if not isinstance(v, dict):
367
  continue
368
+ claim_text = None
369
  raw_id = v.get("id")
370
+ if raw_id is not None:
371
+ try:
372
+ cid = int(raw_id)
373
+ except (TypeError, ValueError):
374
+ cid = None
375
+ if cid is not None and cid in by_id:
376
+ claim_text = by_id[cid]
377
+ if claim_text is None:
378
+ # Fall back to matching the echoed claim text.
379
+ echoed = v.get("claim")
380
+ if isinstance(echoed, str):
381
+ for e in entries:
382
+ if e["claim"].strip() == echoed.strip():
383
+ claim_text = e["claim"]
384
+ break
385
+ if claim_text is None and raw_id is not None:
386
+ try:
387
+ idx = int(raw_id)
388
+ except (TypeError, ValueError):
389
+ idx = -1
390
+ if 0 <= idx < len(raw_claims):
391
+ claim_text = raw_claims[idx].text
392
+ if claim_text is not None:
393
+ out[claim_text] = v
394
  return out
395
 
396
  def _claim_from_verdict(self, raw: Claim, verdict: dict) -> AnswerClaim:
 
408
  reason=reason,
409
  )
410
 
411
+ def _deterministic_claim(
412
  self,
413
  raw: Claim,
414
  citation_map: dict[str, Citation],
415
  all_citations: list[Citation],
416
  ) -> AnswerClaim:
417
+ """Validate a claim WITHOUT any LLM call.
418
+
419
+ Used for claims the batched judge did not verdict, and when the batch
420
+ itself is unavailable. Deliberately skips the LLM judge that
421
+ ``_validate_claim`` invokes, so a partial or failed batch can never
422
+ reintroduce per-claim LLM round trips (the latency bug this replaced).
423
+ A claim the judge skipped is treated as unsupported — an absent verdict
424
+ is not evidence of support.
425
  """
426
  from app.generation.schemas import CitationStatus
427
 
 
428
  if not raw.citation_ids:
429
  return AnswerClaim(
430
  claim=raw.text,
 
433
  reason="Claim has no citations.",
434
  )
435
 
436
+ statuses: list[CitationStatus] = []
437
  reasons: list[str] = []
 
438
  for cid in raw.citation_ids:
439
  citation = citation_map.get(cid)
440
  if citation is None:
441
+ statuses.append(CitationStatus.UNSUPPORTED)
 
442
  reasons.append(f"Unknown citation ID: {cid}.")
443
  continue
444
+ # Token-overlap validator only — no LLM round trip.
445
+ result = self.citation_validator.validate(raw.text, citation.text, cid)
446
+ statuses.append(result.status)
447
+ reasons.append(f"[{cid}] {result.reason}")
 
 
 
 
 
 
 
 
 
 
 
 
448
 
449
  return AnswerClaim(
450
  claim=raw.text,
451
  citation_ids=raw.citation_ids,
452
+ status=self._aggregate_statuses(statuses),
453
+ reason=" ".join(reasons) if reasons else None,
454
  )
455
 
456
  def _do_validate(