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): route @cf models through cloudflare on all api surfaces (#66482)

Andrew Maguire4e9c10a65c4f
diff --git a/services/llm-gateway/src/llm_gateway/api/anthropic.py b/services/llm-gateway/src/llm_gateway/api/anthropic.py
index cf2d8045443f..74218ed94d23 100644
--- a/services/llm-gateway/src/llm_gateway/api/anthropic.py
+++ b/services/llm-gateway/src/llm_gateway/api/anthropic.py
@@ -31,6 +31,7 @@ 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
@@ -403,7 +404,14 @@ async def _handle_anthropic_messages(
provider = _get_provider_from_headers(request)
use_bedrock_fallback = _get_use_bedrock_fallback_from_headers(request)
- if provider == "cloudflare":
+ # `@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.
+ if provider == "cloudflare" or is_cloudflare_model(body.model):
return await _send_cloudflare_messages(data, user, body.stream or False, product)
if provider == "bedrock":
@@ -478,7 +486,10 @@ async def _handle_count_tokens(
provider = _get_provider_from_headers(request)
use_bedrock_fallback = _get_use_bedrock_fallback_from_headers(request)
- if provider == "cloudflare":
+ # 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)
# 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
diff --git a/services/llm-gateway/src/llm_gateway/api/handler.py b/services/llm-gateway/src/llm_gateway/api/handler.py
index 87cc2bf227c3..0e809beaacf5 100644
--- a/services/llm-gateway/src/llm_gateway/api/handler.py
+++ b/services/llm-gateway/src/llm_gateway/api/handler.py
@@ -48,6 +48,7 @@ OPENAI_TRANSCRIPTION_CONFIG = ProviderConfig(name="openai", endpoint_name="audio
# Split endpoint labels so an adapter-specific regression is distinguishable in metrics.
CLOUDFLARE_ANTHROPIC_CONFIG = ProviderConfig(name="cloudflare", endpoint_name="cloudflare_anthropic_messages")
CLOUDFLARE_OPENAI_CONFIG = ProviderConfig(name="cloudflare", endpoint_name="cloudflare_chat_completions")
+CLOUDFLARE_OPENAI_RESPONSES_CONFIG = ProviderConfig(name="cloudflare", endpoint_name="cloudflare_responses")
_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 ca49ef954b81..4e1fc6ceea6e 100644
--- a/services/llm-gateway/src/llm_gateway/api/openai.py
+++ b/services/llm-gateway/src/llm_gateway/api/openai.py
@@ -6,6 +6,7 @@ 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,
@@ -15,7 +16,9 @@ from llm_gateway.api.handler import (
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.dependencies import RateLimitedUser
@@ -26,8 +29,12 @@ from llm_gateway.request_context import apply_posthog_context_from_headers
openai_router = APIRouter()
-def _is_cloudflare_model(model: str) -> bool:
- return model.startswith("@cf/")
+def _invalid_request_error(message: str) -> HTTPException:
+ """A 400 in the OpenAI error envelope (mirrors anthropic.py's `_invalid_header_exception`)."""
+ return HTTPException(
+ status_code=400,
+ detail={"error": {"message": message, "type": "invalid_request_error", "code": None}},
+ )
async def _handle_chat_completions(
@@ -37,7 +44,7 @@ async def _handle_chat_completions(
) -> dict[str, Any] | StreamingResponse:
data = body.model_dump(exclude_none=True)
- if _is_cloudflare_model(body.model):
+ if is_cloudflare_model(body.model):
ensure_cloudflare_model_allowed(body.model)
settings = get_settings()
api_base, api_key = ensure_cloudflare_configured(settings)
@@ -74,6 +81,38 @@ 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).
+ if body.previous_response_id is not None:
+ # The bridge rebuilds prior turns from litellm proxy spend logs; we run litellm as an
+ # SDK (no proxy DB), so it would silently resolve to empty history and drop the
+ # conversation. Reject explicitly rather than answer with lost context.
+ raise _invalid_request_error(
+ "previous_response_id is not supported for Cloudflare models on the Responses API"
+ )
+ if data.get("tools"):
+ # `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.
+ 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,
+ )
+
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/cloudflare.py b/services/llm-gateway/src/llm_gateway/cloudflare.py
index 56f6cb2f6327..79d377486db6 100644
--- a/services/llm-gateway/src/llm_gateway/cloudflare.py
+++ b/services/llm-gateway/src/llm_gateway/cloudflare.py
@@ -17,6 +17,16 @@ from llm_gateway.rate_limiting.cost_refresh import COST_ALIASES
# CF has no native litellm provider; we route through its OpenAI-compatible endpoint.
_CF_LITELLM_PREFIX = "openai/"
+# CF Workers AI model ids are namespaced under `@cf/` (e.g. `@cf/zai-org/glm-5.2`). The id alone is
+# what marks a request for CF routing across every gateway path — chat/completions, responses, and
+# anthropic-messages all branch on this, independent of the provider header.
+_CF_MODEL_PREFIX = "@cf/"
+
+
+def is_cloudflare_model(model: str) -> bool:
+ """Whether `model` is a Cloudflare Workers AI model id (`@cf/...`)."""
+ return model.startswith(_CF_MODEL_PREFIX)
+
def cloudflare_litellm_model(model: str) -> str:
"""The litellm model id CF requests route under (its OpenAI-compatible prefix)."""
@@ -88,3 +98,27 @@ def make_cloudflare_completion_call(api_base: str, api_key: str) -> Callable[...
return await litellm.acompletion(**kwargs)
return llm_call
+
+
+def make_cloudflare_responses_call(api_base: str, api_key: str) -> Callable[..., Awaitable[Any]]:
+ """Build an llm_call that routes OpenAI Responses API requests to Cloudflare.
+
+ CF's OpenAI-compatible endpoint only serves chat/completions, not the Responses API,
+ so we force litellm's Responses->chat/completions bridge (`use_chat_completions_api`)
+ and route the bridged completion through CF's endpoint. Without this, `litellm.aresponses`
+ would hit CF's non-existent `/responses` route. This is the codex/Responses analogue of
+ `make_cloudflare_completion_call` (chat/completions) and `make_cloudflare_anthropic_call`
+ (Anthropic Messages).
+ """
+
+ async def llm_call(**kwargs: Any) -> Any:
+ _inject_cloudflare_params(kwargs, api_base, api_key)
+ # Assign into kwargs rather than passing as an explicit keyword: `ResponsesRequest` allows
+ # extra fields, so a caller could smuggle `use_chat_completions_api` in the request body —
+ # passing it both ways would raise `TypeError: got multiple values for keyword argument`,
+ # and this also stops a caller flipping it to False to escape the bridge onto CF's missing
+ # /responses route.
+ kwargs["use_chat_completions_api"] = True
+ return await litellm.aresponses(**kwargs)
+
+ return llm_call
diff --git a/services/llm-gateway/tests/test_anthropic.py b/services/llm-gateway/tests/test_anthropic.py
index a571f495e438..33e1f92bc65e 100644
--- a/services/llm-gateway/tests/test_anthropic.py
+++ b/services/llm-gateway/tests/test_anthropic.py
@@ -541,6 +541,51 @@ class TestAnthropicMessagesEndpoint:
mock_make_call.assert_called_once()
mock_anthropic.assert_not_called()
+ @patch("llm_gateway.api.anthropic.litellm.anthropic_messages")
+ def test_cf_model_routes_to_cloudflare_without_provider_header(
+ self,
+ mock_anthropic: MagicMock,
+ authenticated_client: TestClient,
+ provider_mock_response: dict,
+ ) -> None:
+ # Real scout case: the harness derives the provider header from the runtime (claude->anthropic)
+ # and never sends "cloudflare", so a claude-runtime scout on GLM arrives as provider="anthropic".
+ # Without id-based routing it would hit the real Anthropic API with a @cf/... model and 404.
+ # Tools are forwarded — the Anthropic->chat/completions adapter translates them (unlike Responses).
+ 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:
+ mock_make_call.return_value = AsyncMock(return_value=mock_response)
+ with patch(
+ "llm_gateway.api.anthropic.ensure_cloudflare_configured",
+ return_value=("https://api.cloudflare.com/ai/v1", "test-key"),
+ ):
+ response = authenticated_client.post(
+ "/v1/messages",
+ json={
+ "model": "@cf/zai-org/glm-5.2",
+ "messages": [{"role": "user", "content": "find issues"}],
+ "tools": [
+ {
+ "name": "emit_signal",
+ "description": "emit a finding",
+ "input_schema": {"type": "object", "properties": {"title": {"type": "string"}}},
+ }
+ ],
+ },
+ # No X-PostHog-Provider header -> defaults to anthropic, as a claude-runtime scout sends.
+ headers={"Authorization": "Bearer phx_test_key"},
+ )
+
+ assert response.status_code == 200
+ mock_make_call.assert_called_once()
+ # Must never reach the real Anthropic path with a `@cf/` model.
+ mock_anthropic.assert_not_called()
+ forwarded = mock_make_call.return_value.call_args.kwargs
+ assert forwarded["model"] == "@cf/zai-org/glm-5.2"
+ assert forwarded["tools"][0]["name"] == "emit_signal"
+
@patch("llm_gateway.api.anthropic.litellm.anthropic_messages")
def test_cloudflare_provider_streams_through_cloudflare(
self,
@@ -1170,6 +1215,29 @@ class TestAnthropicCountTokensEndpoint:
assert isinstance(response.json()["input_tokens"], int)
assert response.json()["input_tokens"] > 0
+ def test_cf_model_approximates_count_without_provider_header(
+ self,
+ authenticated_client: TestClient,
+ ) -> None:
+ # The claude-runtime scout calls count_tokens with provider="anthropic"; CF has no
+ # count_tokens endpoint, so route a @cf/ model by id and approximate rather than POST a
+ # @cf/... id to the real Anthropic count_tokens API (which would 404).
+ with patch("llm_gateway.api.anthropic._anthropic_count_tokens_impl") as mock_real_count:
+ response = authenticated_client.post(
+ "/v1/messages/count_tokens",
+ json={
+ "model": "@cf/zai-org/glm-5.2",
+ "messages": [{"role": "user", "content": "Hello"}],
+ },
+ # No X-PostHog-Provider header -> defaults to anthropic, as a claude-runtime scout sends.
+ 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_cloudflare.py b/services/llm-gateway/tests/test_cloudflare.py
index ac3c876c4894..1cd121e8001c 100644
--- a/services/llm-gateway/tests/test_cloudflare.py
+++ b/services/llm-gateway/tests/test_cloudflare.py
@@ -1,10 +1,18 @@
+from unittest.mock import AsyncMock, patch
+
+import litellm
import pytest
from fastapi import HTTPException
+from litellm.llms.anthropic.experimental_pass_through.adapters.handler import (
+ LiteLLMMessagesToCompletionTransformationHandler,
+)
+from litellm.types.utils import ModelResponse
from llm_gateway.cloudflare import (
CLOUDFLARE_ALLOWED_MODELS,
_inject_cloudflare_params,
ensure_cloudflare_model_allowed,
+ make_cloudflare_responses_call,
)
from llm_gateway.rate_limiting.cost_refresh import COST_ALIASES
@@ -52,9 +60,58 @@ def test_ensure_cloudflare_model_allowed_rejects_unpriced_model(model: str) -> N
def test_litellm_anthropic_messages_adapter_contract() -> None:
- """Fails in CI if a litellm bump renames the experimental symbol the CF anthropic route imports."""
- from litellm.llms.anthropic.experimental_pass_through.adapters.handler import (
- LiteLLMMessagesToCompletionTransformationHandler,
- )
-
+ # Fails in CI if a litellm bump renames the experimental symbol the CF anthropic route imports.
assert callable(LiteLLMMessagesToCompletionTransformationHandler.async_anthropic_messages_handler)
+
+
+async def test_make_cloudflare_responses_call_injects_params_and_forces_bridge() -> None:
+ # The CF responses adapter must inject CF creds/model and force litellm's
+ # Responses->chat/completions bridge (use_chat_completions_api=True), since CF's
+ # OpenAI-compatible endpoint has no native /responses route.
+ llm_call = make_cloudflare_responses_call("https://api.cloudflare.com/test/ai/v1", "secret")
+
+ with patch("llm_gateway.cloudflare.litellm.aresponses", new=AsyncMock(return_value="ok")) as mock_aresponses:
+ await llm_call(model="@cf/zai-org/glm-5.2", input="hi")
+
+ kwargs = mock_aresponses.call_args.kwargs
+ assert kwargs["use_chat_completions_api"] is True
+ assert kwargs["model"] == "openai/@cf/zai-org/glm-5.2"
+ assert kwargs["api_base"] == "https://api.cloudflare.com/test/ai/v1"
+ assert kwargs["api_key"] == "secret"
+ assert kwargs["input"] == "hi"
+
+
+async def test_make_cloudflare_responses_call_ignores_caller_supplied_bridge_flag() -> None:
+ # ResponsesRequest allows extra fields, so a caller can smuggle use_chat_completions_api into
+ # the request body. The adapter must overwrite it (not pass it twice -> TypeError, and not let
+ # False escape the bridge onto CF's missing /responses route).
+ llm_call = make_cloudflare_responses_call("https://api.cloudflare.com/test/ai/v1", "secret")
+
+ with patch("llm_gateway.cloudflare.litellm.aresponses", new=AsyncMock(return_value="ok")) as mock_aresponses:
+ # Caller tries to disable the bridge; must not raise and must not win.
+ await llm_call(model="@cf/zai-org/glm-5.2", input="hi", use_chat_completions_api=False)
+
+ assert mock_aresponses.call_args.kwargs["use_chat_completions_api"] is True
+
+
+async def test_litellm_responses_completion_bridge_contract() -> None:
+ # Load-bearing: litellm.aresponses(use_chat_completions_api=True, ...) must route a CF-style
+ # model through the chat/completions bridge (i.e. call litellm.acompletion), not the native
+ # Responses API. Fails fast if a litellm bump drops/renames the flag — which would silently
+ # send CF responses traffic back to the broken native path.
+ fake = ModelResponse(choices=[{"message": {"role": "assistant", "content": "hi from cf"}}])
+
+ with patch("litellm.acompletion", new=AsyncMock(return_value=fake)) as mock_acompletion:
+ result = await litellm.aresponses(
+ model="openai/@cf/zai-org/glm-5.2",
+ input="hello",
+ use_chat_completions_api=True,
+ api_base="https://api.cloudflare.com/test/ai/v1",
+ api_key="secret",
+ )
+
+ assert mock_acompletion.called
+ assert mock_acompletion.call_args.kwargs["api_base"] == "https://api.cloudflare.com/test/ai/v1"
+ # The bridge must not leak the gateway-internal flag downstream to acompletion.
+ assert "use_chat_completions_api" not in mock_acompletion.call_args.kwargs
+ assert type(result).__name__ == "ResponsesAPIResponse"
diff --git a/services/llm-gateway/tests/test_openai.py b/services/llm-gateway/tests/test_openai.py
index 74bb0070afb1..f90e0d23d7f6 100644
--- a/services/llm-gateway/tests/test_openai.py
+++ b/services/llm-gateway/tests/test_openai.py
@@ -377,6 +377,163 @@ class TestChatCompletionsEndpoint:
mock_make_call.assert_not_called()
+# CF-served models (@cf/...) on the Responses endpoint must route through the CF responses adapter,
+# 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:
+ @patch("llm_gateway.api.openai.litellm.aresponses")
+ @patch("llm_gateway.api.openai.make_cloudflare_responses_call")
+ @patch("llm_gateway.api.openai.ensure_cloudflare_configured")
+ def test_cf_model_routes_through_cloudflare(
+ self,
+ mock_ensure_configured: MagicMock,
+ mock_make_call: MagicMock,
+ mock_aresponses: MagicMock,
+ authenticated_client: TestClient,
+ ) -> None:
+ mock_ensure_configured.return_value = ("https://api.cloudflare.com/ai/v1", "test-key")
+ 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": "@cf/zai-org/glm-5.2",
+ "input": "Hello",
+ },
+ headers={"Authorization": "Bearer phx_test_key"},
+ )
+
+ assert response.status_code == 200
+ mock_make_call.assert_called_once_with("https://api.cloudflare.com/ai/v1", "test-key")
+ # 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.api.openai.make_cloudflare_responses_call")
+ @patch("llm_gateway.api.openai.ensure_cloudflare_configured")
+ def test_cf_model_streams_through_cloudflare(
+ self,
+ mock_ensure_configured: MagicMock,
+ mock_make_call: MagicMock,
+ mock_aresponses: MagicMock,
+ authenticated_client: TestClient,
+ ) -> None:
+ # Streaming branch of the CF Responses route: the routed llm_call returns an async iterator,
+ # format_sse_stream wraps it, and the gateway emits SSE chunks back.
+ mock_ensure_configured.return_value = ("https://api.cloudflare.com/ai/v1", "test-key")
+
+ async def fake_stream():
+ for content in ("hello", "world"):
+ chunk = MagicMock()
+ chunk.model_dump = MagicMock(return_value={"choices": [{"delta": {"content": content}, "index": 0}]})
+ yield chunk
+
+ mock_make_call.return_value = AsyncMock(return_value=fake_stream())
+
+ with authenticated_client.stream(
+ "POST",
+ "/v1/responses",
+ json={
+ "model": "@cf/zai-org/glm-5.2",
+ "input": "Hello",
+ "stream": True,
+ },
+ headers={"Authorization": "Bearer phx_test_key"},
+ ) as response:
+ assert response.status_code == 200
+ body = "".join(response.iter_text())
+
+ assert '"hello"' in body
+ assert '"world"' in body
+ assert "[DONE]" in body
+ 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")
+ def test_unpriced_cf_model_rejected_before_routing(
+ self,
+ mock_ensure_configured: MagicMock,
+ mock_make_call: MagicMock,
+ authenticated_client: TestClient,
+ ) -> None:
+ response = authenticated_client.post(
+ "/v1/responses",
+ json={
+ "model": "@cf/meta/llama-3.3-70b-instruct",
+ "input": "Hello",
+ },
+ headers={"Authorization": "Bearer phx_test_key"},
+ )
+
+ assert response.status_code == 400
+ assert response.json()["error"]["type"] == "invalid_request_error"
+ assert "@cf/meta/llama-3.3-70b-instruct" in response.json()["error"]["message"]
+ # Rejection must happen before we hand the model off to CF, or the gateway eats the
+ # real CF bill while billing the user the flat fallback.
+ 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")
+ def test_previous_response_id_rejected_for_cf_model(
+ self,
+ mock_ensure_configured: MagicMock,
+ mock_make_call: MagicMock,
+ authenticated_client: TestClient,
+ ) -> None:
+ # The Responses->chat/completions bridge rebuilds prior turns from litellm proxy spend logs,
+ # which this SDK-mode gateway doesn't have — so previous_response_id would silently drop
+ # conversation context. Reject it explicitly rather than answer with lost history.
+ response = authenticated_client.post(
+ "/v1/responses",
+ json={
+ "model": "@cf/zai-org/glm-5.2",
+ "input": "Hello",
+ "previous_response_id": "resp_abc123",
+ },
+ headers={"Authorization": "Bearer phx_test_key"},
+ )
+
+ assert response.status_code == 400
+ assert response.json()["error"]["type"] == "invalid_request_error"
+ assert "previous_response_id" in response.json()["error"]["message"]
+ # Rejected before any CF hand-off.
+ 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")
+ def test_tools_rejected_for_cf_model(
+ self,
+ mock_ensure_configured: MagicMock,
+ mock_make_call: MagicMock,
+ authenticated_client: TestClient,
+ ) -> None:
+ # The Responses->chat/completions bridge doesn't faithfully translate Responses-shaped
+ # tools, so CF's chat/completions endpoint would reject them. Reject up front instead of
+ # handing CF a request that fails the moment tools are advertised.
+ response = authenticated_client.post(
+ "/v1/responses",
+ json={
+ "model": "@cf/zai-org/glm-5.2",
+ "input": "Hello",
+ "tools": [{"type": "function", "function": {"name": "get_weather", "parameters": {}}}],
+ },
+ headers={"Authorization": "Bearer phx_test_key"},
+ )
+
+ assert response.status_code == 400
+ assert response.json()["error"]["type"] == "invalid_request_error"
+ assert "tools" in response.json()["error"]["message"]
+ # Rejected before any CF hand-off.
+ mock_ensure_configured.assert_not_called()
+ mock_make_call.assert_not_called()
+
+
class TestUnsupportedModelRejection:
"""Gemini/Vertex models must be rejected before reaching litellm, which would
otherwise raise ImportError from vertex_llm_base because we don't install