Coverage for app / services / agent_context / kinds.py: 99%
183 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""What an agent draws on, in eight kinds — each read from the feature that
2owns it (``docs/guides/knowledge.md#what-an-agent-draws-on``).
4Three are knowledge, by its repositories' kinds (Domain, Temporal,
5Reasoning). The other five are never repositories: each belongs to a
6feature of its own, and the panel says which, and where to change it.
8| Kind | What it is | Owned by |
9| --- | --- | --- |
10| Procedural | named workflows it runs | Skills |
11| Contextual | what this request brings with it | the conversation |
12| Episodic | what it remembers, and the record of what it did | memory, the decision record |
13| Operational | what it can do at run time | tools |
14| Normative | what it may and may not do | rules, its instructions |
16Each kind is one class, registered with :func:`register_kind` and read in
17registry order. A kind reads only what the agent's page already shows, and
18says ``unavailable`` when the part of it svc-ai holds cannot be read —
19never "none".
20"""
22from __future__ import annotations
24from abc import ABC, abstractmethod
25from collections import Counter
26from dataclasses import dataclass
27from enum import StrEnum
28from uuid import UUID
30from app.db.postgres.enums import RuleEnum
31from app.services.agent_context.inputs import AgentContextInputs
32from app.util import knowledge_categories
33from app.util.knowledge_categories import KnowledgeCategory
36class ContextState(StrEnum):
37 #: It has some.
38 present = "present"
39 #: It has none, and could.
40 missing = "missing"
41 #: What it has could not be read just now.
42 unavailable = "unavailable"
45class Owner(StrEnum):
46 """The feature a kind belongs to."""
48 knowledge = "knowledge"
49 skills = "skills"
50 conversation = "conversation"
51 memory = "memory"
52 tools = "tools"
53 governance = "governance"
56OWNER_LABELS: dict[str, str] = {
57 Owner.knowledge: "Knowledge",
58 Owner.skills: "Skills",
59 Owner.conversation: "The conversation",
60 Owner.memory: "Memory and the decision record",
61 Owner.tools: "Tools",
62 Owner.governance: "Rules and instructions",
63}
64if set(OWNER_LABELS) != set(Owner):
65 raise RuntimeError("Every owner of a kind needs a label")
68class PlaceKind(StrEnum):
69 #: A tab of the agent's own page.
70 tab = "tab"
71 #: Another page.
72 page = "page"
75@dataclass(frozen=True)
76class Place:
77 """Where to change it: a tab of the agent's page, or another page."""
79 kind: PlaceKind
80 target: str
83@dataclass(frozen=True)
84class Fact:
85 label: str
86 value: str
89@dataclass(frozen=True)
90class Suggestion:
91 """A built-in repository a missing kind could be given in one step."""
93 id: UUID
94 name: str
95 description: str
98@dataclass(frozen=True)
99class KindReading:
100 key: str
101 label: str
102 description: str
103 owner: Owner
104 state: ContextState
105 summary: str
106 facts: tuple[Fact, ...] = ()
107 place: Place | None = None
108 #: The knowledge category, for the three knowledge kinds.
109 category: str | None = None
110 #: For a missing kind of knowledge: built-ins of that kind it could be
111 #: granted, best match for the agent first.
112 suggestions: tuple[Suggestion, ...] = ()
115class ContextKind(ABC):
116 key: str
117 label: str
118 #: What it is, for the panel.
119 description: str
120 owner: Owner
121 place: Place | None = None
123 @abstractmethod
124 def read(self, inputs: AgentContextInputs) -> KindReading: ...
126 def reading(
127 self,
128 state: ContextState,
129 summary: str,
130 *facts: Fact,
131 category: str | None = None,
132 suggestions: tuple[Suggestion, ...] = (),
133 ) -> KindReading:
134 return KindReading(
135 key=self.key,
136 label=self.label,
137 description=self.description,
138 owner=self.owner,
139 state=state,
140 summary=summary,
141 facts=tuple(facts),
142 place=self.place,
143 category=category,
144 suggestions=suggestions,
145 )
148_REGISTRY: dict[str, ContextKind] = {}
151def register_kind(cls: type[ContextKind]) -> type[ContextKind]:
152 instance = cls()
153 if instance.key in _REGISTRY:
154 raise ValueError(f"Agent context kind {instance.key!r} registered twice")
155 _REGISTRY[instance.key] = instance
156 return cls
159def kinds() -> list[ContextKind]:
160 return list(_REGISTRY.values())
163def catalogue() -> list[dict[str, str]]:
164 return [
165 {
166 "key": k.key,
167 "label": k.label,
168 "description": k.description,
169 "owner": k.owner.value,
170 "owner_label": OWNER_LABELS[k.owner],
171 }
172 for k in kinds()
173 ]
176def _plural(n: int, one: str, many: str | None = None) -> str:
177 return f"{n:,} {one if n == 1 else (many or one + 's')}"
180def _names(names: list[str], limit: int = 3) -> str:
181 shown = ", ".join(names[:limit])
182 return shown + (f" +{len(names) - limit}" if len(names) > limit else "")
185KNOWLEDGE_TAB = Place(PlaceKind.tab, "knowledge")
187#: Built-ins a missing kind names at most.
188MAX_SUGGESTIONS = 3
191class _Knowledge(ContextKind):
192 """One kind of knowledge, by the kind of the repositories granted."""
194 category: KnowledgeCategory
195 owner = Owner.knowledge
196 place = KNOWLEDGE_TAB
198 def read(self, inputs: AgentContextInputs) -> KindReading:
199 granted = inputs.of_kind(self.category)
200 if not granted:
201 return self.reading(
202 ContextState.missing,
203 "None granted.",
204 category=self.category.value,
205 suggestions=self.suggestions(inputs),
206 )
207 sources = sum(r.sources for r in granted)
208 return self.reading(
209 ContextState.present,
210 f"{_plural(len(granted), 'repository', 'repositories')}, "
211 f"{_plural(sources, 'source')}: {_names([r.name for r in granted])}.",
212 category=self.category.value,
213 )
215 def suggestions(self, inputs: AgentContextInputs) -> tuple[Suggestion, ...]:
216 """The built-ins of this kind it could be granted, those whose topics
217 its name, description and instructions share first."""
218 from app.services.system_resources import knowledge as built_in
220 text = " ".join(
221 str(getattr(inputs.agent, field, None) or "")
222 for field in ("name", "description", "system_prompt")
223 )
224 granted = [r.id for r in inputs.repositories]
225 return tuple(
226 Suggestion(
227 id=entry.id,
228 name=entry.name,
229 description=entry.repository.description,
230 )
231 for entry in built_in.suggested(self.category, text, exclude=granted)[
232 :MAX_SUGGESTIONS
233 ]
234 )
237@register_kind
238class DomainKnowledge(_Knowledge):
239 key = "domain"
240 category = KnowledgeCategory.domain
241 label = knowledge_categories.LABELS[KnowledgeCategory.domain]
242 description = knowledge_categories.USE[KnowledgeCategory.domain]
245@register_kind
246class TemporalKnowledge(_Knowledge):
247 key = "temporal"
248 category = KnowledgeCategory.temporal
249 label = knowledge_categories.LABELS[KnowledgeCategory.temporal]
250 description = knowledge_categories.USE[KnowledgeCategory.temporal]
253@register_kind
254class ReasoningKnowledge(_Knowledge):
255 key = "reasoning"
256 category = KnowledgeCategory.reasoning
257 label = knowledge_categories.LABELS[KnowledgeCategory.reasoning]
258 description = knowledge_categories.USE[KnowledgeCategory.reasoning]
261@register_kind
262class Procedural(ContextKind):
263 key = "procedural"
264 label = "Procedural"
265 description = "The named workflows it runs: skills, granted as skillsets."
266 owner = Owner.skills
267 place = Place(PlaceKind.tab, "skillsets")
269 def read(self, inputs: AgentContextInputs) -> KindReading:
270 skills = inputs.skills
271 if not skills:
272 return self.reading(
273 ContextState.missing,
274 "No skills: it answers each request itself.",
275 )
276 return self.reading(
277 ContextState.present,
278 f"{_plural(len(skills), 'skill')} in "
279 f"{_plural(len(inputs.skillsets), 'skillset')}; it answers through "
280 f"{skills[0].name}.",
281 Fact("Skillsets", _names(inputs.skillsets)),
282 )
285@register_kind
286class Contextual(ContextKind):
287 key = "contextual"
288 label = "Contextual"
289 description = (
290 "What each request brings with it: the conversation so far and the "
291 "documents attached in it."
292 )
293 owner = Owner.conversation
295 def read(self, inputs: AgentContextInputs) -> KindReading:
296 asks = bool(getattr(inputs.agent, "clarify_scope", False))
297 return self.reading(
298 ContextState.present,
299 "Reads the conversation and the documents attached in it"
300 + ("; asks first when a request is unclear." if asks else "."),
301 Fact(
302 "Clarifying questions",
303 "Asks before starting" if asks else "Only mid-task, when it must",
304 ),
305 )
308@register_kind
309class Episodic(ContextKind):
310 key = "episodic"
311 label = "Episodic"
312 description = (
313 "What it remembers of earlier conversations with you, and the record "
314 "of what it did on each answer."
315 )
316 owner = Owner.memory
317 place = Place(PlaceKind.tab, "memory")
319 def read(self, inputs: AgentContextInputs) -> KindReading:
320 record = Fact("Decision record", "Every answer")
321 remembered = inputs.memories
322 if remembered is None:
323 return self.reading(
324 ContextState.unavailable,
325 "What it remembers could not be read just now.",
326 record,
327 )
328 if remembered == 0:
329 return self.reading(
330 ContextState.missing,
331 "Nothing remembered of you yet: it keeps what matters from your "
332 "conversations.",
333 record,
334 )
335 return self.reading(
336 ContextState.present,
337 f"Remembers {_plural(remembered, 'thing')} from your conversations.",
338 record,
339 )
342def _tool_name(name: str) -> str:
343 return name.replace("_", " ").capitalize()
346@register_kind
347class Operational(ContextKind):
348 key = "operational"
349 label = "Operational"
350 description = (
351 "What it can do at run time: search the web, read pages, make documents."
352 )
353 owner = Owner.tools
354 place = Place(PlaceKind.tab, "toolkits")
356 def read(self, inputs: AgentContextInputs) -> KindReading:
357 tools = inputs.tools
358 if tools is None:
359 return self.reading(
360 ContextState.unavailable,
361 "CHAIN-R's built-in tools; the list could not be read just now.",
362 )
363 if not tools:
364 return self.reading(ContextState.missing, "No tools.")
365 return self.reading(
366 ContextState.present,
367 f"{_plural(len(tools), 'built-in tool')}: "
368 f"{_names([_tool_name(t) for t in tools], 4)}.",
369 )
372@register_kind
373class Normative(ContextKind):
374 key = "normative"
375 label = "Normative"
376 description = (
377 "What it may and may not do: the rules in force for it here, and its "
378 "own instructions."
379 )
380 owner = Owner.governance
381 place = Place(PlaceKind.page, "rules")
383 def read(self, inputs: AgentContextInputs) -> KindReading:
384 own = bool((getattr(inputs.agent, "system_prompt", None) or "").strip())
385 instructions = Fact("Instructions", "Its own" if own else "CHAIN-R's default")
386 rules = inputs.rules
387 if not rules:
388 return self.reading(
389 ContextState.missing,
390 "No rules govern it here: its instructions are all it follows.",
391 instructions,
392 )
393 from app.services.rules import layers as rule_layers
395 by_layer = Counter(RuleEnum.Layer(r.layer) for r in rules)
396 layers = ", ".join(
397 f"{by_layer[layer]} {rule_layers.get(layer).label}"
398 for layer in RuleEnum.Layer
399 if by_layer[layer]
400 )
401 return self.reading(
402 ContextState.present,
403 f"{_plural(len(rules), 'rule')} govern{'s' if len(rules) == 1 else ''} "
404 f"it here: {layers}.",
405 instructions,
406 )
409def read_all(inputs: AgentContextInputs) -> list[KindReading]:
410 """Every kind, in registry order."""
411 return [kind.read(inputs) for kind in kinds()]
414__all__ = [
415 "OWNER_LABELS",
416 "ContextKind",
417 "ContextState",
418 "KindReading",
419 "Owner",
420 "Place",
421 "PlaceKind",
422 "Suggestion",
423 "catalogue",
424 "kinds",
425 "read_all",
426 "register_kind",
427]