feat: consolida backend RAG e documentação
This commit is contained in:
parent
7c18727f62
commit
d72572ee6f
28 changed files with 2193 additions and 275 deletions
160
rag-api/evaluation.py
Normal file
160
rag-api/evaluation.py
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
"""Dependency-free scoring for controlled ATIVA RAG evaluation runs."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import math
|
||||
from statistics import mean, median
|
||||
from typing import Any
|
||||
|
||||
|
||||
ABSTENTION_MARKERS = (
|
||||
"não está disponível na base",
|
||||
"não encontrei essa informação",
|
||||
"não há informação suficiente",
|
||||
"não consigo responder com base",
|
||||
)
|
||||
|
||||
|
||||
def evaluate(dataset: dict[str, Any], results: dict[str, Any], k: int = 5) -> dict[str, Any]:
|
||||
"""Return descriptive metrics only; this function never approves a model."""
|
||||
if isinstance(k, bool) or not isinstance(k, int) or k < 1:
|
||||
raise ValueError("k precisa ser maior que zero")
|
||||
if not isinstance(dataset, dict) or not isinstance(results, dict):
|
||||
raise ValueError("dataset e results precisam ser objetos JSON")
|
||||
|
||||
cases = dataset.get("cases")
|
||||
runs = results.get("runs")
|
||||
if not isinstance(cases, list) or not isinstance(runs, list):
|
||||
raise ValueError("dataset.cases e results.runs precisam ser listas")
|
||||
|
||||
case_by_id: dict[str, dict[str, Any]] = {}
|
||||
for case in cases:
|
||||
case_id = case.get("id") if isinstance(case, dict) else None
|
||||
if not isinstance(case_id, str) or not case_id or case_id in case_by_id:
|
||||
raise ValueError("cada caso precisa de id único não vazio")
|
||||
if not isinstance(case.get("expected_sources"), list):
|
||||
raise ValueError(f"expected_sources inválido no caso {case_id}")
|
||||
if not all(isinstance(source, str) for source in case["expected_sources"]):
|
||||
raise ValueError(f"expected_sources inválido no caso {case_id}")
|
||||
if not isinstance(case.get("expects_abstention"), bool):
|
||||
raise ValueError(f"expects_abstention inválido no caso {case_id}")
|
||||
case_by_id[case_id] = case
|
||||
|
||||
hits = 0
|
||||
answerable = 0
|
||||
citation_matches = 0
|
||||
citation_total = 0
|
||||
abstention_expected = 0
|
||||
abstention_detected = 0
|
||||
latencies: list[float] = []
|
||||
run_keys: set[tuple[str, int]] = set()
|
||||
run_case_ids: set[str] = set()
|
||||
outcomes_by_case: dict[str, list[tuple[bool | None, bool | None, bool | None]]] = {}
|
||||
manual_review = 0
|
||||
|
||||
for run in runs:
|
||||
if not isinstance(run, dict):
|
||||
raise ValueError("cada resultado precisa ser um objeto")
|
||||
case_id = run.get("case_id")
|
||||
if not isinstance(case_id, str) or case_id not in case_by_id:
|
||||
raise ValueError("resultado referencia case_id desconhecido")
|
||||
required_fields = {"retrieved_sources", "cited_sources", "answer"}
|
||||
if not required_fields.issubset(run):
|
||||
raise ValueError(f"resultado incompleto em {case_id}")
|
||||
repeat = run.get("repeat", 1)
|
||||
if isinstance(repeat, bool) or not isinstance(repeat, int) or repeat < 1:
|
||||
raise ValueError(f"repeat inválido em {case_id}")
|
||||
run_key = (case_id, repeat)
|
||||
if run_key in run_keys:
|
||||
raise ValueError(f"resultado duplicado para {case_id} repetição {repeat}")
|
||||
run_keys.add(run_key)
|
||||
run_case_ids.add(case_id)
|
||||
case = case_by_id[case_id]
|
||||
expected = set(case["expected_sources"])
|
||||
retrieved = run.get("retrieved_sources", [])
|
||||
cited = run.get("cited_sources", [])
|
||||
answer = run.get("answer", "")
|
||||
if not isinstance(retrieved, list) or not all(isinstance(item, str) for item in retrieved):
|
||||
raise ValueError(f"retrieved_sources inválido em {case_id}")
|
||||
if not isinstance(cited, list) or not all(isinstance(item, str) for item in cited):
|
||||
raise ValueError(f"cited_sources inválido em {case_id}")
|
||||
if not isinstance(answer, str):
|
||||
raise ValueError(f"answer inválida em {case_id}")
|
||||
|
||||
retrieval_hit: bool | None = None
|
||||
if expected:
|
||||
answerable += 1
|
||||
retrieval_hit = bool(expected.intersection(retrieved[:k]))
|
||||
if retrieval_hit:
|
||||
hits += 1
|
||||
citation_total += len(cited)
|
||||
citation_matches += sum(1 for source in cited if source in expected)
|
||||
citations_match = bool(cited) and all(source in expected for source in cited) if expected else not cited
|
||||
abstention_hit: bool | None = None
|
||||
if case.get("expects_abstention") is True:
|
||||
abstention_expected += 1
|
||||
normalized = answer.casefold()
|
||||
abstention_hit = any(marker in normalized for marker in ABSTENTION_MARKERS)
|
||||
if abstention_hit:
|
||||
abstention_detected += 1
|
||||
outcomes_by_case.setdefault(case_id, []).append(
|
||||
(retrieval_hit, citations_match, abstention_hit)
|
||||
)
|
||||
latency = run.get("latency_ms")
|
||||
if latency is not None:
|
||||
if (
|
||||
isinstance(latency, bool)
|
||||
or not isinstance(latency, (int, float))
|
||||
or not math.isfinite(latency)
|
||||
or latency < 0
|
||||
):
|
||||
raise ValueError(f"latency_ms inválida em {case_id}")
|
||||
latencies.append(float(latency))
|
||||
if run.get("human_fidelity_review") in (None, "pending"):
|
||||
manual_review += 1
|
||||
|
||||
p95 = None
|
||||
if latencies:
|
||||
ordered = sorted(latencies)
|
||||
p95 = ordered[max(0, math.ceil(0.95 * len(ordered)) - 1)]
|
||||
|
||||
repeated = [outcomes for outcomes in outcomes_by_case.values() if len(outcomes) > 1]
|
||||
consistent = sum(1 for outcomes in repeated if len(set(outcomes)) == 1)
|
||||
|
||||
return {
|
||||
"evaluation": "baseline_descriptive_only",
|
||||
"gate": None,
|
||||
"k": k,
|
||||
"cases_total": len(case_by_id),
|
||||
"cases_evaluated": len(run_case_ids),
|
||||
"retrieval_hit_at_k": {
|
||||
"hits": hits,
|
||||
"eligible": answerable,
|
||||
"rate": hits / answerable if answerable else None,
|
||||
},
|
||||
"citation_precision": {
|
||||
"matches": citation_matches,
|
||||
"total": citation_total,
|
||||
"rate": citation_matches / citation_total if citation_total else None,
|
||||
},
|
||||
"abstention_marker_rate": {
|
||||
"detected": abstention_detected,
|
||||
"expected": abstention_expected,
|
||||
"rate": abstention_detected / abstention_expected if abstention_expected else None,
|
||||
"interpretation": "heurística lexical; requer revisão humana",
|
||||
},
|
||||
"latency_ms": {
|
||||
"samples": len(latencies),
|
||||
"mean": mean(latencies) if latencies else None,
|
||||
"p50_median": median(latencies) if latencies else None,
|
||||
"p95_nearest_rank": p95,
|
||||
},
|
||||
"human_fidelity_reviews_pending": manual_review,
|
||||
"stability": {
|
||||
"repeated_cases": len(repeated),
|
||||
"consistent_cases": consistent,
|
||||
"outcome_consistency_rate": consistent / len(repeated) if repeated else None,
|
||||
"interpretation": "consistência de indicadores binários, não igualdade textual das respostas",
|
||||
},
|
||||
"missing_results": sorted(set(case_by_id) - run_case_ids),
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue