feat(search): add calibrated retrieval and LangChain knowledge tool
Add exact and semantic evidence admission, measured calibration, bounded tool execution, and independent held-out evaluation preparation with regression coverage and operator guides. Real-provider quality gates remain pending. Validation: 1300 provider-free tests passed; 3 Windows symlink skips. PostgreSQL acceptance not rerun because TEST_DATABASE_URL is unset.
This commit is contained in:
@@ -0,0 +1,104 @@
|
||||
"""Ten-case profile-specific cutoff selection, separate from held-out evaluation."""
|
||||
from dataclasses import asdict
|
||||
import math
|
||||
import re
|
||||
import unicodedata
|
||||
|
||||
from app.modules.knowledge.evidence import RETRIEVAL_POLICY, admit_candidates, CalibratedCutoff
|
||||
|
||||
|
||||
def validate_cases(cases):
|
||||
if (len(cases) != 10 or len({c["id"] for c in cases}) != 10
|
||||
or sum(c["answerable"] is True for c in cases) != 6
|
||||
or sum(c["answerable"] is False for c in cases) != 4):
|
||||
raise ValueError("Exactly six answerable and four unsupported separate cases required")
|
||||
for case in cases:
|
||||
groups = case["evidence_groups"]
|
||||
if (not case["query"].strip() or not case["original_sha256"]
|
||||
or bool(groups) != case["answerable"]
|
||||
or any(not g or any(not p.strip() for p in g) for g in groups)):
|
||||
raise ValueError("Original-bound independent evidence annotations required")
|
||||
|
||||
|
||||
def _token_character(character):
|
||||
# Python's \w omits combining marks and format joiners used inside
|
||||
# Unicode words. Treat those as continuations too, without normalizing
|
||||
# or rewriting independently annotated literal evidence.
|
||||
category = unicodedata.category(character)
|
||||
return category[0] in "LNM" or category in ("Pc", "Cf")
|
||||
|
||||
|
||||
def _literal_boundary(text, index, direction):
|
||||
if not 0 <= index < len(text):
|
||||
return True
|
||||
character = text[index]
|
||||
if _token_character(character) or character in "/-+\u066b\u066c":
|
||||
return False
|
||||
if character == ".":
|
||||
outward = index + direction
|
||||
# A sentence period is punctuation; a dot connecting token pieces
|
||||
# extends a number, date or identifier.
|
||||
return not (0 <= outward < len(text) and
|
||||
(_token_character(text[outward]) or text[outward] in "./-"))
|
||||
return True
|
||||
|
||||
|
||||
def literal_annotation_matches(phrase, text):
|
||||
return any(_literal_boundary(text, match.start() - 1, -1)
|
||||
and _literal_boundary(text, match.end(), 1)
|
||||
for match in re.finditer(re.escape(phrase), text))
|
||||
|
||||
|
||||
def complete_support(case, rows, document_id):
|
||||
# Each evidence group must occur together in one faithful chunk of the
|
||||
# annotated original, including all numbers, conditions and exceptions.
|
||||
return all(any(str(row["document_id"]) == str(document_id)
|
||||
and all(literal_annotation_matches(phrase, row["text"]) for phrase in group)
|
||||
for row in rows) for group in case["evidence_groups"])
|
||||
|
||||
|
||||
def select_cutoff(cases, observations, bindings, profile):
|
||||
validate_cases(cases)
|
||||
if set(observations) != {c["id"] for c in cases}:
|
||||
raise ValueError("Every case requires a completed retrieval observation")
|
||||
if any(observations[c["id"]].get("status") == "error" for c in cases):
|
||||
return dict(status="technical_error", cutoff=None, trials=[], cases=observations)
|
||||
distances = {0.0}
|
||||
for observation in observations.values():
|
||||
if observation["retrieval_policy"] != RETRIEVAL_POLICY:
|
||||
raise ValueError("Calibration retrieval policy changed")
|
||||
for row in observation["candidates"]:
|
||||
distance = row["cosine_distance"]
|
||||
if type(distance) not in (int, float) or not math.isfinite(distance):
|
||||
raise ValueError("Calibration requires finite measured distances")
|
||||
if 0 <= distance <= 2:
|
||||
distances.add(distance)
|
||||
trials = []
|
||||
best = None
|
||||
for cutoff in sorted(distances):
|
||||
results = []
|
||||
for case in cases:
|
||||
rows = admit_candidates(observations[case["id"]]["candidates"], cutoff)
|
||||
passed = (complete_support(case, rows, bindings[case["original_sha256"]])
|
||||
if case["answerable"] else not rows)
|
||||
results.append(dict(id=case["id"], answerable=case["answerable"], passed=passed,
|
||||
status="ok" if rows else "no_evidence", sources=rows))
|
||||
coverage = sum(r["passed"] for r in results if r["answerable"])
|
||||
false_positives = sum(not r["passed"] for r in results if not r["answerable"])
|
||||
trials.append(dict(distance=cutoff, complete_support=coverage,
|
||||
unsupported_false_positives=false_positives))
|
||||
# Ascending cutoff traversal preserves the stricter cutoff on ties.
|
||||
if false_positives == 0 and (best is None or coverage > best["complete_support"]):
|
||||
best = dict(distance=cutoff, complete_support=coverage, results=results)
|
||||
if best is None or best["complete_support"] == 0:
|
||||
return dict(status="measured_failure", cutoff=None, trials=trials, cases=observations)
|
||||
return dict(status="calibrated", cutoff=dict(profile=asdict(profile),
|
||||
distance=best["distance"], retrieval_policy=RETRIEVAL_POLICY),
|
||||
complete_support=best["complete_support"],
|
||||
unsupported_false_positives=0, trials=trials, cases=best["results"])
|
||||
|
||||
|
||||
def load_cutoff(report):
|
||||
if report.get("status") != "calibrated" or not report.get("calibration_id"):
|
||||
raise ValueError("Successful measured calibration report required")
|
||||
return CalibratedCutoff(**report["cutoff"], calibration_id=report["calibration_id"])
|
||||
Reference in New Issue
Block a user