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,98 @@
|
||||
"""Backend-owned evidence admission, ordering and execution source identities."""
|
||||
from contextlib import contextmanager
|
||||
from dataclasses import dataclass, field
|
||||
import math
|
||||
from threading import RLock
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from app.modules.knowledge.lexical import LEXICAL_POLICY
|
||||
|
||||
MAX_BRANCH_CANDIDATES = 50
|
||||
MAX_CHUNKS = 5
|
||||
MAX_EVIDENCE_CHARACTERS = 12000
|
||||
RETRIEVAL_POLICY = f"exact-first-cosine-id-50x2-whole-5-12000/{LEXICAL_POLICY}"
|
||||
|
||||
|
||||
def merge_candidates(semantic, exact):
|
||||
by_id = {}
|
||||
for row in semantic:
|
||||
by_id[row["chunk_id"]] = dict(row, exact_match=False)
|
||||
for row in exact:
|
||||
by_id[row["chunk_id"]] = dict(row, exact_match=True)
|
||||
return sorted(by_id.values(), key=lambda row: (
|
||||
not row["exact_match"], row["cosine_distance"], str(row["chunk_id"])))
|
||||
|
||||
|
||||
def admit_candidates(rows, cutoff=None):
|
||||
admitted, used = [], 0
|
||||
for row in rows:
|
||||
if cutoff is not None and row["cosine_distance"] > cutoff:
|
||||
continue
|
||||
size = len(row["text"])
|
||||
if size + used > MAX_EVIDENCE_CHARACTERS:
|
||||
continue
|
||||
admitted.append(row)
|
||||
used += size
|
||||
if len(admitted) == MAX_CHUNKS:
|
||||
break
|
||||
return admitted
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class CalibratedCutoff:
|
||||
profile: dict
|
||||
distance: float
|
||||
calibration_id: str
|
||||
retrieval_policy: str = RETRIEVAL_POLICY
|
||||
|
||||
def __post_init__(self):
|
||||
if (type(self.distance) not in (int, float) or not math.isfinite(self.distance)
|
||||
or not 0 <= self.distance <= 2 or not self.calibration_id):
|
||||
raise ValueError("Measured finite cosine cutoff and calibration identity required")
|
||||
|
||||
|
||||
@dataclass
|
||||
class SearchExecution:
|
||||
"""Created by the trusted caller, never populated from model arguments."""
|
||||
user_id: UUID
|
||||
request_id: str = field(default_factory=lambda: str(uuid4()))
|
||||
_authority: dict | None = field(default=None, init=False, repr=False)
|
||||
_epoch: int | None = field(default=None, init=False, repr=False)
|
||||
_refs: dict = field(default_factory=dict, init=False, repr=False)
|
||||
_lock: RLock = field(default_factory=RLock, init=False, repr=False)
|
||||
|
||||
def capture(self, current, epoch):
|
||||
with self._lock:
|
||||
if self._authority is None:
|
||||
self._authority, self._epoch = dict(current), epoch
|
||||
return self._authority == current and self._epoch == epoch
|
||||
|
||||
def matches(self, current, epoch):
|
||||
with self._lock:
|
||||
return self._authority is not None and self._authority == current and self._epoch == epoch
|
||||
|
||||
@contextmanager
|
||||
def source_handoff(self):
|
||||
"""Stage reference mappings; publish only after authorized commit."""
|
||||
with self._lock:
|
||||
prepared = dict(self._refs)
|
||||
yield lambda rows: self._sources(rows, prepared)
|
||||
self._refs = prepared
|
||||
|
||||
def sources(self, rows):
|
||||
with self._lock:
|
||||
return self._sources(rows, self._refs)
|
||||
|
||||
@staticmethod
|
||||
def _sources(rows, refs):
|
||||
sources = []
|
||||
for row in rows:
|
||||
key = (row["document_id"], row["chunk_id"])
|
||||
if key not in refs:
|
||||
refs[key] = f"S{len(refs) + 1}"
|
||||
sources.append(dict(source_ref=refs[key],
|
||||
document_id=str(row["document_id"]), chunk_id=str(row["chunk_id"]),
|
||||
title=row["title"], text=row["text"],
|
||||
location=dict(page=row["location"].get("page"),
|
||||
section=row["location"].get("section"))))
|
||||
return sources
|
||||
Reference in New Issue
Block a user