Coverage for app / knowledge / turn_report.py: 96%
74 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"""A turn's knowledge report (``app/util/knowledge_report.py``), as svc-ai
2builds it: what the turn asked of its agent's knowledge, what each source
3gave, and what it lacked.
5The retrieval node writes what its search found into ``state.context``
6(:func:`from_bundle`, :func:`with_gaps` after a corrective pass that found
7nothing, :func:`not_searched` when nothing the agent holds applies), and the
8engine finishes it from the run's final state (:func:`assemble`): the
9agent's own ``search_knowledge`` calls counted, and a report made even for a
10turn whose knowledge was never searched (it went to the web), which is what
11says the web answered what the knowledge could not. It rides on the stream's
12``done`` frame and the batch response's context, under :data:`KEY`.
13"""
15from __future__ import annotations
17from collections.abc import Iterable, Mapping
18from typing import Any
20from app.knowledge import categories
21from app.knowledge.mix import MIX_KEY, Mix
22from app.util.knowledge_report import KnowledgeReport, SourceUse
24#: Where the report travels: in ``state.context``, on the ``done`` frame and
25#: in the batch response's context.
26KEY = "knowledge_report"
28#: The tool whose calls' artifacts count the agent's own searches.
29SEARCH_TOOL = "search_knowledge"
32def _ids(knowledge_bases: Iterable[Mapping[str, Any]]) -> list[str]:
33 return [str(kb.get("id", "")) for kb in knowledge_bases]
36def from_bundle(
37 bundle: Any,
38 knowledge_bases: list[dict[str, Any]],
39 searched: list[dict[str, Any]],
40 turn: categories.RetrievalTurn,
41 query: str,
42 *,
43 nothing_relevant: bool,
44 mix: Mix | None = None,
45) -> dict[str, Any]:
46 """The report of a turn whose knowledge was searched: ``searched`` the
47 knowledge bases the turn searched, of the agent's ``knowledge_bases``,
48 each in its role in the turn's ``mix``."""
49 counts = getattr(bundle, "kb_counts", None) or {}
50 searched_ids = set(_ids(searched))
51 return KnowledgeReport(
52 query=query,
53 live=turn.live,
54 complexity=turn.complexity,
55 profile=mix.profile if mix is not None else "",
56 searched=True,
57 nothing_relevant=nothing_relevant,
58 unresolved=list(getattr(bundle, "unresolved_mentions", None) or []),
59 scoped_out=[i for i in _ids(knowledge_bases) if i not in searched_ids],
60 sources=[
61 SourceUse(
62 knowledge_id=str(kb.get("id", "")),
63 category=categories.category_of(kb).value,
64 role=mix.role_of(str(kb.get("id", ""))) if mix is not None else "",
65 **counts.get(str(kb.get("id", "")), {}),
66 )
67 for kb in searched
68 ],
69 ).wire()
72def not_searched(
73 knowledge_bases: list[dict[str, Any]],
74 turn: categories.RetrievalTurn,
75 query: str,
76 *,
77 mix: Mix | None = None,
78) -> dict[str, Any]:
79 """The report of a turn none of whose knowledge applied."""
80 return KnowledgeReport(
81 query=query,
82 live=turn.live,
83 complexity=turn.complexity,
84 profile=mix.profile if mix is not None else "",
85 scoped_out=_ids(knowledge_bases),
86 ).wire()
89def with_gaps(report: Any, gaps: Iterable[str]) -> dict[str, Any] | None:
90 """``report`` with what the quality check found missing that a
91 corrective search of the knowledge did not find; None without one."""
92 current = KnowledgeReport.read(report)
93 if current is None:
94 return None
95 return current.model_copy(
96 update={"gaps": [*current.gaps, *[str(g) for g in gaps]]}
97 ).wire()
100def assemble(values: Mapping[str, Any]) -> dict[str, Any] | None:
101 """The turn's report from its final state, or None for an agent with no
102 knowledge. What the retrieval node wrote, else a report of a turn whose
103 knowledge was not searched, with the agent's own searches counted."""
104 if not values.get("knowledge_bases"):
105 return None
106 context = values.get("context") or {}
107 report = KnowledgeReport.read(context.get(KEY))
108 if report is None:
109 turn = categories.RetrievalTurn.read(context.get(categories.TURN_KEY))
110 mix = Mix.read(context.get(MIX_KEY))
111 report = KnowledgeReport(
112 query=str(values.get("retrieval_query") or values.get("input") or ""),
113 live=turn.live,
114 complexity=turn.complexity,
115 profile=mix.profile if mix is not None else "",
116 )
117 return report.with_tool_searches(
118 _new_hits(
119 [
120 getattr(m, "artifact", None)
121 for m in values.get("messages") or []
122 if getattr(m, "tool_call_id", None) is not None
123 and getattr(m, "name", None) == SEARCH_TOOL
124 ],
125 values.get("retrieval_citations") or [],
126 )
127 ).wire()
130def _packed(citations: Iterable[Any]) -> dict[tuple[str, str], list[tuple[int, int]]]:
131 """The chunks the turn's evidence holds, per (knowledge base, document):
132 each packed passage's span after neighbour expansion."""
133 spans: dict[tuple[str, str], list[tuple[int, int]]] = {}
134 for c in citations:
135 if not isinstance(c, Mapping) or not c.get("document_id"):
136 continue
137 key = (str(c.get("kb_id") or ""), str(c["document_id"]))
138 span = c.get("chunk_span")
139 index = c.get("chunk_index")
140 if isinstance(span, (list, tuple)) and len(span) == 2:
141 spans.setdefault(key, []).append((int(span[0]), int(span[1])))
142 elif isinstance(index, int):
143 spans.setdefault(key, []).append((index, index))
144 return spans
147def _new_hits(calls: list[Any], citations: Iterable[Any]) -> list[Any]:
148 """Each ``search_knowledge`` call's artifact with ``found`` counting the
149 passages new to the turn: none the evidence already held, none an
150 earlier call returned. An agent's own searches had been added whole, so
151 a source whose lane handed on 3 passages was kept 18 times over. An
152 artifact from before hits were listed is counted as it is."""
153 packed = _packed(citations)
154 seen: set[tuple[str, str, int]] = set()
156 def held(kb: str, doc: str, chunk: int) -> bool:
157 return any(lo <= chunk <= hi for lo, hi in packed.get((kb, doc), ()))
159 out: list[Any] = []
160 for call in calls:
161 if not isinstance(call, list):
162 out.append(call)
163 continue
164 entries = []
165 for entry in call:
166 hits = entry.get("hits") if isinstance(entry, dict) else None
167 if not isinstance(hits, list):
168 entries.append(entry)
169 continue
170 kb = str(entry.get("knowledge_id") or "")
171 new = 0
172 for hit in hits:
173 if not isinstance(hit, (list, tuple)) or len(hit) != 2:
174 continue
175 key = (kb, str(hit[0]), int(hit[1]) if isinstance(hit[1], int) else -1)
176 if key in seen or (key[1] and held(*key)):
177 continue
178 seen.add(key)
179 new += 1
180 entries.append({**entry, "found": new})
181 out.append(entries)
182 return out
185__all__ = ["KEY", "SEARCH_TOOL", "assemble", "from_bundle", "not_searched", "with_gaps"]