Coverage for app / services / metering.py: 96%

325 statements  

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

1""" 

2Per-request LLM usage metering — what every model call in a request cost. 

3 

4Why this exists 

5─────────────── 

6Cost used to be worked out once per request, from the one model the request 

7*named*. That is wrong for anything with more than one model in it: a skill 

8graph whose nodes pin different models, the pipeline's own system nodes 

9(gate, planner, synthesis, evaluator) running on the system model, an 

10evaluation's judge, a generation flow's retry. It also went missing entirely 

11whenever a run paused for a human — the interrupted response carried no usage 

12at all — and it summed only the *growth* in input tokens between a graph's 

13calls, while providers bill every call's full prompt. 

14 

15The meter records each call where it happens, with the model that actually 

16answered it, and prices each call on its own. One meter per HTTP request 

17(``LLMUsageMiddleware``), so whatever the endpoint — execute, stream, resume, 

18a generation flow, retrieval, embeddings — its spend is known. 

19 

20How calls reach it 

21────────────────── 

22* LangChain chat models: ``build_langchain_llm`` attaches a ``MeterCallback`` 

23 bound to the model's provider and name, so every call — tool loops, 

24 structured output, retries — is recorded without any node cooperating. 

25* LiteLLM direct calls (``run_model`` / ``stream_model``) and embeddings 

26 (``services/rag.py``) call ``record`` themselves. 

27 

28Each call keeps the graph node that made it (LangGraph's run metadata), how 

29long it took, and whether it failed: a refused call still went to that model, 

30and a retry or a runtime fallback is only legible if the attempts that came 

31before it are on record too. 

32 

33How it leaves 

34───────────── 

35* Every svc-ai trace row (``llm_invocations``) claims the calls made while it 

36 was being served (``UsageMeter.claim``) and stores each one as an 

37 ``llm_invocation_calls`` row — so a graph run whose nodes used three models 

38 says exactly which node called which model, rather than one model id for 

39 the whole run, or none. 

40* Non-streaming responses carry the summary in the ``X-LLM-Usage`` header, 

41 added by the middleware once the endpoint has returned. 

42* Batch executions also fold it into ``ExecuteResponse.usage`` (so svc-ai's 

43 own ``llm_invocations`` row is priced the same way) and streams put it on 

44 the terminal ``done`` frame, whose headers left long before the work ended. 

45 

46Pricing 

47─────── 

48Each call keeps every class of token its provider reported — uncached input, 

49cache reads, cache writes (5-minute and 1-hour), output with reasoning inside 

50it — and is priced class by class on the model's ``PriceCard``: the model 

51catalogue's first (the same figures svc-core quotes and cost caps are written 

52against), then LiteLLM's price map. ``services/provider_usage.py`` has the 

53billing rules. A call is **unpriced** — counted in ``unpriced_calls``, left 

54out of the sum, never priced at zero — when the provider reported no usage, 

55billed it at a non-standard tier, or used a token class no card has a rate 

56for. The summary's cost is None only when nothing in it could be priced. 

57""" 

58 

59from __future__ import annotations 

60 

61import contextvars 

62import json 

63import threading 

64import time 

65from contextlib import contextmanager 

66from dataclasses import dataclass, field 

67from decimal import Decimal 

68from enum import StrEnum 

69from typing import Any, Callable, Iterator 

70 

71from langchain_core.callbacks.base import BaseCallbackHandler 

72 

73from app.services import model_errors, provider_usage 

74from app.services.provider_usage import PriceCard, Priced, TokenUsage 

75from app.util.logger import get_logger 

76 

77logger = get_logger(__name__) 

78 

79#: Response header carrying a request's usage summary as JSON. 

80USAGE_HEADER = "X-LLM-Usage" 

81 

82#: How long the catalogue's prices are cached in-process. 

83PRICE_CACHE_S = 300.0 

84 

85 

86#: ``LLMCall.status`` values. 

87CALL_SUCCESS = "success" 

88CALL_ERROR = "error" 

89 

90#: Longest error message kept on a failed call. 

91CALL_ERROR_MAX_CHARS = 500 

92 

93#: Longest step label kept on a call (``llm_invocation_calls.step``). 

94STEP_MAX_CHARS = 64 

95 

96 

97class Step(StrEnum): 

98 """What a call that is not a structured call was for. A structured call 

99 is labelled with its own ``purpose`` (``__gate__``, ``retrieval.reranker`` 

100 …); these are the rest, so every call a turn makes says why it was made. 

101 """ 

102 

103 #: A worker producing its answer — every round of its tool loop, and the 

104 #: final answer it is asked for when the loop runs out. 

105 respond = "respond" 

106 #: Asking a reply the provider cut off at the token cap to carry on. 

107 continuation = "continuation" 

108 #: Condensing a turn into the memory the agent keeps of it. 

109 memory_summary = "memory_summary" 

110 #: Embedding a request to find the memories it bears on. 

111 memory_recall = "memory_recall" 

112 #: Embedding what the agent keeps of a turn, so recall can find it. 

113 memory_index = "memory_index" 

114 #: An LLM router deciding which edge a skill graph takes. 

115 route = "route" 

116 

117 

118_STEP: contextvars.ContextVar[str | None] = contextvars.ContextVar( 

119 "metering_step", default=None 

120) 

121_PASS: contextvars.ContextVar[int | None] = contextvars.ContextVar( 

122 "metering_pass", default=None 

123) 

124 

125 

126@contextmanager 

127def step(name: str | None) -> Iterator[None]: 

128 """Label every call made inside the block with ``name`` — a nested 

129 block's label wins for its own calls.""" 

130 token = _STEP.set(str(name) if name else None) 

131 try: 

132 yield 

133 finally: 

134 _STEP.reset(token) 

135 

136 

137def current_step() -> str | None: 

138 """The label the caller's calls are made under, if any.""" 

139 return _STEP.get() 

140 

141 

142@contextmanager 

143def graph_pass(index: int | None) -> Iterator[None]: 

144 """Mark every call made inside the block as made on pass ``index`` of a 

145 graph run (0 first; each revision after the quality check adds one).""" 

146 token = _PASS.set(index if isinstance(index, int) else None) 

147 try: 

148 yield 

149 finally: 

150 _PASS.reset(token) 

151 

152 

153@dataclass 

154class LLMCall: 

155 provider: str 

156 model: str 

157 input_tokens: int = 0 

158 output_tokens: int = 0 

159 #: ``chat`` or ``embedding``. 

160 kind: str = "chat" 

161 #: The graph node that made the call, or None outside a graph. 

162 node: str | None = None 

163 #: What the code in that node was doing (:func:`step`) — a structured 

164 #: call's purpose (``retrieval.reranker``), or one of :class:`Step`. A 

165 #: node makes several kinds of call, and the node alone cannot say which 

166 #: of them the tokens went on. None for a call nothing labelled. 

167 step: str | None = None 

168 #: Which pass through the graph made it: 0 the first, 1 the first 

169 #: revision after the quality check, … (:func:`graph_pass`). None 

170 #: outside a graph. 

171 pass_index: int | None = None 

172 latency_ms: int | None = None 

173 #: ``CALL_SUCCESS`` or ``CALL_ERROR``. 

174 status: str = CALL_SUCCESS 

175 error: str | None = None 

176 #: The rest of the provider's breakdown — see ``TokenUsage``. All are 

177 #: part of ``input_tokens`` / ``output_tokens``, not added to them. 

178 cache_read_tokens: int = 0 

179 cache_write_tokens: int = 0 

180 cache_write_1h_tokens: int = 0 

181 reasoning_tokens: int = 0 

182 modifiers: tuple[str, ...] = () 

183 #: False when the provider reported no usage for a call that was made. 

184 usage_reported: bool = True 

185 

186 @property 

187 def usage(self) -> TokenUsage: 

188 return TokenUsage( 

189 input_tokens=self.input_tokens, 

190 output_tokens=self.output_tokens, 

191 cache_read_tokens=self.cache_read_tokens, 

192 cache_write_tokens=self.cache_write_tokens, 

193 cache_write_1h_tokens=self.cache_write_1h_tokens, 

194 reasoning_tokens=self.reasoning_tokens, 

195 modifiers=self.modifiers, 

196 reported=self.usage_reported, 

197 ) 

198 

199 

200@dataclass 

201class UsageMeter: 

202 """Every model call made while serving one request.""" 

203 

204 calls: list[LLMCall] = field(default_factory=list) 

205 _lock: threading.Lock = field(default_factory=threading.Lock, repr=False) 

206 #: How many of ``calls`` a trace row has already taken. 

207 _claimed: int = field(default=0, repr=False) 

208 #: What the calls so far count as against a limit (``enforcement_usd``). 

209 _enforcement: Decimal = field(default=Decimal(0), repr=False) 

210 

211 @property 

212 def enforcement_usd(self) -> Decimal: 

213 """What this request's calls count as against a spending limit: each 

214 successful call at its price, or at the dearest catalogue rates when 

215 it could not be priced (``ceiling_estimate``) — the rule the 

216 deployment's ceiling and svc-core's cost caps count by. A refused 

217 call counts nothing.""" 

218 with self._lock: 

219 return self._enforcement 

220 

221 def _count(self, cost: Decimal) -> None: 

222 with self._lock: 

223 self._enforcement += cost 

224 

225 def record( 

226 self, 

227 provider: str, 

228 model: str, 

229 input_tokens: int = 0, 

230 output_tokens: int = 0, 

231 kind: str = "chat", 

232 *, 

233 node: str | None = None, 

234 step: str | None = None, 

235 pass_index: int | None = None, 

236 latency_ms: int | None = None, 

237 status: str = CALL_SUCCESS, 

238 error: str | None = None, 

239 usage: TokenUsage | None = None, 

240 ) -> LLMCall: 

241 """Record one call. ``usage`` is the provider's full breakdown and 

242 takes the place of ``input_tokens`` / ``output_tokens`` when given.""" 

243 if not provider or not model: 

244 # Every call site names the model it built; one that does not is 

245 # a bug to find, not a row to store as "unknown". 

246 logger.warning( 

247 "[metering] call recorded without a model identity: %r/%r", 

248 provider, 

249 model, 

250 ) 

251 if usage is None: 

252 usage = TokenUsage( 

253 input_tokens=int(input_tokens or 0), 

254 output_tokens=int(output_tokens or 0), 

255 ) 

256 with self._lock: 

257 call = LLMCall( 

258 provider=str(provider or ""), 

259 model=str(model or ""), 

260 input_tokens=usage.input_tokens, 

261 output_tokens=usage.output_tokens, 

262 kind=kind, 

263 node=node or None, 

264 step=(step or None) and str(step)[:STEP_MAX_CHARS], 

265 pass_index=pass_index, 

266 latency_ms=latency_ms, 

267 status=status, 

268 error=(error or "")[:CALL_ERROR_MAX_CHARS] or None, 

269 cache_read_tokens=usage.cache_read_tokens, 

270 cache_write_tokens=usage.cache_write_tokens, 

271 cache_write_1h_tokens=usage.cache_write_1h_tokens, 

272 reasoning_tokens=usage.reasoning_tokens, 

273 modifiers=usage.modifiers, 

274 usage_reported=usage.reported, 

275 ) 

276 self.calls.append(call) 

277 return call 

278 

279 def claim(self) -> list[LLMCall]: 

280 """The calls no trace row has taken yet — now taken. 

281 

282 A request normally writes one trace row; one that writes two must 

283 not put the same call on both. 

284 """ 

285 with self._lock: 

286 calls = self.calls[self._claimed :] 

287 self._claimed = len(self.calls) 

288 return calls 

289 

290 def summary(self) -> dict[str, Any]: 

291 """Totals, cost and a per-model breakdown — the wire shape. 

292 

293 Failed calls are left out: they are on the trace, but a provider does 

294 not bill a refused request, and ``calls`` here is what svc-core 

295 ledgers as the calls that did work. 

296 

297 ``unpriced_estimate_usd`` is what the unpriced calls are taken to have 

298 cost when a limit is judged — their tokens at the catalogue's dearest 

299 rates (``ceiling_estimate``), the rule the deployment's ceiling 

300 counts them by — so an unpriced model cannot spend round a cost cap 

301 either. It is never part of ``estimated_cost_usd``, which stays what 

302 was measured; None when every call was priced. 

303 """ 

304 with self._lock: 

305 calls = [c for c in self.calls if c.status == CALL_SUCCESS] 

306 by_model: dict[tuple[str, str, str], dict[str, Any]] = {} 

307 total_cost = Decimal(0) 

308 unpriced_estimate = Decimal(0) 

309 priced = unpriced = 0 

310 for call in calls: 

311 key = (call.provider, call.model, call.kind) 

312 row = by_model.setdefault( 

313 key, 

314 { 

315 "provider": call.provider, 

316 "model": call.model, 

317 "kind": call.kind, 

318 "calls": 0, 

319 "prompt_tokens": 0, 

320 "completion_tokens": 0, 

321 "cache_read_tokens": 0, 

322 "cache_write_tokens": 0, 

323 "estimated_cost_usd": None, 

324 "unpriced_calls": 0, 

325 }, 

326 ) 

327 row["calls"] += 1 

328 row["prompt_tokens"] += call.input_tokens 

329 row["completion_tokens"] += call.output_tokens 

330 row["cache_read_tokens"] += call.cache_read_tokens 

331 row["cache_write_tokens"] += ( 

332 call.cache_write_tokens + call.cache_write_1h_tokens 

333 ) 

334 cost = price_call(call) 

335 if cost is None: 

336 unpriced += 1 

337 row["unpriced_calls"] += 1 

338 unpriced_estimate += ceiling_estimate(call) 

339 continue 

340 priced += 1 

341 total_cost += cost 

342 row["estimated_cost_usd"] = float( 

343 Decimal(str(row["estimated_cost_usd"] or 0)) + cost 

344 ) 

345 prompt = sum(c.input_tokens for c in calls) 

346 completion = sum(c.output_tokens for c in calls) 

347 return { 

348 "calls": len(calls), 

349 "prompt_tokens": prompt, 

350 "completion_tokens": completion, 

351 "total_tokens": prompt + completion, 

352 "cache_read_tokens": sum(c.cache_read_tokens for c in calls), 

353 "cache_write_tokens": sum( 

354 c.cache_write_tokens + c.cache_write_1h_tokens for c in calls 

355 ), 

356 "estimated_cost_usd": float(total_cost) if priced else None, 

357 "unpriced_calls": unpriced, 

358 "unpriced_estimate_usd": float(unpriced_estimate) if unpriced else None, 

359 "by_model": list(by_model.values()), 

360 } 

361 

362 

363_METER: contextvars.ContextVar[UsageMeter | None] = contextvars.ContextVar( 

364 "llm_usage_meter", default=None 

365) 

366 

367 

368def current_meter() -> UsageMeter | None: 

369 return _METER.get() 

370 

371 

372@contextmanager 

373def metering() -> Iterator[UsageMeter]: 

374 """Open a meter for the enclosed work — a request, or a background job.""" 

375 meter = UsageMeter() 

376 token = _METER.set(meter) 

377 try: 

378 yield meter 

379 finally: 

380 _METER.reset(token) 

381 

382 

383def record( 

384 provider: str, 

385 model: str, 

386 input_tokens: int = 0, 

387 output_tokens: int = 0, 

388 kind: str = "chat", 

389 **detail: Any, 

390) -> None: 

391 """Record one call on the current request's meter, if there is one, and 

392 count its cost against the deployment's spending ceiling either way. 

393 

394 ``detail`` is ``UsageMeter.record``'s keywords: node, step, pass, 

395 latency, status. A step or pass not given is the one the caller is in 

396 (:func:`step`, :func:`graph_pass`). 

397 """ 

398 detail.setdefault("step", _STEP.get()) 

399 detail.setdefault("pass_index", _PASS.get()) 

400 meter = _METER.get() 

401 # A call outside any request still costs money: count it on a meter of 

402 # its own, which nothing claims. 

403 meter = meter or UsageMeter() 

404 call = meter.record(provider, model, input_tokens, output_tokens, kind, **detail) 

405 account(call, meter) 

406 

407 

408def account(call: LLMCall, meter: UsageMeter | None = None) -> None: 

409 """Add a call's cost to the spending ceiling's totals, and to the 

410 request's own count against its limit (``meter``). 

411 

412 A refused call costs nothing. A call that cannot be priced counts at the 

413 dearest rates in the catalogue, so an unpriced model cannot spend round 

414 the ceiling or a budget. Never raises: metering must not break a call. 

415 """ 

416 if call.status != CALL_SUCCESS: 

417 return 

418 try: 

419 from app.services import spend_guard 

420 

421 cost = price_call(call) 

422 if cost is None: 

423 cost = ceiling_estimate(call) 

424 if meter is not None: 

425 meter._count(cost) 

426 spend_guard.guard().account(cost) 

427 except Exception: # noqa: BLE001 — metering must never break a call 

428 logger.warning("[metering] could not count a call's spend", exc_info=True) 

429 

430 

431#: Per-token rates for an unpriced call when the catalogue cannot be read — 

432#: above every seeded model's, so the estimate errs high. 

433FALLBACK_INPUT_RATE = Decimal("0.000015") 

434FALLBACK_OUTPUT_RATE = Decimal("0.000075") 

435 

436 

437def ceiling_estimate(call: LLMCall) -> Decimal: 

438 """An upper estimate of an unpriced call: its tokens at the dearest 

439 input and output rates in the catalogue.""" 

440 cards = list(_catalogue_prices().values()) 

441 inputs = [c.input for c in cards if c.input is not None] 

442 outputs = [c.output for c in cards if c.output is not None] 

443 input_rate = max(inputs, default=FALLBACK_INPUT_RATE) 

444 output_rate = max(outputs, default=FALLBACK_OUTPUT_RATE) 

445 return call.input_tokens * input_rate + call.output_tokens * output_rate 

446 

447 

448def claim_calls() -> list[LLMCall]: 

449 """The current meter's unclaimed calls (see ``UsageMeter.claim``).""" 

450 meter = _METER.get() 

451 return meter.claim() if meter is not None else [] 

452 

453 

454def elapsed_ms(started: float) -> int: 

455 """Milliseconds since a ``time.monotonic()`` reading.""" 

456 return int((time.monotonic() - started) * 1000) 

457 

458 

459def merge_into_usage(usage: dict[str, Any] | None) -> dict[str, Any]: 

460 """``usage`` with the current meter's figures in place of the engine's. 

461 

462 Under a meter, cost comes from the meter alone: an engine's own estimate 

463 prices its summed counts at two rates, which is wrong for any call with 

464 cache or long-context tokens. When the meter saw no call, the engine's 

465 token counts are kept (they describe calls that escaped the meter) but 

466 its cost is dropped — unpriced, not guessed. 

467 """ 

468 usage = dict(usage or {}) 

469 meter = _METER.get() 

470 if meter is None: 

471 return usage 

472 summary = meter.summary() 

473 if not summary["calls"]: 

474 if "estimated_cost_usd" in usage: 

475 usage["estimated_cost_usd"] = None 

476 return usage 

477 usage.update( 

478 { 

479 "prompt_tokens": summary["prompt_tokens"], 

480 "completion_tokens": summary["completion_tokens"], 

481 "total_tokens": summary["total_tokens"], 

482 "cache_read_tokens": summary["cache_read_tokens"], 

483 "cache_write_tokens": summary["cache_write_tokens"], 

484 "estimated_cost_usd": summary["estimated_cost_usd"], 

485 "calls": summary["calls"], 

486 "unpriced_calls": summary["unpriced_calls"], 

487 "unpriced_estimate_usd": summary["unpriced_estimate_usd"], 

488 "by_model": summary["by_model"], 

489 } 

490 ) 

491 return usage 

492 

493 

494# ── LangChain ──────────────────────────────────────────────────────────────── 

495 

496 

497def _graph_node(metadata: dict | None) -> str | None: 

498 """The graph node a LangChain run belongs to, from LangGraph's metadata. 

499 

500 The outermost node of the checkpoint namespace (``outer:<task>|inner:…``) 

501 — the node the graph was built with, even if it runs a graph of its own — 

502 then ``langgraph_node``. None for a call made outside any graph. 

503 """ 

504 metadata = metadata or {} 

505 namespace = str(metadata.get("langgraph_checkpoint_ns") or "") 

506 outer = namespace.split("|", 1)[0].split(":", 1)[0] 

507 node = outer or metadata.get("langgraph_node") 

508 return str(node) if node else None 

509 

510 

511class TurnSpendLimitReached(model_errors.ModelUnavailableError): 

512 """A model call refused because the request has spent its limit — what 

513 svc-core said was left of a budget governing the turn 

514 (``app.common.spend_limit``).""" 

515 

516 def __init__(self, limit: Decimal, spent: Decimal) -> None: 

517 super().__init__(model_errors.FatalKind.TURN_LIMIT, None, "") 

518 self.args = (f"turn spending limit of ${limit} reached (${spent} spent)",) 

519 self.limit = limit 

520 self.spent = spent 

521 

522 def payload(self) -> dict[str, object]: 

523 return { 

524 **super().payload(), 

525 "limit_usd": float(self.limit), 

526 "spent_usd": float(self.spent), 

527 } 

528 

529 

530def check_limits() -> None: 

531 """Refuse the coming call if a limit is reached: the deployment's 

532 spending ceiling (``spend_guard``), or the request's own limit — what 

533 svc-core said was left of the budgets governing the turn. Called before 

534 every model call is sent — a chat model's start event, a direct LiteLLM 

535 call, an embedding — so the calls already made finish and the next one 

536 is never sent. The last call can pass a limit by its own cost, which its 

537 ``max_tokens`` bounds.""" 

538 from app.common import spend_limit 

539 from app.services import spend_guard 

540 

541 spend_guard.check() 

542 limit = spend_limit.current() 

543 meter = _METER.get() 

544 if limit is None or meter is None: 

545 return 

546 spent = meter.enforcement_usd 

547 if spent >= limit: 

548 logger.warning( 

549 "[spend] turn limit of $%s reached ($%s spent) — refusing the next call", 

550 limit, 

551 spent, 

552 ) 

553 raise TurnSpendLimitReached(limit, spent) 

554 

555 

556class MeterCallback(BaseCallbackHandler): 

557 """Records each call of the chat model it is attached to. 

558 

559 Bound to the model at construction, so the call is attributed to the 

560 model that was actually configured rather than to whatever name the 

561 provider echoes back. The start event supplies the graph node and the 

562 clock; the end or error event records the call. 

563 """ 

564 

565 #: Run in the calling task rather than an executor: it only appends to a 

566 #: list, and inline keeps it in the request's context. 

567 run_inline = True 

568 #: Let a spending limit's refusal through (``check_limits``): LangChain 

569 #: swallows a callback's error otherwise. Every other handler here 

570 #: catches its own. 

571 raise_error = True 

572 

573 def __init__(self, provider: str, model: str) -> None: 

574 self.provider = provider 

575 self.model = model 

576 #: run id → (graph node, monotonic start, step, pass) for calls in flight. 

577 self._runs: dict[Any, tuple[str | None, float, str | None, int | None]] = {} 

578 

579 def _start(self, run_id: Any, metadata: dict | None) -> None: 

580 # The step and pass are read here, in the caller's context, where the 

581 # code making the call set them. 

582 self._runs[run_id] = ( 

583 _graph_node(metadata), 

584 time.monotonic(), 

585 _STEP.get(), 

586 _PASS.get(), 

587 ) 

588 

589 def _finish(self, run_id: Any) -> dict[str, Any]: 

590 node, started, step_name, pass_index = self._runs.pop( 

591 run_id, (None, None, None, None) 

592 ) 

593 return { 

594 "node": node, 

595 "step": step_name, 

596 "pass_index": pass_index, 

597 "latency_ms": elapsed_ms(started) if started is not None else None, 

598 } 

599 

600 def on_chat_model_start( 

601 self, 

602 serialized: Any, 

603 messages: Any, 

604 *, 

605 run_id: Any = None, 

606 metadata: dict | None = None, 

607 **kwargs: Any, 

608 ) -> None: 

609 check_limits() 

610 self._start(run_id, metadata) 

611 

612 def on_llm_start( 

613 self, 

614 serialized: Any, 

615 prompts: Any, 

616 *, 

617 run_id: Any = None, 

618 metadata: dict | None = None, 

619 **kwargs: Any, 

620 ) -> None: 

621 check_limits() 

622 self._start(run_id, metadata) 

623 

624 def on_llm_end(self, response: Any, *, run_id: Any = None, **kwargs: Any) -> None: 

625 try: 

626 detail = self._finish(run_id) 

627 usage = provider_usage.from_langchain_result(response) 

628 record(self.provider, self.model, usage=usage, **detail) 

629 except Exception: # noqa: BLE001 — metering must never break a call 

630 logger.warning("[metering] could not read usage", exc_info=True) 

631 

632 def on_llm_error( 

633 self, error: BaseException, *, run_id: Any = None, **kwargs: Any 

634 ) -> None: 

635 try: 

636 record( 

637 self.provider, 

638 self.model, 

639 status=CALL_ERROR, 

640 error=f"{type(error).__name__}: {error}", 

641 **self._finish(run_id), 

642 ) 

643 except Exception: # noqa: BLE001 — metering must never break a call 

644 logger.warning("[metering] could not record a failed call", exc_info=True) 

645 

646 

647def attach(llm: Any, provider: str, model: str) -> Any: 

648 """Attach a ``MeterCallback`` to a chat model, keeping its own callbacks.""" 

649 existing = list(getattr(llm, "callbacks", None) or []) 

650 if any(isinstance(cb, MeterCallback) for cb in existing): 

651 return llm 

652 try: 

653 llm.callbacks = [*existing, MeterCallback(provider, model)] 

654 except Exception: # noqa: BLE001 — a model that refuses callbacks is unmetered 

655 logger.warning("[metering] could not attach to %s/%s", provider, model) 

656 return llm 

657 

658 

659# ── Pricing ────────────────────────────────────────────────────────────────── 

660 

661_prices: dict[tuple[str, str], PriceCard] = {} 

662_prices_loaded_at = 0.0 

663_prices_lock = threading.Lock() 

664 

665 

666def _catalogue_prices() -> dict[tuple[str, str], PriceCard]: 

667 """``(provider, model) → PriceCard`` from the catalogue, cached. 

668 

669 Archived models included: a call to one is priced like any other. 

670 """ 

671 global _prices, _prices_loaded_at 

672 with _prices_lock: 

673 if time.monotonic() - _prices_loaded_at < PRICE_CACHE_S: 

674 return _prices 

675 try: 

676 from app.db.postgres.engine import SessionLocal 

677 from app.db.postgres.models import LLMModel, Provider 

678 

679 db = SessionLocal() 

680 try: 

681 rows = ( 

682 db.query(Provider.name, LLMModel) 

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

684 .all() 

685 ) 

686 _prices = { 

687 ( 

688 str(getattr(provider, "value", provider)), 

689 str(model.model_name), 

690 ): (catalogue_card(model)) 

691 for provider, model in rows 

692 } 

693 finally: 

694 db.close() 

695 except Exception: # noqa: BLE001 — fall back to LiteLLM's table 

696 logger.warning("[metering] could not load catalogue prices", exc_info=True) 

697 _prices_loaded_at = time.monotonic() 

698 return _prices 

699 

700 

701def catalogue_card(model: Any) -> PriceCard: 

702 """The price card a catalogue model row describes.""" 

703 

704 def rate(name: str) -> Decimal | None: 

705 value = getattr(model, name, None) 

706 return Decimal(str(value)) if value is not None else None 

707 

708 return PriceCard( 

709 input=rate("input_cost_per_token"), 

710 output=rate("output_cost_per_token"), 

711 cache_read=rate("cache_read_cost_per_token"), 

712 cache_write=rate("cache_write_cost_per_token"), 

713 cache_write_1h=rate("cache_write_1h_cost_per_token"), 

714 long_context_threshold=getattr(model, "long_context_threshold", None), 

715 long_context_input_multiplier=rate("long_context_input_multiplier") 

716 or Decimal(1), 

717 long_context_output_multiplier=rate("long_context_output_multiplier") 

718 or Decimal(1), 

719 source="catalogue", 

720 ) 

721 

722 

723def price_detail(call: LLMCall) -> Priced: 

724 """A call's cost, the rates behind it, or why it has none. 

725 

726 The catalogue's card when it can price every token class the call used; 

727 otherwise LiteLLM's, for a model registered without cache or long-context 

728 rates; otherwise unpriced, with the catalogue's reason. 

729 """ 

730 usage = call.usage 

731 cards = [ 

732 _catalogue_prices().get((call.provider, call.model)), 

733 provider_usage.litellm_card(call.provider, call.model), 

734 ] 

735 first: Priced | None = None 

736 for card in cards: 

737 if card is None: 

738 continue 

739 priced = provider_usage.price(usage, card) 

740 if priced.cost is not None: 

741 return priced 

742 first = first or priced 

743 return first or provider_usage.price(usage, None) 

744 

745 

746def price_call(call: LLMCall) -> Decimal | None: 

747 """USD for one call, or None when it cannot be priced exactly.""" 

748 return price_detail(call).cost 

749 

750 

751# ── ASGI middleware ────────────────────────────────────────────────────────── 

752 

753 

754#: Called with the calls a request left unclaimed, its method and its path. 

755UnclaimedHandler = Callable[[list[LLMCall], str, str], None] 

756 

757 

758class LLMUsageMiddleware: 

759 """One meter per HTTP request; its summary goes out as ``X-LLM-Usage``. 

760 

761 A pure ASGI middleware rather than ``BaseHTTPMiddleware``: the header is 

762 written when the response *starts*, which for a JSON response is after the 

763 endpoint has finished — so the meter is complete. A streaming response 

764 starts before its work does; streams report usage on their ``done`` frame 

765 instead, and send the header only if something was already metered. 

766 

767 Once the request is over — the stream drained, background tasks run — 

768 any call no trace row claimed is logged and handed to ``on_unclaimed`` 

769 (svc-ai passes ``conversation.trace_unclaimed``), so a model call an 

770 endpoint forgot to trace is still on record rather than lost. 

771 """ 

772 

773 def __init__(self, app: Any, on_unclaimed: UnclaimedHandler | None = None) -> None: 

774 self.app = app 

775 self.on_unclaimed = on_unclaimed 

776 

777 async def __call__(self, scope: dict, receive: Any, send: Any) -> None: 

778 if scope.get("type") != "http": 

779 await self.app(scope, receive, send) 

780 return 

781 with metering() as meter: 

782 

783 async def send_with_usage(message: dict) -> None: 

784 if message.get("type") == "http.response.start" and meter.calls: 

785 summary = meter.summary() 

786 if summary["calls"]: 

787 headers = list(message.get("headers") or []) 

788 headers.append( 

789 ( 

790 USAGE_HEADER.lower().encode(), 

791 json.dumps(summary).encode(), 

792 ) 

793 ) 

794 message = {**message, "headers": headers} 

795 await send(message) 

796 

797 try: 

798 await self.app(scope, receive, send_with_usage) 

799 finally: 

800 await self._trace_leftovers(meter, scope) 

801 

802 async def _trace_leftovers(self, meter: UsageMeter, scope: dict) -> None: 

803 leftover = meter.claim() 

804 if not leftover: 

805 return 

806 method, path = str(scope.get("method", "")), str(scope.get("path", "")) 

807 logger.warning( 

808 "[metering] %d model call(s) on %s %s were not traced by the " 

809 "endpoint; recording them as untraced", 

810 len(leftover), 

811 method, 

812 path, 

813 ) 

814 if self.on_unclaimed is None: 

815 return 

816 try: 

817 from starlette.concurrency import run_in_threadpool 

818 

819 await run_in_threadpool(self.on_unclaimed, leftover, method, path) 

820 except Exception: # noqa: BLE001 — tracing must never break a request 

821 logger.exception("[metering] could not trace unclaimed calls") 

822 

823 

824#: SSE frames that end a stream's work and so report what it cost: ``done``; 

825#: ``hitl_interrupt`` — a paused run has already spent what it spent; and 

826#: ``error`` — a run that failed after its first calls was paid for all the 

827#: same, and svc-core ledgers the failed turn with what it cost. 

828TERMINAL_FRAMES = frozenset({"done", "hitl_interrupt", "error"}) 

829 

830 

831def meter_frame(chunk: str) -> str: 

832 """An SSE chunk, with the meter's usage on it if it ends the stream.""" 

833 if not chunk.startswith("data: ") or not (meter := _METER.get()) or not meter.calls: 

834 return chunk 

835 try: 

836 data = json.loads(chunk[6:].rstrip("\n")) 

837 except ValueError: 

838 return chunk 

839 if not isinstance(data, dict) or data.get("type") not in TERMINAL_FRAMES: 

840 return chunk 

841 data["usage"] = merge_into_usage(data.get("usage")) 

842 return f"data: {json.dumps(data, default=str)}\n\n"