Coverage for app / util / source_registry.py: 98%
95 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"""One id for each source a turn's models see, so an answer's citations are exact.
3Every source a model is shown during one run — a knowledge passage the
4pipeline packed, a web search result, a page ``url_fetch`` read, a passage a
5knowledge tool returned, a graph entity — is shown with an id from this
6registry: ``Cite as: [S3]`` on a tool result's block, ``#### [S3]`` on a
7packed passage. The model cites by the id; CHAIN-R renumbers what the answer
8cites and writes its Sources block from the registry
9(``answer_sources.finalise``). A bare number the model invents can then never
10be read as a source, and no Sources section depends on the model writing one.
12**One id per source**, not per chunk: a source is a page (by its URL, so a
13search hit, its fetch and a knowledge base's snapshot of the same page share
14one), else a knowledge base's document, else a graph entity. A reader's
15Sources list is about documents and pages; the passage's page and chunk stay
16on the citation.
18**Carried in the run config** (``configurable[CONFIG_KEY]``), set by
19``AgentGraphBuilder.run_config`` for every run — batch, stream and resume —
20and read with :func:`current` wherever the code runs: LangChain hands the run
21config to every node, ``Send`` branch, tool and executor thread
22(``var_child_runnable_config``), and the object is shared, not copied. A
23``ContextVar`` set inside the streaming generator would not be: it belongs to
24whichever task advances the generator. The key starts ``__`` so LangGraph
25never copies it into checkpoint metadata. Allocation is locked, for sync
26tools on executor threads. Code with no run (a tool called on its own) gets
27no registry and prints no ids.
28"""
30from __future__ import annotations
32import re
33import threading
34from typing import Any, Iterable
35from urllib.parse import urlsplit
37#: Where a run's registry lives in its config's ``configurable``.
38CONFIG_KEY = "__chainr_sources"
40#: An id as it is written: ``S`` and a number.
41ID = re.compile(r"^S(\d+)$")
44def norm_url(url: str) -> str:
45 """Scheme, ``www.``, fragment and a trailing slash don't make a URL a
46 different source."""
47 if not url:
48 return ""
49 try:
50 parts = urlsplit(url.strip())
51 except ValueError:
52 return ""
53 host = (parts.hostname or "").lower().removeprefix("www.")
54 if not host:
55 return ""
56 path = parts.path.rstrip("/")
57 return f"{host}{path}" + (f"?{parts.query}" if parts.query else "")
60def _url_of(citation: dict[str, Any]) -> str:
61 for key in ("url", "source"):
62 value = str(citation.get(key) or "")
63 if value.startswith(("http://", "https://")):
64 return value
65 return ""
68def source_key(citation: dict[str, Any]) -> str:
69 """What makes two citations the same source: the page's URL, else the
70 document, else the graph entity, else the name.
72 A document is keyed by its id alone, which is unique: a hit that
73 ``search_knowledge`` returned carried no knowledge base, so the passage
74 the pipeline had packed as S1 came back as S3, and the quality check
75 called the answer's citation of either one fabricated."""
76 url = norm_url(_url_of(citation))
77 if url:
78 return f"url:{url}"
79 kb = str(citation.get("kb_id") or citation.get("kb_name") or "")
80 source = str(citation.get("source") or citation.get("title") or "").strip()
81 if citation.get("tool") == "retrieval_graph" or source.startswith("Entity:"):
82 return f"entity:{kb}:{source.lower()}"
83 document = str(citation.get("document_id") or "")
84 if document:
85 return f"doc:{document}"
86 return f"doc:{kb}:{source.lower()}"
89def _merged(first: dict[str, Any], later: dict[str, Any]) -> dict[str, Any]:
90 """The first citation of a source, with what a later one adds (a fetched
91 page's title and date to a search hit)."""
92 out = dict(first)
93 for key, value in later.items():
94 if value not in (None, "", [], {}) and out.get(key) in (None, "", [], {}):
95 out[key] = value
96 return out
99class SourceRegistry:
100 """The ids one run has handed out, and what each names."""
102 def __init__(self) -> None:
103 self._lock = threading.Lock()
104 self._ids: dict[str, str] = {}
105 self._sources: dict[str, dict[str, Any]] = {}
106 self._count = 0
108 def cite(self, citation: dict[str, Any]) -> str:
109 """The id of the source ``citation`` names, handed out the first time
110 it is seen."""
111 key = source_key(citation)
112 with self._lock:
113 sid = self._ids.get(key)
114 if sid is None:
115 self._count += 1
116 sid = f"S{self._count}"
117 self._ids[key] = sid
118 self._sources[sid] = {**citation, "citation_id": sid}
119 else:
120 self._sources[sid] = _merged(self._sources[sid], citation)
121 self._sources[sid]["citation_id"] = sid
122 return sid
124 def get(self, sid: str) -> dict[str, Any] | None:
125 with self._lock:
126 found = self._sources.get(sid)
127 return dict(found) if found else None
129 def issued(self) -> bool:
130 with self._lock:
131 return bool(self._sources)
133 def sources(self) -> dict[str, dict[str, Any]]:
134 with self._lock:
135 return {sid: dict(c) for sid, c in self._sources.items()}
137 def seed(self, citations: Iterable[dict[str, Any]]) -> None:
138 """Take back the ids an earlier segment of this run handed out — a
139 resumed run's checkpointed citations — so numbering carries on and a
140 source keeps its id."""
141 with self._lock:
142 for citation in citations:
143 sid = str(citation.get("citation_id") or "")
144 match = ID.match(sid)
145 if not match:
146 continue
147 key = source_key(citation)
148 self._ids.setdefault(key, sid)
149 self._sources[sid] = (
150 _merged(self._sources[sid], citation)
151 if sid in self._sources
152 else {**citation, "citation_id": sid}
153 )
154 self._count = max(self._count, int(match.group(1)))
157def of_config(config: Any) -> SourceRegistry | None:
158 """The registry a run config carries, or None."""
159 if not isinstance(config, dict):
160 return None
161 found = (config.get("configurable") or {}).get(CONFIG_KEY)
162 return found if isinstance(found, SourceRegistry) else None
165def current() -> SourceRegistry | None:
166 """The registry of the run this code is part of, or None outside a run."""
167 from langchain_core.runnables.config import var_child_runnable_config
169 return of_config(var_child_runnable_config.get())
172def cite_line(citation: dict[str, Any]) -> str | None:
173 """``Cite as: [S3]`` for a tool result's block, or None outside a run."""
174 registry = current()
175 if registry is None:
176 return None
177 return f"Cite as: [{registry.cite(citation)}]"