: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 GLM 5.3 via Baseten (#83361)
Brandon2c18be0d1db5
diff --git a/products/tasks/backend/temporal/process_task/tests/test_utils.py b/products/tasks/backend/temporal/process_task/tests/test_utils.pyindex 394a961507ed..fe060e7a7bda 100644--- a/products/tasks/backend/temporal/process_task/tests/test_utils.py+++ b/products/tasks/backend/temporal/process_task/tests/test_utils.py@@ -35,6 +35,13 @@ from products.tasks.backend.temporal.process_task.utils import (class TestRuntimeModelCapabilities(SimpleTestCase):+ def test_glm_5_3_supports_claude_reasoning_efforts(self) -> None:+ assert "zai-org/glm-5.3" in get_models_for_runtime_adapter("claude")+ assert tuple(effort.value for effort in get_supported_reasoning_efforts("claude", "zai-org/glm-5.3")) == (+ "high",+ "max",+ )+def test_kimi_is_known_without_selectable_reasoning_effort(self) -> None:assert "moonshotai/kimi-k3" in get_models_for_runtime_adapter("claude")assert get_supported_reasoning_efforts("claude", "moonshotai/kimi-k3") == ()diff --git a/products/tasks/backend/temporal/process_task/utils.py b/products/tasks/backend/temporal/process_task/utils.pyindex e5ba3d8864e7..d5a10e4a2d7c 100644--- a/products/tasks/backend/temporal/process_task/utils.py+++ b/products/tasks/backend/temporal/process_task/utils.py@@ -118,6 +118,10 @@ CLAUDE_REASONING_EFFORTS_BY_MODEL: dict[str, tuple[ReasoningEffort, ...]] = {ReasoningEffort.HIGH,ReasoningEffort.MAX,),+ "zai-org/glm-5.3": (+ ReasoningEffort.HIGH,+ ReasoningEffort.MAX,+ ),"moonshotai/kimi-k3": (),"claude-opus-4-5": (ReasoningEffort.LOW,diff --git a/services/llm-gateway/README.md b/services/llm-gateway/README.mdindex 6680e12865a6..392e3edc8d6a 100644--- a/services/llm-gateway/README.md+++ b/services/llm-gateway/README.md@@ -215,6 +215,7 @@ Use your runtime's standard AWS authentication mechanism (e.g. IAM role, IRSA, EThe gateway exposes models consistently across Anthropic Messages, chat/completions, and Responses while choosing their inference provider internally in `src/llm_gateway/inference_routing.py`.- **GLM 5.2** (`@cf/zai-org/glm-5.2`) can run on Cloudflare Workers AI, Modal, or Baseten.+- **GLM 5.3** (`zai-org/glm-5.3`) runs only on Baseten and is available to ReviewHog and PostHog Desktop behind the `tasks-glm-baseten-inference` flag. Do not enable the flag until Baseten lists the model and the deployment slug, context window, and contract rate in `model_cost_overrides.py` / `model_registry.py` are confirmed against `inference.baseten.co/v1/models`: the rate is pinned, so a wrong placeholder bills at the wrong price with no automatic correction.- **DeepSeek V4 Flash** (`deepseek-ai/deepseek-v4-flash-0731`) runs only on Baseten and is available to ReviewHog and PostHog Desktop (client-gated by the `posthog-code-deepseek-model` flag).Provider configuration:diff --git a/services/llm-gateway/src/llm_gateway/baseten.py b/services/llm-gateway/src/llm_gateway/baseten.pyindex 84eca0449d61..19933fab72f2 100644--- a/services/llm-gateway/src/llm_gateway/baseten.py+++ b/services/llm-gateway/src/llm_gateway/baseten.py@@ -19,12 +19,19 @@ BASETEN_METRIC_MODEL = "baseten/zai-org/glm-5.2"BASETEN_DEEPSEEK_PUBLIC_MODEL = "deepseek-ai/deepseek-v4-flash-0731"BASETEN_DEEPSEEK_MODEL = "deepseek-ai/DeepSeek-V4-Flash-0731"BASETEN_DEEPSEEK_METRIC_MODEL = "baseten/deepseek-ai/deepseek-v4-flash-0731"+BASETEN_GLM53_PUBLIC_MODEL = "zai-org/glm-5.3"+BASETEN_GLM53_MODEL = "zai-org/GLM-5.3"+BASETEN_GLM53_METRIC_MODEL = "baseten/zai-org/glm-5.3"BASETEN_MODELS = {BASETEN_PUBLIC_MODEL: BASETEN_GLM_MODEL,BASETEN_DEEPSEEK_PUBLIC_MODEL: BASETEN_DEEPSEEK_MODEL,+ BASETEN_GLM53_PUBLIC_MODEL: BASETEN_GLM53_MODEL,}# Models with no Cloudflare/Modal fallback — always routed to Baseten.-BASETEN_EXCLUSIVE_COST_MODELS: Final[dict[str, str]] = {BASETEN_DEEPSEEK_PUBLIC_MODEL: BASETEN_DEEPSEEK_METRIC_MODEL}+BASETEN_EXCLUSIVE_COST_MODELS: Final[dict[str, str]] = {+ BASETEN_DEEPSEEK_PUBLIC_MODEL: BASETEN_DEEPSEEK_METRIC_MODEL,+ BASETEN_GLM53_PUBLIC_MODEL: BASETEN_GLM53_METRIC_MODEL,+}BASETEN_EXCLUSIVE_MODELS: frozenset[str] = frozenset(BASETEN_EXCLUSIVE_COST_MODELS)diff --git a/services/llm-gateway/src/llm_gateway/inference_routing.py b/services/llm-gateway/src/llm_gateway/inference_routing.pyindex 4efb79003b69..99d3d144b672 100644--- a/services/llm-gateway/src/llm_gateway/inference_routing.py+++ b/services/llm-gateway/src/llm_gateway/inference_routing.py@@ -29,6 +29,7 @@ from llm_gateway.api.handler import (from llm_gateway.auth.models import AuthenticatedUserfrom llm_gateway.baseten import (BASETEN_EXCLUSIVE_MODELS,+ BASETEN_GLM53_PUBLIC_MODEL,BASETEN_PUBLIC_MODEL,ensure_baseten_configured,is_baseten_configured,@@ -61,10 +62,22 @@ LlmCall = Callable[..., Awaitable[Any]]GLM_REASONING_EFFORTS: frozenset[str] = frozenset({"high", "max"})+# GLM models across all backends: these need the Claude-runtime reasoning rewrite on the+# Anthropic surface regardless of which provider serves them.+GLM_MODELS: frozenset[str] = frozenset({BASETEN_PUBLIC_MODEL, BASETEN_GLM53_PUBLIC_MODEL})+def is_inference_routed_model(model: str) -> bool:"""Whether this model id is served by the inference-routing layer rather than a native provider."""- return is_cloudflare_model(model) or model in BASETEN_EXCLUSIVE_MODELS+ normalized = model.strip().lower()+ return is_cloudflare_model(normalized) or normalized in BASETEN_EXCLUSIVE_MODELS+++def normalize_inference_routed_model(request_data: dict[str, Any]) -> dict[str, Any]:+ normalized = request_data["model"].strip().lower()+ if not is_inference_routed_model(normalized) or normalized == request_data["model"]:+ return request_data+ return {**request_data, "model": normalized}def normalize_glm_anthropic_request(request_data: dict[str, Any], *, product: str) -> dict[str, Any]:@@ -178,7 +191,11 @@ async def send_inference_anthropic_messages(is_streaming: bool,product: str,) -> dict[str, Any] | StreamingResponse:- if request_data["model"] not in BASETEN_EXCLUSIVE_MODELS:+ request_data = normalize_inference_routed_model(request_data)+ # Skip normalization only for Baseten-exclusive non-GLM models (DeepSeek); a Baseten-exclusive+ # GLM still needs the Claude-runtime reasoning rewrite.+ model = request_data["model"]+ if model in GLM_MODELS or model not in BASETEN_EXCLUSIVE_MODELS:request_data = normalize_glm_anthropic_request(request_data, product=product)return await _send_inference_request(@@ -201,6 +218,7 @@ async def send_inference_chat_completions(is_streaming: bool,product: str,) -> dict[str, Any] | StreamingResponse:+ request_data = normalize_inference_routed_model(request_data)return await _send_inference_request(request_data,user,@@ -221,6 +239,7 @@ async def send_inference_responses(is_streaming: bool,product: str,) -> dict[str, Any] | StreamingResponse:+ request_data = normalize_inference_routed_model(request_data)return await _send_inference_request(request_data,user,diff --git a/services/llm-gateway/src/llm_gateway/products/config.py b/services/llm-gateway/src/llm_gateway/products/config.pyindex 247e9de2b320..09e49562e4f2 100644--- a/services/llm-gateway/src/llm_gateway/products/config.py+++ b/services/llm-gateway/src/llm_gateway/products/config.py@@ -6,7 +6,7 @@ from typing import Finalfrom fastapi import HTTPException-from llm_gateway.baseten import BASETEN_DEEPSEEK_PUBLIC_MODEL+from llm_gateway.baseten import BASETEN_DEEPSEEK_PUBLIC_MODEL, BASETEN_GLM53_PUBLIC_MODELfrom llm_gateway.bedrock import BEDROCK_MODEL_IDS, get_bedrock_model_access_candidates, get_bedrock_region_namefrom llm_gateway.config import get_settings@@ -88,6 +88,7 @@ _POSTHOG_CODE_AGENT_MODELS: Final[frozenset[str]] = frozenset("gpt-5.2","gpt-5-mini","@cf/zai-org/glm-5.2",+ "zai-org/glm-5.3","moonshotai/kimi-k3",})@@ -99,6 +100,7 @@ _POSTHOG_CODE_AGENT_MODELS: Final[frozenset[str]] = frozenset(RESTRICTED_MODEL_PRODUCTS: Final[dict[str, frozenset[str]]] = {# Evaluated by ReviewHog; exposed in PostHog Code behind the posthog-code-deepseek-model flag.BASETEN_DEEPSEEK_PUBLIC_MODEL: frozenset({"posthog_code", "review_hog"}),+ BASETEN_GLM53_PUBLIC_MODEL: frozenset({"posthog_code", "review_hog"}),}PRODUCTS: Final[dict[str, ProductConfig]] = {@@ -248,10 +250,11 @@ PRODUCTS: Final[dict[str, ProductConfig]] = {allowed_application_ids=None,# The models the review pipeline pins: sonnet-5 (perspectives + one-shots), opus-4-8# (validation), opus-5 (outcome judge), gpt-5.5 / gpt-5.6 sol+luna+terra (Codex reviewers),- # GLM 5.2 and DeepSeek V4 Flash (evaluated as reviewers).+ # GLM 5.2/5.3 and DeepSeek V4 Flash (evaluated as reviewers).allowed_models=frozenset({"@cf/zai-org/glm-5.2",+ "zai-org/glm-5.3","deepseek-ai/deepseek-v4-flash-0731","claude-sonnet-5","claude-opus-4-8",@@ -446,6 +449,7 @@ def check_free_tier_model_access(MODEL_ACCESS_FLAGS: Final[dict[str, str]] = {"moonshotai/kimi-k3": "tasks-kimi-k3","deepseek-ai/deepseek-v4-flash-0731": "posthog-code-deepseek-model",+ "zai-org/glm-5.3": "tasks-glm-baseten-inference",}@@ -469,7 +473,7 @@ def filter_to_free_tier_models(model_ids: list[str]) -> list[str]:def is_model_restricted_for_product(model: str, product: str) -> bool:"""Whether `model` is reserved for other products — see RESTRICTED_MODEL_PRODUCTS."""- allowed_products = RESTRICTED_MODEL_PRODUCTS.get(model.lower())+ allowed_products = RESTRICTED_MODEL_PRODUCTS.get(model.strip().lower())return allowed_products is not None and resolve_product_alias(product) not in allowed_productsdiff --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 3cd6a2fbd68b..84f5b125440b 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@@ -8,7 +8,13 @@ import structlogfrom litellm import model_cost_map_urlfrom litellm.litellm_core_utils.get_model_cost_map import get_model_cost_map-from llm_gateway.baseten import BASETEN_DEEPSEEK_METRIC_MODEL, BASETEN_DEEPSEEK_MODEL, BASETEN_METRIC_MODEL+from llm_gateway.baseten import (+ BASETEN_DEEPSEEK_METRIC_MODEL,+ BASETEN_DEEPSEEK_MODEL,+ BASETEN_GLM53_METRIC_MODEL,+ BASETEN_GLM53_MODEL,+ BASETEN_METRIC_MODEL,+)from llm_gateway.rate_limiting.model_cost_overrides import apply_model_cost_overrideslogger = structlog.get_logger(__name__)@@ -29,6 +35,7 @@ COST_ALIASES: dict[str, tuple[str, str]] = {"openai/zai-org/GLM-5.2-FP8": ("cloudflare/@cf/zai-org/glm-5.2", "openai"),"openai/zai-org/GLM-5.2": (BASETEN_METRIC_MODEL, "openai"),f"openai/{BASETEN_DEEPSEEK_MODEL}": (BASETEN_DEEPSEEK_METRIC_MODEL, "openai"),+ f"openai/{BASETEN_GLM53_MODEL}": (BASETEN_GLM53_METRIC_MODEL, "openai"),"openai/moonshotai/kimi-k3": ("moonshotai/kimi-k3", "openai"),}@@ -41,6 +48,7 @@ ALIAS_METRIC_LABELS: dict[str, tuple[str, str]] = {"openai/zai-org/GLM-5.2-FP8": ("modal", "@cf/zai-org/glm-5.2"),"openai/zai-org/GLM-5.2": ("baseten", BASETEN_METRIC_MODEL),f"openai/{BASETEN_DEEPSEEK_MODEL}": ("baseten", BASETEN_DEEPSEEK_METRIC_MODEL),+ f"openai/{BASETEN_GLM53_MODEL}": ("baseten", BASETEN_GLM53_METRIC_MODEL),"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 d9f1cfebfac1..6d4315c99044 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@@ -2,7 +2,7 @@ from __future__ import annotationsfrom typing import TYPE_CHECKING, Final, cast-from llm_gateway.baseten import BASETEN_DEEPSEEK_METRIC_MODEL, BASETEN_METRIC_MODEL+from llm_gateway.baseten import BASETEN_DEEPSEEK_METRIC_MODEL, BASETEN_GLM53_METRIC_MODEL, BASETEN_METRIC_MODELif TYPE_CHECKING:from llm_gateway.rate_limiting.model_cost_service import ModelCost@@ -33,6 +33,18 @@ BASETEN_GLM_COST: Final[ModelCost] = {"supports_prompt_caching": True,}+# Placeholder: the GLM 5.2 contract rate, pending Baseten listing GLM 5.3. The pin below+# blocks any automatic correction, so confirm the real contract rate here BEFORE creating+# the tasks-glm-baseten-inference flag (see the README's GLM 5.3 go-live note).+BASETEN_GLM53_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,+}+BASETEN_DEEPSEEK_COST: Final[ModelCost] = {"litellm_provider": "baseten","mode": "chat",@@ -45,6 +57,7 @@ BASETEN_DEEPSEEK_COST: Final[ModelCost] = {MODEL_COST_OVERRIDES: Final[dict[str, ModelCost]] = {BASETEN_METRIC_MODEL: cast("ModelCost", dict(BASETEN_GLM_COST)),BASETEN_DEEPSEEK_METRIC_MODEL: cast("ModelCost", dict(BASETEN_DEEPSEEK_COST)),+ BASETEN_GLM53_METRIC_MODEL: cast("ModelCost", dict(BASETEN_GLM53_COST)),"moonshotai/kimi-k3": cast("ModelCost", dict(KIMI_K3_COST)),"claude-fable-5": {"litellm_provider": "anthropic",@@ -98,7 +111,9 @@ 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({BASETEN_METRIC_MODEL, BASETEN_DEEPSEEK_METRIC_MODEL})+PINNED_MODEL_COST_OVERRIDES: Final[frozenset[str]] = frozenset(+ {BASETEN_METRIC_MODEL, BASETEN_DEEPSEEK_METRIC_MODEL, BASETEN_GLM53_METRIC_MODEL}+)def apply_model_cost_overrides(model_cost: dict[str, ModelCost]) -> dict[str, ModelCost]:diff --git a/services/llm-gateway/src/llm_gateway/services/model_registry.py b/services/llm-gateway/src/llm_gateway/services/model_registry.pyindex 1c1c932ec06a..0170ef3efe11 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,13 @@ import osfrom dataclasses import dataclassfrom typing import ClassVar, Final-from llm_gateway.baseten import BASETEN_EXCLUSIVE_COST_MODELS, BASETEN_EXCLUSIVE_MODELS, is_baseten_configured+from llm_gateway.baseten import (+ BASETEN_DEEPSEEK_PUBLIC_MODEL,+ BASETEN_EXCLUSIVE_COST_MODELS,+ BASETEN_EXCLUSIVE_MODELS,+ BASETEN_GLM53_PUBLIC_MODEL,+ is_baseten_configured,+)from llm_gateway.cloudflare import CLOUDFLARE_ALLOWED_MODELS, is_cloudflare_configuredfrom llm_gateway.config import get_settingsfrom llm_gateway.modal import (@@ -24,7 +30,11 @@ from llm_gateway.rate_limiting.model_cost_service import ModelCost, ModelCostSer# and silently fall back to their default._CLOUDFLARE_PROVIDER: Final[str] = "cloudflare"_CLOUDFLARE_DEFAULT_CONTEXT_WINDOW: Final[int] = 128_000-_BASETEN_DEFAULT_CONTEXT_WINDOW: Final[int] = 1_048_000+_BASETEN_CONTEXT_WINDOWS: Final[dict[str, int]] = {+ BASETEN_DEEPSEEK_PUBLIC_MODEL: 1_048_000,+ # Placeholder pending confirmation against the Baseten deployment.+ BASETEN_GLM53_PUBLIC_MODEL: 200_000,+}@dataclass(frozen=True)@@ -174,7 +184,7 @@ class ModelRegistryService:id=model_id,cost_model_id=BASETEN_EXCLUSIVE_COST_MODELS[model_id],provider="baseten",- context_window=_BASETEN_DEFAULT_CONTEXT_WINDOW,+ context_window=_BASETEN_CONTEXT_WINDOWS[model_id],supports_streaming=True,supports_vision=False,)diff --git a/services/llm-gateway/tests/test_baseten.py b/services/llm-gateway/tests/test_baseten.pyindex 7e3668712eaf..91e7038e154b 100644--- a/services/llm-gateway/tests/test_baseten.py+++ b/services/llm-gateway/tests/test_baseten.py@@ -17,6 +17,8 @@ GLM_MODEL = "@cf/zai-org/glm-5.2"BASETEN_MODEL = "openai/zai-org/GLM-5.2"DEEPSEEK_MODEL = "deepseek-ai/deepseek-v4-flash-0731"BASETEN_DEEPSEEK_LITELLM_MODEL = "openai/deepseek-ai/DeepSeek-V4-Flash-0731"+GLM53_MODEL = "zai-org/glm-5.3"+BASETEN_GLM53_LITELLM_MODEL = "openai/zai-org/GLM-5.3"@pytest.mark.parametrize(@@ -24,6 +26,7 @@ BASETEN_DEEPSEEK_LITELLM_MODEL = "openai/deepseek-ai/DeepSeek-V4-Flash-0731"[(GLM_MODEL, BASETEN_MODEL, "baseten/zai-org/glm-5.2", 1.4e-06, 4.4e-06, 1.4e-07),(DEEPSEEK_MODEL, BASETEN_DEEPSEEK_LITELLM_MODEL, f"baseten/{DEEPSEEK_MODEL}", 1.3e-07, 2.6e-07, 2.8e-08),+ (GLM53_MODEL, BASETEN_GLM53_LITELLM_MODEL, f"baseten/{GLM53_MODEL}", 1.4e-06, 4.4e-06, 1.4e-07),],)def test_inject_baseten_params_maps_model_and_pins_api_key(diff --git a/services/llm-gateway/tests/test_dependencies.py b/services/llm-gateway/tests/test_dependencies.pyindex d54c3fe1f650..3e9ab4840b6f 100644--- a/services/llm-gateway/tests/test_dependencies.py+++ b/services/llm-gateway/tests/test_dependencies.py@@ -7,7 +7,7 @@ from starlette.datastructures import Headersfrom llm_gateway.auth.models import AuthenticatedUserfrom llm_gateway.auth.service import InvalidProjectScopeError, UnauthorizedProjectScopeError-from llm_gateway.baseten import BASETEN_DEEPSEEK_PUBLIC_MODEL+from llm_gateway.baseten import BASETEN_DEEPSEEK_PUBLIC_MODEL, BASETEN_GLM53_PUBLIC_MODELfrom llm_gateway.config import get_settingsfrom llm_gateway.dependencies import (_extract_end_user_id_from_body,@@ -458,14 +458,21 @@ class TestBasetenExclusiveModelGateWiring:):yield- # DeepSeek V4 Flash is Baseten-only with no fallback and isn't cleared for external rollout,- # so it's blocked behind its own access flag (not the GLM Baseten routing flag).+ # Baseten-only models with no fallback aren't cleared for external rollout, so each is blocked+ # behind its own access flag (not the GLM Baseten routing flag).@pytest.mark.asyncio+ @pytest.mark.parametrize(+ ("model", "access_flag", "path"),+ [+ (BASETEN_DEEPSEEK_PUBLIC_MODEL, "posthog-code-deepseek-model", "/posthog_code/v1/messages"),+ (BASETEN_GLM53_PUBLIC_MODEL, "tasks-glm-baseten-inference", "/posthog_code/v1/messages"),+ ],+ )@pytest.mark.parametrize("flag_result", [False, None])- async def test_baseten_exclusive_model_blocked_when_flag_off_or_unavailable(self, flag_result: bool | None) -> None:- request = _make_request(- {"model": BASETEN_DEEPSEEK_PUBLIC_MODEL, "messages": []}, path="/posthog_code/v1/messages"- )+ async def test_baseten_exclusive_model_blocked_when_flag_off_or_unavailable(+ self, flag_result: bool | None, model: str, access_flag: str, path: str+ ) -> None:+ request = _make_request({"model": model, "messages": []}, path=path)user = _make_user(auth_method="oauth_access_token", user_id=7)runner = MagicMock()@@ -481,13 +488,12 @@ class TestBasetenExclusiveModelGateWiring:assert exc_info.value.status_code == 403assert exc_info.value.detail["error"]["code"] == "model_gate"assert flag.await_args is not None- assert flag.await_args.args[0] == "posthog-code-deepseek-model"+ assert flag.await_args.args[0] == access_flag@pytest.mark.asyncio- async def test_baseten_exclusive_model_allowed_when_flag_enabled(self) -> None:- request = _make_request(- {"model": BASETEN_DEEPSEEK_PUBLIC_MODEL, "messages": []}, path="/posthog_code/v1/messages"- )+ @pytest.mark.parametrize("model", [BASETEN_DEEPSEEK_PUBLIC_MODEL, BASETEN_GLM53_PUBLIC_MODEL])+ async def test_baseten_exclusive_model_allowed_when_flag_enabled(self, model: str) -> None:+ request = _make_request({"model": model, "messages": []}, path="/posthog_code/v1/messages")user = _make_user(auth_method="oauth_access_token", user_id=7)runner = MagicMock()diff --git a/services/llm-gateway/tests/test_inference_routing.py b/services/llm-gateway/tests/test_inference_routing.pyindex 7a60b7f236a3..8672c3124d20 100644--- a/services/llm-gateway/tests/test_inference_routing.py+++ b/services/llm-gateway/tests/test_inference_routing.py@@ -22,6 +22,7 @@ from llm_gateway.modal import make_modal_anthropic_callfrom llm_gateway.request_context import RequestContext, set_request_contextGLM_MODEL = "@cf/zai-org/glm-5.2"+GLM53_MODEL = "zai-org/glm-5.3"DEEPSEEK_MODEL = "deepseek-ai/deepseek-v4-flash-0731"KIMI_MODEL = "@cf/moonshotai/kimi-k2.6"PRODUCT = "posthog_code"@@ -180,20 +181,36 @@ async def test_baseten_flag_routes_each_surface(send_fn: Any, endpoint: str) ->evaluate.assert_awaited_once_with("tasks-glm-baseten-inference", "d-1")[email protected]("model", [DEEPSEEK_MODEL, GLM53_MODEL])@pytest.mark.parametrize(("send_fn", "endpoint"), [(row[0], f"baseten_{row[2].removeprefix('cloudflare_')}") for row in SURFACES])-async def test_deepseek_routes_each_surface_directly_to_baseten(send_fn: Any, endpoint: str) -> None:+async def test_baseten_exclusive_models_route_each_surface_directly_to_baseten(+ send_fn: Any, endpoint: str, model: str+) -> None:handle = AsyncMock(return_value={"ok": True})- request = {"model": DEEPSEEK_MODEL, "messages": [{"role": "user", "content": "hi"}]}+ request = {"model": model, "messages": [{"role": "user", "content": "hi"}]}_, evaluate = await _send(_settings(baseten_api_key="baseten-key"), handle, send_fn=send_fn, request_data=request)assert handle.call_args.kwargs["provider_config"].endpoint_name == endpoint- assert handle.call_args.kwargs["model"] == DEEPSEEK_MODEL+ assert handle.call_args.kwargs["model"] == modelevaluate.assert_not_called()+ ("send_fn", "endpoint"), [(row[0], f"baseten_{row[2].removeprefix('cloudflare_')}") for row in SURFACES]+)+async def test_baseten_exclusive_model_case_variants_are_canonicalized(send_fn: Any, endpoint: str) -> None:+ handle = AsyncMock(return_value={"ok": True})+ request = {"model": "ZAI-Org/GLM-5.3", "messages": [{"role": "user", "content": "hi"}]}++ await _send(_settings(baseten_api_key="baseten-key"), handle, send_fn=send_fn, request_data=request)++ assert handle.call_args.kwargs["provider_config"].endpoint_name == endpoint+ assert handle.call_args.kwargs["model"] == GLM53_MODEL++async def test_deepseek_does_not_apply_glm_anthropic_normalization() -> None:handle = AsyncMock(return_value={"ok": True})request = {@@ -207,6 +224,20 @@ async def test_deepseek_does_not_apply_glm_anthropic_normalization() -> None:assert handle.call_args.kwargs["request_data"] == request+async def test_baseten_exclusive_glm_still_applies_anthropic_normalization() -> None:+ # A Baseten-exclusive GLM is still a GLM: the Claude-runtime reasoning rewrite must apply.+ handle = AsyncMock(return_value={"ok": True})+ request = {+ "model": GLM53_MODEL,+ "messages": [{"role": "user", "content": "hi"}],+ "output_config": {"effort": "high"},+ }++ await _send(_settings(baseten_api_key="baseten-key"), handle, request_data=request)++ assert handle.call_args.kwargs["request_data"] == {**request, "thinking": {"type": "adaptive"}}++async def test_modal_flag_is_evaluated_without_baseten_credentials() -> None:handle = AsyncMock(return_value={"ok": True})diff --git a/services/llm-gateway/tests/test_model_cost_overrides.py b/services/llm-gateway/tests/test_model_cost_overrides.pyindex 228acb30f927..d3e7eb4f207a 100644--- a/services/llm-gateway/tests/test_model_cost_overrides.py+++ b/services/llm-gateway/tests/test_model_cost_overrides.py@@ -54,6 +54,16 @@ class TestApplyModelCostOverrides:assert cost_map[model_id] == MODEL_COST_OVERRIDES[model_id]assert cost_map[model_id] is not MODEL_COST_OVERRIDES[model_id]+ def test_pinned_membership_is_exactly_the_baseten_contract_prices(self) -> None:+ # Literals on purpose: the parametrized tests above derive their groups from the+ # sets under test, so removing a member there only reshuffles which semantics get+ # asserted. Un-pinning a contract price must fail here.+ assert PINNED_MODEL_COST_OVERRIDES == {+ "baseten/zai-org/glm-5.2",+ "baseten/deepseek-ai/deepseek-v4-flash-0731",+ "baseten/zai-org/glm-5.3",+ }+def test_returns_same_object_in_place(self) -> None:cost_map: dict[str, ModelCost] = {}assert apply_model_cost_overrides(cost_map) is cost_mapdiff --git a/services/llm-gateway/tests/test_model_registry.py b/services/llm-gateway/tests/test_model_registry.pyindex 916bc7434969..1a887fe4b455 100644--- a/services/llm-gateway/tests/test_model_registry.py+++ b/services/llm-gateway/tests/test_model_registry.py@@ -381,22 +381,29 @@ class TestCloudflareModelAdvertising:class TestBasetenModelAdvertising:- def test_deepseek_is_available_to_code_and_review_hog(self):+ @pytest.mark.parametrize(+ ("model_id", "context_window", "allowed_products"),+ [+ ("deepseek-ai/deepseek-v4-flash-0731", 1_048_000, ("review_hog", "posthog_code")),+ ("zai-org/glm-5.3", 200_000, ("review_hog", "posthog_code")),+ ],+ )+ def test_baseten_exclusive_models_advertised_per_product(+ self, model_id: str, context_window: int, allowed_products: tuple[str, ...]+ ):with patch("llm_gateway.services.model_registry.get_settings",return_value=create_mock_settings(baseten=True),):- assert is_model_available("deepseek-ai/deepseek-v4-flash-0731", "review_hog") is True- assert is_model_available("deepseek-ai/deepseek-v4-flash-0731", "posthog_code") is True- assert is_model_available("deepseek-ai/deepseek-v4-flash-0731", "llm_gateway") is False- assert is_model_available("deepseek-ai/deepseek-v4-flash-0731", "slack_app") is False- for product in ("review_hog", "posthog_code"):+ for product in ("review_hog", "posthog_code", "llm_gateway", "slack_app"):+ assert is_model_available(model_id, product) is (product in allowed_products)+ for product in allowed_products:model = next(modelfor model in ModelRegistryService.get_instance().get_available_models(product)- if model.id == "deepseek-ai/deepseek-v4-flash-0731"+ if model.id == model_id)- assert model.context_window == 1_048_000+ assert model.context_window == context_windowclass TestModelMatchesAllowlist:diff --git a/services/llm-gateway/tests/test_product_config.py b/services/llm-gateway/tests/test_product_config.pyindex d02852112ed4..30c47b8ae685 100644--- a/services/llm-gateway/tests/test_product_config.py+++ b/services/llm-gateway/tests/test_product_config.py@@ -3,6 +3,10 @@ from unittest.mock import MagicMock, patchimport pytestfrom fastapi import HTTPException+from llm_gateway.baseten import BASETEN_MODELS+from llm_gateway.cloudflare import CLOUDFLARE_ALLOWED_MODELS+from llm_gateway.inference_routing import is_inference_routed_model+from llm_gateway.modal import is_modal_served_modelfrom llm_gateway.products.config import (ALLOWED_PRODUCTS,BEDROCK_MODELS,@@ -83,6 +87,16 @@ class TestCheckProductAccess:True,None,),+ ("llm_gateway", "personal_api_key", None, "zai-org/glm-5.3", False, "not allowed"),+ ("review_hog", "personal_api_key", None, "zai-org/glm-5.3", True, None),+ (+ "posthog_code",+ "oauth_access_token",+ POSTHOG_CODE_US_APP_ID,+ "zai-org/glm-5.3",+ True,+ None,+ ),# ci allows API keys with any model (used by e2e test runs); OAuth rejected (no app IDs)("ci", "personal_api_key", None, "claude-3-opus", True, None),("ci", "oauth_access_token", "any-app-id", "gpt-4o", False, "not authorized"),@@ -210,10 +224,16 @@ class TestCheckProductAccess:assert allowed is Trueassert error is None- def test_slack_app_rejects_deepseek_despite_shared_allowlist(self):- allowed, error = check_product_access(- "slack_app", "oauth_access_token", POSTHOG_CODE_US_APP_ID, "deepseek-ai/deepseek-v4-flash-0731"- )+ @pytest.mark.parametrize("model", ["deepseek-ai/deepseek-v4-flash-0731", "zai-org/glm-5.3"])+ def test_slack_app_rejects_restricted_models_despite_shared_allowlist(self, model: str):+ allowed, error = check_product_access("slack_app", "oauth_access_token", POSTHOG_CODE_US_APP_ID, model)+ assert allowed is False+ assert error is not None+ assert "not allowed" in error++ @pytest.mark.parametrize("model", [" deepseek-ai/deepseek-v4-flash-0731 ", " zai-org/glm-5.3 "])+ def test_whitespace_cannot_bypass_restricted_model_products(self, model: str):+ allowed, error = check_product_access("llm_gateway", "personal_api_key", None, model)assert allowed is Falseassert error is not Noneassert "not allowed" in error@@ -681,15 +701,36 @@ class TestModelAccessFlag:(" moonshotai/kimi-k3 ", "moonshotai/kimi-k3"),("deepseek-ai/deepseek-v4-flash-0731", "deepseek-ai/deepseek-v4-flash-0731"),("DeepSeek-AI/DeepSeek-V4-Flash-0731", "deepseek-ai/deepseek-v4-flash-0731"),+ ("zai-org/glm-5.3", "zai-org/glm-5.3"),+ ("ZAI-Org/GLM-5.3", "zai-org/glm-5.3"),],)def test_gated_model_requires_its_own_flag(self, model: str, gated: str):# each model resolves to its own dedicated access flag, not a shared oneassert get_required_model_flag(model) == MODEL_ACCESS_FLAGS[gated]- def test_kimi_and_deepseek_use_distinct_flags(self):- assert MODEL_ACCESS_FLAGS["moonshotai/kimi-k3"] != MODEL_ACCESS_FLAGS["deepseek-ai/deepseek-v4-flash-0731"]+ def test_every_gated_model_has_its_own_flag(self):+ flags = list(MODEL_ACCESS_FLAGS.values())+ assert len(flags) == len(set(flags))@pytest.mark.parametrize("model", [None, "", "gpt-5.2", "claude-opus-5", "@cf/zai-org/glm-5.2"])def test_ungated_models_need_no_flag(self, model: str | None):assert get_required_model_flag(model) is None++ def test_suffixed_gated_model_ids_reach_no_backend(self):+ # Product allowlists prefix-match while the access-flag gate matches exactly, so a+ # suffixed id (e.g. zai-org/glm-5.3x) can pass the allowlist without a flag+ # evaluation. Routing exactness is the backstop that keeps such ids unserved; this+ # pins that invariant for every gated model. Literal vocabulary so a new gated+ # model is added here consciously.+ assert set(MODEL_ACCESS_FLAGS) == {+ "moonshotai/kimi-k3",+ "deepseek-ai/deepseek-v4-flash-0731",+ "zai-org/glm-5.3",+ }+ for gated_model in MODEL_ACCESS_FLAGS:+ suffixed = f"{gated_model}x"+ assert not is_inference_routed_model(suffixed)+ assert suffixed not in BASETEN_MODELS+ assert not is_modal_served_model(suffixed)+ assert suffixed not in CLOUDFLARE_ALLOWED_MODELS