: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): add Baseten GLM routing (#74253)
Alessandro Pogliaghi475538bdaf3b
diff --git a/services/llm-gateway/README.md b/services/llm-gateway/README.mdindex eb864517810c..0393531cf470 100644--- a/services/llm-gateway/README.md+++ b/services/llm-gateway/README.md@@ -200,17 +200,20 @@ To use Bedrock (either via `X-PostHog-Provider` or `X-PostHog-Use-Bedrock-FallbaCredentials are intentionally not loaded through `LLM_GATEWAY_*` settings in the gateway.Use your runtime's standard AWS authentication mechanism (e.g. IAM role, IRSA, ECS task role, or pre-existing `AWS_*` env vars provisioned by deployment).-## GLM backends (Cloudflare and Modal)+## GLM backendsGLM is served under the public model id `@cf/zai-org/glm-5.2` on every surface (Anthropic Messages, chat/completions, Responses).Which backend serves a request is a gateway-internal decision made in `src/llm_gateway/glm_routing.py`:- **Cloudflare Workers AI** (the incumbent) — configure `LLM_GATEWAY_CLOUDFLARE_API_KEY` and `LLM_GATEWAY_CLOUDFLARE_ACCOUNT_ID`.- **Modal** (an OpenAI-compatible vLLM endpoint) — configure `LLM_GATEWAY_MODAL_API_BASE`, `LLM_GATEWAY_MODAL_KEY`, and `LLM_GATEWAY_MODAL_SECRET` (a [Modal proxy-token](https://modal.com/docs/guide/endpoints) pair, sent as `Modal-Key`/`Modal-Secret` headers).+- **Baseten** (an OpenAI-compatible endpoint) - configure `LLM_GATEWAY_BASETEN_API_BASE` and `LLM_GATEWAY_BASETEN_API_KEY`.++The `tasks-glm-baseten-inference` feature flag routes matching users to Baseten when its API key is configured. The flag is evaluated server-side, and caller-forwarded flag headers cannot select Baseten. Cloudflare or Modal must remain configured as the fallback for users who do not match the flag or when evaluation is unavailable.Two knobs opt traffic into Modal (OR semantics, both default off):-- The `tasks-glm-modal-inference` feature flag — the primary ramp control, evaluated server-side against PostHog (`LLM_GATEWAY_POSTHOG_PROJECT_TOKEN`/`_HOST`) with a short per-user cache and a brief global backoff when evaluation fails. Caller-forwarded flag headers are deliberately not trusted for routing.+- The `tasks-glm-modal-inference` feature flag, evaluated server-side against PostHog (`LLM_GATEWAY_POSTHOG_PROJECT_TOKEN`/`_HOST`) with a short per-user cache and a brief global backoff when evaluation fails. Caller-forwarded flag headers are not trusted for routing.- `LLM_GATEWAY_GLM_MODAL_TRAFFIC_FRACTION` (0..1, default 0), bucketed deterministically by user id; `LLM_GATEWAY_GLM_MODAL_PRODUCT_TRAFFIC_FRACTIONS` (e.g. `{"posthog_code": 0.25}`) overrides it per product.If Cloudflare credentials are absent, Modal serves all GLM traffic regardless of the knobs.diff --git a/services/llm-gateway/src/llm_gateway/api/handler.py b/services/llm-gateway/src/llm_gateway/api/handler.pyindex 0ed41589e107..d5cb4ca6b657 100644--- a/services/llm-gateway/src/llm_gateway/api/handler.py+++ b/services/llm-gateway/src/llm_gateway/api/handler.py@@ -130,6 +130,21 @@ MODAL_OPENAI_RESPONSES_CONFIG = ProviderConfig(endpoint_name="modal_responses",extract_effort=effort_from_reasoning,)+BASETEN_ANTHROPIC_CONFIG = ProviderConfig(+ name="baseten",+ endpoint_name="baseten_anthropic_messages",+ extract_effort=effort_from_output_config,+)+BASETEN_OPENAI_CONFIG = ProviderConfig(+ name="baseten",+ endpoint_name="baseten_chat_completions",+ extract_effort=effort_from_reasoning_effort,+)+BASETEN_OPENAI_RESPONSES_CONFIG = ProviderConfig(+ name="baseten",+ endpoint_name="baseten_responses",+ extract_effort=effort_from_reasoning,+)_KNOWN_LITELLM_PROVIDER_PREFIXES = ("anthropic/",diff --git a/services/llm-gateway/src/llm_gateway/baseten.py b/services/llm-gateway/src/llm_gateway/baseten.pynew file mode 100644index 000000000000..ef5f4d95b72f--- /dev/null+++ b/services/llm-gateway/src/llm_gateway/baseten.py@@ -0,0 +1,72 @@+from __future__ import annotations++from collections.abc import AsyncIterator, Awaitable, Callable+from typing import Any++import litellm+from fastapi import HTTPException+from litellm.llms.anthropic.experimental_pass_through.adapters.handler import (+ LiteLLMMessagesToCompletionTransformationHandler,+)++from llm_gateway.anthropic_stream import observe_anthropic_stream+from llm_gateway.config import Settings++BASETEN_PUBLIC_MODEL = "@cf/zai-org/glm-5.2"+BASETEN_GLM_MODEL = "zai-org/GLM-5.2"+_BASETEN_LITELLM_MODEL = f"openai/{BASETEN_GLM_MODEL}"+++def is_baseten_configured(settings: Settings) -> bool:+ return bool(settings.baseten_api_base and settings.baseten_api_key)+++def ensure_baseten_configured(settings: Settings) -> tuple[str, str]:+ if not is_baseten_configured(settings):+ raise HTTPException(+ status_code=503,+ detail={"error": {"message": "Baseten inference not configured", "type": "configuration_error"}},+ )+ assert settings.baseten_api_base is not None and settings.baseten_api_key is not None+ return settings.baseten_api_base, settings.baseten_api_key+++def _inject_baseten_params(kwargs: dict[str, Any], api_base: str, api_key: str) -> None:+ kwargs["api_base"] = api_base+ kwargs["api_key"] = api_key+ kwargs.pop("headers", None)+ kwargs["extra_headers"] = {"Authorization": f"Api-Key {api_key}"}+ kwargs["model"] = _BASETEN_LITELLM_MODEL+ kwargs.setdefault("drop_params", True)+ if kwargs.get("stream"):+ stream_options = dict(kwargs.get("stream_options") or {})+ stream_options.update(include_usage=True, continuous_usage_stats=True)+ kwargs["stream_options"] = stream_options+++def make_baseten_anthropic_call(api_base: str, api_key: str) -> Callable[..., Awaitable[Any]]:+ async def llm_call(**kwargs: Any) -> Any:+ _inject_baseten_params(kwargs, api_base, api_key)+ response = await LiteLLMMessagesToCompletionTransformationHandler.async_anthropic_messages_handler(**kwargs)+ if isinstance(response, AsyncIterator):+ return observe_anthropic_stream(response, "baseten")+ return response++ return llm_call+++def make_baseten_completion_call(api_base: str, api_key: str) -> Callable[..., Awaitable[Any]]:+ async def llm_call(**kwargs: Any) -> Any:+ _inject_baseten_params(kwargs, api_base, api_key)+ return await litellm.acompletion(**kwargs)++ return llm_call+++def make_baseten_responses_call(api_base: str, api_key: str) -> Callable[..., Awaitable[Any]]:+ async def llm_call(**kwargs: Any) -> Any:+ _inject_baseten_params(kwargs, api_base, api_key)+ kwargs["use_chat_completions_api"] = True+ return await litellm.aresponses(**kwargs)++ return llm_calldiff --git a/services/llm-gateway/src/llm_gateway/config.py b/services/llm-gateway/src/llm_gateway/config.pyindex de9e2e1dc9c6..d4e3e2ed28bb 100644--- a/services/llm-gateway/src/llm_gateway/config.py+++ b/services/llm-gateway/src/llm_gateway/config.py@@ -164,6 +164,8 @@ class Settings(BaseSettings):fireworks_api_key: str | None = Nonecloudflare_api_key: str | None = Nonecloudflare_account_id: str | None = None+ baseten_api_base: str | None = None+ baseten_api_key: str | None = None# Modal-hosted GLM inference (OpenAI-compatible vLLM endpoint); auth is a proxy-token pair# sent as Modal-Key/Modal-Secret headers. All three must be set for Modal routing.diff --git a/services/llm-gateway/src/llm_gateway/flags.py b/services/llm-gateway/src/llm_gateway/flags.pyindex 2bee590f4b08..96c9ae3cad96 100644--- a/services/llm-gateway/src/llm_gateway/flags.py+++ b/services/llm-gateway/src/llm_gateway/flags.py@@ -11,6 +11,7 @@ from llm_gateway.config import get_settingslogger = structlog.get_logger(__name__)GLM_MODAL_FLAG = "tasks-glm-modal-inference"+GLM_BASETEN_FLAG = "tasks-glm-baseten-inference"_flag_cache: TTLCache[tuple[str, str], bool] = TTLCache(maxsize=10_000, ttl=60)# Global per-flag backoff so an evaluation outage doesn't stack one blocking roundtrip per new user.diff --git a/services/llm-gateway/src/llm_gateway/glm_routing.py b/services/llm-gateway/src/llm_gateway/glm_routing.pyindex 6cad490cee69..6b838ecb1ee5 100644--- a/services/llm-gateway/src/llm_gateway/glm_routing.py+++ b/services/llm-gateway/src/llm_gateway/glm_routing.py@@ -1,9 +1,8 @@-"""Backend selection for GLM (`@cf/...`) traffic during the Cloudflare -> Modal migration.+"""Backend selection for GLM (`@cf/...`) traffic across Cloudflare, Modal, and Baseten.-Modal takes traffic opted in by the server-side `tasks-glm-modal-inference` flag or by the-env-configured fraction (caller-forwarded flag headers are deliberately ignored — they must not-force a backend operators turned off). No cross-backend retries — rollback is turning the-flag/fraction back down.+Modal takes traffic opted in by its server-side flag or the environment-configured fraction.+Baseten takes traffic opted in by its server-side flag. Caller-forwarded flag headers cannot+select a backend. There are no cross-backend retries."""from __future__ import annotations@@ -15,6 +14,9 @@ from fastapi.responses import StreamingResponsefrom llm_gateway.anthropic_request import drop_orphaned_clear_thinkingfrom llm_gateway.api.handler import (+ BASETEN_ANTHROPIC_CONFIG,+ BASETEN_OPENAI_CONFIG,+ BASETEN_OPENAI_RESPONSES_CONFIG,CLOUDFLARE_ANTHROPIC_CONFIG,CLOUDFLARE_OPENAI_CONFIG,CLOUDFLARE_OPENAI_RESPONSES_CONFIG,@@ -25,6 +27,14 @@ from llm_gateway.api.handler import (handle_llm_request,)from llm_gateway.auth.models import AuthenticatedUser+from llm_gateway.baseten import (+ BASETEN_PUBLIC_MODEL,+ ensure_baseten_configured,+ is_baseten_configured,+ make_baseten_anthropic_call,+ make_baseten_completion_call,+ make_baseten_responses_call,+)from llm_gateway.cloudflare import (ensure_cloudflare_configured,ensure_cloudflare_model_allowed,@@ -34,7 +44,7 @@ from llm_gateway.cloudflare import (make_cloudflare_responses_call,)from llm_gateway.config import Settings, get_settings-from llm_gateway.flags import GLM_MODAL_FLAG, evaluate_flag+from llm_gateway.flags import GLM_BASETEN_FLAG, GLM_MODAL_FLAG, evaluate_flagfrom llm_gateway.modal import (is_modal_configured,is_modal_served_model,@@ -70,34 +80,51 @@ async def _route_to_modal(model: str, user: AuthenticatedUser, product: str, setreturn Trueif should_route_glm_to_modal(model, product=product, user_key=str(user.user_id), settings=settings):return True- # Server-side flag evaluation only — a caller-forwarded flag header must not be able to force a- # backend the operators turned off. Evaluated last, since it can cost a remote roundtrip.return await evaluate_flag(GLM_MODAL_FLAG, user.distinct_id) or False-async def _send_via_cloudflare(+async def _route_to_baseten(model: str, user: AuthenticatedUser, settings: Settings) -> bool:+ if model != BASETEN_PUBLIC_MODEL or not is_baseten_configured(settings):+ return False+ return await evaluate_flag(GLM_BASETEN_FLAG, user.distinct_id) or False+++async def _send_provider_request(request_data: dict[str, Any],user: AuthenticatedUser,is_streaming: bool,product: str,provider_config: ProviderConfig,- make_call: Callable[[str, str], LlmCall],- settings: Settings,+ llm_call: LlmCall,) -> dict[str, Any] | StreamingResponse:- model = request_data["model"]- ensure_cloudflare_model_allowed(model)- api_base, api_key = ensure_cloudflare_configured(settings)return await handle_llm_request(request_data=dict(request_data),user=user,- model=model,+ model=request_data["model"],is_streaming=is_streaming,provider_config=provider_config,- llm_call=make_call(api_base, api_key),+ llm_call=llm_call,product=product,)+async def _send_via_cloudflare(+ request_data: dict[str, Any],+ user: AuthenticatedUser,+ is_streaming: bool,+ product: str,+ provider_config: ProviderConfig,+ make_call: Callable[[str, str], LlmCall],+ settings: Settings,+) -> dict[str, Any] | StreamingResponse:+ model = request_data["model"]+ ensure_cloudflare_model_allowed(model)+ api_base, api_key = ensure_cloudflare_configured(settings)+ return await _send_provider_request(+ request_data, user, is_streaming, product, provider_config, make_call(api_base, api_key)+ )++async def _send_glm_request(request_data: dict[str, Any],user: AuthenticatedUser,@@ -105,13 +132,21 @@ async def _send_glm_request(product: str,*,modal_config: ProviderConfig,+ baseten_config: ProviderConfig,cloudflare_config: ProviderConfig,make_modal_call: Callable[[str, str, str], LlmCall],+ make_baseten_call: Callable[[str, str], LlmCall],make_cloudflare_call: Callable[[str, str], LlmCall],) -> dict[str, Any] | StreamingResponse:model = request_data["model"]settings = get_settings()+ if await _route_to_baseten(model, user, settings):+ api_base, api_key = ensure_baseten_configured(settings)+ return await _send_provider_request(+ request_data, user, is_streaming, product, baseten_config, make_baseten_call(api_base, api_key)+ )+if await _route_to_modal(model, user, product, settings):return await send_modal_request(request_data, user, is_streaming, product, modal_config, make_modal_call, settings, handle_llm_request@@ -138,8 +173,10 @@ async def send_glm_anthropic_messages(is_streaming,product,modal_config=MODAL_ANTHROPIC_CONFIG,+ baseten_config=BASETEN_ANTHROPIC_CONFIG,cloudflare_config=CLOUDFLARE_ANTHROPIC_CONFIG,make_modal_call=make_modal_anthropic_call,+ make_baseten_call=make_baseten_anthropic_call,make_cloudflare_call=make_cloudflare_anthropic_call,)@@ -156,8 +193,10 @@ async def send_glm_chat_completions(is_streaming,product,modal_config=MODAL_OPENAI_CONFIG,+ baseten_config=BASETEN_OPENAI_CONFIG,cloudflare_config=CLOUDFLARE_OPENAI_CONFIG,make_modal_call=make_modal_completion_call,+ make_baseten_call=make_baseten_completion_call,make_cloudflare_call=make_cloudflare_completion_call,)@@ -174,7 +213,9 @@ async def send_glm_responses(is_streaming,product,modal_config=MODAL_OPENAI_RESPONSES_CONFIG,+ baseten_config=BASETEN_OPENAI_RESPONSES_CONFIG,cloudflare_config=CLOUDFLARE_OPENAI_RESPONSES_CONFIG,make_modal_call=make_modal_responses_call,+ make_baseten_call=make_baseten_responses_call,make_cloudflare_call=make_cloudflare_responses_call,)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 dcdbcb3cc546..3d317bfcf45f 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@@ -36,6 +36,7 @@ ALIAS_METRIC_LABELS: dict[str, tuple[str, str]] = {"openai/@cf/zai-org/glm-5.2": ("cloudflare", "@cf/zai-org/glm-5.2"),# Same public model id as the CF entry so dashboards slice one model across both backends."openai/zai-org/GLM-5.2-FP8": ("modal", "@cf/zai-org/glm-5.2"),+ "openai/zai-org/GLM-5.2": ("baseten", "@cf/zai-org/glm-5.2"),"openai/moonshotai/kimi-k3": ("modal", "moonshotai/kimi-k3"),}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.pyindex e68af775b4fe..19c6cb0ecc13 100644--- 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.py@@ -22,7 +22,17 @@ KIMI_K3_COST: Final[ModelCost] = {"supports_prompt_caching": True,}+BASETEN_GLM_COST: Final[ModelCost] = {+ "litellm_provider": "baseten",+ "mode": "chat",+ "input_cost_per_token": 1.4e-06,+ "output_cost_per_token": 4.4e-06,+ "cache_read_input_token_cost": 1.4e-07,+ "supports_prompt_caching": True,+}+MODEL_COST_OVERRIDES: Final[dict[str, ModelCost]] = {+ "openai/zai-org/GLM-5.2": cast("ModelCost", dict(BASETEN_GLM_COST)),"moonshotai/kimi-k3": cast("ModelCost", dict(KIMI_K3_COST)),"openai/moonshotai/kimi-k3": cast("ModelCost", dict(KIMI_K3_COST)),"claude-fable-5": {@@ -76,10 +86,13 @@ MODEL_COST_OVERRIDES: Final[dict[str, ModelCost]] = {},}+# Provider-specific contract prices must not be replaced by a same-named LiteLLM entry.+PINNED_MODEL_COST_OVERRIDES: Final[frozenset[str]] = frozenset({"openai/zai-org/GLM-5.2"})+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."""+ """Apply missing bridge entries and contract-pinned provider prices in place."""for model_id, cost in MODEL_COST_OVERRIDES.items():- if model_id not in model_cost:+ if model_id in PINNED_MODEL_COST_OVERRIDES or model_id not in model_cost:model_cost[model_id] = cast("ModelCost", dict(cost))return model_costdiff --git a/services/llm-gateway/tests/test_baseten.py b/services/llm-gateway/tests/test_baseten.pynew file mode 100644index 000000000000..c75cabc29d06--- /dev/null+++ b/services/llm-gateway/tests/test_baseten.py@@ -0,0 +1,66 @@+from typing import Any+from unittest.mock import AsyncMock, patch++import pytest+from fastapi import HTTPException++from llm_gateway.baseten import (+ _inject_baseten_params,+ ensure_baseten_configured,+ make_baseten_responses_call,+)+from llm_gateway.config import Settings+from llm_gateway.rate_limiting.cost_refresh import ALIAS_METRIC_LABELS+from llm_gateway.rate_limiting.model_cost_overrides import MODEL_COST_OVERRIDES++GLM_MODEL = "@cf/zai-org/glm-5.2"+BASETEN_MODEL = "openai/zai-org/GLM-5.2"+++def test_inject_baseten_params_maps_model_and_pins_api_key() -> None:+ kwargs: dict[str, Any] = {+ "model": GLM_MODEL,+ "headers": {"Host": "attacker.example"},+ "extra_headers": {"Authorization": "Bearer attacker", "X-Other": "no"},+ }++ _inject_baseten_params(kwargs, "https://inference.baseten.co/v1", "test-key")++ assert kwargs["model"] == BASETEN_MODEL+ assert kwargs["api_base"] == "https://inference.baseten.co/v1"+ assert "headers" not in kwargs+ assert kwargs["extra_headers"] == {"Authorization": "Api-Key test-key"}+ assert kwargs["drop_params"] is True+ assert BASETEN_MODEL in MODEL_COST_OVERRIDES+ assert MODEL_COST_OVERRIDES[BASETEN_MODEL]["input_cost_per_token"] == 1.4e-06+ assert MODEL_COST_OVERRIDES[BASETEN_MODEL]["cache_read_input_token_cost"] == 1.4e-07+ assert MODEL_COST_OVERRIDES[BASETEN_MODEL]["output_cost_per_token"] == 4.4e-06+ assert ALIAS_METRIC_LABELS[BASETEN_MODEL] == ("baseten", GLM_MODEL)+++def test_inject_baseten_params_forces_streaming_usage() -> None:+ kwargs: dict[str, Any] = {+ "model": GLM_MODEL,+ "stream": True,+ "stream_options": {"include_usage": False},+ }++ _inject_baseten_params(kwargs, "https://inference.baseten.co/v1", "test-key")++ assert kwargs["stream_options"] == {"include_usage": True, "continuous_usage_stats": True}+++def test_ensure_baseten_configured_requires_api_key() -> None:+ with pytest.raises(HTTPException) as exc_info:+ ensure_baseten_configured(Settings())++ assert exc_info.value.status_code == 503+++async def test_make_baseten_responses_call_uses_chat_completions_bridge() -> None:+ llm_call = make_baseten_responses_call("https://inference.baseten.co/v1", "test-key")++ with patch("llm_gateway.baseten.litellm.aresponses", new=AsyncMock(return_value="ok")) as mock_aresponses:+ await llm_call(model=GLM_MODEL, input="hi", use_chat_completions_api=False)++ assert mock_aresponses.call_args.kwargs["use_chat_completions_api"] is Truediff --git a/services/llm-gateway/tests/test_glm_routing.py b/services/llm-gateway/tests/test_glm_routing.pyindex 62f3f86d5068..d3f27dbb80ef 100644--- a/services/llm-gateway/tests/test_glm_routing.py+++ b/services/llm-gateway/tests/test_glm_routing.py@@ -16,6 +16,7 @@ from llm_gateway.glm_routing import (from llm_gateway.request_context import RequestContext, set_request_contextGLM_MODEL = "@cf/zai-org/glm-5.2"+KIMI_MODEL = "@cf/moonshotai/kimi-k2.6"PRODUCT = "posthog_code"SURFACES = [@@ -33,6 +34,7 @@ def _settings(**overrides: Any) -> Settings:base: dict[str, Any] = {"cloudflare_api_key": "cf-key","cloudflare_account_id": "cf-account",+ "baseten_api_base": "https://inference.baseten.co/v1","modal_api_base": "https://posthog--glm.us-east.modal.direct/v1","modal_key": "wk-test","modal_secret": "ws-test",@@ -154,10 +156,57 @@ async def test_alias_products_ramp_through_canonical_fraction(product: str) -> Nasync def test_flag_opts_into_modal_at_fraction_zero() -> None:handle = AsyncMock(return_value={"ok": True})- _, _ = await _send(_settings(), handle, flag=True)+ await _send(_settings(), handle, flag=True)assert _called_providers(handle) == ["modal"]+ ("send_fn", "endpoint"), [(row[0], f"baseten_{row[2].removeprefix('cloudflare_')}") for row in SURFACES]+)+async def test_baseten_flag_routes_each_surface(send_fn: Any, endpoint: str) -> None:+ handle = AsyncMock(return_value={"ok": True})+ settings = _settings(baseten_api_key="baseten-key")++ _, evaluate = await _send(settings, handle, flag=True, send_fn=send_fn)++ assert handle.call_args.kwargs["provider_config"].endpoint_name == endpoint+ evaluate.assert_awaited_once_with("tasks-glm-baseten-inference", "d-1")+++async def test_modal_flag_is_evaluated_without_baseten_credentials() -> None:+ handle = AsyncMock(return_value={"ok": True})++ _, evaluate = await _send(_settings(), handle, flag=False)++ evaluate.assert_awaited_once_with("tasks-glm-modal-inference", "d-1")+++async def test_baseten_flag_does_not_rewrite_other_cloudflare_models() -> None:+ handle = AsyncMock(return_value={"ok": True})+ request = {"model": KIMI_MODEL, "messages": [{"role": "user", "content": "hi"}]}++ _, evaluate = await _send(_settings(baseten_api_key="baseten-key"), handle, flag=True, request_data=request)++ assert _called_providers(handle) == ["cloudflare"]+ assert handle.call_args.kwargs["model"] == KIMI_MODEL+ evaluate.assert_not_called()+++ ("settings", "expected_provider"),+ [+ (_settings(baseten_api_key="baseten-key"), "cloudflare"),+ (_settings(baseten_api_key="baseten-key", glm_modal_traffic_fraction=1.0), "modal"),+ ],+)+async def test_baseten_flag_off_preserves_existing_routing(settings: Settings, expected_provider: str) -> None:+ handle = AsyncMock(return_value={"ok": True})++ await _send(settings, handle, flag=False)++ assert _called_providers(handle) == [expected_provider]++async def test_forwarded_flag_header_cannot_force_modal() -> None:# x-posthog-flag-* headers come from any authenticated caller — they must not override the# server-side flag/fraction, or a client could pin itself to a backend operators turned off.@@ -167,15 +216,22 @@ async def test_forwarded_flag_header_cannot_force_modal() -> None:assert _called_providers(handle) == ["cloudflare"]-async def test_modal_failure_propagates_without_cross_backend_retry() -> None:- # A silent Cloudflare retry would mask Modal degradation from the rollback decision and double- # provider spend under a Modal outage.+ ("settings", "flag", "expected_provider"),+ [+ (_settings(glm_modal_traffic_fraction=1.0), None, "modal"),+ (_settings(baseten_api_key="baseten-key"), True, "baseten"),+ ],+)+async def test_provider_failure_propagates_without_cross_backend_retry(+ settings: Settings, flag: bool | None, expected_provider: str+) -> None:handle = AsyncMock(side_effect=ProviderError(status_code=502, detail={"error": {"message": "boom", "type": "api_error", "code": None}}))with pytest.raises(HTTPException) as exc_info:- await _send(_settings(glm_modal_traffic_fraction=1.0), handle)+ await _send(settings, handle, flag=flag)assert exc_info.value.status_code == 502- assert _called_providers(handle) == ["modal"]+ assert _called_providers(handle) == [expected_provider]diff --git a/services/llm-gateway/tests/test_model_cost_overrides.py b/services/llm-gateway/tests/test_model_cost_overrides.pyindex 170bc624bebf..228acb30f927 100644--- a/services/llm-gateway/tests/test_model_cost_overrides.py+++ b/services/llm-gateway/tests/test_model_cost_overrides.py@@ -9,6 +9,7 @@ import pytestfrom llm_gateway.rate_limiting.model_cost_overrides import (MODEL_COST_OVERRIDES,+ PINNED_MODEL_COST_OVERRIDES,apply_model_cost_overrides,)from llm_gateway.rate_limiting.model_cost_service import ModelCost, ModelCostService@@ -32,13 +33,27 @@ class TestApplyModelCostOverrides: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))+ @pytest.mark.parametrize("model_id", sorted(MODEL_COST_OVERRIDES.keys() - PINNED_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+ @pytest.mark.parametrize("model_id", sorted(PINNED_MODEL_COST_OVERRIDES))+ def test_overrides_upstream_entry_for_pinned_contract_price(self, model_id: str) -> None:+ upstream: ModelCost = {+ "litellm_provider": "openai",+ "input_cost_per_token": -1.0,+ "output_cost_per_token": -1.0,+ }+ cost_map: dict[str, ModelCost] = {model_id: upstream}++ apply_model_cost_overrides(cost_map)++ assert cost_map[model_id] == MODEL_COST_OVERRIDES[model_id]+ assert cost_map[model_id] is not MODEL_COST_OVERRIDES[model_id]+def test_returns_same_object_in_place(self) -> None:cost_map: dict[str, ModelCost] = {}assert apply_model_cost_overrides(cost_map) is cost_map