Coverage for app / router / app / stats / router.py: 96%
269 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
1import logging
2from datetime import datetime
3from typing import Literal
4from uuid import UUID
6from fastapi import APIRouter, Depends, HTTPException, Query, status
7from pydantic import BaseModel
8from sqlalchemy.exc import SQLAlchemyError
9from sqlalchemy.orm import Session
11from app.dependency.user.context import get_current_user
12from app.dependency.base import get_db
13from app.db.postgres.models import User
14from app.services.ai_client import (
15 AIServiceError,
16 get_trace_stats,
17 get_usage_stats,
18 get_web_search_domain_stats,
19 list_llm_invocations,
20)
21from app.services.stats import breakdown as breakdown_service
22from app.services.stats import resource_cost as resource_cost_service
23from app.services.stats import step_usage as step_usage_service
24from app.util.time import UTCDateTime
26logger = logging.getLogger(__name__)
28stats_router = APIRouter(prefix="/stats", tags=["App - Stats"])
31class UsagePeriod(BaseModel):
32 input_tokens: int
33 output_tokens: int
34 total_tokens: int
35 invocation_count: int
36 error_count: int
37 avg_latency_ms: float | None
38 estimated_cost_usd: float | None
41class UsageStatsResponse(BaseModel):
42 this_month: UsagePeriod
43 all_time: UsagePeriod
46class TracePeriod(BaseModel):
47 llm_invocation_count: int
48 tool_invocation_count: int
49 avg_llm_per_conversation: float | None
50 stddev_llm_per_conversation: float | None
51 avg_tool_per_conversation: float | None
52 stddev_tool_per_conversation: float | None
55class TraceStatsResponse(BaseModel):
56 this_month: TracePeriod
57 all_time: TracePeriod
60class WebSearchDomainStat(BaseModel):
61 domain: str
62 visit_count: int
63 avg_trust_score: float | None
64 last_visited: UTCDateTime | None
67class WebSearchDomainStatsResponse(BaseModel):
68 domains: list[WebSearchDomainStat]
71class LLMInvocationCallRecord(BaseModel):
72 """One model call within an invocation — the model that actually did it.
74 Mirrors svc-ai's ``InvocationCallRecord``; every field is declared so the
75 response model passes them all through rather than dropping them.
76 """
78 sequence: int
79 provider: str
80 #: The exact model identifier the call was made with.
81 model_name: str
82 #: svc-ai's catalogue name for it, when the catalogue lists it.
83 model_display_name: str | None = None
84 model_id: UUID | None = None
85 #: ``chat`` or ``embedding``.
86 kind: str = "chat"
87 #: The graph node that made the call; None outside a graph.
88 node: str | None = None
89 #: What the node was doing (svc-ai ``metering.step``: a structured
90 #: call's purpose, or ``respond`` / ``continuation`` …) and which pass of
91 #: the run it was on (0 first; one more per revision). None when
92 #: unlabelled, as every call before svc-ai migration 27 is.
93 step: str | None = None
94 pass_index: int | None = None
95 #: Every prompt token and every generated token (reasoning included);
96 #: the cache and reasoning counts are parts of them, not additions.
97 prompt_tokens: int = 0
98 completion_tokens: int = 0
99 cache_read_tokens: int = 0
100 cache_write_tokens: int = 0
101 reasoning_tokens: int = 0
102 latency_ms: int | None = None
103 status: str
104 error_detail: str | None = None
105 #: None when the call could not be priced (or failed) — never 0 for that.
106 estimated_cost_usd: float | None = None
107 #: The rates behind the cost, whether the long-context tier applied — or
108 #: ``unpriced_reason``.
109 pricing: dict | None = None
112class LLMInvocationRecord(BaseModel):
113 id: UUID
114 created_at: UTCDateTime | None = None
115 purpose: str | None = None
116 conversation_id: UUID | None = None
117 #: The model the invocation asked for (or the one model its calls used).
118 #: None only when it named none and its calls used several — ``calls``
119 #: then names each — or for a trace recorded before calls were.
120 provider: str | None = None
121 model_name: str | None = None
122 model_display_name: str | None = None
123 model_id: UUID | None = None
124 #: Every model call it made, in order; empty for older traces.
125 calls: list[LLMInvocationCallRecord] = []
126 prompt_tokens: int = 0
127 completion_tokens: int = 0
128 total_tokens: int = 0
129 latency_ms: int | None = None
130 status: str
131 error_detail: str | None = None
132 estimated_cost_usd: float | None = None
133 request_config: dict | None = None
134 output_preview: str | None = None
137# --------------------------------------------------------------------------- #
138# Dimensioned breakdowns
139#
140# The schemas below describe the ledger-backed side of this router. The
141# svc-ai proxies answer for the caller's work in one workspace, undimensioned;
142# these answer per agent, model, project or organisation, from svc-core's own
143# governance usage ledger. See app/services/stats/breakdown.py for why the two live in
144# different services.
145# --------------------------------------------------------------------------- #
148class BreakdownBucket(BaseModel):
149 key: str
150 label: str
151 value: float | None
152 share: float | None = None
153 missing: bool = False
156class BreakdownResponse(BaseModel):
157 metric: str
158 source: str
159 dimension: str | None
160 period: str
161 since: UTCDateTime | None
162 until: UTCDateTime
163 unit: str
164 additive: bool
165 zero_is_meaningful: bool
166 total: float | None
167 bucket_count: int
168 buckets: list[BreakdownBucket]
171class CostSlice(BaseModel):
172 key: str | None
173 label: str
174 invocations: int
175 cost_usd: float | None
178class CostDay(BaseModel):
179 date: str
180 invocations: int
181 cost_usd: float | None
184class ResourceCostResponse(BaseModel):
185 source_type: str | None
186 source_id: str | None
187 #: A ``services/stats/periods.py`` key, or ``custom`` for a range.
188 period: str
189 period_label: str
190 #: True when it counts only the caller's own work ("your spend"), false
191 #: when everyone's in the workspace ("workspace spend").
192 mine: bool = True
193 since: UTCDateTime | None
194 until: UTCDateTime
195 invocations: int
196 failed_invocations: int
197 #: None only when there was spend and none of it could be priced.
198 cost_usd: float | None
199 #: Invocations with no cost at all, and metered calls svc-ai could not
200 #: price. Either above zero makes ``cost_usd`` a lower bound.
201 unpriced_invocations: int
202 llm_calls: int
203 unpriced_calls: int
204 input_tokens: int
205 output_tokens: int
206 last_invocation_at: UTCDateTime | None
207 by_execution_type: list[CostSlice]
208 by_source: list[CostSlice]
209 daily: list[CostDay]
212class StepUsageRow(BaseModel):
213 """What one step of the pipeline cost across the turns read."""
215 #: The graph node that made the calls (``__evaluator__``, a skill
216 #: node's id …); None outside a graph.
217 node: str | None
218 #: What the node was doing (``retrieval.reranker``, ``respond`` …); None
219 #: on calls nothing labelled, every one before svc-ai migration 27.
220 step: str | None
221 #: 0 the first pass, 1 the first revision after the quality check, …
222 pass_index: int | None
223 #: ``chat`` or ``embedding``.
224 kind: str
225 calls: int
226 failed_calls: int
227 unpriced_calls: int
228 prompt_tokens: int
229 completion_tokens: int
230 cache_read_tokens: int
231 cache_write_tokens: int
232 reasoning_tokens: int
233 cost_usd: float
234 cache_savings_usd: float
237class StepUsageResponse(BaseModel):
238 source_type: str
239 source_id: str | None
240 period: str
241 period_label: str
242 since: UTCDateTime | None
243 until: UTCDateTime
244 #: The turns svc-ai was asked about: the newest in the period, at most
245 #: ``step_usage.MAX_TURNS``…
246 turns_asked: int
247 #: …of this many.
248 turns_in_period: int
249 #: How many of them svc-ai has calls for (one from before turns were
250 #: named, or that made no call, is not among them).
251 turns: int
252 #: ``unavailable`` when svc-ai could not be asked — not an empty answer.
253 status: Literal["recorded", "unavailable"]
254 steps: list[StepUsageRow]
257class CatalogueEntry(BaseModel):
258 key: str
259 label: str
260 description: str = ""
263class MetricEntry(CatalogueEntry):
264 unit: str
265 additive: bool
266 zero_is_meaningful: bool
267 #: Which record this is counted from. The query is built from the metric
268 #: alone, so a client never states the source separately — it reads this
269 #: to group the picker and to know which dimensions are offerable.
270 source: str
273class DimensionEntry(CatalogueEntry):
274 plural: str = ""
275 resolves_names: bool = True
276 #: The sources this axis can slice. More than one where the same column
277 #: exists on both — a governance event and its redaction expansion share
278 #: every column, so "by rule" is one axis, not two.
279 sources: list[str]
282class StatsCatalogueResponse(BaseModel):
283 sources: list[CatalogueEntry]
284 metrics: list[MetricEntry]
285 dimensions: list[DimensionEntry]
286 periods: list[CatalogueEntry]
287 max_buckets: int
290@stats_router.get("")
291def stats_index(current_user: User = Depends(get_current_user)):
292 return {
293 "endpoints": [
294 "usage",
295 "traces",
296 "invocations",
297 "web-search-domains",
298 "breakdown",
299 "catalogue",
300 ]
301 }
304@stats_router.get("/catalogue", response_model=StatsCatalogueResponse)
305def stats_catalogue(current_user: User = Depends(get_current_user)):
306 """What can be measured, what it can be sliced by, and over what window.
308 Served as one document, and served from the registries rather than
309 restated here, so a metric added as a class appears in the widget editor's
310 pickers without a frontend release — the same contract the rule builder's
311 catalogue and the widget-type catalogue already work to.
313 Every metric names its ``source`` and every dimension the ``sources`` it
314 can slice, which is what lets a client offer only the combinations the
315 query can honour. Asking for a figure never states a source: the metric
316 determines it, so a request cannot name a metric and a table that
317 disagree.
318 """
319 return StatsCatalogueResponse(**breakdown_service.catalogue())
322def _stats_workspace(db: Session, key: str | None, user: User):
323 """The workspace a breakdown counts, and whether its projects' work is
324 in it: an organisation's admins see its projects' figures with its own,
325 since they administer each one; other members see the organisation's
326 own. A personal workspace's projects are its owner's."""
327 if not key:
328 return None, False
329 from app.services import membership
330 from app.services import workspace as workspace_service
332 ws = workspace_service.resolve(db, key, user)
333 if ws.kind is workspace_service.WorkspaceKind.personal:
334 return ws, True
335 if ws.kind is workspace_service.WorkspaceKind.organisation:
336 m = membership.effective_membership(db, membership.ORGANISATION, ws.id, user.id)
337 admin = user.is_superuser or (
338 m is not None and membership.role_of(m) is membership.MemberRole.admin
339 )
340 return ws, admin
341 return ws, False
344@stats_router.get("/breakdown", response_model=BreakdownResponse)
345def stats_breakdown(
346 metric: str = Query(default="estimated_cost_usd"),
347 dimension: str | None = Query(default=None),
348 period: str | None = Query(default=None),
349 filter: list[str] | None = Query(
350 default=None,
351 description=(
352 "Repeatable, written as '<dimension>:<value>' — e.g. "
353 "'project:<uuid>'. Narrows the rows before the metric is "
354 "aggregated, so a tile can report one agent's spend."
355 ),
356 ),
357 limit: int = Query(default=10, ge=1, le=breakdown_service.MAX_BUCKETS),
358 workspace: str | None = Query(
359 default=None,
360 description=(
361 "Count the work done in this workspace by anyone in it, rather "
362 "than the caller's own. An organisation's figures include its "
363 "projects' for its admins."
364 ),
365 ),
366 db: Session = Depends(get_db),
367 current_user: User = Depends(get_current_user),
368):
369 """One metric, over one window, optionally sliced by one dimension.
371 Four sources sit behind this: what invocations consumed
372 (``governance_usage``), what the rules did to them (``governance_events``),
373 what those rules removed (the redaction expansion of the same table), and
374 what a person was asked to look at (``review_flags``). The metric chooses
375 between them; there is no ``source`` parameter, so a request cannot name a
376 metric and a table that disagree.
378 Scoped to the calling user, like the governance activity log and the
379 reviewer queue: the ledger row records whose invocation it was, which is
380 the only scope it can answer on its own. A project-wide figure is a
381 ``project:`` filter, not a different caller.
383 Omitting ``dimension`` returns the figure alone — what a stat tile shows.
384 Supplying one returns it ranked across that axis, with everything past
385 ``limit`` folded into a single ``other`` bucket rather than dropped, so a
386 cost chart still adds up to the total printed above it.
388 Terms that do not resolve are refused with 422 rather than ignored. A
389 filter that silently fell off would widen a tile from one project to the
390 whole account while its caption still named the project.
391 """
392 ws, include_projects = _stats_workspace(db, workspace, current_user)
393 try:
394 filters = breakdown_service.parse_filters(filter)
395 result = breakdown_service.compute(
396 db,
397 current_user.id,
398 metric=metric,
399 dimension=dimension,
400 period=period,
401 filters=filters,
402 limit=limit,
403 workspace=ws,
404 include_projects=include_projects,
405 )
406 except breakdown_service.BreakdownError as exc:
407 raise HTTPException(
408 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)
409 )
410 except SQLAlchemyError:
411 logger.exception("Could not compute the stats breakdown")
412 raise HTTPException(
413 status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
414 detail="Could not compute the requested breakdown.",
415 )
416 return BreakdownResponse(**result.as_dict())
419@stats_router.get("/cost", response_model=ResourceCostResponse)
420def resource_cost(
421 source_type: str | None = Query(
422 default=None,
423 description="A UsageEnum.Source — agent, skill, dashboard, experiment, "
424 "generation, knowledge, knowledge_repository, model, simulation. "
425 "Omit for the whole account.",
426 ),
427 source_id: UUID | None = Query(default=None),
428 period: str | None = Query(default=None),
429 mine: bool = Query(
430 default=False,
431 description="Only the caller's own work in the workspace — 'your "
432 "spend' — rather than everyone's.",
433 ),
434 since: datetime | None = Query(
435 default=None, description="A range in place of the period (UTC)."
436 ),
437 until: datetime | None = Query(default=None),
438 db: Session = Depends(get_db),
439 current_user: User = Depends(get_current_user),
440):
441 """What a resource has cost: the figure behind every cost card.
443 Reads the usage ledger by the resource each invocation is *attributed*
444 to — a dashboard tile's spend is the dashboard's, whichever agent it
445 borrowed. Totals, a split by execution type and by source, and a daily
446 series. Counted in the request's workspace, like a breakdown. See
447 ``docs/guides/cost-monitoring.md``.
448 """
449 from app.dependency.workspace import requested_workspace
451 ws, include_projects = _stats_workspace(db, requested_workspace(), current_user)
452 try:
453 result = resource_cost_service.resource_cost(
454 db,
455 current_user.id,
456 source_type=source_type,
457 source_id=source_id,
458 period=period,
459 workspace=ws,
460 include_projects=include_projects,
461 mine=mine,
462 since=since,
463 until=until,
464 )
465 except resource_cost_service.ResourceCostError as exc:
466 raise HTTPException(
467 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)
468 )
469 except SQLAlchemyError:
470 logger.exception("Could not compute resource cost")
471 raise HTTPException(
472 status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
473 detail="Could not compute the cost.",
474 )
475 return ResourceCostResponse(**result)
478@stats_router.get("/steps", response_model=StepUsageResponse)
479def step_usage(
480 source_type: str = Query(
481 description="The UsageEnum.Source whose turns are read — agent, "
482 "skill, dashboard, experiment …",
483 ),
484 source_id: UUID | None = Query(default=None),
485 period: str | None = Query(default=None),
486 db: Session = Depends(get_db),
487 current_user: User = Depends(get_current_user),
488):
489 """Where a resource's tokens go: its newest turns in the period, as its
490 cost card counts them, summed by the step of the pipeline that made each
491 model call — triage, the answer, the quality check, retrieval's planner
492 and reranker. Read from svc-ai's call records for exactly those turns.
493 See ``docs/guides/cost-monitoring.md#where-the-tokens-go``.
494 """
495 from app.dependency.workspace import requested_workspace
497 ws, include_projects = _stats_workspace(db, requested_workspace(), current_user)
498 try:
499 result = step_usage_service.step_usage(
500 db,
501 current_user.id,
502 source_type=source_type,
503 source_id=source_id,
504 period=period,
505 workspace=ws,
506 include_projects=include_projects,
507 )
508 except resource_cost_service.ResourceCostError as exc:
509 raise HTTPException(
510 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=str(exc)
511 )
512 except SQLAlchemyError:
513 logger.exception("Could not read a resource's turns")
514 raise HTTPException(
515 status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
516 detail="Could not read where the tokens went.",
517 )
518 return StepUsageResponse(**result)
521def _svc_ai_workspace(db: Session, user: User) -> str:
522 """The workspace key svc-ai's figures are narrowed to: the request's.
523 Its usage tiles, Overview cards and Activity feed show the work done
524 there, never the person's other workspaces'."""
525 from app.dependency.workspace import request_workspace
527 return request_workspace(db, user).key
530@stats_router.get("/invocations", response_model=list[LLMInvocationRecord])
531def llm_invocations(
532 purpose: str | None = None,
533 limit: int = Query(default=200, ge=1, le=500),
534 offset: int = Query(default=0, ge=0),
535 db: Session = Depends(get_db),
536 current_user: User = Depends(get_current_user),
537) -> list[LLMInvocationRecord]:
538 """
539 Proxy to svc-ai's individual LLM invocation traces for the current user,
540 in the request's workspace.
542 Includes every recorded LLM call — conversation executions and platform
543 flows such as generative agent setup. ``offset`` pages past ``limit``.
544 """
545 try:
546 data = list_llm_invocations(
547 user_id=str(current_user.id),
548 purpose=purpose,
549 limit=limit,
550 offset=offset,
551 workspace=_svc_ai_workspace(db, current_user),
552 )
553 except AIServiceError as exc:
554 logger.error("Could not fetch LLM invocations from svc-ai: %s", exc)
555 raise HTTPException(
556 status_code=status.HTTP_502_BAD_GATEWAY,
557 detail="Could not reach svc-ai to retrieve LLM invocations.",
558 )
559 return [LLMInvocationRecord(**record) for record in data]
562@stats_router.get("/traces", response_model=TraceStatsResponse)
563def trace_stats(
564 db: Session = Depends(get_db),
565 current_user: User = Depends(get_current_user),
566) -> TraceStatsResponse:
567 """Proxy to svc-ai's LLM and tool invocation trace statistics for the
568 current user, in the request's workspace."""
569 try:
570 data = get_trace_stats(
571 user_id=str(current_user.id),
572 workspace=_svc_ai_workspace(db, current_user),
573 )
574 except AIServiceError as exc:
575 logger.error("Could not fetch trace stats from svc-ai: %s", exc)
576 raise HTTPException(
577 status_code=status.HTTP_502_BAD_GATEWAY,
578 detail="Could not reach svc-ai to retrieve trace statistics.",
579 )
580 return TraceStatsResponse(**data)
583@stats_router.get("/usage", response_model=UsageStatsResponse)
584def usage_stats(
585 db: Session = Depends(get_db),
586 current_user: User = Depends(get_current_user),
587) -> UsageStatsResponse:
588 """Proxy to svc-ai's aggregated token usage statistics for the current
589 user, in the request's workspace."""
590 try:
591 data = get_usage_stats(
592 user_id=str(current_user.id),
593 workspace=_svc_ai_workspace(db, current_user),
594 )
595 except AIServiceError as exc:
596 logger.error("Could not fetch usage stats from svc-ai: %s", exc)
597 raise HTTPException(
598 status_code=status.HTTP_502_BAD_GATEWAY,
599 detail="Could not reach svc-ai to retrieve usage statistics.",
600 )
601 return UsageStatsResponse(**data)
604@stats_router.get("/web-search-domains", response_model=WebSearchDomainStatsResponse)
605def web_search_domain_stats(
606 limit: int = Query(default=20, ge=1, le=100),
607 since: datetime | None = None,
608 until: datetime | None = None,
609 db: Session = Depends(get_db),
610 current_user: User = Depends(get_current_user),
611) -> WebSearchDomainStatsResponse:
612 """Proxy to svc-ai web-search citation domain statistics for the current
613 user, in the request's workspace."""
614 try:
615 data = get_web_search_domain_stats(
616 user_id=str(current_user.id),
617 limit=limit,
618 since=since.isoformat() if since else None,
619 until=until.isoformat() if until else None,
620 workspace=_svc_ai_workspace(db, current_user),
621 )
622 except AIServiceError as exc:
623 logger.error("Could not fetch web-search domain stats from svc-ai: %s", exc)
624 raise HTTPException(
625 status_code=status.HTTP_502_BAD_GATEWAY,
626 detail="Could not reach svc-ai to retrieve web-search domain statistics.",
627 )
628 return WebSearchDomainStatsResponse(**data)