File size: 12,275 Bytes
d80690d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
"""Make the edge of the indexed corpus visible in the answer.

The retrieved text routinely points at legal sources this assistant does not
index.  `§ 31 SGB V` grants the claim to medicines "soweit diese nicht … durch
Richtlinien nach § 92 Absatz 1 Satz 2 Nummer 6 ausgeschlossen sind" — that
exclusion lives in the Arzneimittel-Richtlinie.  A model that only sees the
statute will answer confidently and omit the exception.

Since the `amrl` corpus was added, that particular reference is covered and the
note disappears by itself (`covered_by`).  What did *not* move into the index are
the AM-RL's Anlagen — the substance and product lists — and they are tracked as
their own entry.  Splitting the two matters: a single entry would either vanish
with the directive text and imply the lists were checked, or keep firing on
answers that were in fact fully covered.

That is the same failure mode `corpus_router` guards against on the way in, one
step later: not the wrong corpus, but a *missing* one.  The cheap, honest fix is
to detect the dangling reference in the retrieved context and say so, rather than
to let the answer imply completeness it does not have.

Detection runs on the retrieved chunks, not on the question. A user asking "Ist
Ibuprofen erstattungsfähig?" names no source at all — but the § 31 chunk that
answers it carries the reference to the AM-RL verbatim, which makes the context
the far more reliable signal.
"""

from __future__ import annotations

import re
from dataclasses import dataclass
from typing import Any, Dict, Iterable, List, Optional, Sequence


@dataclass(frozen=True)
class ExternalSource:
    """A legal source the retrieved text may point at."""

    key: str
    label: str
    # What the user should understand is missing, in one clause.
    scope: str
    pattern: re.Pattern[str]
    # Corpus id that would cover this source once indexed.  None = no corpus of
    # this project will ever cover it (then the note is permanent, not a TODO).
    covered_by: Optional[str] = None


def _rx(pattern: str) -> re.Pattern[str]:
    return re.compile(pattern, re.I)


# Ordered by how often the reference actually decides a pharmacy question.
EXTERNAL_SOURCES: tuple[ExternalSource, ...] = (
    # The AM-RL is indexed as its directive text only.  Its Anlagen are substance
    # and product lists that the G-BA publishes as separate documents, and they
    # stay out on purpose: the decisive answer about a list is frequently the
    # negative one ("not listed, so it may be substituted"), and a vector search
    # cannot establish absence — it always returns the k nearest chunks.  So this
    # gap is not a TODO, it is a property of the retrieval method, and it is the
    # sharper of the two AM-RL entries.  It is listed first for that reason.
    #
    # Roman numerals are what make the detection specific: the Rahmenvertrag and
    # the Abrechnungsvereinbarung number their own Anlagen in arabic digits, so
    # "Anlage VII" in retrieved text always means the AM-RL.  Measured over the
    # indexed corpora: 57 hits in amrl, 6 in rv129 (§ 9 Abs. 1 points at the
    # "Substitutions-Ausschlussliste … (Arzneimittel-Richtlinie Anlage VII
    # Teil B)"), 0 in sgb5 and amabrv.
    ExternalSource(
        key="am_rl_anlagen",
        label="Anlagen der Arzneimittel-Richtlinie (Wirkstoff- und Produktlisten)",
        # Was hier steht, muss den *verbliebenen* Rest benennen. Sieben Anlagen
        # sind inzwischen als Lookup nachschlagbar (I, II, IIa, III, VII Teil A
        # und B, VIIa) und werden vom Aufrufer aus dem Hinweis genommen, sobald
        # ein Befund vorliegt; nennte der Text sie weiter als ungeprüft, meldete
        # er eine Lücke, die die Antwort zwei Absätze darüber geschlossen hat.
        # Anlage IIa stand hier, solange `amrl_lifestyle` den Weg über § 34
        # Absatz 2 SGB V nur benennen konnte; seit `amrl_tabakentwoehnung` löst
        # ein eigener Befund ihn ein.
        #
        # Die Aufzählung nennt nur die wirkstoff- und produktbezogenen Listen.
        # Das Muster unten trifft auch die Anlagen VIII bis XII (Analogpräparate,
        # Festbeträge, Nutzenbewertung) — die sind keine solchen Listen, und der
        # Hinweis benennt sie deshalb sammelnd am Ende, statt einen Katalog zu
        # führen, der bei jeder Novelle nachzuziehen wäre.
        scope="die übrigen wirkstoff- und produktbezogenen Listen — Therapiehinweise "
        "(Anlage IV), verordnungsfähige Medizinprodukte (Anlage V), Verbandmittel "
        "(Anlage Va) und der Off-Label-Use (Anlage VI) — sowie die übrigen Anlagen "
        "der Richtlinie",
        pattern=_rx(
            r"Anlage\s+(?:XII|XI|X|IX|VIII|VII|VI|V|IV|III|II|I)a?\b"
            r"|Substitutions-?\s?Ausschlussliste"
            r"|Substitutionsausschluss"
            r"|OTC-?\s?(?:Übersicht|Ausnahmeliste)"
            r"|§\s*129\s+Abs(?:atz|\.)?\s*1a\s+Satz\s*2"
        ),
    ),
    # The directive text itself: covered once the `amrl` corpus is loaded.  Kept
    # as a separate entry rather than deleted, so a single-corpus deployment
    # still discloses the gap.
    ExternalSource(
        key="am_rl",
        label="Arzneimittel-Richtlinie (AM-RL)",
        scope="Verordnungsfähigkeit, Verordnungsausschlüsse und die Regeln zur "
        "Austauschbarkeit",
        pattern=_rx(
            r"§\s*92\s+Abs(?:atz|\.)?\s*1\s+Satz\s*2\s+Nummer\s*6"
            r"|§\s*92\s+Abs\.\s*1\s+Satz\s*2\s+Nr\.\s*6"
            r"|Arzneimittel-?\s?Richtlinie"
            r"|Richtlinien?\s+nach\s+§\s*92"
        ),
        covered_by="amrl",
    ),
    ExternalSource(
        key="ampreisv",
        label="Arzneimittelpreisverordnung (AMPreisV)",
        scope="Apothekenzuschläge und Preisbildung",
        pattern=_rx(r"Arzneimittelpreisverordnung|AMPreisV|Arzneimittelpreisrecht"),
    ),
    # Die Verschreibungspflicht selbst steht in keinem der vier Korpora. Der
    # Rahmenvertrag setzt sie voraus und verweist auf die Formerfordernisse
    # („wenn die Angaben den §§ 2 Absatz 1 Nummern 4 bis 6 und 7 AMVV … nicht
    # vollständig entsprechen", § 6); § 48 AMG ordnet sie an. Ohne diese beiden
    # Einträge beantwortete der Prototyp eine Frage nach der Verschreibungs-
    # pflicht aus § 31 SGB V — einer Anspruchsnorm, die dazu nichts sagt — und
    # nichts im Text hätte die Lücke benannt.
    ExternalSource(
        key="amvv",
        label="Arzneimittelverschreibungsverordnung (AMVV)",
        scope="die Verschreibungspflicht einzelner Stoffe und die Formerfordernisse "
        "der Verschreibung",
        pattern=_rx(r"Arzneimittelverschreibungsverordnung|\bAMVV\b"),
    ),
    ExternalSource(
        key="amg",
        label="Arzneimittelgesetz (AMG)",
        scope="Zulassung, Verschreibungspflicht nach § 48 und Verkehrsfähigkeit",
        pattern=_rx(r"Arzneimittelgesetz(?:es)?\b|\bAMG\b"),
    ),
    ExternalSource(
        key="btmvv",
        label="Betäubungsmittel-Verschreibungsverordnung (BtMVV)",
        scope="Betäubungsmittelrezepte und deren Formerfordernisse",
        pattern=_rx(r"Bet[äa]ubungsmittel-?Verschreibungsverordnung|BtMVV"),
    ),
    ExternalSource(
        key="apog",
        label="Apothekengesetz (ApoG)",
        scope="Betriebserlaubnis, Zuweisungsverbot und Versandhandel",
        pattern=_rx(r"Apothekengesetz(?:es)?\b|\bApoG\b"),
    ),
    # Der Rahmenvertrag nennt sie ohne Paragraphenzeichen — „die mit dem
    # kleinsten Packungsgrößenkennzeichen gemäß der PackungsV in Vertrieb
    # befindliche Packung" (§ 17). Für den Verweisparser ist das kein Verweis,
    # für die Reichweite sehr wohl: welche Packung N1 ist, steht dort und
    # nirgends im Bestand.
    ExternalSource(
        key="packungsv",
        label="Packungsgrößenverordnung (PackungsV)",
        scope="die Packungsgrößenkennzeichen N1, N2 und N3 und ihre Bestimmung",
        pattern=_rx(r"Packungsgr[öo]ßenverordnung|\bPackungsV\b"),
    ),
    ExternalSource(
        key="apbetro",
        label="Apothekenbetriebsordnung (ApBetrO)",
        scope="Betriebspflichten der Apotheke",
        pattern=_rx(r"Apothekenbetriebsordnung|ApBetrO"),
    ),
    # Die Vereinbarung ist indiziert, ihre Technischen Anlagen sind es nicht —
    # und dort steht, welches Sonderkennzeichen für welchen Sachverhalt gilt.
    # Deshalb ein eigener Eintrag statt eines Zusatzes beim amabrv-Eintrag: der
    # verschwindet mit dem geladenen Korpus, die Anlagen bleiben draußen.
    # Dieselbe Trennung wie bei der AM-RL und ihren Anlagen.
    ExternalSource(
        key="amabrv_technische_anlagen",
        label="Technische Anlagen zur Arzneimittelabrechnungsvereinbarung",
        scope="die einzelnen Sonderkennzeichen, der Datensatzaufbau und die "
        "Feldbelegungen",
        pattern=_rx(r"Technische[nrs]?\s+Anlage\s*\d*"),
    ),
    ExternalSource(
        key="amabrv",
        label="Arzneimittelabrechnungsvereinbarung (§ 300 Abs. 3 SGB V)",
        scope="Abrechnungsverfahren, Sonderkennzeichen, Beanstandung und Fristen",
        pattern=_rx(
            r"§\s*300\s+Abs(?:atz|\.)?\s*3"
            r"|Abrechnungsvereinbarung"
            r"|Vereinbarung\s+nach\s+§\s*300"
        ),
        covered_by="amabrv",
    ),
    ExternalSource(
        key="rahmenvertrag",
        label="Rahmenvertrag nach § 129 Abs. 2 SGB V",
        scope="Abgaberegeln der Apotheke",
        pattern=_rx(r"Rahmenvertrag\s+nach\s+§\s*129|Rahmenvertrag(?:es)?\s+über\s+die\s+Arzneimittelversorgung"),
        covered_by="rv129",
    ),
)


def _hit_text(hit: Dict[str, Any]) -> str:
    metadata = hit.get("metadata") or {}
    parts = [
        hit.get("text"),
        hit.get("document"),
        metadata.get("text"),
    ]
    return " ".join(str(p) for p in parts if p)


def detect_external_references(
    hits: Sequence[Dict[str, Any]],
    *,
    available_corpora: Iterable[str] = (),
    max_results: int = 3,
) -> List[Dict[str, str]]:
    """External sources the retrieved context leans on but the index lacks.

    A source whose `covered_by` corpus is loaded is not reported: the assistant
    can answer from it, so there is no gap to disclose.
    """
    available = {str(c).lower() for c in available_corpora}
    blob = " ".join(_hit_text(hit) for hit in hits or [])
    if not blob.strip():
        return []

    found: List[Dict[str, str]] = []
    for source in EXTERNAL_SOURCES:
        if source.covered_by and source.covered_by.lower() in available:
            continue
        if source.pattern.search(blob):
            found.append({"key": source.key, "label": source.label, "scope": source.scope})
        if len(found) >= max_results:
            break
    return found


def boundary_note(references: Sequence[Dict[str, str]]) -> str:
    """One short paragraph naming what the answer could not consider."""
    if not references:
        return ""

    # Die Labels tragen keinen Artikel, damit sie auch in der Aufzählung unten
    # passen; der Satzbau vermeidet ihn deshalb durch den Doppelpunkt.
    if len(references) == 1:
        ref = references[0]
        return (
            "Hinweis zur Reichweite: Die herangezogenen Textstellen verweisen auf ein "
            f"Regelwerk außerhalb des durchsuchten Bestands — {ref['label']}. "
            f"Damit sind {ref['scope']} hier nicht geprüft."
        )

    labels = "; ".join(f"{r['label']} ({r['scope']})" for r in references)
    return (
        "Hinweis zur Reichweite: Die herangezogenen Textstellen verweisen auf Regelwerke "
        f"außerhalb des durchsuchten Bestands — {labels}. Diese sind hier nicht geprüft."
    )


def append_boundary_note(answer: str, references: Sequence[Dict[str, str]]) -> str:
    """Attach the note without disturbing the answer's own structure.

    Appended rather than woven in: the composer's schema (Kurzantwort /
    Maßgebliche Norm / Wortlaut / Einordnung) is validated elsewhere, and the
    note is a statement about the index, not about the law.
    """
    note = boundary_note(references)
    if not note:
        return answer
    text = (answer or "").rstrip()
    if not text:
        return note
    return f"{text}\n\n{note}"