Coverage for app / services / provider_usage.py: 95%

218 statements  

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

1""" 

2What a model call actually cost, from what the provider reported. 

3 

4Neither OpenAI nor Anthropic returns a cost on an inference response. What 

5each returns is a *usage breakdown* — and every class of token in it has its 

6own published rate. Pricing ``prompt_tokens × input rate + completion_tokens 

7× output rate`` is wrong whenever any of the other classes appear, which in 

8an agent loop is almost always: 

9 

10================== ========================================================== 

11Token class How each provider reports and bills it 

12================== ========================================================== 

13Cache reads OpenAI ``*_tokens_details.cached_tokens`` (inside the 

14 prompt total); Anthropic ``cache_read_input_tokens`` 

15 (outside it). Billed at a per-model rate — 0.1× input on 

16 most models, 0.05× or 0.025× on some, 0.5× on GPT-4o. 

17Cache writes OpenAI ``cache_write_tokens`` (GPT-5.6 and later: 1.25× 

18 input); Anthropic ``cache_creation_input_tokens``, split 

19 by TTL — 5 minutes at 1.25×, 1 hour at 2×. 

20Reasoning/thinking Already inside the output count, billed as output. 

21Long context OpenAI: past 272K prompt tokens the *whole request* is 

22 repriced (input classes 2×, output 1.5×). Claude 4.6 and 

23 later bill the full window at standard rates. 

24Service tier etc. Flex/priority/fast/ultrafast tiers, Anthropic fast mode, 

25 server-tool charges and multi-attempt ``iterations`` 

26 change the bill in ways the token counts do not show. 

27 (US-only inference and regional processing follow 

28 request parameters svc-ai never sends.) 

29================== ========================================================== 

30 

31So a call is priced from a ``TokenUsage`` (every class the provider reported) 

32against a ``PriceCard`` (every rate the model has): the catalogue's card 

33first — the figures cost caps are written against — then LiteLLM's price map 

34for a model registered without one. A call is **unpriced** rather than 

35guessed whenever the provider reported no usage, reported a tier or modifier 

36the platform does not price, or used a token class the card has no rate for. 

37 

38The provider's billing APIs (OpenAI's Costs API, Anthropic's Usage & Cost 

39Admin API) report cost per day, model and key — not per request — and need 

40an admin key; they are the place to reconcile these figures, not to source 

41them. 

42""" 

43 

44from __future__ import annotations 

45 

46import re 

47from dataclasses import dataclass, field 

48from decimal import Decimal 

49from typing import Any, Mapping 

50 

51#: Tiers billed at a model's standard rates, as each provider reports them. 

52STANDARD_TIERS = frozenset({"", "default", "standard"}) 

53 

54 

55@dataclass(frozen=True) 

56class TokenUsage: 

57 """Every class of token one call consumed, as the provider reported it.""" 

58 

59 #: Every prompt token — cached, written to cache, or neither. 

60 input_tokens: int = 0 

61 #: Every generated token, reasoning / thinking included. 

62 output_tokens: int = 0 

63 cache_read_tokens: int = 0 

64 #: Cache writes at the standard write rate (OpenAI; Anthropic's 5-minute). 

65 cache_write_tokens: int = 0 

66 #: Anthropic writes to the 1-hour cache, billed at their own rate. 

67 cache_write_1h_tokens: int = 0 

68 #: Part of ``output_tokens``; reported, not priced separately. 

69 reasoning_tokens: int = 0 

70 #: Anything that bills at other than standard rates — ``service_tier: 

71 #: priority``, ``speed: fast``, ``inference_geo: us``, server-tool 

72 #: charges, multi-attempt iterations. A call with any is unpriced. 

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

74 #: False when the provider sent no usage at all — not a free call. 

75 reported: bool = True 

76 

77 @property 

78 def cache_writes(self) -> int: 

79 return self.cache_write_tokens + self.cache_write_1h_tokens 

80 

81 @property 

82 def uncached_input_tokens(self) -> int: 

83 return max(0, self.input_tokens - self.cache_read_tokens - self.cache_writes) 

84 

85 

86UNREPORTED = TokenUsage(reported=False) 

87 

88 

89def _int(value: Any) -> int: 

90 try: 

91 return max(0, int(value or 0)) 

92 except (TypeError, ValueError): 

93 return 0 

94 

95 

96def _get(obj: Any, key: str) -> Any: 

97 if obj is None: 

98 return None 

99 if isinstance(obj, Mapping): 

100 return obj.get(key) 

101 return getattr(obj, key, None) 

102 

103 

104def _tier_modifier(tier: Any) -> tuple[str, ...]: 

105 tier = str(tier or "").strip().lower() 

106 return () if tier in STANDARD_TIERS else (f"service_tier:{tier}",) 

107 

108 

109# ── Provider payloads ──────────────────────────────────────────────────────── 

110 

111 

112def from_openai(usage: Any, service_tier: Any = None) -> TokenUsage: 

113 """An OpenAI ``usage`` object — Chat Completions or Responses shape. 

114 

115 Cached and cache-write tokens are inside the prompt total; reasoning 

116 tokens are inside the completion total. 

117 """ 

118 if usage is None: 

119 return UNREPORTED 

120 if _get(usage, "input_tokens") is not None or _get(usage, "prompt_tokens") is None: 

121 prompt = _get(usage, "input_tokens") 

122 completion = _get(usage, "output_tokens") 

123 in_details = _get(usage, "input_tokens_details") 

124 out_details = _get(usage, "output_tokens_details") 

125 else: 

126 prompt = _get(usage, "prompt_tokens") 

127 completion = _get(usage, "completion_tokens") 

128 in_details = _get(usage, "prompt_tokens_details") 

129 out_details = _get(usage, "completion_tokens_details") 

130 if prompt is None and completion is None: 

131 return UNREPORTED 

132 return TokenUsage( 

133 input_tokens=_int(prompt), 

134 output_tokens=_int(completion), 

135 cache_read_tokens=_int(_get(in_details, "cached_tokens")), 

136 cache_write_tokens=_int(_get(in_details, "cache_write_tokens")), 

137 reasoning_tokens=_int(_get(out_details, "reasoning_tokens")), 

138 modifiers=_tier_modifier(service_tier or _get(usage, "service_tier")), 

139 ) 

140 

141 

142def from_anthropic(usage: Any) -> TokenUsage: 

143 """An Anthropic ``usage`` object. 

144 

145 ``input_tokens`` there is the *uncached remainder*; the prompt is it plus 

146 cache reads plus cache writes. Writes split by TTL when the breakdown is 

147 present. 

148 """ 

149 if usage is None: 

150 return UNREPORTED 

151 uncached = _int(_get(usage, "input_tokens")) 

152 reads = _int(_get(usage, "cache_read_input_tokens")) 

153 writes = _int(_get(usage, "cache_creation_input_tokens")) 

154 by_ttl = _get(usage, "cache_creation") 

155 writes_5m, writes_1h = writes, 0 

156 if by_ttl is not None: 

157 five = _int(_get(by_ttl, "ephemeral_5m_input_tokens")) 

158 hour = _int(_get(by_ttl, "ephemeral_1h_input_tokens")) 

159 if five or hour: 

160 writes_5m, writes_1h = five, hour 

161 out_details = _get(usage, "output_tokens_details") 

162 # ``inference_geo`` on the response is where inference ran; the 1.1× 

163 # US-only rate follows the *request* parameter, which svc-ai never sets. 

164 modifiers = list(_tier_modifier(_get(usage, "service_tier"))) 

165 if str(_get(usage, "speed") or "standard") != "standard": 

166 modifiers.append(f"speed:{_get(usage, 'speed')}") 

167 server_tools = _get(usage, "server_tool_use") 

168 if server_tools is not None and _int(_get(server_tools, "web_search_requests")): 

169 modifiers.append("server_tool_use:web_search") 

170 if _get(usage, "iterations"): 

171 modifiers.append("iterations") 

172 return TokenUsage( 

173 input_tokens=uncached + reads + writes_5m + writes_1h, 

174 output_tokens=_int(_get(usage, "output_tokens")), 

175 cache_read_tokens=reads, 

176 cache_write_tokens=writes_5m, 

177 cache_write_1h_tokens=writes_1h, 

178 reasoning_tokens=_int(_get(out_details, "thinking_tokens")), 

179 modifiers=tuple(modifiers), 

180 ) 

181 

182 

183def from_litellm(usage: Any) -> TokenUsage: 

184 """A LiteLLM ``Usage`` — OpenAI-shaped for every provider. 

185 

186 LiteLLM folds Anthropic's cache reads and writes into ``prompt_tokens`` 

187 and reports them under ``prompt_tokens_details`` (``cached_tokens``, 

188 ``cache_creation_tokens`` with a 5m/1h breakdown). 

189 """ 

190 if usage is None: 

191 return UNREPORTED 

192 base = from_openai(usage) 

193 if not base.reported: 

194 return base 

195 details = _get(usage, "prompt_tokens_details") 

196 creation = _int(_get(details, "cache_creation_tokens")) or _int( 

197 _get(usage, "cache_creation_input_tokens") 

198 ) 

199 if not creation: 

200 return base 

201 by_ttl = _get(details, "cache_creation_token_details") 

202 five = _int(_get(by_ttl, "ephemeral_5m_input_tokens")) 

203 hour = _int(_get(by_ttl, "ephemeral_1h_input_tokens")) 

204 if not (five or hour): 

205 five = creation 

206 return TokenUsage( 

207 input_tokens=base.input_tokens, 

208 output_tokens=base.output_tokens, 

209 cache_read_tokens=base.cache_read_tokens, 

210 cache_write_tokens=five, 

211 cache_write_1h_tokens=hour, 

212 reasoning_tokens=base.reasoning_tokens, 

213 modifiers=base.modifiers, 

214 ) 

215 

216 

217# ── LangChain ──────────────────────────────────────────────────────────────── 

218 

219#: Prefixes langchain-openai puts on token-detail keys for a non-standard tier. 

220_TIER_PREFIXES = ("priority", "flex") 

221 

222 

223def from_langchain_result(response: Any) -> TokenUsage: 

224 """The usage of one LangChain ``LLMResult`` (a chat model's ``on_llm_end``). 

225 

226 ``usage_metadata`` is the normalised breakdown both provider packages 

227 fill, streamed or not: total input (cache classes included), output, 

228 ``cache_read`` / ``cache_creation`` / Anthropic's ``ephemeral_5m`` and 

229 ``ephemeral_1h`` writes, reasoning. The raw provider usage on 

230 ``llm_output`` (a non-streamed call) adds the tier and modifiers the 

231 normalised form leaves out. 

232 """ 

233 llm_output = getattr(response, "llm_output", None) or {} 

234 raw = llm_output.get("usage") or llm_output.get("token_usage") 

235 tier = llm_output.get("service_tier") 

236 message = None 

237 for generations in getattr(response, "generations", None) or []: 

238 for generation in generations or []: 

239 message = getattr(generation, "message", None) 

240 info = getattr(generation, "generation_info", None) or {} 

241 meta = getattr(message, "response_metadata", None) or {} 

242 tier = tier or info.get("service_tier") or meta.get("service_tier") 

243 break 

244 break 

245 

246 provider = str( 

247 llm_output.get("model_provider") 

248 or (getattr(message, "response_metadata", None) or {}).get("model_provider") 

249 or "" 

250 ) 

251 anthropic = provider == "anthropic" or ( 

252 raw is not None 

253 and any( 

254 _get(raw, key) is not None 

255 for key in ("cache_read_input_tokens", "cache_creation_input_tokens") 

256 ) 

257 ) 

258 

259 metadata = getattr(message, "usage_metadata", None) 

260 if not metadata: 

261 if raw is None: 

262 return UNREPORTED 

263 return from_anthropic(raw) if anthropic else from_openai(raw, tier) 

264 

265 inputs = dict(metadata.get("input_token_details") or {}) 

266 outputs = dict(metadata.get("output_token_details") or {}) 

267 for prefix in _TIER_PREFIXES: 

268 if f"{prefix}_cache_read" in inputs or prefix in inputs: 

269 tier = tier or prefix 

270 inputs.setdefault("cache_read", inputs.get(f"{prefix}_cache_read")) 

271 outputs.setdefault("reasoning", outputs.get(f"{prefix}_reasoning")) 

272 

273 five = _int(inputs.get("ephemeral_5m_input_tokens")) 

274 hour = _int(inputs.get("ephemeral_1h_input_tokens")) 

275 writes = five if (five or hour) else _int(inputs.get("cache_creation")) 

276 

277 modifiers = list(_tier_modifier(tier)) 

278 if raw is not None and anthropic: 

279 # Anthropic's raw usage carries the modifiers the metadata drops. 

280 modifiers += [m for m in from_anthropic(raw).modifiers if m not in modifiers] 

281 return TokenUsage( 

282 input_tokens=_int(metadata.get("input_tokens")), 

283 output_tokens=_int(metadata.get("output_tokens")), 

284 cache_read_tokens=_int(inputs.get("cache_read")), 

285 cache_write_tokens=writes, 

286 cache_write_1h_tokens=hour, 

287 reasoning_tokens=_int(outputs.get("reasoning")), 

288 modifiers=tuple(modifiers), 

289 ) 

290 

291 

292def install_openai_cache_write_mapping() -> None: 

293 """Carry OpenAI's ``cache_write_tokens`` into LangChain's usage metadata. 

294 

295 langchain-openai builds ``usage_metadata`` from the response's usage but 

296 maps only ``cached_tokens``, so the cache writes GPT-5.6 and later bill 

297 at 1.25× input never reach the meter — streamed or not, Chat Completions 

298 or Responses. This wraps its two builders to add them under 

299 ``cache_creation``, the key langchain-anthropic uses for the same thing. 

300 Idempotent; ``tests/services/test_provider_usage.py`` fails when the 

301 package maps the field itself and this can go. 

302 """ 

303 from langchain_openai.chat_models import base 

304 

305 for name, details_key in ( 

306 ("_create_usage_metadata", "prompt_tokens_details"), 

307 ("_create_usage_metadata_responses", "input_tokens_details"), 

308 ): 

309 builder = getattr(base, name) 

310 if getattr(builder, "_carries_cache_writes", False): 

311 continue 

312 setattr(base, name, _with_cache_writes(builder, details_key)) 

313 

314 

315def _with_cache_writes(builder: Any, details_key: str) -> Any: 

316 def build(oai_token_usage: dict, *args: Any, **kwargs: Any) -> Any: 

317 usage = builder(oai_token_usage, *args, **kwargs) 

318 details = (oai_token_usage or {}).get(details_key) or {} 

319 writes = ( 

320 details.get("cache_write_tokens") if isinstance(details, dict) else None 

321 ) 

322 if writes and "cache_creation" not in usage.get("input_token_details", {}): 

323 usage.setdefault("input_token_details", {})["cache_creation"] = int(writes) 

324 return usage 

325 

326 build._carries_cache_writes = True # type: ignore[attr-defined] 

327 return build 

328 

329 

330# ── Prices ─────────────────────────────────────────────────────────────────── 

331 

332 

333@dataclass(frozen=True) 

334class PriceCard: 

335 """Every rate one model bills at, USD per token, at standard tier.""" 

336 

337 input: Decimal | None 

338 output: Decimal | None 

339 cache_read: Decimal | None = None 

340 cache_write: Decimal | None = None 

341 cache_write_1h: Decimal | None = None 

342 #: Prompt size past which the whole request is repriced, or None. 

343 long_context_threshold: int | None = None 

344 long_context_input_multiplier: Decimal = Decimal(1) 

345 long_context_output_multiplier: Decimal = Decimal(1) 

346 #: Where the rates came from — ``catalogue`` or ``litellm``. 

347 source: str = "catalogue" 

348 extra: dict[str, Any] = field(default_factory=dict, compare=False) 

349 

350 def missing_rate(self, usage: TokenUsage) -> str | None: 

351 """The first token class ``usage`` has that this card cannot price.""" 

352 needed = ( 

353 ("input", self.input, usage.uncached_input_tokens), 

354 ("output", self.output, usage.output_tokens), 

355 ("cache read", self.cache_read, usage.cache_read_tokens), 

356 ("cache write", self.cache_write, usage.cache_write_tokens), 

357 ("1-hour cache write", self.cache_write_1h, usage.cache_write_1h_tokens), 

358 ) 

359 for name, rate, tokens in needed: 

360 if tokens and rate is None: 

361 return name 

362 if self.input is None and self.output is None: 

363 return "input" 

364 return None 

365 

366 

367@dataclass(frozen=True) 

368class Priced: 

369 """A call's cost, or why it has none.""" 

370 

371 cost: Decimal | None 

372 #: The rates applied (USD per token) and whether the long-context tier 

373 #: did — kept on the call row so the figure can be audited later. 

374 detail: dict[str, Any] 

375 unpriced_reason: str | None = None 

376 

377 

378def price(usage: TokenUsage, card: PriceCard | None) -> Priced: 

379 """What ``usage`` cost on ``card`` — or None, with the reason.""" 

380 if not usage.reported: 

381 return Priced(None, {}, "the provider reported no usage") 

382 if usage.modifiers: 

383 return Priced( 

384 None, 

385 {"modifiers": list(usage.modifiers)}, 

386 "billed at a non-standard rate: " + ", ".join(usage.modifiers), 

387 ) 

388 if card is None: 

389 return Priced(None, {}, "no price for this model") 

390 missing = card.missing_rate(usage) 

391 if missing: 

392 return Priced( 

393 None, {"source": card.source}, f"no {missing} rate for this model" 

394 ) 

395 

396 long = bool( 

397 card.long_context_threshold and usage.input_tokens > card.long_context_threshold 

398 ) 

399 in_x = card.long_context_input_multiplier if long else Decimal(1) 

400 out_x = card.long_context_output_multiplier if long else Decimal(1) 

401 zero = Decimal(0) 

402 cost = ( 

403 Decimal(usage.uncached_input_tokens) * (card.input or zero) 

404 + Decimal(usage.cache_read_tokens) * (card.cache_read or zero) 

405 + Decimal(usage.cache_write_tokens) * (card.cache_write or zero) 

406 + Decimal(usage.cache_write_1h_tokens) * (card.cache_write_1h or zero) 

407 ) * in_x + Decimal(usage.output_tokens) * (card.output or zero) * out_x 

408 detail: dict[str, Any] = { 

409 "source": card.source, 

410 "rates": { 

411 name: format(rate, "f") 

412 for name, rate in ( 

413 ("input", card.input), 

414 ("output", card.output), 

415 ("cache_read", card.cache_read), 

416 ("cache_write", card.cache_write), 

417 ("cache_write_1h", card.cache_write_1h), 

418 ) 

419 if rate is not None 

420 }, 

421 } 

422 if long: 

423 detail["long_context"] = { 

424 "threshold": card.long_context_threshold, 

425 "input_multiplier": format(in_x, "f"), 

426 "output_multiplier": format(out_x, "f"), 

427 } 

428 return Priced(cost, detail) 

429 

430 

431def _dec(value: Any) -> Decimal | None: 

432 if value is None: 

433 return None 

434 try: 

435 return Decimal(str(value)) 

436 except Exception: # noqa: BLE001 — an unreadable rate is no rate 

437 return None 

438 

439 

440_ABOVE = re.compile(r"^input_cost_per_token_above_(\d+)k_tokens$") 

441 

442 

443def litellm_card(provider: str, model: str) -> PriceCard | None: 

444 """A model's rates from LiteLLM's price map, standard tier only.""" 

445 try: 

446 import litellm 

447 

448 table = litellm.model_cost 

449 except Exception: # noqa: BLE001 — no table, no card 

450 return None 

451 entry = table.get(f"{provider}/{model}") or table.get(model) 

452 if not isinstance(entry, Mapping): 

453 return None 

454 input_rate = _dec(entry.get("input_cost_per_token")) 

455 output_rate = _dec(entry.get("output_cost_per_token")) 

456 if input_rate is None and output_rate is None: 

457 return None 

458 threshold, in_x, out_x = None, Decimal(1), Decimal(1) 

459 for key in entry: 

460 match = _ABOVE.match(str(key)) 

461 if match and input_rate: 

462 threshold = int(match.group(1)) * 1000 

463 in_x = (_dec(entry[key]) or input_rate) / input_rate 

464 above_out = _dec( 

465 entry.get(f"output_cost_per_token_above_{match.group(1)}k_tokens") 

466 ) 

467 out_x = (above_out / output_rate) if (above_out and output_rate) else in_x 

468 break 

469 return PriceCard( 

470 input=input_rate, 

471 output=output_rate, 

472 cache_read=_dec(entry.get("cache_read_input_token_cost")), 

473 cache_write=_dec(entry.get("cache_creation_input_token_cost")), 

474 cache_write_1h=_dec(entry.get("cache_creation_input_token_cost_above_1hr")), 

475 long_context_threshold=threshold, 

476 long_context_input_multiplier=in_x, 

477 long_context_output_multiplier=out_x, 

478 source="litellm", 

479 )