Coverage for app / services / llm_paths.py: 100%
23 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"""
2Every way svc-core makes a language model do work — and where it pays for it.
4The platform's cost claim is that *every* invocation of a model is on the
5usage ledger, priced, and attributed to the resource that caused it. That is
6only true if nobody adds a path that forgets. So the paths are declared here,
7one entry each, and ``tests/test_llm_paths.py`` holds the codebase to the
8list:
10* every svc-ai endpoint ``ai_client`` calls is classified — as a model call
11 here, or as not one in ``NON_LLM_ENDPOINTS`` — so a new endpoint cannot
12 arrive unclassified;
13* every ``ai_client`` function that reaches a model feeds the usage capture
14 (``_capture`` / ``_capture_summary``);
15* every path's ledgering module really writes the ledger with its source;
16* every source and execution type is documented in
17 ``docs/guides/cost-monitoring.md``.
19Adding a path is one entry here, a ``usage_capture()`` around the call, and a
20``record_usage`` / ``record_measured`` with a ``UsageEnum.Source``.
21"""
23from __future__ import annotations
25from dataclasses import dataclass
27from app.db.postgres.enums import UsageEnum
29Source = UsageEnum.Source
32@dataclass(frozen=True)
33class LLMPath:
34 #: Short name, used in the docs table.
35 key: str
36 #: What the user did that caused it.
37 description: str
38 #: ``ai_client`` function(s) that make the call.
39 clients: tuple[str, ...]
40 #: svc-ai endpoint(s) those functions reach.
41 endpoints: tuple[str, ...]
42 #: ``governance_usage.execution_type`` of the row.
43 execution_type: str
44 #: What the spend is attributed to.
45 source: UsageEnum.Source
46 #: Module(s), relative to ``app/``, that write the ledger row.
47 ledgered_in: tuple[str, ...]
48 #: Module(s), relative to ``app/``, where the workspace's budgets are
49 #: asked before the call (cost-control plan A1.5): a turn's policy rules
50 #: (``rule_engine.evaluate_input``), or the budgets alone for work that
51 #: is not a turn (``budgets.gate.check``). A used-up budget refuses every
52 #: path; the one call that never asks is the rebuild after an
53 #: embedding-model change (``knowledge/reindex.py``), which restores
54 #: search a person already had.
55 gated_in: tuple[str, ...] = ()
58LLM_PATHS: tuple[LLMPath, ...] = (
59 LLMPath(
60 key="agent_turn",
61 description="A chat turn with an agent, streamed or not, including "
62 "CHAINR Bot and an agent whose body is a skill; resumes after a pause "
63 "count toward the same turn.",
64 clients=("execute_agent_request", "astream_execute"),
65 endpoints=(
66 "/agents/execute",
67 "/agents/execute/stream",
68 "/agents/execute/stream/resume",
69 ),
70 execution_type="agent",
71 source=Source.agent,
72 ledgered_in=(
73 "router/app/agents/transformers.py",
74 "router/app/agents/router.py",
75 ),
76 gated_in=(
77 "router/app/agents/router.py",
78 "services/hitl.py",
79 ),
80 ),
81 LLMPath(
82 key="model_prompt",
83 description="A direct prompt to a model from its chat page.",
84 clients=("invoke_model",),
85 endpoints=("/agents/execute",),
86 execution_type="model",
87 source=Source.model,
88 ledgered_in=("router/app/models/router.py",),
89 gated_in=("router/app/models/router.py",),
90 ),
91 LLMPath(
92 key="skill_run",
93 description="A standalone skill run, each segment of it — the part "
94 "before a pause and each part after a resume.",
95 clients=("run_skill",),
96 endpoints=("/agents/execute",),
97 execution_type="skill",
98 source=Source.skill,
99 ledgered_in=("services/skill_runs/runner.py",),
100 gated_in=(
101 "services/skill_runs/runner.py",
102 "services/hitl.py",
103 ),
104 ),
105 LLMPath(
106 key="evaluation",
107 description="An evaluation or Quick try: every cell, the LLM judge "
108 "grading them, and the prompt optimiser's proposals and candidate "
109 "scoring.",
110 clients=("invoke_model", "invoke_agent"),
111 endpoints=("/agents/execute",),
112 execution_type="evaluation",
113 source=Source.experiment,
114 ledgered_in=(
115 "services/evaluation/runner.py",
116 "services/evaluation/optimiser.py",
117 ),
118 gated_in=("services/evaluation/targets.py",),
119 ),
120 LLMPath(
121 key="dashboard_tile",
122 description="A dashboard automation tile refreshing, on view, on "
123 "demand or on the scheduler.",
124 clients=("invoke_model", "invoke_agent"),
125 endpoints=("/agents/execute",),
126 execution_type="dashboard",
127 source=Source.dashboard,
128 ledgered_in=("services/dashboards/widgets.py",),
129 gated_in=("services/evaluation/targets.py",),
130 ),
131 LLMPath(
132 key="generation",
133 description="A generative setup flow — agent, skill, skillset, "
134 "toolkit, knowledge, rule or dashboard — attributed to its "
135 "GenerationRun.",
136 clients=(
137 "generate_agent_config",
138 "generate_skill_config",
139 "generate_skillset_config",
140 "generate_toolkit_config",
141 "generate_knowledge_config",
142 # Knowledge setup's search plan, in the same run, and the
143 # matching of what it found to given sources (source discovery).
144 "plan_knowledge_discovery",
145 "assign_knowledge_sources",
146 "generate_rules_config",
147 "invoke_model",
148 ),
149 endpoints=(
150 "/agents/generate-config",
151 "/skills/generate-config",
152 "/skillsets/generate-config",
153 "/toolkits/generate-config",
154 "/knowledge/generate-config",
155 "/knowledge/discover/plan",
156 "/knowledge/discover/assign",
157 "/rules/generate-config",
158 "/agents/execute",
159 ),
160 execution_type="generation",
161 source=Source.generation,
162 ledgered_in=("services/generation.py",),
163 gated_in=("services/generation.py",),
164 ),
165 LLMPath(
166 key="knowledge_search",
167 description="Searching a knowledge base or repository from its page.",
168 clients=("retrieve_knowledge",),
169 endpoints=("/knowledge/retrieve",),
170 execution_type="retrieval",
171 source=Source.knowledge,
172 ledgered_in=("router/app/knowledge/router.py",),
173 gated_in=("router/app/knowledge/router.py",),
174 ),
175 LLMPath(
176 key="repository_search",
177 description="Searching across a knowledge repository.",
178 clients=("retrieve_knowledge",),
179 endpoints=("/knowledge/retrieve",),
180 execution_type="retrieval",
181 source=Source.knowledge_repository,
182 # The endpoint names the source; the shared search helper writes it.
183 ledgered_in=(
184 "router/app/repositories/router.py",
185 "router/app/knowledge/router.py",
186 ),
187 gated_in=("router/app/knowledge/router.py",),
188 ),
189 LLMPath(
190 key="knowledge_indexing",
191 description="Embedding a knowledge base's content: each uploaded "
192 "document (one row per document) and each website crawl (one row per "
193 "crawl), and the rebuild that re-embeds them when the embedding model "
194 "changes (services/knowledge/reindex.py).",
195 clients=("embed_texts",),
196 endpoints=("/knowledge/embed",),
197 execution_type="embedding",
198 source=Source.knowledge,
199 ledgered_in=(
200 "router/app/knowledge/router.py",
201 "services/knowledge/web_crawl.py",
202 ),
203 gated_in=(
204 "router/app/knowledge/router.py",
205 "services/knowledge/web_crawl.py",
206 ),
207 ),
208 LLMPath(
209 key="swarm",
210 description="A swarm run: every task its agents did — the lead's "
211 "plan, each piece of work, the review and the answer — each its own "
212 "governed agent turn, ledgered as it finishes.",
213 clients=("execute_agent_request",),
214 endpoints=("/agents/execute",),
215 execution_type="swarm",
216 source=Source.swarm,
217 ledgered_in=("services/swarms/tasks.py",),
218 # Each task's policy rules (the evaluation targets'), and the
219 # budgets alone before a run is dispatched.
220 gated_in=("services/evaluation/targets.py", "services/swarms/engine.py"),
221 ),
222 LLMPath(
223 key="simulation",
224 description="A simulation run (out of the navigation, reachable by URL).",
225 clients=("run_simulation",),
226 endpoints=("/simulate/run",),
227 execution_type="simulation",
228 source=Source.simulation,
229 ledgered_in=("router/app/simulations/router.py",),
230 gated_in=("router/app/simulations/router.py",),
231 ),
232)
234#: svc-ai endpoints ``ai_client`` calls that never reach a model: registry
235#: reads, catalogue lookups, stats, memory, MCP probes, page fetches.
236NON_LLM_ENDPOINTS: frozenset[str] = frozenset(
237 {
238 # svc-ai's code fingerprint: the platform benchmark re-runs CHAINR
239 # Bot only when it changes.
240 "/health",
241 # The deployment's spending ceiling: the benchmark reads it before a
242 # run, so it never spends what people need.
243 "/spend",
244 # Which embedding model is active: collections are built at its size.
245 "/knowledge/embedding",
246 "/models/{model_id}",
247 "/models",
248 "/models/providers",
249 "/models/lookup",
250 "/models/validate",
251 "/mcp/servers/templates",
252 "/mcp/servers/probe",
253 "/tools/available",
254 "/skills/available",
255 "/skills/agents",
256 "/skills/agents/{name}",
257 "/knowledge/node-types",
258 "/knowledge/web/fetch",
259 "/knowledge/web/favicon",
260 # A document downloaded for a file source: a fetch, no model.
261 "/knowledge/web/document",
262 # Knowledge setup's searches and the check of what they found: web
263 # search and probes, no model (the searches are recorded on svc-ai
264 # as web_search tool invocations, unpriced as an agent's are).
265 "/knowledge/discover/search",
266 "/knowledge/discover/check",
267 "/stats/usage",
268 "/stats/traces",
269 "/stats/invocations",
270 # The model and tool calls behind one turn, for its decision record.
271 "/stats/turns/{core_invocation_id}",
272 "/stats/web-search-domains",
273 # One day's metered calls, for the daily economics export.
274 "/stats/meter",
275 # A set of turns' calls summed by step: where their tokens went.
276 "/stats/steps",
277 "/memory",
278 "/memory/summary",
279 "/memory/{agent_id}",
280 "/memory/{agent_id}/{memory_id}",
281 "/agents/execute/threads/{thread_id}",
282 # Layout only: a stored document rendered to PDF, no model involved.
283 "/documents/pdf",
284 }
285)
288def llm_endpoints() -> frozenset[str]:
289 return frozenset(e for path in LLM_PATHS for e in path.endpoints)
292def llm_clients() -> frozenset[str]:
293 return frozenset(c for path in LLM_PATHS for c in path.clients)
296ExecutionType = UsageEnum.ExecutionType
298#: Execution types as the stats breakdown and the rule builder label them —
299#: one per ``UsageEnum.ExecutionType``, held to it by ``tests/test_llm_paths.py``.
300EXECUTION_TYPE_LABELS: dict[str, str] = {
301 ExecutionType.agent: "Agent turn",
302 ExecutionType.model: "Direct prompt",
303 ExecutionType.skill: "Skill run",
304 ExecutionType.evaluation: "Evaluation run",
305 ExecutionType.dashboard: "Dashboard tile",
306 ExecutionType.generation: "Generation",
307 ExecutionType.retrieval: "Knowledge search",
308 ExecutionType.embedding: "Indexing",
309 ExecutionType.simulation: "Simulation",
310 ExecutionType.swarm: "Swarm task",
311}
313#: Sources as a cost card or breakdown labels them.
314SOURCE_LABELS: dict[str, str] = {
315 Source.agent: "Agents",
316 Source.model: "Models",
317 Source.skill: "Skills",
318 Source.dashboard: "Dashboards",
319 Source.experiment: "Evaluations",
320 Source.generation: "Generation",
321 Source.knowledge: "Knowledge",
322 Source.knowledge_repository: "Repositories",
323 Source.simulation: "Simulations",
324 Source.swarm: "Swarms",
325}