mirror of
https://github.com/BerriAI/litellm.git
synced 2026-11-29 01:03:17 +00:00
* feat(nace): add NDI document parse as an OCR provider Add a Rust OCR adapter for Nace Document Intelligence (NDI) Parse with the models nace/parse-low, nace/parse-medium and nace/parse-high. A public https link goes to Nace as a link. Any other document is uploaded with a one-time grant, parsed, and deleted after the call. The cost map bills each processed page at the price of the effort. * fix(nace): clean the job error before the OCR response hooks see it The copy of a Nace job that goes to the response hooks now has its error code and message cleaned and the deployment API key masked. The copy keeps the key order of the job. The password texts now say that the logging callbacks mask it. * fix(nace): accept include_image_base64 and never send it to Nace Clients that use the Mistral OCR request shape send the top-level include_image_base64 option. A host that passes every body field on sent it to Nace, which refuses an unknown field with a 422. The option is now accepted with any value and left out of the parse request, since Nace returns images as links (output.include_images), not base64. * fix(nace): map the pages option to Nace page_ranges Clients that use the Mistral OCR request shape select pages with the top-level pages option (0-based page indexes). The Python host dropped it, so Nace parsed and billed the whole document, and a host that passes every body field on sent it to Nace, which refuses it with a 422. The option is now sorted, deduplicated, shifted to 1-based pages and merged into page_ranges runs. An empty list parses the whole document. Values that are not non-negative integers, or pages together with page_ranges, are refused with a 400 before the upload. * test(nace): assert request headers without loops and drop a redundant doc line * fix(nace): refuse include_image_base64 true unless drop_params is on Nace returns images as links, never as base64, so a request asking for base64 images now gets the unsupported-param 400 that other OCR providers give for output they cannot return. drop_params drops it instead, and false or null are still accepted and never sent, which keeps Open WebUI's Mistral loader working * fix(nace): refuse output.include_images unless drop_params is on Nace returns image crops only as links that need the operator's Nace key and stop working once cleanup deletes the job, so image requests now get the same unsupported-param 400 as include_image_base64 and every job is deleted * fix(nace): bill only the requested pages when Nace omits billed units With page_ranges, the page count Nace reports covers the whole document, so a job without units now bills the requested pages that exist in the document instead of every page --------- Co-authored-by: mateo-berri <277851410+mateo-berri@users.noreply.github.com>
1435 lines
64 KiB
Python
1435 lines
64 KiB
Python
from __future__ import annotations
|
|
|
|
import json
|
|
import re
|
|
from collections.abc import Iterator, Mapping
|
|
from itertools import chain
|
|
from pathlib import Path
|
|
from types import MappingProxyType
|
|
from typing import Final
|
|
|
|
import pytest
|
|
from pydantic import BaseModel, ConfigDict, JsonValue, TypeAdapter
|
|
|
|
import litellm
|
|
from litellm.cost_calculator import completion_cost
|
|
from litellm.litellm_core_utils.fallback_generalizations import match_capability_generalizations
|
|
from litellm.litellm_core_utils.reasoning_effort_capability import resolve_supported_reasoning_efforts
|
|
from litellm.llms.base_llm.ocr.transformation import OCRPage, OCRResponse, OCRUsageInfo
|
|
from litellm.llms.bedrock.common_utils import BedrockModelInfo
|
|
from litellm.llms.openai.chat.gpt_reasoning_transformation import is_gpt_reasoning_series_name
|
|
from litellm.llms.openai_like.json_loader import JSONProviderRegistry
|
|
from litellm.types.utils import CompletionTokensDetailsWrapper, PromptTokensDetailsWrapper, SearchFreeRequests, Usage
|
|
from litellm.utils import ProviderConfigManager
|
|
|
|
REPO_ROOT = Path(__file__).parents[2]
|
|
PRICES_PATH = REPO_ROOT / "model_prices_and_context_window.json"
|
|
BACKUP_PRICES_PATH = REPO_ROOT / "litellm" / "model_prices_and_context_window_backup.json"
|
|
|
|
CostMap = Mapping[str, Mapping[str, JsonValue]]
|
|
|
|
|
|
@pytest.fixture(scope="module")
|
|
def prices() -> dict:
|
|
return json.loads(PRICES_PATH.read_text())
|
|
|
|
|
|
@pytest.mark.parametrize("model", ("azure/gpt-audio-1.5-2026-02-23", "azure/gpt-audio-mini-2025-10-06"))
|
|
def test_azure_audio_snapshot_capabilities_match_declared_modalities(model: str, local_model_cost_map: None) -> None:
|
|
catalog: Final = TypeAdapter(dict[str, JsonValue]).validate_json(PRICES_PATH.read_bytes())
|
|
backup: Final = TypeAdapter(dict[str, JsonValue]).validate_json(BACKUP_PRICES_PATH.read_bytes())
|
|
entry: Final = catalog[model]
|
|
assert isinstance(entry, dict)
|
|
assert entry == backup[model]
|
|
input_modalities: Final = entry["supported_modalities"]
|
|
output_modalities: Final = entry["supported_output_modalities"]
|
|
assert isinstance(input_modalities, list)
|
|
assert isinstance(output_modalities, list)
|
|
expected: Final = ("audio" in input_modalities, "audio" in output_modalities)
|
|
info: Final = litellm.get_model_info(model)
|
|
assert (info["supports_audio_input"], info["supports_audio_output"]) == expected
|
|
assert (litellm.supports_audio_input(model), litellm.supports_audio_output(model)) == expected
|
|
|
|
|
|
class _CopilotEndpointRow(BaseModel):
|
|
model_config = ConfigDict(frozen=True, extra="ignore")
|
|
|
|
mode: str
|
|
max_input_tokens: int
|
|
max_output_tokens: int
|
|
supported_endpoints: tuple[str, ...]
|
|
|
|
|
|
class _CopilotThinkingCapabilities(BaseModel):
|
|
model_config = ConfigDict(frozen=True, extra="ignore")
|
|
|
|
supports_reasoning: bool | None = None
|
|
supports_adaptive_thinking: bool | None = None
|
|
supports_legacy_thinking: bool | None = None
|
|
thinking_always_on: bool | None = None
|
|
|
|
|
|
def _copilot_endpoint_rows(path: Path) -> Mapping[str, _CopilotEndpointRow]:
|
|
prices: Final[dict[str, JsonValue]] = TypeAdapter(dict[str, JsonValue]).validate_json(path.read_bytes())
|
|
return MappingProxyType(
|
|
{
|
|
key: _CopilotEndpointRow.model_validate(value)
|
|
for key, value in prices.items()
|
|
if key.startswith("github_copilot/") and isinstance(value, dict) and "supported_endpoints" in value
|
|
}
|
|
)
|
|
|
|
|
|
def _thinking_capabilities(prices: Mapping[str, JsonValue], key: str) -> _CopilotThinkingCapabilities:
|
|
return _CopilotThinkingCapabilities.model_validate(prices[key])
|
|
|
|
|
|
def _github_copilot_catalog_rows(path: Path) -> Mapping[str, JsonValue]:
|
|
prices: Final[dict[str, JsonValue]] = TypeAdapter(dict[str, JsonValue]).validate_json(path.read_bytes())
|
|
return MappingProxyType({key: value for key, value in prices.items() if key.startswith("github_copilot/")})
|
|
|
|
|
|
_THINKING_KEYS: Final[tuple[str, ...]] = (
|
|
"supports_reasoning",
|
|
"supports_adaptive_thinking",
|
|
"supports_legacy_thinking",
|
|
"thinking_always_on",
|
|
)
|
|
|
|
|
|
def _anthropic_counterpart(key: str) -> str:
|
|
return key.removeprefix("github_copilot/").removesuffix("-fast").replace(".", "-")
|
|
|
|
|
|
@pytest.mark.parametrize(("path",), [(PRICES_PATH,), (BACKUP_PRICES_PATH,)], ids=("main", "backup"))
|
|
def test_github_copilot_rows_derive_mode_from_their_endpoints(path: Path) -> None:
|
|
rows: Final[Mapping[str, _CopilotEndpointRow]] = _copilot_endpoint_rows(path)
|
|
assert rows, f"No GitHub Copilot endpoint rows found in {path}"
|
|
assert {key: row.mode for key, row in rows.items()} == {
|
|
key: "chat" if "/v1/chat/completions" in row.supported_endpoints else "responses" for key, row in rows.items()
|
|
}
|
|
|
|
|
|
def _mantle_route_rows_priced_apart_from_their_provider_row(
|
|
prices: Mapping[str, Mapping[str, object]],
|
|
) -> tuple[str, ...]:
|
|
route: Final = "bedrock/mantle/"
|
|
provider_rows: Final = {
|
|
key: prices.get(f"bedrock_mantle/{key.removeprefix(route)}") for key in prices if key.startswith(route)
|
|
}
|
|
return tuple(
|
|
key
|
|
for key, provider_row in provider_rows.items()
|
|
if provider_row is not None and _price_fields(prices[key]) != _price_fields(provider_row)
|
|
)
|
|
|
|
|
|
def _price_fields(row: Mapping[str, object]) -> Mapping[str, object]:
|
|
return {field: value for field, value in row.items() if "cost" in field}
|
|
|
|
|
|
def test_bedrock_mantle_route_rows_price_like_their_bedrock_mantle_provider_rows(prices: dict) -> None:
|
|
assert _mantle_route_rows_priced_apart_from_their_provider_row(prices) == ()
|
|
|
|
|
|
@pytest.mark.parametrize("model", ("anthropic.claude-sonnet-5-5", "anthropic.claude-haiku-5-5"))
|
|
def test_claude_5_5_costs_the_same_on_both_govcloud_bedrock_prefixes(
|
|
model: str, local_model_cost_map: None, prices: dict
|
|
) -> None:
|
|
litellm.register_model({f"bedrock/us-gov-west-1/{model}": prices[f"bedrock/us-gov-west-1/{model}"]})
|
|
litellm.register_model({f"bedrock_mantle/us-gov-west-1/{model}": prices[f"bedrock_mantle/us-gov-west-1/{model}"]})
|
|
tokens: Final = {"prompt_tokens": 1_000_000, "completion_tokens": 1_000_000}
|
|
assert litellm.cost_per_token(model=f"bedrock/us-gov-west-1/{model}", **tokens) == litellm.cost_per_token(
|
|
model=f"bedrock_mantle/us-gov-west-1/{model}", **tokens
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("provider", "region", "model"),
|
|
(
|
|
("bedrock_mantle", "ap-northeast-1", "deepseek.v3.1"),
|
|
("bedrock", "ap-south-1", "amazon.nova-pro-v1:0"),
|
|
("bedrock", "ap-southeast-1", "apac.amazon.nova-lite-v1:0"),
|
|
("azure", None, "us-gov/o3-mini-2025-01-31"),
|
|
),
|
|
)
|
|
def test_regional_catalog_rows_price_the_requested_region(
|
|
provider: str, region: str | None, model: str, local_model_cost_map: None, prices: dict
|
|
) -> None:
|
|
key: Final = f"{provider}/{region}/{model}" if region is not None else f"{provider}/{model}"
|
|
row: Final = prices[key]
|
|
assert litellm.cost_per_token(
|
|
model=model, custom_llm_provider=provider, region_name=region, prompt_tokens=1, completion_tokens=1
|
|
) == pytest.approx((row["input_cost_per_token"], row["output_cost_per_token"]))
|
|
|
|
|
|
@pytest.mark.parametrize("service_tier", ("priority", "flex"))
|
|
@pytest.mark.parametrize(
|
|
("provider", "region", "model"),
|
|
(
|
|
("bedrock_mantle", "ap-northeast-1", "deepseek.v3.1"),
|
|
("bedrock", "ap-south-1", "amazon.nova-pro-v1:0"),
|
|
),
|
|
)
|
|
def test_regional_catalog_rows_price_the_requested_service_tier(
|
|
provider: str, region: str, model: str, service_tier: str, local_model_cost_map: None, prices: dict
|
|
) -> None:
|
|
row: Final = prices[f"{provider}/{region}/{model}"]
|
|
assert litellm.cost_per_token(
|
|
model=model,
|
|
custom_llm_provider=provider,
|
|
region_name=region,
|
|
service_tier=service_tier,
|
|
prompt_tokens=1,
|
|
completion_tokens=1,
|
|
) == pytest.approx(
|
|
(row[f"input_cost_per_token_{service_tier}"], row[f"output_cost_per_token_{service_tier}"])
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("tokens", (0, 1))
|
|
@pytest.mark.parametrize("region", ("ap-northeast-1", "eu-north-1", "us-west-2"))
|
|
@pytest.mark.parametrize("model", ("amazon.nova-2-5-sonic", "amazon.nova-2-sonic-v1:0"))
|
|
def test_regional_sonic_catalog_rows_price_audio_tokens(
|
|
model: str, region: str, tokens: int, local_model_cost_map: None, prices: dict
|
|
) -> None:
|
|
row: Final = prices[f"bedrock/{region}/{model}"]
|
|
assert litellm.cost_per_token(
|
|
model=model,
|
|
custom_llm_provider="bedrock",
|
|
region_name=region,
|
|
prompt_tokens=tokens,
|
|
completion_tokens=tokens,
|
|
usage_object=Usage(
|
|
prompt_tokens=tokens,
|
|
completion_tokens=tokens,
|
|
prompt_tokens_details=PromptTokensDetailsWrapper(audio_tokens=tokens, text_tokens=0),
|
|
completion_tokens_details=CompletionTokensDetailsWrapper(audio_tokens=tokens, text_tokens=0),
|
|
),
|
|
) == pytest.approx((tokens * row["input_cost_per_audio_token"], tokens * row["output_cost_per_audio_token"]))
|
|
|
|
|
|
@pytest.mark.parametrize("above_threshold", (False, True))
|
|
@pytest.mark.parametrize(
|
|
("model", "threshold"),
|
|
(
|
|
("ca.anthropic.claude-haiku-5-5", 100_000),
|
|
("in.openai.gpt-5.6-luna", 272_000),
|
|
("in.openai.gpt-5.6-terra", 272_000),
|
|
),
|
|
)
|
|
def test_geo_catalog_rows_price_the_declared_long_context_boundary(
|
|
model: str, threshold: int, above_threshold: bool, local_model_cost_map: None, prices: dict
|
|
) -> None:
|
|
row: Final = prices[model]
|
|
prompt_tokens: Final = threshold + int(above_threshold)
|
|
suffix: Final = f"_above_{threshold // 1000}k_tokens" if above_threshold else ""
|
|
assert litellm.cost_per_token(
|
|
model=model, custom_llm_provider="bedrock", prompt_tokens=prompt_tokens, completion_tokens=1
|
|
) == pytest.approx((prompt_tokens * row[f"input_cost_per_token{suffix}"], row[f"output_cost_per_token{suffix}"]))
|
|
|
|
|
|
@pytest.mark.parametrize("model", ("openai.gpt-6.2-sol", "openai.gpt-6.2-astra"))
|
|
def test_bedrock_mantle_gpt_6_2_deployments_are_served_by_the_mantle_responses_config(
|
|
model: str, local_model_cost_map: None
|
|
) -> None:
|
|
# A proxy deployment registers its model_info under its own bedrock_mantle/ name. Without a
|
|
# bedrock_mantle row, that registration merges into the bedrock_converse row for the same
|
|
# Bedrock id, Mantle loses its Responses capability, and requests leave unsigned.
|
|
litellm.register_model({f"bedrock_mantle/{model}": {"litellm_provider": "bedrock_mantle", "mode": "responses"}})
|
|
config: Final = ProviderConfigManager.get_provider_responses_api_config(
|
|
provider=litellm.LlmProviders.BEDROCK_MANTLE, model=model
|
|
)
|
|
assert isinstance(config, litellm.BedrockMantleResponsesAPIConfig)
|
|
assert config.get_complete_url(api_base=None, litellm_params={"aws_region_name": "us-east-1"}) == (
|
|
"https://bedrock-mantle.us-east-1.api.aws/openai/v1/responses"
|
|
)
|
|
|
|
|
|
def _rows_carrying_legacy_max_tokens(prices: Mapping[str, Mapping[str, object]]) -> tuple[str, ...]:
|
|
return tuple(key for key, row in prices.items() if "max_tokens" in row)
|
|
|
|
|
|
def test_no_row_carries_the_retired_max_tokens_field(prices: dict) -> None:
|
|
assert _rows_carrying_legacy_max_tokens(prices) == ()
|
|
|
|
|
|
def test_github_copilot_backup_rows_match_the_main_catalog() -> None:
|
|
assert _github_copilot_catalog_rows(PRICES_PATH) == _github_copilot_catalog_rows(BACKUP_PRICES_PATH)
|
|
|
|
|
|
class _TokenLimits(BaseModel):
|
|
model_config = ConfigDict(frozen=True, extra="ignore")
|
|
|
|
max_input_tokens: int
|
|
max_output_tokens: int
|
|
|
|
|
|
@pytest.mark.parametrize("path", (PRICES_PATH, BACKUP_PRICES_PATH), ids=("main", "backup"))
|
|
def test_zerogpu_rows_have_an_output_limit_that_fits_the_context_window(path: Path) -> None:
|
|
prices: Final[dict[str, JsonValue]] = TypeAdapter(dict[str, JsonValue]).validate_json(path.read_bytes())
|
|
rows: Final = MappingProxyType(
|
|
{key: _TokenLimits.model_validate(value) for key, value in prices.items() if key.startswith("zerogpu/")}
|
|
)
|
|
assert rows, f"No ZeroGPU rows found in {path}"
|
|
assert tuple(key for key, row in rows.items() if row.max_output_tokens > row.max_input_tokens) == ()
|
|
|
|
|
|
def test_github_copilot_rows_resolve_through_get_model_info() -> None:
|
|
rows: Final[Mapping[str, _CopilotEndpointRow]] = _copilot_endpoint_rows(PRICES_PATH)
|
|
assert {
|
|
key: (litellm.get_model_info(key)["mode"], litellm.get_model_info(key)["max_input_tokens"]) for key in rows
|
|
} == {key: (row.mode, row.max_input_tokens) for key, row in rows.items()}
|
|
|
|
|
|
def test_github_copilot_rows_keep_the_reasoning_flag_their_family_fallback_supplies() -> None:
|
|
reasoning_rows: Final = tuple(
|
|
key
|
|
for key in _copilot_endpoint_rows(PRICES_PATH)
|
|
if (match_capability_generalizations(key) or {}).get("supports_reasoning") is True
|
|
)
|
|
prices: Final[dict[str, JsonValue]] = TypeAdapter(dict[str, JsonValue]).validate_json(PRICES_PATH.read_bytes())
|
|
assert reasoning_rows
|
|
assert {key: _thinking_capabilities(prices, key).supports_reasoning for key in reasoning_rows} == dict.fromkeys(
|
|
reasoning_rows, True
|
|
)
|
|
assert {key: litellm.get_model_info(key).get("supports_reasoning") for key in reasoning_rows} == dict.fromkeys(
|
|
reasoning_rows, True
|
|
)
|
|
assert {
|
|
key: resolve_supported_reasoning_efforts(
|
|
litellm.get_model_info(key),
|
|
deployment_is_mapped=True,
|
|
)
|
|
!= ()
|
|
for key in reasoning_rows
|
|
} == dict.fromkeys(reasoning_rows, True)
|
|
|
|
|
|
def test_github_copilot_messages_claude_rows_keep_their_anthropic_thinking_capabilities() -> None:
|
|
prices: Final[dict[str, JsonValue]] = TypeAdapter(dict[str, JsonValue]).validate_json(PRICES_PATH.read_bytes())
|
|
claude_rows: Final = tuple(
|
|
key
|
|
for key, row in _copilot_endpoint_rows(PRICES_PATH).items()
|
|
if key.startswith("github_copilot/claude-") and "/v1/messages" in row.supported_endpoints
|
|
)
|
|
assert claude_rows
|
|
assert {key: _thinking_capabilities(prices, key) for key in claude_rows} == {
|
|
key: _thinking_capabilities(prices, _anthropic_counterpart(key)) for key in claude_rows
|
|
}
|
|
assert {
|
|
key: tuple(litellm.get_model_info(key).get(thinking_key) for thinking_key in _THINKING_KEYS)
|
|
for key in claude_rows
|
|
} == {
|
|
key: tuple(
|
|
litellm.get_model_info(_anthropic_counterpart(key)).get(thinking_key) for thinking_key in _THINKING_KEYS
|
|
)
|
|
for key in claude_rows
|
|
}
|
|
|
|
|
|
def find_duplicate_keys(path: Path) -> list[str]:
|
|
duplicates: list[str] = []
|
|
|
|
def record_duplicates(pairs):
|
|
seen: set[str] = set()
|
|
for key, _ in pairs:
|
|
if key in seen:
|
|
duplicates.append(key)
|
|
seen.add(key)
|
|
return dict(pairs)
|
|
|
|
json.loads(path.read_text(), object_pairs_hook=record_duplicates)
|
|
return duplicates
|
|
|
|
|
|
@pytest.mark.parametrize("path", (PRICES_PATH, BACKUP_PRICES_PATH), ids=("main", "backup"))
|
|
def test_price_map_has_no_duplicate_keys(path: Path):
|
|
assert find_duplicate_keys(path) == [], (
|
|
f"{path.name} defines the same key twice; JSON parsers keep only the last "
|
|
"occurrence, so the earlier entry's fields are silently dropped. This is what "
|
|
"a clean text merge of two branches that both added a model looks like: "
|
|
"deduplicate the keys into one entry"
|
|
)
|
|
|
|
|
|
DATED_VARIANT = re.compile(r"^(.*?)-(\d{4}-\d{2}-\d{2})$")
|
|
SERVICE_TIER_SUFFIXES = ("_flex", "_priority")
|
|
|
|
|
|
def tier_anchor(tier_key: str) -> str:
|
|
matched = next(suffix for suffix in SERVICE_TIER_SUFFIXES if tier_key.endswith(suffix))
|
|
return tier_key[: -len(matched)]
|
|
|
|
|
|
def test_dated_variants_carry_base_alias_service_tier_pricing(prices: dict):
|
|
drifted = [
|
|
f"{name}: missing {tier_key}={base[tier_key]} (base alias {match.group(1)})"
|
|
for name, entry in prices.items()
|
|
if isinstance(entry, dict)
|
|
for match in [DATED_VARIANT.match(name)]
|
|
if match is not None
|
|
for base in [prices.get(match.group(1))]
|
|
if isinstance(base, dict)
|
|
for tier_key in base
|
|
if tier_key.endswith(SERVICE_TIER_SUFFIXES)
|
|
and tier_anchor(tier_key) in base
|
|
and entry.get(tier_anchor(tier_key)) == base[tier_anchor(tier_key)]
|
|
and entry.get(tier_key) != base[tier_key]
|
|
]
|
|
assert drifted == [], (
|
|
"dated model variants are missing flex/priority pricing their base alias has; "
|
|
"sync the tier keys so service-tier requests against pinned snapshots are not "
|
|
"billed at standard rates:\n" + "\n".join(drifted)
|
|
)
|
|
|
|
|
|
# Azure OpenAI web_search runs on Grounding with Bing and bills each Bing request reported in
|
|
# tool_usage.web_search.num_requests: https://learn.microsoft.com/en-us/azure/foundry/openai/how-to/web-search
|
|
# Grounding with Bing lists $14 per 1,000 transactions: https://www.microsoft.com/en-us/bing/apis/grounding-pricing
|
|
AZURE_WEB_SEARCH_COST_PER_REQUEST: Final = 0.014
|
|
_AZURE_DEPLOYMENT_PREFIX: Final = re.compile(r"^azure/(us/|eu/|global/|global-standard/)?")
|
|
|
|
|
|
def _azure_rows(prices: Mapping[str, object]) -> Mapping[str, dict]:
|
|
return MappingProxyType(
|
|
{key: row for key, row in prices.items() if key.startswith("azure/") and isinstance(row, dict)}
|
|
)
|
|
|
|
|
|
def test_azure_web_search_rows_charge_the_grounding_with_bing_price(prices: dict):
|
|
wrong = {
|
|
key: row["search_context_cost_per_query"]
|
|
for key, row in _azure_rows(prices).items()
|
|
if row.get("search_context_cost_per_query")
|
|
and set(row["search_context_cost_per_query"].values()) != {AZURE_WEB_SEARCH_COST_PER_REQUEST}
|
|
}
|
|
assert wrong == {}
|
|
|
|
|
|
def test_azure_rows_price_web_search_when_their_openai_model_does(prices: dict):
|
|
missing = sorted(
|
|
key
|
|
for key, row in _azure_rows(prices).items()
|
|
if not row.get("search_context_cost_per_query")
|
|
and row.get("mode") in ("chat", "responses", None)
|
|
and isinstance(twin := prices.get(_AZURE_DEPLOYMENT_PREFIX.sub("", key)), dict)
|
|
and twin.get("search_context_cost_per_query")
|
|
)
|
|
assert missing == []
|
|
|
|
|
|
PRIORITY_SUFFIX: Final = "_priority"
|
|
MIN_PRIORITY_MARKUP: Final = 1.0
|
|
MAX_PRIORITY_MARKUP: Final = 5.0
|
|
# Vertex pricing, verified 2026-11-03: https://cloud.google.com/gemini-enterprise-agent-platform/generative-ai/pricing
|
|
VERIFIED_PRIORITY_MARKUP_MAXIMA: Final = MappingProxyType(
|
|
{("gemini-2.5-flash", "input_cost_per_audio_token_above_200k_tokens_priority"): 6.0}
|
|
)
|
|
|
|
|
|
def _rate(value: JsonValue | None) -> float | None:
|
|
return float(value) if isinstance(value, (int, float)) and not isinstance(value, bool) else None
|
|
|
|
|
|
def _priority_markup(entry: Mapping[str, JsonValue], key: str) -> float | None:
|
|
if not key.endswith(PRIORITY_SUFFIX):
|
|
return None
|
|
priority: Final = _rate(entry[key])
|
|
standard: Final = _rate(entry.get(key.removesuffix(PRIORITY_SUFFIX)))
|
|
if priority is None or standard is None or standard <= 0:
|
|
return None
|
|
return priority / standard
|
|
|
|
|
|
def priority_markups(prices: Mapping[str, JsonValue]) -> Iterator[tuple[str, str, float]]:
|
|
for name, entry in prices.items():
|
|
if not isinstance(entry, dict):
|
|
continue
|
|
for key in entry:
|
|
if (markup := _priority_markup(entry, key)) is not None:
|
|
yield name, key, markup
|
|
|
|
|
|
@pytest.mark.parametrize("path", (PRICES_PATH, BACKUP_PRICES_PATH), ids=("main", "backup"))
|
|
def test_priority_rates_stay_within_a_premium_of_their_standard_rate(path: Path) -> None:
|
|
prices: Final = TypeAdapter(dict[str, JsonValue]).validate_json(path.read_bytes())
|
|
markups: Final = tuple(priority_markups(prices))
|
|
assert markups
|
|
overpriced: Final = tuple(
|
|
f"{name}.{key} is {markup:.1f}x its standard rate"
|
|
for name, key, markup in markups
|
|
if not MIN_PRIORITY_MARKUP <= markup <= VERIFIED_PRIORITY_MARKUP_MAXIMA.get((name, key), MAX_PRIORITY_MARKUP)
|
|
)
|
|
assert overpriced == (), (
|
|
"a priority rate is a premium on the standard rate, so one below it or far above it was likely copied from "
|
|
"another model; drop the key when the provider sells no priority tier for the model:\n" + "\n".join(overpriced)
|
|
)
|
|
|
|
|
|
# Azure Foundry GPT-6.1 Sol announcement, 2026-09-29: https://techcommunity.microsoft.com/blog/azure-ai-foundry-blog/introducing-gpt-6-1-sol-in-microsoft-foundry-advanced-intelligence-optimized-for/4560811
|
|
AZURE_GPT_6_1_SOL_REGIONAL_PREMIUM: Final = MappingProxyType({"us": 1.1, "eu": 1.2, "apac": 1.2})
|
|
|
|
|
|
@pytest.mark.parametrize("region", sorted(AZURE_GPT_6_1_SOL_REGIONAL_PREMIUM))
|
|
def test_azure_gpt_6_1_sol_data_zone_rows_charge_the_global_web_search_price(prices: dict, region: str):
|
|
global_search_cost = prices["azure/gpt-6.1-sol"]["search_context_cost_per_query"]
|
|
assert global_search_cost
|
|
assert prices[f"azure/{region}/gpt-6.1-sol"].get("search_context_cost_per_query") == global_search_cost
|
|
|
|
|
|
@pytest.mark.parametrize("region", sorted(AZURE_GPT_6_1_SOL_REGIONAL_PREMIUM))
|
|
def test_azure_gpt_6_1_sol_data_zone_rows_price_requests_at_the_regional_premium(region: str):
|
|
premium = AZURE_GPT_6_1_SOL_REGIONAL_PREMIUM[region]
|
|
usage = {"prompt_tokens": 300_000, "completion_tokens": 1_000, "cache_read_input_tokens": 100_000}
|
|
|
|
def total_cost(model: str) -> float:
|
|
prompt_cost, completion_cost = litellm.cost_per_token(
|
|
model=model,
|
|
custom_llm_provider="azure",
|
|
prompt_tokens=usage["prompt_tokens"],
|
|
completion_tokens=usage["completion_tokens"],
|
|
cache_read_input_tokens=usage["cache_read_input_tokens"],
|
|
)
|
|
return prompt_cost + completion_cost
|
|
|
|
global_cost = total_cost("azure/gpt-6.1-sol")
|
|
assert global_cost > 0
|
|
assert total_cost(f"azure/{region}/gpt-6.1-sol") == pytest.approx(global_cost * premium)
|
|
|
|
|
|
AZURE_GPT_6_1_SOL_ROWS: Final = (
|
|
"azure/gpt-6.1-sol",
|
|
"azure/gpt-6.1-sol-2026-09-29",
|
|
"azure/us/gpt-6.1-sol",
|
|
"azure/eu/gpt-6.1-sol",
|
|
"azure/apac/gpt-6.1-sol",
|
|
"azure_ai/gpt-6.1-sol",
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("row", AZURE_GPT_6_1_SOL_ROWS)
|
|
def test_azure_gpt_6_1_sol_rows_accept_the_same_reasoning_efforts_as_the_openai_row(prices: dict, row: str):
|
|
openai_efforts: Final = resolve_supported_reasoning_efforts(prices["gpt-6.1-sol"], deployment_is_mapped=True)
|
|
assert openai_efforts
|
|
|
|
assert resolve_supported_reasoning_efforts(prices[row], deployment_is_mapped=True) == openai_efforts
|
|
|
|
|
|
# https://ai.google.dev/gemini-api/docs/models/deep-research-preview-04-2026
|
|
@pytest.mark.parametrize("model", ["gemini/deep-research-preview-04-2026", "gemini/deep-research-max-preview-04-2026"])
|
|
def test_gemini_deep_research_previews_accept_the_documented_input_window(prices: dict, model: str):
|
|
assert prices[model]["max_input_tokens"] == 1_048_576
|
|
assert prices[model]["max_output_tokens"] == 65_536
|
|
|
|
|
|
# https://cloud.google.com/vertex-ai/generative-ai/docs/learn/model-versions, checked 2026-11-21
|
|
VERTEX_GEMINI_FLASH_RETIREMENT_DATES: Final = MappingProxyType(
|
|
{"gemini-3.6-flash": "2027-01-28", "gemini-3.7-flash": "2027-01-28"}
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("model", sorted(VERTEX_GEMINI_FLASH_RETIREMENT_DATES))
|
|
@pytest.mark.parametrize("prefix", ["", "vertex_ai/"])
|
|
def test_vertex_gemini_flash_rows_carry_the_documented_retirement_date(prices: dict, model: str, prefix: str):
|
|
assert prices[f"{prefix}{model}"]["deprecation_date"] == VERTEX_GEMINI_FLASH_RETIREMENT_DATES[model]
|
|
|
|
|
|
# https://developers.openai.com/api/docs/deprecations, the 2026-10-14 GPT-4 series notice
|
|
OPENAI_GPT_4_SERIES_SNAPSHOTS: Final = MappingProxyType(
|
|
{
|
|
"gpt-4o": ("gpt-4o-2024-08-06", "gpt-4o-2024-11-20"),
|
|
"gpt-4o-mini": ("gpt-4o-mini-2024-07-18",),
|
|
"gpt-4.1": ("gpt-4.1-2025-04-14",),
|
|
"gpt-4.1-mini": ("gpt-4.1-mini-2025-04-14",),
|
|
}
|
|
)
|
|
|
|
|
|
class _ShutdownRow(BaseModel):
|
|
model_config = ConfigDict(frozen=True, extra="ignore")
|
|
|
|
deprecation_date: str | None = None
|
|
|
|
|
|
@pytest.mark.parametrize("path", (PRICES_PATH, BACKUP_PRICES_PATH), ids=("main", "backup"))
|
|
@pytest.mark.parametrize("alias", sorted(OPENAI_GPT_4_SERIES_SNAPSHOTS))
|
|
def test_openai_gpt_4_series_aliases_retire_with_their_snapshots(path: Path, alias: str) -> None:
|
|
prices: Final[dict[str, JsonValue]] = TypeAdapter(dict[str, JsonValue]).validate_json(path.read_bytes())
|
|
snapshot_dates: Final = frozenset(
|
|
_ShutdownRow.model_validate(prices[snapshot]).deprecation_date
|
|
for snapshot in OPENAI_GPT_4_SERIES_SNAPSHOTS[alias]
|
|
)
|
|
assert snapshot_dates == {_ShutdownRow.model_validate(prices[alias]).deprecation_date}
|
|
|
|
|
|
def _sampling_flags_across_provider_twins(prices: Mapping[str, Mapping[str, object]], key: str) -> frozenset[object]:
|
|
bare: Final = key.split("/")[-1]
|
|
twins: Final = tuple(twin for twin in (bare, f"vertex_ai/{bare}", f"gemini/{bare}") if twin in prices)
|
|
return frozenset(prices[twin].get("supports_sampling_params") for twin in (key, *twins))
|
|
|
|
|
|
def test_gemini_rows_agree_on_supports_sampling_params_across_their_provider_twins(
|
|
prices: Mapping[str, Mapping[str, object]],
|
|
) -> None:
|
|
"""The bare, vertex_ai/ and gemini/ rows of one Gemini model gate sampling params identically, so a request
|
|
takes the same drop-or-400 path on the Vertex route and the AI Studio route"""
|
|
flagged: Final = tuple(
|
|
key
|
|
for key, row in prices.items()
|
|
if "supports_sampling_params" in row and key.split("/")[-1].startswith("gemini-")
|
|
)
|
|
assert flagged
|
|
for key in flagged:
|
|
assert len(_sampling_flags_across_provider_twins(prices, key)) == 1, key
|
|
|
|
|
|
OPENAI_REASONING_FAMILY_MARKERS = ("codex", "deep-research", "chat-latest")
|
|
|
|
|
|
def is_openai_o_series(name: str) -> bool:
|
|
return len(name) > 1 and name[0] == "o" and name[1].isdigit()
|
|
|
|
|
|
def is_openai_reasoning_family(name: str) -> bool:
|
|
base = name.split("/")[-1].removeprefix("ft:")
|
|
if "search-api" in base:
|
|
return False
|
|
return (
|
|
is_openai_o_series(base)
|
|
or is_gpt_reasoning_series_name(base)
|
|
or any(marker in base for marker in OPENAI_REASONING_FAMILY_MARKERS)
|
|
)
|
|
|
|
|
|
def test_openai_reasoning_family_entries_carry_supports_reasoning(prices: dict):
|
|
unflagged = [
|
|
name
|
|
for name, entry in prices.items()
|
|
if isinstance(entry, dict)
|
|
and entry.get("litellm_provider") == "openai"
|
|
and is_openai_reasoning_family(name)
|
|
and entry.get("supports_reasoning") is not True
|
|
]
|
|
assert unflagged == [], (
|
|
"OpenAI o-series, gpt-5+, codex, deep-research, and chat-latest models are reasoning "
|
|
"models, and the Responses API drops the `reasoning` param for any mapped OpenAI model "
|
|
"whose entry lacks supports_reasoning; flag these entries:\n" + "\n".join(unflagged)
|
|
)
|
|
|
|
|
|
_ABSENT: Final = object()
|
|
|
|
REASONING_ANNOTATION_KEYS: Final = (
|
|
"supports_reasoning",
|
|
"supports_minimal_reasoning_effort",
|
|
"supports_none_reasoning_effort",
|
|
"supports_xhigh_reasoning_effort",
|
|
"default_reasoning_effort",
|
|
)
|
|
|
|
|
|
def chatgpt_openai_twins(prices: dict) -> list[tuple[str, str]]:
|
|
"""`chatgpt/<model>` rows paired with the bare `<model>` row served by the openai provider.
|
|
|
|
Scoped to openai twins on purpose. `ChatGPTConfig` and `ChatGPTResponsesAPIConfig` subclass
|
|
their openai counterparts, so a chatgpt row's reasoning behaviour is whatever the openai row
|
|
describes. The azure rows are a separate registry that already diverges from openai here, and
|
|
pinning them to each other would assert something this repository does not control.
|
|
"""
|
|
pairs = []
|
|
for name, entry in prices.items():
|
|
if not isinstance(entry, dict) or not name.startswith("chatgpt/"):
|
|
continue
|
|
bare = name.split("/", 1)[1]
|
|
twin = prices.get(bare)
|
|
if isinstance(twin, dict) and twin.get("litellm_provider") == "openai":
|
|
pairs.append((name, bare))
|
|
return pairs
|
|
|
|
|
|
def test_chatgpt_rows_carry_their_openai_twin_reasoning_annotations(prices: dict):
|
|
"""A chatgpt row must not silently drop the reasoning annotations of the model it proxies.
|
|
|
|
`litellm.utils._get_model_info_from_generalization` refuses to fall back when an exact cost-map
|
|
key exists, so an unannotated `chatgpt/<model>` row wins over its annotated twin and
|
|
`/model/info` reports the model as non-reasoning.
|
|
"""
|
|
twins = chatgpt_openai_twins(prices)
|
|
assert twins, "no chatgpt/* row has an openai twin any more; this guard has stopped guarding"
|
|
|
|
mismatched = []
|
|
for name, bare in twins:
|
|
for key in REASONING_ANNOTATION_KEYS:
|
|
if prices[name].get(key, _ABSENT) != prices[bare].get(key, _ABSENT):
|
|
mismatched.append(
|
|
f"{name}.{key} is {prices[name].get(key)!r}, {bare}.{key} is {prices[bare].get(key)!r}"
|
|
)
|
|
|
|
assert mismatched == [], (
|
|
"chatgpt/* entries proxy their openai twin through ChatGPTConfig, so they must carry the "
|
|
"same reasoning annotations; an exact cost-map key blocks the generalization fallback, so "
|
|
"a missing flag here is reported to callers as 'not a reasoning model':\n" + "\n".join(mismatched)
|
|
)
|
|
|
|
|
|
def test_chat_latest_declares_the_one_effort_openai_accepts(prices: dict):
|
|
"""OpenAI rejects every reasoning.effort on chat-latest except medium, and a reasoning entry
|
|
with no declared levels resolves to None, which lets /model_group/info and the dashboard offer
|
|
levels the upstream will 400 on."""
|
|
assert resolve_supported_reasoning_efforts(prices["chat-latest"], deployment_is_mapped=True) == ("medium",)
|
|
|
|
|
|
@pytest.mark.parametrize("key", ["azure/gpt-chat-latest", "azure/chat-latest", "azure/us/gpt-chat-latest"])
|
|
def test_azure_gpt_chat_latest_declares_the_one_effort_azure_accepts(prices: dict, key: str):
|
|
"""Azure answers every reasoning_effort on a gpt-chat-latest deployment except medium with
|
|
"Unsupported value ... Supported values are: 'medium'", the same fixed level OpenAI's chat-latest
|
|
carries, so the Foundry product name and the OpenAI API name both declare that one level."""
|
|
assert resolve_supported_reasoning_efforts(prices[key], deployment_is_mapped=True) == ("medium",)
|
|
|
|
|
|
BEDROCK_OPENAI_GPT_MARKERS: Final = ("openai.gpt-5.4", "openai.gpt-5.5", "openai.gpt-5.6", "openai.gpt-6-astra")
|
|
BEDROCK_PROVIDERS: Final = frozenset(("bedrock", "bedrock_converse", "bedrock_mantle"))
|
|
BEDROCK_ROW_PREFIXES: Final = ("bedrock_mantle/", "us.", "global.")
|
|
GPT_5_4_BEDROCK_LADDER: Final = ("none", "low", "medium", "high", "xhigh")
|
|
GPT_5_6_BEDROCK_LADDER: Final = ("none", "low", "medium", "high", "xhigh", "max")
|
|
GPT_6_ASTRA_BEDROCK_LADDER: Final = ("low", "medium", "high", "xhigh", "max")
|
|
BEDROCK_OPENAI_GPT_LADDERS: Final = MappingProxyType(
|
|
{
|
|
"bedrock_mantle/openai.gpt-5.4": GPT_5_4_BEDROCK_LADDER,
|
|
"bedrock_mantle/openai.gpt-5.5": GPT_5_4_BEDROCK_LADDER,
|
|
**{
|
|
f"{prefix}openai.gpt-5.6-{variant}": GPT_5_6_BEDROCK_LADDER
|
|
for prefix in BEDROCK_ROW_PREFIXES
|
|
for variant in ("luna", "sol", "terra")
|
|
},
|
|
**{f"{prefix}openai.gpt-6-astra": GPT_6_ASTRA_BEDROCK_LADDER for prefix in BEDROCK_ROW_PREFIXES},
|
|
}
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("name", "ladder"), tuple(BEDROCK_OPENAI_GPT_LADDERS.items()), ids=tuple(BEDROCK_OPENAI_GPT_LADDERS)
|
|
)
|
|
def test_bedrock_openai_gpt_rows_advertise_the_ladder_bedrock_accepts(prices: dict, name: str, ladder: tuple[str, ...]):
|
|
"""Each ladder is the set of levels Bedrock answered 200 to for that row through the proxy on
|
|
2026-09-11 (PR #40740): the Mantle rows go out over its Responses endpoint and the Converse rows
|
|
over inference profiles. Bedrock differs from the direct OpenAI rows in two places, gpt-5.6 and
|
|
gpt-6-astra take max there, and gpt-6-astra refuses none; minimal is refused on every row.
|
|
xhigh and max are opt-in for the resolver, so a row missing either flag silently drops that
|
|
level from every group it belongs to."""
|
|
assert resolve_supported_reasoning_efforts(prices[name], deployment_is_mapped=True) == ladder
|
|
|
|
|
|
def test_every_bedrock_openai_gpt_row_advertises_xhigh(prices: dict):
|
|
"""The GovCloud and gpt-5.6-cyber rows cannot be called from our account, so they carry the
|
|
family's xhigh flag rather than a measured ladder."""
|
|
missing: Final = [
|
|
name
|
|
for name, entry in prices.items()
|
|
if isinstance(entry, dict)
|
|
and entry.get("litellm_provider") in BEDROCK_PROVIDERS
|
|
and any(marker in name for marker in BEDROCK_OPENAI_GPT_MARKERS)
|
|
and "xhigh" not in (resolve_supported_reasoning_efforts(entry, deployment_is_mapped=True) or ())
|
|
]
|
|
assert missing == []
|
|
|
|
|
|
def is_active_priced_mistral_chat_row(name: str, entry: Mapping[str, object]) -> bool:
|
|
input_cost: Final = entry.get("input_cost_per_token")
|
|
return (
|
|
name.startswith("mistral/")
|
|
and entry.get("mode") == "chat"
|
|
and entry.get("deprecation_date") is None
|
|
and isinstance(input_cost, (int, float))
|
|
and input_cost > 0
|
|
)
|
|
|
|
|
|
def cache_read_is_below_input(entry: Mapping[str, object]) -> bool:
|
|
cache_read: Final = entry.get("cache_read_input_token_cost")
|
|
input_cost: Final = entry.get("input_cost_per_token")
|
|
return isinstance(cache_read, float) and isinstance(input_cost, (int, float)) and 0 < cache_read < input_cost
|
|
|
|
|
|
@pytest.mark.parametrize("path", (PRICES_PATH, BACKUP_PRICES_PATH), ids=("main", "backup"))
|
|
def test_active_mistral_chat_rows_price_cache_reads_below_input(path: Path):
|
|
"""A Mistral chat row without a cache-read rate bills cached prompt tokens at zero, so every
|
|
active priced row must carry one, and it must be cheaper than a fresh input token."""
|
|
rows: Mapping[str, object] = json.loads(path.read_text())
|
|
drifted: Final = [
|
|
f"{name}: cache_read={entry.get('cache_read_input_token_cost')} input={entry.get('input_cost_per_token')}"
|
|
for name, entry in rows.items()
|
|
if isinstance(entry, dict)
|
|
and is_active_priced_mistral_chat_row(name, entry)
|
|
and not cache_read_is_below_input(entry)
|
|
]
|
|
assert drifted == []
|
|
|
|
|
|
DEEPSEEK_PRICED_ROWS: Final = tuple(
|
|
f"{prefix}{name}"
|
|
for name in ("deepseek-flash", "deepseek-v4-flash", "deepseek-v4-flash-vision-exp", "deepseek-v4-pro")
|
|
for prefix in ("", "deepseek/")
|
|
)
|
|
DEEPSEEK_OFF_PEAK_WINDOWS: Final = (
|
|
{"hours_utc": ["00:00-01:00", "04:00-06:00", "10:00-00:00"], "weekdays": [1, 2, 3, 4, 5]},
|
|
{"hours_utc": "00:00-00:00", "weekdays": [6, 7]},
|
|
)
|
|
DEEPSEEK_HALVED_RATES: Final = ("input_cost_per_token", "output_cost_per_token", "cache_read_input_token_cost")
|
|
TENCENT_TOKENHUB_DEEPSEEK_PRICED_ROWS: Final = (
|
|
"tencent/deepseek-v4-pro-0813",
|
|
"tencent/deepseek-v4.1-flash",
|
|
)
|
|
TENCENT_TOKENHUB_GLM_ROWS: Final = MappingProxyType(
|
|
{
|
|
"tencent/glm-5.3-flashx": (3.7e-07, 1.25e-06, 7.5e-08, True, True),
|
|
"tencent/glm-5.3-flash": (1.5e-07, 5e-07, 3e-08, True, True),
|
|
"tencent/glm-5.3": (1.4e-06, 4.4e-06, 2.6e-07, False, False),
|
|
"tencent/glm-5.2": (1.4e-06, 4.4e-06, 2.6e-07, False, False),
|
|
}
|
|
)
|
|
TENCENT_TOKENHUB_KIMI_ROWS: Final = MappingProxyType(
|
|
{
|
|
"tencent/kimi-k3": (3e-06, 1.5e-05, 3e-07, 1000000, False, False),
|
|
"tencent/kimi-k2.8-preview": (1e-06, 4e-06, 2.5e-07, 1000000, False, False),
|
|
"tencent/kimi-k2.7-code-highspeed": (1.9e-06, 8e-06, 3.8e-07, 256000, False, False),
|
|
"tencent/kimi-k2.7-code": (9.5e-07, 4e-06, 1.9e-07, 256000, False, False),
|
|
}
|
|
)
|
|
|
|
|
|
def deepseek_off_peak_drift(entry: Mapping[str, object]) -> str | None:
|
|
block: Final = entry.get("off_peak_pricing")
|
|
if not isinstance(block, dict):
|
|
return "no off_peak_pricing block"
|
|
if tuple(block.get("windows", ())) != DEEPSEEK_OFF_PEAK_WINDOWS:
|
|
return f"windows={block.get('windows')}"
|
|
halved: Final = {rate: block.get(rate) for rate in DEEPSEEK_HALVED_RATES}
|
|
expected: Final = {rate: float(str(entry[rate])) / 2 for rate in DEEPSEEK_HALVED_RATES}
|
|
mismatched: Final = {
|
|
rate for rate in DEEPSEEK_HALVED_RATES if halved[rate] != pytest.approx(expected[rate], rel=1e-9)
|
|
}
|
|
return f"off-peak rates {halved} are not half of the listed rates" if mismatched else None
|
|
|
|
|
|
@pytest.mark.parametrize("path", (PRICES_PATH, BACKUP_PRICES_PATH), ids=("main", "backup"))
|
|
def test_deepseek_rows_bill_half_rate_outside_weekday_peak_hours(path: Path):
|
|
"""DeepSeek charges half its listed rate outside 01:00-04:00 and 06:00-10:00 UTC Monday to
|
|
Friday (api-docs.deepseek.com/quick_start/pricing, read 2026-09-19), so every row on that
|
|
pricing page carries an off_peak_pricing block with those windows and the halved rates."""
|
|
rows: Mapping[str, object] = json.loads(path.read_text())
|
|
drifted: Final = {
|
|
name: deepseek_off_peak_drift(entry)
|
|
for name in DEEPSEEK_PRICED_ROWS
|
|
if isinstance(entry := rows.get(name), dict) and deepseek_off_peak_drift(entry) is not None
|
|
}
|
|
assert drifted == {}
|
|
assert all(name in rows for name in DEEPSEEK_PRICED_ROWS)
|
|
|
|
|
|
@pytest.mark.parametrize("path", (PRICES_PATH, BACKUP_PRICES_PATH), ids=("main", "backup"))
|
|
def test_tencent_tokenhub_deepseek_rows_bill_half_rate_outside_weekday_peak_hours(path: Path):
|
|
"""Tencent TokenHub applies the DeepSeek weekday peak windows and half-rate off-peak prices
|
|
to these models (tencentcloud.com/document/product/1300/78937, read 2026-10-13)."""
|
|
rows: Mapping[str, object] = json.loads(path.read_text())
|
|
drifted: Final = {
|
|
name: deepseek_off_peak_drift(entry)
|
|
for name in TENCENT_TOKENHUB_DEEPSEEK_PRICED_ROWS
|
|
if isinstance(entry := rows.get(name), dict) and deepseek_off_peak_drift(entry) is not None
|
|
}
|
|
invalid_timezones: Final = tuple(
|
|
name
|
|
for name in TENCENT_TOKENHUB_DEEPSEEK_PRICED_ROWS
|
|
if isinstance(entry := rows.get(name), dict)
|
|
and isinstance(block := entry.get("off_peak_pricing"), dict)
|
|
and block.get("weekday_timezone") != "Asia/Shanghai"
|
|
)
|
|
assert drifted == {}
|
|
assert all(name in rows for name in TENCENT_TOKENHUB_DEEPSEEK_PRICED_ROWS)
|
|
assert invalid_timezones == ()
|
|
|
|
|
|
@pytest.mark.parametrize("path", (PRICES_PATH, BACKUP_PRICES_PATH), ids=("main", "backup"))
|
|
def test_tencent_tokenhub_glm_rows_match_published_metadata(path: Path):
|
|
"""TokenHub publishes these prices and capabilities in its official model catalog and rate card
|
|
(tencentcloud.com/document/product/1300/78934 and /78937, read 2026-10-13)."""
|
|
rows: Mapping[str, object] = json.loads(path.read_text())
|
|
actual: Final = MappingProxyType(
|
|
{
|
|
name: (
|
|
entry.get("input_cost_per_token"),
|
|
entry.get("output_cost_per_token"),
|
|
entry.get("cache_read_input_token_cost"),
|
|
entry.get("supports_vision", False),
|
|
entry.get("supports_video_input", False),
|
|
)
|
|
for name in TENCENT_TOKENHUB_GLM_ROWS
|
|
if isinstance(entry := rows.get(name), dict)
|
|
}
|
|
)
|
|
invalid_metadata: Final = tuple(
|
|
name
|
|
for name in TENCENT_TOKENHUB_GLM_ROWS
|
|
if not isinstance(entry := rows.get(name), dict)
|
|
or entry.get("litellm_provider") != "tencent"
|
|
or entry.get("max_input_tokens") != 1000000
|
|
or entry.get("max_output_tokens") != 128000
|
|
or entry.get("input_cost_per_token_cache_hit") != entry.get("cache_read_input_token_cost")
|
|
)
|
|
assert actual == TENCENT_TOKENHUB_GLM_ROWS
|
|
assert invalid_metadata == ()
|
|
|
|
|
|
@pytest.mark.parametrize("path", (PRICES_PATH, BACKUP_PRICES_PATH), ids=("main", "backup"))
|
|
def test_tencent_tokenhub_kimi_rows_match_published_metadata(path: Path):
|
|
"""TokenHub publishes these Kimi prices and capabilities in its official model catalog and rate card
|
|
(tencentcloud.com/document/product/1300/78934 and /78937, read 2026-10-13)."""
|
|
rows: Mapping[str, object] = json.loads(path.read_text())
|
|
actual: Final = MappingProxyType(
|
|
{
|
|
name: (
|
|
entry.get("input_cost_per_token"),
|
|
entry.get("output_cost_per_token"),
|
|
entry.get("cache_read_input_token_cost"),
|
|
entry.get("max_output_tokens"),
|
|
entry.get("supports_vision", False),
|
|
entry.get("supports_video_input", False),
|
|
)
|
|
for name in TENCENT_TOKENHUB_KIMI_ROWS
|
|
if isinstance(entry := rows.get(name), dict)
|
|
}
|
|
)
|
|
invalid_metadata: Final = tuple(
|
|
name
|
|
for name, expected in TENCENT_TOKENHUB_KIMI_ROWS.items()
|
|
if not isinstance(entry := rows.get(name), dict)
|
|
or entry.get("litellm_provider") != "tencent"
|
|
or entry.get("max_input_tokens") != expected[3]
|
|
or entry.get("max_output_tokens") != expected[3]
|
|
or entry.get("input_cost_per_token_cache_hit") != entry.get("cache_read_input_token_cost")
|
|
or not entry.get("supports_reasoning")
|
|
or not entry.get("supports_response_schema")
|
|
or not entry.get("supports_function_calling")
|
|
or not entry.get("supports_prompt_caching")
|
|
)
|
|
assert actual == TENCENT_TOKENHUB_KIMI_ROWS
|
|
assert invalid_metadata == ()
|
|
|
|
|
|
class TestBedrockClaude35SonnetContextWindow:
|
|
@pytest.mark.parametrize("path", (PRICES_PATH, BACKUP_PRICES_PATH), ids=("main", "backup"))
|
|
def test_bare_model_ids_match_us_and_eu_siblings(self, path: Path):
|
|
rows = json.loads(path.read_text())
|
|
for model in (
|
|
"anthropic.claude-3-5-sonnet-20240620-v1:0",
|
|
"anthropic.claude-3-5-sonnet-20241022-v2:0",
|
|
):
|
|
assert rows[model]["max_input_tokens"] == rows[f"us.{model}"]["max_input_tokens"]
|
|
assert rows[model]["max_input_tokens"] == rows[f"eu.{model}"]["max_input_tokens"]
|
|
|
|
@pytest.mark.parametrize("path", (PRICES_PATH, BACKUP_PRICES_PATH), ids=("main", "backup"))
|
|
def test_bare_model_ids_have_200k_context_window(self, path: Path):
|
|
rows = json.loads(path.read_text())
|
|
# Claude 3.5 Sonnet context window is 200K tokens, https://www.anthropic.com/news/claude-3-5-sonnet (accessed 2026-10-13)
|
|
for model in (
|
|
"anthropic.claude-3-5-sonnet-20240620-v1:0",
|
|
"anthropic.claude-3-5-sonnet-20241022-v2:0",
|
|
):
|
|
assert rows[model]["max_input_tokens"] == 200000
|
|
|
|
@pytest.mark.parametrize("path", (PRICES_PATH, BACKUP_PRICES_PATH), ids=("main", "backup"))
|
|
def test_bare_model_ids_have_no_above_200k_pricing(self, path: Path):
|
|
rows = json.loads(path.read_text())
|
|
above_200k_fields = (
|
|
"input_cost_per_token_above_200k_tokens",
|
|
"output_cost_per_token_above_200k_tokens",
|
|
"cache_creation_input_token_cost_above_200k_tokens",
|
|
"cache_read_input_token_cost_above_200k_tokens",
|
|
)
|
|
for model in (
|
|
"anthropic.claude-3-5-sonnet-20240620-v1:0",
|
|
"anthropic.claude-3-5-sonnet-20241022-v2:0",
|
|
):
|
|
assert not set(above_200k_fields).intersection(rows[model])
|
|
|
|
|
|
PROVIDER_LABELS_WITHOUT_A_MODEL_SET: Final = frozenset({"sagemaker", "bedrock_converse"})
|
|
MODES_SERVED_OUTSIDE_THE_LLM_PROVIDER_REGISTRY: Final = frozenset({"search", "decisions", "evaluation"})
|
|
|
|
|
|
def is_registered_provider(label: str, model_names: tuple[str, ...]) -> bool:
|
|
if label in litellm.models_by_provider or JSONProviderRegistry.exists(label):
|
|
return True
|
|
family_root: Final = label.split("-", 1)[0]
|
|
wildcard_models: Final = litellm.models_by_provider.get(family_root, ())
|
|
return any(
|
|
name in wildcard_models or name.removeprefix(f"{family_root}/") in wildcard_models for name in model_names
|
|
)
|
|
|
|
|
|
def unregistered_providers(rows: Mapping[str, object]) -> list[str]:
|
|
labelled_rows: Final = tuple(
|
|
(name, entry["litellm_provider"])
|
|
for name, entry in rows.items()
|
|
if name != "sample_spec"
|
|
and isinstance(entry, dict)
|
|
and "litellm_provider" in entry
|
|
and entry.get("mode") not in MODES_SERVED_OUTSIDE_THE_LLM_PROVIDER_REGISTRY
|
|
and entry["litellm_provider"] not in PROVIDER_LABELS_WITHOUT_A_MODEL_SET
|
|
)
|
|
return sorted(
|
|
label
|
|
for label in {label for _, label in labelled_rows}
|
|
if not is_registered_provider(label, tuple(name for name, row_label in labelled_rows if row_label == label))
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("path", (PRICES_PATH, BACKUP_PRICES_PATH), ids=("main", "backup"))
|
|
def test_every_cost_map_provider_is_registered(path: Path):
|
|
assert unregistered_providers(json.loads(path.read_text())) == [], (
|
|
f"{path.name} carries a litellm_provider whose models a `<provider>/*` grant does not list. A new provider "
|
|
"needs a `<provider>_models` set in litellm/__init__.py, filled in _populate_provider_model_sets and listed "
|
|
"in _build_models_by_provider. A new `<provider>-<family>` label needs its rows added to a set that "
|
|
"`models_by_provider[<provider>]` includes"
|
|
)
|
|
|
|
|
|
def test_unregistered_provider_guard_flags_only_labels_nobody_registered():
|
|
wired_vertex_model: Final = sorted(litellm.vertex_language_models)[0]
|
|
rows: Final = {
|
|
"sample_spec": {"litellm_provider": "one of the supported providers", "mode": "chat"},
|
|
"nobody_registered/StartJob": {"litellm_provider": "nobody_registered", "mode": "audio_transcription"},
|
|
"gpt-4o": {"litellm_provider": "openai", "mode": "chat"},
|
|
wired_vertex_model: {"litellm_provider": "vertex_ai-language-models", "mode": "chat"},
|
|
"vertex_ai/new-family-model": {"litellm_provider": "vertex_ai-new_family_models", "mode": "chat"},
|
|
"unknown_root/model": {"litellm_provider": "unknown_root-new_family_models", "mode": "chat"},
|
|
"some_search/search": {"litellm_provider": "some_search", "mode": "search"},
|
|
}
|
|
assert unregistered_providers(rows) == [
|
|
"nobody_registered",
|
|
"unknown_root-new_family_models",
|
|
"vertex_ai-new_family_models",
|
|
]
|
|
|
|
|
|
@pytest.mark.parametrize("model", ("gpt-realtime-2.1", "gpt-realtime-2.1-mini"))
|
|
def test_realtime_family_cache_image_rate_tracks_azure(prices: dict, model: str):
|
|
openai: Final = prices[model]
|
|
azure: Final = prices[f"azure/{model}"]
|
|
|
|
assert openai["cache_read_input_image_token_cost"] > 0
|
|
assert azure["cache_read_input_image_token_cost"] == openai["cache_read_input_image_token_cost"]
|
|
assert azure["input_cost_per_image_token"] >= azure["cache_read_input_image_token_cost"]
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"model,mode",
|
|
(
|
|
("gpt-realtime-translate", "realtime"),
|
|
("gpt-live-transcribe", "audio_transcription"),
|
|
("gpt-transcribe", "audio_transcription"),
|
|
),
|
|
)
|
|
def test_azure_realtime_specialized_models_follow_openai_modes(prices: dict, model: str, mode: str):
|
|
openai: Final = prices[model]
|
|
azure: Final = prices[f"azure/{model}"]
|
|
|
|
assert openai["mode"] == azure["mode"] == mode
|
|
assert azure["supports_audio_input"] is True
|
|
assert set(openai.get("supported_endpoints", ())) <= set(azure.get("supported_endpoints", ()))
|
|
|
|
|
|
_DATED_SNAPSHOT: Final = re.compile(r"(?P<alias>.+)-\d{4}-\d{2}-\d{2}")
|
|
|
|
|
|
def _azure_realtime_snapshots_with_an_alias(prices: Mapping[str, dict]) -> tuple[tuple[str, str], ...]:
|
|
dated: Final = (
|
|
(name, _DATED_SNAPSHOT.fullmatch(name))
|
|
for name, entry in prices.items()
|
|
if name.startswith("azure/") and "/v1/realtime" in entry.get("supported_endpoints", ())
|
|
)
|
|
return tuple((name, match["alias"]) for name, match in dated if match is not None and match["alias"] in prices)
|
|
|
|
|
|
def _realtime_ga_only(entry: dict) -> object:
|
|
return (entry.get("provider_specific_entry") or {}).get("realtime_ga_only")
|
|
|
|
|
|
def test_dated_azure_realtime_models_select_the_same_protocol_as_their_alias(prices: dict):
|
|
snapshots: Final = _azure_realtime_snapshots_with_an_alias(prices)
|
|
disagreeing: Final = tuple(
|
|
(snapshot, alias)
|
|
for snapshot, alias in snapshots
|
|
if _realtime_ga_only(prices[snapshot]) != _realtime_ga_only(prices[alias])
|
|
)
|
|
|
|
assert snapshots
|
|
assert disagreeing == ()
|
|
|
|
|
|
def test_model_prices_backup_is_synchronized(prices: dict):
|
|
backup: Final = json.loads(BACKUP_PRICES_PATH.read_text())
|
|
|
|
assert backup == prices
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"alias,snapshot",
|
|
(
|
|
("gpt-realtime-translate", "gpt-realtime-translate-2026-05-06"),
|
|
("gpt-realtime-whisper", "gpt-realtime-whisper-2026-05-06"),
|
|
("gpt-realtime-2.1", "gpt-realtime-2.1-2026-07-07"),
|
|
("gpt-realtime-2.1-mini", "gpt-realtime-2.1-mini-2026-07-07"),
|
|
("gpt-6.1-terra", "us/gpt-6.1-terra"),
|
|
("gpt-6.1-terra", "eu/gpt-6.1-terra"),
|
|
("gpt-6.1-terra", "apac/gpt-6.1-terra"),
|
|
),
|
|
)
|
|
def test_azure_aliases_and_model_variants_retire_together(prices: CostMap, alias: str, snapshot: str) -> None:
|
|
assert prices[f"azure/{alias}"]["deprecation_date"] == prices[f"azure/{snapshot}"]["deprecation_date"]
|
|
|
|
|
|
def test_gmi_gemini_hydrogen_bills_at_its_hosted_rates(prices: CostMap, local_model_cost_map: None) -> None:
|
|
model: Final = "gmi/google/gemini-4-hydrogen"
|
|
row: Final = prices[model]
|
|
|
|
prompt_cost, completion_cost = litellm.cost_per_token(
|
|
model=model,
|
|
usage_object=Usage(
|
|
prompt_tokens=100,
|
|
completion_tokens=20,
|
|
total_tokens=120,
|
|
prompt_tokens_details=PromptTokensDetailsWrapper(cached_tokens=40, cache_write_tokens=10),
|
|
),
|
|
)
|
|
|
|
expected_input: Final = (
|
|
50 * TypeAdapter(float).validate_python(row["input_cost_per_token"])
|
|
+ 10 * TypeAdapter(float).validate_python(row["cache_creation_input_token_cost"])
|
|
+ 40 * TypeAdapter(float).validate_python(row["cache_read_input_token_cost"])
|
|
)
|
|
expected_output: Final = 20 * TypeAdapter(float).validate_python(row["output_cost_per_token"])
|
|
assert (prompt_cost, completion_cost) == pytest.approx((expected_input, expected_output))
|
|
|
|
|
|
def _search_free_requests_rows(path: Path) -> Mapping[str, dict[str, JsonValue]]:
|
|
prices: Final[dict[str, JsonValue]] = TypeAdapter(dict[str, JsonValue]).validate_json(path.read_bytes())
|
|
return MappingProxyType(
|
|
{key: row for key, row in prices.items() if isinstance(row, dict) and "search_free_requests" in row}
|
|
)
|
|
|
|
|
|
def _supports_continuation_rows(path: Path) -> frozenset[str]:
|
|
prices: Final[dict[str, JsonValue]] = TypeAdapter(dict[str, JsonValue]).validate_json(path.read_bytes())
|
|
return frozenset(
|
|
key for key, row in prices.items() if isinstance(row, dict) and row.get("supports_continuation") is True
|
|
)
|
|
|
|
|
|
def test_gemini_4_argon_google_rows_carry_supports_continuation_in_both_cost_map_copies() -> None:
|
|
main_rows: Final = _supports_continuation_rows(PRICES_PATH)
|
|
# long decode models: https://ai.google.dev/gemini-api/docs/generate-content/long-decode and
|
|
# https://docs.cloud.google.com/gemini-enterprise-agent-platform/models/guides/gemini-4-argon (2026-11-02)
|
|
long_decode_rows: Final = {
|
|
"gemini/gemini-4-argon",
|
|
"vertex_ai/gemini-4-argon",
|
|
"vertex_ai/gemini-4-argon-cyber-permissive",
|
|
}
|
|
assert long_decode_rows <= main_rows, sorted(main_rows)
|
|
assert _supports_continuation_rows(BACKUP_PRICES_PATH) == main_rows
|
|
|
|
|
|
def test_gemini_4_rows_share_the_gemini_3_search_allowance_in_both_cost_map_copies() -> None:
|
|
main_rows: Final = _search_free_requests_rows(PRICES_PATH)
|
|
# 5,000 free grounding requests per month shared across Gemini 3 and newer:
|
|
# https://ai.google.dev/gemini-api/docs/pricing#gemini-4-carbon and
|
|
# https://cloud.google.com/vertex-ai/generative-ai/pricing (2026-11-10)
|
|
gemini_4_rows: Final = {
|
|
"gemini/gemini-4-argon",
|
|
"vertex_ai/gemini-4-argon",
|
|
"vertex_ai/gemini-4-argon-cyber-permissive",
|
|
"gemini/gemini-4-carbon",
|
|
"vertex_ai/gemini-4-carbon",
|
|
"vertex_ai/gemini-4-carbon-cyber-permissive",
|
|
}
|
|
assert gemini_4_rows <= main_rows.keys(), sorted(main_rows)
|
|
gemini_3_allowances: Final = {
|
|
json.dumps(main_rows[key]["search_free_requests"], sort_keys=True)
|
|
for key in ("gemini/gemini-3.8-flash", "vertex_ai/gemini-3.8-flash")
|
|
}
|
|
assert {
|
|
json.dumps(main_rows[key]["search_free_requests"], sort_keys=True) for key in gemini_4_rows
|
|
} == gemini_3_allowances
|
|
assert _search_free_requests_rows(BACKUP_PRICES_PATH) == main_rows
|
|
|
|
|
|
@pytest.mark.parametrize("path", (PRICES_PATH, BACKUP_PRICES_PATH), ids=("main", "backup"))
|
|
def test_search_free_requests_rows_are_grounding_rows_with_one_allowance_per_group(path: Path) -> None:
|
|
rows = _search_free_requests_rows(path)
|
|
assert rows
|
|
allowances = {
|
|
key: TypeAdapter(SearchFreeRequests).validate_python(row["search_free_requests"]) for key, row in rows.items()
|
|
}
|
|
for key, row in rows.items():
|
|
assert row.get("supports_web_search") is True, key
|
|
assert row.get("search_context_cost_per_query"), key
|
|
assert allowances[key]["count"] > 0, key
|
|
for group in {allowance["shared_group"] for allowance in allowances.values()}:
|
|
same_group = {(a["count"], a["period"]) for a in allowances.values() if a["shared_group"] == group}
|
|
assert len(same_group) == 1, (group, same_group)
|
|
|
|
|
|
def test_search_free_requests_backup_rows_match_the_main_catalog() -> None:
|
|
assert _search_free_requests_rows(BACKUP_PRICES_PATH) == _search_free_requests_rows(PRICES_PATH)
|
|
|
|
|
|
@pytest.mark.parametrize("path", (PRICES_PATH, BACKUP_PRICES_PATH), ids=("main", "backup"))
|
|
def test_volcengine_doubao_seed_2_1_pro_260915_row_matches_published_metadata(path: Path):
|
|
"""Volcengine Ark lists doubao-seed-2-1-pro-260915 at 6 / 30 CNY per million input / output tokens with
|
|
cache hits at 1.2 (ark.volcengine.com model detail and docs.volcengine.com/docs/82379/1544106, read
|
|
2026-10-20), a 1024k context window and a 256k output cap. USD rows use the 6.9565 CNY/USD rate of the
|
|
sibling 260628 row."""
|
|
rows: Mapping[str, object] = json.loads(path.read_text())
|
|
entry = rows.get("volcengine/doubao-seed-2-1-pro-260915")
|
|
assert isinstance(entry, dict)
|
|
assert entry["litellm_provider"] == "volcengine"
|
|
assert entry["mode"] == "chat"
|
|
assert entry["max_input_tokens"] == 1024000
|
|
assert entry["max_output_tokens"] == 256000
|
|
# Volcengine Ark pricing https://www.volcengine.com/docs/82379/1544106 checked 2026-10-20
|
|
assert entry["input_cost_per_token"] == pytest.approx(6.0 / 6.9565 / 1_000_000, rel=1e-4)
|
|
assert entry["output_cost_per_token"] == pytest.approx(30.0 / 6.9565 / 1_000_000, rel=1e-4)
|
|
assert entry["cache_read_input_token_cost"] == pytest.approx(1.2 / 6.9565 / 1_000_000, rel=1e-4)
|
|
sibling = rows["volcengine/doubao-seed-2-1-pro-260628"]
|
|
assert isinstance(sibling, dict)
|
|
assert all(
|
|
entry[key] == sibling[key]
|
|
for key in ("input_cost_per_token", "output_cost_per_token", "cache_read_input_token_cost")
|
|
)
|
|
|
|
|
|
def _bedrock_gpt_oss_rows(prices: Mapping[str, JsonValue]) -> tuple[str, ...]:
|
|
return tuple(
|
|
key
|
|
for key, row in prices.items()
|
|
if "gpt-oss" in key and isinstance(row, dict) and str(row.get("litellm_provider", "")).startswith("bedrock")
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("path", [PRICES_PATH, BACKUP_PRICES_PATH], ids=["main", "backup"])
|
|
def test_bedrock_gpt_oss_rows_declare_vision_support_like_their_safeguard_siblings(path: Path) -> None:
|
|
prices: Final = json.loads(path.read_text())
|
|
rows: Final = _bedrock_gpt_oss_rows(prices)
|
|
assert rows, "no Bedrock gpt-oss rows found"
|
|
reference: Final = prices["openai.gpt-oss-safeguard-120b"]["supports_vision"]
|
|
undeclared: Final = tuple(key for key in rows if prices[key].get("supports_vision") is not reference)
|
|
assert undeclared == (), f"modality routing only skips rows that declare supports_vision: {undeclared}"
|
|
|
|
|
|
def test_bedrock_gpt_oss_vision_is_explicitly_disabled_for_the_router_gate() -> None:
|
|
assert litellm.utils.is_vision_explicitly_disabled("bedrock/openai.gpt-oss-120b-1:0") is True
|
|
assert litellm.utils.is_vision_explicitly_disabled("bedrock_mantle/openai.gpt-oss-20b") is True
|
|
|
|
|
|
def _nace_rows(path: Path) -> Mapping[str, Mapping[str, JsonValue]]:
|
|
prices: Final = TypeAdapter(dict[str, dict[str, JsonValue]]).validate_json(path.read_bytes())
|
|
return {key: row for key, row in prices.items() if key.startswith("nace/")}
|
|
|
|
|
|
@pytest.mark.parametrize("model", ("drex-v1.0", "drex-v1.5", "drex-latest", "drex-max"))
|
|
def test_drex_alias_metadata_matches_the_served_version(local_model_cost_map: None, model: str) -> None:
|
|
alias: Final = litellm.model_cost[f"nace/{model}"]
|
|
served: Final = litellm.model_cost["nace/drex-max-v1.1"]
|
|
for field in ("input_cost_per_token", "output_cost_per_token", "max_input_tokens", "supports_vision"):
|
|
assert alias.get(field) == served[field]
|
|
assert litellm.supports_vision(f"nace/{model}") is True
|
|
|
|
|
|
def test_drex_max_metadata_supports_decisions_and_input_billing(local_model_cost_map: None) -> None:
|
|
served: Final = litellm.model_cost["nace/drex-max-v1.1"]
|
|
assert served["input_cost_per_token"] > 0
|
|
assert served["output_cost_per_token"] == 0
|
|
assert (served["litellm_provider"], served["mode"]) == ("nace", "evaluation")
|
|
assert served["max_input_tokens"] > 0
|
|
assert litellm.supports_vision("nace/drex-max-v1.1") is True
|
|
|
|
|
|
@pytest.mark.parametrize("effort", ("low", "medium", "high"))
|
|
def test_nace_parse_bills_each_processed_page_at_its_effort_row_price(local_model_cost_map: None, effort: str) -> None:
|
|
model: Final = f"nace/parse-{effort}"
|
|
row: Final = litellm.model_cost[model]
|
|
assert (row["litellm_provider"], row["mode"], row["supported_endpoints"]) == ("nace", "ocr", ["/v1/ocr"])
|
|
response: Final = OCRResponse(
|
|
pages=[OCRPage(index=0, markdown="page")],
|
|
model=f"parse-{effort}",
|
|
usage_info=OCRUsageInfo(pages_processed=3),
|
|
)
|
|
cost: Final = completion_cost(
|
|
completion_response=response, model=model, custom_llm_provider="nace", call_type="ocr"
|
|
)
|
|
assert cost == pytest.approx(3 * row["ocr_cost_per_page"])
|
|
assert cost > 0
|
|
|
|
|
|
def test_nace_backup_rows_match_the_main_catalog() -> None:
|
|
assert {"nace/drex-max", "nace/drex-max-v1.1", "nace/parse-low"} <= _nace_rows(PRICES_PATH).keys()
|
|
assert _nace_rows(BACKUP_PRICES_PATH) == _nace_rows(PRICES_PATH)
|
|
|
|
|
|
@pytest.mark.parametrize("path", (PRICES_PATH, BACKUP_PRICES_PATH), ids=("main", "backup"))
|
|
def test_azure_ai_claude_rows_bill_web_search_like_their_anthropic_rows(path: Path) -> None:
|
|
prices: Final[dict[str, JsonValue]] = TypeAdapter(dict[str, JsonValue]).validate_json(path.read_bytes())
|
|
pairs: Final = {
|
|
key: (row, prices[key.removeprefix("azure_ai/")])
|
|
for key, row in prices.items()
|
|
if key.startswith("azure_ai/claude") and isinstance(row, dict) and key.removeprefix("azure_ai/") in prices
|
|
}
|
|
priced_pairs: Final = {
|
|
key: (row, bare)
|
|
for key, (row, bare) in pairs.items()
|
|
if isinstance(bare, dict) and bare.get("search_context_cost_per_query")
|
|
}
|
|
assert priced_pairs
|
|
drifted: Final = tuple(
|
|
key
|
|
for key, (row, bare) in priced_pairs.items()
|
|
if row.get("search_context_cost_per_query") != bare["search_context_cost_per_query"]
|
|
or row.get("supports_web_search") is not True
|
|
)
|
|
assert drifted == (), drifted
|
|
|
|
|
|
@pytest.mark.parametrize("path", (PRICES_PATH, BACKUP_PRICES_PATH), ids=("main", "backup"))
|
|
def test_azure_ai_claude_rows_priced_for_web_search_say_they_support_it(path: Path) -> None:
|
|
prices: Final[dict[str, JsonValue]] = TypeAdapter(dict[str, JsonValue]).validate_json(path.read_bytes())
|
|
priced_rows: Final = {
|
|
key: row
|
|
for key, row in prices.items()
|
|
if key.startswith("azure_ai/claude") and isinstance(row, dict) and row.get("search_context_cost_per_query")
|
|
}
|
|
assert priced_rows
|
|
unflagged: Final = tuple(key for key, row in priced_rows.items() if row.get("supports_web_search") is not True)
|
|
assert unflagged == (), unflagged
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("model", "supports_vision", "supports_video_input", "supports_audio_input"),
|
|
(
|
|
("deepinfra/zai-org/GLM-5.3-Flash", True, True, False),
|
|
("deepinfra/XiaomiMiMo/MiMo-V2.6-Flash", True, True, True),
|
|
("deepinfra/nvidia/NVIDIA-Nemotron-3.5-Super-VL", True, True, False),
|
|
("deepinfra/tencent/Hy4-preview", False, False, False),
|
|
),
|
|
)
|
|
def test_deepinfra_new_catalog_models_resolve_pricing_and_capabilities(
|
|
model: str,
|
|
supports_vision: bool,
|
|
supports_video_input: bool,
|
|
supports_audio_input: bool,
|
|
local_model_cost_map: None,
|
|
) -> None:
|
|
from litellm.llms.deepinfra.chat.transformation import DeepInfraConfig
|
|
|
|
catalog: Final = TypeAdapter(dict[str, JsonValue]).validate_json(PRICES_PATH.read_bytes())
|
|
backup: Final = TypeAdapter(dict[str, JsonValue]).validate_json(BACKUP_PRICES_PATH.read_bytes())
|
|
row: Final = catalog[model]
|
|
assert isinstance(row, dict)
|
|
assert row == backup[model]
|
|
assert (row["litellm_provider"], row["mode"]) == ("deepinfra", "chat")
|
|
|
|
max_input: Final = row["max_input_tokens"]
|
|
input_cost: Final = row["input_cost_per_token"]
|
|
output_cost: Final = row["output_cost_per_token"]
|
|
cache_read_cost: Final = row["cache_read_input_token_cost"]
|
|
assert isinstance(max_input, int) and max_input > 0
|
|
assert isinstance(input_cost, float) and isinstance(output_cost, float) and isinstance(cache_read_cost, float)
|
|
assert 0 < cache_read_cost < input_cost and output_cost > 0
|
|
|
|
bare_model: Final = model.removeprefix("deepinfra/")
|
|
info: Final = litellm.get_model_info(model=bare_model, custom_llm_provider="deepinfra")
|
|
assert info["input_cost_per_token"] == input_cost
|
|
assert info["output_cost_per_token"] == output_cost
|
|
assert info["cache_read_input_token_cost"] == cache_read_cost
|
|
|
|
prompt_cost, completion_cost = litellm.cost_per_token(
|
|
model=model, prompt_tokens=1_000_000, completion_tokens=1_000_000
|
|
)
|
|
assert (prompt_cost, completion_cost) == pytest.approx((input_cost * 1_000_000, output_cost * 1_000_000))
|
|
|
|
assert litellm.supports_reasoning(model=model) is True
|
|
assert litellm.supports_function_calling(model=model) is True
|
|
assert litellm.supports_response_schema(model=model) is True
|
|
assert litellm.utils.supports_prompt_caching(model=model) is True
|
|
assert litellm.supports_vision(model=model) is supports_vision
|
|
assert litellm.supports_video_input(model=model) is supports_video_input
|
|
assert litellm.supports_audio_input(model=model) is supports_audio_input
|
|
assert "reasoning_effort" in DeepInfraConfig().get_supported_openai_params(model=model)
|
|
|
|
|
|
# Probed against Bedrock Converse in us-east-1 on 2026-11-19: each id takes toolChoice auto, any, and a named tool
|
|
BEDROCK_CONVERSE_MISTRAL_TOOL_CHOICE_MODELS: Final = (
|
|
"mistral.mistral-large-3-675b-instruct",
|
|
"mistral.ministral-3-14b-instruct",
|
|
"mistral.ministral-3-8b-instruct",
|
|
"mistral.ministral-3-3b-instruct",
|
|
)
|
|
WEATHER_TOOL: Final = MappingProxyType(
|
|
{
|
|
"type": "function",
|
|
"function": {
|
|
"name": "get_weather",
|
|
"parameters": {"type": "object", "properties": {"city": {"type": "string"}}, "required": ["city"]},
|
|
},
|
|
}
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("route", ("", "converse/"))
|
|
@pytest.mark.parametrize("model", BEDROCK_CONVERSE_MISTRAL_TOOL_CHOICE_MODELS)
|
|
@pytest.mark.parametrize(
|
|
("tool_choice", "converse_tool_choice"),
|
|
(
|
|
("auto", {"auto": {}}),
|
|
("required", {"any": {}}),
|
|
({"type": "function", "function": {"name": "get_weather"}}, {"tool": {"name": "get_weather"}}),
|
|
),
|
|
)
|
|
def test_bedrock_converse_mistral_rows_send_tool_choice_to_bedrock(
|
|
local_model_cost_map: None,
|
|
route: str,
|
|
model: str,
|
|
tool_choice: str | dict[str, JsonValue],
|
|
converse_tool_choice: dict[str, JsonValue],
|
|
) -> None:
|
|
optional_params: Final = litellm.get_optional_params(
|
|
model=f"{route}{model}", custom_llm_provider="bedrock", tools=[dict(WEATHER_TOOL)], tool_choice=tool_choice
|
|
)
|
|
|
|
assert optional_params["tool_choice"] == converse_tool_choice
|
|
|
|
|
|
def _region_pinned_bedrock_converse_rows(prices: CostMap) -> Iterator[tuple[str, str]]:
|
|
return (
|
|
(key, base)
|
|
for key, row in prices.items()
|
|
if key.startswith("bedrock/")
|
|
and row.get("litellm_provider") == "bedrock_converse"
|
|
and (base := BedrockModelInfo.get_base_model(key)) in prices
|
|
)
|
|
|
|
|
|
def _capabilities_missing_from_one_side(prices: CostMap, key: str, base: str) -> Iterator[str]:
|
|
capabilities: Final = sorted({name for name in (*prices[key], *prices[base]) if name.startswith("supports_")})
|
|
return (
|
|
f"{key} {name}={prices[key].get(name)} but {base} {name}={prices[base].get(name)}"
|
|
for name in capabilities
|
|
if bool(prices[key].get(name)) != bool(prices[base].get(name))
|
|
)
|
|
|
|
|
|
def test_region_pinned_bedrock_converse_rows_carry_their_base_rows_capabilities(prices: CostMap) -> None:
|
|
rows: Final = tuple(_region_pinned_bedrock_converse_rows(prices))
|
|
assert {base for _, base in rows} >= set(BEDROCK_CONVERSE_MISTRAL_TOOL_CHOICE_MODELS)
|
|
|
|
assert list(chain.from_iterable(_capabilities_missing_from_one_side(prices, key, base) for key, base in rows)) == []
|