: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-gateway): expose model pricing (#80988)
Adam Bowker5e31e39ba50a
diff --git a/services/llm-gateway/PARITY.md b/services/llm-gateway/PARITY.mdindex b754f046fa82..5749e4b264f1 100644--- a/services/llm-gateway/PARITY.md+++ b/services/llm-gateway/PARITY.md@@ -68,7 +68,7 @@ These are compatibility checks, not automatic blockers:| OpenAI APIs | Chat Completions, Responses, bare Responses alias, and normalized router chat. | Audio transcription and broader LiteLLM translation. || Anthropic APIs | Messages and token counting, including Bedrock-hosted models. | OpenAI models exposed through the Anthropic shape and Python-specific Bedrock opt-in behavior. || Providers | OpenAI, Anthropic, Azure OpenAI, Bedrock, and selected Modal models. | OpenRouter, Fireworks, Cloudflare Workers AI, and Baseten. |-| Models | Gateway-owned catalog, canonical IDs and aliases, capability checks, and router categories. | Broader LiteLLM model acceptance and Python product allowlists. |+| Models | Gateway-owned catalog, canonical IDs and aliases, capability checks, router categories, and OpenRouter-shaped pricing. | Broader LiteLLM model acceptance, Python product allowlists, and product-scoped model pricing. || Routing and failure behavior | Health-based host choice, circuit breakers, hosted-provider failover, and strict provider pinning. | Caller opt-in Bedrock fallback and provider-specific Python routing. || Event metadata | One `X-PostHog-Properties` JSON object plus dedicated distinct ID, trace ID, and provider headers. | `X-POSTHOG-PROPERTY-*` and `X-POSTHOG-FLAG-*` headers. || Session attribution | No native session header on main. [PostHog/ai-gateway#383](https://github.com/PostHog/ai-gateway/pull/383) adds `X-PostHog-Session-Id`. | The per-key property header can emit `$ai_session_id`. |diff --git a/services/llm-gateway/src/llm_gateway/api/models.py b/services/llm-gateway/src/llm_gateway/api/models.pyindex 76798e17a87d..369ebb3cd2c1 100644--- a/services/llm-gateway/src/llm_gateway/api/models.py+++ b/services/llm-gateway/src/llm_gateway/api/models.py@@ -1,3 +1,4 @@+from decimal import Decimalfrom typing import Literalimport structlog@@ -13,6 +14,7 @@ from llm_gateway.products.config import (filter_to_free_tier_models,validate_product,)+from llm_gateway.rate_limiting.model_cost_service import ModelCostServicefrom llm_gateway.rate_limiting.throttles import is_usage_unlimitedfrom llm_gateway.services.model_registry import get_available_modelsfrom llm_gateway.services.quota_resolver import resolve_quota_status@@ -31,6 +33,13 @@ class TruncationPolicyConfig(BaseModel):limit: int = 10_000+class ModelPricing(BaseModel):+ prompt: str+ completion: str+ input_cache_read: str | None = None+ input_cache_write: str | None = None++class ModelObject(BaseModel):id: strslug: str = "" # codex-acp compatibility — mirrors `id`@@ -53,6 +62,7 @@ class ModelObject(BaseModel):truncation_policy: TruncationPolicyConfig = TruncationPolicyConfig()supports_parallel_tool_calls: bool = Trueexperimental_supported_tools: list[str] = []+ pricing: ModelPricing | None = None# Free-tier gate (posthog_code): restricted models are marked, not omitted.allowed: bool = Truerestriction_reason: str | None = None@@ -64,6 +74,31 @@ class ModelsResponse(BaseModel):models: list[ModelObject] = [] # Alias for `data` — codex-acp expects this field+def _format_rate(rate: float) -> str:+ return format(Decimal(str(rate)), "f")+++def _get_model_pricing(cost_model_id: str) -> ModelPricing | None:+ costs = ModelCostService.get_instance().get_costs(cost_model_id)+ if costs is None:+ return None++ input_cost = costs.get("input_cost_per_token")+ output_cost = costs.get("output_cost_per_token")+ if input_cost is None or output_cost is None:+ return None++ supports_prompt_caching = bool(costs.get("supports_prompt_caching", False))+ cache_read_cost = costs.get("cache_read_input_token_cost", input_cost) if supports_prompt_caching else None+ cache_write_cost = costs.get("cache_creation_input_token_cost", input_cost) if supports_prompt_caching else None+ return ModelPricing(+ prompt=_format_rate(input_cost),+ completion=_format_rate(output_cost),+ input_cache_read=_format_rate(cache_read_cost) if cache_read_cost is not None else None,+ input_cache_write=_format_rate(cache_write_cost) if cache_write_cost is not None else None,+ )++def _build_response(product: str) -> ModelsResponse:models = get_available_models(product)model_objects = [@@ -75,6 +110,7 @@ def _build_response(product: str) -> ModelsResponse:context_window=m.context_window,supports_streaming=m.supports_streaming,supports_vision=m.supports_vision,+ pricing=_get_model_pricing(m.cost_model_id),)for m in models]diff --git a/services/llm-gateway/src/llm_gateway/baseten.py b/services/llm-gateway/src/llm_gateway/baseten.pyindex 5d1bf2296432..84eca0449d61 100644--- a/services/llm-gateway/src/llm_gateway/baseten.py+++ b/services/llm-gateway/src/llm_gateway/baseten.py@@ -1,7 +1,7 @@from __future__ import annotationsfrom collections.abc import AsyncIterator, Awaitable, Callable-from typing import Any+from typing import Any, Finalimport litellmfrom fastapi import HTTPException@@ -24,7 +24,8 @@ BASETEN_MODELS = {BASETEN_DEEPSEEK_PUBLIC_MODEL: BASETEN_DEEPSEEK_MODEL,}# Models with no Cloudflare/Modal fallback — always routed to Baseten.-BASETEN_EXCLUSIVE_MODELS: frozenset[str] = frozenset({BASETEN_DEEPSEEK_PUBLIC_MODEL})+BASETEN_EXCLUSIVE_COST_MODELS: Final[dict[str, str]] = {BASETEN_DEEPSEEK_PUBLIC_MODEL: BASETEN_DEEPSEEK_METRIC_MODEL}+BASETEN_EXCLUSIVE_MODELS: frozenset[str] = frozenset(BASETEN_EXCLUSIVE_COST_MODELS)def is_baseten_configured(settings: Settings) -> bool:diff --git a/services/llm-gateway/src/llm_gateway/services/model_registry.py b/services/llm-gateway/src/llm_gateway/services/model_registry.pyindex 12b0542aa218..1c1c932ec06a 100644--- a/services/llm-gateway/src/llm_gateway/services/model_registry.py+++ b/services/llm-gateway/src/llm_gateway/services/model_registry.py@@ -4,7 +4,7 @@ import osfrom dataclasses import dataclassfrom typing import ClassVar, Final-from llm_gateway.baseten import BASETEN_EXCLUSIVE_MODELS, is_baseten_configured+from llm_gateway.baseten import BASETEN_EXCLUSIVE_COST_MODELS, BASETEN_EXCLUSIVE_MODELS, is_baseten_configuredfrom llm_gateway.cloudflare import CLOUDFLARE_ALLOWED_MODELS, is_cloudflare_configuredfrom llm_gateway.config import get_settingsfrom llm_gateway.modal import (@@ -30,6 +30,7 @@ _BASETEN_DEFAULT_CONTEXT_WINDOW: Final[int] = 1_048_000@dataclass(frozen=True)class ModelInfo:id: str+ cost_model_id: strprovider: strcontext_window: intsupports_streaming: bool = True@@ -108,6 +109,7 @@ class ModelRegistryService:return Nonereturn ModelInfo(id=model_id,+ cost_model_id=model_id,provider=cost_data.get("litellm_provider", "unknown"),context_window=cost_data.get("max_input_tokens") or 0,supports_vision=bool(cost_data.get("supports_vision", False)),@@ -147,6 +149,7 @@ class ModelRegistryService:models.append(ModelInfo(id=model_id,+ cost_model_id=COST_ALIASES[f"openai/{model_id}"][0],provider=_CLOUDFLARE_PROVIDER,context_window=_CLOUDFLARE_DEFAULT_CONTEXT_WINDOW,supports_streaming=True,@@ -169,6 +172,7 @@ class ModelRegistryService:models.append(ModelInfo(id=model_id,+ cost_model_id=BASETEN_EXCLUSIVE_COST_MODELS[model_id],provider="baseten",context_window=_BASETEN_DEFAULT_CONTEXT_WINDOW,supports_streaming=True,diff --git a/services/llm-gateway/tests/test_models_api.py b/services/llm-gateway/tests/test_models_api.pyindex dac795458b6a..05ec0a47b133 100644--- a/services/llm-gateway/tests/test_models_api.py+++ b/services/llm-gateway/tests/test_models_api.py@@ -24,6 +24,10 @@ MOCK_COST_DATA: dict[str, ModelCost] = {"litellm_provider": "openai","max_input_tokens": 200000,"supports_vision": True,+ "supports_prompt_caching": True,+ "input_cost_per_token": 2.5e-6,+ "output_cost_per_token": 10e-6,+ "cache_read_input_token_cost": 0.25e-6,"mode": "chat",},"gpt-5-mini": {@@ -54,6 +58,11 @@ MOCK_COST_DATA: dict[str, ModelCost] = {"litellm_provider": "anthropic","max_input_tokens": 200000,"supports_vision": True,+ "supports_prompt_caching": True,+ "input_cost_per_token": 5e-6,+ "output_cost_per_token": 25e-6,+ "cache_read_input_token_cost": 0.5e-6,+ "cache_creation_input_token_cost": 6.25e-6,"mode": "chat",},"claude-opus-4-6": {@@ -98,6 +107,24 @@ MOCK_COST_DATA: dict[str, ModelCost] = {"supports_vision": False,"mode": "chat",},+ "cloudflare/@cf/zai-org/glm-5.2": {+ "litellm_provider": "cloudflare",+ "max_input_tokens": 128000,+ "supports_prompt_caching": True,+ "input_cost_per_token": 1.4e-6,+ "output_cost_per_token": 4.4e-6,+ "cache_read_input_token_cost": 0.14e-6,+ "mode": "chat",+ },+ "baseten/deepseek-ai/deepseek-v4-flash-0731": {+ "litellm_provider": "baseten",+ "max_input_tokens": 1048000,+ "supports_prompt_caching": True,+ "input_cost_per_token": 0.13e-6,+ "output_cost_per_token": 0.26e-6,+ "cache_read_input_token_cost": 0.028e-6,+ "mode": "chat",+ },}@@ -199,6 +226,36 @@ class TestListModelsForProductEndpoint:assert "gpt-4o" not in model_idsassert "o1" not in model_ids+ def test_posthog_code_returns_effective_pricing(self, client: TestClient):+ response = client.get("/posthog_code/v1/models")+ assert response.status_code == 200+ models = {model["id"]: model for model in response.json()["data"]}++ assert models["gpt-5.2"]["pricing"] == {+ "prompt": "0.0000025",+ "completion": "0.00001",+ "input_cache_read": "0.00000025",+ "input_cache_write": "0.0000025",+ }+ assert models["claude-opus-4-5"]["pricing"] == {+ "prompt": "0.000005",+ "completion": "0.000025",+ "input_cache_read": "0.0000005",+ "input_cache_write": "0.00000625",+ }+ assert models["@cf/zai-org/glm-5.2"]["pricing"] == {+ "prompt": "0.0000014",+ "completion": "0.0000044",+ "input_cache_read": "0.00000014",+ "input_cache_write": "0.0000014",+ }+ assert models["deepseek-ai/deepseek-v4-flash-0731"]["pricing"] == {+ "prompt": "0.00000013",+ "completion": "0.00000026",+ "input_cache_read": "0.000000028",+ "input_cache_write": "0.00000013",+ }+@pytest.mark.parametrize("alias", ["twig", "array"])def test_legacy_alias_routes_to_posthog_code(self, client: TestClient, alias: str):response = client.get(f"/{alias}/v1/models")