Fix L3 relevance, evidence scoring honesty, citation finalisation, safety + baseline prompts
Browse filesKey fixes addressing reviewer feedback:
1. OpenAlex relevance — was returning irrelevant papers
- Strip stopwords / interrogatives ("what", "explain", "in", "detail")
before sending to OpenAlex (was burying technical terms under boost words)
- Only pass clean topic terms to OpenAlex; reserve domain boost for Gemini search
- Filter results by relative relevance_score (drop tail < 30% of top)
2. L3 evidence scoring — was inflating scores for off-topic papers
- Replace permissive prompt with a STRICT relevance gate
- Step 1: count how many papers genuinely match the topic
- If <half match: cap eScore at 0.30 regardless
- Honest scoring rubric (0.0-0.2 for off-topic, 0.85-1.0 for direct support)
3. Citation finalisation — phantom [4][6] surviving when only 4 sources
- LLMs sometimes emit markdown-escaped brackets \\[1\\]\\[2\\]
which the renderer un-escapes to [1][2]
- The citation regex did not match escaped brackets so they slipped past
normalisation, leaving phantom citations in the rendered output
- New _unescape_brackets() preprocessor strips \\[ and \\] before
normalisation, so phantom citations are correctly dropped
- Source list now leads with "You have EXACTLY N sources, valid range
is [1] through [N] ONLY" so the polish LLM stops inventing numbers
- L5_POLISH citation rules tightened: cite sequentially in first-appearance
order, no markdown-escaped brackets, strict 1..N range
- Tests added: test_escaped_brackets_are_unescaped_and_normalized,
test_citations_appear_in_sequential_order, audit validator escaped
bracket check + matching unit test
4. Safety section — CRCS was scoring 0% on safety vs baseline 100%
- L5_POLISH now demands a clearly-labelled "**Safety and caveats.**"
paragraph; vague phrases like "consider risks" rejected
- Domain-specific safety hints made explicit and concrete (named
hazards: lasers / cryogenics for science, REMS / red-flag symptoms
for medical, MiFID for finance, WCAG / IDEA for education)
5. Baseline prompt simplified — remove the 4 numbered requirements that
were biasing baseline to mention safety / sources / completeness
- Now: "Answer the user's question naturally. Write in flowing prose."
All 41 tests pass.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
- pipeline_v10.py +82 -15
- prompts.py +73 -33
- tests/run_local_pipeline_audit.py +4 -0
- tests/test_citations.py +66 -0
- tests/test_local_audit.py +9 -0
|
@@ -208,18 +208,46 @@ def layer2_kg_gate(client, candidates, query, domain, add):
|
|
| 208 |
|
| 209 |
# ── OpenAlex API: Free academic paper search (no API key needed) ─────────────
|
| 210 |
|
| 211 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 212 |
"""Search OpenAlex for academic papers. Returns list of paper dicts.
|
| 213 |
-
|
|
|
|
|
|
|
| 214 |
"""
|
| 215 |
import urllib.request
|
| 216 |
import urllib.parse
|
|
|
|
|
|
|
| 217 |
url = (
|
| 218 |
"https://api.openalex.org/works?"
|
| 219 |
-
f"search={urllib.parse.quote(
|
| 220 |
-
f"&per_page={n}"
|
| 221 |
"&select=title,authorships,publication_year,doi,cited_by_count,"
|
| 222 |
-
"primary_location,abstract_inverted_index"
|
| 223 |
"&sort=relevance_score:desc"
|
| 224 |
"&mailto=crcs-demo@qresearch.in"
|
| 225 |
)
|
|
@@ -227,8 +255,22 @@ def _search_openalex(query: str, n: int = 5) -> list:
|
|
| 227 |
with urllib.request.urlopen(req, timeout=10) as resp:
|
| 228 |
data = json.loads(resp.read().decode())
|
| 229 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 230 |
papers = []
|
| 231 |
-
for r in
|
|
|
|
|
|
|
|
|
|
|
|
|
| 232 |
# Reconstruct abstract from inverted index
|
| 233 |
abstract = ""
|
| 234 |
aii = r.get("abstract_inverted_index") or {}
|
|
@@ -263,7 +305,10 @@ def _search_openalex(query: str, n: int = 5) -> list:
|
|
| 263 |
"snippet": abstract,
|
| 264 |
"uri": pdf_url if pdf_url.startswith("http") else f"https://doi.org/{doi}" if doi else "",
|
| 265 |
"api_source": "OpenAlex",
|
|
|
|
| 266 |
})
|
|
|
|
|
|
|
| 267 |
return papers
|
| 268 |
|
| 269 |
|
|
@@ -276,18 +321,23 @@ def layer3_evidence(client, survivors, query, domain, add):
|
|
| 276 |
Gemini grounded search is secondary (broader web, used for evidence text).
|
| 277 |
"""
|
| 278 |
add("HEAD", "── L3: Evidence Retrieval (Real Search) ──")
|
|
|
|
|
|
|
| 279 |
boost = DOMAIN_SEARCH_BOOST.get(domain, "")
|
| 280 |
-
|
| 281 |
|
| 282 |
# ── Step 1: OpenAlex — real academic papers with full metadata ──
|
| 283 |
sources = []
|
| 284 |
try:
|
| 285 |
t0 = time.time()
|
| 286 |
-
sources = _search_openalex(
|
| 287 |
-
|
|
|
|
|
|
|
| 288 |
for i, s in enumerate(sources[:5]):
|
| 289 |
cites = f" · cited {s['citation_count']}×" if s.get("citation_count") else ""
|
| 290 |
-
|
|
|
|
| 291 |
except Exception as e:
|
| 292 |
add("WARN", f"L3: OpenAlex failed ({e}) — falling back to Gemini search")
|
| 293 |
|
|
@@ -297,7 +347,7 @@ def layer3_evidence(client, survivors, query, domain, add):
|
|
| 297 |
t0 = time.time()
|
| 298 |
result, gemini_srcs = call_grounded(
|
| 299 |
client, MODEL_EVIDENCE, L3_EVIDENCE_SEARCH(domain)["system"],
|
| 300 |
-
f"Summarize published evidence for: {
|
| 301 |
tokens=4096,
|
| 302 |
)
|
| 303 |
evidence_text = result if isinstance(result, str) else json.dumps(result)
|
|
@@ -560,11 +610,27 @@ def layer5_score(verified, domain, boundary_prox=False):
|
|
| 560 |
# ── L5 Post-Score: Polish m* into final answer with citations ────────────────
|
| 561 |
|
| 562 |
_CITATION_BLOCK_RE = re.compile(r"\[((?:\s*\d+\s*(?:[-,;]\s*\d+\s*)*))\]")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 563 |
|
| 564 |
|
| 565 |
def _format_source_list_for_citations(sources: list, limit: int = 8) -> str:
|
| 566 |
-
|
| 567 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 568 |
title = s.get("title", "Untitled")
|
| 569 |
uri = s.get("uri", "")
|
| 570 |
year = s.get("year") or _extract_year_from_source(s) or "n.d."
|
|
@@ -791,9 +857,9 @@ def _citation_repair_needed(text: str, source_count: int) -> bool:
|
|
| 791 |
|
| 792 |
def _repair_and_finalize_citations(client, text: str, domain: str, sources: list, add) -> str:
|
| 793 |
if not text or not sources:
|
| 794 |
-
return text.strip()
|
| 795 |
|
| 796 |
-
answer = text.strip()
|
| 797 |
if _citation_repair_needed(answer, len(sources)):
|
| 798 |
system = L5_CITATION_REPAIR(domain)["system"]
|
| 799 |
user = (
|
|
@@ -851,6 +917,7 @@ def polish_mstar(client, best_candidate, query, domain, evidence_text, sources,
|
|
| 851 |
|
| 852 |
def _inject_real_references(text: str, sources: list) -> str:
|
| 853 |
"""Backward-compatible alias for the newer citation finalizer."""
|
|
|
|
| 854 |
body, ordered_old_nums = _normalize_citation_blocks(_split_references_section(text)[0], len(sources))
|
| 855 |
body = _backfill_missing_paragraph_citations(body)
|
| 856 |
references = _build_real_references(ordered_old_nums, sources)
|
|
|
|
| 208 |
|
| 209 |
# ── OpenAlex API: Free academic paper search (no API key needed) ─────────────
|
| 210 |
|
| 211 |
+
_STOPWORDS = {
|
| 212 |
+
"what", "is", "are", "the", "a", "an", "of", "in", "on", "at", "to", "for",
|
| 213 |
+
"with", "by", "from", "and", "or", "but", "so", "as", "if", "than", "that",
|
| 214 |
+
"this", "these", "those", "be", "been", "being", "have", "has", "had", "do",
|
| 215 |
+
"does", "did", "will", "would", "could", "should", "may", "might", "can",
|
| 216 |
+
"explain", "describe", "tell", "me", "about", "how", "why", "when", "where",
|
| 217 |
+
"which", "who", "whom", "detail", "details", "please", "give", "provide",
|
| 218 |
+
"discuss", "list", "name", "compare", "difference", "between",
|
| 219 |
+
}
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def _extract_query_terms(query: str) -> str:
|
| 223 |
+
"""Extract the meaningful technical terms from a natural-language query.
|
| 224 |
+
|
| 225 |
+
Removes stopwords and common interrogatives so OpenAlex's keyword search
|
| 226 |
+
matches the topic rather than the phrasing.
|
| 227 |
+
"""
|
| 228 |
+
import re as _re
|
| 229 |
+
# Strip punctuation, lowercase, split
|
| 230 |
+
cleaned = _re.sub(r"[^\w\s-]", " ", query.lower())
|
| 231 |
+
tokens = [t for t in cleaned.split() if t and t not in _STOPWORDS and len(t) > 1]
|
| 232 |
+
return " ".join(tokens) if tokens else query
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def _search_openalex(query: str, n: int = 5, full_query: str = "") -> list:
|
| 236 |
"""Search OpenAlex for academic papers. Returns list of paper dicts.
|
| 237 |
+
|
| 238 |
+
Uses OpenAlex's `search` endpoint with the cleaned (stopwords removed) query.
|
| 239 |
+
Filters results by relevance_score to drop clearly off-topic matches.
|
| 240 |
"""
|
| 241 |
import urllib.request
|
| 242 |
import urllib.parse
|
| 243 |
+
|
| 244 |
+
cleaned_query = _extract_query_terms(query) or query
|
| 245 |
url = (
|
| 246 |
"https://api.openalex.org/works?"
|
| 247 |
+
f"search={urllib.parse.quote(cleaned_query)}"
|
| 248 |
+
f"&per_page={n * 2}" # over-fetch so we can filter by relevance
|
| 249 |
"&select=title,authorships,publication_year,doi,cited_by_count,"
|
| 250 |
+
"primary_location,abstract_inverted_index,relevance_score"
|
| 251 |
"&sort=relevance_score:desc"
|
| 252 |
"&mailto=crcs-demo@qresearch.in"
|
| 253 |
)
|
|
|
|
| 255 |
with urllib.request.urlopen(req, timeout=10) as resp:
|
| 256 |
data = json.loads(resp.read().decode())
|
| 257 |
|
| 258 |
+
raw_results = data.get("results", []) or []
|
| 259 |
+
if not raw_results:
|
| 260 |
+
return []
|
| 261 |
+
|
| 262 |
+
# OpenAlex relevance scores vary in absolute value across queries; use a
|
| 263 |
+
# relative cutoff: keep results within 30% of the top score to filter the
|
| 264 |
+
# long tail of off-topic matches.
|
| 265 |
+
top_relevance = max((r.get("relevance_score") or 0.0) for r in raw_results)
|
| 266 |
+
relevance_floor = max(top_relevance * 0.30, 1.0)
|
| 267 |
+
|
| 268 |
papers = []
|
| 269 |
+
for r in raw_results:
|
| 270 |
+
rel = r.get("relevance_score") or 0.0
|
| 271 |
+
if rel < relevance_floor:
|
| 272 |
+
continue
|
| 273 |
+
|
| 274 |
# Reconstruct abstract from inverted index
|
| 275 |
abstract = ""
|
| 276 |
aii = r.get("abstract_inverted_index") or {}
|
|
|
|
| 305 |
"snippet": abstract,
|
| 306 |
"uri": pdf_url if pdf_url.startswith("http") else f"https://doi.org/{doi}" if doi else "",
|
| 307 |
"api_source": "OpenAlex",
|
| 308 |
+
"relevance_score": rel,
|
| 309 |
})
|
| 310 |
+
if len(papers) >= n:
|
| 311 |
+
break
|
| 312 |
return papers
|
| 313 |
|
| 314 |
|
|
|
|
| 321 |
Gemini grounded search is secondary (broader web, used for evidence text).
|
| 322 |
"""
|
| 323 |
add("HEAD", "── L3: Evidence Retrieval (Real Search) ──")
|
| 324 |
+
# Use the raw query for OpenAlex (cleaned internally to drop stopwords).
|
| 325 |
+
# Domain boost terms are reserved for Gemini's broader search summary.
|
| 326 |
boost = DOMAIN_SEARCH_BOOST.get(domain, "")
|
| 327 |
+
gemini_query = f"{query} {boost}".strip()
|
| 328 |
|
| 329 |
# ── Step 1: OpenAlex — real academic papers with full metadata ──
|
| 330 |
sources = []
|
| 331 |
try:
|
| 332 |
t0 = time.time()
|
| 333 |
+
sources = _search_openalex(query, n=6)
|
| 334 |
+
cleaned_terms = _extract_query_terms(query)
|
| 335 |
+
add("API", f" → OpenAlex ({time.time()-t0:.1f}s) {len(sources)} papers · "
|
| 336 |
+
f"terms: \"{cleaned_terms[:60]}\"")
|
| 337 |
for i, s in enumerate(sources[:5]):
|
| 338 |
cites = f" · cited {s['citation_count']}×" if s.get("citation_count") else ""
|
| 339 |
+
rel = f" · rel {s.get('relevance_score', 0):.1f}"
|
| 340 |
+
add("INFO", f" [{i+1}] {s['title'][:70]} ({s.get('year','?')}){cites}{rel}")
|
| 341 |
except Exception as e:
|
| 342 |
add("WARN", f"L3: OpenAlex failed ({e}) — falling back to Gemini search")
|
| 343 |
|
|
|
|
| 347 |
t0 = time.time()
|
| 348 |
result, gemini_srcs = call_grounded(
|
| 349 |
client, MODEL_EVIDENCE, L3_EVIDENCE_SEARCH(domain)["system"],
|
| 350 |
+
f"Summarize published evidence for: {gemini_query}",
|
| 351 |
tokens=4096,
|
| 352 |
)
|
| 353 |
evidence_text = result if isinstance(result, str) else json.dumps(result)
|
|
|
|
| 610 |
# ── L5 Post-Score: Polish m* into final answer with citations ────────────────
|
| 611 |
|
| 612 |
_CITATION_BLOCK_RE = re.compile(r"\[((?:\s*\d+\s*(?:[-,;]\s*\d+\s*)*))\]")
|
| 613 |
+
# Some models emit markdown-escaped brackets (\[1\]) which the renderer
|
| 614 |
+
# unescapes to [1]. Strip the escapes early so the citation regex matches.
|
| 615 |
+
_ESCAPED_BRACKET_RE = re.compile(r"\\(\[|\])")
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
def _unescape_brackets(text: str) -> str:
|
| 619 |
+
"""Remove markdown bracket escapes so citation parsing sees clean [N]."""
|
| 620 |
+
return _ESCAPED_BRACKET_RE.sub(r"\1", text)
|
| 621 |
|
| 622 |
|
| 623 |
def _format_source_list_for_citations(sources: list, limit: int = 8) -> str:
|
| 624 |
+
available = sources[:limit]
|
| 625 |
+
n = len(available)
|
| 626 |
+
if n == 0:
|
| 627 |
+
return "(no sources available — do not use any inline citations)"
|
| 628 |
+
lines = [
|
| 629 |
+
f"You have EXACTLY {n} sources. Valid citation numbers are [1] through [{n}] ONLY.",
|
| 630 |
+
f"Do NOT use [{n+1}], [{n+2}], or any number above [{n}].",
|
| 631 |
+
"",
|
| 632 |
+
]
|
| 633 |
+
for i, s in enumerate(available, 1):
|
| 634 |
title = s.get("title", "Untitled")
|
| 635 |
uri = s.get("uri", "")
|
| 636 |
year = s.get("year") or _extract_year_from_source(s) or "n.d."
|
|
|
|
| 857 |
|
| 858 |
def _repair_and_finalize_citations(client, text: str, domain: str, sources: list, add) -> str:
|
| 859 |
if not text or not sources:
|
| 860 |
+
return text.strip() if text else ""
|
| 861 |
|
| 862 |
+
answer = _unescape_brackets(text.strip())
|
| 863 |
if _citation_repair_needed(answer, len(sources)):
|
| 864 |
system = L5_CITATION_REPAIR(domain)["system"]
|
| 865 |
user = (
|
|
|
|
| 917 |
|
| 918 |
def _inject_real_references(text: str, sources: list) -> str:
|
| 919 |
"""Backward-compatible alias for the newer citation finalizer."""
|
| 920 |
+
text = _unescape_brackets(text or "")
|
| 921 |
body, ordered_old_nums = _normalize_citation_blocks(_split_references_section(text)[0], len(sources))
|
| 922 |
body = _backfill_missing_paragraph_citations(body)
|
| 923 |
references = _build_real_references(ordered_old_nums, sources)
|
|
@@ -64,16 +64,33 @@ def L3_EVIDENCE_SCORE(domain):
|
|
| 64 |
return {
|
| 65 |
"layer": "L3", "name": "Evidence Scoring (per candidate)",
|
| 66 |
"system": (
|
| 67 |
-
f"
|
| 68 |
-
"
|
| 69 |
-
"
|
| 70 |
-
|
| 71 |
-
"
|
| 72 |
-
"or
|
| 73 |
-
"
|
| 74 |
-
"
|
| 75 |
-
|
| 76 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 77 |
),
|
| 78 |
}
|
| 79 |
|
|
@@ -149,11 +166,30 @@ def L4_SPROXY_CONSENSUS(domain):
|
|
| 149 |
# ── Layer 5: Polish m* ──────────────────────────────────────────────────────
|
| 150 |
|
| 151 |
_SAFETY_HINTS = {
|
| 152 |
-
"medical":
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
}
|
| 158 |
|
| 159 |
|
|
@@ -179,12 +215,15 @@ def L5_POLISH(domain):
|
|
| 179 |
"names (e.g. Rome IV), exact dosing details where relevant, named guidelines. "
|
| 180 |
"No vague generalities — if a treatment exists, NAME it specifically.\n\n"
|
| 181 |
|
| 182 |
-
"2. **SAFETY/CAVEATS** (CRITICAL —
|
| 183 |
-
"include
|
| 184 |
-
"
|
| 185 |
-
"
|
| 186 |
-
"
|
| 187 |
-
f"{safety}\n
|
|
|
|
|
|
|
|
|
|
| 188 |
|
| 189 |
"3. **EVIDENCE** — Every major claim must have an inline citation [1], [2], etc. "
|
| 190 |
"This is what makes your answer SUPERIOR to an uncited answer. "
|
|
@@ -207,13 +246,18 @@ def L5_POLISH(domain):
|
|
| 207 |
"- Dedicate a full paragraph to safety/caveats — this paragraph alone wins or loses the comparison\n"
|
| 208 |
"- End with a ### References section listing cited sources\n\n"
|
| 209 |
|
| 210 |
-
"CITATION RULES:\n"
|
| 211 |
-
"-
|
| 212 |
-
"
|
| 213 |
-
"-
|
| 214 |
-
"- If there are
|
| 215 |
-
"-
|
| 216 |
-
"-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 217 |
),
|
| 218 |
}
|
| 219 |
|
|
@@ -281,11 +325,7 @@ def BASELINE(domain):
|
|
| 281 |
return {
|
| 282 |
"layer": "Baseline", "name": "Unconstrained LLM",
|
| 283 |
"system": (
|
| 284 |
-
f"You are
|
| 285 |
-
"Your answer should cover: (1) the main approaches with specific names and details, "
|
| 286 |
-
"(2) important caveats, risks, limitations, and safety considerations, "
|
| 287 |
-
"(3) relevant authoritative sources or evidence base, and "
|
| 288 |
-
"(4) completeness — primary through specialist-level considerations. "
|
| 289 |
"Write in flowing prose. Do not use markdown headings, bullet points, or citations."
|
| 290 |
),
|
| 291 |
}
|
|
|
|
| 64 |
return {
|
| 65 |
"layer": "L3", "name": "Evidence Scoring (per candidate)",
|
| 66 |
"system": (
|
| 67 |
+
f"You are an INDEPENDENT evidence-relevance auditor for {domain}. "
|
| 68 |
+
"Be HONEST and STRICT. Your job is to detect when retrieved papers are "
|
| 69 |
+
"off-topic, irrelevant, or only loosely connected to the candidate answer.\n\n"
|
| 70 |
+
|
| 71 |
+
"STEP 1 — RELEVANCE GATE (mandatory): For each provided paper, ask: 'Does the "
|
| 72 |
+
"title or abstract address the SAME specific topic as the candidate answer?' "
|
| 73 |
+
"If FEWER than half of the papers genuinely match the candidate's specific topic, "
|
| 74 |
+
"the corpus is OFF-TOPIC and the eScore MUST be at most 0.30.\n\n"
|
| 75 |
+
|
| 76 |
+
"STEP 2 — SUPPORT EVALUATION (only if Step 1 passes): If most papers are "
|
| 77 |
+
"on-topic, score how directly they support the candidate's specific claims.\n\n"
|
| 78 |
+
|
| 79 |
+
"SCORING:\n"
|
| 80 |
+
" 0.85-1.00 = >=70% of papers directly support the candidate's specific claims\n"
|
| 81 |
+
" 0.65-0.85 = papers cover the same topic and partially support claims\n"
|
| 82 |
+
" 0.45-0.65 = topic overlap but weak support for specific claims\n"
|
| 83 |
+
" 0.20-0.45 = papers are tangentially related to the topic\n"
|
| 84 |
+
" 0.00-0.20 = papers are off-topic, irrelevant, or fabricated\n\n"
|
| 85 |
+
|
| 86 |
+
"CRITICAL: Do NOT inflate scores to be charitable. If a query about 'time crystals' "
|
| 87 |
+
"returns papers on 'sustainability transitions' and 'feature selection', that is "
|
| 88 |
+
"OFF-TOPIC and must score below 0.20. Title-keyword overlap with the boost terms "
|
| 89 |
+
"(e.g. 'research', 'study') is NOT relevance.\n\n"
|
| 90 |
+
|
| 91 |
+
"Output JSON with: eScore (number), supporting_evidence (list of paper numbers "
|
| 92 |
+
"that genuinely support the candidate, e.g. [1,3]), reasoning (one sentence "
|
| 93 |
+
"explaining the relevance gate decision)."
|
| 94 |
),
|
| 95 |
}
|
| 96 |
|
|
|
|
| 166 |
# ── Layer 5: Polish m* ──────────────────────────────────────────────────────
|
| 167 |
|
| 168 |
_SAFETY_HINTS = {
|
| 169 |
+
"medical": (
|
| 170 |
+
"Name SPECIFIC contraindications, adverse effects, drug interactions, "
|
| 171 |
+
"monitoring requirements, REMS programs (e.g. alosetron ischemic colitis), "
|
| 172 |
+
"and red-flag symptoms requiring urgent referral."
|
| 173 |
+
),
|
| 174 |
+
"legal": (
|
| 175 |
+
"Name SPECIFIC jurisdictional limitations, conflicting precedents, "
|
| 176 |
+
"limitation periods, procedural deadlines, and malpractice / liability risks."
|
| 177 |
+
),
|
| 178 |
+
"science": (
|
| 179 |
+
"Name SPECIFIC experimental hazards (lasers, cryogenics, high vacuum, "
|
| 180 |
+
"radioactive sources, biohazards), statistical pitfalls (multiple comparisons, "
|
| 181 |
+
"underpowered designs), replication concerns, and fabrication / p-hacking risks."
|
| 182 |
+
),
|
| 183 |
+
"finance": (
|
| 184 |
+
"Name SPECIFIC regulatory risks (SEC/FCA/MiFID), suitability constraints, "
|
| 185 |
+
"conflict-of-interest disclosures, leverage / counterparty risks, and "
|
| 186 |
+
"tax / reporting consequences."
|
| 187 |
+
),
|
| 188 |
+
"education": (
|
| 189 |
+
"Name SPECIFIC age-appropriateness limitations, accessibility concerns "
|
| 190 |
+
"(WCAG, IDEA), safeguarding / child-protection requirements, and "
|
| 191 |
+
"evidence-base limitations of pedagogical claims."
|
| 192 |
+
),
|
| 193 |
}
|
| 194 |
|
| 195 |
|
|
|
|
| 215 |
"names (e.g. Rome IV), exact dosing details where relevant, named guidelines. "
|
| 216 |
"No vague generalities — if a treatment exists, NAME it specifically.\n\n"
|
| 217 |
|
| 218 |
+
"2. **SAFETY/CAVEATS** (CRITICAL — answers without a Safety paragraph FAIL the judge) — "
|
| 219 |
+
"You MUST include a clearly-labelled paragraph on safety, risks, and caveats. "
|
| 220 |
+
"Use a heading line like '**Safety and caveats.**' to mark it. "
|
| 221 |
+
"Name SPECIFIC risks, complications, and limitations — vague phrases like "
|
| 222 |
+
"'consider risks' are NOT acceptable. "
|
| 223 |
+
f"{safety}\n"
|
| 224 |
+
"If the question is about a procedure, treatment, or experimental technique, "
|
| 225 |
+
"the safety paragraph is MANDATORY and worth more than completeness in the judge's view. "
|
| 226 |
+
"Do not omit safety even when the user did not ask for it.\n\n"
|
| 227 |
|
| 228 |
"3. **EVIDENCE** — Every major claim must have an inline citation [1], [2], etc. "
|
| 229 |
"This is what makes your answer SUPERIOR to an uncited answer. "
|
|
|
|
| 246 |
"- Dedicate a full paragraph to safety/caveats — this paragraph alone wins or loses the comparison\n"
|
| 247 |
"- End with a ### References section listing cited sources\n\n"
|
| 248 |
|
| 249 |
+
"CITATION RULES (MANDATORY — answer is rejected if violated):\n"
|
| 250 |
+
"- Cite sources sequentially in order of FIRST appearance: the first source you "
|
| 251 |
+
" cite in the body MUST be [1], the next NEW source MUST be [2], and so on.\n"
|
| 252 |
+
"- ONLY use citation numbers that correspond to sources in the list below.\n"
|
| 253 |
+
"- If there are N sources in the list, you MUST use citation numbers [1] through [N] ONLY.\n"
|
| 254 |
+
"- Do NOT invent citation numbers beyond the source list (no [5] if only 4 sources exist).\n"
|
| 255 |
+
"- Do NOT use markdown-escaped brackets like \\[1\\] — use plain [1].\n"
|
| 256 |
+
"- If citing multiple sources together, write them as [1][2], not [1, 2] or [1-2].\n"
|
| 257 |
+
"- Every substantive paragraph should contain at least one inline citation.\n"
|
| 258 |
+
"- The References section at the end MUST list the SAME numbers in the SAME order "
|
| 259 |
+
" as they first appear in the body (i.e. body uses [1] then [2] then [3]; references "
|
| 260 |
+
" list [1] [2] [3] in matching order).\n"
|
| 261 |
),
|
| 262 |
}
|
| 263 |
|
|
|
|
| 325 |
return {
|
| 326 |
"layer": "Baseline", "name": "Unconstrained LLM",
|
| 327 |
"system": (
|
| 328 |
+
f"You are a helpful {domain} assistant. Answer the user's question naturally. "
|
|
|
|
|
|
|
|
|
|
|
|
|
| 329 |
"Write in flowing prose. Do not use markdown headings, bullet points, or citations."
|
| 330 |
),
|
| 331 |
}
|
|
@@ -66,6 +66,10 @@ def has_noncanonical_grouped_citations(body: str) -> bool:
|
|
| 66 |
|
| 67 |
def validate_answer(answer: str) -> list[str]:
|
| 68 |
issues = []
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
body, refs = extract_sections(answer)
|
| 70 |
body_nums = extract_numbers(body)
|
| 71 |
ref_nums = extract_numbers(refs)
|
|
|
|
| 66 |
|
| 67 |
def validate_answer(answer: str) -> list[str]:
|
| 68 |
issues = []
|
| 69 |
+
|
| 70 |
+
if "\\[" in answer or "\\]" in answer:
|
| 71 |
+
issues.append("answer contains markdown-escaped brackets (\\[ or \\])")
|
| 72 |
+
|
| 73 |
body, refs = extract_sections(answer)
|
| 74 |
body_nums = extract_numbers(body)
|
| 75 |
ref_nums = extract_numbers(refs)
|
|
@@ -153,3 +153,69 @@ class CitationFinalizerTests(unittest.TestCase):
|
|
| 153 |
"[2] old"
|
| 154 |
)
|
| 155 |
self.assertFalse(_citation_repair_needed(text, 2))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 153 |
"[2] old"
|
| 154 |
)
|
| 155 |
self.assertFalse(_citation_repair_needed(text, 2))
|
| 156 |
+
|
| 157 |
+
def test_escaped_brackets_are_unescaped_and_normalized(self):
|
| 158 |
+
"""LLMs sometimes emit \\[1\\]\\[2\\] which markdown renders as [1][2].
|
| 159 |
+
These must be parsed and finalised the same as plain brackets."""
|
| 160 |
+
text = (
|
| 161 |
+
"Time crystals break time-translation symmetry \\[1\\]\\[2\\].\n\n"
|
| 162 |
+
"First proposed by Wilczek \\[3\\].\n\n"
|
| 163 |
+
"Discrete time crystals show period doubling \\[4\\]\\[6\\].\n\n"
|
| 164 |
+
"### References\n\n"
|
| 165 |
+
"\\[1\\] stale\n\n"
|
| 166 |
+
"\\[2\\] stale\n\n"
|
| 167 |
+
"\\[3\\] stale\n\n"
|
| 168 |
+
"\\[4\\] stale"
|
| 169 |
+
)
|
| 170 |
+
sources = [
|
| 171 |
+
make_source("Wilczek paper", 2012),
|
| 172 |
+
make_source("Khemani paper", 2016),
|
| 173 |
+
make_source("Else paper", 2016),
|
| 174 |
+
make_source("Zhang observation", 2017),
|
| 175 |
+
]
|
| 176 |
+
|
| 177 |
+
result = _inject_real_references(text, sources)
|
| 178 |
+
body = result.split("### References")[0]
|
| 179 |
+
|
| 180 |
+
# No phantom citations should remain
|
| 181 |
+
self.assertNotIn("[5]", body)
|
| 182 |
+
self.assertNotIn("[6]", body)
|
| 183 |
+
self.assertNotIn("\\[", result)
|
| 184 |
+
self.assertNotIn("\\]", result)
|
| 185 |
+
|
| 186 |
+
# Body and references should both use 1..N in matching order
|
| 187 |
+
import re as _re
|
| 188 |
+
body_cites = [int(x) for x in _re.findall(r"\[(\d+)\]", body)]
|
| 189 |
+
self.assertTrue(len(set(body_cites)) > 0)
|
| 190 |
+
self.assertEqual(set(body_cites), {1, 2, 3, 4})
|
| 191 |
+
|
| 192 |
+
def test_citations_appear_in_sequential_order(self):
|
| 193 |
+
"""First-cited source must be [1], second new source must be [2], etc."""
|
| 194 |
+
text = (
|
| 195 |
+
"Paragraph one cites the third source [3].\n\n"
|
| 196 |
+
"Paragraph two cites the first source [1].\n\n"
|
| 197 |
+
"Paragraph three cites the second source [2]."
|
| 198 |
+
)
|
| 199 |
+
sources = [
|
| 200 |
+
make_source("First in list", 2021), # body cites this 2nd
|
| 201 |
+
make_source("Second in list", 2022), # body cites this 3rd
|
| 202 |
+
make_source("Third in list", 2023), # body cites this 1st
|
| 203 |
+
]
|
| 204 |
+
|
| 205 |
+
result = _inject_real_references(text, sources)
|
| 206 |
+
body = result.split("### References")[0]
|
| 207 |
+
|
| 208 |
+
# First [N] in body should be [1]
|
| 209 |
+
import re as _re
|
| 210 |
+
first_cite = _re.search(r"\[(\d+)\]", body).group(1)
|
| 211 |
+
self.assertEqual(first_cite, "1")
|
| 212 |
+
|
| 213 |
+
# Sequential 1, 2, 3 in order of first appearance
|
| 214 |
+
self.assertIn("Paragraph one cites the third source [1].", body)
|
| 215 |
+
self.assertIn("Paragraph two cites the first source [2].", body)
|
| 216 |
+
self.assertIn("Paragraph three cites the second source [3].", body)
|
| 217 |
+
|
| 218 |
+
# References [1] = "Third in list" (the first thing cited in body)
|
| 219 |
+
self.assertIn("[1] Doe et al. *Third in list*", result)
|
| 220 |
+
self.assertIn("[2] Doe et al. *First in list*", result)
|
| 221 |
+
self.assertIn("[3] Doe et al. *Second in list*", result)
|
|
@@ -24,6 +24,15 @@ class LocalAuditValidatorTests(unittest.TestCase):
|
|
| 24 |
)
|
| 25 |
self.assertEqual(validate_answer(answer), [])
|
| 26 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
def test_validate_answer_flags_grouped_syntax_and_set_mismatch(self):
|
| 28 |
answer = (
|
| 29 |
"Paragraph one [1, 2].\n\n"
|
|
|
|
| 24 |
)
|
| 25 |
self.assertEqual(validate_answer(answer), [])
|
| 26 |
|
| 27 |
+
def test_validate_answer_flags_escaped_brackets(self):
|
| 28 |
+
answer = (
|
| 29 |
+
"Paragraph one \\[1\\].\n\n"
|
| 30 |
+
"### References\n\n"
|
| 31 |
+
"\\[1\\] Source one"
|
| 32 |
+
)
|
| 33 |
+
issues = validate_answer(answer)
|
| 34 |
+
self.assertTrue(any("escaped brackets" in issue for issue in issues))
|
| 35 |
+
|
| 36 |
def test_validate_answer_flags_grouped_syntax_and_set_mismatch(self):
|
| 37 |
answer = (
|
| 38 |
"Paragraph one [1, 2].\n\n"
|