Coverage for app / agents / answer_sources.py: 95%
334 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""What an answer cites, and the Sources block CHAIN-R writes for it.
3Every source a run's models see carries an id (``util/source_registry``):
4``Cite as: [S3]`` on a tool result's block, ``#### [S3]`` on a packed
5passage. The model marks each fact with the id; it is told never to number
6sources and never to write a Sources section (``prompts.RESPONSE_FORMATTING_
7STANDARDS``). Once the quality check's verdict is final, :func:`finalise`
8turns that into what the person reads:
101. markers are normalised (``source_ledger.normalise_citation_markers``);
112. a citation section the model wrote anyway is taken out — only when it
12 ends the answer and every entry names a source the run was given, so a
13 reading list that *is* the answer stays — and the numbers it gave each
14 source are kept as a map, so ``[1]`` its section ties to a page's URL
15 reads as that page;
163. every other bare number is escaped (``\\[2\\]``): it names no source, and
17 left as written it would read as one of the numbers below;
184. ``[S#]`` markers become ``[1]``, ``[2]``… in order of first use, a group
19 (``[S1, S3]``) becoming ``[1] [2]``; an id the run never handed out is
20 dropped;
215. a **Sources** block listing exactly those, in that order, is appended
22 before any trailing render fences.
24Placeholder markers (``[knowledge]``, ``[source]``) cite nothing, and go.
25When the run handed out no ids, every ``[S#]`` goes too — it names nothing —
26and the rest of the answer is untouched. Nothing is done when the answer is
27not free text (a typed output's JSON). :func:`check_markers` is the quality check's
28side of the same rules: a marker that names no source is a citation problem,
29and the agent revises with the ids listed (``graph._revision_note``).
30:func:`plain` is an answer as history and memory keep it: no block, no
31markers — their ids mean nothing to a later turn.
32"""
34from __future__ import annotations
36import re
37from dataclasses import dataclass, field
38from typing import Any
40from app.agents import source_ledger
41from app.util.source_registry import SourceRegistry, norm_url
43#: An id marker, alone or grouped: ``[S3]``, ``[S1, S3]``, ``[S1; S2]`` —
44#: never a link's text (``[S3](…)``) nor its target (``](…[S3]…)``).
45_ID_GROUP = source_ledger.SID_GROUP
46#: A bare number marker: ``[3]`` — not an index (``arr[0]``), not a link's
47#: text or target.
48_BARE = re.compile(r"(?<![\w\]\\])(?<!\]\()\[(\d{1,3})\](?!\()")
49#: A marker that stands for a source without naming one — ``[knowledge]``
50#: after an answer that said its knowledge held nothing on the subject.
51_PLACEHOLDER = re.compile(
52 r"(?<![\w\]\\])(?<!\]\()\[(?:knowledge(?: base)?|kb|sources?|web|"
53 r"citation(?: needed)?)\](?!\()",
54 re.IGNORECASE,
55)
56#: The heading of the block :func:`finalise` writes.
57SOURCES_HEADING = "**Sources**"
58#: Trailing render fences (charts, documents) the block goes before.
59_TRAILING_FENCES = re.compile(r"(?:\s*```[a-z]*[ \t]*\n.*?\n```\s*)+\Z", re.DOTALL)
60#: A line of a citation section: a list item or a marker-led entry.
61_ENTRY_LINE = re.compile(r"^\s*(?:[-*•+]\s+|\d{1,3}[.)]\s+|\[)")
62_URL = re.compile(r"https?://[^\s)>\]]+")
63_UNSAFE = re.compile(r"([\\`*_\[\]<>|#])")
66@dataclass
67class FinalAnswer:
68 """An answer as it is delivered."""
70 text: str
71 #: The sources it cites, in order, each with its ``marker`` (1, 2, …).
72 cited: list[dict[str, Any]] = field(default_factory=list)
73 #: Ids it wrote that the run never handed out, removed.
74 dropped: list[str] = field(default_factory=list)
77def _split_code(text: str) -> list[tuple[bool, str]]:
78 """``text`` as (is_code, segment) pairs, so prose rules never touch code."""
79 out: list[tuple[bool, str]] = []
80 last = 0
81 for code in source_ledger._CODE.finditer(text):
82 out.append((False, text[last : code.start()]))
83 out.append((True, code.group(0)))
84 last = code.end()
85 out.append((False, text[last:]))
86 return out
89_ids_in = source_ledger.ids_in_group
92def _url_index(registry: SourceRegistry) -> dict[str, str]:
93 """Each source's normalised URL → its id."""
94 out: dict[str, str] = {}
95 for sid, citation in registry.sources().items():
96 for key in ("url", "source"):
97 url = norm_url(str(citation.get(key) or ""))
98 if url:
99 out.setdefault(url, sid)
100 return out
103def _section_bounds(text: str) -> tuple[int, int] | None:
104 """Where a citation section the model wrote runs: from its heading to
105 the end, when it is the last thing in the text."""
106 lines = text.split("\n")
107 for i in range(len(lines) - 1, -1, -1):
108 if source_ledger._SOURCES_HEADING.match(lines[i]):
109 start = sum(len(line) + 1 for line in lines[:i])
110 return start, len(text)
111 return None
114def _name_index(registry: SourceRegistry) -> list[tuple[str, str]]:
115 """Each source's title and name, lowercased → its id, longest first."""
116 out: list[tuple[str, str]] = []
117 for sid, citation in registry.sources().items():
118 for key in ("title", "source", "page_title"):
119 name = " ".join(str(citation.get(key) or "").split()).lower()
120 if name.startswith("entity:"):
121 name = name[len("entity:") :]
122 if len(name) >= 3:
123 out.append((name, sid))
124 return sorted(out, key=lambda pair: -len(pair[0]))
127#: An entry's leading bullet and number: ``- [1] ``, ``1. ``, ``[2] ``.
128_ENTRY_LEAD = re.compile(r"^\s*(?:[-*•+]\s+)?(?:\[?\d{1,3}[\].)]\s*)?")
131def _section_map(section: str, registry: SourceRegistry) -> tuple[bool, dict[str, str]]:
132 """Whether a citation section only names the run's sources, and the
133 numbers it gave them (``"1"`` → ``"S3"``). An entry names a source by its
134 id, its URL, or — for a document, which has none — by starting with its
135 name, as the block :func:`finalise` writes does."""
136 by_url = _url_index(registry)
137 by_name = _name_index(registry)
138 numbers: dict[str, str] = {}
139 entries = [line for line in section.split("\n")[1:] if line.strip()]
140 if not entries:
141 return False, {}
142 for line in entries:
143 if not _ENTRY_LINE.match(line):
144 return False, {}
145 ids = [sid for g in _ID_GROUP.findall(line) for sid in _ids_in(g)]
146 known = [sid for sid in ids if registry.get(sid)]
147 urls = [by_url.get(norm_url(u.rstrip(".,;"))) for u in _URL.findall(line)]
148 resolved = known or [sid for sid in urls if sid]
149 if not resolved:
150 text = " ".join(re.sub(r"\\(.)", r"\1", line).split()).lower()
151 text = _ENTRY_LEAD.sub("", text).lstrip("[")
152 resolved = [sid for name, sid in by_name if text.startswith(name)][:1]
153 if not resolved:
154 return False, {}
155 number = re.match(r"^\s*(?:[-*•+]\s+)?\[?(\d{1,3})[\].)]", line)
156 if number:
157 numbers[number.group(1)] = resolved[0]
158 return True, numbers
161def _renumber(
162 prose: str,
163 registry: SourceRegistry,
164 numbers: dict[str, str],
165 order: dict[str, int],
166 dropped: list[str],
167) -> str:
168 def number_of(sid: str) -> int:
169 if sid not in order:
170 order[sid] = len(order) + 1
171 return order[sid]
173 def bare(match: re.Match[str]) -> str:
174 sid = numbers.get(match.group(1))
175 return f"[{sid}]" if sid else rf"\[{match.group(1)}\]"
177 def group(match: re.Match[str]) -> str:
178 known = []
179 for sid in _ids_in(match.group(1)):
180 sid = sid.upper()
181 if registry.get(sid):
182 known.append(sid)
183 elif sid not in dropped:
184 dropped.append(sid)
185 if not known:
186 return _REMOVED
187 return " ".join(f"[{number_of(sid)}]" for sid in dict.fromkeys(known))
189 prose = _BARE.sub(bare, prose)
190 prose = _ID_GROUP.sub(group, prose)
191 prose = _PLACEHOLDER.sub(_REMOVED, prose)
192 # A marker dropped whole takes the space before it with it.
193 return re.sub(rf"[ \t]*{_REMOVED}", "", prose)
196def _without_ids(prose: str, dropped: list[str]) -> str:
197 """``prose`` from a run that handed out no ids: every id marker and
198 placeholder goes, bare numbers stay as written."""
200 def group(match: re.Match[str]) -> str:
201 for sid in _ids_in(match.group(1)):
202 if sid.upper() not in dropped:
203 dropped.append(sid.upper())
204 return _REMOVED
206 prose = _ID_GROUP.sub(group, prose)
207 prose = _PLACEHOLDER.sub(_REMOVED, prose)
208 return re.sub(rf"[ \t]*{_REMOVED}", "", prose)
211#: Where a dropped marker was, until the space before it goes too.
212_REMOVED = "\u0000"
215def _escape(text: str) -> str:
216 return _UNSAFE.sub(r"\\\1", " ".join(str(text).split()))
219def _link(title: str, url: str) -> str:
220 if not url.startswith(("http://", "https://")) or any(c in url for c in " <>"):
221 return _escape(title)
222 return f"[{_escape(title)}](<{url}>)"
225def _date(value: Any) -> str:
226 return str(value)[:10] if value else ""
229def entry_line(marker: int, citation: dict[str, Any]) -> str:
230 """One line of the Sources block, for the source a marker names."""
231 url = str(citation.get("url") or "")
232 source = str(citation.get("source") or "")
233 if not url and source.startswith(("http://", "https://")):
234 url = source
235 title = str(citation.get("page_title") or citation.get("title") or source or url)
236 if title.startswith("Entity:"):
237 title = title[len("Entity:") :]
238 parts = [f"[{marker}] {_link(title, url) if url else _escape(title)}"]
239 details: list[str] = []
240 kb = str(citation.get("kb_name") or "")
241 publisher = str(citation.get("publisher") or citation.get("attribution") or "")
242 if kb:
243 details.append(_escape(kb))
244 elif publisher:
245 details.append(_escape(publisher))
246 if citation.get("page_number") is not None and not url:
247 details.append(f"p.{citation['page_number']}")
248 published = _date(citation.get("published"))
249 if published:
250 details.append(published)
251 line = parts[0] + (f" — {' · '.join(details)}" if details else "")
252 via = citation.get("via") or []
253 if via and isinstance(via, list) and isinstance(via[0], dict) and via[0].get("url"):
254 line += f" — via {_link(str(via[0].get('title') or via[0]['url']), str(via[0]['url']))}"
255 return f"- {line}"
258def sources_block(cited: list[dict[str, Any]]) -> str:
259 """The **Sources** block for ``cited`` (each with its ``marker``)."""
260 if not cited:
261 return ""
262 lines = [SOURCES_HEADING, *(entry_line(c["marker"], c) for c in cited)]
263 return "\n".join(lines)
266def _is_data(text: str) -> bool:
267 """An answer that is data — JSON whole — is no prose to cite in: its
268 ``[1]`` is an array."""
269 stripped = text.strip()
270 if not stripped.startswith(("{", "[")):
271 return False
272 from app.util import safe_json
274 try:
275 safe_json.loads_exact(stripped)
276 except ValueError:
277 return False
278 return True
281def finalise(text: str, registry: SourceRegistry | None) -> FinalAnswer:
282 """The answer as it is delivered: markers renumbered by first use and a
283 Sources block of exactly what they cite (see the module notes)."""
284 if not text or registry is None or _is_data(text):
285 return FinalAnswer(text)
286 if not registry.issued():
287 # Nothing was shown with an id, so an id names nothing: an answer
288 # that wrote "[S1, S2]" over an empty search shipped them.
289 dropped: list[str] = []
290 out = "".join(
291 segment if is_code else _without_ids(segment, dropped)
292 for is_code, segment in _split_code(text)
293 )
294 return FinalAnswer(out, [], dropped)
295 fences_match = _TRAILING_FENCES.search(text)
296 body = text[: fences_match.start()] if fences_match else text
297 fences = text[fences_match.start() :] if fences_match else ""
298 body = source_ledger.normalise_citation_markers(body)
300 numbers: dict[str, str] = {}
301 bounds = _section_bounds(body)
302 if bounds is not None:
303 provable, numbers = _section_map(body[bounds[0] :], registry)
304 if provable:
305 body = body[: bounds[0]].rstrip()
306 else:
307 numbers = {}
309 order: dict[str, int] = {}
310 dropped: list[str] = []
311 body = "".join(
312 segment if is_code else _renumber(segment, registry, numbers, order, dropped)
313 for is_code, segment in _split_code(body)
314 )
315 cited = [
316 {**(registry.get(sid) or {}), "citation_id": sid, "marker": n}
317 for sid, n in order.items()
318 ]
319 block = sources_block(cited)
320 out = body.rstrip() + (f"\n\n{block}" if block else "")
321 if fences:
322 out += "\n\n" + fences.strip("\n")
323 return FinalAnswer(out, cited, dropped)
326@dataclass(frozen=True)
327class MarkerProblem:
328 """A marker in a draft that names no source the run was given."""
330 marker: str
331 #: ``unknown_id``: an id never handed out; ``not_an_id``: a number.
332 kind: str
335def check_markers(draft: str, registry: SourceRegistry | None) -> list[MarkerProblem]:
336 """What in ``draft`` would not survive :func:`finalise` as a citation:
337 ids the run never handed out, and numbers no citation section of the
338 draft ties to a source. When the run handed out no ids, every id is
339 unknown and numbers are left alone."""
340 if not draft or registry is None or _is_data(draft):
341 return []
342 body = source_ledger.normalise_citation_markers(draft)
343 if not registry.issued():
344 unknown: list[MarkerProblem] = []
345 for is_code, segment in _split_code(body):
346 if is_code:
347 continue
348 for group in _ID_GROUP.findall(segment):
349 for sid in _ids_in(group):
350 marker = f"[{sid.upper()}]"
351 if all(p.marker != marker for p in unknown):
352 unknown.append(MarkerProblem(marker, "unknown_id"))
353 return unknown
354 numbers: dict[str, str] = {}
355 bounds = _section_bounds(body)
356 if bounds is not None:
357 provable, numbers = _section_map(body[bounds[0] :], registry)
358 body = body[: bounds[0]] if provable else body
359 numbers = numbers if provable else {}
360 problems: list[MarkerProblem] = []
361 seen: set[str] = set()
362 for is_code, segment in _split_code(body):
363 if is_code:
364 continue
365 for group in _ID_GROUP.findall(segment):
366 for sid in _ids_in(group):
367 sid = sid.upper()
368 if not registry.get(sid) and sid not in seen:
369 seen.add(sid)
370 problems.append(MarkerProblem(f"[{sid}]", "unknown_id"))
371 for number in _BARE.findall(segment):
372 if number not in numbers and number not in seen:
373 seen.add(number)
374 problems.append(MarkerProblem(f"[{number}]", "not_an_id"))
375 return problems
378def for_check(draft: str, registry: SourceRegistry | None) -> str:
379 """``draft`` as the quality check reads it: without the id markers that
380 name no source the run handed out, and the placeholders that stand for
381 one. Ids it did hand out stay as written, for ``<citation_check>``.
383 Those markers are code's: :func:`finalise` drops them, and the evaluator
384 sends the rest back with the ids the agent may use (:func:`check_markers`).
385 A check that saw them judged them again, though its prompt said not to:
386 an ``[S3]`` on a turn that handed out no ids failed a correct answer as an
387 unsupported fact, and the revision that took it out shipped failed for it
388 (scenario run 7)."""
389 if not draft or registry is None or _is_data(draft):
390 return draft
392 def group(match: re.Match[str]) -> str:
393 known = [sid.upper() for sid in _ids_in(match.group(1))]
394 known = [sid for sid in dict.fromkeys(known) if registry.get(sid)]
395 return f"[{', '.join(known)}]" if known else _REMOVED
397 out = []
398 for is_code, segment in _split_code(
399 source_ledger.normalise_citation_markers(draft)
400 ):
401 if not is_code:
402 segment = _ID_GROUP.sub(group, segment)
403 segment = _PLACEHOLDER.sub(_REMOVED, segment)
404 segment = re.sub(rf"[ \t]*{_REMOVED}", "", segment)
405 out.append(segment)
406 return "".join(out)
409def describe_problems(
410 problems: list[MarkerProblem], registry: SourceRegistry | None
411) -> list[str]:
412 """``problems`` as the agent reads them on a revision, with the ids it
413 may use."""
414 lines = []
415 for p in problems:
416 if p.kind == "unknown_id":
417 lines.append(f"{p.marker} is not an id you were given.")
418 else:
419 lines.append(
420 f"{p.marker} is a number, not a source id: mark the fact with "
421 "the id its source was shown with."
422 )
423 if registry is not None and lines:
424 given = [
425 f"[{sid}] {c.get('title') or c.get('source') or ''}".strip()
426 for sid, c in registry.sources().items()
427 ]
428 if given:
429 lines.append("The ids you were given: " + "; ".join(given[:20]))
430 else:
431 lines.append(
432 "You were given no source ids for this request: take the markers out."
433 )
434 return lines
437def plain(text: str) -> str:
438 """An answer as history and memory keep it: without the Sources block
439 and the markers, which name sources a later turn was never shown."""
440 if not text:
441 return text
442 at = text.rfind(f"\n{SOURCES_HEADING}\n")
443 if at >= 0:
444 tail = text[at + len(SOURCES_HEADING) + 2 :]
445 rest = tail.split("\n")
446 kept = [line for line in rest if not line.startswith("- [")]
447 text = text[:at] + (
448 "\n" + "\n".join(kept) if any(k.strip() for k in kept) else ""
449 )
450 out = []
451 for is_code, segment in _split_code(text):
452 if not is_code:
453 segment = _ID_GROUP.sub("", _BARE.sub("", segment))
454 segment = _PLACEHOLDER.sub("", segment)
455 segment = re.sub(r"[ \t]+([.,;:!?])", r"\1", segment)
456 segment = re.sub(r"[ \t]{2,}", " ", segment)
457 segment = re.sub(r"[ \t]+(?=\n)", "", segment)
458 out.append(segment)
459 return "".join(out).rstrip()
462def document_line(citation: dict[str, Any]) -> str:
463 """A document's sources-list line for one cited source: ``Title — URL
464 (date)``, or ``Name (knowledge base)`` for a document with no URL — the
465 shape ``DocumentSpec.sources`` takes."""
466 url = str(citation.get("url") or "")
467 source = str(citation.get("source") or "")
468 if not url and source.startswith(("http://", "https://")):
469 url = source
470 title = " ".join(
471 str(
472 citation.get("page_title") or citation.get("title") or source or url
473 ).split()
474 )
475 if title.startswith("Entity:"):
476 title = title[len("Entity:") :]
477 published = _date(citation.get("published"))
478 kb = str(citation.get("kb_name") or "")
479 if url:
480 return f"{title} — {url}" + (f" ({published})" if published else "")
481 return title + (f" ({kb})" if kb else "")
484def renumber_document(
485 fields: dict[str, Any], registry: SourceRegistry | None
486) -> dict[str, Any] | None:
487 """A document's fields with the ids its text cites renumbered ``[1]``…
488 by first use — summary, then key findings, then body — and its
489 ``sources`` list built from them; None when its text cites no id the run
490 handed out (its own sources list then stands)."""
491 if registry is None or not registry.issued():
492 return None
493 order: dict[str, int] = {}
494 dropped: list[str] = []
496 def renumbered(text: str) -> str:
497 return "".join(
498 segment if is_code else _renumber(segment, registry, {}, order, dropped)
499 for is_code, segment in _split_code(text)
500 )
502 out = dict(fields)
503 if isinstance(out.get("summary"), str):
504 out["summary"] = renumbered(out["summary"])
505 if isinstance(out.get("key_findings"), list):
506 out["key_findings"] = [
507 renumbered(v) if isinstance(v, str) else v for v in out["key_findings"]
508 ]
509 if isinstance(out.get("body"), str):
510 out["body"] = renumbered(out["body"])
511 if not order:
512 return None
513 out["sources"] = [document_line(registry.get(sid) or {}) for sid in order]
514 return out
517def delivered_citations(
518 verdict: Any,
519 citations: list[dict[str, Any]],
520 registry: SourceRegistry | None,
521 final_output: str,
522) -> list[dict[str, Any]]:
523 """What the delivered answer cites: the sources :func:`finalise` listed,
524 each with its ``marker``, in order — the done frame's and the batch
525 response's ``cited_citations``. An answer that was not finalised (a
526 typed output, a run that handed out no ids) is read by
527 ``source_ledger.cited_citations``. Each of ``citations`` the answer cites
528 is stamped with its marker too, so a record that keeps every citation (a
529 skill run) can link its chips."""
530 sources = getattr(verdict, "answer_sources", None)
531 if sources is None and isinstance(verdict, dict):
532 sources = verdict.get("answer_sources")
533 if not sources:
534 return source_ledger.cited_citations(final_output, citations)
535 by_id: dict[str, dict[str, Any]] = {}
536 for c in citations:
537 sid = str(c.get("citation_id") or "")
538 if sid and sid not in by_id:
539 by_id[sid] = c
540 markers: dict[str, int] = {}
541 out: list[dict[str, Any]] = []
542 for item in sources:
543 marker = getattr(item, "marker", None) or (
544 item.get("marker") if isinstance(item, dict) else None
545 )
546 sid = getattr(item, "citation_id", None) or (
547 item.get("citation_id") if isinstance(item, dict) else None
548 )
549 if not marker or not sid:
550 continue
551 found = by_id.get(sid) or (registry.get(sid) if registry is not None else None)
552 if not found:
553 continue
554 markers[sid] = int(marker)
555 out.append(
556 source_ledger.with_kind(
557 {**found, "citation_id": sid, "marker": int(marker)}
558 )
559 )
560 for c in citations:
561 sid = str(c.get("citation_id") or "")
562 if sid in markers:
563 c["marker"] = markers[sid]
564 return out