Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Studio: pricing follow-up to #5690 (longest-prefix match + chat-style usage keys) (#5722)

Daniel Han542d74370f3b
diff --git a/studio/backend/core/inference/external_provider.py b/studio/backend/core/inference/external_provider.py
index a1309ae1aca..cf050defda8 100644
--- a/studio/backend/core/inference/external_provider.py
+++ b/studio/backend/core/inference/external_provider.py
@@ -4418,6 +4418,11 @@ def _build_usage_chunk(
"cache_creation_input_tokens": cache_creation,
"cache_read_input_tokens": cache_read,
}
+ # Forward 5m/1h cache-write breakdown so cost calc applies the
+ # 2x 1h premium instead of defaulting to 5m on chat-style.
+ cc_breakdown = last_usage.get("cache_creation")
+ if isinstance(cc_breakdown, dict) and cc_breakdown:
+ usage_block["cache_creation"] = cc_breakdown
# Propagate fast-mode `usage.speed` so the cost ledger can apply
# the 6x multiplier without re-derivation (Anthropic falls back
# to "standard" when fast-mode is unsupported or rate-limited).
diff --git a/studio/backend/core/inference/pricing.py b/studio/backend/core/inference/pricing.py
index 4241f67296c..84eec17e842 100644
--- a/studio/backend/core/inference/pricing.py
+++ b/studio/backend/core/inference/pricing.py
@@ -1,50 +1,24 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""Static per-MTok pricing tables for external providers, plus a
-``calculate_cost`` helper that turns an upstream ``usage`` block into
-a USD figure for surfacing in the chat UI.
+"""Static per-MTok pricing tables and ``calculate_cost`` helper for
+turning an upstream ``usage`` block into a USD figure.
-Neither the Anthropic Messages API nor the OpenAI Responses API
-reports a ``cost`` field on the response. Both expose detailed token
-counts (input, output, cache hits, server-tool invocations); pricing
-multipliers live in the provider docs. We fold the docs into a static
-table here, multiply by the usage block, and emit a per-turn cost +
-running session total client-side.
-
-Sources (verified live 2026-05-22):
-- Anthropic models overview:
- https://platform.claude.com/docs/en/about-claude/models/overview
-- Anthropic prompt-caching multipliers (5m write 1.25x, 1h write 2x,
- read 0.1x):
- https://platform.claude.com/docs/en/build-with-claude/prompt-caching
-- Anthropic web search ($10 / 1000 searches, code execution
- free-with-paid when paired with the newer web tools):
- https://platform.claude.com/docs/en/agents-and-tools/tool-use/web-search-tool
- https://platform.claude.com/docs/en/agents-and-tools/tool-use/code-execution-tool
-- OpenAI pricing page (input / output per MTok per model family):
- https://platform.openai.com/docs/pricing
+Sources: Anthropic prompt-caching docs (5m write 1.25x, 1h write 2x,
+read 0.1x), web search ($10/1000), code execution; OpenAI pricing page.
"""
from __future__ import annotations
from typing import Any, Optional
-# Per-million-token base pricing. `cache_5m_write_mult`, `cache_1h_write_mult`,
-# `cache_read_mult` are multipliers ON `input_per_mtok` -- not absolute prices --
-# matching how Anthropic publishes them (5m write = 1.25x base, etc.).
-#
-# `input_per_mtok` and `output_per_mtok` are USD per 1,000,000 tokens.
+# Per-MTok base pricing in USD. Cache multipliers are applied ON
+# `input_per_mtok` (not absolute prices), matching Anthropic's docs.
ANTHROPIC_PRICING: dict[str, dict[str, float]] = {
"claude-opus-4-7": {"input_per_mtok": 5.0, "output_per_mtok": 25.0},
"claude-opus-4-6": {"input_per_mtok": 5.0, "output_per_mtok": 25.0},
- # Canonical 4.5 ids are referenced from backend defaults (e.g.
- # PROVIDER_REGISTRY['anthropic'].default_models) without the date
- # suffix. The dated ids ARE the canonical names per Anthropic's
- # models overview, but lookups for the bare id ("claude-opus-4-5")
- # don't prefix-match the dated key the other way around, so we
- # alias both forms here. Otherwise calculate_cost returns
- # priced=False + zero cost for the common ids.
+ # Alias both the bare id and dated id: backend defaults reference
+ # the bare form, which won't prefix-match the dated key.
"claude-opus-4-5": {"input_per_mtok": 5.0, "output_per_mtok": 25.0},
"claude-opus-4-5-20251101": {"input_per_mtok": 5.0, "output_per_mtok": 25.0},
"claude-opus-4-1": {"input_per_mtok": 15.0, "output_per_mtok": 75.0},
@@ -59,19 +33,9 @@ ANTHROPIC_PRICING: dict[str, dict[str, float]] = {
}
OPENAI_PRICING: dict[str, dict[str, float]] = {
- # All values verified against developers.openai.com/api/docs/pricing
- # 2026-05-22. Update against the live pricing page on every model launch.
- # Initial commit underbilled every gpt-5.x family 2-6x -- fixed here
- # after PR review caught it via doc cross-check.
- #
- # `long_context_input_per_mtok` / `long_context_output_per_mtok` /
- # `long_context_threshold` are populated when OpenAI publishes a
- # second pricing tier for prompts above N input tokens. gpt-5.5 and
- # gpt-5.4 cross over at 272k input tokens; the long-context rates
- # are double the headline input price (and ~1.5x on output). Other
- # families currently ship with a single rate (no `long_context_*`
- # keys = no tier crossover). Reference:
- # https://developers.openai.com/api/docs/pricing
+ # Verified against developers.openai.com/api/docs/pricing.
+ # `long_context_*` keys apply once input exceeds the threshold
+ # (gpt-5.5/5.4: 272k); families without these keys ship a single rate.
"gpt-5.5": {
"input_per_mtok": 5.0,
"output_per_mtok": 30.0,
@@ -91,14 +55,11 @@ OPENAI_PRICING: dict[str, dict[str, float]] = {
"gpt-5.4-mini": {"input_per_mtok": 0.75, "output_per_mtok": 4.5},
"gpt-5.4-nano": {"input_per_mtok": 0.20, "output_per_mtok": 1.25},
"gpt-5.3-codex": {"input_per_mtok": 1.75, "output_per_mtok": 14.0},
- # chat-latest / gpt-5.3-chat-latest is an alias for the current
- # ChatGPT model; same price as gpt-5.5.
+ # chat-latest aliases gpt-5.5.
"gpt-5.3-chat-latest": {"input_per_mtok": 5.0, "output_per_mtok": 30.0},
"chat-latest": {"input_per_mtok": 5.0, "output_per_mtok": 30.0},
- # o-series and gpt-4.5: NOT currently listed on the pricing page.
- # Removed to avoid silent-underbilling drift. Returning priced=False
- # is honest; the UI can still render token counts. Restore with
- # verified per-MTok rates if/when the page lists them again.
+ # o-series and gpt-4.5 are no longer on the pricing page; omit them
+ # so calculate_cost returns priced=False rather than silently $0.
}
# Shared multipliers (same across every Anthropic model).
@@ -109,28 +70,18 @@ ANTHROPIC_CACHE_READ_MULT = 0.1
# https://platform.claude.com/docs/en/build-with-claude/fast-mode#pricing
ANTHROPIC_FAST_MODE_MULT = 6.0
-# OpenAI: cache reads are 0.1x base input, cache writes are not billed
-# separately (the first prefix-write request just pays normal input).
+# OpenAI: cache reads 0.1x; cache writes pay normal input price.
OPENAI_CACHE_READ_MULT = 0.1
-# Server-tool surcharges.
-# Anthropic: $10 / 1000 web searches; code_execution is $0.05/hr after
-# 50 free hours/day per org (no per-org visibility here, so the
-# calculator reports the marginal rate).
+# Server-tool surcharges. Anthropic code_exec is $0.05/hr marginal
+# (50 free hours/day per org, not visible here).
ANTHROPIC_WEB_SEARCH_USD_PER_1K = 10.0
ANTHROPIC_CODE_EXEC_USD_PER_HOUR = 0.05
-# OpenAI: web_search is billed at $10/1000 calls plus the model's
-# token rate for the returned search content (already captured under
-# input/output_tokens). The hosted shell tool bills per 20-minute
-# session per container memory tier (1g/4g/16g/64g at
-# $0.03/$0.12/$0.48/$1.92). Since Studio doesn't surface the memory
-# tier in the cost ledger and most users land on the default 1g, we
-# bill the 1g rate ($0.09/hour) and let the user inspect the OpenAI
-# dashboard for the exact figure on heavier configs.
-# Source: developers.openai.com/api/docs/pricing 2026-05-22.
+# OpenAI container bills per memory tier; we report the 1g default
+# ($0.09/hour) since the tier isn't surfaced to the cost ledger.
OPENAI_WEB_SEARCH_USD_PER_1K = 10.0
-OPENAI_CONTAINER_USD_PER_HOUR = 0.09 # 1g default tier; 3 x $0.03 / 60min
+OPENAI_CONTAINER_USD_PER_HOUR = 0.09 # 1g default tier
def _lookup(provider: str, model: str) -> Optional[dict[str, float]]:
@@ -145,11 +96,13 @@ def _lookup(provider: str, model: str) -> Optional[dict[str, float]]:
return None
if model in table:
return table[model]
- # Fall back to a prefix match so date-suffixed snapshots
- # ("gpt-5.5-2026-04-23") inherit the canonical-id prices.
- for key, val in table.items():
- if model.startswith(key):
- return val
+ # Longest-prefix match on a dash boundary: lets dated snapshots
+ # inherit canonical prices while preventing "claude-opus-4-15"
+ # from matching "claude-opus-4-1" or "gpt-5.5-prod" from matching
+ # "gpt-5.5-pro". Sort longest-first to pick the most specific row.
+ for key in sorted(table, key = len, reverse = True):
+ if model.startswith(key) and (len(model) == len(key) or model[len(key)] == "-"):
+ return table[key]
return None
@@ -158,28 +111,11 @@ def calculate_cost(
model: str,
usage: dict[str, Any],
) -> dict[str, float]:
- """Return a per-turn USD cost breakdown.
-
- Returns a dict with the per-bucket cost AND the totals so the
- frontend can render either a single number or a "where did the
- money go" tooltip without re-doing the math:
-
- {
- "input_usd": 0.0042,
- "output_usd": 0.012,
- "cache_write_usd": 0.0001,
- "cache_read_usd": 0.0008,
- "server_tools_usd": 0.01,
- "total_usd": 0.0271,
- "billable_input_tokens": 5023, # input + cache_create + cache_read
- "billable_output_tokens": 480,
- "model_priced": "claude-opus-4-7",
- "priced": true,
- }
-
- When the model isn't in the static table (new family, custom base
- URL), `priced` is False and every USD field is 0.0; the frontend
- can still show the token counts.
+ """Return a per-turn USD cost breakdown with per-bucket + total
+ fields so the frontend can render either a single number or a
+ tooltip without re-doing the math. When the model isn't in the
+ static table, ``priced`` is False and USD fields are 0.0 (token
+ counts still report).
"""
prices = _lookup(provider, model)
out: dict[str, float] = {
@@ -195,34 +131,64 @@ def calculate_cost(
"priced": bool(prices),
}
- input_tokens = int(usage.get("input_tokens") or 0)
- output_tokens = int(usage.get("output_tokens") or 0)
- cache_creation = int(usage.get("cache_creation_input_tokens") or 0)
- cache_read = int(usage.get("cache_read_input_tokens") or 0)
- # OpenAI Responses reports cached tokens under input_tokens_details
- # but ALSO folds them into the top-level input_tokens, so we don't
- # add cache_read into the billable total again below (Anthropic
- # excludes cache buckets from input_tokens, OpenAI includes them --
- # the two providers differ here and the calculator must match).
- if provider == "openai":
- details = usage.get("input_tokens_details") or {}
+ # Accept raw (input_tokens/output_tokens) and Studio chat-style
+ # (prompt_tokens/completion_tokens) envelopes. Cache buckets
+ # behave differently per envelope:
+ # raw Anthropic: input_tokens EXCLUDES cache buckets
+ # raw OpenAI: input_tokens INCLUDES cache_read
+ # Studio Anthropic: prompt_tokens INCLUDES cache_creation + cache_read
+ # Studio OpenAI: prompt_tokens == raw input_tokens
+ # Clamp tokens >=0 so corrupted payloads can't produce a negative bill.
+ cache_creation = max(0, int(usage.get("cache_creation_input_tokens") or 0))
+ cache_read_native_present = (
+ "cache_read_input_tokens" in usage
+ and usage.get("cache_read_input_tokens") is not None
+ )
+ cache_read = max(0, int(usage.get("cache_read_input_tokens") or 0))
+ # Fallback to mirrored prompt_tokens_details only when the native
+ # cache_read_input_tokens key is absent. An explicit native 0 is
+ # authoritative, so a stale mirrored block from a proxy can never
+ # inflate cache_read past the native count.
+ if not cache_read_native_present:
+ details = usage.get("prompt_tokens_details") or {}
if isinstance(details, dict):
- cache_read = max(cache_read, int(details.get("cached_tokens") or 0))
- # OpenAI: cache_read already counted inside input_tokens.
+ cache_read = max(0, int(details.get("cached_tokens") or 0))
+ has_input_tokens = "input_tokens" in usage and usage.get("input_tokens") is not None
+ if has_input_tokens:
+ input_tokens = max(0, int(usage.get("input_tokens") or 0))
+ else:
+ # Chat-style: peel cache buckets back out for Anthropic to
+ # recover the raw uncached prompt count.
+ prompt_tokens = max(0, int(usage.get("prompt_tokens") or 0))
+ if provider == "anthropic":
+ input_tokens = max(0, prompt_tokens - cache_creation - cache_read)
+ else:
+ input_tokens = prompt_tokens
+ # Prefer raw output_tokens even when 0 (an `or` fallback would
+ # silently pick a stale completion_tokens).
+ if "output_tokens" in usage and usage.get("output_tokens") is not None:
+ output_tokens = max(0, int(usage.get("output_tokens") or 0))
+ else:
+ output_tokens = max(0, int(usage.get("completion_tokens") or 0))
+ if provider == "openai":
+ # Cached tokens land on either input_tokens_details (raw
+ # Responses) or prompt_tokens_details (Studio chat-style).
+ for key in ("input_tokens_details", "prompt_tokens_details"):
+ details = usage.get(key) or {}
+ if isinstance(details, dict):
+ cache_read = max(cache_read, int(details.get("cached_tokens") or 0))
+ # OpenAI input_tokens already counts cache_read.
out["billable_input_tokens"] = input_tokens + cache_creation
else:
- # Anthropic: input_tokens excludes cache_* buckets, add them all.
+ # Anthropic input_tokens excludes cache buckets; add them back.
out["billable_input_tokens"] = input_tokens + cache_creation + cache_read
out["billable_output_tokens"] = output_tokens
if not prices:
return out
- # Long-context tier crossover (gpt-5.5 / gpt-5.4 today). OpenAI
- # bills the whole turn at the long-context rate once the prompt
- # crosses the threshold, NOT a per-token blend, so we pick a
- # single (base, out_per) pair for this turn based on
- # billable_input_tokens.
+ # Long-context tier: whole-turn flip (not per-token blend) once
+ # billable_input_tokens crosses the threshold.
lc_thresh = prices.get("long_context_threshold")
in_long_context_tier = (
lc_thresh is not None
@@ -251,13 +217,14 @@ def calculate_cost(
out["output_usd"] = (output_tokens / 1_000_000.0) * out_per
if provider == "anthropic":
- # Split cache_creation across 5m / 1h buckets when the
- # response surfaces the breakdown.
- cc_breakdown = usage.get("cache_creation") or {}
- cc_5m = int(cc_breakdown.get("ephemeral_5m_input_tokens") or 0)
- cc_1h = int(cc_breakdown.get("ephemeral_1h_input_tokens") or 0)
+ # Split cache_creation into 5m / 1h buckets when surfaced.
+ # Tolerate non-dict (some proxies fold to an int total).
+ cc_raw = usage.get("cache_creation")
+ cc_breakdown = cc_raw if isinstance(cc_raw, dict) else {}
+ cc_5m = max(0, int(cc_breakdown.get("ephemeral_5m_input_tokens") or 0))
+ cc_1h = max(0, int(cc_breakdown.get("ephemeral_1h_input_tokens") or 0))
if cc_5m + cc_1h == 0 and cache_creation > 0:
- # Fall back: assume default 5m pool when no breakdown is given.
+ # No breakdown -- assume default 5m pool.
cc_5m = cache_creation
out["cache_write_usd"] = (
cc_5m / 1_000_000.0
@@ -277,24 +244,17 @@ def calculate_cost(
+ code_exec_hours * ANTHROPIC_CODE_EXEC_USD_PER_HOUR
)
else:
- # OpenAI: cache writes share the base input price (no premium).
- # Only cache reads get the 0.1x multiplier; subtract those from
- # the input_usd we already counted so we don't double-bill.
- # Anthropic excludes cache buckets from input_tokens, but
- # OpenAI folds them in, so the math differs.
+ # OpenAI: cache writes pay base input; only cache reads get
+ # 0.1x. Subtract cached from already-counted input_usd to
+ # avoid double-billing (OpenAI folds cache into input_tokens).
if cache_read > 0:
non_cached_input = max(0, input_tokens - cache_read)
out["input_usd"] = (non_cached_input / 1_000_000.0) * base
out["cache_read_usd"] = (
(cache_read / 1_000_000.0) * base * OPENAI_CACHE_READ_MULT
)
- # Server-tool surcharges. OpenAI doesn't include these on its
- # `usage` object directly -- web_search invocations are counted
- # from `ResponseFunctionWebSearch` items in the output array,
- # and container hours come from the SSE translator's shell-tool
- # accounting. Studio surfaces both under a normalised
- # `openai_tool_use` key on the usage dict the SSE finaliser
- # hands to this calculator.
+ # OpenAI server-tool surcharges arrive under `openai_tool_use`
+ # (normalised by the SSE finaliser from output array items).
srv = usage.get("openai_tool_use") or {}
if isinstance(srv, dict):
web_searches = int(srv.get("web_search_requests") or 0)
@@ -316,11 +276,7 @@ def calculate_cost(
def pricing_snapshot() -> dict[str, Any]:
- """Whole pricing table, for the /api/providers/pricing endpoint.
-
- Returns a flat structure the frontend can hand to its cost
- formatter without re-implementing the multipliers.
- """
+ """Whole pricing table for the /api/providers/pricing endpoint."""
return {
"anthropic": {
"models": dict(ANTHROPIC_PRICING),
diff --git a/studio/backend/tests/test_pricing.py b/studio/backend/tests/test_pricing.py
index f534f1f58a3..313c15a441d 100644
--- a/studio/backend/tests/test_pricing.py
+++ b/studio/backend/tests/test_pricing.py
@@ -1,12 +1,8 @@
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
-"""Unit tests for the per-session cost calculator.
-
-Pricing inputs are baked into ``core/inference/pricing.py``; this
-test verifies the math (with multipliers from the prompt-caching
-docs) and that unknown models / empty usage degrade gracefully.
-"""
+"""Unit tests for the per-session cost calculator. Verifies math
+against ``core/inference/pricing.py`` and graceful degradation."""
import math
@@ -161,8 +157,7 @@ def test_anthropic_cache_1h_write_uses_2x_multiplier():
def test_anthropic_cache_5m_default_when_no_breakdown():
- # When the docs/response doesn't surface the 5m/1h split, treat
- # the full cache_creation bucket as 5m (the upstream default pool).
+ # No 5m/1h split surfaced -> assume the default 5m pool.
base = ANTHROPIC_PRICING["claude-opus-4-7"]["input_per_mtok"]
out = calculate_cost(
"anthropic",
@@ -207,8 +202,7 @@ def test_anthropic_code_exec_charged_per_hour():
def test_anthropic_dated_id_falls_back_to_canonical_prefix():
- # Hypothetical dated snapshot of claude-opus-4-7 should still
- # inherit the canonical-id pricing via the prefix-match fallback.
+ # Dated snapshot inherits canonical pricing via prefix-match.
out = calculate_cost(
"anthropic",
"claude-opus-4-7-20260712",
@@ -222,8 +216,7 @@ def test_anthropic_dated_id_falls_back_to_canonical_prefix():
def test_openai_gpt55_input_output_math():
- # Sub-272k input keeps us in the short-context tier ($5/$30).
- # The dedicated long-context tests below exercise the crossover.
+ # Sub-272k stays in short-context tier ($5/$30).
out = calculate_cost(
"openai",
"gpt-5.5",
@@ -235,11 +228,7 @@ def test_openai_gpt55_input_output_math():
def test_openai_cache_read_subtracted_from_input_at_discount():
- # OpenAI folds cached tokens into input_tokens, unlike Anthropic.
- # The calculator must subtract cached_tokens from the "full price"
- # bucket and re-bill them at 0.1x. Use a sub-272k total so the
- # short-context tier applies (long-context crossover is exercised
- # in its own test below).
+ # OpenAI folds cached into input_tokens; subtract and re-bill at 0.1x.
base = OPENAI_PRICING["gpt-5.5"]["input_per_mtok"]
out = calculate_cost(
"openai",
@@ -258,9 +247,7 @@ def test_openai_cache_read_subtracted_from_input_at_discount():
def test_openai_billable_input_tokens_does_not_double_count_cache_read():
- # OpenAI's input_tokens already includes cached_tokens, so the
- # billable counter must NOT add cache_read on top -- otherwise the
- # tooltip says 180k input when the bill is for 100k.
+ # input_tokens already includes cached; don't double-count.
out = calculate_cost(
"openai",
"gpt-5.5",
@@ -274,9 +261,7 @@ def test_openai_billable_input_tokens_does_not_double_count_cache_read():
def test_openai_dated_snapshot_inherits_canonical_pricing():
- # Sub-272k stays in the short-context tier; the prefix-match
- # fallback is what proves the dated snapshot inherits gpt-5.5
- # pricing.
+ # Dated snapshot inherits gpt-5.5 pricing via prefix-match.
out = calculate_cost(
"openai",
"gpt-5.5-2026-04-23",
@@ -287,10 +272,7 @@ def test_openai_dated_snapshot_inherits_canonical_pricing():
def test_openai_gpt54_family_uses_verified_prices():
- # Spot-check the lower-tier rows that previously underbilled.
- # gpt-5.4 has a long-context tier so the input has to stay
- # below 272k; the mini/nano/codex rows have no crossover so
- # 1M tokens is fine.
+ # Spot-check lower-tier rows that previously underbilled.
cases = {
# (input_tokens, expected_input_usd, expected_output_usd)
"gpt-5.4": (200_000, 200_000 / 1_000_000.0 * 2.5, 200_000 / 1_000_000.0 * 15.0),
@@ -310,8 +292,7 @@ def test_openai_gpt54_family_uses_verified_prices():
def test_openai_unlisted_model_priced_false_not_zero_default():
- # o-series / gpt-4.5 are no longer on the pricing page, so we
- # intentionally drop them rather than silently underbill at $0.
+ # o-series / gpt-4.5 are off the pricing page; drop rather than $0.
for model in ("o3", "o4-mini", "gpt-4.5", "gpt-4.5-preview"):
out = calculate_cost(
"openai",
@@ -329,9 +310,7 @@ def test_openai_unlisted_model_priced_false_not_zero_default():
def test_anthropic_canonical_4_5_ids_are_priced():
- # Codex P1: claude-opus-4-5 (no date) is the canonical id used
- # in backend defaults but was missing from the table, so the
- # calculator returned priced=False + zero cost. Pin the aliases.
+ # Pin the bare-id aliases (backend defaults reference these).
cases = {
"claude-opus-4-5": (5.0, 25.0),
"claude-sonnet-4-5": (3.0, 15.0),
@@ -366,8 +345,7 @@ def test_openai_gpt55_short_context_under_272k_uses_base_rates():
def test_openai_gpt55_long_context_crossover_uses_higher_rates():
- # 300k billable input > 272k threshold -> long-context tier
- # applies to the WHOLE turn, not a per-token blend.
+ # >272k billable -> long-context tier on the whole turn.
out = calculate_cost(
"openai",
"gpt-5.5",
@@ -389,8 +367,7 @@ def test_openai_gpt54_long_context_crossover():
def test_openai_gpt54_mini_has_no_long_context_tier():
- # Mini/nano/codex don't publish a long-context price; the base
- # rate must keep applying even at very large prompts.
+ # Mini/nano/codex have no long-context tier; base rate always applies.
out = calculate_cost(
"openai",
"gpt-5.4-mini",
@@ -433,8 +410,7 @@ def test_openai_container_hours_charged():
def test_openai_tool_surcharges_added_to_total():
- # End-to-end: input + output + web_search + container in one
- # turn. Total must sum all four buckets.
+ # End-to-end: total must sum input + output + web_search + container.
out = calculate_cost(
"openai",
"gpt-5.5",
@@ -476,8 +452,7 @@ def test_snapshot_contains_provider_buckets_and_multipliers():
assert "code_execution_usd_per_hour" in a
assert "models" in o and "gpt-5.5" in o["models"]
assert o["cache_read_mult"] == OPENAI_CACHE_READ_MULT
- # OpenAI tool surcharge constants are also exposed so the frontend
- # tooltip can render the per-call rate.
+ # OpenAI tool surcharge constants are exposed for the frontend.
assert o["web_search_usd_per_1k"] == OPENAI_WEB_SEARCH_USD_PER_1K
assert o["container_usd_per_hour"] == OPENAI_CONTAINER_USD_PER_HOUR
# Long-context tier metadata travels with the model row.
@@ -485,3 +460,169 @@ def test_snapshot_contains_provider_buckets_and_multipliers():
assert gpt55["long_context_threshold"] == 272_000
assert gpt55["long_context_input_per_mtok"] == 10.0
assert gpt55["long_context_output_per_mtok"] == 45.0
+
+
+# ── longest-prefix match: dated mini variant must not collide with the
+# shorter family prefix. ──
+
+
+def test_longest_prefix_match_wins_for_dated_mini_snapshot():
+ """`gpt-5.4-mini-2026-...` must inherit the mini rate, not the
+ shorter `gpt-5.4` rate (longest prefix wins)."""
+ out = calculate_cost(
+ "openai",
+ "gpt-5.4-mini-2026-04-23",
+ {"input_tokens": 1_000_000, "output_tokens": 0},
+ )
+ assert out["priced"] is True
+ # mini = 0.75/MTok, shorter gpt-5.4 = 2.5/MTok (>3x overcharge).
+ assert _isclose(out["input_usd"], 0.75), out
+
+
+def test_longest_prefix_match_wins_for_dated_pro_snapshot():
+ out = calculate_cost(
+ "openai",
+ "gpt-5.5-pro-2026-04-23",
+ {"input_tokens": 1_000_000, "output_tokens": 0},
+ )
+ assert out["priced"] is True
+ # gpt-5.5-pro = 30/MTok vs gpt-5.5 = 5/MTok; longest wins.
+ assert _isclose(out["input_usd"], 30.0), out
+
+
+# ── accept both chat-style and Responses envelope shapes. ──
+
+
+def test_openai_chat_style_usage_keys_priced_correctly():
+ """Chat-style envelope (`prompt_tokens` / `completion_tokens`) must
+ produce a non-zero cost (previously silently zeroed)."""
+ out = calculate_cost(
+ "openai",
+ "gpt-5.4-mini",
+ {"prompt_tokens": 1_000_000, "completion_tokens": 1_000_000},
+ )
+ # gpt-5.4-mini: 0.75 input + 4.5 output per MTok.
+ assert _isclose(out["input_usd"], 0.75), out
+ assert _isclose(out["output_usd"], 4.5), out
+
+
+def test_input_tokens_preferred_when_both_keys_present():
+ """Raw key wins when both envelope shapes are present."""
+ out = calculate_cost(
+ "openai",
+ "gpt-5.4-mini",
+ {
+ "input_tokens": 2_000_000,
+ "prompt_tokens": 5_000_000,
+ "output_tokens": 0,
+ },
+ )
+ # input_tokens=2M wins -> 2 * 0.75 = 1.50.
+ assert _isclose(out["input_usd"], 1.50), out
+
+
+def test_anthropic_chat_style_prompt_tokens_dedupes_cache_buckets():
+ """Anthropic chat-style prompt_tokens already folds cache buckets;
+ don't double-count billable input."""
+ # 1M uncached + 200K cache_creation + 500K cache_read -> 1.7M folded.
+ raw = calculate_cost(
+ "anthropic",
+ "claude-opus-4-7",
+ {
+ "input_tokens": 1_000_000,
+ "cache_creation_input_tokens": 200_000,
+ "cache_read_input_tokens": 500_000,
+ "output_tokens": 0,
+ },
+ )
+ chat = calculate_cost(
+ "anthropic",
+ "claude-opus-4-7",
+ {
+ "prompt_tokens": 1_700_000,
+ "cache_creation_input_tokens": 200_000,
+ "cache_read_input_tokens": 500_000,
+ "completion_tokens": 0,
+ },
+ )
+ # Both envelopes must price the same.
+ assert _isclose(chat["input_usd"], raw["input_usd"]), (chat, raw)
+ assert _isclose(chat["cache_write_usd"], raw["cache_write_usd"]), (chat, raw)
+ assert _isclose(chat["cache_read_usd"], raw["cache_read_usd"]), (chat, raw)
+ assert _isclose(chat["total_usd"], raw["total_usd"]), (chat, raw)
+ assert chat["billable_input_tokens"] == raw["billable_input_tokens"], (chat, raw)
+
+
+def test_openai_chat_style_prompt_tokens_keeps_cache_read_semantics():
+ """OpenAI prompt_tokens includes cache_read like raw input_tokens."""
+ raw = calculate_cost(
+ "openai",
+ "gpt-5.5",
+ {
+ "input_tokens": 1_000_000,
+ "input_tokens_details": {"cached_tokens": 200_000},
+ "output_tokens": 100_000,
+ },
+ )
+ chat = calculate_cost(
+ "openai",
+ "gpt-5.5",
+ {
+ "prompt_tokens": 1_000_000,
+ "cache_read_input_tokens": 200_000,
+ "completion_tokens": 100_000,
+ },
+ )
+ assert _isclose(chat["total_usd"], raw["total_usd"]), (chat, raw)
+
+
+def test_openai_chat_style_envelope_reads_cache_from_prompt_tokens_details():
+ """Chat-style envelope ships cached under prompt_tokens_details;
+ calculator must honour both this and input_tokens_details."""
+ base = OPENAI_PRICING["gpt-5.5"]["input_per_mtok"]
+ raw = calculate_cost(
+ "openai",
+ "gpt-5.5",
+ {
+ "input_tokens": 100_000,
+ "input_tokens_details": {"cached_tokens": 80_000},
+ "output_tokens": 0,
+ },
+ )
+ chat_style = calculate_cost(
+ "openai",
+ "gpt-5.5",
+ {
+ "prompt_tokens": 100_000,
+ "prompt_tokens_details": {"cached_tokens": 80_000},
+ "completion_tokens": 0,
+ },
+ )
+ # Both envelopes must price identically.
+ assert _isclose(chat_style["input_usd"], raw["input_usd"]), (chat_style, raw)
+ assert _isclose(chat_style["cache_read_usd"], raw["cache_read_usd"]), (
+ chat_style,
+ raw,
+ )
+ # 80k at 0.1x base, 20k at full.
+ assert _isclose(
+ chat_style["cache_read_usd"],
+ 80_000 / 1_000_000.0 * base * OPENAI_CACHE_READ_MULT,
+ )
+
+
+def test_explicit_zero_output_tokens_wins_over_stale_completion_tokens():
+ """Explicit ``output_tokens: 0`` beats a stale ``completion_tokens``;
+ the previous `or` fallback treated 0 as missing."""
+ out = calculate_cost(
+ "openai",
+ "gpt-4o-mini",
+ {
+ "input_tokens": 100,
+ "output_tokens": 0,
+ # Stale chat-style mirror; must not bill against it.
+ "completion_tokens": 50,
+ },
+ )
+ assert out["billable_output_tokens"] == 0, out
+ assert out["output_usd"] == 0.0, out
diff --git a/studio/backend/tests/test_pricing_edge.py b/studio/backend/tests/test_pricing_edge.py
new file mode 100644
index 00000000000..ca4be258e09
--- /dev/null
+++ b/studio/backend/tests/test_pricing_edge.py
@@ -0,0 +1,475 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""Adversarial edge cases for ``calculate_cost`` / ``_lookup``: prefix
+boundary, negative tokens, chat vs raw parity, long-context crossover
+on billable count, and malformed sub-objects."""
+
+import math
+
+from core.inference.pricing import (
+ ANTHROPIC_CACHE_5M_WRITE_MULT,
+ ANTHROPIC_CACHE_READ_MULT,
+ ANTHROPIC_PRICING,
+ OPENAI_CACHE_READ_MULT,
+ OPENAI_PRICING,
+ _lookup,
+ calculate_cost,
+)
+
+
+def _isclose(a, b, tol = 1e-6):
+ return math.isclose(a, b, rel_tol = tol, abs_tol = tol)
+
+
+# ── prefix-match boundary checks ────────────────────────────────────
+
+
+def test_prefix_match_requires_dash_boundary_opus_variant():
+ # `claude-opus-4-15` must not inherit `claude-opus-4-1` pricing;
+ # next char must be `-` or end-of-string.
+ assert _lookup("anthropic", "claude-opus-4-15") is None
+ out = calculate_cost(
+ "anthropic",
+ "claude-opus-4-15",
+ {"input_tokens": 1_000_000, "output_tokens": 0},
+ )
+ assert out["priced"] is False
+ assert out["total_usd"] == 0.0
+
+
+def test_prefix_match_requires_dash_boundary_gpt_variant():
+ # Same dash-boundary invariant for OpenAI ids.
+ assert _lookup("openai", "gpt-5.55") is None
+ assert _lookup("openai", "gpt-5.55-2026-04-23") is None
+ out = calculate_cost(
+ "openai",
+ "gpt-5.55-2026-04-23",
+ {"input_tokens": 1_000_000, "output_tokens": 0},
+ )
+ assert out["priced"] is False
+
+
+def test_prefix_match_requires_dash_boundary_pro_lookalike():
+ # `gpt-5.5-prod` must fall through `gpt-5.5-pro` (6x overcharge)
+ # and land on the canonical `gpt-5.5` row.
+ prices = _lookup("openai", "gpt-5.5-prod")
+ assert prices is not None
+ assert (
+ prices["input_per_mtok"] == OPENAI_PRICING["gpt-5.5"]["input_per_mtok"]
+ ), "expected fallback to gpt-5.5 base ($5), not gpt-5.5-pro ($30)"
+ out = calculate_cost(
+ "openai",
+ "gpt-5.5-prod",
+ {"input_tokens": 100_000, "output_tokens": 0},
+ )
+ assert out["priced"] is True
+ assert _isclose(out["input_usd"], 100_000 / 1_000_000.0 * 5.0)
+
+
+def test_prefix_match_still_resolves_legit_dated_snapshots():
+ # Boundary fix must not regress legit dated snapshots.
+ out = calculate_cost(
+ "openai",
+ "gpt-5.4-mini-2026-04-23",
+ {"input_tokens": 1_000_000, "output_tokens": 0},
+ )
+ assert out["priced"] is True
+ assert _isclose(out["input_usd"], 0.75)
+
+ # And Anthropic dated snapshot still resolves to canonical row.
+ out = calculate_cost(
+ "anthropic",
+ "claude-opus-4-7-20260414",
+ {"input_tokens": 1_000_000, "output_tokens": 0},
+ )
+ assert out["priced"] is True
+ assert _isclose(out["input_usd"], 5.0)
+
+
+# ── precedence: input_tokens wins over prompt_tokens (and 0 is real) ──
+
+
+def test_explicit_zero_input_tokens_wins_over_stale_prompt_tokens():
+ # Input-side mirror of the output zero precedence test.
+ out = calculate_cost(
+ "openai",
+ "gpt-5.5",
+ {
+ "input_tokens": 0,
+ "prompt_tokens": 1_000_000, # stale chat-style mirror
+ "output_tokens": 100,
+ },
+ )
+ assert out["billable_input_tokens"] == 0
+ assert out["input_usd"] == 0.0
+
+
+def test_none_input_tokens_falls_through_to_prompt_tokens():
+ # `None` is "key present but unset"; chat-style mirror wins.
+ out = calculate_cost(
+ "openai",
+ "gpt-5.5",
+ {
+ "input_tokens": None,
+ "prompt_tokens": 200_000,
+ "output_tokens": None,
+ "completion_tokens": 5_000,
+ },
+ )
+ assert out["billable_input_tokens"] == 200_000
+ assert out["billable_output_tokens"] == 5_000
+ assert _isclose(out["input_usd"], 200_000 / 1_000_000.0 * 5.0)
+ assert _isclose(out["output_usd"], 5_000 / 1_000_000.0 * 30.0)
+
+
+# ── negative / corrupted upstream values clamp to zero ──────────────
+
+
+def test_negative_tokens_clamp_to_zero_no_negative_bill():
+ out = calculate_cost(
+ "openai",
+ "gpt-5.5",
+ {"input_tokens": -100, "output_tokens": -50},
+ )
+ assert out["billable_input_tokens"] == 0
+ assert out["billable_output_tokens"] == 0
+ assert out["input_usd"] == 0.0
+ assert out["output_usd"] == 0.0
+ assert out["total_usd"] == 0.0
+
+
+def test_negative_cache_buckets_clamp_to_zero():
+ # Negative cache_read on Anthropic would otherwise refund the bill.
+ out = calculate_cost(
+ "anthropic",
+ "claude-opus-4-7",
+ {
+ "input_tokens": 1_000,
+ "output_tokens": 0,
+ "cache_creation_input_tokens": -500,
+ "cache_read_input_tokens": -1_000,
+ },
+ )
+ assert out["cache_write_usd"] == 0.0
+ assert out["cache_read_usd"] == 0.0
+ assert out["billable_input_tokens"] == 1_000
+ assert out["total_usd"] >= 0.0
+
+
+def test_negative_prompt_tokens_chat_style_clamp():
+ out = calculate_cost(
+ "openai",
+ "gpt-5.4-mini",
+ {"prompt_tokens": -100, "completion_tokens": -50},
+ )
+ assert out["billable_input_tokens"] == 0
+ assert out["billable_output_tokens"] == 0
+ assert out["total_usd"] == 0.0
+
+
+# ── cache_read > prompt_tokens corruption: no negative billable ─────
+
+
+def test_anthropic_chat_cache_read_exceeds_prompt_no_negative_billable():
+ # cache_read > prompt_tokens clamps uncached_input at 0; billable
+ # still reflects cache buckets (we charge for what we got).
+ out = calculate_cost(
+ "anthropic",
+ "claude-opus-4-7",
+ {
+ "prompt_tokens": 100,
+ "cache_creation_input_tokens": 0,
+ "cache_read_input_tokens": 500,
+ "completion_tokens": 0,
+ },
+ )
+ assert out["input_usd"] == 0.0 # uncached clamped to 0
+ assert out["billable_input_tokens"] == 500 # 0 uncached + 500 cache_read
+ # cache_read still priced at the discount rate.
+ base = ANTHROPIC_PRICING["claude-opus-4-7"]["input_per_mtok"]
+ assert _isclose(
+ out["cache_read_usd"], 500 / 1_000_000.0 * base * ANTHROPIC_CACHE_READ_MULT
+ )
+
+
+def test_openai_raw_cached_tokens_exceeds_input_clamp_non_cached():
+ # OpenAI variant: cached > input must not produce negative input_usd.
+ base = OPENAI_PRICING["gpt-5.5"]["input_per_mtok"]
+ out = calculate_cost(
+ "openai",
+ "gpt-5.5",
+ {
+ "input_tokens": 100,
+ "output_tokens": 0,
+ "input_tokens_details": {"cached_tokens": 500},
+ },
+ )
+ assert out["input_usd"] == 0.0
+ # Cache read still priced (the 0.1x bucket).
+ assert _isclose(
+ out["cache_read_usd"], 500 / 1_000_000.0 * base * OPENAI_CACHE_READ_MULT
+ )
+
+
+# ── long-context tier crosses on billable, including cache_creation ──
+
+
+def test_openai_long_context_triggers_on_cache_creation_inflated_billable():
+ # cache_creation pushes billable past 272k -> long-context tier
+ # must fire to avoid undercounting.
+ out = calculate_cost(
+ "openai",
+ "gpt-5.5",
+ {
+ "input_tokens": 250_000,
+ "cache_creation_input_tokens": 50_000,
+ "output_tokens": 1_000,
+ },
+ )
+ assert out["billable_input_tokens"] == 300_000
+ assert "long-context" in out["model_priced"]
+ assert _isclose(out["input_usd"], 250_000 / 1_000_000.0 * 10.0)
+ assert _isclose(out["output_usd"], 1_000 / 1_000_000.0 * 45.0)
+
+
+def test_openai_long_context_threshold_boundary_inclusive():
+ # Threshold is inclusive (>=).
+ out = calculate_cost(
+ "openai",
+ "gpt-5.5",
+ {"input_tokens": 272_000, "output_tokens": 1_000},
+ )
+ assert "long-context" in out["model_priced"]
+ out_lo = calculate_cost(
+ "openai",
+ "gpt-5.5",
+ {"input_tokens": 271_999, "output_tokens": 1_000},
+ )
+ assert "long-context" not in out_lo["model_priced"]
+
+
+# ── chat-style vs raw envelope parity at OpenAI long-context tier ──
+
+
+def test_openai_chat_envelope_long_context_parity_with_raw():
+ raw = calculate_cost(
+ "openai",
+ "gpt-5.5",
+ {"input_tokens": 300_000, "output_tokens": 10_000},
+ )
+ chat = calculate_cost(
+ "openai",
+ "gpt-5.5",
+ {"prompt_tokens": 300_000, "completion_tokens": 10_000},
+ )
+ assert _isclose(chat["total_usd"], raw["total_usd"])
+ assert "long-context" in chat["model_priced"]
+ assert "long-context" in raw["model_priced"]
+
+
+# ── malformed sub-objects: no crash, no false bill ──────────────────
+
+
+def test_cache_creation_as_int_does_not_crash():
+ # Proxies sometimes fold cache_creation to an int; tolerate it
+ # and fall back to the 5m default.
+ base = ANTHROPIC_PRICING["claude-opus-4-7"]["input_per_mtok"]
+ out = calculate_cost(
+ "anthropic",
+ "claude-opus-4-7",
+ {
+ "input_tokens": 0,
+ "output_tokens": 0,
+ "cache_creation_input_tokens": 1_000_000,
+ "cache_creation": 12345, # malformed; must not raise
+ },
+ )
+ # Falls back to 5m default for the whole bucket.
+ assert _isclose(
+ out["cache_write_usd"],
+ 1_000_000 / 1_000_000.0 * base * ANTHROPIC_CACHE_5M_WRITE_MULT,
+ )
+
+
+def test_non_dict_server_tool_use_is_ignored():
+ out = calculate_cost(
+ "anthropic",
+ "claude-opus-4-7",
+ {"input_tokens": 100, "output_tokens": 100, "server_tool_use": "garbage"},
+ )
+ assert out["server_tools_usd"] == 0.0
+
+ out = calculate_cost(
+ "openai",
+ "gpt-5.5",
+ {"input_tokens": 100, "output_tokens": 100, "openai_tool_use": [1, 2, 3]},
+ )
+ assert out["server_tools_usd"] == 0.0
+
+
+def test_non_dict_input_tokens_details_is_ignored():
+ out = calculate_cost(
+ "openai",
+ "gpt-5.5",
+ {
+ "input_tokens": 100,
+ "output_tokens": 0,
+ "input_tokens_details": "nope",
+ "prompt_tokens_details": [1, 2, 3],
+ },
+ )
+ # No cached_tokens recovered -> no discount.
+ assert out["cache_read_usd"] == 0.0
+
+
+# ── unknown provider degrades gracefully ────────────────────────────
+
+
+def test_unknown_provider_priced_false_zero_bill():
+ out = calculate_cost(
+ "gemini",
+ "gemini-pro",
+ {"input_tokens": 1_000_000, "output_tokens": 1_000_000},
+ )
+ assert out["priced"] is False
+ assert out["total_usd"] == 0.0
+ # Tokens still report for the UI.
+ assert out["billable_input_tokens"] == 1_000_000
+ assert out["billable_output_tokens"] == 1_000_000
+
+
+def test_anthropic_provider_with_openai_model_priced_false():
+ # OpenAI id against Anthropic table must not falsely match.
+ out = calculate_cost(
+ "anthropic",
+ "gpt-5.5",
+ {"input_tokens": 1_000_000, "output_tokens": 0},
+ )
+ assert out["priced"] is False
+
+
+# ── all-zero / empty usage stays at zero ────────────────────────────
+
+
+def test_empty_usage_dict_zero_bill():
+ out = calculate_cost("openai", "gpt-5.5", {})
+ assert out["priced"] is True # model is in the table
+ assert out["billable_input_tokens"] == 0
+ assert out["total_usd"] == 0.0
+
+
+# ── Defense-in-depth: Anthropic prompt_tokens_details.cached_tokens ──
+
+
+def test_anthropic_prompt_tokens_details_fallback_when_native_key_missing():
+ """Chat-style envelope without `cache_read_input_tokens` but with
+ mirrored `prompt_tokens_details.cached_tokens` should still apply
+ the cache_read discount."""
+ r = calculate_cost(
+ provider = "anthropic",
+ model = "claude-opus-4-7",
+ usage = {
+ "prompt_tokens": 1_000_000,
+ "completion_tokens": 0,
+ # Only the mirrored shape (no native key).
+ "prompt_tokens_details": {"cached_tokens": 1_000_000},
+ "cache_creation_input_tokens": 0,
+ },
+ )
+ assert r["billable_input_tokens"] == 1_000_000, r
+ # 1M cached at 0.1x of $5 (opus 4.7) = $0.50
+ assert math.isclose(r["cache_read_usd"], 0.5, rel_tol = 1e-3), r
+
+
+def test_anthropic_native_key_takes_precedence_over_mirrored():
+ """When both native and mirrored cache-read fields are present,
+ the native Anthropic field wins (mirror is fallback-only)."""
+ r = calculate_cost(
+ provider = "anthropic",
+ model = "claude-opus-4-7",
+ usage = {
+ "prompt_tokens": 1_000_000,
+ "cache_read_input_tokens": 800_000,
+ "prompt_tokens_details": {"cached_tokens": 1_000_000},
+ "cache_creation_input_tokens": 0,
+ },
+ )
+ # billable = uncached_input + cache_creation + cache_read
+ # = (1M - 0 - 800k) + 0 + 800k = 1M
+ assert r["billable_input_tokens"] == 1_000_000, r
+ # cache_read uses 800k (native), not 1M (mirrored).
+ assert math.isclose(r["cache_read_usd"], 0.4, rel_tol = 1e-3), r
+
+
+def test_anthropic_native_zero_takes_precedence_over_mirrored():
+ """Explicit `cache_read_input_tokens: 0` is authoritative; a stale
+ mirrored block from a proxy must not inflate cache_read past it."""
+ r = calculate_cost(
+ provider = "anthropic",
+ model = "claude-opus-4-7",
+ usage = {
+ "input_tokens": 1_000_000,
+ "output_tokens": 0,
+ "cache_read_input_tokens": 0,
+ # Stale mirror from a proxy; must be ignored (native present).
+ "prompt_tokens_details": {"cached_tokens": 1_000_000},
+ },
+ )
+ # Native is 0 -> cache_read stays 0.
+ assert r["cache_read_usd"] == 0.0, r
+ # billable = input + cache_creation + cache_read = 1M + 0 + 0
+ assert r["billable_input_tokens"] == 1_000_000, r
+ # 1M uncached at $5/M (no discount).
+ assert math.isclose(r["input_usd"], 5.0, rel_tol = 1e-3), r
+ assert math.isclose(r["total_usd"], 5.0, rel_tol = 1e-3), r
+
+
+# ── _build_usage_chunk preserves cache_creation breakdown ──
+
+
+def test_build_usage_chunk_forwards_anthropic_cache_creation_breakdown():
+ """Chat-style envelope must carry the 5m/1h cache-write breakdown
+ so downstream cost calc applies the 2x 1h premium."""
+ import json
+ from core.inference.external_provider import _build_usage_chunk
+
+ chunk = _build_usage_chunk(
+ completion_id = "cmpl-x",
+ provider = "anthropic",
+ last_usage = {
+ "input_tokens": 10,
+ "output_tokens": 5,
+ "cache_creation_input_tokens": 1_000_000,
+ "cache_read_input_tokens": 0,
+ "cache_creation": {
+ "ephemeral_5m_input_tokens": 250_000,
+ "ephemeral_1h_input_tokens": 750_000,
+ },
+ },
+ )
+ assert chunk is not None
+ payload = json.loads(chunk.split("data: ", 1)[1])
+ cc = payload["usage"]["cache_creation"]
+ assert cc["ephemeral_1h_input_tokens"] == 750_000, cc
+ assert cc["ephemeral_5m_input_tokens"] == 250_000, cc
+
+
+def test_calculate_cost_uses_forwarded_cache_creation_for_1h_premium():
+ """Re-emitted chat envelope must price 1h cache writes at 2x base."""
+ r = calculate_cost(
+ provider = "anthropic",
+ model = "claude-opus-4-7",
+ usage = {
+ "prompt_tokens": 1_000_010,
+ "completion_tokens": 0,
+ "cache_creation_input_tokens": 1_000_000,
+ "cache_read_input_tokens": 0,
+ "cache_creation": {
+ "ephemeral_5m_input_tokens": 0,
+ "ephemeral_1h_input_tokens": 1_000_000,
+ },
+ },
+ )
+ # 1M at 1h-premium (2x of $5 = $10); 5m baseline would be $6.25.
+ assert math.isclose(r["cache_write_usd"], 10.0, rel_tol = 1e-2), r