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 Kimi K3 on Modal (#74181)

Alessandro Pogliaghif5bf2121366c
diff --git a/services/llm-gateway/scripts/kimi_modal_smoke.py b/services/llm-gateway/scripts/kimi_modal_smoke.py
new file mode 100644
index 000000000000..9197d19b96a8
--- /dev/null
+++ b/services/llm-gateway/scripts/kimi_modal_smoke.py
@@ -0,0 +1,45 @@
+import asyncio
+import sys
+
+from dotenv import load_dotenv
+from fastapi import HTTPException
+
+from llm_gateway.config import Settings
+from llm_gateway.modal import ensure_modal_model_configured, make_modal_anthropic_call
+
+KIMI_MODEL = "moonshotai/kimi-k3"
+
+
+async def main() -> None:
+ load_dotenv()
+ try:
+ api_base, modal_key, modal_secret = ensure_modal_model_configured(KIMI_MODEL, Settings())
+ except HTTPException:
+ sys.exit("Missing Modal Kimi configuration")
+
+ response = await make_modal_anthropic_call(api_base, modal_key, modal_secret)(
+ model=KIMI_MODEL,
+ max_tokens=256,
+ messages=[{"role": "user", "content": "Use the tool to get the weather in Paris."}],
+ tools=[
+ {
+ "name": "get_weather",
+ "description": "Get the current weather for a city",
+ "input_schema": {
+ "type": "object",
+ "properties": {"city": {"type": "string"}},
+ "required": ["city"],
+ },
+ }
+ ],
+ )
+ content = getattr(response, "content", None) or (response.get("content") if isinstance(response, dict) else None)
+ if not any(
+ (getattr(block, "type", None) or (block.get("type") if isinstance(block, dict) else None)) == "tool_use"
+ for block in content or []
+ ):
+ sys.exit("Kimi K3 did not return a tool call")
+
+
+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 fcbf4d04bc64..59777de51ef1 100644
--- a/services/llm-gateway/src/llm_gateway/api/anthropic.py
+++ b/services/llm-gateway/src/llm_gateway/api/anthropic.py
@@ -46,6 +46,8 @@ from llm_gateway.metrics.prometheus import (
REQUEST_COUNT,
REQUEST_LATENCY,
)
+from llm_gateway.modal import is_modal_served_model
+from llm_gateway.modal_routing import send_modal_anthropic_messages
from llm_gateway.models.anthropic import GATEWAY_ONLY_FIELDS, AnthropicCountTokensRequest, AnthropicMessagesRequest
from llm_gateway.products.config import validate_product
from llm_gateway.request_context import (
@@ -535,6 +537,9 @@ async def _handle_anthropic_messages(
if provider == "cloudflare" or is_cloudflare_model(body.model):
return await send_glm_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)
+
if provider == "bedrock":
return await _send_bedrock_messages(data, user, request, body.stream or False, product)
@@ -615,12 +620,13 @@ async def _handle_count_tokens(
# Route `@cf/` models by model id (see `_handle_anthropic_messages`): a claude-runtime scout on a
# CF model counts tokens here with provider="anthropic", and CF has no count_tokens endpoint, so
# approximate locally rather than POST a CF model id to the real Anthropic count_tokens API.
- if provider == "cloudflare" or is_cloudflare_model(body.model):
- ensure_cloudflare_model_allowed(body.model)
+ if provider == "cloudflare" or is_cloudflare_model(body.model) or is_modal_served_model(body.model):
+ if is_cloudflare_model(body.model):
+ ensure_cloudflare_model_allowed(body.model)
# CF Workers AI has no count_tokens endpoint. Approximate via litellm's tokenizer on the
# serialised payload — callers use this for context-window budgeting, where over-counting
# just trims and only under-counting would overflow.
- aliased_model = cloudflare_litellm_model(body.model)
+ aliased_model = cloudflare_litellm_model(body.model) if is_cloudflare_model(body.model) else body.model
try:
count = await asyncio.to_thread(litellm.token_counter, model=aliased_model, text=json.dumps(data))
except Exception as exc:
diff --git a/services/llm-gateway/src/llm_gateway/api/openai.py b/services/llm-gateway/src/llm_gateway/api/openai.py
index 74ab7a142ea3..271e1b6d1f46 100644
--- a/services/llm-gateway/src/llm_gateway/api/openai.py
+++ b/services/llm-gateway/src/llm_gateway/api/openai.py
@@ -14,6 +14,8 @@ from llm_gateway.api.handler import (
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.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
from llm_gateway.products.config import validate_product
from llm_gateway.request_context import apply_posthog_context_from_headers
@@ -39,6 +41,9 @@ async def _handle_chat_completions(
if is_cloudflare_model(body.model):
return await send_glm_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)
+
return await handle_llm_request(
request_data=data,
user=user,
@@ -84,6 +89,13 @@ async def _handle_responses(
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)
+ if is_modal_served_model(body.model):
+ if body.previous_response_id is not None:
+ raise _invalid_request_error("previous_response_id is not supported for Modal models on the Responses API")
+ if data.get("tools"):
+ raise _invalid_request_error("tools are not yet supported for Modal models on the Responses API")
+ return await send_modal_responses(data, user, body.stream or False, product)
+
original_model = body.model
normalized_model = normalize_litellm_model_name(original_model, OPENAI_RESPONSES_CONFIG.name)
data["model"] = normalized_model
diff --git a/services/llm-gateway/src/llm_gateway/config.py b/services/llm-gateway/src/llm_gateway/config.py
index 3f5088d16f16..050ef2f04091 100644
--- a/services/llm-gateway/src/llm_gateway/config.py
+++ b/services/llm-gateway/src/llm_gateway/config.py
@@ -153,6 +153,7 @@ class Settings(BaseSettings):
# 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_kimi_api_base: str | None = None
modal_key: str | None = None
modal_secret: str | None = None
diff --git a/services/llm-gateway/src/llm_gateway/glm_routing.py b/services/llm-gateway/src/llm_gateway/glm_routing.py
index e62428a99304..6cad490cee69 100644
--- a/services/llm-gateway/src/llm_gateway/glm_routing.py
+++ b/services/llm-gateway/src/llm_gateway/glm_routing.py
@@ -36,8 +36,6 @@ from llm_gateway.cloudflare import (
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,
@@ -45,6 +43,7 @@ from llm_gateway.modal import (
make_modal_responses_call,
should_route_glm_to_modal,
)
+from llm_gateway.modal_routing import send_modal_request
LlmCall = Callable[..., Awaitable[Any]]
@@ -99,29 +98,6 @@ async def _send_via_cloudflare(
)
-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,
@@ -137,7 +113,9 @@ async def _send_glm_request(
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_modal_request(
+ request_data, user, is_streaming, product, modal_config, make_modal_call, settings, handle_llm_request
+ )
return await _send_via_cloudflare(
request_data, user, is_streaming, product, cloudflare_config, make_cloudflare_call, settings
diff --git a/services/llm-gateway/src/llm_gateway/modal.py b/services/llm-gateway/src/llm_gateway/modal.py
index 0e4cc153dbd5..e9afaface43c 100644
--- a/services/llm-gateway/src/llm_gateway/modal.py
+++ b/services/llm-gateway/src/llm_gateway/modal.py
@@ -2,7 +2,8 @@ from __future__ import annotations
import hashlib
from collections.abc import AsyncIterator, Awaitable, Callable
-from typing import Any, Final
+from dataclasses import dataclass
+from typing import Any, Final, Literal
import litellm
from fastapi import HTTPException
@@ -22,31 +23,50 @@ _MODAL_LITELLM_PREFIX = "openai/"
# 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",
+
+@dataclass(frozen=True)
+class ModalModelConfig:
+ served_model: str
+ api_base_setting: Literal["modal_api_base", "modal_kimi_api_base"]
+ has_cloudflare_fallback: bool = False
+
+
+MODAL_MODELS: Final[dict[str, ModalModelConfig]] = {
+ "@cf/zai-org/glm-5.2": ModalModelConfig(
+ served_model="zai-org/GLM-5.2-FP8",
+ api_base_setting="modal_api_base",
+ has_cloudflare_fallback=True,
+ ),
+ "moonshotai/kimi-k3": ModalModelConfig(served_model="moonshotai/kimi-k3", api_base_setting="modal_kimi_api_base"),
}
-MODAL_ALLOWED_MODELS: Final[frozenset[str]] = frozenset(MODAL_MODEL_MAP)
+MODAL_ALLOWED_MODELS: Final[frozenset[str]] = frozenset(MODAL_MODELS)
+MODAL_EXCLUSIVE_MODELS: Final[frozenset[str]] = frozenset(
+ model for model, config in MODAL_MODELS.items() if not config.has_cloudflare_fallback
+)
# 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
+ return model in MODAL_MODELS
def modal_litellm_model(model: str) -> str:
- return f"{_MODAL_LITELLM_PREFIX}{MODAL_MODEL_MAP[model]}"
+ return f"{_MODAL_LITELLM_PREFIX}{MODAL_MODELS[model].served_model}"
def is_modal_configured(settings: Settings) -> bool:
return bool(settings.modal_api_base and settings.modal_key and settings.modal_secret)
+def is_modal_model_configured(model: str, settings: Settings) -> bool:
+ config = MODAL_MODELS.get(model)
+ api_base = getattr(settings, config.api_base_setting) if config else None
+ return bool(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(
@@ -57,6 +77,17 @@ def ensure_modal_configured(settings: Settings) -> tuple[str, str, str]:
return settings.modal_api_base, settings.modal_key, settings.modal_secret
+def ensure_modal_model_configured(model: str, settings: Settings) -> tuple[str, str, str]:
+ ensure_modal_model_allowed(model)
+ api_base = getattr(settings, MODAL_MODELS[model].api_base_setting)
+ if not api_base or not settings.modal_key or not settings.modal_secret:
+ raise HTTPException(
+ status_code=503,
+ detail={"error": {"message": "Modal inference not configured", "type": "configuration_error"}},
+ )
+ return 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(
diff --git a/services/llm-gateway/src/llm_gateway/modal_routing.py b/services/llm-gateway/src/llm_gateway/modal_routing.py
new file mode 100644
index 000000000000..b7634c5a103e
--- /dev/null
+++ b/services/llm-gateway/src/llm_gateway/modal_routing.py
@@ -0,0 +1,71 @@
+from collections.abc import Awaitable, Callable
+from typing import Any
+
+from fastapi.responses import StreamingResponse
+
+from llm_gateway.api.handler import (
+ MODAL_ANTHROPIC_CONFIG,
+ MODAL_OPENAI_CONFIG,
+ MODAL_OPENAI_RESPONSES_CONFIG,
+ ProviderConfig,
+ handle_llm_request,
+)
+from llm_gateway.auth.models import AuthenticatedUser
+from llm_gateway.config import Settings, get_settings
+from llm_gateway.modal import (
+ ensure_modal_model_allowed,
+ ensure_modal_model_configured,
+ make_modal_anthropic_call,
+ make_modal_completion_call,
+ make_modal_responses_call,
+)
+
+LlmCall = Callable[..., Awaitable[Any]]
+
+
+async def send_modal_request(
+ request_data: dict[str, Any],
+ user: AuthenticatedUser,
+ is_streaming: bool,
+ product: str,
+ provider_config: ProviderConfig,
+ make_call: Callable[[str, str, str], LlmCall],
+ settings: Settings | None = None,
+ handle_request: LlmCall = handle_llm_request,
+) -> dict[str, Any] | StreamingResponse:
+ model = request_data["model"]
+ ensure_modal_model_allowed(model)
+ api_base, modal_key, modal_secret = ensure_modal_model_configured(model, settings or get_settings())
+ return await handle_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_modal_anthropic_messages(
+ request_data: dict[str, Any], user: AuthenticatedUser, is_streaming: bool, product: str
+) -> dict[str, Any] | StreamingResponse:
+ return await send_modal_request(
+ request_data, user, is_streaming, product, MODAL_ANTHROPIC_CONFIG, make_modal_anthropic_call
+ )
+
+
+async def send_modal_chat_completions(
+ request_data: dict[str, Any], user: AuthenticatedUser, is_streaming: bool, product: str
+) -> dict[str, Any] | StreamingResponse:
+ return await send_modal_request(
+ request_data, user, is_streaming, product, MODAL_OPENAI_CONFIG, make_modal_completion_call
+ )
+
+
+async def send_modal_responses(
+ request_data: dict[str, Any], user: AuthenticatedUser, is_streaming: bool, product: str
+) -> dict[str, Any] | StreamingResponse:
+ return await send_modal_request(
+ request_data, user, is_streaming, product, MODAL_OPENAI_RESPONSES_CONFIG, make_modal_responses_call
+ )
diff --git a/services/llm-gateway/src/llm_gateway/products/config.py b/services/llm-gateway/src/llm_gateway/products/config.py
index 84c777fab530..fc876b2a5a95 100644
--- a/services/llm-gateway/src/llm_gateway/products/config.py
+++ b/services/llm-gateway/src/llm_gateway/products/config.py
@@ -85,6 +85,7 @@ _POSTHOG_CODE_AGENT_MODELS: Final[frozenset[str]] = frozenset(
"gpt-5.2",
"gpt-5-mini",
"@cf/zai-org/glm-5.2",
+ "moonshotai/kimi-k3",
}
)
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 fadeb2e1fcf8..dcdbcb3cc546 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,7 +23,7 @@ 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
+ # Modal serves the same GLM checkpoint; 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",
}
@@ -36,6 +36,7 @@ ALIAS_METRIC_LABELS: dict[str, tuple[str, str]] = {
"openai/@cf/zai-org/glm-5.2": ("cloudflare", "@cf/zai-org/glm-5.2"),
# Same public model id as the CF entry so dashboards slice one model across both backends.
"openai/zai-org/GLM-5.2-FP8": ("modal", "@cf/zai-org/glm-5.2"),
+ "openai/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 794d1f24986d..e68af775b4fe 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
@@ -10,7 +10,21 @@ if TYPE_CHECKING:
# is invisible even when allowlisted in products/config.py. Merged only when
# LiteLLM doesn't already define the model; delete each entry once upstream lands it.
# Pricing verified against OpenRouter (Anthropic + Bedrock).
+KIMI_K3_COST: Final[ModelCost] = {
+ "litellm_provider": "modal",
+ "mode": "chat",
+ "max_input_tokens": 262_144,
+ "max_output_tokens": 32_768,
+ "input_cost_per_token": 3e-06,
+ "output_cost_per_token": 1.5e-05,
+ "cache_read_input_token_cost": 3e-07,
+ "supports_vision": False,
+ "supports_prompt_caching": True,
+}
+
MODEL_COST_OVERRIDES: Final[dict[str, ModelCost]] = {
+ "moonshotai/kimi-k3": cast("ModelCost", dict(KIMI_K3_COST)),
+ "openai/moonshotai/kimi-k3": cast("ModelCost", dict(KIMI_K3_COST)),
"claude-fable-5": {
"litellm_provider": "anthropic",
"mode": "chat",
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 c1277cf47e4e..e39d52e61755 100644
--- a/services/llm-gateway/src/llm_gateway/services/model_registry.py
+++ b/services/llm-gateway/src/llm_gateway/services/model_registry.py
@@ -6,7 +6,12 @@ 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.modal import (
+ MODAL_ALLOWED_MODELS,
+ MODAL_EXCLUSIVE_MODELS,
+ is_modal_configured,
+ is_modal_model_configured,
+)
from llm_gateway.products.config import get_product_config
from llm_gateway.rate_limiting.model_cost_service import ModelCost, ModelCostService
@@ -143,6 +148,14 @@ class ModelRegistryService:
supports_vision=False,
)
)
+ for model_id in MODAL_EXCLUSIVE_MODELS:
+ if not is_modal_model_configured(model_id, get_settings()):
+ continue
+ if allowed_models is not None and not _model_matches_allowlist(model_id, allowed_models):
+ continue
+ model = self.get_model(model_id)
+ if model is not None:
+ models.append(model)
return models
def is_model_available(self, model_id: str, product: str) -> bool:
@@ -159,6 +172,9 @@ class ModelRegistryService:
if _model_matches_allowlist(model_id, CLOUDFLARE_ALLOWED_MODELS):
return _glm_backend_configured(model_id)
+ if _model_matches_allowlist(model_id, MODAL_ALLOWED_MODELS):
+ return is_modal_model_configured(model_id, 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 b5dacb6248e9..d93dd6b003c3 100644
--- a/services/llm-gateway/tests/test_anthropic.py
+++ b/services/llm-gateway/tests/test_anthropic.py
@@ -1493,6 +1493,25 @@ class TestAnthropicCountTokensEndpoint:
assert response.json()["input_tokens"] > 0
mock_real_count.assert_not_called()
+ def test_modal_model_approximates_count_without_provider_header(
+ self,
+ authenticated_client: TestClient,
+ ) -> None:
+ with patch("llm_gateway.api.anthropic._anthropic_count_tokens_impl") as mock_real_count:
+ response = authenticated_client.post(
+ "/v1/messages/count_tokens",
+ json={
+ "model": "moonshotai/kimi-k3",
+ "messages": [{"role": "user", "content": "Hello"}],
+ },
+ headers={"Authorization": "Bearer phx_test_key"},
+ )
+
+ assert response.status_code == 200
+ assert isinstance(response.json()["input_tokens"], int)
+ assert response.json()["input_tokens"] > 0
+ mock_real_count.assert_not_called()
+
def test_cloudflare_provider_rejects_unpriced_model(
self,
authenticated_client: TestClient,
diff --git a/services/llm-gateway/tests/test_modal.py b/services/llm-gateway/tests/test_modal.py
index 911ce7cd8922..aa88f6756da5 100644
--- a/services/llm-gateway/tests/test_modal.py
+++ b/services/llm-gateway/tests/test_modal.py
@@ -7,20 +7,24 @@ from fastapi import HTTPException
from llm_gateway.config import Settings
from llm_gateway.modal import (
MODAL_ALLOWED_MODELS,
- MODAL_MODEL_MAP,
+ MODAL_MODELS,
_inject_modal_params,
ensure_modal_model_allowed,
+ ensure_modal_model_configured,
make_modal_responses_call,
should_route_glm_to_modal,
)
from llm_gateway.rate_limiting.cost_refresh import ALIAS_METRIC_LABELS, COST_ALIASES
+from llm_gateway.rate_limiting.model_cost_overrides import MODEL_COST_OVERRIDES
GLM_MODEL = "@cf/zai-org/glm-5.2"
+KIMI_MODEL = "moonshotai/kimi-k3"
def _modal_settings(**overrides: Any) -> Settings:
base: dict[str, Any] = {
"modal_api_base": "https://posthog--glm.us-east.modal.direct/v1",
+ "modal_kimi_api_base": "https://posthog--kimi.us-west.modal.direct/v1",
"modal_key": "wk-test",
"modal_secret": "ws-test",
}
@@ -63,17 +67,26 @@ def test_inject_modal_params_drop_params(initial: dict, expected: bool) -> None:
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
+ for public_id, config in MODAL_MODELS.items():
+ litellm_key = f"openai/{config.served_model}"
+ assert litellm_key in COST_ALIASES or litellm_key in MODEL_COST_OVERRIDES
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", [GLM_MODEL, KIMI_MODEL])
+def test_ensure_modal_model_allowed_accepts_mapped_model(model: str) -> None:
+ ensure_modal_model_allowed(model)
+ assert model in MODAL_ALLOWED_MODELS
+
+
+def test_kimi_uses_its_endpoint_with_shared_credentials() -> None:
+ assert ensure_modal_model_configured(KIMI_MODEL, _modal_settings()) == (
+ "https://posthog--kimi.us-west.modal.direct/v1",
+ "wk-test",
+ "ws-test",
+ )
@pytest.mark.parametrize("model", ["@cf/moonshotai/kimi-k2.6", "@cf/unknown/model", "zai-org/GLM-5.2-FP8"])
diff --git a/services/llm-gateway/tests/test_model_registry.py b/services/llm-gateway/tests/test_model_registry.py
index 99e0b172995a..e67b630507de 100644
--- a/services/llm-gateway/tests/test_model_registry.py
+++ b/services/llm-gateway/tests/test_model_registry.py
@@ -147,6 +147,7 @@ def create_mock_settings(
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_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
return settings
diff --git a/services/llm-gateway/tests/test_openai.py b/services/llm-gateway/tests/test_openai.py
index cbe9b6fb89ac..1a3db7cdaf8d 100644
--- a/services/llm-gateway/tests/test_openai.py
+++ b/services/llm-gateway/tests/test_openai.py
@@ -381,7 +381,7 @@ class TestChatCompletionsEndpoint:
# not litellm.aresponses (which prefixes openai/ and hits the real OpenAI Responses API ->
# model_not_supported). This is the codex/Responses gap that left every GLM-routed scout run making
# zero generations.
-class TestResponsesCloudflareRouting:
+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")
@@ -411,6 +411,31 @@ class TestResponsesCloudflareRouting:
# Native OpenAI Responses path must not be touched for a CF model.
mock_aresponses.assert_not_called()
+ @patch("llm_gateway.api.openai.litellm.aresponses")
+ @patch("llm_gateway.modal_routing.make_modal_responses_call")
+ @patch("llm_gateway.modal_routing.ensure_modal_model_configured")
+ def test_kimi_routes_through_modal(
+ self,
+ mock_ensure_configured: MagicMock,
+ mock_make_call: MagicMock,
+ mock_aresponses: MagicMock,
+ authenticated_client: TestClient,
+ ) -> None:
+ mock_ensure_configured.return_value = ("https://kimi.modal.test/v1", "key", "secret")
+ mock_response = MagicMock()
+ mock_response.model_dump = MagicMock(return_value={"id": "resp_1", "output": []})
+ mock_make_call.return_value = AsyncMock(return_value=mock_response)
+
+ response = authenticated_client.post(
+ "/v1/responses",
+ json={"model": "moonshotai/kimi-k3", "input": "Hello"},
+ headers={"Authorization": "Bearer phx_test_key"},
+ )
+
+ assert response.status_code == 200
+ mock_make_call.assert_called_once_with("https://kimi.modal.test/v1", "key", "secret")
+ 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")