Skip to content

: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.

feat(llm-gateway): add DeepSeek V4 Flash via Baseten (#76879)

Peter Kirkhama02e594641ad
diff --git a/services/llm-gateway/README.md b/services/llm-gateway/README.md
index 0393531cf470..7c33d5b1edfc 100644
--- a/services/llm-gateway/README.md
+++ b/services/llm-gateway/README.md
@@ -200,10 +200,14 @@ To use Bedrock (either via `X-PostHog-Provider` or `X-PostHog-Use-Bedrock-Fallba
Credentials 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
+## Inference-provider routing
-GLM 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`:
+The 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.
+- **DeepSeek V4 Flash** (`deepseek-ai/deepseek-v4-flash-0731`) runs only on Baseten and is available to ReviewHog and PostHog Code (client-gated by the `posthog-code-deepseek-model` flag).
+
+Provider configuration:
- **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).
diff --git a/services/llm-gateway/src/llm_gateway/api/anthropic.py b/services/llm-gateway/src/llm_gateway/api/anthropic.py
index 59777de51ef1..e31b35c54a3f 100644
--- a/services/llm-gateway/src/llm_gateway/api/anthropic.py
+++ b/services/llm-gateway/src/llm_gateway/api/anthropic.py
@@ -35,7 +35,7 @@ from llm_gateway.cloudflare import (
)
from llm_gateway.config import get_settings
from llm_gateway.dependencies import AnthropicCircuitBreakerDep, RateLimitedUser
-from llm_gateway.glm_routing import send_glm_anthropic_messages
+from llm_gateway.inference_routing import is_inference_routed_model, send_inference_anthropic_messages
from llm_gateway.metrics.prometheus import (
ANTHROPIC_CIRCUIT_BREAKER_BYPASSED,
BEDROCK_COUNT_TOKENS_ERRORS,
@@ -526,16 +526,15 @@ async def _handle_anthropic_messages(
provider = _get_provider_from_headers(request)
use_bedrock_fallback = _get_use_bedrock_fallback_from_headers(request)
- # `@cf/` models are served by the GLM routing layer (Cloudflare, or Modal during the ramp), so
- # route them by model id — the same way the chat/completions and responses handlers do. The
- # agent harness derives the provider header from the runtime (`claude`->anthropic,
- # `codex`->openai) and never sends "cloudflare", so a claude-runtime scout on a CF-served model
- # (e.g. GLM) arrives here as provider="anthropic". Without the id check it would fall through to
- # the real Anthropic API and 404. Unlike the Responses path, this route serves tools fine:
- # litellm's Anthropic->chat/completions adapter translates Anthropic tools into OpenAI function
- # tools that both backends' OpenAI-compatible endpoints accept.
- if provider == "cloudflare" or is_cloudflare_model(body.model):
- return await send_glm_anthropic_messages(data, user, body.stream or False, product)
+ # Models backed by our inference providers route by model id, just as the chat/completions and
+ # responses handlers do. The agent harness derives the provider header from the runtime
+ # (`claude`->anthropic, `codex`->openai) and never sends "cloudflare", so a claude-runtime scout
+ # on a CF-served model (e.g. GLM) arrives here as provider="anthropic". Without the id check it
+ # would fall through to the real Anthropic API and 404. Unlike the Responses path, this route
+ # serves tools fine: litellm's Anthropic->chat/completions adapter translates Anthropic tools
+ # into OpenAI function tools that both backends' OpenAI-compatible endpoints accept.
+ if provider == "cloudflare" or is_inference_routed_model(body.model):
+ return await send_inference_anthropic_messages(data, user, body.stream or False, product)
if is_modal_served_model(body.model):
return await send_modal_anthropic_messages(data, user, body.stream or False, product)
diff --git a/services/llm-gateway/src/llm_gateway/api/openai.py b/services/llm-gateway/src/llm_gateway/api/openai.py
index 271e1b6d1f46..98db2ee91689 100644
--- a/services/llm-gateway/src/llm_gateway/api/openai.py
+++ b/services/llm-gateway/src/llm_gateway/api/openai.py
@@ -11,9 +11,12 @@ from llm_gateway.api.handler import (
handle_llm_request,
normalize_litellm_model_name,
)
-from llm_gateway.cloudflare import is_cloudflare_model
from llm_gateway.dependencies import RateLimitedUser
-from llm_gateway.glm_routing import send_glm_chat_completions, send_glm_responses
+from llm_gateway.inference_routing import (
+ is_inference_routed_model,
+ send_inference_chat_completions,
+ send_inference_responses,
+)
from llm_gateway.modal import is_modal_served_model
from llm_gateway.modal_routing import send_modal_chat_completions, send_modal_responses
from llm_gateway.models.openai import ChatCompletionRequest, ResponsesRequest, TranscriptionRequest
@@ -38,8 +41,8 @@ async def _handle_chat_completions(
) -> dict[str, Any] | StreamingResponse:
data = body.model_dump(exclude_none=True)
- if is_cloudflare_model(body.model):
- return await send_glm_chat_completions(data, user, body.stream or False, product)
+ if is_inference_routed_model(body.model):
+ return await send_inference_chat_completions(data, user, body.stream or False, product)
if is_modal_served_model(body.model):
return await send_modal_chat_completions(data, user, body.stream or False, product)
@@ -67,18 +70,16 @@ async def _handle_responses(
"""
data = body.model_dump(exclude_none=True)
- if is_cloudflare_model(body.model):
- # `@cf/`-served models can't use the native OpenAI Responses path below: it would prefix
- # `openai/` and call the real OpenAI Responses API. Route through the GLM backend's endpoint
- # via litellm's Responses->chat/completions bridge instead (see make_cloudflare_responses_call
- # / make_modal_responses_call).
+ if is_inference_routed_model(body.model):
+ # OpenAI-compatible backends can't use the native OpenAI Responses path below: it would prefix
+ # `openai/` and call the real OpenAI Responses API. Route through the selected inference
+ # provider's endpoint via litellm's Responses->chat/completions bridge instead (see
+ # make_cloudflare_responses_call / make_modal_responses_call).
if body.previous_response_id is not None:
# The bridge rebuilds prior turns from litellm proxy spend logs; we run litellm as an
# SDK (no proxy DB), so it would silently resolve to empty history and drop the
# conversation. Reject explicitly rather than answer with lost context.
- raise _invalid_request_error(
- "previous_response_id is not supported for Cloudflare models on the Responses API"
- )
+ raise _invalid_request_error("previous_response_id is not supported for this model on the Responses API")
if data.get("tools"):
# `tools` arrives as an extra field (ResponsesRequest allows extras). The
# Responses->chat/completions bridge doesn't faithfully translate Responses-shaped
@@ -86,8 +87,8 @@ async def _handle_responses(
# chat-completions-shaped function tools lose their name, so the backend's
# chat/completions endpoint rejects the payload. Reject up front rather than hand it a
# request that will fail once tools are advertised.
- raise _invalid_request_error("tools are not yet supported for Cloudflare models on the Responses API")
- return await send_glm_responses(data, user, body.stream or False, product)
+ raise _invalid_request_error("tools are not yet supported for this model on the Responses API")
+ return await send_inference_responses(data, user, body.stream or False, product)
if is_modal_served_model(body.model):
if body.previous_response_id is not None:
diff --git a/services/llm-gateway/src/llm_gateway/baseten.py b/services/llm-gateway/src/llm_gateway/baseten.py
index 09164016ba3d..76ada99bc85d 100644
--- a/services/llm-gateway/src/llm_gateway/baseten.py
+++ b/services/llm-gateway/src/llm_gateway/baseten.py
@@ -15,7 +15,15 @@ from llm_gateway.config import Settings
BASETEN_PUBLIC_MODEL = "@cf/zai-org/glm-5.2"
BASETEN_GLM_MODEL = "zai-org/GLM-5.2"
BASETEN_METRIC_MODEL = "baseten/zai-org/glm-5.2"
-_BASETEN_LITELLM_MODEL = f"openai/{BASETEN_GLM_MODEL}"
+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_MODELS = {
+ BASETEN_PUBLIC_MODEL: BASETEN_GLM_MODEL,
+ 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})
def is_baseten_configured(settings: Settings) -> bool:
@@ -33,11 +41,12 @@ def ensure_baseten_configured(settings: Settings) -> tuple[str, str]:
def _inject_baseten_params(kwargs: dict[str, Any], api_base: str, api_key: str) -> None:
+ model = kwargs["model"]
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["extra_headers"] = {"Authorization": f"Bearer {api_key}"}
+ kwargs["model"] = f"openai/{BASETEN_MODELS[model]}"
kwargs.setdefault("drop_params", True)
if kwargs.get("stream"):
stream_options = dict(kwargs.get("stream_options") or {})
diff --git a/services/llm-gateway/src/llm_gateway/glm_routing.py b/services/llm-gateway/src/llm_gateway/inference_routing.py
similarity index 84%
rename from services/llm-gateway/src/llm_gateway/glm_routing.py
rename to services/llm-gateway/src/llm_gateway/inference_routing.py
index 6b838ecb1ee5..4efb79003b69 100644
--- a/services/llm-gateway/src/llm_gateway/glm_routing.py
+++ b/services/llm-gateway/src/llm_gateway/inference_routing.py
@@ -1,8 +1,8 @@
-"""Backend selection for GLM (`@cf/...`) traffic across Cloudflare, Modal, and Baseten.
+"""Route supported models to their configured inference providers.
-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.
+GLM can be served by Cloudflare, Modal, or Baseten. DeepSeek V4 Flash is served only by
+Baseten. Provider selection is internal to the gateway; caller-forwarded feature flag headers
+cannot select a backend. There are no cross-provider retries.
"""
from __future__ import annotations
@@ -28,6 +28,7 @@ from llm_gateway.api.handler import (
)
from llm_gateway.auth.models import AuthenticatedUser
from llm_gateway.baseten import (
+ BASETEN_EXCLUSIVE_MODELS,
BASETEN_PUBLIC_MODEL,
ensure_baseten_configured,
is_baseten_configured,
@@ -39,6 +40,7 @@ from llm_gateway.cloudflare import (
ensure_cloudflare_configured,
ensure_cloudflare_model_allowed,
is_cloudflare_configured,
+ is_cloudflare_model,
make_cloudflare_anthropic_call,
make_cloudflare_completion_call,
make_cloudflare_responses_call,
@@ -60,6 +62,11 @@ LlmCall = Callable[..., Awaitable[Any]]
GLM_REASONING_EFFORTS: frozenset[str] = frozenset({"high", "max"})
+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
+
+
def normalize_glm_anthropic_request(request_data: dict[str, Any], *, product: str) -> dict[str, Any]:
"""Make Claude runtime reasoning settings valid for GLM's Anthropic surface."""
normalized = dict(request_data)
@@ -84,7 +91,11 @@ async def _route_to_modal(model: str, user: AuthenticatedUser, product: str, set
async def _route_to_baseten(model: str, user: AuthenticatedUser, settings: Settings) -> bool:
- if model != BASETEN_PUBLIC_MODEL or not is_baseten_configured(settings):
+ if not is_baseten_configured(settings):
+ return False
+ if model in BASETEN_EXCLUSIVE_MODELS:
+ return True
+ if model != BASETEN_PUBLIC_MODEL:
return False
return await evaluate_flag(GLM_BASETEN_FLAG, user.distinct_id) or False
@@ -125,7 +136,7 @@ async def _send_via_cloudflare(
)
-async def _send_glm_request(
+async def _send_inference_request(
request_data: dict[str, Any],
user: AuthenticatedUser,
is_streaming: bool,
@@ -161,14 +172,17 @@ async def _send_glm_request(
# overridable seam.
-async def send_glm_anthropic_messages(
+async def send_inference_anthropic_messages(
request_data: dict[str, Any],
user: AuthenticatedUser,
is_streaming: bool,
product: str,
) -> dict[str, Any] | StreamingResponse:
- return await _send_glm_request(
- normalize_glm_anthropic_request(request_data, product=product),
+ if request_data["model"] not in BASETEN_EXCLUSIVE_MODELS:
+ request_data = normalize_glm_anthropic_request(request_data, product=product)
+
+ return await _send_inference_request(
+ request_data,
user,
is_streaming,
product,
@@ -181,13 +195,13 @@ async def send_glm_anthropic_messages(
)
-async def send_glm_chat_completions(
+async def send_inference_chat_completions(
request_data: dict[str, Any],
user: AuthenticatedUser,
is_streaming: bool,
product: str,
) -> dict[str, Any] | StreamingResponse:
- return await _send_glm_request(
+ return await _send_inference_request(
request_data,
user,
is_streaming,
@@ -201,13 +215,13 @@ async def send_glm_chat_completions(
)
-async def send_glm_responses(
+async def send_inference_responses(
request_data: dict[str, Any],
user: AuthenticatedUser,
is_streaming: bool,
product: str,
) -> dict[str, Any] | StreamingResponse:
- return await _send_glm_request(
+ return await _send_inference_request(
request_data,
user,
is_streaming,
diff --git a/services/llm-gateway/src/llm_gateway/products/config.py b/services/llm-gateway/src/llm_gateway/products/config.py
index f086b9541074..4207ca6c5440 100644
--- a/services/llm-gateway/src/llm_gateway/products/config.py
+++ b/services/llm-gateway/src/llm_gateway/products/config.py
@@ -6,6 +6,7 @@ from typing import Final
from fastapi import HTTPException
+from llm_gateway.baseten import BASETEN_DEEPSEEK_PUBLIC_MODEL
from llm_gateway.bedrock import BEDROCK_MODEL_IDS, get_bedrock_model_access_candidates, get_bedrock_region_name
from llm_gateway.config import get_settings
@@ -103,6 +104,15 @@ UNCONDITIONAL_SERVER_CREDENTIAL_PRODUCTS: Final[frozenset[str]] = frozenset(
}
)
+# Models reserved for specific products must stay restricted even when a product otherwise allows
+# every model (`allowed_models=None`). This is an authorization boundary, not merely a
+# model-registry advertising filter; the registry also derives its advertising from it so the two
+# can't drift. Keys must be lowercase.
+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"}),
+}
+
PRODUCTS: Final[dict[str, ProductConfig]] = {
"llm_gateway": ProductConfig(
allowed_application_ids=None,
@@ -119,7 +129,7 @@ PRODUCTS: Final[dict[str, ProductConfig]] = {
),
"posthog_code": ProductConfig(
allowed_application_ids=frozenset({POSTHOG_CODE_US_APP_ID, POSTHOG_CODE_EU_APP_ID, POSTHOG_CODE_DEV_APP_ID}),
- allowed_models=_POSTHOG_CODE_AGENT_MODELS | BEDROCK_MODELS,
+ allowed_models=_POSTHOG_CODE_AGENT_MODELS | {BASETEN_DEEPSEEK_PUBLIC_MODEL} | BEDROCK_MODELS,
allow_api_keys=False,
# Bills as posthog_code credits (pass-through model costs, no markup) — see
# get_teams_with_posthog_code_credits_used_in_period in posthog/tasks/usage_report.py.
@@ -247,10 +257,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 (evaluated as reviewer).
+ # GLM 5.2 and DeepSeek V4 Flash (evaluated as reviewers).
allowed_models=frozenset(
{
"@cf/zai-org/glm-5.2",
+ "deepseek-ai/deepseek-v4-flash-0731",
"claude-sonnet-5",
"claude-opus-4-8",
"claude-opus-5",
@@ -440,6 +451,12 @@ def filter_to_free_tier_models(model_ids: list[str]) -> list[str]:
return [m for m in model_ids if _model_matches_product_allowlist(m, free_models, settings=settings)]
+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())
+ return allowed_products is not None and resolve_product_alias(product) not in allowed_products
+
+
def check_product_access(
product: str,
auth_method: str,
@@ -485,6 +502,9 @@ def check_product_access(
):
return False, f"Product '{product}' requires a server-minted credential"
+ if model and is_model_restricted_for_product(model, resolved_product):
+ return False, f"Model '{model}' not allowed for product '{product}'"
+
if model and config.allowed_models is not None:
if not _model_matches_product_allowlist(
model, config.allowed_models, provider=provider, settings=settings, exact=config.exact_model_match
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.py
index 855b624f7469..3cd6a2fbd68b 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,7 @@ import structlog
from litellm import model_cost_map_url
from litellm.litellm_core_utils.get_model_cost_map import get_model_cost_map
-from llm_gateway.baseten import BASETEN_METRIC_MODEL
+from llm_gateway.baseten import BASETEN_DEEPSEEK_METRIC_MODEL, BASETEN_DEEPSEEK_MODEL, BASETEN_METRIC_MODEL
from llm_gateway.rate_limiting.model_cost_overrides import apply_model_cost_overrides
logger = structlog.get_logger(__name__)
@@ -28,6 +28,7 @@ COST_ALIASES: dict[str, tuple[str, str]] = {
# up against Modal's GPU-time invoices.
"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"),
"openai/moonshotai/kimi-k3": ("moonshotai/kimi-k3", "openai"),
}
@@ -39,6 +40,7 @@ ALIAS_METRIC_LABELS: dict[str, tuple[str, str]] = {
# 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", BASETEN_METRIC_MODEL),
+ f"openai/{BASETEN_DEEPSEEK_MODEL}": ("baseten", BASETEN_DEEPSEEK_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.py
index 11a00c5fbcde..d9f1cfebfac1 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 annotations
from typing import TYPE_CHECKING, Final, cast
-from llm_gateway.baseten import BASETEN_METRIC_MODEL
+from llm_gateway.baseten import BASETEN_DEEPSEEK_METRIC_MODEL, BASETEN_METRIC_MODEL
if TYPE_CHECKING:
from llm_gateway.rate_limiting.model_cost_service import ModelCost
@@ -33,8 +33,18 @@ BASETEN_GLM_COST: Final[ModelCost] = {
"supports_prompt_caching": True,
}
+BASETEN_DEEPSEEK_COST: Final[ModelCost] = {
+ "litellm_provider": "baseten",
+ "mode": "chat",
+ "input_cost_per_token": 1.3e-07,
+ "output_cost_per_token": 2.6e-07,
+ "cache_read_input_token_cost": 2.8e-08,
+ "supports_prompt_caching": True,
+}
+
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)),
"moonshotai/kimi-k3": cast("ModelCost", dict(KIMI_K3_COST)),
"claude-fable-5": {
"litellm_provider": "anthropic",
@@ -88,7 +98,7 @@ 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})
+PINNED_MODEL_COST_OVERRIDES: Final[frozenset[str]] = frozenset({BASETEN_METRIC_MODEL, BASETEN_DEEPSEEK_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.py
index b1ad827dbb3e..12b0542aa218 100644
--- a/services/llm-gateway/src/llm_gateway/services/model_registry.py
+++ b/services/llm-gateway/src/llm_gateway/services/model_registry.py
@@ -4,6 +4,7 @@ import os
from dataclasses import dataclass
from typing import ClassVar, Final
+from llm_gateway.baseten import BASETEN_EXCLUSIVE_MODELS, is_baseten_configured
from llm_gateway.cloudflare import CLOUDFLARE_ALLOWED_MODELS, is_cloudflare_configured
from llm_gateway.config import get_settings
from llm_gateway.modal import (
@@ -12,7 +13,7 @@ from llm_gateway.modal import (
is_modal_configured,
is_modal_model_configured,
)
-from llm_gateway.products.config import get_product_config
+from llm_gateway.products.config import get_product_config, is_model_restricted_for_product
from llm_gateway.rate_limiting.cost_refresh import COST_ALIASES
from llm_gateway.rate_limiting.model_cost_service import ModelCost, ModelCostService
@@ -23,6 +24,7 @@ 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
@dataclass(frozen=True)
@@ -159,6 +161,20 @@ class ModelRegistryService:
model = self.get_model(model_id)
if model is not None:
models.append(model)
+ for model_id in BASETEN_EXCLUSIVE_MODELS:
+ if is_model_restricted_for_product(model_id, product) or not is_baseten_configured(get_settings()):
+ continue
+ if allowed_models is not None and not _model_matches_allowlist(model_id, allowed_models):
+ continue
+ models.append(
+ ModelInfo(
+ id=model_id,
+ provider="baseten",
+ context_window=_BASETEN_DEFAULT_CONTEXT_WINDOW,
+ supports_streaming=True,
+ supports_vision=False,
+ )
+ )
return models
def is_model_available(self, model_id: str, product: str) -> bool:
@@ -178,6 +194,9 @@ class ModelRegistryService:
if _model_matches_allowlist(model_id, MODAL_ALLOWED_MODELS):
return is_modal_model_configured(model_id, get_settings())
+ if model_id in BASETEN_EXCLUSIVE_MODELS:
+ return not is_model_restricted_for_product(model_id, product) and is_baseten_configured(get_settings())
+
model = self.get_model(model_id)
if model is None:
return False
diff --git a/services/llm-gateway/tests/test_anthropic.py b/services/llm-gateway/tests/test_anthropic.py
index d93dd6b003c3..498c3034bce0 100644
--- a/services/llm-gateway/tests/test_anthropic.py
+++ b/services/llm-gateway/tests/test_anthropic.py
@@ -568,13 +568,13 @@ class TestAnthropicMessagesEndpoint:
mock_response.model_dump = MagicMock(return_value=provider_mock_response)
with patch(
- "llm_gateway.glm_routing.make_cloudflare_anthropic_call",
+ "llm_gateway.inference_routing.make_cloudflare_anthropic_call",
) as mock_make_call:
mock_llm_call = AsyncMock(return_value=mock_response)
mock_make_call.return_value = mock_llm_call
with patch(
- "llm_gateway.glm_routing.ensure_cloudflare_configured",
+ "llm_gateway.inference_routing.ensure_cloudflare_configured",
return_value=("https://api.cloudflare.com/ai/v1", "test-key"),
):
response = authenticated_client.post(
@@ -607,10 +607,10 @@ class TestAnthropicMessagesEndpoint:
mock_response = MagicMock()
mock_response.model_dump = MagicMock(return_value=provider_mock_response)
- with patch("llm_gateway.glm_routing.make_cloudflare_anthropic_call") as mock_make_call:
+ with patch("llm_gateway.inference_routing.make_cloudflare_anthropic_call") as mock_make_call:
mock_make_call.return_value = AsyncMock(return_value=mock_response)
with patch(
- "llm_gateway.glm_routing.ensure_cloudflare_configured",
+ "llm_gateway.inference_routing.ensure_cloudflare_configured",
return_value=("https://api.cloudflare.com/ai/v1", "test-key"),
):
response = authenticated_client.post(
@@ -655,12 +655,12 @@ class TestAnthropicMessagesEndpoint:
yield b'event: message_stop\ndata: {"type":"message_stop"}\n\n'
with patch(
- "llm_gateway.glm_routing.make_cloudflare_anthropic_call",
+ "llm_gateway.inference_routing.make_cloudflare_anthropic_call",
) as mock_make_call:
mock_make_call.return_value = AsyncMock(return_value=fake_stream())
with patch(
- "llm_gateway.glm_routing.ensure_cloudflare_configured",
+ "llm_gateway.inference_routing.ensure_cloudflare_configured",
return_value=("https://api.cloudflare.com/ai/v1", "test-key"),
):
with authenticated_client.stream(
@@ -689,8 +689,8 @@ class TestAnthropicMessagesEndpoint:
self,
authenticated_client: TestClient,
) -> None:
- with patch("llm_gateway.glm_routing.ensure_cloudflare_configured") as mock_ensure_configured:
- with patch("llm_gateway.glm_routing.make_cloudflare_anthropic_call") as mock_make_call:
+ with patch("llm_gateway.inference_routing.ensure_cloudflare_configured") as mock_ensure_configured:
+ with patch("llm_gateway.inference_routing.make_cloudflare_anthropic_call") as mock_make_call:
response = authenticated_client.post(
"/v1/messages",
json={
diff --git a/services/llm-gateway/tests/test_baseten.py b/services/llm-gateway/tests/test_baseten.py
index de93c449f7eb..7e3668712eaf 100644
--- a/services/llm-gateway/tests/test_baseten.py
+++ b/services/llm-gateway/tests/test_baseten.py
@@ -5,7 +5,6 @@ import pytest
from fastapi import HTTPException
from llm_gateway.baseten import (
- BASETEN_METRIC_MODEL,
_inject_baseten_params,
ensure_baseten_configured,
make_baseten_responses_call,
@@ -16,27 +15,43 @@ 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"
+DEEPSEEK_MODEL = "deepseek-ai/deepseek-v4-flash-0731"
+BASETEN_DEEPSEEK_LITELLM_MODEL = "openai/deepseek-ai/DeepSeek-V4-Flash-0731"
-def test_inject_baseten_params_maps_model_and_pins_api_key() -> None:
+ ("public_model", "litellm_model", "metric_model", "input_cost", "output_cost", "cache_read_cost"),
+ [
+ (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),
+ ],
+)
+def test_inject_baseten_params_maps_model_and_pins_api_key(
+ public_model: str,
+ litellm_model: str,
+ metric_model: str,
+ input_cost: float,
+ output_cost: float,
+ cache_read_cost: float,
+) -> None:
kwargs: dict[str, Any] = {
- "model": GLM_MODEL,
+ "model": public_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["model"] == litellm_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["extra_headers"] == {"Authorization": "Bearer test-key"}
assert kwargs["drop_params"] is True
- assert COST_ALIASES[BASETEN_MODEL] == (BASETEN_METRIC_MODEL, "openai")
- assert MODEL_COST_OVERRIDES[BASETEN_METRIC_MODEL]["input_cost_per_token"] == 1.4e-06
- assert MODEL_COST_OVERRIDES[BASETEN_METRIC_MODEL]["cache_read_input_token_cost"] == 1.4e-07
- assert MODEL_COST_OVERRIDES[BASETEN_METRIC_MODEL]["output_cost_per_token"] == 4.4e-06
- assert normalize_metric_labels(BASETEN_MODEL, "openai") == ("baseten", "baseten/zai-org/glm-5.2")
+ assert COST_ALIASES[litellm_model] == (metric_model, "openai")
+ assert MODEL_COST_OVERRIDES[metric_model]["input_cost_per_token"] == input_cost
+ assert MODEL_COST_OVERRIDES[metric_model]["cache_read_input_token_cost"] == cache_read_cost
+ assert MODEL_COST_OVERRIDES[metric_model]["output_cost_per_token"] == output_cost
+ assert normalize_metric_labels(litellm_model, "openai") == ("baseten", metric_model)
def test_inject_baseten_params_forces_streaming_usage() -> None:
diff --git a/services/llm-gateway/tests/test_glm_routing.py b/services/llm-gateway/tests/test_inference_routing.py
similarity index 82%
rename from services/llm-gateway/tests/test_glm_routing.py
rename to services/llm-gateway/tests/test_inference_routing.py
index d3f27dbb80ef..2b5c076ae95b 100644
--- a/services/llm-gateway/tests/test_glm_routing.py
+++ b/services/llm-gateway/tests/test_inference_routing.py
@@ -7,22 +7,23 @@ from fastapi import HTTPException
from llm_gateway.api.handler import ProviderError
from llm_gateway.auth.models import AuthenticatedUser
from llm_gateway.config import Settings
-from llm_gateway.glm_routing import (
+from llm_gateway.inference_routing import (
normalize_glm_anthropic_request,
- send_glm_anthropic_messages,
- send_glm_chat_completions,
- send_glm_responses,
+ send_inference_anthropic_messages,
+ send_inference_chat_completions,
+ send_inference_responses,
)
from llm_gateway.request_context import RequestContext, set_request_context
GLM_MODEL = "@cf/zai-org/glm-5.2"
+DEEPSEEK_MODEL = "deepseek-ai/deepseek-v4-flash-0731"
KIMI_MODEL = "@cf/moonshotai/kimi-k2.6"
PRODUCT = "posthog_code"
SURFACES = [
- (send_glm_anthropic_messages, "modal_anthropic_messages", "cloudflare_anthropic_messages"),
- (send_glm_chat_completions, "modal_chat_completions", "cloudflare_chat_completions"),
- (send_glm_responses, "modal_responses", "cloudflare_responses"),
+ (send_inference_anthropic_messages, "modal_anthropic_messages", "cloudflare_anthropic_messages"),
+ (send_inference_chat_completions, "modal_chat_completions", "cloudflare_chat_completions"),
+ (send_inference_responses, "modal_responses", "cloudflare_responses"),
]
@@ -47,15 +48,15 @@ async def _send(
settings: Settings,
handle: AsyncMock,
flag: bool | None = None,
- send_fn: Any = send_glm_anthropic_messages,
+ send_fn: Any = send_inference_anthropic_messages,
product: str = PRODUCT,
request_data: dict[str, Any] | None = None,
) -> tuple[Any, AsyncMock]:
evaluate = AsyncMock(return_value=flag)
with (
- patch("llm_gateway.glm_routing.get_settings", return_value=settings),
- patch("llm_gateway.glm_routing.handle_llm_request", handle),
- patch("llm_gateway.glm_routing.evaluate_flag", evaluate),
+ patch("llm_gateway.inference_routing.get_settings", return_value=settings),
+ patch("llm_gateway.inference_routing.handle_llm_request", handle),
+ patch("llm_gateway.inference_routing.evaluate_flag", evaluate),
):
result = await send_fn(
request_data or {"model": GLM_MODEL, "messages": [{"role": "user", "content": "hi"}]},
@@ -173,6 +174,33 @@ async def test_baseten_flag_routes_each_surface(send_fn: Any, endpoint: str) ->
evaluate.assert_awaited_once_with("tasks-glm-baseten-inference", "d-1")
+ ("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:
+ handle = AsyncMock(return_value={"ok": True})
+ request = {"model": DEEPSEEK_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
+ evaluate.assert_not_called()
+
+
+async def test_deepseek_does_not_apply_glm_anthropic_normalization() -> None:
+ handle = AsyncMock(return_value={"ok": True})
+ request = {
+ "model": DEEPSEEK_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
+
+
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_registry.py b/services/llm-gateway/tests/test_model_registry.py
index fc40e7cacb4f..916bc7434969 100644
--- a/services/llm-gateway/tests/test_model_registry.py
+++ b/services/llm-gateway/tests/test_model_registry.py
@@ -136,6 +136,7 @@ def create_mock_settings(
fireworks: bool = False,
cloudflare: bool = False,
modal: bool = False,
+ baseten: bool = False,
) -> MagicMock:
settings = MagicMock()
settings.openai_api_key = "sk-test" if openai else None
@@ -151,6 +152,8 @@ def create_mock_settings(
settings.modal_kimi_api_base = "https://kimi.modal.test/v1" if modal else None
settings.modal_key = "wk-test" if modal else None
settings.modal_secret = "ws-test" if modal else None
+ settings.baseten_api_base = "https://baseten.test/v1" if baseten else None
+ settings.baseten_api_key = "baseten-test" if baseten else None
return settings
@@ -377,6 +380,25 @@ class TestCloudflareModelAdvertising:
assert self._cf_ids("llm_gateway") == {"@cf/zai-org/glm-5.2"}
+class TestBasetenModelAdvertising:
+ def test_deepseek_is_available_to_code_and_review_hog(self):
+ 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"):
+ model = next(
+ model
+ for model in ModelRegistryService.get_instance().get_available_models(product)
+ if model.id == "deepseek-ai/deepseek-v4-flash-0731"
+ )
+ assert model.context_window == 1_048_000
+
+
class TestModelMatchesAllowlist:
@pytest.mark.parametrize(
"model_id,expected",
diff --git a/services/llm-gateway/tests/test_openai.py b/services/llm-gateway/tests/test_openai.py
index 1a3db7cdaf8d..5af7ca16e226 100644
--- a/services/llm-gateway/tests/test_openai.py
+++ b/services/llm-gateway/tests/test_openai.py
@@ -280,8 +280,8 @@ class TestChatCompletionsEndpoint:
assert forwarded_metadata["nested"]["keep"] == "ok"
@patch("llm_gateway.api.openai.litellm.acompletion")
- @patch("llm_gateway.glm_routing.make_cloudflare_completion_call")
- @patch("llm_gateway.glm_routing.ensure_cloudflare_configured")
+ @patch("llm_gateway.inference_routing.make_cloudflare_completion_call")
+ @patch("llm_gateway.inference_routing.ensure_cloudflare_configured")
def test_cf_model_routes_through_cloudflare(
self,
mock_ensure_configured: MagicMock,
@@ -309,8 +309,8 @@ class TestChatCompletionsEndpoint:
mock_acompletion.assert_not_called()
@patch("llm_gateway.api.openai.litellm.acompletion")
- @patch("llm_gateway.glm_routing.make_cloudflare_completion_call")
- @patch("llm_gateway.glm_routing.ensure_cloudflare_configured")
+ @patch("llm_gateway.inference_routing.make_cloudflare_completion_call")
+ @patch("llm_gateway.inference_routing.ensure_cloudflare_configured")
def test_cf_model_streams_through_cloudflare(
self,
mock_ensure_configured: MagicMock,
@@ -351,8 +351,8 @@ class TestChatCompletionsEndpoint:
mock_make_call.assert_called_once_with("https://api.cloudflare.com/ai/v1", "test-key")
mock_acompletion.assert_not_called()
- @patch("llm_gateway.glm_routing.make_cloudflare_completion_call")
- @patch("llm_gateway.glm_routing.ensure_cloudflare_configured")
+ @patch("llm_gateway.inference_routing.make_cloudflare_completion_call")
+ @patch("llm_gateway.inference_routing.ensure_cloudflare_configured")
def test_unpriced_cf_model_rejected_before_routing(
self,
mock_ensure_configured: MagicMock,
@@ -383,8 +383,8 @@ class TestChatCompletionsEndpoint:
# zero generations.
class TestResponsesRoutedModels:
@patch("llm_gateway.api.openai.litellm.aresponses")
- @patch("llm_gateway.glm_routing.make_cloudflare_responses_call")
- @patch("llm_gateway.glm_routing.ensure_cloudflare_configured")
+ @patch("llm_gateway.inference_routing.make_cloudflare_responses_call")
+ @patch("llm_gateway.inference_routing.ensure_cloudflare_configured")
def test_cf_model_routes_through_cloudflare(
self,
mock_ensure_configured: MagicMock,
@@ -437,8 +437,8 @@ class TestResponsesRoutedModels:
mock_aresponses.assert_not_called()
@patch("llm_gateway.api.openai.litellm.aresponses")
- @patch("llm_gateway.glm_routing.make_cloudflare_responses_call")
- @patch("llm_gateway.glm_routing.ensure_cloudflare_configured")
+ @patch("llm_gateway.inference_routing.make_cloudflare_responses_call")
+ @patch("llm_gateway.inference_routing.ensure_cloudflare_configured")
def test_cf_model_streams_through_cloudflare(
self,
mock_ensure_configured: MagicMock,
@@ -477,8 +477,8 @@ class TestResponsesRoutedModels:
mock_make_call.assert_called_once_with("https://api.cloudflare.com/ai/v1", "test-key")
mock_aresponses.assert_not_called()
- @patch("llm_gateway.glm_routing.make_cloudflare_responses_call")
- @patch("llm_gateway.glm_routing.ensure_cloudflare_configured")
+ @patch("llm_gateway.inference_routing.make_cloudflare_responses_call")
+ @patch("llm_gateway.inference_routing.ensure_cloudflare_configured")
def test_unpriced_cf_model_rejected_before_routing(
self,
mock_ensure_configured: MagicMock,
@@ -502,8 +502,8 @@ class TestResponsesRoutedModels:
mock_ensure_configured.assert_not_called()
mock_make_call.assert_not_called()
- @patch("llm_gateway.glm_routing.make_cloudflare_responses_call")
- @patch("llm_gateway.glm_routing.ensure_cloudflare_configured")
+ @patch("llm_gateway.inference_routing.make_cloudflare_responses_call")
+ @patch("llm_gateway.inference_routing.ensure_cloudflare_configured")
def test_previous_response_id_rejected_for_cf_model(
self,
mock_ensure_configured: MagicMock,
@@ -530,8 +530,8 @@ class TestResponsesRoutedModels:
mock_ensure_configured.assert_not_called()
mock_make_call.assert_not_called()
- @patch("llm_gateway.glm_routing.make_cloudflare_responses_call")
- @patch("llm_gateway.glm_routing.ensure_cloudflare_configured")
+ @patch("llm_gateway.inference_routing.make_cloudflare_responses_call")
+ @patch("llm_gateway.inference_routing.ensure_cloudflare_configured")
def test_tools_rejected_for_cf_model(
self,
mock_ensure_configured: MagicMock,
diff --git a/services/llm-gateway/tests/test_product_config.py b/services/llm-gateway/tests/test_product_config.py
index 8a7b65dbbcaf..4e1e4a8a60be 100644
--- a/services/llm-gateway/tests/test_product_config.py
+++ b/services/llm-gateway/tests/test_product_config.py
@@ -46,6 +46,22 @@ class TestCheckProductAccess:
("llm_gateway", "personal_api_key", None, "claude-3-opus", True, None),
("llm_gateway", "oauth_access_token", "any-app-id", "gpt-4o", False, "not authorized"),
("llm_gateway", "personal_api_key", None, None, True, None),
+ (
+ "llm_gateway",
+ "personal_api_key",
+ None,
+ "deepseek-ai/deepseek-v4-flash-0731",
+ False,
+ "not allowed",
+ ),
+ (
+ "review_hog",
+ "personal_api_key",
+ None,
+ "deepseek-ai/deepseek-v4-flash-0731",
+ 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"),
@@ -54,6 +70,14 @@ class TestCheckProductAccess:
("posthog_code", "oauth_access_token", "invalid-app-id", None, False, "not authorized"),
("posthog_code", "oauth_access_token", POSTHOG_CODE_US_APP_ID, None, True, None),
("posthog_code", "oauth_access_token", POSTHOG_CODE_EU_APP_ID, None, True, None),
+ (
+ "posthog_code",
+ "oauth_access_token",
+ POSTHOG_CODE_US_APP_ID,
+ "deepseek-ai/deepseek-v4-flash-0731",
+ True,
+ None,
+ ),
# wizard allows API keys and OAuth with valid app ID
("wizard", "personal_api_key", None, "claude-3-opus", True, None),
("wizard", "oauth_access_token", "invalid-app-id", None, False, "not authorized"),
@@ -157,6 +181,7 @@ class TestCheckProductAccess:
"gpt-5.3-codex",
"gpt-5.2",
"gpt-5-mini",
+ "deepseek-ai/deepseek-v4-flash-0731",
],
)
def test_posthog_code_allows_restricted_models_with_valid_app_id(self, model: str):
@@ -164,6 +189,14 @@ class TestCheckProductAccess:
assert allowed is True
assert 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"
+ )
+ assert allowed is False
+ assert error is not None
+ assert "not allowed" in error
+
@pytest.mark.parametrize(
"model",
[