Coverage for app / routers / stats.py: 97%

305 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1""" 

2Usage statistics aggregated from LLMInvocation and ToolInvocation records. 

3 

4Every aggregate here takes an optional ``user_id``. svc-core always sends the 

5caller's id, so the figures a person sees are their own; the parameter is 

6optional only so that an internal caller can still ask for the whole 

7deployment. ``user_id`` is a soft reference to svc-core's ``users.id`` stamped 

8on every trace row at write time (see ``app.services.conversation``). 

9 

10``workspace`` narrows each to the work done in one svc-core workspace — the 

11key svc-core stamped on the row (``app/common/workspace.py``). A workspace's 

12pages ask for theirs; the account's usage page leaves it out. 

13""" 

14 

15import urllib.parse 

16from collections import defaultdict 

17from datetime import date, datetime, timedelta, timezone 

18from decimal import Decimal 

19from typing import Optional 

20from uuid import UUID 

21 

22from fastapi import APIRouter, Depends, HTTPException, Query, status 

23from pydantic import BaseModel, Field 

24from sqlalchemy import and_, case, func, select 

25from sqlalchemy.orm import Session, joinedload, selectinload 

26 

27from app.db.postgres.enums import InvocationEnum, ToolInvocationEnum 

28from app.db.postgres.models import ( 

29 LLMInvocation, 

30 LLMInvocationCall, 

31 LLMModel, 

32 Provider, 

33 SpendCounter, 

34 ToolCitation, 

35 ToolInvocation, 

36) 

37from app.common import workspace as workspace_context 

38from app.dependency.base import get_db 

39from app.util.time import UTCDateTime 

40 

41router = APIRouter(prefix="/stats", tags=["stats"]) 

42 

43 

44def _workspace( 

45 workspace: str | None = Query( 

46 default=None, 

47 description="Count only the work done in this svc-core workspace: " 

48 "user:<id>, organisation:<id> or project:<id>.", 

49 ), 

50) -> str | None: 

51 if workspace is None: 

52 return None 

53 key = workspace_context.parse(workspace) 

54 if key is None or key == workspace_context.PERSONAL: 

55 raise HTTPException( 

56 status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, 

57 detail=f"Not a workspace key: {workspace!r}", 

58 ) 

59 return key 

60 

61 

62class UsagePeriod(BaseModel): 

63 input_tokens: int 

64 output_tokens: int 

65 total_tokens: int 

66 invocation_count: int 

67 error_count: int 

68 avg_latency_ms: Optional[float] 

69 estimated_cost_usd: Optional[float] 

70 

71 

72class UsageStatsResponse(BaseModel): 

73 this_month: UsagePeriod 

74 all_time: UsagePeriod 

75 

76 

77def _aggregate( 

78 db: Session, 

79 since: datetime | None = None, 

80 user_id: UUID | None = None, 

81 workspace: str | None = None, 

82) -> UsagePeriod: 

83 q = db.query( 

84 func.coalesce(func.sum(LLMInvocation.prompt_tokens), 0).label("input_tokens"), 

85 func.coalesce(func.sum(LLMInvocation.completion_tokens), 0).label( 

86 "output_tokens" 

87 ), 

88 func.coalesce(func.sum(LLMInvocation.total_tokens), 0).label("total_tokens"), 

89 func.count(LLMInvocation.id).label("invocation_count"), 

90 func.count(LLMInvocation.id) 

91 .filter(LLMInvocation.status == InvocationEnum.Status.error) 

92 .label("error_count"), 

93 func.avg(LLMInvocation.latency_ms).label("avg_latency_ms"), 

94 func.coalesce(func.sum(LLMInvocation.estimated_cost_usd), 0).label( 

95 "estimated_cost_usd" 

96 ), 

97 ) 

98 if since: 

99 q = q.filter(LLMInvocation.created_at >= since) 

100 if user_id: 

101 q = q.filter(LLMInvocation.user_id == user_id) 

102 if workspace: 

103 q = q.filter(workspace_context.clause(LLMInvocation, workspace)) 

104 row = q.one() 

105 return UsagePeriod( 

106 input_tokens=int(row.input_tokens), 

107 output_tokens=int(row.output_tokens), 

108 total_tokens=int(row.total_tokens), 

109 invocation_count=int(row.invocation_count), 

110 error_count=int(row.error_count), 

111 avg_latency_ms=float(row.avg_latency_ms) 

112 if row.avg_latency_ms is not None 

113 else None, 

114 estimated_cost_usd=float(row.estimated_cost_usd) 

115 if row.estimated_cost_usd 

116 else None, 

117 ) 

118 

119 

120class TracePeriod(BaseModel): 

121 llm_invocation_count: int 

122 tool_invocation_count: int 

123 avg_llm_per_conversation: Optional[float] 

124 stddev_llm_per_conversation: Optional[float] 

125 avg_tool_per_conversation: Optional[float] 

126 stddev_tool_per_conversation: Optional[float] 

127 

128 

129class TraceStatsResponse(BaseModel): 

130 this_month: TracePeriod 

131 all_time: TracePeriod 

132 

133 

134def _aggregate_traces( 

135 db: Session, 

136 since: datetime | None = None, 

137 user_id: UUID | None = None, 

138 workspace: str | None = None, 

139) -> TracePeriod: 

140 def _f(v) -> Optional[float]: 

141 return round(float(v), 2) if v is not None else None 

142 

143 # One place for the window and the owner, so the flat counts and the 

144 # per-conversation averages can never disagree about which rows they cover. 

145 def _scoped(stmt, model): 

146 if since: 

147 stmt = stmt.where(model.created_at >= since) 

148 if user_id: 

149 stmt = stmt.where(model.user_id == user_id) 

150 if workspace: 

151 stmt = stmt.where(workspace_context.clause(model, workspace)) 

152 return stmt 

153 

154 # ── Flat counts ────────────────────────────────────────────────────────── 

155 llm_count_stmt = _scoped(select(func.count(LLMInvocation.id)), LLMInvocation) 

156 tool_count_stmt = _scoped(select(func.count(ToolInvocation.id)), ToolInvocation) 

157 llm_count = db.execute(llm_count_stmt).scalar() or 0 

158 tool_count = db.execute(tool_count_stmt).scalar() or 0 

159 

160 # ── Per-conversation avg ± stddev ──────────────────────────────────────── 

161 # Build an inner query that counts invocations per conversation, then 

162 # aggregate over those counts. select_from() is required so SQLAlchemy 

163 # emits FROM (subquery) and not FROM the base table. 

164 def _per_conv_agg(model): 

165 inner = _scoped( 

166 select(func.count(model.id).label("cnt")) 

167 .where(model.conversation_id.isnot(None)) 

168 .group_by(model.conversation_id), 

169 model, 

170 ) 

171 sub = inner.subquery() 

172 stmt = select( 

173 func.avg(sub.c.cnt).label("avg"), 

174 func.stddev_samp(sub.c.cnt).label("stddev"), 

175 ).select_from(sub) 

176 return db.execute(stmt).one() 

177 

178 llm_agg = _per_conv_agg(LLMInvocation) 

179 tool_agg = _per_conv_agg(ToolInvocation) 

180 

181 return TracePeriod( 

182 llm_invocation_count=int(llm_count), 

183 tool_invocation_count=int(tool_count), 

184 avg_llm_per_conversation=_f(llm_agg.avg), 

185 stddev_llm_per_conversation=_f(llm_agg.stddev), 

186 avg_tool_per_conversation=_f(tool_agg.avg), 

187 stddev_tool_per_conversation=_f(tool_agg.stddev), 

188 ) 

189 

190 

191class InvocationCallRecord(BaseModel): 

192 """One model call within an invocation — the model that actually did it.""" 

193 

194 sequence: int 

195 provider: str 

196 #: The exact model identifier the call was made with. 

197 model_name: str 

198 #: The catalogue's name for it, when the catalogue lists it. 

199 model_display_name: str | None = None 

200 model_id: UUID | None = None 

201 #: ``chat`` or ``embedding``. 

202 kind: str = "chat" 

203 #: The graph node that made the call; None outside a graph. 

204 node: str | None = None 

205 #: What the node was doing (``metering.step``), and which pass of the 

206 #: run it was on (0 first; one more per revision). None when unlabelled. 

207 step: str | None = None 

208 pass_index: int | None = None 

209 #: Every prompt token, and every generated token (reasoning included); 

210 #: the three after them are parts of these, as the provider reported. 

211 prompt_tokens: int = 0 

212 completion_tokens: int = 0 

213 cache_read_tokens: int = 0 

214 cache_write_tokens: int = 0 

215 reasoning_tokens: int = 0 

216 latency_ms: int | None = None 

217 status: str 

218 error_detail: str | None = None 

219 #: None when the call could not be priced (or failed) — never 0 for that. 

220 estimated_cost_usd: float | None = None 

221 #: The rates behind the cost and their source, whether the long-context 

222 #: tier applied — or ``unpriced_reason``. 

223 pricing: dict | None = None 

224 

225 

226class InvocationRecord(BaseModel): 

227 id: UUID 

228 created_at: UTCDateTime | None = None 

229 purpose: str | None = None 

230 user_id: UUID | None = None 

231 conversation_id: UUID | None = None 

232 #: The model the invocation asked for (or the one model its calls used), 

233 #: by exact identifier. None only when it named none and its calls used 

234 #: several — or for a trace recorded before calls were. 

235 provider: str | None = None 

236 model_name: str | None = None 

237 model_display_name: str | None = None 

238 model_id: UUID | None = None 

239 #: Every model call it made, in order. Empty for traces recorded before 

240 #: calls were. 

241 calls: list[InvocationCallRecord] = [] 

242 prompt_tokens: int = 0 

243 completion_tokens: int = 0 

244 total_tokens: int = 0 

245 latency_ms: int | None = None 

246 status: str 

247 error_detail: str | None = None 

248 estimated_cost_usd: float | None = None 

249 request_config: dict | None = None 

250 output_preview: str | None = None 

251 

252 

253@router.get("/invocations", response_model=list[InvocationRecord]) 

254def list_invocations( 

255 user_id: UUID | None = None, 

256 purpose: str | None = None, 

257 limit: int = Query(default=200, ge=1, le=500), 

258 offset: int = Query(default=0, ge=0), 

259 workspace: str | None = Depends(_workspace), 

260 db: Session = Depends(get_db), 

261) -> list[InvocationRecord]: 

262 """ 

263 List individual LLM invocation traces, newest first. 

264 

265 Covers every recorded LLM call — conversation executions and platform 

266 flows such as generative agent setup alike. ``user_id`` scopes the 

267 list to calls attributed to that user. ``offset`` pages past ``limit``, 

268 which is how the activity feed reaches calls older than its first page. 

269 """ 

270 q = db.query(LLMInvocation).options( 

271 joinedload(LLMInvocation.model).joinedload(LLMModel.provider), 

272 selectinload(LLMInvocation.calls), 

273 ) 

274 if user_id: 

275 q = q.filter(LLMInvocation.user_id == user_id) 

276 if workspace: 

277 q = q.filter(workspace_context.clause(LLMInvocation, workspace)) 

278 if purpose: 

279 q = q.filter(LLMInvocation.purpose == purpose) 

280 rows = ( 

281 q.order_by(LLMInvocation.created_at.desc(), LLMInvocation.id.desc()) 

282 .offset(offset) 

283 .limit(limit) 

284 .all() 

285 ) 

286 names = _display_names(db) if rows else {} 

287 return [_invocation_record(row, names) for row in rows] 

288 

289 

290#: How much of a tool's raw output a turn's record carries. The record is 

291#: read in a browser; a scraped page can be megabytes. 

292TOOL_OUTPUT_CHARS = 4000 

293 

294 

295class ToolCitationRecord(BaseModel): 

296 index: int 

297 #: ``url``, ``document`` or another kind (``ToolInvocationEnum.SourceType``). 

298 source_type: str 

299 source: str 

300 title: str 

301 collection: str | None = None 

302 relevance_score: float | None = None 

303 

304 

305class ToolCallRecord(BaseModel): 

306 """One tool call a turn made, as svc-ai recorded it.""" 

307 

308 id: UUID 

309 created_at: UTCDateTime | None = None 

310 tool_name: str 

311 input_args: dict | None = None 

312 #: The tool's output, cut at ``TOOL_OUTPUT_CHARS`` (``truncated``). 

313 output: str | None = None 

314 truncated: bool = False 

315 latency_ms: int | None = None 

316 status: str 

317 error_detail: str | None = None 

318 #: The node, skill or agent that made the call. 

319 execution_context: dict | None = None 

320 citations: list[ToolCitationRecord] = [] 

321 #: A web search's report: what each engine said and what each check 

322 #: removed (``app/util/web_search_report.py``); None for any other tool, 

323 #: and for a search recorded before reports were kept. 

324 report: dict | None = None 

325 

326 

327class TurnTraceResponse(BaseModel): 

328 """Everything svc-ai recorded for one svc-core turn: each traced 

329 invocation (an execution, a resumed segment, an untraced leftover) with 

330 its model calls, and every tool call.""" 

331 

332 invocations: list[InvocationRecord] = [] 

333 tool_calls: list[ToolCallRecord] = [] 

334 

335 

336@router.get("/turns/{core_invocation_id}", response_model=TurnTraceResponse) 

337def get_turn( 

338 core_invocation_id: UUID, 

339 user_id: UUID | None = None, 

340 db: Session = Depends(get_db), 

341) -> TurnTraceResponse: 

342 """The model and tool calls behind one svc-core turn — an answer, a skill 

343 run, an evaluation cell — by the id svc-core sent with it 

344 (``X-Invocation-Id``; ``core_invocation_id`` on the rows). In the order 

345 they were made. ``user_id`` narrows it to that person's rows, as every 

346 read here does; svc-core sends the turn's owner. 

347 

348 Turns from before the id was sent have no rows: an empty answer means 

349 "not recorded by turn", not "made no calls". 

350 """ 

351 invocations = db.query(LLMInvocation).options( 

352 joinedload(LLMInvocation.model).joinedload(LLMModel.provider), 

353 selectinload(LLMInvocation.calls), 

354 ) 

355 tools = db.query(ToolInvocation).options(selectinload(ToolInvocation.citations)) 

356 invocations = invocations.filter( 

357 LLMInvocation.core_invocation_id == core_invocation_id 

358 ) 

359 tools = tools.filter(ToolInvocation.core_invocation_id == core_invocation_id) 

360 if user_id: 

361 invocations = invocations.filter(LLMInvocation.user_id == user_id) 

362 tools = tools.filter(ToolInvocation.user_id == user_id) 

363 rows = invocations.order_by( 

364 LLMInvocation.created_at.asc(), LLMInvocation.id.asc() 

365 ).all() 

366 names = _display_names(db) if rows else {} 

367 return TurnTraceResponse( 

368 invocations=[_invocation_record(row, names) for row in rows], 

369 tool_calls=[ 

370 _tool_call_record(row) 

371 for row in tools.order_by( 

372 ToolInvocation.created_at.asc(), ToolInvocation.id.asc() 

373 ).all() 

374 ], 

375 ) 

376 

377 

378def _tool_call_record(row: ToolInvocation) -> ToolCallRecord: 

379 output = row.raw_output 

380 return ToolCallRecord( 

381 id=row.id, 

382 created_at=row.created_at, 

383 tool_name=row.tool_name, 

384 input_args=row.input_args if isinstance(row.input_args, dict) else None, 

385 output=output[:TOOL_OUTPUT_CHARS] if output is not None else None, 

386 truncated=output is not None and len(output) > TOOL_OUTPUT_CHARS, 

387 latency_ms=row.latency_ms, 

388 status=_enum_text(row.status), 

389 error_detail=row.error_detail, 

390 execution_context=row.execution_context 

391 if isinstance(row.execution_context, dict) 

392 else None, 

393 report=row.report if isinstance(row.report, dict) else None, 

394 citations=[ 

395 ToolCitationRecord( 

396 index=citation.index, 

397 source_type=_enum_text(citation.source_type), 

398 source=citation.source, 

399 title=citation.title, 

400 collection=citation.collection, 

401 relevance_score=citation.relevance_score, 

402 ) 

403 for citation in row.citations 

404 ], 

405 ) 

406 

407 

408def _display_names(db: Session) -> dict[tuple[str, str], str]: 

409 """``(provider, model_name) → display name`` across the catalogue.""" 

410 rows = ( 

411 db.query(Provider.name, LLMModel.model_name, LLMModel.display_name) 

412 .join(Provider, LLMModel.provider_id == Provider.id) 

413 .all() 

414 ) 

415 return { 

416 (_enum_text(provider), str(model)): display 

417 for provider, model, display in rows 

418 if display 

419 } 

420 

421 

422def _enum_text(value) -> str: 

423 return str(value.value if hasattr(value, "value") else value) 

424 

425 

426def _invocation_model(row: LLMInvocation) -> tuple[str | None, str | None]: 

427 """The row's own provider and model; for a row written before they were 

428 stored, the catalogue model its ``model_id`` still points at.""" 

429 if row.model_name: 

430 return row.provider, row.model_name 

431 if row.model is not None and row.model.provider is not None: 

432 return _enum_text(row.model.provider.name), row.model.model_name 

433 return None, None 

434 

435 

436def _invocation_record( 

437 row: LLMInvocation, names: dict[tuple[str, str], str] 

438) -> InvocationRecord: 

439 provider, model_name = _invocation_model(row) 

440 return InvocationRecord( 

441 id=row.id, 

442 created_at=row.created_at, 

443 purpose=row.purpose, 

444 user_id=row.user_id, 

445 conversation_id=row.conversation_id, 

446 provider=provider, 

447 model_name=model_name, 

448 model_display_name=names.get((provider or "", model_name or "")), 

449 model_id=row.model_id, 

450 calls=[ 

451 InvocationCallRecord( 

452 sequence=call.sequence, 

453 provider=call.provider, 

454 model_name=call.model_name, 

455 model_display_name=names.get((call.provider, call.model_name)), 

456 model_id=call.model_id, 

457 kind=call.kind or "chat", 

458 node=call.node, 

459 step=call.step, 

460 pass_index=call.pass_index, 

461 prompt_tokens=call.prompt_tokens or 0, 

462 completion_tokens=call.completion_tokens or 0, 

463 cache_read_tokens=call.cache_read_tokens or 0, 

464 cache_write_tokens=call.cache_write_tokens or 0, 

465 reasoning_tokens=call.reasoning_tokens or 0, 

466 pricing=call.pricing, 

467 latency_ms=call.latency_ms, 

468 status=_enum_text(call.status), 

469 error_detail=call.error_detail, 

470 estimated_cost_usd=float(call.estimated_cost_usd) 

471 if call.estimated_cost_usd is not None 

472 else None, 

473 ) 

474 for call in row.calls 

475 ], 

476 prompt_tokens=row.prompt_tokens or 0, 

477 completion_tokens=row.completion_tokens or 0, 

478 total_tokens=row.total_tokens or 0, 

479 latency_ms=row.latency_ms, 

480 status=str(row.status.value if hasattr(row.status, "value") else row.status), 

481 error_detail=row.error_detail, 

482 estimated_cost_usd=float(row.estimated_cost_usd) 

483 if row.estimated_cost_usd is not None 

484 else None, 

485 request_config=row.request_config, 

486 output_preview=row.output_preview, 

487 ) 

488 

489 

490def _month_start() -> datetime: 

491 now = datetime.now(timezone.utc) 

492 return now.replace(day=1, hour=0, minute=0, second=0, microsecond=0) 

493 

494 

495@router.get("/traces", response_model=TraceStatsResponse) 

496def get_trace_stats( 

497 user_id: UUID | None = None, 

498 workspace: str | None = Depends(_workspace), 

499 db: Session = Depends(get_db), 

500) -> TraceStatsResponse: 

501 """ 

502 Return LLM and tool invocation counts with per-conversation avg ± stddev. 

503 Provides both current-month and all-time totals. ``user_id`` scopes both 

504 to the traces attributed to that user; without it the figures cover the 

505 whole deployment. 

506 """ 

507 month_start = _month_start() 

508 return TraceStatsResponse( 

509 this_month=_aggregate_traces( 

510 db, since=month_start, user_id=user_id, workspace=workspace 

511 ), 

512 all_time=_aggregate_traces(db, user_id=user_id, workspace=workspace), 

513 ) 

514 

515 

516@router.get("/usage", response_model=UsageStatsResponse) 

517def get_usage_stats( 

518 user_id: UUID | None = None, 

519 workspace: str | None = Depends(_workspace), 

520 db: Session = Depends(get_db), 

521) -> UsageStatsResponse: 

522 """ 

523 Return token usage aggregated from LLMInvocation records. 

524 Provides both current-month and all-time totals. ``user_id`` scopes both 

525 to the invocations attributed to that user; without it the figures cover 

526 the whole deployment. 

527 """ 

528 month_start = _month_start() 

529 return UsageStatsResponse( 

530 this_month=_aggregate( 

531 db, since=month_start, user_id=user_id, workspace=workspace 

532 ), 

533 all_time=_aggregate(db, user_id=user_id, workspace=workspace), 

534 ) 

535 

536 

537# --------------------------------------------------------------------------- 

538# One day's metered calls, for svc-core's economics export 

539# --------------------------------------------------------------------------- 

540 

541 

542class MeterGroup(BaseModel): 

543 """A day's model calls that share these keys, summed. 

544 

545 Read by svc-core's economics export (``app/services/economics``), which 

546 attributes them to workspaces and modules. Ids, model names and figures 

547 only: nothing anyone wrote. 

548 """ 

549 

550 #: The svc-core workspace key stamped on the trace (``user:<id>``, 

551 #: ``organisation:<id>``, ``project:<id>``), or None. 

552 workspace: Optional[str] 

553 #: The trace's user, given only where the trace names no workspace: such 

554 #: a row predates workspaces and counts as that user's Personal. None on 

555 #: both is platform work nobody started (the benchmark, built-in tiles, 

556 #: crawls of built-in sources). 

557 user_id: Optional[UUID] 

558 #: What produced the calls (``LLMInvocation.purpose``). 

559 purpose: Optional[str] 

560 provider: str 

561 model: str 

562 #: ``chat`` or ``embedding``. 

563 kind: str 

564 #: Whether the invocation the calls were part of succeeded. Spend under 

565 #: ``error`` bought nothing anyone received. 

566 status: str 

567 calls: int 

568 #: Calls that failed themselves (their invocation may still have 

569 #: succeeded, on a retry or a fallback). 

570 failed_calls: int 

571 #: Calls that answered but could not be priced: ``cost_usd`` is a lower 

572 #: bound wherever this is above 0. 

573 unpriced_calls: int 

574 prompt_tokens: int 

575 completion_tokens: int 

576 cache_read_tokens: int 

577 cache_write_tokens: int 

578 reasoning_tokens: int 

579 cost_usd: Decimal 

580 #: What the cache reads would have cost as uncached input, less what they 

581 #: did cost: what prompt caching saved, at each call's own rates. 

582 cache_savings_usd: Decimal 

583 

584 

585class DailyMeterResponse(BaseModel): 

586 day: date 

587 groups: list[MeterGroup] 

588 #: The spending ceiling's count for the day (``spend_counters``), which 

589 #: includes every metered call (an unpriced one at the dearest rate). 

590 #: None when the guard recorded nothing that day. 

591 ceiling_counted_usd: Optional[Decimal] 

592 

593 

594def _rate(name: str): 

595 """A rate the call was priced at, from its ``pricing`` record.""" 

596 return LLMInvocationCall.pricing[("rates", name)].as_numeric(20, 12) 

597 

598 

599def _call_sums() -> list: 

600 """What a group of model calls added up to — the aggregates the daily 

601 meter and a turn's steps both read, labelled as their response fields.""" 

602 call = LLMInvocationCall 

603 failed = call.status != InvocationEnum.Status.success # error or timeout 

604 savings = case( 

605 ( 

606 and_(call.cache_read_tokens > 0, call.estimated_cost_usd.is_not(None)), 

607 call.cache_read_tokens * (_rate("input") - _rate("cache_read")), 

608 ), 

609 else_=0, 

610 ) 

611 return [ 

612 func.count(call.id).label("calls"), 

613 func.count(call.id).filter(failed).label("failed_calls"), 

614 func.count(call.id) 

615 .filter(~failed, call.estimated_cost_usd.is_(None)) 

616 .label("unpriced_calls"), 

617 func.coalesce(func.sum(call.prompt_tokens), 0).label("prompt_tokens"), 

618 func.coalesce(func.sum(call.completion_tokens), 0).label("completion_tokens"), 

619 func.coalesce(func.sum(call.cache_read_tokens), 0).label("cache_read_tokens"), 

620 func.coalesce(func.sum(call.cache_write_tokens), 0).label("cache_write_tokens"), 

621 func.coalesce(func.sum(call.reasoning_tokens), 0).label("reasoning_tokens"), 

622 func.coalesce(func.sum(call.estimated_cost_usd), 0).label("cost_usd"), 

623 func.coalesce(func.sum(savings), 0).label("cache_savings_usd"), 

624 ] 

625 

626 

627def _sums_of(row) -> dict: 

628 """A summed row's figures, as the response models take them.""" 

629 return { 

630 "calls": int(row.calls), 

631 "failed_calls": int(row.failed_calls), 

632 "unpriced_calls": int(row.unpriced_calls), 

633 "prompt_tokens": int(row.prompt_tokens), 

634 "completion_tokens": int(row.completion_tokens), 

635 "cache_read_tokens": int(row.cache_read_tokens), 

636 "cache_write_tokens": int(row.cache_write_tokens), 

637 "reasoning_tokens": int(row.reasoning_tokens), 

638 "cost_usd": Decimal(str(row.cost_usd)), 

639 "cache_savings_usd": Decimal(str(row.cache_savings_usd)), 

640 } 

641 

642 

643def _daily_meter(db: Session, day: date) -> list[MeterGroup]: 

644 start = datetime(day.year, day.month, day.day) # columns hold naive UTC 

645 end = start + timedelta(days=1) 

646 call = LLMInvocationCall 

647 # The user only where no workspace says whose the work was. 

648 owner = case( 

649 (LLMInvocation.workspace.is_(None), LLMInvocation.user_id), else_=None 

650 ).label("user_id") 

651 keys = ( 

652 LLMInvocation.workspace, 

653 owner, 

654 LLMInvocation.purpose, 

655 call.provider, 

656 call.model_name, 

657 call.kind, 

658 LLMInvocation.status, 

659 ) 

660 rows = ( 

661 db.query(*keys, *_call_sums()) 

662 .join(LLMInvocation, call.invocation_id == LLMInvocation.id) 

663 .filter(call.created_at >= start, call.created_at < end) 

664 .group_by(*keys) 

665 .all() 

666 ) 

667 return [ 

668 MeterGroup( 

669 workspace=row.workspace, 

670 user_id=row.user_id, 

671 purpose=row.purpose, 

672 provider=row.provider, 

673 model=row.model_name, 

674 kind=row.kind, 

675 status=getattr(row.status, "value", row.status), 

676 **_sums_of(row), 

677 ) 

678 for row in rows 

679 ] 

680 

681 

682@router.get("/meter", response_model=DailyMeterResponse) 

683def get_daily_meter( 

684 day: date = Query(description="The UTC day, YYYY-MM-DD."), 

685 db: Session = Depends(get_db), 

686) -> DailyMeterResponse: 

687 """Every model call metered on one UTC day, summed by workspace, purpose, 

688 model and outcome — the deployment's whole spend, platform work included, 

689 for svc-core's daily economics export.""" 

690 counter = db.get(SpendCounter, f"day:{day:%Y-%m-%d}") 

691 return DailyMeterResponse( 

692 day=day, 

693 groups=_daily_meter(db, day), 

694 ceiling_counted_usd=None if counter is None else Decimal(str(counter.cost_usd)), 

695 ) 

696 

697 

698#: Most turns one request may ask about. 

699MAX_STEP_TURNS = 2000 

700 

701 

702class StepUsageRequest(BaseModel): 

703 #: svc-core's turn ids (``X-Invocation-Id``; ``core_invocation_id`` on 

704 #: the rows). svc-core picks them from its own ledger, already narrowed 

705 #: to a workspace and to what the caller may see, so svc-ai answers for 

706 #: exactly these. 

707 core_invocation_ids: list[UUID] = Field(max_length=MAX_STEP_TURNS) 

708 

709 

710class StepUsage(BaseModel): 

711 """What one step of those turns cost, on one model.""" 

712 

713 #: The graph node that made the calls; None outside a graph. 

714 node: Optional[str] 

715 #: What the node was doing (``metering.step``); None on calls nothing 

716 #: labelled, every one before svc-ai migration 27 among them. 

717 step: Optional[str] 

718 #: 0 the first pass, 1 the first revision after the quality check, … 

719 pass_index: Optional[int] 

720 kind: str 

721 provider: str 

722 model: str 

723 calls: int 

724 failed_calls: int 

725 unpriced_calls: int 

726 prompt_tokens: int 

727 completion_tokens: int 

728 cache_read_tokens: int 

729 cache_write_tokens: int 

730 reasoning_tokens: int 

731 cost_usd: Decimal 

732 cache_savings_usd: Decimal 

733 #: The calls' own time, summed — not wall clock: graph calls overlap. 

734 latency_ms: int 

735 

736 

737class StepUsageResponse(BaseModel): 

738 #: How many of the turns asked about svc-ai has calls for. One from 

739 #: before turns were named, or that made no call, is not among them. 

740 turns: int 

741 steps: list[StepUsage] 

742 

743 

744@router.post("/steps", response_model=StepUsageResponse) 

745def get_step_usage( 

746 body: StepUsageRequest, db: Session = Depends(get_db) 

747) -> StepUsageResponse: 

748 """Where a set of turns' tokens went: every model call they made, summed 

749 by graph node, step, pass and model. For svc-core's "where the tokens 

750 go" views, and the measurements that show what a change to the pipeline 

751 saved.""" 

752 ids = list(dict.fromkeys(body.core_invocation_ids)) 

753 if not ids: 

754 return StepUsageResponse(turns=0, steps=[]) 

755 call = LLMInvocationCall 

756 keys = ( 

757 call.node, 

758 call.step, 

759 call.pass_index, 

760 call.kind, 

761 call.provider, 

762 call.model_name, 

763 ) 

764 in_turns = LLMInvocation.core_invocation_id.in_(ids) 

765 rows = ( 

766 db.query( 

767 *keys, 

768 *_call_sums(), 

769 func.coalesce(func.sum(call.latency_ms), 0).label("latency_ms"), 

770 ) 

771 .join(LLMInvocation, call.invocation_id == LLMInvocation.id) 

772 .filter(in_turns) 

773 .group_by(*keys) 

774 .all() 

775 ) 

776 turns = ( 

777 db.query(func.count(func.distinct(LLMInvocation.core_invocation_id))) 

778 .filter(in_turns) 

779 .scalar() 

780 ) 

781 return StepUsageResponse( 

782 turns=int(turns or 0), 

783 steps=[ 

784 StepUsage( 

785 node=row.node, 

786 step=row.step, 

787 pass_index=row.pass_index, 

788 kind=row.kind, 

789 provider=row.provider, 

790 model=row.model_name, 

791 latency_ms=int(row.latency_ms), 

792 **_sums_of(row), 

793 ) 

794 for row in rows 

795 ], 

796 ) 

797 

798 

799class WebSearchDomainStat(BaseModel): 

800 domain: str 

801 visit_count: int 

802 avg_trust_score: Optional[float] 

803 last_visited: Optional[UTCDateTime] 

804 

805 

806class WebSearchDomainStatsResponse(BaseModel): 

807 domains: list[WebSearchDomainStat] 

808 

809 

810@router.get("/web-search-domains", response_model=WebSearchDomainStatsResponse) 

811def web_search_domain_stats( 

812 user_id: UUID | None = None, 

813 since: datetime | None = None, 

814 until: datetime | None = None, 

815 limit: int = Query(default=20, ge=1, le=100), 

816 workspace: str | None = Depends(_workspace), 

817 db: Session = Depends(get_db), 

818) -> WebSearchDomainStatsResponse: 

819 """ 

820 Aggregate web_search result citations by source domain. 

821 

822 Reports how often each domain was surfaced in search results and its 

823 average trust/quality score (0.0-1.0, from the domain quality tiering 

824 applied when results were fetched). ``user_id`` scopes the aggregation 

825 to a single user's tool calls; ``since``/``until`` scope it to the tool 

826 calls whose invocation fell within that window. 

827 """ 

828 q = ( 

829 db.query(ToolCitation) 

830 .join(ToolInvocation, ToolCitation.tool_invocation_id == ToolInvocation.id) 

831 .options(joinedload(ToolCitation.invocation)) 

832 .filter(ToolInvocation.tool_name == "web_search") 

833 .filter(ToolCitation.source_type == ToolInvocationEnum.SourceType.url) 

834 ) 

835 if user_id: 

836 q = q.filter(ToolInvocation.user_id == user_id) 

837 if workspace: 

838 q = q.filter(workspace_context.clause(ToolInvocation, workspace)) 

839 if since: 

840 q = q.filter(ToolInvocation.created_at >= since) 

841 if until: 

842 q = q.filter(ToolInvocation.created_at <= until) 

843 

844 buckets: dict[str, dict] = defaultdict( 

845 lambda: {"count": 0, "score_sum": 0.0, "score_n": 0, "last": None} 

846 ) 

847 for citation in q.all(): 

848 hostname = (urllib.parse.urlparse(citation.source).hostname or "").lower() 

849 if not hostname: 

850 continue 

851 bucket = buckets[hostname] 

852 bucket["count"] += 1 

853 if citation.relevance_score is not None: 

854 bucket["score_sum"] += citation.relevance_score 

855 bucket["score_n"] += 1 

856 created = citation.invocation.created_at if citation.invocation else None 

857 if created and (bucket["last"] is None or created > bucket["last"]): 

858 bucket["last"] = created 

859 

860 domains = [ 

861 WebSearchDomainStat( 

862 domain=domain, 

863 visit_count=bucket["count"], 

864 avg_trust_score=round(bucket["score_sum"] / bucket["score_n"], 3) 

865 if bucket["score_n"] 

866 else None, 

867 last_visited=bucket["last"], 

868 ) 

869 for domain, bucket in buckets.items() 

870 ] 

871 domains.sort(key=lambda d: d.visit_count, reverse=True) 

872 return WebSearchDomainStatsResponse(domains=domains[:limit])