Brings in tobayah/legal-memory's RAG findings (Apache-2.0, CREDITS.md): - the answer prompt is data (app/ai/prompts/answer.json, PL + EN) with two worked examples, the second a REFUSAL although the right act is present; - services/grounding.verify drops every sentence that cites nothing, a passage out of range, an art./section/ust. number, date or act number its CITED passage does not hold (invented vs miscited after searching the whole context), or whose lemmatised words its passage does not support; nothing left = refused; a `verification` block goes to REST and MCP; - retrieval adds up to INSIDER_ANSWER_GRAPH_EXPAND articles one hop away in legal_ref, only while RankPrior.active() (the rank_prior guard); - tests/answer_eval.py: a misbehaving fake generator per failure mode, plus real questions for --live runs; infra-matrix test in bare and full. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
177 lines
7.9 KiB
Python
177 lines
7.9 KiB
Python
"""The cited-answer evaluation: a generator that misbehaves on purpose, and real questions.
|
|
|
|
`tests/fixtures/answer_eval.json`:
|
|
* `fake` — per case a FAKE generator's reply (invents an article, invents the content of an act
|
|
that IS in the passages, cites the wrong passage, cites one out of range, answers with no
|
|
citation, adds a date or an act number from memory …) and what the verifier
|
|
(`services/grounding.verify`, through `semantic.answer` and the real prompt) must make of it:
|
|
refused or not, how many sentences survive, which rules fired. Offline, no model.
|
|
* `real` — questions with the article an answer must cite. Offline, the CONTEXT is checked:
|
|
the full infrastructure profile (`tests/infra.py`: index + graph + PageRank) retrieves, the
|
|
graph expands, and the expected article must be among the passages. With `--live` the
|
|
configured generator (INSIDER_GENERATOR, INSIDER_*_API_KEY, INSIDER_OLLAMA_URL in the
|
|
environment) answers, and the answer must cite that article and pass the verifier.
|
|
|
|
`python tests/answer_eval.py [--live] [--allow-external]` prints the table;
|
|
`tests/test_answer_eval.py` asserts the offline part.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
import json
|
|
import os
|
|
import sys
|
|
import tempfile
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
|
|
|
FIXTURE = Path(__file__).parent / "fixtures" / "answer_eval.json"
|
|
|
|
|
|
def load() -> dict:
|
|
return json.loads(FIXTURE.read_text(encoding="utf-8"))
|
|
|
|
|
|
def passages(spec: dict) -> dict[str, dict]:
|
|
"""Fixture key → a passage as `semantic.collect_passages` builds it (real article text)."""
|
|
import search_eval as se
|
|
acts = {a["eli"]: a for a in se.load_fixture()}
|
|
out = {}
|
|
for key, p in spec.items():
|
|
if "eli" in p:
|
|
art = next(x for x in acts[p["eli"]]["articles"] if x["num"] == p["num"])
|
|
out[key] = {"label": p["label"], "text": art["text"], "id": f"dzu_md:{p['eli']}",
|
|
"kind": "act", "official_url": None, "signature": p["eli"],
|
|
"ord": art["ord"]}
|
|
else:
|
|
out[key] = {"label": p["label"], "text": p["text"], "id": f"inline:{key}",
|
|
"kind": "act", "official_url": None, "signature": None, "ord": None}
|
|
return out
|
|
|
|
|
|
class MisbehavingGenerator:
|
|
"""Says what the case tells it to, whatever it is asked; records the prompt."""
|
|
name = "fake:misbehaving"
|
|
|
|
def __init__(self, reply: str) -> None:
|
|
self.reply, self.seen = reply, []
|
|
|
|
async def complete(self, system, user, *, max_tokens=800, is_admin=False,
|
|
allow_external=False):
|
|
self.seen.append((system, user))
|
|
return self.reply
|
|
|
|
|
|
def run_fake(min_support: float | None = None) -> list[dict]:
|
|
from app.services import grounding, semantic
|
|
data = load()
|
|
pool = passages(data["passages"])
|
|
rows = []
|
|
for case in data["fake"]:
|
|
gen = MisbehavingGenerator(case["reply"])
|
|
ps = [pool[k] for k in case["passages"]]
|
|
out = asyncio.run(semantic.answer(
|
|
gen, case["question"], ps,
|
|
min_support=grounding.MIN_SUPPORT if min_support is None else min_support))
|
|
ver = out["verification"]
|
|
got = {"refused": out["refused"], "kept": ver["kept"],
|
|
"rules": [f["rule"] for f in ver["flagged"]]}
|
|
exp = case["expect"]
|
|
ok = (got["refused"] == exp["refused"] and got["kept"] == exp["kept"]
|
|
and got["rules"] == exp["rules"]
|
|
and ver["model_refused"] == exp.get("model_refused", False))
|
|
rows.append({"name": case["name"], "ok": ok, "got": got, "expect": exp,
|
|
"flagged": ver["flagged"], "prompt": gen.seen[0] if gen.seen else None})
|
|
return rows
|
|
|
|
|
|
def _world(root: Path):
|
|
import infra
|
|
profile = infra.PROFILES["full"]
|
|
return infra.World(profile, root)
|
|
|
|
|
|
def _has(ps: list[dict], eli: str, num: str, store) -> bool:
|
|
for p in ps:
|
|
if p.get("id") == f"dzu_md:{eli}" and p.get("ord") is not None:
|
|
art = store.get_articles(eli, [p["ord"]]).get(p["ord"]) or {}
|
|
if art.get("num") == num:
|
|
return True
|
|
return False
|
|
|
|
|
|
def run_real(*, live: bool = False, allow_external: bool = False) -> list[dict]:
|
|
"""Per real question: the context holds the expected article (offline), and with `live`
|
|
the generator's answer cites it and passes the verifier."""
|
|
from app.services import semantic
|
|
data = load()
|
|
rows = []
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
world = _world(Path(tmp))
|
|
try:
|
|
world.activate()
|
|
gen = None
|
|
if live:
|
|
from app import ai
|
|
gen = ai.generator(SimpleNamespace(
|
|
insider_generator=os.environ.get("INSIDER_GENERATOR", "none"),
|
|
insider_generator_api_key=os.environ.get("INSIDER_GENERATOR_API_KEY", ""),
|
|
insider_anthropic_api_key=os.environ.get("INSIDER_ANTHROPIC_API_KEY", ""),
|
|
insider_ollama_url=os.environ.get("INSIDER_OLLAMA_URL",
|
|
"http://localhost:11434/v1"),
|
|
model_provider_secret=os.environ.get("MODEL_PROVIDER_SECRET", "")))
|
|
if gen is None:
|
|
raise SystemExit("--live needs INSIDER_GENERATOR")
|
|
models = semantic.get_models()
|
|
semantic.set_models(semantic.Models(models.embedder, models.reranker, gen))
|
|
for case in data["real"]:
|
|
ps, _res, exp = asyncio.run(world.legal.answer_context(case["q"]))
|
|
store = world.store
|
|
in_ctx = all(_has(ps, e, n, store) for e, n in case["articles"])
|
|
row = {"q": case["q"], "context_ok": in_ctx, "passages": len(ps),
|
|
"graph_added": exp.get("added", 0)}
|
|
if live:
|
|
out = asyncio.run(world.legal.answer(case["q"],
|
|
allow_external=allow_external))
|
|
cited = [c for c in out["citations"]]
|
|
hit = all(any(c["id"] == f"dzu_md:{e}" and _has([c], e, n, store)
|
|
for c in cited) for e, n in case["articles"])
|
|
row.update(answer_ok=hit and not out["refused"]
|
|
and out["verification"]["passed"],
|
|
refused=out["refused"], answer=out["answer"],
|
|
flagged=[f["rule"] for f in out["verification"]["flagged"]])
|
|
rows.append(row)
|
|
finally:
|
|
world.close()
|
|
return rows
|
|
|
|
|
|
def main(argv: list[str]) -> int:
|
|
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
|
live, ext = "--live" in argv, "--allow-external" in argv
|
|
fake = run_fake()
|
|
print(f"{'misbehaving generator':<62} {'result':<8} rules")
|
|
for r in fake:
|
|
print(f"{r['name'][:62]:<62} {'ok' if r['ok'] else 'FAIL':<8} {r['got']['rules']}"
|
|
+ ("" if r["ok"] else f" expected {r['expect']}"))
|
|
real = run_real(live=live, allow_external=ext)
|
|
print(f"\n{'real question':<70} context graph+" + (" answer" if live else ""))
|
|
for r in real:
|
|
line = f"{r['q'][:70]:<70} {'ok' if r['context_ok'] else 'MISS':<8} {r['graph_added']:<6}"
|
|
if live:
|
|
line += f" {'ok' if r['answer_ok'] else 'FAIL'} {r['flagged']}"
|
|
print(line)
|
|
# context recall is REPORTED, not failed: it measures retrieval, which search_eval owns
|
|
recall = sum(r["context_ok"] for r in real)
|
|
bad = sum(not r["ok"] for r in fake) + sum(not r.get("answer_ok", True) for r in real)
|
|
print(f"\n{len(fake)} fake cases, {len(real)} real questions "
|
|
f"(context recall {recall}/{len(real)}), {bad} failing")
|
|
return 1 if bad else 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
raise SystemExit(main(sys.argv[1:]))
|