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 modal backend for glm with weighted routing (#71860)

Alessandro Pogliaghifabff88af2d2
diff --git a/services/llm-gateway/README.md b/services/llm-gateway/README.md
index b79fc85be07b..013e8d51e06c 100644
--- a/services/llm-gateway/README.md
+++ b/services/llm-gateway/README.md
@@ -200,6 +200,24 @@ 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 (Cloudflare and Modal)
+
+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`:
+
+- **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).
+
+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.
+- `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.
+
+There are no cross-backend retries: a Modal-side failure surfaces to the caller unchanged (each backend's health stays independently visible under its `provider` metric label), and rollback is turning the flag/fraction back down.
+Smoke scripts: `scripts/glm_cf_smoke.py` (Cloudflare) and `scripts/glm_modal_smoke.py` (Modal).
+
## Products
Every request is scoped to a **product**. The product determines which models and auth methods are allowed, and is recorded as `ai_product` on `$ai_generation` events so you can filter costs per product.
diff --git a/services/llm-gateway/scripts/glm_modal_smoke.py b/services/llm-gateway/scripts/glm_modal_smoke.py
new file mode 100644
index 000000000000..c83e3a903991
--- /dev/null
+++ b/services/llm-gateway/scripts/glm_modal_smoke.py
@@ -0,0 +1,76 @@
+"""Smoke test: call GLM-5.2 on a Modal vLLM endpoint through the gateway's own Modal
+anthropic-messages adapter — the exact code path a cloud-task agent on the claude runtime
+uses. Proves Modal proxy-token auth + routing + Anthropic<->OpenAI tool translation, the
+Modal analogue of glm_cf_smoke.py.
+
+Run from services/llm-gateway:
+ .venv/bin/python scripts/glm_modal_smoke.py
+
+Reads LLM_GATEWAY_MODAL_API_BASE / LLM_GATEWAY_MODAL_KEY / LLM_GATEWAY_MODAL_SECRET from the
+repo .env (create the token pair with `modal workspace proxy-tokens create`).
+"""
+
+import asyncio
+import sys
+
+from dotenv import load_dotenv
+from fastapi import HTTPException
+
+from llm_gateway.config import Settings
+from llm_gateway.modal import (
+ MODAL_ALLOWED_MODELS,
+ ensure_modal_configured,
+ make_modal_anthropic_call,
+)
+
+GLM_MODEL = "@cf/zai-org/glm-5.2"
+
+
+async def main() -> None:
+ assert GLM_MODEL in MODAL_ALLOWED_MODELS, f"{GLM_MODEL} not in allowlist"
+ # Settings has no env_file, so load the repo .env into the environment first (as benchmark.py does).
+ load_dotenv()
+ try:
+ api_base, modal_key, modal_secret = ensure_modal_configured(Settings())
+ except HTTPException:
+ sys.exit("Missing LLM_GATEWAY_MODAL_API_BASE / LLM_GATEWAY_MODAL_KEY / LLM_GATEWAY_MODAL_SECRET")
+ print(f"api_base: {api_base}")
+
+ llm_call = make_modal_anthropic_call(api_base, modal_key, modal_secret)
+
+ # Anthropic Messages request WITH a tool — tool translation through litellm's adapter is the
+ # part most likely to differ between backends, so it's the qualification gate for the ramp.
+ response = await llm_call(
+ model=GLM_MODEL,
+ max_tokens=256,
+ messages=[{"role": "user", "content": "What's the weather in Paris? Use the tool."}],
+ tools=[
+ {
+ "name": "get_weather",
+ "description": "Get the current weather for a city",
+ "input_schema": {
+ "type": "object",
+ "properties": {"city": {"type": "string"}},
+ "required": ["city"],
+ },
+ }
+ ],
+ )
+
+ print("\n=== raw response ===")
+ print(response)
+
+ content = getattr(response, "content", None) or (response.get("content") if isinstance(response, dict) else None)
+ print("\n=== content blocks ===")
+ used_tool = False
+ for block in content or []:
+ btype = getattr(block, "type", None) or (block.get("type") if isinstance(block, dict) else None)
+ print(f"- {btype}: {block}")
+ if btype == "tool_use":
+ used_tool = True
+
+ print(f"\nRESULT: GLM-5.2 via Modal responded; tool_use emitted = {used_tool}")
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/services/llm-gateway/src/llm_gateway/api/anthropic.py b/services/llm-gateway/src/llm_gateway/api/anthropic.py
index 84c8a0b88bfb..68cd51f6f575 100644
--- a/services/llm-gateway/src/llm_gateway/api/anthropic.py
+++ b/services/llm-gateway/src/llm_gateway/api/anthropic.py
@@ -14,7 +14,6 @@ from fastapi.responses import StreamingResponse
from llm_gateway.api.handler import (
ANTHROPIC_CONFIG,
BEDROCK_CONFIG,
- CLOUDFLARE_ANTHROPIC_CONFIG,
ProviderError,
_sanitize_request_data,
handle_llm_request,
@@ -30,13 +29,12 @@ from llm_gateway.bedrock import (
from llm_gateway.circuit_breaker import AnthropicCircuitBreaker
from llm_gateway.cloudflare import (
cloudflare_litellm_model,
- ensure_cloudflare_configured,
ensure_cloudflare_model_allowed,
is_cloudflare_model,
- make_cloudflare_anthropic_call,
)
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.metrics.prometheus import (
ANTHROPIC_CIRCUIT_BREAKER_BYPASSED,
BEDROCK_COUNT_TOKENS_ERRORS,
@@ -357,31 +355,6 @@ def reconcile_tool_choice(data: dict[str, Any], *, model: str, product: str) ->
BEDROCK_PARAM_STRIPPED.labels(param="tool_choice", product=product).inc()
-async def _send_cloudflare_messages(
- request_data: dict[str, Any],
- user: RateLimitedUser,
- is_streaming: bool,
- product: str,
-) -> dict[str, Any] | StreamingResponse:
- ensure_cloudflare_model_allowed(request_data["model"])
- settings = get_settings()
- api_base, api_key = ensure_cloudflare_configured(settings)
-
- data = dict(request_data)
- original_model = data["model"]
- llm_call = make_cloudflare_anthropic_call(api_base, api_key)
-
- return await handle_llm_request(
- request_data=data,
- user=user,
- model=original_model,
- is_streaming=is_streaming,
- provider_config=CLOUDFLARE_ANTHROPIC_CONFIG,
- llm_call=llm_call,
- product=product,
- )
-
-
async def _send_bedrock_messages(
request_data: dict[str, Any],
user: RateLimitedUser,
@@ -549,15 +522,16 @@ async def _handle_anthropic_messages(
provider = _get_provider_from_headers(request)
use_bedrock_fallback = _get_use_bedrock_fallback_from_headers(request)
- # `@cf/` models are Cloudflare-only, so route them to CF 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 CF route serves tools fine: litellm's Anthropic->chat/completions adapter
- # translates Anthropic tools into OpenAI function tools that CF's endpoint accepts.
+ # `@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_cloudflare_messages(data, user, body.stream or False, product)
+ return await send_glm_anthropic_messages(data, user, body.stream or False, product)
if provider == "bedrock":
return await _send_bedrock_messages(data, user, request, body.stream or False, product)
diff --git a/services/llm-gateway/src/llm_gateway/api/handler.py b/services/llm-gateway/src/llm_gateway/api/handler.py
index 549db3912b5a..0ed41589e107 100644
--- a/services/llm-gateway/src/llm_gateway/api/handler.py
+++ b/services/llm-gateway/src/llm_gateway/api/handler.py
@@ -113,6 +113,23 @@ CLOUDFLARE_OPENAI_RESPONSES_CONFIG = ProviderConfig(
endpoint_name="cloudflare_responses",
extract_effort=effort_from_reasoning,
)
+# Modal-served GLM (OpenAI-compatible vLLM endpoint). Same per-surface split as Cloudflare so a
+# Modal-specific regression is distinguishable in metrics during the migration.
+MODAL_ANTHROPIC_CONFIG = ProviderConfig(
+ name="modal",
+ endpoint_name="modal_anthropic_messages",
+ extract_effort=effort_from_output_config,
+)
+MODAL_OPENAI_CONFIG = ProviderConfig(
+ name="modal",
+ endpoint_name="modal_chat_completions",
+ extract_effort=effort_from_reasoning_effort,
+)
+MODAL_OPENAI_RESPONSES_CONFIG = ProviderConfig(
+ name="modal",
+ endpoint_name="modal_responses",
+ extract_effort=effort_from_reasoning,
+)
_KNOWN_LITELLM_PROVIDER_PREFIXES = (
"anthropic/",
diff --git a/services/llm-gateway/src/llm_gateway/api/openai.py b/services/llm-gateway/src/llm_gateway/api/openai.py
index 102666f4c27f..74ab7a142ea3 100644
--- a/services/llm-gateway/src/llm_gateway/api/openai.py
+++ b/services/llm-gateway/src/llm_gateway/api/openai.py
@@ -5,23 +5,15 @@ from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFile
from fastapi.responses import StreamingResponse
from llm_gateway.api.handler import (
- CLOUDFLARE_OPENAI_CONFIG,
- CLOUDFLARE_OPENAI_RESPONSES_CONFIG,
OPENAI_CONFIG,
OPENAI_RESPONSES_CONFIG,
OPENAI_TRANSCRIPTION_CONFIG,
handle_llm_request,
normalize_litellm_model_name,
)
-from llm_gateway.cloudflare import (
- ensure_cloudflare_configured,
- ensure_cloudflare_model_allowed,
- is_cloudflare_model,
- make_cloudflare_completion_call,
- make_cloudflare_responses_call,
-)
-from llm_gateway.config import get_settings
+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.models.openai import ChatCompletionRequest, ResponsesRequest, TranscriptionRequest
from llm_gateway.products.config import validate_product
from llm_gateway.request_context import apply_posthog_context_from_headers
@@ -45,18 +37,7 @@ async def _handle_chat_completions(
data = body.model_dump(exclude_none=True)
if is_cloudflare_model(body.model):
- ensure_cloudflare_model_allowed(body.model)
- settings = get_settings()
- api_base, api_key = ensure_cloudflare_configured(settings)
- return await handle_llm_request(
- request_data=data,
- user=user,
- model=body.model,
- is_streaming=body.stream or False,
- provider_config=CLOUDFLARE_OPENAI_CONFIG,
- llm_call=make_cloudflare_completion_call(api_base, api_key),
- product=product,
- )
+ return await send_glm_chat_completions(data, user, body.stream or False, product)
return await handle_llm_request(
request_data=data,
@@ -82,9 +63,10 @@ async def _handle_responses(
data = body.model_dump(exclude_none=True)
if is_cloudflare_model(body.model):
- # CF-served models (`@cf/...`) can't use the native OpenAI Responses path below: it would
- # prefix `openai/` and call the real OpenAI Responses API. Route through CF's endpoint via
- # litellm's Responses->chat/completions bridge instead (see make_cloudflare_responses_call).
+ # `@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 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
@@ -96,22 +78,11 @@ async def _handle_responses(
# `tools` arrives as an extra field (ResponsesRequest allows extras). The
# Responses->chat/completions bridge doesn't faithfully translate Responses-shaped
# tools: Responses-only types (`shell`, `custom`) pass through unchanged and
- # chat-completions-shaped function tools lose their name, so CF's chat/completions
- # endpoint rejects the payload. Reject up front rather than hand CF a request that
- # will fail once tools are advertised.
+ # 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")
- ensure_cloudflare_model_allowed(body.model)
- settings = get_settings()
- api_base, api_key = ensure_cloudflare_configured(settings)
- return await handle_llm_request(
- request_data=data,
- user=user,
- model=body.model,
- is_streaming=body.stream or False,
- provider_config=CLOUDFLARE_OPENAI_RESPONSES_CONFIG,
- llm_call=make_cloudflare_responses_call(api_base, api_key),
- product=product,
- )
+ return await send_glm_responses(data, user, body.stream or False, product)
original_model = body.model
normalized_model = normalize_litellm_model_name(original_model, OPENAI_RESPONSES_CONFIG.name)
diff --git a/services/llm-gateway/src/llm_gateway/config.py b/services/llm-gateway/src/llm_gateway/config.py
index e46fe0151cac..568e663c7bd3 100644
--- a/services/llm-gateway/src/llm_gateway/config.py
+++ b/services/llm-gateway/src/llm_gateway/config.py
@@ -149,6 +149,17 @@ class Settings(BaseSettings):
cloudflare_api_key: str | None = None
cloudflare_account_id: 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.
+ modal_api_base: str | None = None
+ modal_key: str | None = None
+ modal_secret: str | None = None
+
+ # User-sticky fraction (0..1) of GLM traffic served by Modal; per-product entries override the
+ # global value. The tasks-glm-modal-inference flag ORs with this.
+ glm_modal_traffic_fraction: float = 0.0
+ glm_modal_product_traffic_fractions: dict[str, float] = {}
+
# Project token for AI observability events
posthog_project_token: str | None = None
posthog_host: str = "https://us.i.posthog.com"
@@ -216,6 +227,38 @@ class Settings(BaseSettings):
def parse_user_cost_limits(cls, v: str | dict | None) -> dict[str, UserCostLimit]:
return _parse_model_dict(v, UserCostLimit, DEFAULT_USER_COST_LIMITS, "user_cost_limits")
+ @field_validator("glm_modal_traffic_fraction")
+ @classmethod
+ def validate_glm_modal_traffic_fraction(cls, v: float) -> float:
+ if not 0.0 <= v <= 1.0:
+ raise ValueError(f"glm_modal_traffic_fraction must be between 0 and 1, got {v}")
+ return v
+
+ @field_validator("glm_modal_product_traffic_fractions", mode="before")
+ @classmethod
+ def parse_glm_modal_product_traffic_fractions(cls, v: str | dict[str, float] | None) -> dict[str, float]:
+ if v is None or v == "":
+ return {}
+ if isinstance(v, str):
+ try:
+ v = json.loads(v)
+ except json.JSONDecodeError as e:
+ raise ValueError(f"Invalid JSON in glm_modal_product_traffic_fractions: {e}") from e
+ if not isinstance(v, dict):
+ raise ValueError("glm_modal_product_traffic_fractions must be a JSON object")
+ result: dict[str, float] = {}
+ for product, fraction in v.items():
+ try:
+ value = float(fraction)
+ except (TypeError, ValueError) as e:
+ raise ValueError(f"glm_modal_product_traffic_fractions values must be numbers: {e}") from e
+ if not 0.0 <= value <= 1.0:
+ raise ValueError(
+ f"glm_modal_product_traffic_fractions values must be between 0 and 1, got {value} for {product}"
+ )
+ result[_normalize_cost_key(str(product))] = value
+ return result
+
@field_validator("staff_rate_limit_multiplier")
@classmethod
def validate_staff_rate_limit_multiplier(cls, v: int) -> int:
diff --git a/services/llm-gateway/src/llm_gateway/flags.py b/services/llm-gateway/src/llm_gateway/flags.py
new file mode 100644
index 000000000000..2bee590f4b08
--- /dev/null
+++ b/services/llm-gateway/src/llm_gateway/flags.py
@@ -0,0 +1,60 @@
+from __future__ import annotations
+
+import asyncio
+
+import structlog
+from cachetools import TTLCache
+from posthoganalytics import Posthog
+
+from llm_gateway.config import get_settings
+
+logger = structlog.get_logger(__name__)
+
+GLM_MODAL_FLAG = "tasks-glm-modal-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.
+_flag_unavailable_cache: TTLCache[str, bool] = TTLCache(maxsize=100, ttl=5)
+_client: Posthog | None = None
+
+
+def _get_client() -> Posthog | None:
+ global _client
+ settings = get_settings()
+ if not settings.posthog_project_token:
+ return None
+ if _client is None:
+ _client = Posthog(
+ settings.posthog_project_token,
+ host=settings.posthog_host,
+ sync_mode=True,
+ enable_local_evaluation=False,
+ feature_flags_request_timeout_seconds=2,
+ )
+ return _client
+
+
+async def evaluate_flag(flag_key: str, distinct_id: str) -> bool | None:
+ """None when evaluation is unavailable — callers fall back to their own default."""
+ cache_key = (flag_key, distinct_id)
+ if cache_key in _flag_cache:
+ return _flag_cache[cache_key]
+ if flag_key in _flag_unavailable_cache:
+ return None
+ client = _get_client()
+ if client is None:
+ return None
+ try:
+ # Blocking /flags roundtrip — keep it off the event loop. send_feature_flag_events=False:
+ # with sync_mode the default would also block on a $feature_flag_called capture upload
+ # (15s SDK timeout) for every uncached user.
+ enabled = await asyncio.to_thread(client.feature_enabled, flag_key, distinct_id, send_feature_flag_events=False)
+ except Exception as exc:
+ logger.warning("flag_evaluation_failed", flag=flag_key, error=str(exc))
+ _flag_unavailable_cache[flag_key] = True
+ return None
+ if enabled is None:
+ _flag_unavailable_cache[flag_key] = True
+ return None
+ _flag_cache[cache_key] = bool(enabled)
+ return bool(enabled)
diff --git a/services/llm-gateway/src/llm_gateway/glm_routing.py b/services/llm-gateway/src/llm_gateway/glm_routing.py
new file mode 100644
index 000000000000..a08c8d0bf9b9
--- /dev/null
+++ b/services/llm-gateway/src/llm_gateway/glm_routing.py
@@ -0,0 +1,187 @@
+"""Backend selection for GLM (`@cf/...`) traffic during the Cloudflare -> Modal migration.
+
+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.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Awaitable, Callable
+from typing import Any
+
+from fastapi.responses import StreamingResponse
+
+from llm_gateway.api.handler import (
+ CLOUDFLARE_ANTHROPIC_CONFIG,
+ CLOUDFLARE_OPENAI_CONFIG,
+ CLOUDFLARE_OPENAI_RESPONSES_CONFIG,
+ MODAL_ANTHROPIC_CONFIG,
+ MODAL_OPENAI_CONFIG,
+ MODAL_OPENAI_RESPONSES_CONFIG,
+ ProviderConfig,
+ handle_llm_request,
+)
+from llm_gateway.auth.models import AuthenticatedUser
+from llm_gateway.cloudflare import (
+ ensure_cloudflare_configured,
+ ensure_cloudflare_model_allowed,
+ is_cloudflare_configured,
+ make_cloudflare_anthropic_call,
+ make_cloudflare_completion_call,
+ 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.modal import (
+ ensure_modal_configured,
+ ensure_modal_model_allowed,
+ is_modal_configured,
+ is_modal_served_model,
+ make_modal_anthropic_call,
+ make_modal_completion_call,
+ make_modal_responses_call,
+ should_route_glm_to_modal,
+)
+
+LlmCall = Callable[..., Awaitable[Any]]
+
+
+async def _route_to_modal(model: str, user: AuthenticatedUser, product: str, settings: Settings) -> bool:
+ if not is_modal_served_model(model) or not is_modal_configured(settings):
+ return False
+ # Modal is the only configured backend — don't route to a Cloudflare 503.
+ if not is_cloudflare_configured(settings):
+ return True
+ if 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(
+ 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 handle_llm_request(
+ request_data=dict(request_data),
+ user=user,
+ model=model,
+ is_streaming=is_streaming,
+ provider_config=provider_config,
+ llm_call=make_call(api_base, api_key),
+ product=product,
+ )
+
+
+async def _send_via_modal(
+ request_data: dict[str, Any],
+ user: AuthenticatedUser,
+ is_streaming: bool,
+ product: str,
+ provider_config: ProviderConfig,
+ make_call: Callable[[str, str, str], LlmCall],
+ settings: Settings,
+) -> dict[str, Any] | StreamingResponse:
+ model = request_data["model"]
+ ensure_modal_model_allowed(model)
+ api_base, modal_key, modal_secret = ensure_modal_configured(settings)
+ return await handle_llm_request(
+ request_data=dict(request_data),
+ user=user,
+ model=model,
+ is_streaming=is_streaming,
+ provider_config=provider_config,
+ llm_call=make_call(api_base, modal_key, modal_secret),
+ product=product,
+ )
+
+
+async def _send_glm_request(
+ request_data: dict[str, Any],
+ user: AuthenticatedUser,
+ is_streaming: bool,
+ product: str,
+ *,
+ modal_config: ProviderConfig,
+ cloudflare_config: ProviderConfig,
+ make_modal_call: Callable[[str, 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_modal(model, user, product, settings):
+ return await _send_via_modal(request_data, user, is_streaming, product, modal_config, make_modal_call, settings)
+
+ return await _send_via_cloudflare(
+ request_data, user, is_streaming, product, cloudflare_config, make_cloudflare_call, settings
+ )
+
+
+# Factories are passed at call time (not captured at import) so the module-level names stay the
+# overridable seam.
+
+
+async def send_glm_anthropic_messages(
+ request_data: dict[str, Any],
+ user: AuthenticatedUser,
+ is_streaming: bool,
+ product: str,
+) -> dict[str, Any] | StreamingResponse:
+ return await _send_glm_request(
+ request_data,
+ user,
+ is_streaming,
+ product,
+ modal_config=MODAL_ANTHROPIC_CONFIG,
+ cloudflare_config=CLOUDFLARE_ANTHROPIC_CONFIG,
+ make_modal_call=make_modal_anthropic_call,
+ make_cloudflare_call=make_cloudflare_anthropic_call,
+ )
+
+
+async def send_glm_chat_completions(
+ request_data: dict[str, Any],
+ user: AuthenticatedUser,
+ is_streaming: bool,
+ product: str,
+) -> dict[str, Any] | StreamingResponse:
+ return await _send_glm_request(
+ request_data,
+ user,
+ is_streaming,
+ product,
+ modal_config=MODAL_OPENAI_CONFIG,
+ cloudflare_config=CLOUDFLARE_OPENAI_CONFIG,
+ make_modal_call=make_modal_completion_call,
+ make_cloudflare_call=make_cloudflare_completion_call,
+ )
+
+
+async def send_glm_responses(
+ request_data: dict[str, Any],
+ user: AuthenticatedUser,
+ is_streaming: bool,
+ product: str,
+) -> dict[str, Any] | StreamingResponse:
+ return await _send_glm_request(
+ request_data,
+ user,
+ is_streaming,
+ product,
+ modal_config=MODAL_OPENAI_RESPONSES_CONFIG,
+ cloudflare_config=CLOUDFLARE_OPENAI_RESPONSES_CONFIG,
+ make_modal_call=make_modal_responses_call,
+ make_cloudflare_call=make_cloudflare_responses_call,
+ )
diff --git a/services/llm-gateway/src/llm_gateway/modal.py b/services/llm-gateway/src/llm_gateway/modal.py
new file mode 100644
index 000000000000..7bf2925588dd
--- /dev/null
+++ b/services/llm-gateway/src/llm_gateway/modal.py
@@ -0,0 +1,133 @@
+from __future__ import annotations
+
+import hashlib
+from collections.abc import Awaitable, Callable
+from typing import Any, Final
+
+import litellm
+from fastapi import HTTPException
+
+# Experimental litellm path — `tests/test_cloudflare.py` has a contract test that fails fast on a rename.
+from litellm.llms.anthropic.experimental_pass_through.adapters.handler import (
+ LiteLLMMessagesToCompletionTransformationHandler,
+)
+
+from llm_gateway.config import Settings, _normalize_cost_key
+
+# Modal endpoints are OpenAI-compatible vLLM servers; no native litellm provider.
+_MODAL_LITELLM_PREFIX = "openai/"
+
+# Modal auth rides in the Modal-Key/Modal-Secret headers, but litellm's OpenAI client
+# requires a non-empty api_key.
+_MODAL_PLACEHOLDER_API_KEY = "modal-proxy-token-auth"
+
+# Public gateway model id -> the model name Modal's endpoint serves. The public id keeps its
+# `@cf/` form so clients need no changes; every served name must be priced in COST_ALIASES
+# under `openai/<served>` (tests/test_modal.py enforces the pairing).
+MODAL_MODEL_MAP: Final[dict[str, str]] = {
+ "@cf/zai-org/glm-5.2": "zai-org/GLM-5.2-FP8",
+}
+
+MODAL_ALLOWED_MODELS: Final[frozenset[str]] = frozenset(MODAL_MODEL_MAP)
+
+# Salted so the ramp bucket is independent of other user-hash rollouts.
+_TRAFFIC_BUCKET_SALT = "glm-modal-routing"
+
+
+def is_modal_served_model(model: str) -> bool:
+ return model in MODAL_MODEL_MAP
+
+
+def modal_litellm_model(model: str) -> str:
+ return f"{_MODAL_LITELLM_PREFIX}{MODAL_MODEL_MAP[model]}"
+
+
+def is_modal_configured(settings: Settings) -> bool:
+ return bool(settings.modal_api_base and settings.modal_key and settings.modal_secret)
+
+
+def ensure_modal_configured(settings: Settings) -> tuple[str, str, str]:
+ if not is_modal_configured(settings):
+ raise HTTPException(
+ status_code=503,
+ detail={"error": {"message": "Modal inference not configured", "type": "configuration_error"}},
+ )
+ assert settings.modal_api_base is not None and settings.modal_key is not None and settings.modal_secret is not None
+ return settings.modal_api_base, settings.modal_key, settings.modal_secret
+
+
+def ensure_modal_model_allowed(model: str) -> None:
+ if model not in MODAL_ALLOWED_MODELS:
+ raise HTTPException(
+ status_code=400,
+ detail={
+ "error": {
+ "message": f"Model '{model}' is not supported on the modal provider",
+ "type": "invalid_request_error",
+ }
+ },
+ )
+
+
+def _traffic_bucket(user_key: str) -> float:
+ digest = hashlib.sha256(f"{_TRAFFIC_BUCKET_SALT}:{user_key}".encode()).digest()
+ return int.from_bytes(digest[:8], "big") / 2**64
+
+
+def modal_traffic_fraction(product: str, settings: Settings) -> float:
+ # Legacy product aliases (twig/array) must read their canonical product's fraction.
+ product = _normalize_cost_key(product)
+ return settings.glm_modal_product_traffic_fractions.get(product, settings.glm_modal_traffic_fraction)
+
+
+def should_route_glm_to_modal(model: str, *, product: str, user_key: str, settings: Settings) -> bool:
+ """Env-fraction opt-in; bucketing is per user so a session sticks to one backend."""
+ if not is_modal_served_model(model) or not is_modal_configured(settings):
+ return False
+ fraction = modal_traffic_fraction(product, settings)
+ if fraction <= 0.0:
+ return False
+ if fraction >= 1.0:
+ return True
+ return _traffic_bucket(user_key) < fraction
+
+
+def _inject_modal_params(kwargs: dict[str, Any], api_base: str, modal_key: str, modal_secret: str) -> None:
+ kwargs["api_base"] = api_base
+ kwargs["api_key"] = _MODAL_PLACEHOLDER_API_KEY
+ # Never forward caller-supplied headers/extra_headers: both arrive as extra-allowed request
+ # body fields and litellm merges caller `headers` with `extra_headers` into the outbound
+ # request, so e.g. a caller Host header would steer this authenticated request (and the
+ # proxy-token pair) to an attacker-controlled endpoint.
+ kwargs.pop("headers", None)
+ kwargs["extra_headers"] = {"Modal-Key": modal_key, "Modal-Secret": modal_secret}
+ kwargs["model"] = modal_litellm_model(kwargs["model"])
+ # The OpenAI-compatible surface rejects provider-specific params (see cloudflare.py).
+ kwargs.setdefault("drop_params", True)
+
+
+def make_modal_anthropic_call(api_base: str, modal_key: str, modal_secret: str) -> Callable[..., Awaitable[Any]]:
+ async def llm_call(**kwargs: Any) -> Any:
+ _inject_modal_params(kwargs, api_base, modal_key, modal_secret)
+ return await LiteLLMMessagesToCompletionTransformationHandler.async_anthropic_messages_handler(**kwargs)
+
+ return llm_call
+
+
+def make_modal_completion_call(api_base: str, modal_key: str, modal_secret: str) -> Callable[..., Awaitable[Any]]:
+ async def llm_call(**kwargs: Any) -> Any:
+ _inject_modal_params(kwargs, api_base, modal_key, modal_secret)
+ return await litellm.acompletion(**kwargs)
+
+ return llm_call
+
+
+def make_modal_responses_call(api_base: str, modal_key: str, modal_secret: str) -> Callable[..., Awaitable[Any]]:
+ """vLLM has no /responses route — force litellm's bridge, same as make_cloudflare_responses_call."""
+
+ async def llm_call(**kwargs: Any) -> Any:
+ _inject_modal_params(kwargs, api_base, modal_key, modal_secret)
+ kwargs["use_chat_completions_api"] = True
+ return await litellm.aresponses(**kwargs)
+
+ return llm_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.py
index acf1a5a6f908..fadeb2e1fcf8 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
@@ -23,6 +23,9 @@ CACHE_TTL_SECONDS = 300
COST_ALIASES: dict[str, str] = {
"openai/@cf/moonshotai/kimi-k2.6": "moonshot/kimi-k2.6",
"openai/@cf/zai-org/glm-5.2": "cloudflare/@cf/zai-org/glm-5.2",
+ # Modal serves the same GLM checkpoint (MODAL_MODEL_MAP); billed at the CF rate until trued
+ # up against Modal's GPU-time invoices.
+ "openai/zai-org/GLM-5.2-FP8": "cloudflare/@cf/zai-org/glm-5.2",
}
# For aliased models, litellm's reported (provider, model) labels don't match what the user asked
@@ -31,6 +34,8 @@ COST_ALIASES: dict[str, str] = {
ALIAS_METRIC_LABELS: dict[str, tuple[str, str]] = {
"openai/@cf/moonshotai/kimi-k2.6": ("cloudflare", "@cf/moonshotai/kimi-k2.6"),
"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"),
}
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 bfc3e93042a1..c1277cf47e4e 100644
--- a/services/llm-gateway/src/llm_gateway/services/model_registry.py
+++ b/services/llm-gateway/src/llm_gateway/services/model_registry.py
@@ -6,6 +6,7 @@ from typing import ClassVar, Final
from llm_gateway.cloudflare import CLOUDFLARE_ALLOWED_MODELS, is_cloudflare_configured
from llm_gateway.config import get_settings
+from llm_gateway.modal import MODAL_ALLOWED_MODELS, is_modal_configured
from llm_gateway.products.config import get_product_config
from llm_gateway.rate_limiting.model_cost_service import ModelCost, ModelCostService
@@ -63,6 +64,13 @@ def _cloudflare_configured() -> bool:
return is_cloudflare_configured(get_settings())
+def _glm_backend_configured(model_id: str) -> bool:
+ """A `@cf/` model is servable when Cloudflare or its Modal equivalent is configured."""
+ if _cloudflare_configured():
+ return True
+ return model_id in MODAL_ALLOWED_MODELS and is_modal_configured(get_settings())
+
+
def _is_text_generation_model(cost_data: ModelCost) -> bool:
"""Check if a model supports text generation (chat/completions/responses)."""
mode = cost_data.get("mode", "")
@@ -118,21 +126,23 @@ class ModelRegistryService:
if model is not None:
models.append(model)
- # Append CF models, filtered by the product allowlist (module header explains why they're
- # not reachable through the litellm loop above).
- if _cloudflare_configured():
- for model_id in CLOUDFLARE_ALLOWED_MODELS:
- if allowed_models is not None and not _model_matches_allowlist(model_id, allowed_models):
- continue
- models.append(
- ModelInfo(
- id=model_id,
- provider=_CLOUDFLARE_PROVIDER,
- context_window=_CLOUDFLARE_DEFAULT_CONTEXT_WINDOW,
- supports_streaming=True,
- supports_vision=False,
- )
+ # Append `@cf/` models with a configured backend (module header explains why they're not in
+ # the litellm loop above). Always advertised as provider "cloudflare" — clients key model
+ # handling off the `@cf/` id/owner, and the Modal ramp must not change what they see.
+ for model_id in CLOUDFLARE_ALLOWED_MODELS:
+ if not _glm_backend_configured(model_id):
+ continue
+ if allowed_models is not None and not _model_matches_allowlist(model_id, allowed_models):
+ continue
+ models.append(
+ ModelInfo(
+ id=model_id,
+ provider=_CLOUDFLARE_PROVIDER,
+ context_window=_CLOUDFLARE_DEFAULT_CONTEXT_WINDOW,
+ supports_streaming=True,
+ supports_vision=False,
)
+ )
return models
def is_model_available(self, model_id: str, product: str) -> bool:
@@ -144,10 +154,10 @@ class ModelRegistryService:
if not _model_matches_allowlist(model_id, config.allowed_models):
return False
- # Cloudflare-served models aren't in litellm's cost map (so get_model returns None) — gate
- # them on the CF allowlist + configured CF creds instead.
+ # `@cf/`-served models aren't in litellm's cost map (so get_model returns None) — gate them
+ # on the CF allowlist + a configured backend (Cloudflare or Modal) instead.
if _model_matches_allowlist(model_id, CLOUDFLARE_ALLOWED_MODELS):
- return _cloudflare_configured()
+ return _glm_backend_configured(model_id)
model = self.get_model(model_id)
if model is None:
diff --git a/services/llm-gateway/tests/test_anthropic.py b/services/llm-gateway/tests/test_anthropic.py
index 85d55e42e2df..2b7d24429d6b 100644
--- a/services/llm-gateway/tests/test_anthropic.py
+++ b/services/llm-gateway/tests/test_anthropic.py
@@ -516,13 +516,13 @@ class TestAnthropicMessagesEndpoint:
mock_response.model_dump = MagicMock(return_value=provider_mock_response)
with patch(
- "llm_gateway.api.anthropic.make_cloudflare_anthropic_call",
+ "llm_gateway.glm_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.api.anthropic.ensure_cloudflare_configured",
+ "llm_gateway.glm_routing.ensure_cloudflare_configured",
return_value=("https://api.cloudflare.com/ai/v1", "test-key"),
):
response = authenticated_client.post(
@@ -555,10 +555,10 @@ class TestAnthropicMessagesEndpoint:
mock_response = MagicMock()
mock_response.model_dump = MagicMock(return_value=provider_mock_response)
- with patch("llm_gateway.api.anthropic.make_cloudflare_anthropic_call") as mock_make_call:
+ with patch("llm_gateway.glm_routing.make_cloudflare_anthropic_call") as mock_make_call:
mock_make_call.return_value = AsyncMock(return_value=mock_response)
with patch(
- "llm_gateway.api.anthropic.ensure_cloudflare_configured",
+ "llm_gateway.glm_routing.ensure_cloudflare_configured",
return_value=("https://api.cloudflare.com/ai/v1", "test-key"),
):
response = authenticated_client.post(
@@ -603,12 +603,12 @@ class TestAnthropicMessagesEndpoint:
yield b'event: message_stop\ndata: {"type":"message_stop"}\n\n'
with patch(
- "llm_gateway.api.anthropic.make_cloudflare_anthropic_call",
+ "llm_gateway.glm_routing.make_cloudflare_anthropic_call",
) as mock_make_call:
mock_make_call.return_value = AsyncMock(return_value=fake_stream())
with patch(
- "llm_gateway.api.anthropic.ensure_cloudflare_configured",
+ "llm_gateway.glm_routing.ensure_cloudflare_configured",
return_value=("https://api.cloudflare.com/ai/v1", "test-key"),
):
with authenticated_client.stream(
@@ -637,8 +637,8 @@ class TestAnthropicMessagesEndpoint:
self,
authenticated_client: TestClient,
) -> None:
- with patch("llm_gateway.api.anthropic.ensure_cloudflare_configured") as mock_ensure_configured:
- with patch("llm_gateway.api.anthropic.make_cloudflare_anthropic_call") as mock_make_call:
+ 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:
response = authenticated_client.post(
"/v1/messages",
json={
diff --git a/services/llm-gateway/tests/test_flags.py b/services/llm-gateway/tests/test_flags.py
new file mode 100644
index 000000000000..b79a2d8be0ff
--- /dev/null
+++ b/services/llm-gateway/tests/test_flags.py
@@ -0,0 +1,42 @@
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from llm_gateway import flags
+
+
[email protected](autouse=True)
+def clear_flag_caches() -> None:
+ flags._flag_cache.clear()
+ flags._flag_unavailable_cache.clear()
+
+
[email protected]("enabled", [True, False])
+async def test_evaluate_flag_caches_definitive_answers(enabled: bool) -> None:
+ # Both definitive answers must cache — False (flag disabled) is the normal rollout state, and
+ # caching only True would re-hit /flags on every GLM request while the ramp is off.
+ client = MagicMock()
+ client.feature_enabled.return_value = enabled
+ with patch("llm_gateway.flags._get_client", return_value=client):
+ assert await flags.evaluate_flag("some-flag", "user-a") is enabled
+ assert await flags.evaluate_flag("some-flag", "user-a") is enabled
+ # One roundtrip per (flag, user) within the TTL — flag checks sit on the GLM hot path.
+ assert client.feature_enabled.call_count == 1
+ # sync_mode would otherwise block each uncached evaluation on a $feature_flag_called upload.
+ assert client.feature_enabled.call_args.kwargs["send_feature_flag_events"] is False
+
+
[email protected]("failure_mode", ["sdk_error", "sdk_none"])
+async def test_evaluate_flag_backs_off_globally_when_unavailable(failure_mode: str) -> None:
+ # An outage (exception) and an SDK None result (flag missing / evaluation unavailable) hit the
+ # backoff independently; neither must stack one blocking roundtrip per new user — after the
+ # first miss everyone gets the fallback answer until the backoff expires.
+ client = MagicMock()
+ if failure_mode == "sdk_error":
+ client.feature_enabled.side_effect = RuntimeError("posthog down")
+ else:
+ client.feature_enabled.return_value = None
+ with patch("llm_gateway.flags._get_client", return_value=client):
+ assert await flags.evaluate_flag("some-flag", "user-a") is None
+ assert await flags.evaluate_flag("some-flag", "user-b") is None
+ assert client.feature_enabled.call_count == 1
diff --git a/services/llm-gateway/tests/test_glm_routing.py b/services/llm-gateway/tests/test_glm_routing.py
new file mode 100644
index 000000000000..b99c12d2fabe
--- /dev/null
+++ b/services/llm-gateway/tests/test_glm_routing.py
@@ -0,0 +1,149 @@
+from typing import Any
+from unittest.mock import AsyncMock, patch
+
+import pytest
+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 (
+ send_glm_anthropic_messages,
+ send_glm_chat_completions,
+ send_glm_responses,
+)
+from llm_gateway.request_context import RequestContext, set_request_context
+
+GLM_MODEL = "@cf/zai-org/glm-5.2"
+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"),
+]
+
+
+def _user() -> AuthenticatedUser:
+ return AuthenticatedUser(user_id=1, team_id=1, auth_method="oauth_access_token", distinct_id="d-1")
+
+
+def _settings(**overrides: Any) -> Settings:
+ base: dict[str, Any] = {
+ "cloudflare_api_key": "cf-key",
+ "cloudflare_account_id": "cf-account",
+ "modal_api_base": "https://posthog--glm.us-east.modal.direct/v1",
+ "modal_key": "wk-test",
+ "modal_secret": "ws-test",
+ }
+ base.update(overrides)
+ return Settings(**base)
+
+
+async def _send(
+ settings: Settings,
+ handle: AsyncMock,
+ flag: bool | None = None,
+ send_fn: Any = send_glm_anthropic_messages,
+ product: str = PRODUCT,
+) -> 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),
+ ):
+ result = await send_fn(
+ {"model": GLM_MODEL, "messages": [{"role": "user", "content": "hi"}]},
+ _user(),
+ False,
+ product,
+ )
+ return result, evaluate
+
+
+def _called_providers(handle: AsyncMock) -> list[str]:
+ return [call.kwargs["provider_config"].name for call in handle.call_args_list]
+
+
+async def test_routes_to_cloudflare_by_default() -> None:
+ handle = AsyncMock(return_value={"ok": True})
+ result, _ = await _send(_settings(), handle)
+ assert result == {"ok": True}
+ assert _called_providers(handle) == ["cloudflare"]
+ # The public model id must reach handle_llm_request unchanged — it drives metrics and the
+ # unsupported-model gate.
+ assert handle.call_args.kwargs["model"] == GLM_MODEL
+
+
+async def test_routes_to_modal_when_fraction_one_without_flag_roundtrip() -> None:
+ # A guaranteed-Modal route must not pay (or depend on) a remote flag evaluation.
+ handle = AsyncMock(return_value={"ok": True})
+ result, evaluate = await _send(_settings(glm_modal_traffic_fraction=1.0), handle)
+ assert result == {"ok": True}
+ assert _called_providers(handle) == ["modal"]
+ assert handle.call_args.kwargs["model"] == GLM_MODEL
+ evaluate.assert_not_called()
+
+
+async def test_modal_only_configuration_routes_to_modal() -> None:
+ # With Cloudflare creds absent, GLM is still advertised (it has a Modal backend) — routing must
+ # not send those requests to Cloudflare's 503, whatever the flag/fraction say.
+ handle = AsyncMock(return_value={"ok": True})
+ _, evaluate = await _send(_settings(cloudflare_api_key=None, cloudflare_account_id=None), handle, flag=False)
+ assert _called_providers(handle) == ["modal"]
+ evaluate.assert_not_called()
+
+
[email protected](("send_fn", "modal_endpoint", "cloudflare_endpoint"), SURFACES)
+async def test_each_surface_routes_to_its_provider_configs(
+ send_fn: Any, modal_endpoint: str, cloudflare_endpoint: str
+) -> None:
+ # Every GLM surface must dispatch to its own per-backend ProviderConfig — a mixed-up pairing
+ # would mislabel metrics and use the wrong litellm adapter.
+ handle = AsyncMock(return_value={"ok": True})
+ _, _ = await _send(_settings(glm_modal_traffic_fraction=1.0), handle, send_fn=send_fn)
+ assert handle.call_args.kwargs["provider_config"].endpoint_name == modal_endpoint
+
+ handle.reset_mock()
+ _, _ = await _send(_settings(), handle, send_fn=send_fn)
+ assert handle.call_args.kwargs["provider_config"].endpoint_name == cloudflare_endpoint
+
+
[email protected]("product", ["twig", "array"])
+async def test_alias_products_ramp_through_canonical_fraction(product: str) -> None:
+ # twig/array requests must follow posthog_code's per-product ramp end to end.
+ handle = AsyncMock(return_value={"ok": True})
+ settings = _settings(glm_modal_product_traffic_fractions={"posthog_code": 1.0})
+ _, evaluate = await _send(settings, handle, product=product)
+ assert _called_providers(handle) == ["modal"]
+ evaluate.assert_not_called()
+
+
+async def test_flag_opts_into_modal_at_fraction_zero() -> None:
+ handle = AsyncMock(return_value={"ok": True})
+ _, _ = await _send(_settings(), handle, flag=True)
+ assert _called_providers(handle) == ["modal"]
+
+
+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.
+ handle = AsyncMock(return_value={"ok": True})
+ set_request_context(RequestContext(request_id="test", posthog_flags={"tasks-glm-modal-inference": "true"}))
+ _, _ = await _send(_settings(), handle, flag=False)
+ 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.
+ 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)
+ assert exc_info.value.status_code == 502
+ assert _called_providers(handle) == ["modal"]
diff --git a/services/llm-gateway/tests/test_modal.py b/services/llm-gateway/tests/test_modal.py
new file mode 100644
index 000000000000..911ce7cd8922
--- /dev/null
+++ b/services/llm-gateway/tests/test_modal.py
@@ -0,0 +1,173 @@
+from typing import Any
+from unittest.mock import AsyncMock, patch
+
+import pytest
+from fastapi import HTTPException
+
+from llm_gateway.config import Settings
+from llm_gateway.modal import (
+ MODAL_ALLOWED_MODELS,
+ MODAL_MODEL_MAP,
+ _inject_modal_params,
+ ensure_modal_model_allowed,
+ make_modal_responses_call,
+ should_route_glm_to_modal,
+)
+from llm_gateway.rate_limiting.cost_refresh import ALIAS_METRIC_LABELS, COST_ALIASES
+
+GLM_MODEL = "@cf/zai-org/glm-5.2"
+
+
+def _modal_settings(**overrides: Any) -> Settings:
+ base: dict[str, Any] = {
+ "modal_api_base": "https://posthog--glm.us-east.modal.direct/v1",
+ "modal_key": "wk-test",
+ "modal_secret": "ws-test",
+ }
+ base.update(overrides)
+ return Settings(**base)
+
+
+def test_inject_modal_params_maps_model_and_pins_proxy_auth() -> None:
+ # Caller-supplied header dicts (`headers` or `extra_headers`, any casing) must never reach the
+ # authenticated upstream request — litellm merges both into the outbound headers, and a
+ # forwarded Host header would exfiltrate the proxy-token pair.
+ kwargs: dict = {
+ "model": GLM_MODEL,
+ "headers": {"Host": "attacker.example"},
+ "extra_headers": {"MODAL-KEY": "attacker", "host": "attacker.example", "X-Other": "no"},
+ }
+ _inject_modal_params(kwargs, "https://modal.test/v1", "wk", "ws")
+
+ assert kwargs["model"] == "openai/zai-org/GLM-5.2-FP8"
+ assert kwargs["api_base"] == "https://modal.test/v1"
+ # litellm's OpenAI client rejects a missing api_key even though Modal auth is header-based.
+ assert kwargs["api_key"]
+ assert "headers" not in kwargs
+ assert kwargs["extra_headers"] == {"Modal-Key": "wk", "Modal-Secret": "ws"}
+ # Load-bearing: if this fails, the litellm model key is unpriced/unlabeled and cost lookup
+ # silently falls to default_fallback_cost_usd (and metrics lose the modal provider label).
+ assert kwargs["model"] in COST_ALIASES
+ assert kwargs["model"] in ALIAS_METRIC_LABELS
+
+
[email protected](("initial", "expected"), [({}, True), ({"drop_params": False}, False)])
+def test_inject_modal_params_drop_params(initial: dict, expected: bool) -> None:
+ # drop_params must default on (the OpenAI-compatible surface 400s on Anthropic-only params)
+ # while an explicit caller opt-out keeps its value.
+ kwargs: dict = {"model": GLM_MODEL, **initial}
+ _inject_modal_params(kwargs, "https://modal.test/v1", "wk", "ws")
+ assert kwargs["drop_params"] is expected
+
+
+def test_modal_model_map_served_names_all_priced_and_labeled() -> None:
+ # An unpriced Modal model would bill the flat fallback cost; the label must keep the public id
+ # so one model id slices across backends in dashboards.
+ for public_id, served in MODAL_MODEL_MAP.items():
+ litellm_key = f"openai/{served}"
+ assert litellm_key in COST_ALIASES
+ provider, metric_model = ALIAS_METRIC_LABELS[litellm_key]
+ assert provider == "modal"
+ assert metric_model == public_id
+
+
+def test_ensure_modal_model_allowed_accepts_mapped_model() -> None:
+ ensure_modal_model_allowed(GLM_MODEL)
+ assert GLM_MODEL in MODAL_ALLOWED_MODELS
+
+
[email protected]("model", ["@cf/moonshotai/kimi-k2.6", "@cf/unknown/model", "zai-org/GLM-5.2-FP8"])
+def test_ensure_modal_model_allowed_rejects_unmapped_model(model: str) -> None:
+ with pytest.raises(HTTPException) as exc_info:
+ ensure_modal_model_allowed(model)
+ assert exc_info.value.status_code == 400
+ assert exc_info.value.detail["error"]["type"] == "invalid_request_error"
+ assert model in exc_info.value.detail["error"]["message"]
+
+
+ ("fraction", "product_fractions", "configured", "expected"),
+ [
+ (0.0, {}, True, False),
+ (1.0, {}, True, True),
+ # Missing credentials beat any fraction.
+ (1.0, {}, False, False),
+ # Per-product override beats the global fraction in both directions.
+ (0.0, {"posthog_code": 1.0}, True, True),
+ (1.0, {"posthog_code": 0.0}, True, False),
+ ],
+)
+def test_should_route_glm_to_modal(
+ fraction: float, product_fractions: dict[str, float], configured: bool, expected: bool
+) -> None:
+ overrides: dict[str, Any] = {
+ "glm_modal_traffic_fraction": fraction,
+ "glm_modal_product_traffic_fractions": product_fractions,
+ }
+ if not configured:
+ overrides["modal_key"] = None
+ settings = _modal_settings(**overrides)
+ assert (
+ should_route_glm_to_modal(GLM_MODEL, product="posthog_code", user_key="user-1", settings=settings) is expected
+ )
+
+
[email protected]("product", ["twig", "array"])
+def test_product_aliases_resolve_in_fraction_lookup(product: str) -> None:
+ # Legacy aliases must read posthog_code's per-product fraction, or its ramp/rollback would
+ # silently skip alias traffic.
+ settings = _modal_settings(
+ glm_modal_traffic_fraction=0.0, glm_modal_product_traffic_fractions={"posthog_code": 1.0}
+ )
+ assert should_route_glm_to_modal(GLM_MODEL, product=product, user_key="user-1", settings=settings) is True
+
+
+def test_should_route_only_modal_served_models() -> None:
+ # kimi is CF-allowlisted but has no Modal-served equivalent; routing it to Modal would 404.
+ settings = _modal_settings(glm_modal_traffic_fraction=1.0)
+ assert (
+ should_route_glm_to_modal("@cf/moonshotai/kimi-k2.6", product="posthog_code", user_key="u", settings=settings)
+ is False
+ )
+
+
+def test_partial_fraction_is_sticky_and_monotonic() -> None:
+ # Repeat calls must be identical, and a user routed to Modal at fraction f must stay routed at
+ # any higher fraction — otherwise each ramp-up step would flap migrated users back.
+ fractions = (0.25, 0.5, 0.75)
+ settings = [_modal_settings(glm_modal_traffic_fraction=f) for f in fractions]
+ for user in ("user-1", "user-2", "user-3", "user-4", "user-5"):
+ decisions = [
+ should_route_glm_to_modal(GLM_MODEL, product="posthog_code", user_key=user, settings=s) for s in settings
+ ]
+ assert decisions == sorted(decisions)
+ repeat = [
+ should_route_glm_to_modal(GLM_MODEL, product="posthog_code", user_key=user, settings=s) for s in settings
+ ]
+ assert repeat == decisions
+
+
+def test_partial_fraction_splits_pinned_users() -> None:
+ # Pinned user keys with known buckets ("3" -> ~0.25, "2" -> ~0.96) must land on opposite sides
+ # of fraction 0.5 — a degenerate bucket (constant 0 or 1) passes the monotonicity test above
+ # but fails here.
+ settings = _modal_settings(glm_modal_traffic_fraction=0.5)
+ assert should_route_glm_to_modal(GLM_MODEL, product="posthog_code", user_key="3", settings=settings) is True
+ assert should_route_glm_to_modal(GLM_MODEL, product="posthog_code", user_key="2", settings=settings) is False
+
+
+async def test_make_modal_responses_call_forces_bridge_and_ignores_smuggled_flag() -> None:
+ # vLLM has no /responses route, so the Responses->chat/completions bridge must be forced and a
+ # caller-smuggled use_chat_completions_api=False must not escape it (same bug class as CF).
+ llm_call = make_modal_responses_call("https://modal.test/v1", "wk", "ws")
+
+ with patch("llm_gateway.modal.litellm.aresponses", new=AsyncMock(return_value="ok")) as mock_aresponses:
+ await llm_call(model=GLM_MODEL, input="hi", use_chat_completions_api=False)
+
+ kwargs = mock_aresponses.call_args.kwargs
+ assert kwargs["use_chat_completions_api"] is True
+ assert kwargs["model"] == "openai/zai-org/GLM-5.2-FP8"
+ assert kwargs["api_base"] == "https://modal.test/v1"
+ assert kwargs["extra_headers"]["Modal-Key"] == "wk"
+ assert kwargs["extra_headers"]["Modal-Secret"] == "ws"
+ assert kwargs["input"] == "hi"
diff --git a/services/llm-gateway/tests/test_model_registry.py b/services/llm-gateway/tests/test_model_registry.py
index 4fc3e2e3fb8e..99e0b172995a 100644
--- a/services/llm-gateway/tests/test_model_registry.py
+++ b/services/llm-gateway/tests/test_model_registry.py
@@ -134,6 +134,7 @@ def create_mock_settings(
openrouter: bool = False,
fireworks: bool = False,
cloudflare: bool = False,
+ modal: bool = False,
) -> MagicMock:
settings = MagicMock()
settings.openai_api_key = "sk-test" if openai else None
@@ -144,6 +145,10 @@ def create_mock_settings(
# auto-attributes don't silently enable Cloudflare model advertising.
settings.cloudflare_api_key = "cf-test" if cloudflare else None
settings.cloudflare_account_id = "acct-test" if cloudflare else None
+ # Modal needs all three; same MagicMock-truthiness hazard as CF above.
+ settings.modal_api_base = "https://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
return settings
@@ -350,6 +355,15 @@ class TestCloudflareModelAdvertising:
):
assert self._cf_ids("posthog_code") == {"@cf/zai-org/glm-5.2"}
+ def test_modal_only_advertises_modal_served_models(self):
+ # If CF creds are ever pulled after the Modal migration, GLM must stay advertised (it has a
+ # Modal backend) while CF-only models like kimi drop off the listing.
+ with patch(
+ "llm_gateway.services.model_registry.get_settings",
+ return_value=create_mock_settings(cloudflare=False, modal=True),
+ ):
+ assert self._cf_ids("llm_gateway") == {"@cf/zai-org/glm-5.2"}
+
class TestModelMatchesAllowlist:
@pytest.mark.parametrize(
@@ -399,22 +413,28 @@ class TestIsModelAvailable:
assert is_model_available(model_id, product) == expected
@pytest.mark.parametrize(
- "model_id,product,cloudflare,expected",
+ "model_id,product,cloudflare,modal,expected",
[
# CF creds present + model priced/allowed -> available.
- ("@cf/zai-org/glm-5.2", "llm_gateway", True, True),
- # Same model, but CF creds absent -> the runtime gate refuses it.
- ("@cf/zai-org/glm-5.2", "llm_gateway", False, False),
+ ("@cf/zai-org/glm-5.2", "llm_gateway", True, False, True),
+ # Same model, but no backend configured -> the runtime gate refuses it.
+ ("@cf/zai-org/glm-5.2", "llm_gateway", False, False, False),
+ # No CF creds, but Modal serves GLM -> still available.
+ ("@cf/zai-org/glm-5.2", "llm_gateway", False, True, True),
+ # Modal alone can't serve models without a Modal-served equivalent.
+ ("@cf/moonshotai/kimi-k2.6", "llm_gateway", False, True, False),
# CF configured but the product allowlist excludes this CF model -> unavailable.
- ("@cf/moonshotai/kimi-k2.6", "posthog_code", True, False),
+ ("@cf/moonshotai/kimi-k2.6", "posthog_code", True, False, False),
# CF configured and the product allowlist includes it -> available.
- ("@cf/zai-org/glm-5.2", "posthog_code", True, True),
+ ("@cf/zai-org/glm-5.2", "posthog_code", True, False, True),
],
)
- def test_cf_model_availability_gated_on_creds(self, model_id: str, product: str, cloudflare: bool, expected: bool):
+ def test_cf_model_availability_gated_on_creds(
+ self, model_id: str, product: str, cloudflare: bool, modal: bool, expected: bool
+ ):
with patch(
"llm_gateway.services.model_registry.get_settings",
- return_value=create_mock_settings(cloudflare=cloudflare),
+ return_value=create_mock_settings(cloudflare=cloudflare, modal=modal),
):
assert is_model_available(model_id, product) is expected
diff --git a/services/llm-gateway/tests/test_openai.py b/services/llm-gateway/tests/test_openai.py
index 65661da794fe..cbe9b6fb89ac 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.api.openai.make_cloudflare_completion_call")
- @patch("llm_gateway.api.openai.ensure_cloudflare_configured")
+ @patch("llm_gateway.glm_routing.make_cloudflare_completion_call")
+ @patch("llm_gateway.glm_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.api.openai.make_cloudflare_completion_call")
- @patch("llm_gateway.api.openai.ensure_cloudflare_configured")
+ @patch("llm_gateway.glm_routing.make_cloudflare_completion_call")
+ @patch("llm_gateway.glm_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.api.openai.make_cloudflare_completion_call")
- @patch("llm_gateway.api.openai.ensure_cloudflare_configured")
+ @patch("llm_gateway.glm_routing.make_cloudflare_completion_call")
+ @patch("llm_gateway.glm_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 TestResponsesCloudflareRouting:
@patch("llm_gateway.api.openai.litellm.aresponses")
- @patch("llm_gateway.api.openai.make_cloudflare_responses_call")
- @patch("llm_gateway.api.openai.ensure_cloudflare_configured")
+ @patch("llm_gateway.glm_routing.make_cloudflare_responses_call")
+ @patch("llm_gateway.glm_routing.ensure_cloudflare_configured")
def test_cf_model_routes_through_cloudflare(
self,
mock_ensure_configured: MagicMock,
@@ -412,8 +412,8 @@ class TestResponsesCloudflareRouting:
mock_aresponses.assert_not_called()
@patch("llm_gateway.api.openai.litellm.aresponses")
- @patch("llm_gateway.api.openai.make_cloudflare_responses_call")
- @patch("llm_gateway.api.openai.ensure_cloudflare_configured")
+ @patch("llm_gateway.glm_routing.make_cloudflare_responses_call")
+ @patch("llm_gateway.glm_routing.ensure_cloudflare_configured")
def test_cf_model_streams_through_cloudflare(
self,
mock_ensure_configured: MagicMock,
@@ -452,8 +452,8 @@ class TestResponsesCloudflareRouting:
mock_make_call.assert_called_once_with("https://api.cloudflare.com/ai/v1", "test-key")
mock_aresponses.assert_not_called()
- @patch("llm_gateway.api.openai.make_cloudflare_responses_call")
- @patch("llm_gateway.api.openai.ensure_cloudflare_configured")
+ @patch("llm_gateway.glm_routing.make_cloudflare_responses_call")
+ @patch("llm_gateway.glm_routing.ensure_cloudflare_configured")
def test_unpriced_cf_model_rejected_before_routing(
self,
mock_ensure_configured: MagicMock,
@@ -477,8 +477,8 @@ class TestResponsesCloudflareRouting:
mock_ensure_configured.assert_not_called()
mock_make_call.assert_not_called()
- @patch("llm_gateway.api.openai.make_cloudflare_responses_call")
- @patch("llm_gateway.api.openai.ensure_cloudflare_configured")
+ @patch("llm_gateway.glm_routing.make_cloudflare_responses_call")
+ @patch("llm_gateway.glm_routing.ensure_cloudflare_configured")
def test_previous_response_id_rejected_for_cf_model(
self,
mock_ensure_configured: MagicMock,
@@ -505,8 +505,8 @@ class TestResponsesCloudflareRouting:
mock_ensure_configured.assert_not_called()
mock_make_call.assert_not_called()
- @patch("llm_gateway.api.openai.make_cloudflare_responses_call")
- @patch("llm_gateway.api.openai.ensure_cloudflare_configured")
+ @patch("llm_gateway.glm_routing.make_cloudflare_responses_call")
+ @patch("llm_gateway.glm_routing.ensure_cloudflare_configured")
def test_tools_rejected_for_cf_model(
self,
mock_ensure_configured: MagicMock,