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.

fix(llm-gateway): advertise and serve cloudflare models for the agent (#66684)

Andrew Maguirefe958fbe18a0
diff --git a/services/llm-gateway/scripts/glm_cf_smoke.py b/services/llm-gateway/scripts/glm_cf_smoke.py
new file mode 100644
index 000000000000..4eee4015ebe7
--- /dev/null
+++ b/services/llm-gateway/scripts/glm_cf_smoke.py
@@ -0,0 +1,75 @@
+"""Smoke test: call GLM-5.2 via Cloudflare Workers AI through the gateway's own
+CF anthropic-messages adapter — the exact code path a scout on the claude runtime
+uses (issue 28). Proves CF creds + routing + Anthropic<->OpenAI tool translation.
+
+Run from services/llm-gateway:
+ .venv/bin/python scripts/glm_cf_smoke.py
+
+Reads LLM_GATEWAY_CLOUDFLARE_API_KEY / LLM_GATEWAY_CLOUDFLARE_ACCOUNT_ID from the
+repo .env (Workers AI token needs the "Workers AI: Read + Run" scope).
+"""
+
+import asyncio
+import sys
+
+from dotenv import load_dotenv
+from fastapi import HTTPException
+
+from llm_gateway.cloudflare import (
+ CLOUDFLARE_ALLOWED_MODELS,
+ ensure_cloudflare_configured,
+ make_cloudflare_anthropic_call,
+)
+from llm_gateway.config import Settings
+
+GLM_MODEL = "@cf/zai-org/glm-5.2"
+
+
+async def main() -> None:
+ assert GLM_MODEL in CLOUDFLARE_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, api_key = ensure_cloudflare_configured(Settings())
+ except HTTPException:
+ sys.exit("Missing LLM_GATEWAY_CLOUDFLARE_API_KEY / LLM_GATEWAY_CLOUDFLARE_ACCOUNT_ID")
+ print(f"api_base: {api_base}")
+
+ llm_call = make_cloudflare_anthropic_call(api_base, api_key)
+
+ # Anthropic Messages request WITH a tool — the codex/Responses path can't
+ # translate tools (issue 28 root-cause v2); this claude path must.
+ 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 Cloudflare responded; tool_use emitted = {used_tool}")
+
+
+if __name__ == "__main__":
+ asyncio.run(main())
diff --git a/services/llm-gateway/src/llm_gateway/cloudflare.py b/services/llm-gateway/src/llm_gateway/cloudflare.py
index 79d377486db6..ba1e4e78e303 100644
--- a/services/llm-gateway/src/llm_gateway/cloudflare.py
+++ b/services/llm-gateway/src/llm_gateway/cloudflare.py
@@ -46,13 +46,20 @@ def cloudflare_api_base(account_id: str) -> str:
return f"https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/v1"
+def is_cloudflare_configured(settings: Settings) -> bool:
+ """Whether both Cloudflare credentials (API key + account id) are present."""
+ return bool(settings.cloudflare_api_key and settings.cloudflare_account_id)
+
+
def ensure_cloudflare_configured(settings: Settings) -> tuple[str, str]:
"""Validate Cloudflare credentials and return (api_base, api_key)."""
- if not settings.cloudflare_api_key or not settings.cloudflare_account_id:
+ if not is_cloudflare_configured(settings):
raise HTTPException(
status_code=503,
detail={"error": {"message": "Cloudflare Workers AI not configured", "type": "configuration_error"}},
)
+ # Narrowed by is_cloudflare_configured above; assert restates it for the type checker.
+ assert settings.cloudflare_api_key is not None and settings.cloudflare_account_id is not None
return cloudflare_api_base(settings.cloudflare_account_id), settings.cloudflare_api_key
@@ -74,6 +81,10 @@ def _inject_cloudflare_params(kwargs: dict[str, Any], api_base: str, api_key: st
kwargs["api_base"] = api_base
kwargs["api_key"] = api_key
kwargs["model"] = cloudflare_litellm_model(kwargs["model"])
+ # CF Workers AI is reached through litellm's OpenAI-compatible surface, which rejects
+ # provider-specific params a caller's runtime sends (e.g. Anthropic's reasoning_effort /
+ # context_management). Drop the unsupported ones instead of failing the request.
+ kwargs.setdefault("drop_params", True)
def make_cloudflare_anthropic_call(api_base: str, api_key: str) -> Callable[..., Awaitable[Any]]:
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 ae8053a36d5d..bfc3e93042a1 100644
--- a/services/llm-gateway/src/llm_gateway/services/model_registry.py
+++ b/services/llm-gateway/src/llm_gateway/services/model_registry.py
@@ -4,10 +4,19 @@ import os
from dataclasses import dataclass
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.products.config import get_product_config
from llm_gateway.rate_limiting.model_cost_service import ModelCost, ModelCostService
+# Cloudflare Workers AI models are served via the `@cf/` path (CLOUDFLARE_ALLOWED_MODELS), not
+# through litellm's cost map — so the litellm iteration in get_available_models never surfaces them.
+# Advertise them explicitly on /v1/models when CF creds are configured, else clients that validate a
+# requested model against the listing (e.g. the agent's claude runtime) can't select an `@cf/` model
+# and silently fall back to their default.
+_CLOUDFLARE_PROVIDER: Final[str] = "cloudflare"
+_CLOUDFLARE_DEFAULT_CONTEXT_WINDOW: Final[int] = 128_000
+
@dataclass(frozen=True)
class ModelInfo:
@@ -43,6 +52,17 @@ def _get_configured_providers() -> frozenset[str]:
return frozenset(configured)
+def _cloudflare_configured() -> bool:
+ """Whether the gateway can reach Cloudflare Workers AI — needs both an API key and account id.
+
+ Kept separate from `_get_configured_providers` (litellm-provider keys) on purpose: CF models are
+ served via the `@cf/` path, not litellm, so we only ever advertise the vetted
+ `CLOUDFLARE_ALLOWED_MODELS` — never the broader set of `cloudflare/...` ids litellm happens to
+ price but the gateway won't route.
+ """
+ return is_cloudflare_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", "")
@@ -97,6 +117,22 @@ class ModelRegistryService:
model = self.get_model(model_id)
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,
+ )
+ )
return models
def is_model_available(self, model_id: str, product: str) -> bool:
@@ -108,6 +144,11 @@ 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.
+ if _model_matches_allowlist(model_id, CLOUDFLARE_ALLOWED_MODELS):
+ return _cloudflare_configured()
+
model = self.get_model(model_id)
if model is None:
return False
diff --git a/services/llm-gateway/tests/test_cloudflare.py b/services/llm-gateway/tests/test_cloudflare.py
index 1cd121e8001c..594cca0b2269 100644
--- a/services/llm-gateway/tests/test_cloudflare.py
+++ b/services/llm-gateway/tests/test_cloudflare.py
@@ -29,6 +29,21 @@ def test_inject_cloudflare_params_prefix_matches_cost_alias_keys() -> None:
assert kwargs["model"] in COST_ALIASES
+def test_inject_cloudflare_params_defaults_drop_params_true() -> None:
+ # CF routes through litellm's OpenAI-compatible surface, which 400s on provider-specific params
+ # (Anthropic's reasoning_effort etc.). drop_params must default on so those are dropped, not fatal.
+ kwargs: dict = {"model": "@cf/zai-org/glm-5.2"}
+ _inject_cloudflare_params(kwargs, "https://api.cloudflare.com/test/ai/v1", "secret")
+ assert kwargs["drop_params"] is True
+
+
+def test_inject_cloudflare_params_preserves_explicit_drop_params() -> None:
+ # setdefault semantics: a caller that explicitly opts out keeps their value.
+ kwargs: dict = {"model": "@cf/zai-org/glm-5.2", "drop_params": False}
+ _inject_cloudflare_params(kwargs, "https://api.cloudflare.com/test/ai/v1", "secret")
+ assert kwargs["drop_params"] is False
+
+
def test_allowlist_derived_from_cost_aliases() -> None:
# Any @cf/ entry in COST_ALIASES must be reachable through the allowlist,
# otherwise we'd have a priced model we refuse to route.
diff --git a/services/llm-gateway/tests/test_model_registry.py b/services/llm-gateway/tests/test_model_registry.py
index 707c71502b9f..4fc3e2e3fb8e 100644
--- a/services/llm-gateway/tests/test_model_registry.py
+++ b/services/llm-gateway/tests/test_model_registry.py
@@ -3,6 +3,7 @@ from unittest.mock import MagicMock, patch
import pytest
+from llm_gateway.cloudflare import CLOUDFLARE_ALLOWED_MODELS
from llm_gateway.rate_limiting.model_cost_service import ModelCost, ModelCostService
from llm_gateway.services.model_registry import (
ModelInfo,
@@ -132,12 +133,17 @@ def create_mock_settings(
anthropic: bool = True,
openrouter: bool = False,
fireworks: bool = False,
+ cloudflare: bool = False,
) -> MagicMock:
settings = MagicMock()
settings.openai_api_key = "sk-test" if openai else None
settings.anthropic_api_key = "sk-ant-test" if anthropic else None
settings.openrouter_api_key = "or-test" if openrouter else None
settings.fireworks_api_key = "fw-test" if fireworks else None
+ # CF needs both a key and an account id; default off so a MagicMock's truthy
+ # 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
return settings
@@ -306,6 +312,45 @@ class TestProviderFiltering:
assert providers == {"openai", "anthropic", "openrouter", "fireworks_ai"}
+class TestCloudflareModelAdvertising:
+ """CF Workers AI models aren't in litellm's cost map, so /v1/models advertises them explicitly
+ when CF creds are set — gated on both key + account id, filtered by the product allowlist."""
+
+ def _cf_ids(self, product: str) -> set[str]:
+ return {m.id for m in get_available_models(product) if m.id.startswith("@cf/")}
+
+ def test_cf_models_listed_when_configured(self):
+ with patch(
+ "llm_gateway.services.model_registry.get_settings",
+ return_value=create_mock_settings(cloudflare=True),
+ ):
+ models = get_available_models("llm_gateway")
+ cf = [m for m in models if m.id.startswith("@cf/")]
+ assert {m.id for m in cf} == set(CLOUDFLARE_ALLOWED_MODELS)
+ assert all(m.provider == "cloudflare" for m in cf)
+
+ def test_cf_models_absent_when_not_configured(self):
+ with patch(
+ "llm_gateway.services.model_registry.get_settings",
+ return_value=create_mock_settings(cloudflare=False),
+ ):
+ assert self._cf_ids("llm_gateway") == set()
+
+ def test_cf_requires_both_key_and_account_id(self):
+ settings = create_mock_settings(cloudflare=True)
+ settings.cloudflare_account_id = None
+ with patch("llm_gateway.services.model_registry.get_settings", return_value=settings):
+ assert self._cf_ids("llm_gateway") == set()
+
+ def test_cf_models_filtered_by_product_allowlist(self):
+ # posthog_code's allowlist includes @cf/zai-org/glm-5.2 but not the other CF model(s).
+ with patch(
+ "llm_gateway.services.model_registry.get_settings",
+ return_value=create_mock_settings(cloudflare=True),
+ ):
+ assert self._cf_ids("posthog_code") == {"@cf/zai-org/glm-5.2"}
+
+
class TestModelMatchesAllowlist:
@pytest.mark.parametrize(
"model_id,expected",
@@ -353,6 +398,26 @@ class TestIsModelAvailable:
def test_model_availability(self, model_id: str, product: str, expected: bool):
assert is_model_available(model_id, product) == expected
+ @pytest.mark.parametrize(
+ "model_id,product,cloudflare,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 configured but the product allowlist excludes this CF model -> unavailable.
+ ("@cf/moonshotai/kimi-k2.6", "posthog_code", True, False),
+ # CF configured and the product allowlist includes it -> available.
+ ("@cf/zai-org/glm-5.2", "posthog_code", True, True),
+ ],
+ )
+ def test_cf_model_availability_gated_on_creds(self, model_id: str, product: str, cloudflare: bool, expected: bool):
+ with patch(
+ "llm_gateway.services.model_registry.get_settings",
+ return_value=create_mock_settings(cloudflare=cloudflare),
+ ):
+ assert is_model_available(model_id, product) is expected
+
def test_model_not_available_when_provider_not_configured(self):
with patch.dict(os.environ, {}, clear=False):
for var in PROVIDER_ENV_VARS: