ragops-observatory 0.10.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ragops/__init__.py +7 -0
- ragops/alerts.py +162 -0
- ragops/assurance.py +234 -0
- ragops/benchmark.py +206 -0
- ragops/benchmark_squad.py +234 -0
- ragops/cli.py +869 -0
- ragops/clickhouse.py +212 -0
- ragops/config.py +54 -0
- ragops/dashboard/Home.py +89 -0
- ragops/dashboard/__init__.py +0 -0
- ragops/dashboard/common.py +114 -0
- ragops/dashboard/pages/1_Root_Causes.py +32 -0
- ragops/dashboard/pages/2_Traces.py +82 -0
- ragops/dashboard/pages/3_Drift.py +64 -0
- ragops/dashboard/pages/4_Knowledge_Base.py +40 -0
- ragops/dashboard/pages/5_Golden_Sets.py +43 -0
- ragops/dashboard/pages/6_Judge_Calibration.py +28 -0
- ragops/dashboard/pages/7_SLOs_and_Alerts.py +49 -0
- ragops/dashboard/pages/8_Report.py +16 -0
- ragops/dashboard/pages/9_Settings.py +61 -0
- ragops/db.py +104 -0
- ragops/demo/corpus.py +158 -0
- ragops/demo/pipeline.py +125 -0
- ragops/demo/seed.py +199 -0
- ragops/diagnosis.py +390 -0
- ragops/doctor.py +436 -0
- ragops/drift.py +348 -0
- ragops/embeddings.py +103 -0
- ragops/eval/__init__.py +4 -0
- ragops/eval/calibration.py +60 -0
- ragops/eval/judges.py +496 -0
- ragops/eval/sampler.py +62 -0
- ragops/eval/types.py +51 -0
- ragops/gate.py +184 -0
- ragops/guard.py +72 -0
- ragops/insights.py +474 -0
- ragops/judge_check.py +73 -0
- ragops/kb_health.py +108 -0
- ragops/migrate.py +83 -0
- ragops/migrations/__init__.py +0 -0
- ragops/migrations/env.py +40 -0
- ragops/migrations/script.py.mako +22 -0
- ragops/migrations/versions/0001_v04_baseline.py +301 -0
- ragops/migrations/versions/0002_v05_runs_vectors.py +120 -0
- ragops/migrations/versions/0003_v06_orgs_sso.py +97 -0
- ragops/models.py +400 -0
- ragops/pipelines.py +234 -0
- ragops/queue_arq.py +159 -0
- ragops/redaction.py +120 -0
- ragops/reliability.py +167 -0
- ragops/report_pdf.py +142 -0
- ragops/reports.py +123 -0
- ragops/run_service.py +169 -0
- ragops/runs.py +236 -0
- ragops/schemas.py +201 -0
- ragops/sdk/__init__.py +3 -0
- ragops/sdk/adapters.py +77 -0
- ragops/sdk/client.py +350 -0
- ragops/security.py +33 -0
- ragops/server/__init__.py +0 -0
- ragops/server/app.py +1258 -0
- ragops/server/importers.py +126 -0
- ragops/server/otel.py +195 -0
- ragops/server/ui/assets/ibm-plex-sans-latin-400-normal-CDDApCn2.woff2 +0 -0
- ragops/server/ui/assets/ibm-plex-sans-latin-400-normal-CYLoc0-x.woff +0 -0
- ragops/server/ui/assets/ibm-plex-sans-latin-500-normal-6ng42L7E.woff2 +0 -0
- ragops/server/ui/assets/ibm-plex-sans-latin-500-normal-BgVn5rGT.woff +0 -0
- ragops/server/ui/assets/ibm-plex-sans-latin-600-normal-Cu4Hd6ag.woff +0 -0
- ragops/server/ui/assets/ibm-plex-sans-latin-600-normal-CuJfVYMP.woff2 +0 -0
- ragops/server/ui/assets/index-DUrUfMF3.css +1 -0
- ragops/server/ui/assets/index-DoZERkmi.js +150 -0
- ragops/server/ui/index.html +14 -0
- ragops/services.py +1138 -0
- ragops/services_chunking.py +21 -0
- ragops/slo.py +52 -0
- ragops/sso.py +234 -0
- ragops/testgen.py +237 -0
- ragops/testing/__init__.py +0 -0
- ragops/testing/stub_llm.py +127 -0
- ragops/textutil.py +115 -0
- ragops/vectors.py +125 -0
- ragops/worker.py +144 -0
- ragops_observatory-0.10.0.dist-info/METADATA +387 -0
- ragops_observatory-0.10.0.dist-info/RECORD +87 -0
- ragops_observatory-0.10.0.dist-info/WHEEL +4 -0
- ragops_observatory-0.10.0.dist-info/entry_points.txt +2 -0
- ragops_observatory-0.10.0.dist-info/licenses/LICENSE +21 -0
ragops/__init__.py
ADDED
ragops/alerts.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""Alert delivery: Slack, Microsoft Teams, generic webhook, PagerDuty Events v2 and SMTP email.
|
|
2
|
+
|
|
3
|
+
Every channel can be verified end to end with ``ragops alerts test`` or
|
|
4
|
+
``POST /v1/projects/{project}/alert-channels/{id}/test`` before you rely on it.
|
|
5
|
+
|
|
6
|
+
Environment:
|
|
7
|
+
RAGOPS_PAGERDUTY_URL Events v2 endpoint (default https://events.pagerduty.com/v2/enqueue; EU accounts use
|
|
8
|
+
https://events.eu.pagerduty.com/v2/enqueue)
|
|
9
|
+
RAGOPS_SMTP_HOST/PORT SMTP relay (port default 587)
|
|
10
|
+
RAGOPS_SMTP_USER/PASSWORD login (optional)
|
|
11
|
+
RAGOPS_SMTP_SECURITY starttls | ssl | none (default: starttls when a user is set, otherwise none)
|
|
12
|
+
RAGOPS_SMTP_FROM sender address (default ragops@localhost)
|
|
13
|
+
RAGOPS_PUBLIC_URL used to put a "open in RAGOps" link in alerts
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import hashlib
|
|
19
|
+
import logging
|
|
20
|
+
import os
|
|
21
|
+
import smtplib
|
|
22
|
+
import ssl
|
|
23
|
+
from dataclasses import dataclass
|
|
24
|
+
from email.message import EmailMessage
|
|
25
|
+
|
|
26
|
+
import httpx
|
|
27
|
+
|
|
28
|
+
log = logging.getLogger("ragops.alerts")
|
|
29
|
+
|
|
30
|
+
KINDS = ("slack", "teams", "webhook", "pagerduty", "email")
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
@dataclass
|
|
34
|
+
class DeliveryResult:
|
|
35
|
+
ok: bool
|
|
36
|
+
kind: str
|
|
37
|
+
detail: str = ""
|
|
38
|
+
|
|
39
|
+
def __bool__(self) -> bool: # keeps `if deliver(...)` working
|
|
40
|
+
return self.ok
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def format_root_causes(rc: dict[str, int]) -> str:
|
|
44
|
+
total = sum(rc.values())
|
|
45
|
+
if not total:
|
|
46
|
+
return "no diagnosed failures in window"
|
|
47
|
+
parts = [f"{k.replace('_', ' ')} {v / total:.0%}" for k, v in sorted(rc.items(), key=lambda kv: -kv[1])[:4]]
|
|
48
|
+
return "Root causes: " + ", ".join(parts)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _link(payload: dict | None) -> str | None:
|
|
52
|
+
base = os.environ.get("RAGOPS_PUBLIC_URL")
|
|
53
|
+
project = (payload or {}).get("project")
|
|
54
|
+
if base and project:
|
|
55
|
+
return f"{base.rstrip('/')}/ui/#/p/{project}"
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def slack_payload(title: str, body: str, severity: str, payload: dict | None = None) -> dict:
|
|
60
|
+
emoji = {"critical": ":rotating_light:", "warning": ":warning:"}.get(severity, ":information_source:")
|
|
61
|
+
blocks = [
|
|
62
|
+
{"type": "header", "text": {"type": "plain_text", "text": f"{title}"[:150]}},
|
|
63
|
+
{"type": "section", "text": {"type": "mrkdwn", "text": f"{emoji} *{severity.upper()}*\n{body}"[:2900]}},
|
|
64
|
+
]
|
|
65
|
+
if (link := _link(payload)):
|
|
66
|
+
blocks.append({"type": "actions", "elements": [
|
|
67
|
+
{"type": "button", "text": {"type": "plain_text", "text": "Open in RAGOps"}, "url": link}]})
|
|
68
|
+
# `text` is the notification / fallback string; blocks are the rich message.
|
|
69
|
+
return {"text": f"{title}: {body}"[:3000], "blocks": blocks}
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def teams_payload(title: str, body: str, severity: str, payload: dict | None = None) -> dict:
|
|
73
|
+
card = {"type": "AdaptiveCard", "version": "1.4", "$schema": "http://adaptivecards.io/schemas/adaptive-card.json",
|
|
74
|
+
"body": [{"type": "TextBlock", "size": "Large", "weight": "Bolder", "text": title, "wrap": True,
|
|
75
|
+
"color": "Attention" if severity == "critical" else "Warning"},
|
|
76
|
+
{"type": "TextBlock", "text": body, "wrap": True}]}
|
|
77
|
+
if (link := _link(payload)):
|
|
78
|
+
card["actions"] = [{"type": "Action.OpenUrl", "title": "Open in RAGOps", "url": link}]
|
|
79
|
+
return {"type": "message", "attachments": [{"contentType": "application/vnd.microsoft.card.adaptive", "content": card}]}
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def pagerduty_payload(routing_key: str, title: str, body: str, severity: str, payload: dict | None = None) -> dict:
|
|
83
|
+
p = payload or {}
|
|
84
|
+
# dedup_key groups repeated firings of the same alert into one PagerDuty incident.
|
|
85
|
+
dedup = hashlib.sha1(f"{p.get('project', '')}|{title}".encode()).hexdigest()[:32]
|
|
86
|
+
event = {"routing_key": routing_key, "event_action": "trigger", "dedup_key": dedup,
|
|
87
|
+
"payload": {"summary": title[:1024], "severity": severity if severity in ("critical", "error", "warning", "info") else "warning",
|
|
88
|
+
"source": f"ragops-observatory/{p.get('project', 'unknown')}", "component": "rag-pipeline",
|
|
89
|
+
"group": p.get("project", "ragops"), "class": "rag-quality",
|
|
90
|
+
"custom_details": {"body": body, **p}},
|
|
91
|
+
"client": "RAGOps Observatory"}
|
|
92
|
+
if (link := _link(payload)):
|
|
93
|
+
event["client_url"] = link
|
|
94
|
+
event["links"] = [{"href": link, "text": "Open in RAGOps"}]
|
|
95
|
+
return event
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def email_message(to: str, title: str, body: str, severity: str, payload: dict | None = None) -> EmailMessage:
|
|
99
|
+
msg = EmailMessage()
|
|
100
|
+
msg["Subject"] = f"[RAGOps {severity}] {title}"
|
|
101
|
+
msg["To"] = to
|
|
102
|
+
msg["From"] = os.environ.get("RAGOPS_SMTP_FROM", "ragops@localhost")
|
|
103
|
+
link = _link(payload)
|
|
104
|
+
msg.set_content(body + (f"\n\nOpen in RAGOps: {link}" if link else "") + "\n\n-- RAGOps Observatory")
|
|
105
|
+
return msg
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _send_email(msg: EmailMessage) -> None:
|
|
109
|
+
host = os.environ.get("RAGOPS_SMTP_HOST")
|
|
110
|
+
if not host:
|
|
111
|
+
raise RuntimeError("RAGOPS_SMTP_HOST not set")
|
|
112
|
+
user = os.environ.get("RAGOPS_SMTP_USER")
|
|
113
|
+
security = os.environ.get("RAGOPS_SMTP_SECURITY", "starttls" if user else "none").lower()
|
|
114
|
+
port = int(os.environ.get("RAGOPS_SMTP_PORT", "465" if security == "ssl" else "587"))
|
|
115
|
+
ctx = ssl.create_default_context()
|
|
116
|
+
smtp_cls = smtplib.SMTP_SSL if security == "ssl" else smtplib.SMTP
|
|
117
|
+
kwargs = {"context": ctx} if security == "ssl" else {}
|
|
118
|
+
with smtp_cls(host, port, timeout=15, **kwargs) as s:
|
|
119
|
+
if security == "starttls":
|
|
120
|
+
s.starttls(context=ctx)
|
|
121
|
+
if user:
|
|
122
|
+
s.login(user, os.environ.get("RAGOPS_SMTP_PASSWORD", ""))
|
|
123
|
+
s.send_message(msg)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def send(kind: str, target: str, title: str, body: str, severity: str = "warning",
|
|
127
|
+
payload: dict | None = None) -> DeliveryResult:
|
|
128
|
+
"""Deliver one alert and report exactly what happened."""
|
|
129
|
+
try:
|
|
130
|
+
if kind == "slack":
|
|
131
|
+
r = httpx.post(target, json=slack_payload(title, body, severity, payload), timeout=10)
|
|
132
|
+
elif kind == "teams":
|
|
133
|
+
r = httpx.post(target, json=teams_payload(title, body, severity, payload), timeout=10)
|
|
134
|
+
elif kind == "webhook":
|
|
135
|
+
r = httpx.post(target, json={"title": title, "body": body, "severity": severity, **(payload or {})}, timeout=10)
|
|
136
|
+
elif kind == "pagerduty":
|
|
137
|
+
url = os.environ.get("RAGOPS_PAGERDUTY_URL", "https://events.pagerduty.com/v2/enqueue")
|
|
138
|
+
r = httpx.post(url, json=pagerduty_payload(target, title, body, severity, payload), timeout=10)
|
|
139
|
+
elif kind == "email":
|
|
140
|
+
_send_email(email_message(target, title, body, severity, payload))
|
|
141
|
+
return DeliveryResult(True, kind, f"accepted by {os.environ.get('RAGOPS_SMTP_HOST')}")
|
|
142
|
+
else:
|
|
143
|
+
raise ValueError(f"unknown channel kind {kind!r} (use one of {', '.join(KINDS)})")
|
|
144
|
+
if r.status_code >= 300:
|
|
145
|
+
return DeliveryResult(False, kind, f"HTTP {r.status_code}: {r.text[:300]}")
|
|
146
|
+
return DeliveryResult(True, kind, f"HTTP {r.status_code}")
|
|
147
|
+
except Exception as e: # network errors, SMTP errors, bad config
|
|
148
|
+
log.warning("alert delivery to %s failed: %s", kind, e)
|
|
149
|
+
return DeliveryResult(False, kind, f"{type(e).__name__}: {e}")
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def deliver(kind: str, target: str, title: str, body: str, severity: str = "warning", payload: dict | None = None) -> bool:
|
|
153
|
+
res = send(kind, target, title, body, severity, payload)
|
|
154
|
+
if not res.ok:
|
|
155
|
+
log.warning("alert delivery to %s failed: %s", kind, res.detail)
|
|
156
|
+
return res.ok
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def test_alert(project: str) -> tuple[str, str, dict]:
|
|
160
|
+
return (f"RAGOps test alert for {project}",
|
|
161
|
+
"This is a test from RAGOps Observatory. If you can read this, the channel works.",
|
|
162
|
+
{"project": project, "test": True})
|
ragops/assurance.py
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
1
|
+
"""Assurance report: turn a test run into a verdict and evidence a business owner, client or auditor can act on.
|
|
2
|
+
|
|
3
|
+
Input: the rows of a test run (``ragops.runs.run_cases``) plus what was tested. Output: a dict that renders to a
|
|
4
|
+
self-contained HTML page and a JSON evidence file. The report states
|
|
5
|
+
|
|
6
|
+
- a verdict, **Ready / Ready with conditions / Not ready**, from explicit criteria (each shown with its number);
|
|
7
|
+
- what fails, in plain language, with the fix and example questions;
|
|
8
|
+
- which documents to write (questions nothing covers) and which answers came from outdated documents;
|
|
9
|
+
- how far to trust the judge (LLM or word matching, scores settled by rules, fallbacks);
|
|
10
|
+
- how the evidence relates to RBI FREE-AI, the EU AI Act and ISO/IEC 42001 (supporting evidence, not certification);
|
|
11
|
+
- a SHA-256 fingerprint of the inputs and results, so a changed report can be detected.
|
|
12
|
+
|
|
13
|
+
The verdict is an assessment of the tested questions only; the limitations section says so.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import hashlib
|
|
19
|
+
import html
|
|
20
|
+
import json
|
|
21
|
+
import uuid
|
|
22
|
+
from datetime import datetime, timezone
|
|
23
|
+
|
|
24
|
+
from ragops.textutil import is_abstention
|
|
25
|
+
|
|
26
|
+
PLAIN = {
|
|
27
|
+
"security_leak": ("The assistant followed an injected instruction or exposed contacts or keys.",
|
|
28
|
+
"Never put secrets in documents or prompts; tell the model to ignore instructions inside "
|
|
29
|
+
"questions and documents; add the grounding guard."),
|
|
30
|
+
"knowledge_gap": ("No document covers the question.", "Write the missing document, or keep the assistant declining."),
|
|
31
|
+
"stale_knowledge": ("The answer came from an outdated document.", "Update or remove the old version, then re-index."),
|
|
32
|
+
"chunking_defect": ("The answer is split across chunks.", "Use larger chunks or more overlap."),
|
|
33
|
+
"incomplete_context": ("The right document was found, but not the passage with the answer.",
|
|
34
|
+
"Retrieve more chunks (top_k) or use larger chunks."),
|
|
35
|
+
"retrieval_miss": ("The right document exists but search did not find it.",
|
|
36
|
+
"Improve search: better embeddings, hybrid keyword search, query rewriting."),
|
|
37
|
+
"ranking_failure": ("The right passage was found but ranked too low to be used.", "Add a reranker or raise top_k."),
|
|
38
|
+
"prompt_overflow": ("The right passage was dropped when the prompt was built.", "Raise the context budget."),
|
|
39
|
+
"generation_failure": ("The assistant had the right passage but answered badly.",
|
|
40
|
+
"Tighten the prompt (answer only from context), or use a stronger model."),
|
|
41
|
+
"conflicting_context": ("Retrieved passages contradict each other.", "Remove or reconcile the conflicting documents."),
|
|
42
|
+
"pipeline_error": ("The assistant crashed or returned nothing.", "Check the endpoint, timeouts and token limits."),
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
EVIDENCE_MAP = [
|
|
46
|
+
{"framework": "RBI FREE-AI (India, financial sector, Aug 2025)",
|
|
47
|
+
"requirement": "Model risk management: validation before deployment and ongoing monitoring",
|
|
48
|
+
"evidence": "Test results, failure stages and verdict in this report; SLOs and drift alerts in production"},
|
|
49
|
+
{"framework": "RBI FREE-AI",
|
|
50
|
+
"requirement": "AI incident reporting",
|
|
51
|
+
"evidence": "Failed cases with root cause and timestamps; alert history from the RAGOps server"},
|
|
52
|
+
{"framework": "EU AI Act, Article 15",
|
|
53
|
+
"requirement": "Appropriate accuracy, robustness and consistency, with declared accuracy metrics",
|
|
54
|
+
"evidence": "Measured accuracy, grounding and refusal metrics with the test method and sample size"},
|
|
55
|
+
{"framework": "EU AI Act, Article 72",
|
|
56
|
+
"requirement": "Post-market monitoring by providers",
|
|
57
|
+
"evidence": "Production traces, SLOs and re-certification reports over time"},
|
|
58
|
+
{"framework": "ISO/IEC 42001, clause 9",
|
|
59
|
+
"requirement": "Performance evaluation: monitoring, measurement, analysis and evaluation",
|
|
60
|
+
"evidence": "Repeatable test set, metrics, judge reliability and this report's fingerprint"},
|
|
61
|
+
{"framework": "DPDP Act 2023 (India)",
|
|
62
|
+
"requirement": "Reasonable security safeguards for personal data processed by the assistant",
|
|
63
|
+
"evidence": "Not covered by a quality test; use PII redaction and the audit log, and assess separately"},
|
|
64
|
+
]
|
|
65
|
+
|
|
66
|
+
RULE_SETTLED = ("word for word", "matches the reference", "declines", "nothing to verify")
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _pct(x):
|
|
70
|
+
return None if x is None else round(100 * x, 1)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def build(rows: list[dict], summary: dict, meta: dict, thresholds: dict | None = None) -> dict:
|
|
74
|
+
"""meta: pipeline, dataset, judge, judge_is_llm, config, ragops_version, generated_by (optional)."""
|
|
75
|
+
th = {"pass_ready": 0.95, "pass_min": 0.80, "faith_ready": 0.90, "faith_min": 0.80, "refuse_min": 0.80,
|
|
76
|
+
"hit_ready": 0.90, "min_cases": 20, **(thresholds or {})}
|
|
77
|
+
n = len(rows)
|
|
78
|
+
unans = [r for r in rows if r.get("expected_answer") and is_abstention(r.get("expected_answer"))
|
|
79
|
+
and r.get("kind") != "security"]
|
|
80
|
+
probes = [r for r in rows if r.get("kind") == "security"]
|
|
81
|
+
declined = [r for r in unans if is_abstention(r.get("answer"))]
|
|
82
|
+
refuse_rate = len(declined) / len(unans) if unans else None
|
|
83
|
+
errors = sum(1 for r in rows if r.get("error"))
|
|
84
|
+
err_rate = errors / n if n else 0.0
|
|
85
|
+
m = summary.get("metrics") or {}
|
|
86
|
+
faith = m.get("faithfulness")
|
|
87
|
+
pass_rate = summary.get("pass_rate")
|
|
88
|
+
reasons = [str(v) for r in rows for v in (r.get("reasons") or {}).values() if v]
|
|
89
|
+
rule_share = (sum(1 for v in reasons if any(k in v for k in RULE_SETTLED)) / len(reasons)) if reasons else None
|
|
90
|
+
fallbacks = sum(1 for v in reasons if "heuristic fallback" in v)
|
|
91
|
+
|
|
92
|
+
crit = []
|
|
93
|
+
|
|
94
|
+
def add(name, value, shown, ok, blocking_fail, explain):
|
|
95
|
+
level = "pass" if ok else ("blocking" if blocking_fail else "condition")
|
|
96
|
+
crit.append({"criterion": name, "value": value, "shown": shown, "result": level, "explain": explain})
|
|
97
|
+
|
|
98
|
+
if pass_rate is not None:
|
|
99
|
+
add("Answers correct and grounded", pass_rate, f"{_pct(pass_rate)}% of {n} questions pass",
|
|
100
|
+
pass_rate >= th["pass_ready"], pass_rate < th["pass_min"],
|
|
101
|
+
f"Ready at {int(th['pass_ready'] * 100)}%; below {int(th['pass_min'] * 100)}% is not ready.")
|
|
102
|
+
if faith is not None:
|
|
103
|
+
add("No made-up content", faith, f"mean faithfulness {faith:.2f}", faith >= th["faith_ready"],
|
|
104
|
+
faith < th["faith_min"], "Share of answer statements supported by the retrieved passages.")
|
|
105
|
+
if refuse_rate is not None:
|
|
106
|
+
add("Declines what the documents do not cover", refuse_rate,
|
|
107
|
+
f"{len(declined)} of {len(unans)} unanswerable questions declined", refuse_rate >= 1.0,
|
|
108
|
+
refuse_rate < th["refuse_min"], "An assistant that invents answers to uncovered questions misleads users.")
|
|
109
|
+
if probes:
|
|
110
|
+
from ragops.testgen import leaked
|
|
111
|
+
|
|
112
|
+
leaks = [r for r in probes if leaked(r.get("answer"))]
|
|
113
|
+
safe = len(probes) - len(leaks)
|
|
114
|
+
add("Resists prompt injection and data leaks", safe / len(probes),
|
|
115
|
+
f"{safe} of {len(probes)} attack probes handled safely", not leaks, bool(leaks),
|
|
116
|
+
"Probes try to override instructions or extract contacts and keys; any leak is blocking.")
|
|
117
|
+
add("No crashes or empty answers", 1 - err_rate, f"{errors} pipeline errors", errors == 0, err_rate > 0.05,
|
|
118
|
+
"Errors are blocking above 5% of questions.")
|
|
119
|
+
if summary.get("hit_rate") is not None:
|
|
120
|
+
h = summary["hit_rate"]
|
|
121
|
+
add("Finds the right document", h, f"{_pct(h)}% expected-document hit rate", h >= th["hit_ready"], False,
|
|
122
|
+
"Retrieval quality; low values usually explain the failures below.")
|
|
123
|
+
add("Enough questions to judge", n, f"{n} questions", n >= th["min_cases"], False,
|
|
124
|
+
f"Fewer than {th['min_cases']} questions gives a weak estimate.")
|
|
125
|
+
add("Trustworthy judge", 1.0 if meta.get("judge_is_llm") and not fallbacks else 0.0,
|
|
126
|
+
("LLM judge" if meta.get("judge_is_llm") else "word matching only") + f", {fallbacks} fallbacks",
|
|
127
|
+
bool(meta.get("judge_is_llm")) and fallbacks == 0, False,
|
|
128
|
+
"Word matching cannot judge meaning; use an LLM judge and check it with `ragops judge check`.")
|
|
129
|
+
|
|
130
|
+
verdict = ("Not ready" if any(c["result"] == "blocking" for c in crit)
|
|
131
|
+
else "Ready with conditions" if any(c["result"] == "condition" for c in crit) else "Ready")
|
|
132
|
+
|
|
133
|
+
fails = [r for r in rows if r.get("failed")]
|
|
134
|
+
causes = []
|
|
135
|
+
for label, count in sorted(((lab, sum(1 for r in fails if r.get("label") == lab)) for lab in
|
|
136
|
+
{r.get("label") for r in fails}), key=lambda x: -x[1]):
|
|
137
|
+
what, fix = PLAIN.get(label, ("Unclassified failure.", "Inspect the examples."))
|
|
138
|
+
ex = [{"question": r["query"], "answered": (r.get("answer") or r.get("error") or "")[:300],
|
|
139
|
+
"expected": (r.get("expected_answer") or "")[:300]} for r in fails if r.get("label") == label][:3]
|
|
140
|
+
causes.append({"stage": label, "cases": count, "what": what, "fix": fix, "examples": ex})
|
|
141
|
+
write_docs = [r["query"] for r in fails if r.get("label") == "knowledge_gap"]
|
|
142
|
+
stale = sorted({c.get("doc_id") for r in fails if r.get("label") == "stale_knowledge"
|
|
143
|
+
for c in (r.get("contexts") or []) if isinstance(c, dict) and c.get("doc_id")})
|
|
144
|
+
|
|
145
|
+
body = {
|
|
146
|
+
"report_id": uuid.uuid4().hex[:12],
|
|
147
|
+
"created_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
|
|
148
|
+
"subject": {k: meta.get(k) for k in ("pipeline", "dataset", "config", "generated_by")},
|
|
149
|
+
"method": {"judge": meta.get("judge"), "judge_is_llm": bool(meta.get("judge_is_llm")),
|
|
150
|
+
"ragops_version": meta.get("ragops_version"), "questions": n,
|
|
151
|
+
"unanswerable_questions": len(unans),
|
|
152
|
+
"rule_settled_share": None if rule_share is None else round(rule_share, 3),
|
|
153
|
+
"judge_fallbacks": fallbacks},
|
|
154
|
+
"verdict": verdict,
|
|
155
|
+
"criteria": crit,
|
|
156
|
+
"summary": summary,
|
|
157
|
+
"root_causes": causes,
|
|
158
|
+
"documents_to_write": write_docs,
|
|
159
|
+
"outdated_documents": stale,
|
|
160
|
+
"evidence_mapping": EVIDENCE_MAP,
|
|
161
|
+
"limitations": [
|
|
162
|
+
"The verdict covers the tested questions only; real users will ask others.",
|
|
163
|
+
"LLM judges make mistakes; the method section shows how many scores were settled by rules and how "
|
|
164
|
+
"many fell back to word matching. Check the judge against human labels before relying on it.",
|
|
165
|
+
"This report is supporting evidence. It is not a legal opinion or a certification of compliance.",
|
|
166
|
+
],
|
|
167
|
+
}
|
|
168
|
+
canon = json.dumps({"rows": rows, "body": {k: v for k, v in body.items() if k not in ("report_id", "created_at")}},
|
|
169
|
+
sort_keys=True, default=str)
|
|
170
|
+
body["fingerprint_sha256"] = hashlib.sha256(canon.encode("utf-8")).hexdigest()
|
|
171
|
+
body["rows"] = rows
|
|
172
|
+
return body
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
def verify(report: dict) -> bool:
|
|
176
|
+
"""True when the report's content still matches its fingerprint."""
|
|
177
|
+
body = {k: v for k, v in report.items() if k not in ("report_id", "created_at", "fingerprint_sha256", "rows")}
|
|
178
|
+
canon = json.dumps({"rows": report.get("rows", []), "body": body}, sort_keys=True, default=str)
|
|
179
|
+
return hashlib.sha256(canon.encode("utf-8")).hexdigest() == report.get("fingerprint_sha256")
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
# ------------------------------------------------------------------------------------------------ rendering
|
|
183
|
+
_COLOR = {"Ready": "#1f7a3a", "Ready with conditions": "#9a6700", "Not ready": "#b42318"}
|
|
184
|
+
_MARK = {"pass": "Pass", "condition": "Condition", "blocking": "Blocking"}
|
|
185
|
+
|
|
186
|
+
|
|
187
|
+
def to_html(rep: dict, title: str | None = None, brand: str | None = None) -> str:
|
|
188
|
+
e = html.escape
|
|
189
|
+
t = title or f"RAG assurance report: {rep['subject'].get('pipeline') or 'assistant'}"
|
|
190
|
+
crit = "".join(f"<tr><td>{e(c['criterion'])}</td><td>{e(c['shown'])}</td><td class='r-{c['result']}'>"
|
|
191
|
+
f"{_MARK[c['result']]}</td><td>{e(c['explain'])}</td></tr>" for c in rep["criteria"])
|
|
192
|
+
causes = ""
|
|
193
|
+
for c in rep["root_causes"]:
|
|
194
|
+
ex = "".join(f"<li><b>{e(x['question'])}</b><br>Answered: {e(x['answered']) or '(nothing)'}<br>"
|
|
195
|
+
f"Expected: {e(x['expected'])}</li>" for x in c["examples"])
|
|
196
|
+
causes += (f"<h3>{e(c['stage'].replace('_', ' ').capitalize())}: {c['cases']} questions</h3>"
|
|
197
|
+
f"<p>{e(c['what'])} <b>Fix:</b> {e(c['fix'])}</p><ul>{ex}</ul>")
|
|
198
|
+
causes = causes or "<p>No failures among the tested questions.</p>"
|
|
199
|
+
docs = "".join(f"<li>{e(q)}</li>" for q in rep["documents_to_write"]) or "<li>None</li>"
|
|
200
|
+
stale = "".join(f"<li>{e(d)}</li>" for d in rep["outdated_documents"]) or "<li>None</li>"
|
|
201
|
+
ev = "".join(f"<tr><td>{e(x['framework'])}</td><td>{e(x['requirement'])}</td><td>{e(x['evidence'])}</td></tr>"
|
|
202
|
+
for x in rep["evidence_mapping"])
|
|
203
|
+
m = rep["method"]
|
|
204
|
+
lim = "".join(f"<li>{e(x)}</li>" for x in rep["limitations"])
|
|
205
|
+
s = rep["summary"]
|
|
206
|
+
rs = "n/a" if m["rule_settled_share"] is None else f"{round(100 * m['rule_settled_share'])}%"
|
|
207
|
+
return f"""<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
208
|
+
<title>{e(t)}</title><style>
|
|
209
|
+
body{{font:15px/1.55 system-ui,-apple-system,"Segoe UI",sans-serif;color:#1d2433;max-width:920px;margin:32px auto;padding:0 20px}}
|
|
210
|
+
h1{{font-size:24px;margin:0 0 4px}}h2{{font-size:18px;margin:32px 0 8px;border-bottom:1px solid #dde2ea;padding-bottom:4px}}
|
|
211
|
+
h3{{font-size:15px;margin:18px 0 4px}}.muted{{color:#5b6475}}table{{border-collapse:collapse;width:100%;margin:8px 0}}
|
|
212
|
+
td,th{{border:1px solid #dde2ea;padding:6px 8px;text-align:left;vertical-align:top}}th{{background:#f4f6f9}}
|
|
213
|
+
.verdict{{display:inline-block;padding:6px 14px;border-radius:6px;color:#fff;font-weight:600;background:{_COLOR[rep['verdict']]}}}
|
|
214
|
+
.r-pass{{color:#1f7a3a;font-weight:600}}.r-condition{{color:#9a6700;font-weight:600}}.r-blocking{{color:#b42318;font-weight:600}}
|
|
215
|
+
code{{font-size:12px;word-break:break-all}}@media print{{body{{margin:0}}}}
|
|
216
|
+
</style></head><body>
|
|
217
|
+
<p class="muted">{e(brand or 'RAGOps assurance')} · report {e(rep['report_id'])} · {e(rep['created_at'])}</p>
|
|
218
|
+
<h1>{e(t)}</h1>
|
|
219
|
+
<p><span class="verdict">{e(rep['verdict'])}</span></p>
|
|
220
|
+
<p>{s.get('cases')} questions tested · pass rate {_pct(s.get('pass_rate'))}% · judge: {e(str(m['judge']))}</p>
|
|
221
|
+
<h2>Criteria</h2><table><tr><th>Criterion</th><th>Measured</th><th>Result</th><th>Why it matters</th></tr>{crit}</table>
|
|
222
|
+
<h2>What fails and how to fix it</h2>{causes}
|
|
223
|
+
<h2>Documents to write</h2><p class="muted">Questions no document answers.</p><ul>{docs}</ul>
|
|
224
|
+
<h2>Outdated documents used in answers</h2><ul>{stale}</ul>
|
|
225
|
+
<h2>How far to trust these scores</h2>
|
|
226
|
+
<p>Judge: {e(str(m['judge']))}. Scores settled by deterministic rules (verbatim support, exact reference match, declines): {rs}.
|
|
227
|
+
Judge fallbacks to word matching: {m['judge_fallbacks']}. RAGOps version {e(str(m['ragops_version']))}.</p>
|
|
228
|
+
<h2>Supporting evidence for regulations and standards</h2>
|
|
229
|
+
<p class="muted">How this report can support requirements. It is not a certification of compliance.</p>
|
|
230
|
+
<table><tr><th>Framework</th><th>Requirement</th><th>Evidence here</th></tr>{ev}</table>
|
|
231
|
+
<h2>Limitations</h2><ul>{lim}</ul>
|
|
232
|
+
<h2>Integrity</h2><p>SHA-256 fingerprint of the inputs and results: <code>{e(rep['fingerprint_sha256'])}</code>.
|
|
233
|
+
Check it with <code>ragops assure --verify assurance.json</code>.</p>
|
|
234
|
+
</body></html>"""
|
ragops/benchmark.py
ADDED
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
"""Root-cause attribution benchmark.
|
|
2
|
+
|
|
3
|
+
We take the demo knowledge base, deliberately inject each of the seven failure types into otherwise healthy RAG
|
|
4
|
+
calls, and measure how often the classifier names the stage we broke. A healthy control set measures false alarms.
|
|
5
|
+
|
|
6
|
+
Every injected case carries the signal a production system would have (a failed golden case or a thumbs-down),
|
|
7
|
+
so the benchmark measures *attribution*, separate from failure *detection*. Stale knowledge is the exception: it
|
|
8
|
+
is flagged without any failure signal, because the observatory can see that the context came from an old version.
|
|
9
|
+
|
|
10
|
+
Run it with ``ragops benchmark`` (writes benchmark/RESULTS.md).
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import random
|
|
16
|
+
import re
|
|
17
|
+
from collections import Counter, defaultdict
|
|
18
|
+
from dataclasses import dataclass
|
|
19
|
+
|
|
20
|
+
import numpy as np
|
|
21
|
+
|
|
22
|
+
from ragops.demo.corpus import DOCS, GAP_QUESTIONS
|
|
23
|
+
from ragops.demo.pipeline import ABSTAIN, Index, chunk
|
|
24
|
+
from ragops.diagnosis import LABELS, CorpusChunk, CorpusView, diagnose
|
|
25
|
+
from ragops.eval.judges import HeuristicJudge, evaluate
|
|
26
|
+
from ragops.eval.types import ContextChunk, RagSample
|
|
27
|
+
from ragops.textutil import content_tokens, coverage, sentences
|
|
28
|
+
|
|
29
|
+
CHUNK_WORDS = 45
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@dataclass
|
|
33
|
+
class Case:
|
|
34
|
+
injected: str # one of LABELS or "ok"
|
|
35
|
+
sample: RagSample
|
|
36
|
+
feedback: float | None
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _cc(c: dict, rank: int, version: int = 2) -> ContextChunk:
|
|
40
|
+
return ContextChunk(text=c["text"], doc_id=c["doc_id"], chunk_id=c["chunk_id"], doc_version=version,
|
|
41
|
+
score=c.get("score"), rank=rank)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _answer_from(query: str, chunks: list[dict]) -> str:
|
|
45
|
+
q = content_tokens(query)
|
|
46
|
+
best, bs, bc = None, 0.0, None
|
|
47
|
+
for c in chunks:
|
|
48
|
+
for s in sentences(c["text"]):
|
|
49
|
+
sc = coverage(q, content_tokens(s))
|
|
50
|
+
if sc > bs:
|
|
51
|
+
best, bs, bc = s, sc, c
|
|
52
|
+
if best is None or bs < 0.34:
|
|
53
|
+
return ABSTAIN
|
|
54
|
+
return f"{best} [{bc['doc_id']}]"
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _corrupt(answer: str, rng: random.Random) -> str:
|
|
58
|
+
nums = re.findall(r"\d+", answer)
|
|
59
|
+
if nums and rng.random() < 0.6:
|
|
60
|
+
return answer.replace(nums[0], str(int(nums[0]) * 3 + 11), 1)
|
|
61
|
+
return answer.split(" [")[0] + " It also includes unlimited free storage for every guest and a lifetime discount."
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def build_cases(seed: int = 0) -> tuple[list[Case], CorpusView]:
|
|
65
|
+
rng = random.Random(seed)
|
|
66
|
+
all_chunks = [c for d in DOCS for c in chunk(d["doc_id"], d["text"], CHUNK_WORDS, 2)]
|
|
67
|
+
idx = Index(all_chunks)
|
|
68
|
+
corpus = CorpusView([CorpusChunk(c["chunk_id"], c["doc_id"], 2, int(c["chunk_id"].split("#")[1]), c["text"])
|
|
69
|
+
for c in all_chunks], None, {d["doc_id"]: 2 for d in DOCS}, set())
|
|
70
|
+
by_doc = defaultdict(list)
|
|
71
|
+
for c in all_chunks:
|
|
72
|
+
by_doc[c["doc_id"]].append(c)
|
|
73
|
+
cases: list[Case] = []
|
|
74
|
+
|
|
75
|
+
def gold_for(q: str, doc: str) -> dict:
|
|
76
|
+
qt = content_tokens(q)
|
|
77
|
+
return max(by_doc[doc], key=lambda c: coverage(qt, content_tokens(c["text"])))
|
|
78
|
+
|
|
79
|
+
questions = [(q, d["doc_id"]) for d in DOCS for q in d["questions"]]
|
|
80
|
+
for q, doc in questions:
|
|
81
|
+
gold = gold_for(q, doc)
|
|
82
|
+
cands = idx.search(q, 8)
|
|
83
|
+
if gold["chunk_id"] not in {c["chunk_id"] for c in cands}:
|
|
84
|
+
cands = [{**gold, "score": 0.5}] + cands[:7]
|
|
85
|
+
others = [c for c in cands if c["doc_id"] != doc]
|
|
86
|
+
noise = [c for c in all_chunks if c["doc_id"] != doc]
|
|
87
|
+
|
|
88
|
+
# healthy control
|
|
89
|
+
ctx = [gold] + others[:2]
|
|
90
|
+
cases.append(Case("ok", RagSample(q, _answer_from(q, ctx), [_cc(c, i + 1) for i, c in enumerate(ctx)],
|
|
91
|
+
[_cc(c, i + 1) for i, c in enumerate(cands)]), None))
|
|
92
|
+
# generation failure: right context, corrupted answer
|
|
93
|
+
cases.append(Case("generation_failure", RagSample(
|
|
94
|
+
q, _corrupt(_answer_from(q, ctx), rng), [_cc(c, i + 1) for i, c in enumerate(ctx)],
|
|
95
|
+
[_cc(c, i + 1) for i, c in enumerate(cands)]), -1.0))
|
|
96
|
+
# ranking failure: gold retrieved, dropped before the prompt
|
|
97
|
+
ctx_r = others[:3]
|
|
98
|
+
cases.append(Case("ranking_failure", RagSample(
|
|
99
|
+
q, _answer_from(q, ctx_r), [_cc(c, i + 1) for i, c in enumerate(ctx_r)],
|
|
100
|
+
[_cc(c, i + 1) for i, c in enumerate([*others[:3], gold, *others[3:6]])]), -1.0))
|
|
101
|
+
# retrieval miss: the gold document is absent from the candidates
|
|
102
|
+
miss = [c for c in idx.search(q, 20) if c["doc_id"] != doc][:6]
|
|
103
|
+
cases.append(Case("retrieval_miss", RagSample(
|
|
104
|
+
q, _answer_from(q, miss[:3]), [_cc(c, i + 1) for i, c in enumerate(miss[:3])],
|
|
105
|
+
[_cc(c, i + 1) for i, c in enumerate(miss)]), -1.0))
|
|
106
|
+
# context overload: gold buried at position 6 of 10 among unrelated chunks
|
|
107
|
+
filler = rng.sample(noise, 9)
|
|
108
|
+
ctx_o = filler[:5] + [gold] + filler[5:]
|
|
109
|
+
cases.append(Case("context_overload", RagSample(
|
|
110
|
+
q, _answer_from(q, filler[:2]), [_cc(c, i + 1) for i, c in enumerate(ctx_o)],
|
|
111
|
+
[_cc(c, i + 1) for i, c in enumerate(ctx_o)]), -1.0))
|
|
112
|
+
# stale knowledge: context served from document version 1 while the registry is at version 2
|
|
113
|
+
ctx_s = [gold] + others[:2]
|
|
114
|
+
cases.append(Case("stale_knowledge", RagSample(
|
|
115
|
+
q, _answer_from(q, ctx_s), [_cc(c, i + 1, version=1 if c is gold else 2) for i, c in enumerate(ctx_s)],
|
|
116
|
+
[_cc(c, i + 1) for i, c in enumerate(cands)]), None))
|
|
117
|
+
|
|
118
|
+
# knowledge gap: questions the corpus does not cover, answered confidently anyway
|
|
119
|
+
for q in GAP_QUESTIONS:
|
|
120
|
+
cands = idx.search(q, 6)
|
|
121
|
+
cases.append(Case("knowledge_gap", RagSample(
|
|
122
|
+
q, "Yes, this is fully supported on all plans. [pricing-plans]", [_cc(c, i + 1) for i, c in enumerate(cands[:3])],
|
|
123
|
+
[_cc(c, i + 1) for i, c in enumerate(cands)]), -1.0))
|
|
124
|
+
|
|
125
|
+
# chunking defect: questions built from the tail of chunk i and the head of chunk i+1 of the same document
|
|
126
|
+
for doc, chs in by_doc.items():
|
|
127
|
+
for a, b in zip(chs, chs[1:]):
|
|
128
|
+
ta = [w for w in re.findall(r"[A-Za-z][A-Za-z\-]+", a["text"]) if len(w) > 4][-4:]
|
|
129
|
+
tb = [w for w in re.findall(r"[A-Za-z][A-Za-z\-]+", b["text"]) if len(w) > 4][:4]
|
|
130
|
+
if len(ta) < 3 or len(tb) < 3:
|
|
131
|
+
continue
|
|
132
|
+
q = f"How does {' '.join(ta).lower()} relate to {' '.join(tb).lower()}?"
|
|
133
|
+
cands = idx.search(q, 6)
|
|
134
|
+
ctx_c = [a] + [c for c in cands if c["chunk_id"] not in (a["chunk_id"], b["chunk_id"])][:2]
|
|
135
|
+
cases.append(Case("chunking_defect", RagSample(
|
|
136
|
+
q, _answer_from(q, [a]), [_cc(c, i + 1) for i, c in enumerate(ctx_c)],
|
|
137
|
+
[_cc(c, i + 1) for i, c in enumerate(cands)]), -1.0))
|
|
138
|
+
return cases, corpus
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def run_benchmark(seed: int = 0) -> dict:
|
|
142
|
+
cases, corpus = build_cases(seed)
|
|
143
|
+
judge = HeuristicJudge()
|
|
144
|
+
labels = LABELS + ["ok"]
|
|
145
|
+
confusion = {t: Counter() for t in labels}
|
|
146
|
+
for c in cases:
|
|
147
|
+
c.sample.corpus_max_similarity = float(corpus.relevance(c.sample.query).max())
|
|
148
|
+
scores = {k: v.score for k, v in evaluate(c.sample, judge).items()}
|
|
149
|
+
dx = diagnose(c.sample, scores, corpus, c.feedback)
|
|
150
|
+
confusion[c.injected][dx.label if dx.is_failure else "ok"] += 1 # an alarm = flagged as a failure
|
|
151
|
+
per_label = {}
|
|
152
|
+
for lab in labels:
|
|
153
|
+
n = sum(confusion[lab].values())
|
|
154
|
+
tp = confusion[lab][lab]
|
|
155
|
+
predicted = sum(confusion[t][lab] for t in labels)
|
|
156
|
+
per_label[lab] = {"n": n, "recall": round(tp / n, 3) if n else None,
|
|
157
|
+
"precision": round(tp / predicted, 3) if predicted else None}
|
|
158
|
+
injected = [c for c in cases if c.injected != "ok"]
|
|
159
|
+
correct = sum(confusion[c][c] for c in LABELS)
|
|
160
|
+
ok_n = sum(confusion["ok"].values())
|
|
161
|
+
return {
|
|
162
|
+
"cases": len(cases), "injected_failures": len(injected),
|
|
163
|
+
"attribution_accuracy": round(correct / len(injected), 3),
|
|
164
|
+
"macro_recall": round(float(np.mean([per_label[lab]["recall"] for lab in LABELS])), 3),
|
|
165
|
+
"false_alarm_rate": round(1 - confusion["ok"]["ok"] / ok_n, 3) if ok_n else None,
|
|
166
|
+
"per_label": per_label,
|
|
167
|
+
"confusion": {t: dict(confusion[t]) for t in labels},
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def to_markdown(r: dict) -> str:
|
|
172
|
+
labels = LABELS + ["ok"]
|
|
173
|
+
lines = [
|
|
174
|
+
"# Root-cause attribution benchmark", "",
|
|
175
|
+
"Generated by `ragops benchmark`. Each case is a healthy RAG call with one failure injected on purpose; "
|
|
176
|
+
"the classifier must name the pipeline stage that was broken. Judge: deterministic heuristic judge "
|
|
177
|
+
"(no LLM calls), so the numbers are exactly reproducible.", "",
|
|
178
|
+
f"- **Cases:** {r['cases']} ({r['injected_failures']} injected failures + healthy controls)",
|
|
179
|
+
f"- **Attribution accuracy:** {r['attribution_accuracy']:.1%}",
|
|
180
|
+
f"- **Macro recall across the 7 stages:** {r['macro_recall']:.1%}",
|
|
181
|
+
f"- **False-alarm rate on healthy calls:** {r['false_alarm_rate']:.1%}", "",
|
|
182
|
+
"## Per stage", "", "| Injected failure | Cases | Recall | Precision |", "|---|---|---|---|",
|
|
183
|
+
]
|
|
184
|
+
for lab in labels:
|
|
185
|
+
pl = r["per_label"][lab]
|
|
186
|
+
rec = "–" if pl["recall"] is None else f"{pl['recall']:.0%}"
|
|
187
|
+
pre = "–" if pl["precision"] is None else f"{pl['precision']:.0%}"
|
|
188
|
+
lines.append(f"| {lab} | {pl['n']} | {rec} | {pre} |")
|
|
189
|
+
lines += ["", "## Confusion matrix (rows = injected, columns = predicted)", "",
|
|
190
|
+
"| injected \\ predicted | " + " | ".join(lab.replace("_", " ") for lab in labels) + " |",
|
|
191
|
+
"|---" * (len(labels) + 1) + "|"]
|
|
192
|
+
for t in labels:
|
|
193
|
+
lines.append(f"| **{t}** | " + " | ".join(str(r["confusion"][t].get(p, 0) or "·") for p in labels) + " |")
|
|
194
|
+
lines += ["", "## How failures are injected", "",
|
|
195
|
+
"| Stage | Injection |", "|---|---|",
|
|
196
|
+
"| knowledge_gap | Questions on topics absent from the corpus, answered confidently |",
|
|
197
|
+
"| stale_knowledge | Context chunk served from document v1 while the registry holds v2 |",
|
|
198
|
+
"| chunking_defect | Question built from the end of chunk *i* and the start of chunk *i+1*; only chunk *i* in context |",
|
|
199
|
+
"| retrieval_miss | Every chunk of the relevant document removed from the candidates |",
|
|
200
|
+
"| ranking_failure | Relevant chunk in the retriever candidates but not in the prompt |",
|
|
201
|
+
"| context_overload | Relevant chunk buried at position 6 of 10 unrelated chunks |",
|
|
202
|
+
"| generation_failure | Relevant chunk at rank 1, answer corrupted (wrong figure or invented claim) |",
|
|
203
|
+
"", "Limitations: the corpus is small (18 documents) and synthetic, and failures are injected one at a "
|
|
204
|
+
"time. Real systems mix failure types; treat these numbers as a regression baseline for the classifier, "
|
|
205
|
+
"not as a claim about every production system.", ""]
|
|
206
|
+
return "\n".join(lines)
|