From 4c6e77017e945c0366fed50a7d0021f0149e6538 Mon Sep 17 00:00:00 2001 From: Alpaq92 Date: Fri, 23 Oct 2026 23:15:50 +0200 Subject: [PATCH] Ground cited answers: few-shot refusal, a verifier, graph expansion, an eval 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 --- .env.example | 5 + CLAUDE.md | 9 + CREDITS.md | 2 +- README.md | 26 ++- backend/app/ai/prompts/answer.json | 53 +++++ backend/app/config.py | 6 + backend/app/mcp_server.py | 12 +- backend/app/routers/legal.py | 8 +- backend/app/services/grounding.py | 277 ++++++++++++++++++++++++ backend/app/services/legal.py | 104 ++++++++- backend/app/services/runtime.py | 4 +- backend/app/services/semantic.py | 66 ++---- backend/tests/answer_eval.py | 176 +++++++++++++++ backend/tests/fixtures/answer_eval.json | 69 ++++++ backend/tests/test_answer_eval.py | 26 +++ backend/tests/test_grounding.py | 150 +++++++++++++ backend/tests/test_infra_matrix.py | 41 ++++ backend/tests/test_semantic.py | 12 +- 18 files changed, 977 insertions(+), 69 deletions(-) create mode 100644 backend/app/ai/prompts/answer.json create mode 100644 backend/app/services/grounding.py create mode 100644 backend/tests/answer_eval.py create mode 100644 backend/tests/fixtures/answer_eval.json create mode 100644 backend/tests/test_answer_eval.py create mode 100644 backend/tests/test_grounding.py diff --git a/.env.example b/.env.example index 58d1058..e77ef2c 100644 --- a/.env.example +++ b/.env.example @@ -234,6 +234,11 @@ INSIDER_ANTHROPIC_API_KEY= INSIDER_OLLAMA_URL=http://localhost:11434/v1 # the platform's provider-key secret (the hub's MODEL_PROVIDER_SECRET), for provider:… MODEL_PROVIDER_SECRET= +# Cited answers are verified sentence by sentence (README "Models"): the share of a sentence's +# lemmatised words its cited passage must hold (0 = no lexical check), and how many articles one +# hop away in the reference graph join the passages (only while the graph is complete; 0 = never). +INSIDER_ANSWER_MIN_SUPPORT=0.35 +INSIDER_ANSWER_GRAPH_EXPAND=4 # ── OCR (acts published only as PDF) ──────────────────────────────────────── # auto | paddle_vl | paddle | tesseract | off. The core image has the PDF text layer only; the diff --git a/CLAUDE.md b/CLAUDE.md index cf565c7..64de2f3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -383,6 +383,15 @@ frontend/ui/v1/ the family's shared shell (a copy of Atrium's; don't edit loca ## Invariants — preserve these +- **A cited answer is verified, not trusted** (`services/grounding.py`, README "Models"). The prompt + (rules + a grounded example + a REFUSAL with the right act present) is data in + `app/ai/prompts/answer.json` — keep the refusal example, it is what stops invented article content. + `verify` drops every sentence whose art./§/ust., date or act number is not in the passage it + CITES, or whose lemmatised words are not supported by it; nothing left = refused. Search the + whole context before calling something invented (amending-act titles quote EU acts). The graph + only WIDENS the passages (one hop, after retrieval's, `RankPrior.active` guard) — never replaces. + `answer_question` stays optional: the MCP facts tools are the default reader path. + - **NEVER add logic to a shim.** `models/__init__.py` (its core re-exports), `services/auth.py`, `services/authz.py` (`nodes` tenancy only — in `simple` it is local logic), `services/audit.py`, `db.py`, `errors.py`, `security.py` and `enums.py` exist so call sites keep their import paths. diff --git a/CREDITS.md b/CREDITS.md index 464dec6..7a248aa 100644 --- a/CREDITS.md +++ b/CREDITS.md @@ -73,7 +73,7 @@ Deliberately **not** used: Surya (GPL + restricted weights), MinerU (AGPL), mark | Project | License | What Insider took | |---|---|---| -| [tobayah/legal-memory](https://github.com/tobayah/legal-memory) (Tobiasz; commit `bb93733`) | **Apache-2.0** (LICENSE in the repository) | the graph model (Act › Księga › Tytuł › Dział › Rozdział › Oddział › Article; article→article edges with their type and the citing sentence), the in-body reference rules of `src/refs-inbody.ts` (the list / range continuation, the 80-article range cap, `ODSYLA_DO` / `STOSUJE_ODPOWIEDNIO` / `Z_ZASTRZEZENIEM` with their confidences, precision over recall), the MCP shape `find_article` / `references` / `trace_path`, and its self-checks as `backend/tests/test_legalref.py`. Re-implemented in Python (a lark grammar instead of the TypeScript regexes, Postgres instead of a JSON file); no code copied verbatim | +| [tobayah/legal-memory](https://github.com/tobayah/legal-memory) (Tobiasz; commit `bb93733`) | **Apache-2.0** (LICENSE in the repository) | the graph model (Act › Księga › Tytuł › Dział › Rozdział › Oddział › Article; article→article edges with their type and the citing sentence), the in-body reference rules of `src/refs-inbody.ts` (the list / range continuation, the 80-article range cap, `ODSYLA_DO` / `STOSUJE_ODPOWIEDNIO` / `Z_ZASTRZEZENIEM` with their confidences, precision over recall), the MCP shape `find_article` / `references` / `trace_path`, and its self-checks as `backend/tests/test_legalref.py`. From its RAG reader (`rag/answer_l1.py`, `HANDOFF.md`): the second few-shot example that refuses although the right act is among the sources (`backend/app/ai/prompts/answer.json`), the citation checks of its `_check` (source numbers in range, "art. N" / act dates absent from the context, no citation), the "graph as expander over retrieval, not instead of it" design, and the ops note that amending-act titles quote whole EU acts — re-implemented and extended in `services/grounding.py` (checks against the CITED passage, lexical support through Insider's analyzer) Re-implemented in Python (a lark grammar instead of the TypeScript regexes, Postgres instead of a JSON file); no code copied verbatim | ## Data sources diff --git a/README.md b/README.md index b695304..99d5145 100644 --- a/README.md +++ b/README.md @@ -266,7 +266,31 @@ as a key reader, decrypted with the platform's `MODEL_PROVIDER_SECRET`. Plain ht numbered passages → the model answers **only from them**, every sentence ending in `[n]`. Sentences that cite nothing (or a passage that does not exist) are dropped; nothing left, or the model's `BRAK_PODSTAW`, is a refusal (`refused: true`). `citations[]` names each passage: act + article or - judgment signature + court, with the `official_url`. + judgment signature + court, with the `official_url`. `lang=pl|en` picks the answer's language. + - **The prompt is data** (`backend/app/ai/prompts/answer.json`): the rules plus two worked examples + per language — one grounded answer, and one **refusal although the right act is among the + passages** (the passage does not say what is asked). tobayah/legal-memory found that a ban in + the system prompt alone did not stop invented article content; that second example did. + - **The graph widens the passages, never replaces them.** After retrieval, up to + `INSIDER_ANSWER_GRAPH_EXPAND` (4; 0 = off) articles one hop away in `legal_ref` — what the + retrieved articles cite and what cites them — are appended, marked `via: graph:*`, after the + retrieved ones. Only while the graph is complete by the same guard as `rank_prior` + (`RankPrior.active`); otherwise skipped. `graph_expansion: {used, added, cap, skipped?}` says which. + - **Every sentence is verified** (`services/grounding.verify`) and dropped on the first rule it + fails: `no_citation`; `source_out_of_range`; an art. / § / ust. number, a date, or an act number + (`2016/679`, `poz. N`, a case signature) **not in the passage it cites** (`invented_*` when no + passage has it, `miscited_*` when another does — the whole context is searched first, because + Polish amending acts quote whole EU acts in their titles); and `low_support`: fewer than + `INSIDER_ANSWER_MIN_SUPPORT` (0.35) of its content words, lemmatised by Insider's analyzer, are + in the cited passage — which catches an invented description of an act that IS among the + sources (Polish answers; an English one is not measured, `support_checked: false`). Nothing + left → refused. The response (and the MCP result) carries `verification: {passed, flagged[] + (sentence, rule, detail, action), kept, sentences, model_refused, min_support}`. + - **Optional by design.** The MCP search / resolve / graph tools serve the facts to a client that + is itself a better reader; `answer_question` is for clients that want Insider to answer. + - `python backend/tests/answer_eval.py` runs a generator that misbehaves on purpose (invents an + article, cites the wrong passage, answers with no support …) and checks each is caught; real + questions with the article an answer must cite run with `--live` against `INSIDER_GENERATOR`. **Questions leaving the machine.** A generator is *external* unless it is a server on localhost (or `ollama`/`host.docker.internal`) or a `local` platform provider. An external one is refused until an diff --git a/backend/app/ai/prompts/answer.json b/backend/app/ai/prompts/answer.json new file mode 100644 index 0000000..e8cf297 --- /dev/null +++ b/backend/app/ai/prompts/answer.json @@ -0,0 +1,53 @@ +{ + "_comment": "The cited-answer prompt (services/grounding.py builds it). Data, not code: edit the rules and the worked examples here. The refusal token stays BRAK_PODSTAW in every language (the verifier looks for it). The SECOND example is the one that matters: the right act IS among the passages, but the passage does not say what is asked, so the model refuses. A system-prompt ban alone did not stop invented article content (tobayah/legal-memory, Apache-2.0, CREDITS.md); this pair did.", + "pl": { + "system": "Odpowiadasz na pytania prawne WYŁĄCZNIE na podstawie ponumerowanych fragmentów aktów prawnych i orzeczeń podanych przez użytkownika. Zasady: (1) każde zdanie odpowiedzi kończy się odwołaniem do fragmentu w nawiasach kwadratowych, np. [2] albo [1][3]; (2) nie korzystasz z wiedzy spoza fragmentów i nie wymyślasz przepisów, ich treści, dat ani sygnatur; (3) numer artykułu, paragrafu lub ustępu podajesz tylko wtedy, gdy występuje w cytowanym fragmencie; (4) jeżeli fragmenty nie wystarczają do odpowiedzi — także wtedy, gdy właściwy akt jest wśród fragmentów, ale nie zawierają one treści, o którą chodzi — odpowiadasz dokładnie słowem BRAK_PODSTAW i niczym więcej; (5) odpowiadasz w języku pytania, zwięźle.", + "examples_heading": "Przykłady (wzór postępowania, nie źródła):", + "example_heading": "Przykład {n}", + "passages": "Fragmenty:", + "question": "Pytanie:", + "answer": "Odpowiedź:", + "related": "powiązany przepis", + "examples": [ + { + "passages": [ + {"label": "Kodeks pracy, art. 52", "text": "Art. 52. § 1. Pracodawca może rozwiązać umowę o pracę bez wypowiedzenia z winy pracownika w razie: 1) ciężkiego naruszenia przez pracownika podstawowych obowiązków pracowniczych; 2) popełnienia przez pracownika w czasie trwania umowy o pracę przestępstwa, które uniemożliwia dalsze zatrudnianie go na zajmowanym stanowisku, jeżeli przestępstwo jest oczywiste lub zostało stwierdzone prawomocnym wyrokiem."} + ], + "question": "Kiedy pracodawca może rozwiązać umowę o pracę bez wypowiedzenia z winy pracownika?", + "answer": "Pracodawca może rozwiązać umowę bez wypowiedzenia z winy pracownika w razie ciężkiego naruszenia przez pracownika podstawowych obowiązków pracowniczych [1]. Może to zrobić także, gdy pracownik popełnił w czasie trwania umowy przestępstwo uniemożliwiające dalsze zatrudnianie go na zajmowanym stanowisku, jeżeli przestępstwo jest oczywiste lub stwierdzone prawomocnym wyrokiem [1]." + }, + { + "passages": [ + {"label": "Kodeks cywilny, art. 415", "text": "Art. 415. Kto z winy swej wyrządził drugiemu szkodę, obowiązany jest do jej naprawienia."} + ], + "question": "W jakim terminie przedawnia się roszczenie o naprawienie szkody z art. 415 Kodeksu cywilnego?", + "answer": "BRAK_PODSTAW" + } + ] + }, + "en": { + "system": "You answer legal questions ONLY from the numbered passages of legal acts and judgments the user gives you. Rules: (1) every sentence of the answer ends with a reference to a passage in square brackets, e.g. [2] or [1][3]; (2) you use no knowledge from outside the passages and never invent provisions, their content, dates or case numbers; (3) you give an article, paragraph (§) or section (ust.) number only when it appears in the cited passage; (4) when the passages do not support an answer — including when the right act is among them but they do not contain what is asked — you reply with exactly the word BRAK_PODSTAW and nothing else; (5) you answer in English, briefly; quote Polish legal terms as they appear in the passages.", + "examples_heading": "Examples (how to behave, not sources):", + "example_heading": "Example {n}", + "passages": "Passages:", + "question": "Question:", + "answer": "Answer:", + "related": "related provision", + "examples": [ + { + "passages": [ + {"label": "Kodeks pracy, art. 52", "text": "Art. 52. § 1. Pracodawca może rozwiązać umowę o pracę bez wypowiedzenia z winy pracownika w razie: 1) ciężkiego naruszenia przez pracownika podstawowych obowiązków pracowniczych; 2) popełnienia przez pracownika w czasie trwania umowy o pracę przestępstwa, które uniemożliwia dalsze zatrudnianie go na zajmowanym stanowisku, jeżeli przestępstwo jest oczywiste lub zostało stwierdzone prawomocnym wyrokiem."} + ], + "question": "When may an employer terminate an employment contract without notice through the employee's fault?", + "answer": "The employer may terminate the contract without notice (bez wypowiedzenia) for a grave breach by the employee of basic employee duties (ciężkiego naruszenia podstawowych obowiązków pracowniczych) [1]. It may also do so when the employee committed, during the contract, an offence (przestępstwo) that prevents further employment in the position, if the offence is obvious or confirmed by a final judgment (prawomocnym wyrokiem) [1]." + }, + { + "passages": [ + {"label": "Kodeks cywilny, art. 415", "text": "Art. 415. Kto z winy swej wyrządził drugiemu szkodę, obowiązany jest do jej naprawienia."} + ], + "question": "What is the limitation period for a damages claim under art. 415 of the Civil Code?", + "answer": "BRAK_PODSTAW" + } + ] + } +} diff --git a/backend/app/config.py b/backend/app/config.py index 8eff4a1..5bb29fd 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -266,6 +266,12 @@ class Settings(BaseSettings): insider_ollama_url: str = "http://localhost:11434/v1" # the platform's provider-key secret (shared with the hub), for INSIDER_GENERATOR=provider:… model_provider_secret: str = "" + # Cited answers (services/grounding.py): a sentence citing a passage must share at least this + # share of its lemmatised content words with it, or it is dropped (0 = no lexical check) … + insider_answer_min_support: float = Field(default=0.35, ge=0, le=1) + # … and the reference graph adds up to this many articles one hop from the retrieved ones + # (what they cite, what cites them) — only while the graph is complete; 0 = never. + insider_answer_graph_expand: int = Field(default=4, ge=0, le=20) # ── OCR (PDF-only acts) ─────────────────────────────────────────────────────── # auto: text layer → PaddleOCR-VL (GPU only) → PaddleOCR PP-OCRv5 (CPU) → Tesseract, escalating diff --git a/backend/app/mcp_server.py b/backend/app/mcp_server.py index 73222e3..937d29f 100644 --- a/backend/app/mcp_server.py +++ b/backend/app/mcp_server.py @@ -162,17 +162,21 @@ async def get_judgment(judgment: str, source: Literal["saos", "eurlex"] | None = @mcp.tool() async def answer_question(question: str, - jurisdiction: Literal["all", "pl", "eu"] = "all") -> dict[str, Any]: + jurisdiction: Literal["all", "pl", "eu"] = "all", + lang: Literal["pl", "en"] = "pl") -> dict[str, Any]: """Answer a legal question ONLY from passages Insider retrieves: every sentence cites a passage ([n] → `citations`: act + article or judgment signature, with its official_url), and - the answer is refused (`refused: true`) when the passages do not support one. Available only - when the instance's administrator enabled answers; not legal advice.""" + the answer is refused (`refused: true`) when the passages do not support one. Every sentence + is verified against the passage it cites (its art./§/ust. numbers, dates and act numbers must + be there, and enough of its words); `verification` lists what was dropped and why. Optional: + the search, resolve and graph tools give the facts to a client that reads them itself. + Available only when the instance's administrator enabled answers; not legal advice.""" from .services import aiswitch flags = aiswitch.flags() if not flags["ai_answers"]: return {"error": "Conflict", "detail": "Answers are switched off on this instance.", "status": 409} - return await _call(_legal().answer(question[:1000], jurisdiction=jurisdiction, + return await _call(_legal().answer(question[:1000], jurisdiction=jurisdiction, lang=lang, allow_external=flags["ai_external_allowed"])) diff --git a/backend/app/routers/legal.py b/backend/app/routers/legal.py index c0761b6..294147b 100644 --- a/backend/app/routers/legal.py +++ b/backend/app/routers/legal.py @@ -78,15 +78,17 @@ async def _ai(user: AppUser, flag: str, arg: str | None = None) -> dict: @router.get("/answer") async def answer(q: str = Query(min_length=3, max_length=1000), jurisdiction: Literal["all", "pl", "eu"] = "all", + lang: Literal["pl", "en"] = "pl", user: AppUser = Depends(get_current_user), legal: Legal = Depends(get_legal)) -> dict: - """A cited answer from the retrieved passages (every sentence cites one) or a refusal — - only when an administrator turned on `ai_answers` (README "Models").""" + """A cited answer from the retrieved passages (every sentence grounded in the passage it + cites, `verification` says what was dropped and why) or a refusal — only when an + administrator turned on `ai_answers` (README "Models"). `lang` = the answer's language.""" from ..errors import ConflictError ai = await _ai(user, "ai_answers") if not ai.pop("_on"): raise ConflictError("Answers are switched off (Administracja → Modele).") - return await legal.answer(q, jurisdiction=jurisdiction, **ai) + return await legal.answer(q, jurisdiction=jurisdiction, lang=lang, **ai) @router.get("/search/pending") diff --git a/backend/app/services/grounding.py b/backend/app/services/grounding.py new file mode 100644 index 0000000..9191a78 --- /dev/null +++ b/backend/app/services/grounding.py @@ -0,0 +1,277 @@ +"""Cited answers: the prompt (from `app/ai/prompts/answer.json`) and the post-generation verifier. + +Two findings of tobayah/legal-memory's RAG reader (Apache-2.0, CREDITS.md) shape this module: + + * **the prompt** — a system-prompt ban alone did NOT stop a model inventing an article's content; + a second worked example in which the model REFUSES although the right act is among the sources + did. Both examples (one grounded answer, that refusal) live in the data file, per language. + * **a cheap citation checker** — out-of-range source numbers, "art. N" absent from the context, + act dates absent from the context, no citation at all. Their checker could not catch an + invented description of an act that IS in the sources (their context held titles only). + Insider has the passages' text, so this verifier goes further: every reference is checked + against the passages the sentence CITES, and every cited sentence must share enough of its + (lemmatised) content words with them. + +`verify` is the one decision: it keeps the sentences that pass, drops the others with the rule +that dropped them, and refuses when nothing grounded remains. Before calling a sentence +invented, the WHOLE context is searched (legal-memory's ops gotcha: Polish amending acts quote +whole EU acts in their titles) — that only changes the reason given (`miscited` vs `invented`), +never whether the sentence stays: a fact the cited passage does not hold is not grounded by it. +""" +from __future__ import annotations + +import functools +import json +import re +from pathlib import Path + +REFUSAL = "BRAK_PODSTAW" +LANGS = ("pl", "en") +PROMPT_FILE = Path(__file__).resolve().parent.parent / "ai" / "prompts" / "answer.json" +PASSAGE_CHARS = 1500 +#: the share of a cited sentence's content words its cited passages must hold (lemmatised) +MIN_SUPPORT = 0.35 +#: a sentence with fewer content words than this is not measured (too short to say anything) +SUPPORT_MIN_WORDS = 3 + +# ── the prompt ───────────────────────────────────────────────────────────────────────────────── + + +@functools.lru_cache(maxsize=1) +def _prompts() -> dict: + return json.loads(PROMPT_FILE.read_text(encoding="utf-8")) + + +def prompt_spec(lang: str = "pl") -> dict: + return _prompts()[lang if lang in LANGS else "pl"] + + +def _block(spec: dict, passages: list[dict], question: str) -> str: + body = "\n\n".join(f"[{i}] {p['label']}\n{p['text'][:PASSAGE_CHARS]}" + for i, p in enumerate(passages, 1)) + return f"{spec['passages']}\n\n{body}\n\n{spec['question']} {question.strip()[:1000]}" + + +def build_prompt(question: str, passages: list[dict], lang: str = "pl") -> tuple[str, str]: + """(system, user): the rules, then the worked examples (as text — the generator interface is + one system prompt + one user message), then the numbered passages and the question.""" + spec = prompt_spec(lang) + shots = [f"{spec['example_heading'].format(n=n)}\n{_block(spec, ex['passages'], ex['question'])}" + f"\n{spec['answer']} {ex['answer']}" + for n, ex in enumerate(spec["examples"], 1)] + system = spec["system"] + "\n\n" + spec["examples_heading"] + "\n\n" + "\n\n".join(shots) + return system, _block(spec, passages, question) + + +# ── the verifier ─────────────────────────────────────────────────────────────────────────────── +_CITE = re.compile(r"\[(\d{1,2}(?:\s*,\s*\d{1,2})*)\]") +_BREAK = re.compile(r"([.!?…])\s+(?=[A-ZĄĆĘŁŃÓŚŹŻ(\"„])|\n+") +#: a full stop after these is an abbreviation, not a sentence end ("art. 52", "Dz. U.", "2018 r.") +_ABBR = {"art", "ust", "poz", "pkt", "dz", "u", "r", "nr", "zm", "lit", "np", "tj", "t.j", "k.c", + "k.p", "k.k", "k.p.c", "k.p.k", "in", "m.in", "ww", "tzw", "ok", "tys", "zob", "por", + "sygn", "akt", "prof", "dr", "św", "i", "ii", "iii", "iv", "v", "vi"} +_NUM = r"\d+[a-z]?(?:[¹²³⁴⁵⁶⁷⁸⁹⁰ᵃᵇᶜᵈᵉᶠᵍʰⁱʲᵏˡᵐⁿᵒᵖʳˢᵗᵘᵛʷˣʸᶻ]+)?" +_LIST = rf"{_NUM}(?:\s*(?:,|i|oraz|lub|albo|-|–|—)\s*{_NUM})*" +_REFS = { + "art": re.compile(rf"\bart(?:ykuł\w*|\.)\s*({_LIST})", re.I), + "§": re.compile(rf"§§?\s*({_LIST})"), + "ust": re.compile(rf"\bust(?:\.|ęp\w*)\s*({_LIST})", re.I), +} +_MONTHS = ("stycznia lutego marca kwietnia maja czerwca lipca sierpnia września października " + "listopada grudnia").split() +_DATE = re.compile(r"\b(\d{1,2})\s+(" + "|".join(_MONTHS) + r")\s+(\d{4})\b" + r"|\b(\d{1,2})[./](\d{1,2})[./](\d{4})\b", re.I) +#: act numbers: (UE) 2016/679 · 2016/679 · Dz. U. … poz. 1465 · a case signature (II CSK 123/20) +_ACTNUM = re.compile(r"\b(\d{4}/\d{1,5}|\d{1,5}/\d{4})\b|\bpoz\.\s*(\d+)" + r"|\b([IVX]{1,4}\s+[A-Z][A-Za-z]{0,4}\s+\d{1,5}/\d{2})\b") + + +def _nums(s: str) -> list[str]: + return [n.lower().replace(" ", "") for n in re.findall(_NUM, s)] + + +def _expand(found: str) -> list[str]: + """"52 i 53" → [52, 53]; "52–55" → 52..55 when short; superscripts kept as written.""" + parts = re.split(r"\s*(-|–|—)\s*", found) + if len(parts) == 3 and all(p.isdecimal() for p in (parts[0], parts[2])) \ + and 0 < int(parts[2]) - int(parts[0]) <= 20: + return [str(i) for i in range(int(parts[0]), int(parts[2]) + 1)] + return _nums(found) + + +def refs_in(text: str) -> set[tuple[str, str]]: + """{("art", "52"), ("§", "1"), ("ust", "2")} mentioned in `text`.""" + out = set() + for kind, rx in _REFS.items(): + for m in rx.finditer(text): + out |= {(kind, n) for n in _expand(m.group(1))} + return out + + +def passage_refs(text: str) -> set[tuple[str, str]]: + """What a passage holds: its explicit mentions, plus the numbering a statute prints without + the word — "Art. 52." heads, "§ 1." paragraphs, "1." sections at a line start or after a + full stop (a section never says "ust. 1" about itself).""" + out = refs_in(text) + out |= {("ust", n) for n in re.findall(r"(?:^|[.:;]\s+|\n)\s*(\d+[a-z]?)\.\s+[A-ZŁŚŻŹĆŃÓĘĄ]", + text)} + return out + + +def _norm(s: str) -> str: + return re.sub(r"\s+", " ", s.lower()).replace(" ", " ") + + +def dates_in(text: str) -> set[str]: + out = set() + for m in _DATE.finditer(text): + if m.group(1): + d, mo, y = int(m.group(1)), _MONTHS.index(m.group(2).lower()) + 1, m.group(3) + else: + d, mo, y = int(m.group(4)), int(m.group(5)), m.group(6) + out.add(f"{y}-{mo:02d}-{d:02d}") + return out + + +def actnums_in(text: str) -> set[str]: + out = set() + for m in _ACTNUM.finditer(text): + if m.group(1): + out.add(m.group(1)) + elif m.group(2): + out.add(f"poz.{m.group(2)}") + else: + out.add(re.sub(r"\s+", " ", m.group(3)).upper()) + return out + + +def _terms(text: str, lang: str) -> set[str]: + from ..integrations import analysis + try: + return set(analysis.analyse(text, lang).split()) + except Exception: # noqa: BLE001 — no analyzer: the words themselves + return set(analysis.words(text.lower())) + + +def support(sentence: str, passages_text: str, lang: str = "pl") -> float | None: + """The share of the sentence's content terms (citations, numbers removed) its cited passages + hold, through Insider's analyzer — lemmas where the lexicon has them, stems otherwise. + None: too short to measure.""" + s = _CITE.sub(" ", sentence) + s = re.sub(r"\d+", " ", s) + have = _terms(s, lang) + if len(have) < SUPPORT_MIN_WORDS: + return None + return len(have & _terms(passages_text, lang)) / len(have) + + +def _cites(sentence: str) -> list[int]: + return [int(n) for grp in _CITE.findall(sentence) for n in re.split(r"\s*,\s*", grp)] + + +def _sentences(text: str) -> list[str]: + """Split at a sentence end: a stop + space + a capital — not after an abbreviation.""" + out, start = [], 0 + for m in _BREAK.finditer(text): + if m.group(1): + word = re.search(r"([\w.]+)$", text[start:m.start(1)]) + if word and word.group(1).lower().strip(".") in _ABBR: + continue + out.append(text[start:m.start() + (1 if m.group(1) else 0)]) + start = m.end() + out.append(text[start:]) + return [s.strip() for s in out if s and s.strip()] + + +def verify(raw: str, passages: list[dict], *, lang: str = "pl", + min_support: float = MIN_SUPPORT) -> dict: + """The generated text against the passages it was given → the answer that survives. + + Per sentence, in order (the first rule that fails drops it): + `no_citation` cites no passage + `source_out_of_range` cites [n] with no passage n + `invented_reference` / `miscited_reference` an art. / § / ust. number its cited passages + do not hold (invented: absent from every passage; miscited: another + passage has it) + `invented_date` / `miscited_date`, `invented_act_number` / `miscited_act_number` the same + for a date and an act number / journal position / case signature + `low_support` fewer than `min_support` of its content words are in its cited + passages (Polish answers; an answer in another language than the + passages is not measured — `support_checked: false`) + Nothing left → refused. `verification.passed` = nothing was flagged.""" + text = (raw or "").strip() + n = len(passages) + check_support = lang == "pl" and min_support > 0 + base = {"rules": ["no_citation", "source_out_of_range", "reference", "date", "act_number", + "low_support"], + "min_support": min_support if check_support else None, + "support_checked": check_support} + if not text or text.rstrip(".").strip() == REFUSAL or text.startswith(REFUSAL): + return {"refused": True, "answer": None, "cited": [], "dropped": 0, + "verification": {**base, "passed": True, "model_refused": True, "sentences": 0, + "kept": 0, "flagged": []}} + every = "\n".join(f"{p.get('label', '')}\n{p.get('text', '')}" for p in passages) + every_n = _norm(every) + every_refs, every_dates, every_acts = passage_refs(every), dates_in(every), actnums_in(every) + kept, cited, flagged = [], [], [] + sentences = [s for s in _sentences(text) if REFUSAL not in s] + + def flag(s, rule, detail, n_cited=None, score=None): + item = {"sentence": s, "rule": rule, "detail": detail, "action": "dropped"} + if score is not None: + item["support"] = round(score, 3) + flagged.append(item) + + for s in sentences: + refs = _cites(s) + if not refs: + flag(s, "no_citation", "the sentence cites no passage") + continue + bad = sorted({r for r in refs if not 1 <= r <= n}) + if bad: + flag(s, "source_out_of_range", f"cites {', '.join(f'[{b}]' for b in bad)}; " + f"there are {n} passages") + continue + src = "\n".join(f"{passages[r - 1].get('label', '')}\n{passages[r - 1].get('text', '')}" + for r in dict.fromkeys(refs)) + body = _CITE.sub(" ", s) + problem = None + have = passage_refs(src) + for kind, num in sorted(refs_in(body)): + if (kind, num) not in have: + where = "miscited" if (kind, num) in every_refs else "invented" + problem = (f"{where}_reference", f"{'art.' if kind == 'art' else kind} {num} is " + f"not in the cited passage" + ("" if where == "invented" + else " (another passage has it)")) + break + if problem is None: + src_dates = dates_in(src) + for d in sorted(dates_in(body) - src_dates): + where = "miscited" if d in every_dates else "invented" + problem = (f"{where}_date", f"the date {d} is not in the cited passage") + break + if problem is None: + src_acts = actnums_in(src) + for a in sorted(actnums_in(body) - src_acts): + # the whole context first: an amending act's title quotes whole EU acts + where = "miscited" if (a in every_acts or a.lower() in every_n) else "invented" + problem = (f"{where}_act_number", f"{a} is not in the cited passage") + break + if problem is not None: + flag(s, *problem) + continue + if check_support: + score = support(body, src, lang) + if score is not None and score < min_support: + flag(s, "low_support", f"{score:.0%} of its content words are in the cited " + f"passage (minimum {min_support:.0%})", score=score) + continue + kept.append(s) + cited += [r for r in refs if r not in cited] + ver = {**base, "passed": not flagged, "model_refused": False, "sentences": len(sentences), + "kept": len(kept), "flagged": flagged} + if not kept: + return {"refused": True, "answer": None, "cited": [], "dropped": len(flagged), + "verification": ver} + return {"refused": False, "answer": " ".join(kept), "cited": sorted(cited), + "dropped": len(flagged), "verification": ver} diff --git a/backend/app/services/legal.py b/backend/app/services/legal.py index 781b308..0645712 100644 --- a/backend/app/services/legal.py +++ b/backend/app/services/legal.py @@ -139,8 +139,13 @@ SAOS_POLICY = ("SAOS is used for user-initiated live queries only (its robots.tx class Legal: def __init__(self, registry, cache: SourceCache, texts, codec: CursorCodec, *, budget: float = 10.0, min_text_confidence: float = 0.8, - slow_budget: float = 40.0, secret: str = "", indexing=None) -> None: + slow_budget: float = 40.0, secret: str = "", indexing=None, + answer_min_support: float = 0.35, answer_graph_expand: int = 4) -> None: self.registry = registry + #: cited answers: the verifier's lexical-support floor (`grounding.verify`), and how many + #: graph neighbours of the retrieved articles join the context (0 = never; README "Models") + self.answer_min_support = answer_min_support + self.answer_graph_expand = answer_graph_expand #: INDEXED mode (`services/indexing.Indexing`) or None (LIVE only). Its adapters are in #: the registry like any source; this holds the importers' status for the panel. self.indexing = indexing @@ -295,10 +300,12 @@ class Legal: return base async def answer(self, question: str, *, jurisdiction: str = "all", is_admin: bool = False, - allow_external: bool = False) -> dict: + allow_external: bool = False, lang: str = "pl") -> dict: """A cited answer from the passages retrieval finds (`semantic.answer`), or a refusal. The question is rewritten first (a plain-language question rarely holds every word of - the article that answers it); every claim cites a passage, or the answer is refused.""" + the article that answers it); the graph widens the passages by one hop when it is + complete (`_graph_passages`); every sentence must be grounded in the passage it cites + (`grounding.verify`), or it is dropped — and with nothing left, the answer is refused.""" from . import semantic gen = semantic.get_models().generator if gen is None: @@ -306,18 +313,93 @@ class Legal: question = (question or "").strip() if len(question) < 3: raise ValidationError("Ask a question.") + passages, res, expansion = await self.answer_context( + question, jurisdiction=jurisdiction, is_admin=is_admin, + allow_external=allow_external, lang=lang) + try: + out = await semantic.answer(gen, question, passages, is_admin=is_admin, + allow_external=allow_external, lang=lang, + min_support=self.answer_min_support) + except semantic.ModelUnavailable as exc: + raise UpstreamError(f"The model did not answer: {exc}") from exc + return {"question": question, **out, "model": gen.name, "lang": lang, + "graph_expansion": expansion, + "rewrite": res.get("rewrite"), "sources": res.get("sources"), + "notice": ("Odpowiedź wygenerowana przez model na podstawie cytowanych fragmentów " + "— sprawdź je w źródle; to nie jest porada prawna." if lang != "en" else + "An answer generated by a model from the cited passages — check them " + "at the source; this is not legal advice.")} + + async def answer_context(self, question: str, *, jurisdiction: str = "all", + is_admin: bool = False, allow_external: bool = False, + lang: str = "pl") -> tuple[list[dict], dict, dict]: + """The passages an answer is generated from: retrieval's, then the graph's one hop. + (passages, the search result, the expansion's report) — no generator needed (the + rewrite is skipped without one), so `tests/answer_eval.py` measures it offline.""" + from . import semantic res = await self.search(Query(q=question[:300], jurisdiction=jurisdiction), limit=8, rewrite=True, is_admin=is_admin, allow_external=allow_external) passages = await asyncio.to_thread(semantic.collect_passages, res, self._part_text) + added, expansion = await asyncio.to_thread(self._graph_passages, passages, lang) + return passages + added, res, expansion + + def _graph_passages(self, passages: list[dict], lang: str = "pl") -> tuple[list[dict], dict]: + """One hop of the reference graph from the retrieved ARTICLES (tobayah/legal-memory's + "graph as expander, not replacement"): the articles they cite and the articles citing + them, at most `answer_graph_expand`, ranked by how many retrieved articles reach them and + the edges' confidence, appended AFTER the retrieved passages (`via: graph:*`, weight + 0.5) — never instead of them. Only when the graph is complete by the guard `rank_prior` + uses (`RankPrior.active`: the last build finished, not interrupted, its PageRank pass + covers it); a partial graph would widen the context with whatever happened to be parsed.""" + from .legalgraph import label as art_label + from .legalgraph import printed + ix = self.indexing + graph = getattr(ix, "graph", None) if ix is not None else None + ranker = self._ranker() + cap = max(0, int(self.answer_graph_expand)) + state = {"used": False, "added": 0, "cap": cap} + if cap == 0: + return [], {**state, "skipped": "off"} + if graph is None or ranker is None: + return [], {**state, "skipped": "no graph"} try: - out = await semantic.answer(gen, question, passages, is_admin=is_admin, - allow_external=allow_external) - except semantic.ModelUnavailable as exc: - raise UpstreamError(f"The model did not answer: {exc}") from exc - return {"question": question, **out, "model": gen.name, - "rewrite": res.get("rewrite"), "sources": res.get("sources"), - "notice": "Odpowiedź wygenerowana przez model na podstawie cytowanych fragmentów " - "— sprawdź je w źródle; to nie jest porada prawna."} + if not ranker.active(): + return [], {**state, "skipped": "graph incomplete"} + seeds = [(str(p["id"]).split(":", 1)[1], int(p["ord"])) for p in passages + if str(p.get("id", "")).startswith("dzu_md:") and p.get("ord") is not None] + if not seeds: + return [], {**state, "used": True, "skipped": "no article among the hits"} + have = set(seeds) + score: dict[tuple[str, int], float] = {} + via: dict[tuple[str, int], str] = {} + store = graph.store + for way, rows in (("cites", store.refs_from(seeds, 10 * cap)), + ("cited_by", store.refs_to(seeds, 10 * cap))): + for r in rows: + k = ((r.get("dst_eli"), r.get("dst_ord")) if way == "cites" + else (r.get("src_eli"), r.get("src_ord"))) + if k[1] is None or k in have: + continue + score[k] = score.get(k, 0.0) + float(r.get("confidence") or 0.5) + via.setdefault(k, way) + picked = sorted(score, key=lambda k: (-score[k], k))[:cap] + titles = graph.resolver().title + from . import grounding + related = grounding.prompt_spec(lang)["related"] + out = [] + for eli, o in picked: + art = store.get_articles(eli, [o]).get(o) or {} + if not art.get("text"): + continue + num = printed(art_label(art.get("num"))) or str(art.get("num") or o) + out.append({"label": f"{titles.get(eli, eli)}, art. {num} ({related})", + "text": art["text"], "id": f"dzu_md:{eli}", "kind": "act", + "official_url": None, "signature": eli, "ord": o, + "via": f"graph:{via[(eli, o)]}", "weight": 0.5}) + except Exception as exc: # noqa: BLE001 — the graph widens an answer, never fails it + log.warning("answer: graph expansion skipped: %s", exc) + return [], {**state, "skipped": "error"} + return out, {**state, "used": True, "added": len(out)} def _part_text(self, doc: dict, hit: dict) -> str | None: """An indexed part's full text (an article, a judgment's section) from the local store.""" diff --git a/backend/app/services/runtime.py b/backend/app/services/runtime.py index 9165f34..2826124 100644 --- a/backend/app/services/runtime.py +++ b/backend/app/services/runtime.py @@ -28,7 +28,9 @@ def build_default() -> Legal: CursorCodec(s.insider_cursor_secret), budget=s.insider_search_budget_seconds, min_text_confidence=s.ocr_min_confidence, slow_budget=s.insider_slow_source_budget_seconds, - secret=s.insider_cursor_secret, indexing=indexing) + secret=s.insider_cursor_secret, indexing=indexing, + answer_min_support=s.insider_answer_min_support, + answer_graph_expand=s.insider_answer_graph_expand) def get_legal() -> Legal: diff --git a/backend/app/services/semantic.py b/backend/app/services/semantic.py index 516673e..6c12f08 100644 --- a/backend/app/services/semantic.py +++ b/backend/app/services/semantic.py @@ -29,6 +29,7 @@ from collections.abc import Callable from ..ai import ModelUnavailable from ..integrations import analysis +from . import grounding log = logging.getLogger("insider.semantic") @@ -343,18 +344,11 @@ def fuse_docs(lists: list[list[dict]], limit: int, *, k: int = 60) -> list[dict] # ── (4) cited answers ────────────────────────────────────────────────────────────────────────── -ANSWER_SYSTEM = ( - "Odpowiadasz na pytania prawne WYŁĄCZNIE na podstawie ponumerowanych fragmentów aktów prawnych " - "i orzeczeń podanych przez użytkownika. Zasady: (1) każde zdanie odpowiedzi kończy się " - "odwołaniem do fragmentu w nawiasach kwadratowych, np. [2] albo [1][3]; (2) nie korzystasz " - "z wiedzy spoza fragmentów i nie wymyślasz przepisów ani sygnatur; (3) jeżeli fragmenty nie " - "wystarczają do odpowiedzi, odpowiadasz dokładnie słowem BRAK_PODSTAW i niczym więcej; " - "(4) odpowiadasz w języku pytania, zwięźle.") -REFUSAL = "BRAK_PODSTAW" +# the prompt (rules + worked examples, per language) is data: `app/ai/prompts/answer.json`; +# the post-generation verifier is `services/grounding.verify` (README "Models") +REFUSAL = grounding.REFUSAL MAX_PASSAGES = 10 -PASSAGE_CHARS = 1500 -_CITE = re.compile(r"\[(\d{1,2})\]") -_SENTENCE = re.compile(r"(?<=[.!?…])\s+|\n+") +PASSAGE_CHARS = grounding.PASSAGE_CHARS def passage_label(doc: dict, hit: dict | None) -> str: @@ -369,32 +363,8 @@ def passage_label(doc: dict, hit: dict | None) -> str: return name -def answer_prompt(question: str, passages: list[dict]) -> tuple[str, str]: - body = "\n\n".join(f"[{i}] {p['label']}\n{p['text'][:PASSAGE_CHARS]}" - for i, p in enumerate(passages, 1)) - return ANSWER_SYSTEM, f"Fragmenty:\n\n{body}\n\nPytanie: {question.strip()[:1000]}" - - -def enforce_citations(raw: str, n: int) -> dict: - """Keep only the sentences that cite a passage that exists; refuse when the model refused or - nothing cited survives. `dropped` = sentences removed for citing nothing (or nothing real).""" - text = (raw or "").strip() - if not text or REFUSAL in text: - return {"refused": True, "answer": None, "cited": [], "dropped": 0} - kept, dropped, cited = [], 0, [] - for s in (x.strip() for x in _SENTENCE.split(text)): - if not s: - continue - refs = [int(r) for r in _CITE.findall(s)] - if refs and all(1 <= r <= n for r in refs): - kept.append(s) - cited += [r for r in refs if r not in cited] - else: - dropped += 1 - if not kept: - return {"refused": True, "answer": None, "cited": [], "dropped": dropped} - return {"refused": False, "answer": " ".join(kept), "cited": sorted(cited), - "dropped": dropped} +def answer_prompt(question: str, passages: list[dict], lang: str = "pl") -> tuple[str, str]: + return grounding.build_prompt(question, passages, lang) def collect_passages(result: dict, texts: Callable[[dict, dict], str | None] | None = None, @@ -424,19 +394,27 @@ def collect_passages(result: dict, texts: Callable[[dict, dict], str | None] | N async def answer(generator, question: str, passages: list[dict], *, is_admin: bool = False, - allow_external: bool = False) -> dict: + allow_external: bool = False, lang: str = "pl", + min_support: float = grounding.MIN_SUPPORT) -> dict: + """The model's text, verified (`grounding.verify`): only sentences grounded in the passages + they cite survive, and the `verification` block says what was dropped and why.""" if not passages: return {"refused": True, "answer": None, "citations": [], "dropped": 0, - "reason": "no passages found"} - system, user = answer_prompt(question, passages) + "reason": "no passages found", + "verification": {"passed": True, "model_refused": False, "sentences": 0, + "kept": 0, "flagged": [], "skipped": "no passages"}} + system, user = answer_prompt(question, passages, lang) raw = await generator.complete(system, user, max_tokens=900, is_admin=is_admin, allow_external=allow_external) - res = enforce_citations(raw, len(passages)) - res["citations"] = [{"n": i, **{k: passages[i - 1][k] for k in - ("label", "id", "kind", "official_url", "signature", "ord")}} + res = grounding.verify(raw, passages, lang=lang, min_support=min_support) + res["citations"] = [{"n": i, **{k: passages[i - 1].get(k) for k in + ("label", "id", "kind", "official_url", "signature", "ord")}, + **({"via": passages[i - 1]["via"]} if passages[i - 1].get("via") else {})} for i in res.pop("cited")] if res["refused"]: - res["reason"] = "the passages found do not support an answer" + res["reason"] = ("the model found no support in the passages" + if res["verification"]["model_refused"] + else "no sentence of the answer is grounded in the passages it cites") return res diff --git a/backend/tests/answer_eval.py b/backend/tests/answer_eval.py new file mode 100644 index 0000000..4f23b12 --- /dev/null +++ b/backend/tests/answer_eval.py @@ -0,0 +1,176 @@ +"""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:])) diff --git a/backend/tests/fixtures/answer_eval.json b/backend/tests/fixtures/answer_eval.json new file mode 100644 index 0000000..8102af3 --- /dev/null +++ b/backend/tests/fixtures/answer_eval.json @@ -0,0 +1,69 @@ +{ + "_comment": "tests/answer_eval.py. `passages`: an article of the search_eval fixture (eli + num, its real text) or an inline passage. `fake`: a generator that misbehaves on purpose, and what the verifier must make of it. `real`: questions with the article an answer must cite, for anyone with a local model (--live); offline, the retrieval + graph context is checked to hold that article.", + "passages": { + "kc415": {"eli": "DU/2026/795", "num": "415", "label": "Kodeks cywilny, art. 415"}, + "kc4421": {"eli": "DU/2026/795", "num": "442¹", "label": "Kodeks cywilny, art. 442¹"}, + "kc118": {"eli": "DU/2026/795", "num": "118", "label": "Kodeks cywilny, art. 118"}, + "kp52": {"eli": "DU/2026/1245", "num": "52", "label": "Kodeks pracy, art. 52"}, + "kp30": {"eli": "DU/2026/1245", "num": "30", "label": "Kodeks pracy, art. 30"}, + "najem19a": {"eli": "DU/2023/725", "num": "19a", "label": "Ustawa o ochronie praw lokatorów, art. 19a"}, + "rodo_title": {"label": "Ustawa z dnia 21 lutego 2019 r. o zmianie niektórych ustaw w związku z zapewnieniem stosowania rozporządzenia (UE) 2016/679", + "text": "Ustawa z dnia 21 lutego 2019 r. o zmianie niektórych ustaw w związku z zapewnieniem stosowania rozporządzenia Parlamentu Europejskiego i Rady (UE) 2016/679 z dnia 27 kwietnia 2016 r. w sprawie ochrony osób fizycznych w związku z przetwarzaniem danych osobowych i w sprawie swobodnego przepływu takich danych oraz uchylenia dyrektywy 95/46/WE (ogólne rozporządzenie o ochronie danych)."} + }, + "fake": [ + {"name": "grounded answer (control)", "passages": ["kp52"], + "question": "Kiedy pracodawca może rozwiązać umowę bez wypowiedzenia?", + "reply": "Pracodawca może rozwiązać umowę o pracę bez wypowiedzenia z winy pracownika w razie ciężkiego naruszenia przez pracownika podstawowych obowiązków pracowniczych [1].", + "expect": {"refused": false, "kept": 1, "rules": []}}, + {"name": "invents an article", "passages": ["kc415"], + "question": "W jakim terminie przedawnia się roszczenie o naprawienie szkody?", + "reply": "Roszczenie przedawnia się z upływem trzech lat zgodnie z art. 442¹ [1].", + "expect": {"refused": true, "kept": 0, "rules": ["invented_reference"]}}, + {"name": "invents the content of an act that IS in the sources", "passages": ["kc415"], + "question": "W jakim terminie przedawnia się roszczenie z art. 415 k.c.?", + "reply": "Zgodnie z art. 415 roszczenie o naprawienie szkody przedawnia się z upływem trzech lat od dnia zdarzenia wywołującego szkodę [1].", + "expect": {"refused": true, "kept": 0, "rules": ["low_support"]}}, + {"name": "cites the wrong source (content of [2] under [1])", "passages": ["kc415", "kc4421"], + "question": "W jakim terminie przedawnia się roszczenie o naprawienie szkody?", + "reply": "Roszczenie o naprawienie szkody wyrządzonej czynem niedozwolonym ulega przedawnieniu z upływem lat trzech od dnia, w którym poszkodowany dowiedział się o szkodzie [1].", + "expect": {"refused": true, "kept": 0, "rules": ["low_support"]}}, + {"name": "cites the wrong source for an article number", "passages": ["kc415", "kc4421"], + "question": "W jakim terminie przedawnia się roszczenie o naprawienie szkody?", + "reply": "Termin przedawnienia określa art. 442¹ [1].", + "expect": {"refused": true, "kept": 0, "rules": ["miscited_reference"]}}, + {"name": "cites a source out of range", "passages": ["kp52"], + "question": "Kiedy pracodawca może rozwiązać umowę bez wypowiedzenia?", + "reply": "Pracodawca może rozwiązać umowę bez wypowiedzenia w razie ciężkiego naruszenia obowiązków [1, 4].", + "expect": {"refused": true, "kept": 0, "rules": ["source_out_of_range"]}}, + {"name": "answers without any citation", "passages": ["kp52"], + "question": "Kiedy pracodawca może rozwiązać umowę bez wypowiedzenia?", + "reply": "Pracodawca może zawsze rozwiązać umowę, jeżeli pracownik się spóźnia.", + "expect": {"refused": true, "kept": 0, "rules": ["no_citation"]}}, + {"name": "adds an act date from memory", "passages": ["kp52"], + "question": "Kiedy pracodawca może rozwiązać umowę bez wypowiedzenia?", + "reply": "Pracodawca może rozwiązać umowę o pracę bez wypowiedzenia z winy pracownika w razie ciężkiego naruszenia obowiązków, co przewiduje ustawa z dnia 26 czerwca 1974 r. [1].", + "expect": {"refused": true, "kept": 0, "rules": ["invented_date"]}}, + {"name": "adds an act number from memory", "passages": ["kp52"], + "question": "Kiedy pracodawca może rozwiązać umowę bez wypowiedzenia?", + "reply": "Pracodawca może rozwiązać umowę o pracę bez wypowiedzenia z winy pracownika w razie ciężkiego naruszenia obowiązków (Dz. U. z 2023 r. poz. 1465) [1].", + "expect": {"refused": true, "kept": 0, "rules": ["invented_act_number"]}}, + {"name": "an EU act quoted in an amending act's title is NOT invented", "passages": ["rodo_title"], + "question": "Którą ustawą zapewniono stosowanie RODO?", + "reply": "Stosowanie rozporządzenia (UE) 2016/679 z dnia 27 kwietnia 2016 r. zapewnia ustawa z dnia 21 lutego 2019 r. o zmianie niektórych ustaw [1].", + "expect": {"refused": false, "kept": 1, "rules": []}}, + {"name": "one grounded sentence, one invented: the invented one goes", "passages": ["kp52", "kp30"], + "question": "Jak można rozwiązać umowę o pracę?", + "reply": "Umowa o pracę rozwiązuje się na mocy porozumienia stron albo przez oświadczenie jednej ze stron z zachowaniem okresu wypowiedzenia [2]. Okres wypowiedzenia zawsze wynosi trzy miesiące zgodnie z art. 36 [2].", + "expect": {"refused": false, "kept": 1, "rules": ["invented_reference"]}}, + {"name": "the model refuses", "passages": ["kc415"], + "question": "W jakim terminie przedawnia się roszczenie z art. 415 k.c.?", + "reply": "BRAK_PODSTAW", + "expect": {"refused": true, "kept": 0, "rules": [], "model_refused": true}} + ], + "real": [ + {"q": "Kiedy pracodawca może rozwiązać umowę o pracę bez wypowiedzenia z winy pracownika?", "articles": [["DU/2026/1245", "52"]]}, + {"q": "Czym jest umowa najmu okazjonalnego lokalu?", "articles": [["DU/2023/725", "19a"]]}, + {"q": "Kto odpowiada za szkodę wyrządzoną z winy?", "articles": [["DU/2026/795", "415"]]}, + {"q": "Jaki jest ogólny termin przedawnienia roszczeń?", "articles": [["DU/2026/795", "118"]]} + ] +} diff --git a/backend/tests/test_answer_eval.py b/backend/tests/test_answer_eval.py new file mode 100644 index 0000000..56ec2b1 --- /dev/null +++ b/backend/tests/test_answer_eval.py @@ -0,0 +1,26 @@ +"""The offline part of `tests/answer_eval.py`: every misbehaving generator is caught.""" +from __future__ import annotations + +import pytest +from answer_eval import load, run_fake, run_real + + +@pytest.mark.parametrize("case", [c["name"] for c in load()["fake"]]) +def test_the_verifier_catches_each_misbehaviour(case): + row = next(r for r in run_fake() if r["name"] == case) + assert row["ok"], (row["got"], row["expect"], row["flagged"]) + + +def test_every_fake_prompt_carries_the_refusal_example(): + for r in run_fake(): + system, _user = r["prompt"] + assert system.count("BRAK_PODSTAW") >= 2 + + +def test_the_full_box_widens_the_context_through_the_graph(): + pytest.importorskip("tantivy") + pytest.importorskip("numpy") + rows = run_real() + assert all(r["graph_added"] > 0 for r in rows), rows + # the one question this fixture's retrieval answers today; the others are reported + assert next(r for r in rows if "najmu okazjonalnego" in r["q"])["context_ok"], rows diff --git a/backend/tests/test_grounding.py b/backend/tests/test_grounding.py new file mode 100644 index 0000000..973529e --- /dev/null +++ b/backend/tests/test_grounding.py @@ -0,0 +1,150 @@ +"""Cited answers: the prompt assembly (`app/ai/prompts/answer.json`) and the verifier's rules.""" +from __future__ import annotations + +import asyncio + +import pytest + +from app.services import grounding as g +from app.services import semantic as sem + +KC415 = {"label": "Kodeks cywilny, art. 415", "id": "dzu_md:DU/2026/795", "ord": 471, + "text": "Art. 415. Kto z winy swej wyrządził drugiemu szkodę, obowiązany jest do jej " + "naprawienia."} +KC4421 = {"label": "Kodeks cywilny, art. 442¹", "id": "dzu_md:DU/2026/795", "ord": 503, + "text": "Art. 442¹. § 1. Roszczenie o naprawienie szkody wyrządzonej czynem " + "niedozwolonym ulega przedawnieniu z upływem lat trzech od dnia, w którym " + "poszkodowany dowiedział się o szkodzie. 2. Drugi ustęp."} + + +# ── the prompt ── +@pytest.mark.parametrize("lang", ["pl", "en"]) +def test_the_prompt_carries_both_worked_examples(lang): + system, user = g.build_prompt("Kiedy?", [KC415], lang) + spec = g.prompt_spec(lang) + assert len(spec["examples"]) == 2 + grounded, refusal = spec["examples"] + assert "[1]" in grounded["answer"] and refusal["answer"] == g.REFUSAL + # the refusal's passage IS the right act — that is the example that stops invention + assert "415" in refusal["passages"][0]["label"] and "415" in refusal["question"] + assert grounded["answer"] in system and system.count(g.REFUSAL) >= 2 + assert user.startswith(spec["passages"]) and user.endswith(f"{spec['question']} Kiedy?") + assert "[1] Kodeks cywilny, art. 415\n" in user + + +def test_the_language_falls_back_to_polish_and_the_old_entry_point_still_builds_it(): + assert g.prompt_spec("de") == g.prompt_spec("pl") + system, user = sem.answer_prompt("Kiedy?", [KC415]) + assert "WYŁĄCZNIE" in system and user.endswith("Pytanie: Kiedy?") + assert "ONLY" in sem.answer_prompt("When?", [KC415], "en")[0] + + +def test_the_examples_themselves_pass_the_verifier(): + """A worked example the verifier would reject teaches the model the wrong thing.""" + for lang in g.LANGS: + ex = g.prompt_spec(lang)["examples"][0] + res = g.verify(ex["answer"], ex["passages"], lang=lang) + assert not res["refused"] and res["verification"]["passed"], res + + +# ── the parsers ── +def test_references_dates_and_act_numbers_are_read(): + assert g.refs_in("art. 52 i 53 § 1 ust. 2-4") == { + ("art", "52"), ("art", "53"), ("§", "1"), ("ust", "2"), ("ust", "3"), ("ust", "4")} + assert ("art", "442¹") in g.refs_in("art. 442¹ k.c.") + assert g.refs_in("art. 2³–5") == {("art", "2³"), ("art", "5")} # superscripts: no int() + assert g.dates_in("z dnia 10 maja 2018 r. i 01.02.2020") == {"2018-05-10", "2020-02-01"} + assert g.actnums_in("(UE) 2016/679, poz. 1465, II CSK 123/20") == { + "2016/679", "poz.1465", "II CSK 123/20"} + # a statute numbers its sections without saying "ust." + assert ("ust", "2") in g.passage_refs(KC4421["text"]) + + +def test_sentences_do_not_split_at_abbreviations(): + assert g._sentences("Zgodnie z art. 52 § 1 k.p. może [1]. Dz. U. z 2023 r. poz. 5 [1].") == [ + "Zgodnie z art. 52 § 1 k.p. może [1].", "Dz. U. z 2023 r. poz. 5 [1]."] + + +# ── the rules ── +def _rules(raw, passages, **kw): + res = g.verify(raw, passages, **kw) + return res, [f["rule"] for f in res["verification"]["flagged"]] + + +def test_a_grounded_sentence_passes(): + res, rules = _rules("Kto z winy swej wyrządził drugiemu szkodę, obowiązany jest do jej " + "naprawienia (art. 415) [1].", [KC415]) + assert rules == [] and not res["refused"] and res["cited"] == [1] + assert res["verification"]["passed"] and res["verification"]["support_checked"] + + +@pytest.mark.parametrize(("raw", "rule"), [ + ("Szkodę naprawia sprawca [1, 3].", "source_out_of_range"), + ("Szkodę naprawia ten, kto ją wyrządził.", "no_citation"), + ("Przedawnienie reguluje art. 999 [1].", "invented_reference"), + ("Przedawnienie reguluje art. 442¹ [1].", "miscited_reference"), + ("Kto wyrządził szkodę, naprawia ją według § 4 [1].", "invented_reference"), + ("Kto z winy wyrządził szkodę, naprawia ją od 1 stycznia 2020 r. [1].", "invented_date"), + ("Kto z winy wyrządził szkodę, naprawia ją (Dz. U. poz. 1465) [1].", "invented_act_number"), + ("Zgodnie z art. 415 roszczenie przedawnia się z upływem trzech lat od zdarzenia [1].", + "low_support"), +]) +def test_each_rule_drops_its_sentence_and_refuses_when_nothing_is_left(raw, rule): + res, rules = _rules(raw, [KC415, KC4421]) + assert rules == [rule] and res["refused"] and res["answer"] is None + assert res["verification"]["flagged"][0]["action"] == "dropped" + + +def test_a_mixed_answer_keeps_the_grounded_sentence(): + res, rules = _rules("Kto z winy swej wyrządził drugiemu szkodę, obowiązany jest do jej " + "naprawienia [1]. Termin wynosi dziesięć lat według art. 118 [1].", + [KC415]) + assert rules == ["invented_reference"] and not res["refused"] + assert res["answer"].endswith("naprawienia [1].") and res["dropped"] == 1 + assert not res["verification"]["passed"] and res["verification"]["kept"] == 1 + + +def test_the_whole_context_is_searched_before_calling_a_number_invented(): + """legal-memory's gotcha: an amending act's title quotes a whole EU act, date and all.""" + title = {"label": "Ustawa o zmianie niektórych ustaw", "text": ( + "Ustawa z dnia 21 lutego 2019 r. o zmianie niektórych ustaw w związku z zapewnieniem " + "stosowania rozporządzenia (UE) 2016/679 z dnia 27 kwietnia 2016 r.")} + res, rules = _rules("Stosowanie rozporządzenia (UE) 2016/679 z dnia 27 kwietnia 2016 r. " + "zapewnia ustawa o zmianie niektórych ustaw [1].", [title]) + assert rules == [] and not res["refused"] + # cited from the OTHER passage: the context has it, so it is miscited, not invented + res, rules = _rules("Zapewnia to rozporządzenie (UE) 2016/679 o szkodzie [1].", [KC415, title]) + assert rules == ["miscited_act_number"] + + +def test_the_model_refusal_and_the_switches(): + res = g.verify("BRAK_PODSTAW", [KC415]) + assert res["refused"] and res["verification"]["model_refused"] + assert res["verification"]["passed"] + # min_support 0 switches the lexical check off; an English answer is not measured + raw = "Zgodnie z art. 415 roszczenie przedawnia się z upływem trzech lat od zdarzenia [1]." + assert not g.verify(raw, [KC415], min_support=0)["refused"] + en = g.verify("Anyone who culpably causes damage must redress it (art. 415) [1].", [KC415], + lang="en") + assert not en["refused"] and en["verification"]["support_checked"] is False + + +class _Gen: + name = "fake" + + def __init__(self, reply): + self.reply = reply + + async def complete(self, system, user, **kw): + return self.reply + + +def test_answer_returns_the_verification_block_and_the_reason(): + out = asyncio.run(sem.answer(_Gen("Przedawnienie reguluje art. 999 [1]."), "Kiedy?", [KC415])) + assert out["refused"] and out["citations"] == [] + assert out["reason"].startswith("no sentence") + assert out["verification"]["flagged"][0]["rule"] == "invented_reference" + out = asyncio.run(sem.answer(_Gen("BRAK_PODSTAW"), "Kiedy?", [KC415])) + assert out["reason"] == "the model found no support in the passages" + out = asyncio.run(sem.answer(_Gen("x"), "Kiedy?", [])) + assert out["refused"] and out["verification"]["skipped"] == "no passages" diff --git a/backend/tests/test_infra_matrix.py b/backend/tests/test_infra_matrix.py index 9adc916..0ca060c 100644 --- a/backend/tests/test_infra_matrix.py +++ b/backend/tests/test_infra_matrix.py @@ -94,6 +94,47 @@ def test_rank_prior_is_graph_only_when_the_rank_is_complete(infra, api): assert body["rank_prior"] == ("graph" if infra.profile.graph_prior else "naive") +# ── cited answers (services/grounding.py) ─────────────────────────────────────────────────────────── +class _AnswerGen: + name = "fake:answer" + + def __init__(self, reply): + self.reply = reply + + async def complete(self, system, user, **kw): + return self.reply + + +@pytest.mark.infra("bare", "full") +def test_answers_are_verified_and_the_graph_widens_them_only_when_complete(infra, api, + monkeypatch): + """With answers on: no generator → a clean 409; a generator inventing an article → refused + with the rule that caught it; the graph adds passages exactly where `rank_prior` is graph.""" + from app.services import aiswitch, semantic + monkeypatch.setattr(semantic, "ai_flags", lambda *a, **k: { + "ai_query_rewrite": False, "ai_answers": True, "ai_external_allowed": False}) + aiswitch.clear() + models = semantic.get_models() + try: + semantic.set_models(semantic.Models(models.embedder, None, None)) + r = api.get("/api/v1/answer", params={"q": "umowa o pracę"}) + assert r.status_code == 409 and "INSIDER_GENERATOR" in r.text, r.text + semantic.set_models(semantic.Models(models.embedder, None, _AnswerGen( + "Umowę o pracę reguluje art. 9999 [1]."))) + r = api.get("/api/v1/answer", params={"q": "umowa o pracę", "lang": "en"}) + assert r.status_code == 200, r.text + body = r.json() + assert body["refused"] and body["lang"] == "en" + assert [f["rule"] for f in body["verification"]["flagged"]] == ["invented_reference"] + exp = body["graph_expansion"] + assert exp["used"] is infra.profile.graph_prior, exp + if not infra.profile.graph_prior: + assert exp["added"] == 0 and exp["skipped"] in ("no graph", "graph incomplete") + finally: + semantic.set_models(models) + aiswitch.clear() + + # ── vectors ───────────────────────────────────────────────────────────────────────────────────────── def test_the_vector_side_is_used_only_when_the_vectors_are_complete(infra, api, monkeypatch): searched = [] diff --git a/backend/tests/test_semantic.py b/backend/tests/test_semantic.py index b44bf16..57fb876 100644 --- a/backend/tests/test_semantic.py +++ b/backend/tests/test_semantic.py @@ -288,12 +288,16 @@ def test_answer_prompt_numbers_the_passages(): def test_citation_enforcement(): - r = sem.enforce_citations("Można bez wypowiedzenia [1]. Tak orzekł SN [2][1]. " - "Zawsze warto iść do sądu. Coś [7].", 2) + """The citation rules `grounding.verify` starts with (tests/test_grounding.py has the rest).""" + from app.services.grounding import verify + r = verify("Można bez wypowiedzenia [1]. Tak orzekł SN [2][1]. " + "Zawsze warto iść do sądu. Coś [7].", PASSAGES, min_support=0) assert r["answer"] == "Można bez wypowiedzenia [1]. Tak orzekł SN [2][1]." assert r["cited"] == [1, 2] and r["dropped"] == 2 and not r["refused"] - assert sem.enforce_citations("BRAK_PODSTAW", 2)["refused"] - assert sem.enforce_citations("Nic nie cytuję.", 2)["refused"] + assert [f["rule"] for f in r["verification"]["flagged"]] == ["no_citation", + "source_out_of_range"] + assert verify("BRAK_PODSTAW", PASSAGES)["refused"] + assert verify("Nic nie cytuję.", PASSAGES)["refused"] def test_answer_end_to_end_with_a_fake_generator():