:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat: llm override on gateway (#62567)
Peter Kirkham63bd75b8b606
diff --git a/services/llm-gateway/src/llm_gateway/rate_limiting/cost_refresh.py b/services/llm-gateway/src/llm_gateway/rate_limiting/cost_refresh.pyindex 43a906c926db..f730927ab81f 100644--- a/services/llm-gateway/src/llm_gateway/rate_limiting/cost_refresh.py+++ b/services/llm-gateway/src/llm_gateway/rate_limiting/cost_refresh.py@@ -7,6 +7,8 @@ import structlogfrom litellm import model_cost_map_urlfrom litellm.litellm_core_utils.get_model_cost_map import get_model_cost_map+from llm_gateway.rate_limiting.model_cost_overrides import apply_model_cost_overrides+logger = structlog.get_logger(__name__)CACHE_TTL_SECONDS = 300@@ -38,6 +40,7 @@ class CostRefreshService:def refresh(self) -> None:try:model_cost = get_model_cost_map(url=model_cost_map_url)+ apply_model_cost_overrides(model_cost)litellm.model_cost = model_cost# Provider sets (anthropic_models, etc.) back get_llm_provider's inference# for bare names — without re-running this they stay frozen at import time.diff --git a/services/llm-gateway/src/llm_gateway/rate_limiting/model_cost_overrides.py b/services/llm-gateway/src/llm_gateway/rate_limiting/model_cost_overrides.pynew file mode 100644index 000000000000..1a86b2a035d7--- /dev/null+++ b/services/llm-gateway/src/llm_gateway/rate_limiting/model_cost_overrides.py@@ -0,0 +1,35 @@+from __future__ import annotations++from typing import TYPE_CHECKING, Final, cast++if TYPE_CHECKING:+ from llm_gateway.rate_limiting.model_cost_service import ModelCost++# Bridge entries for models not yet in LiteLLM's upstream cost map. The gateway+# derives /v1/models (and billing cost) from that map, so a model missing upstream+# is invisible even when allowlisted in products/config.py. Merged only when+# LiteLLM doesn't already define the model; delete each entry once upstream lands it.+# Pricing verified against OpenRouter (Anthropic + Bedrock).+MODEL_COST_OVERRIDES: Final[dict[str, ModelCost]] = {+ "claude-fable-5": {+ "litellm_provider": "anthropic",+ "mode": "chat",+ # 200k not 1M: the 1M window is a beta-header feature, same as opus-4.x.+ "max_input_tokens": 200_000,+ "max_output_tokens": 64_000,+ "input_cost_per_token": 1e-05,+ "output_cost_per_token": 5e-05,+ "cache_read_input_token_cost": 1e-06,+ "cache_creation_input_token_cost": 1.25e-05,+ "supports_vision": True,+ "supports_prompt_caching": True,+ },+}+++def apply_model_cost_overrides(model_cost: dict[str, ModelCost]) -> dict[str, ModelCost]:+ """Fill bridge entries LiteLLM doesn't define, in place. Upstream always wins."""+ for model_id, cost in MODEL_COST_OVERRIDES.items():+ if model_id not in model_cost:+ model_cost[model_id] = cast("ModelCost", dict(cost))+ return model_costdiff --git a/services/llm-gateway/src/llm_gateway/rate_limiting/model_cost_service.py b/services/llm-gateway/src/llm_gateway/rate_limiting/model_cost_service.pyindex 4eeaad6c813f..9265b9a33088 100644--- a/services/llm-gateway/src/llm_gateway/rate_limiting/model_cost_service.py+++ b/services/llm-gateway/src/llm_gateway/rate_limiting/model_cost_service.py@@ -8,6 +8,8 @@ import structlogfrom litellm import model_cost_map_urlfrom litellm.litellm_core_utils.get_model_cost_map import get_model_cost_map+from llm_gateway.rate_limiting.model_cost_overrides import apply_model_cost_overrides+logger = structlog.get_logger(__name__)TARGET_LIMIT_COST_PER_HOUR: Final[float] = 60.0@@ -45,6 +47,12 @@ class ModelCost(TypedDict, total=False):"""Whether the model supports image/vision input."""mode: str"""Model mode (e.g., "chat", "completion", "embedding")."""+ cache_read_input_token_cost: float+ """Cost in USD per cached input token read."""+ cache_creation_input_token_cost: float+ """Cost in USD per input token written to the cache."""+ supports_prompt_caching: bool+ """Whether the model supports prompt caching."""class ModelCostService:@@ -73,6 +81,7 @@ class ModelCostService:def _refresh_cache(self) -> None:try:model_cost = get_model_cost_map(url=model_cost_map_url)+ apply_model_cost_overrides(model_cost)litellm.model_cost = model_cost# Keep provider sets in sync — see cost_refresh.py.litellm.add_known_models(model_cost)diff --git a/services/llm-gateway/tests/test_model_cost_overrides.py b/services/llm-gateway/tests/test_model_cost_overrides.pynew file mode 100644index 000000000000..ad1eeeb92ea1--- /dev/null+++ b/services/llm-gateway/tests/test_model_cost_overrides.py@@ -0,0 +1,123 @@+from __future__ import annotations++import os+from collections.abc import Iterator+from unittest.mock import MagicMock, patch++import litellm+import pytest++from llm_gateway.rate_limiting.model_cost_overrides import (+ MODEL_COST_OVERRIDES,+ apply_model_cost_overrides,+)+from llm_gateway.rate_limiting.model_cost_service import ModelCost, ModelCostService+from llm_gateway.services.model_registry import (+ ModelRegistryService,+ get_available_models,+)++PROVIDER_ENV_VARS = [+ "OPENAI_API_KEY",+ "ANTHROPIC_API_KEY",+ "OPENROUTER_API_KEY",+ "FIREWORKS_API_KEY",+]+++class TestApplyModelCostOverrides:+ @pytest.mark.parametrize("model_id", sorted(MODEL_COST_OVERRIDES))+ def test_adds_missing_model(self, model_id: str) -> None:+ cost_map: dict[str, ModelCost] = {"gpt-4": {"litellm_provider": "openai"}}+ apply_model_cost_overrides(cost_map)+ assert cost_map[model_id] == MODEL_COST_OVERRIDES[model_id]++ @pytest.mark.parametrize("model_id", sorted(MODEL_COST_OVERRIDES))+ def test_does_not_override_existing_upstream_entry(self, model_id: str) -> None:+ upstream: ModelCost = {"litellm_provider": "anthropic", "max_input_tokens": 1_000_000}+ cost_map: dict[str, ModelCost] = {model_id: upstream}+ apply_model_cost_overrides(cost_map)+ assert cost_map[model_id] is upstream++ def test_returns_same_object_in_place(self) -> None:+ cost_map: dict[str, ModelCost] = {}+ assert apply_model_cost_overrides(cost_map) is cost_map++ @pytest.mark.parametrize("model_id", sorted(MODEL_COST_OVERRIDES))+ def test_inserted_entry_is_a_copy(self, model_id: str) -> None:+ # The shared constant must survive callers (and litellm) mutating the map.+ cost_map: dict[str, ModelCost] = {}+ apply_model_cost_overrides(cost_map)+ cost_map[model_id]["input_cost_per_token"] = -1.0+ assert MODEL_COST_OVERRIDES[model_id].get("input_cost_per_token") != -1.0+++class TestOverrideSurfacesThroughRefresh:+ @pytest.fixture(autouse=True)+ def restore_litellm_globals(self) -> Iterator[None]:+ model_cost_snapshot = litellm.model_cost+ # add_known_models mutates one provider set per provider in the cost map,+ # so snapshot every set in litellm's namespace rather than just anthropic's.+ set_snapshots = {name: value.copy() for name, value in vars(litellm).items() if isinstance(value, set)}+ try:+ yield+ finally:+ litellm.model_cost = model_cost_snapshot+ for name, snapshot in set_snapshots.items():+ provider_set = getattr(litellm, name)+ provider_set.clear()+ provider_set.update(snapshot)++ @pytest.fixture(autouse=True)+ def reset_singletons(self) -> Iterator[None]:+ ModelCostService.reset_instance()+ ModelRegistryService.reset_instance()+ yield+ ModelCostService.reset_instance()+ ModelRegistryService.reset_instance()++ @patch("llm_gateway.rate_limiting.model_cost_service.get_model_cost_map")+ def test_refresh_injects_fable_5_when_upstream_missing(self, mock_get_cost_map: MagicMock) -> None:+ mock_get_cost_map.return_value = {+ "claude-opus-4-8": {+ "litellm_provider": "anthropic",+ "mode": "chat",+ "max_input_tokens": 200_000,+ },+ }++ service = ModelCostService.get_instance()+ service._refresh_cache()++ costs = service.get_costs("claude-fable-5")+ assert costs is not None+ assert costs["litellm_provider"] == "anthropic"+ assert "claude-fable-5" in service.get_all_models()++ @patch("llm_gateway.rate_limiting.model_cost_service.get_model_cost_map")+ def test_fable_5_listed_for_posthog_code(self, mock_get_cost_map: MagicMock) -> None:+ mock_get_cost_map.return_value = {+ "claude-opus-4-8": {+ "litellm_provider": "anthropic",+ "mode": "chat",+ "max_input_tokens": 200_000,+ },+ }+ ModelCostService.get_instance()._refresh_cache()++ settings = MagicMock()+ settings.openai_api_key = None+ settings.anthropic_api_key = "sk-ant-test"+ settings.openrouter_api_key = None+ settings.fireworks_api_key = None++ with patch.dict(os.environ, {}, clear=False):+ for var in PROVIDER_ENV_VARS:+ os.environ.pop(var, None)+ with patch(+ "llm_gateway.services.model_registry.get_settings",+ return_value=settings,+ ):+ model_ids = {m.id for m in get_available_models("posthog_code")}++ assert "claude-fable-5" in model_ids