Coverage for app / util / knowledge_report.py: 99%
86 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 a turn's knowledge did, as a record: the report svc-ai keeps beside
2an answer, which svc-core stores as the retrieval record.
4The citations record says which sources an answer cited (*use*). It cannot
5say what the knowledge failed to provide: a search that found nothing that
6bore on the request, a gap the quality check named that the knowledge did
7not hold, a file the person named that no source has, or a turn that went to
8the web while the agent's own knowledge was never searched. Those are what
9say which knowledge to add, and what a source retrieved but never cited is
10for. This report carries them: one per turn of an agent with knowledge, the
11turn's searches counted per source.
13svc-ai writes it (``app/knowledge/turn_report.py``), from the retrieval
14node's counts and the agent's own ``search_knowledge`` calls, and sends it
15on the stream's ``done`` frame and the batch response's context; svc-core
16stores it (``services/knowledge/retrievals.py``). The two services carry
17this file byte for byte (``tools/test_shared_modules.py``). A report from a
18later version reads as far as it can: unknown fields are ignored, and one
19that does not validate is unreadable (None), never a guess.
21It holds the request as retrieval searched for it, and what the quality
22check found missing: a person's words, so svc-core redacts them as the
23input was before it stores them, never keeps them for a withheld answer,
24and deletes them with the message. It holds no passage, no document name
25and no URL.
26"""
28from __future__ import annotations
30from collections.abc import Callable, Iterable
31from typing import Any
33from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator
35#: The report's shape. A reader keeps what it understands of a later one.
36VERSION = 1
38#: The longest request a report keeps.
39MAX_QUERY_CHARS = 500
40#: The gaps, and the files named and not found, a report keeps at most, and
41#: the longest of each.
42MAX_ITEMS = 5
43MAX_ITEM_CHARS = 200
46def _clip(text: Any, limit: int) -> str:
47 return " ".join(str(text or "").split())[:limit]
50def _items(values: Any) -> list[str]:
51 if not isinstance(values, list | tuple):
52 return []
53 clipped = [_clip(v, MAX_ITEM_CHARS) for v in values]
54 return [v for v in clipped if v][:MAX_ITEMS]
57class _Record(BaseModel):
58 model_config = ConfigDict(extra="ignore", frozen=True)
61class SourceUse(_Record):
62 """What one knowledge source gave the turn."""
64 knowledge_id: str
65 #: Its kind (``app/util/knowledge_categories.py``), as it was searched.
66 category: str = "domain"
67 #: Passages (or graph facts) its search found.
68 found: int = 0
69 #: Of those, packed into what the agent was given.
70 kept: int = 0
71 #: Found, and ruled out by the relevance judge.
72 ruled_out: int = 0
73 #: Found, and left out by the turn's window (dated knowledge).
74 out_of_window: int = 0
75 #: Times the agent searched it itself (``search_knowledge``).
76 tool_searches: int = 0
77 #: Its role in the turn's mix (``primary``, ``supporting``, ``method``);
78 #: empty for a source the agent searched on its own, or a report from
79 #: before the mix.
80 role: str = ""
83class KnowledgeReport(_Record):
84 """One turn of an agent with knowledge: what was asked of its
85 knowledge, what each source gave, and what it lacked."""
87 version: int = VERSION
88 #: The request as retrieval searched for it (triage's standalone form).
89 query: str = ""
90 #: Triage judged that the request needs current information.
91 live: bool = False
92 #: Triage's grade of the request; None when triage failed.
93 complexity: str | None = None
94 #: The input profile the turn's mix was read from (``lookup``,
95 #: ``current``, ``analysis``…); empty before the mix.
96 profile: str = ""
97 #: Internal retrieval searched the knowledge.
98 searched: bool = False
99 #: It found passages, and the relevance judge ruled out every one.
100 nothing_relevant: bool = False
101 #: What the quality check found missing that the knowledge did not hold
102 #: (corrective retrieval searched for it and found nothing).
103 gaps: list[str] = Field(default_factory=list)
104 #: Files the request named that no knowledge base holds.
105 unresolved: list[str] = Field(default_factory=list)
106 #: The knowledge bases this turn did not search, by id (a framework on
107 #: a simple request, the rest on a request about what is current).
108 scoped_out: list[str] = Field(default_factory=list)
109 sources: list[SourceUse] = Field(default_factory=list)
111 @field_validator("query", mode="before")
112 @classmethod
113 def _bounded_query(cls, value: Any) -> str:
114 return _clip(value, MAX_QUERY_CHARS)
116 @field_validator("gaps", "unresolved", mode="before")
117 @classmethod
118 def _bounded_items(cls, value: Any) -> list[str]:
119 return _items(value)
121 @classmethod
122 def read(cls, value: Any) -> KnowledgeReport | None:
123 """``value`` as a report, or None when it is not one."""
124 if isinstance(value, cls):
125 return value
126 if not isinstance(value, dict):
127 return None
128 try:
129 return cls.model_validate(value)
130 except ValidationError:
131 return None
133 @property
134 def kept(self) -> int:
135 """Passages the agent was given, from every source."""
136 return sum(s.kept for s in self.sources)
138 @property
139 def came_up_short(self) -> bool:
140 """The knowledge was searched and did not serve the request: nothing
141 bore on it, nothing was kept, or the quality check named a gap it
142 did not hold."""
143 return self.searched and (
144 self.nothing_relevant or self.kept == 0 or bool(self.gaps)
145 )
147 def with_tool_searches(self, searches: Iterable[Any]) -> KnowledgeReport:
148 """This report with the agent's own searches counted: each of
149 ``searches`` is one ``search_knowledge`` call's artifact (a list of
150 ``{knowledge_id, category, found}``), unreadable ones skipped. What a
151 search found went to the agent as it was, so it is kept too; and a
152 turn that searched this way searched its knowledge."""
153 by_id = {s.knowledge_id: s for s in self.sources}
154 order = [s.knowledge_id for s in self.sources]
155 counted = False
156 for call in searches:
157 for entry in call if isinstance(call, list) else ():
158 if not isinstance(entry, dict) or not entry.get("knowledge_id"):
159 continue
160 kid = str(entry["knowledge_id"])
161 current = by_id.get(kid) or SourceUse(
162 knowledge_id=kid, category=str(entry.get("category") or "domain")
163 )
164 found = entry.get("found")
165 found = found if isinstance(found, int) and found > 0 else 0
166 by_id[kid] = current.model_copy(
167 update={
168 "found": current.found + found,
169 "kept": current.kept + found,
170 "tool_searches": current.tool_searches + 1,
171 }
172 )
173 counted = True
174 if kid not in order:
175 order.append(kid)
176 return self.model_copy(
177 update={
178 "sources": [by_id[k] for k in order],
179 "searched": self.searched or counted,
180 }
181 )
183 def redacted(self, redact: Callable[[str], str]) -> KnowledgeReport:
184 """This report with the person's words passed through ``redact``:
185 the turn's redaction, as the request was."""
186 return self.model_copy(
187 update={
188 "query": redact(self.query) if self.query else "",
189 "gaps": [redact(g) for g in self.gaps],
190 "unresolved": [redact(u) for u in self.unresolved],
191 }
192 )
194 def without_text(self) -> KnowledgeReport:
195 """This report keeping none of the person's words: for an answer an
196 Output rule withheld, which keeps nothing of what the run read."""
197 return self.model_copy(update={"query": "", "gaps": [], "unresolved": []})
199 def wire(self) -> dict[str, Any]:
200 """This report as JSON travels: a frame, a response's context."""
201 return self.model_dump(mode="json")
204__all__ = [
205 "MAX_ITEMS",
206 "MAX_ITEM_CHARS",
207 "MAX_QUERY_CHARS",
208 "VERSION",
209 "KnowledgeReport",
210 "SourceUse",
211]