: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(gateway): add cloudflare provider (#59961)
Joshua Snyder0892c22441ce
diff --git a/.github/workflows/ci-llm-gateway.yml b/.github/workflows/ci-llm-gateway.ymlindex 9da9e2bd187a..72b19907a9a6 100644--- a/.github/workflows/ci-llm-gateway.yml+++ b/.github/workflows/ci-llm-gateway.yml@@ -54,7 +54,7 @@ jobs:needs: changesif: needs.changes.outputs.llm_gateway == 'true'runs-on: ubuntu-latest- timeout-minutes: 10+ timeout-minutes: 15defaults:run:working-directory: services/llm-gateway@@ -83,6 +83,8 @@ jobs:OPENROUTER_API_KEY: ${{ secrets.OPENROUTER_API_KEY }}FIREWORKS_API_KEY: ${{ secrets.FIREWORKS_API_KEY }}AWS_DEFAULT_REGION: us-east-1+ CLOUDFLARE_API_KEY: ${{ secrets.CLOUDFLARE_LLM_GATEWAY_TOKEN }}+ CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}run: uv run pytest tests/ -v --tb=short --junitxml=junit.xml- name: Upload test resultsdiff --git a/services/llm-gateway/src/llm_gateway/api/anthropic.py b/services/llm-gateway/src/llm_gateway/api/anthropic.pyindex 0191a9a67bbf..fedc47a2c804 100644--- a/services/llm-gateway/src/llm_gateway/api/anthropic.py+++ b/services/llm-gateway/src/llm_gateway/api/anthropic.py@@ -1,7 +1,8 @@import asyncio+import jsonimport timefrom collections.abc import AsyncIterator-from typing import Any+from typing import Any, castimport httpximport litellm@@ -13,6 +14,7 @@ from fastapi.responses import StreamingResponsefrom llm_gateway.api.handler import (ANTHROPIC_CONFIG,BEDROCK_CONFIG,+ CLOUDFLARE_ANTHROPIC_CONFIG,_sanitize_request_data,handle_llm_request,normalize_litellm_model_name,@@ -24,6 +26,12 @@ from llm_gateway.bedrock import (map_to_bedrock_model,)from llm_gateway.circuit_breaker import AnthropicCircuitBreaker+from llm_gateway.cloudflare import (+ cloudflare_litellm_model,+ ensure_cloudflare_configured,+ ensure_cloudflare_model_allowed,+ make_cloudflare_anthropic_call,+)from llm_gateway.config import get_settingsfrom llm_gateway.dependencies import AnthropicCircuitBreakerDep, RateLimitedUserfrom llm_gateway.metrics.prometheus import (@@ -202,6 +210,31 @@ def strip_server_side_tools(data: dict[str, Any], *, model: str, product: str) -del data["tools"]+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,@@ -286,7 +319,8 @@ def _wrap_stream_with_breaker(success = Truetry:async for chunk in inner:- yield chunk+ # body_iterator types loosely as str|bytes|memoryview; our upstream only emits bytes.+ yield cast(bytes, chunk)except asyncio.CancelledError:# Client disconnect — neither success nor failure of Anthropic.raise@@ -318,6 +352,9 @@ async def _handle_anthropic_messages(provider = _get_provider_from_headers(request)use_bedrock_fallback = _get_use_bedrock_fallback_from_headers(request)+ if provider == "cloudflare":+ return await _send_cloudflare_messages(data, user, body.stream or False, product)+if provider == "bedrock":return await _send_bedrock_messages(data, user, request, body.stream or False, product)@@ -386,6 +423,22 @@ async def _handle_count_tokens(provider = _get_provider_from_headers(request)use_bedrock_fallback = _get_use_bedrock_fallback_from_headers(request)+ if provider == "cloudflare":+ 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)+ try:+ count = await asyncio.to_thread(litellm.token_counter, model=aliased_model, text=json.dumps(data))+ except Exception as exc:+ logger.exception("cloudflare_count_tokens_failed", model=body.model)+ raise HTTPException(+ status_code=502,+ detail={"error": {"message": "Failed to count tokens", "type": "internal_error"}},+ ) from exc+ return {"input_tokens": count}+if provider == "bedrock":return await _bedrock_count_tokens_impl(data, body.model, user, product)diff --git a/services/llm-gateway/src/llm_gateway/api/handler.py b/services/llm-gateway/src/llm_gateway/api/handler.pyindex 8e7121cd9e1c..4af18dda8342 100644--- a/services/llm-gateway/src/llm_gateway/api/handler.py+++ b/services/llm-gateway/src/llm_gateway/api/handler.py@@ -45,6 +45,9 @@ BEDROCK_CONFIG = ProviderConfig(name="bedrock", endpoint_name="bedrock_messages"OPENAI_CONFIG = ProviderConfig(name="openai", endpoint_name="chat_completions")OPENAI_RESPONSES_CONFIG = ProviderConfig(name="openai", endpoint_name="responses")OPENAI_TRANSCRIPTION_CONFIG = ProviderConfig(name="openai", endpoint_name="audio_transcriptions")+# 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")_KNOWN_LITELLM_PROVIDER_PREFIXES = ("anthropic/",@@ -62,13 +65,13 @@ def normalize_litellm_model_name(model: str, provider: str) -> str:return f"{provider}/{model}"-# Google providers require litellm[google], which we don't install. Reject these-# at the edge so litellm doesn't crash deep in vertex_llm_base with an ImportError.-# Match both explicit provider prefixes (gemini/foo, vertex_ai/foo) and bare names-# that litellm will route to vertex/gemini — most commonly anything starting with-# "gemini-" (e.g. "gemini-3-pro-preview") — since those may not yet be in the cost-# registry when brand new.-_UNSUPPORTED_PROVIDERS = frozenset({"vertex_ai", "vertex_ai-language-models", "gemini"})+# Block model prefixes that would route to a provider we don't call via the generic path:+# - Google needs litellm[google] (not installed) — would crash in vertex_llm_base with ImportError.+# - Native `cloudflare/...` bypasses per-call credential injection and the CLOUDFLARE_ALLOWED_MODELS+# allowlist the `@cf/...` path enforces — reject so callers can't smuggle models onto gateway creds.+# Matches explicit prefixes (gemini/, vertex_ai/) and bare gemini- names litellm routes to vertex/gemini,+# which may not be in the cost registry yet when brand new.+_UNSUPPORTED_PROVIDERS = frozenset({"vertex_ai", "vertex_ai-language-models", "gemini", "cloudflare"})_UNSUPPORTED_MODEL_PREFIXES = (*(f"{p}/" for p in _UNSUPPORTED_PROVIDERS),"gemini-",@@ -98,18 +101,15 @@ def _raise_if_unsupported_model(model: str) -> None:_raise_unsupported_model(model)-# Parameters that control LLM client routing/authentication.-# These must never be accepted from user input to prevent request-# redirection and API key exfiltration.+# LLM routing/auth params — never accept from user input (request redirection, key exfiltration).FORBIDDEN_REQUEST_PARAMS = frozenset({"api_key", "api_base", "base_url", "api_version", "organization", "model_list", "fallbacks", "custom_llm_provider"})def _sanitize_request_value(value: Any) -> Any:- # Recursively strip forbidden params from nested dicts and lists.- # litellm forwards nested params (e.g. model_list[*].litellm_params.api_key)- # to the upstream provider, so a shallow filter is insufficient.+ # Strip recursively: litellm forwards nested params (e.g. model_list[*].litellm_params.api_key)+ # to the provider, so a shallow filter is insufficient.if isinstance(value, dict):return {k: _sanitize_request_value(v) for k, v in value.items() if k not in FORBIDDEN_REQUEST_PARAMS}if isinstance(value, list):diff --git a/services/llm-gateway/src/llm_gateway/api/openai.py b/services/llm-gateway/src/llm_gateway/api/openai.pyindex 1d0b4b35b3ec..ca49ef954b81 100644--- a/services/llm-gateway/src/llm_gateway/api/openai.py+++ b/services/llm-gateway/src/llm_gateway/api/openai.py@@ -5,12 +5,19 @@ from fastapi import APIRouter, File, Form, HTTPException, Request, UploadFilefrom fastapi.responses import StreamingResponsefrom llm_gateway.api.handler import (+ CLOUDFLARE_OPENAI_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,+ make_cloudflare_completion_call,+)+from llm_gateway.config import get_settingsfrom llm_gateway.dependencies import RateLimitedUserfrom llm_gateway.models.openai import ChatCompletionRequest, ResponsesRequest, TranscriptionRequestfrom llm_gateway.products.config import validate_product@@ -19,6 +26,10 @@ from llm_gateway.request_context import apply_posthog_context_from_headersopenai_router = APIRouter()+def _is_cloudflare_model(model: str) -> bool:+ return model.startswith("@cf/")++async def _handle_chat_completions(body: ChatCompletionRequest,user: RateLimitedUser,@@ -26,6 +37,20 @@ async def _handle_chat_completions() -> dict[str, Any] | StreamingResponse: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 handle_llm_request(request_data=data,user=user,@@ -161,7 +186,7 @@ async def _handle_transcription(request = TranscriptionRequest(model=normalized_model, file=file_tuple, language=language)- # is_streaming=False, so handle_llm_request always returns a dict here, never a StreamingResponse.+ # is_streaming=False always yields a dict, never a StreamingResponse.return cast(dict[str, Any],await handle_llm_request(diff --git a/services/llm-gateway/src/llm_gateway/callbacks/posthog.py b/services/llm-gateway/src/llm_gateway/callbacks/posthog.pyindex d29828d8bc08..b66a986f821f 100644--- a/services/llm-gateway/src/llm_gateway/callbacks/posthog.py+++ b/services/llm-gateway/src/llm_gateway/callbacks/posthog.py@@ -11,6 +11,7 @@ from posthoganalytics import Posthogfrom llm_gateway.auth.models import resolve_distinct_idfrom llm_gateway.callbacks.base import InstrumentedCallbackfrom llm_gateway.products.config import get_product_config+from llm_gateway.rate_limiting.cost_refresh import normalize_metric_labelsfrom llm_gateway.request_context import (get_auth_user,get_posthog_flags,@@ -194,9 +195,14 @@ class PostHogCallback(InstrumentedCallback):is_streaming = standard_logging_object.get("stream", False)usage_object = (standard_logging_object.get("metadata") or {}).get("usage_object") or {}+ ai_provider, ai_model = normalize_metric_labels(+ standard_logging_object.get("model", ""),+ standard_logging_object.get("custom_llm_provider", ""),+ )+properties: dict[str, Any] = {- "$ai_model": standard_logging_object.get("model", ""),- "$ai_provider": standard_logging_object.get("custom_llm_provider", ""),+ "$ai_model": ai_model,+ "$ai_provider": ai_provider,"$ai_input": _replace_binary_content(standard_logging_object.get("messages")),"$ai_input_tokens": standard_logging_object.get("prompt_tokens", 0),"$ai_output_tokens": standard_logging_object.get("completion_tokens", 0),diff --git a/services/llm-gateway/src/llm_gateway/callbacks/prometheus.py b/services/llm-gateway/src/llm_gateway/callbacks/prometheus.pyindex 044ecb282b73..13677a1ccdb5 100644--- a/services/llm-gateway/src/llm_gateway/callbacks/prometheus.py+++ b/services/llm-gateway/src/llm_gateway/callbacks/prometheus.py@@ -15,6 +15,7 @@ from llm_gateway.metrics.prometheus import (TOKENS_OUTPUT,TOKENS_REASONING,)+from llm_gateway.rate_limiting.cost_refresh import normalize_metric_labelsfrom llm_gateway.request_context import get_auth_user, get_product@@ -31,8 +32,9 @@ class PrometheusCallback(InstrumentedCallback):usage_object = metadata.get("usage_object", {}) or {}cost_breakdown = standard_logging_object.get("cost_breakdown", {}) or {}- provider = standard_logging_object.get("custom_llm_provider", "unknown")- model = standard_logging_object.get("model", "unknown")+ litellm_provider = standard_logging_object.get("custom_llm_provider", "unknown")+ litellm_model = standard_logging_object.get("model", "unknown")+ provider, model = normalize_metric_labels(litellm_model, litellm_provider)product = get_product()is_streaming = standard_logging_object.get("stream", False)diff --git a/services/llm-gateway/src/llm_gateway/callbacks/rate_limiting.py b/services/llm-gateway/src/llm_gateway/callbacks/rate_limiting.pyindex 1a0fe086ec0c..a53cca158bf1 100644--- a/services/llm-gateway/src/llm_gateway/callbacks/rate_limiting.py+++ b/services/llm-gateway/src/llm_gateway/callbacks/rate_limiting.py@@ -8,6 +8,7 @@ import structlogfrom llm_gateway.callbacks.base import InstrumentedCallbackfrom llm_gateway.config import get_settingsfrom llm_gateway.metrics.prometheus import COST_ESTIMATED, COST_FALLBACK_DEFAULT, COST_MISSING, COST_RECORDED+from llm_gateway.rate_limiting.cost_refresh import normalize_metric_labelsfrom llm_gateway.request_context import get_product, record_costlogger = structlog.get_logger(__name__)@@ -45,8 +46,11 @@ class RateLimitCallback(InstrumentedCallback):) -> None:standard_logging_object = kwargs.get("standard_logging_object", {})response_cost = standard_logging_object.get("response_cost")- model = standard_logging_object.get("model", "unknown")- provider = standard_logging_object.get("custom_llm_provider", "unknown")+ # Keep the litellm-view model for cost lookups (litellm.model_cost is keyed+ # on the aliased name), but use the user-facing labels for metric emission.+ litellm_model = standard_logging_object.get("model", "unknown")+ litellm_provider = standard_logging_object.get("custom_llm_provider", "unknown")+ provider, model = normalize_metric_labels(litellm_model, litellm_provider)product = get_product()input_tokens = standard_logging_object.get("prompt_tokens")output_tokens = standard_logging_object.get("completion_tokens")@@ -65,7 +69,7 @@ class RateLimitCallback(InstrumentedCallback):COST_RECORDED.labels(provider=provider, model=model, product=product).inc(response_cost)return- estimated_cost = estimate_cost_from_tokens(model, input_tokens, output_tokens)+ estimated_cost = estimate_cost_from_tokens(litellm_model, input_tokens, output_tokens)if estimated_cost and estimated_cost > 0:logger.debug(diff --git a/services/llm-gateway/src/llm_gateway/cloudflare.py b/services/llm-gateway/src/llm_gateway/cloudflare.pynew file mode 100644index 000000000000..56f6cb2f6327--- /dev/null+++ b/services/llm-gateway/src/llm_gateway/cloudflare.py@@ -0,0 +1,90 @@+from __future__ import annotations++from collections.abc import Awaitable, Callable+from typing import Any++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+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/"+++def cloudflare_litellm_model(model: str) -> str:+ """The litellm model id CF requests route under (its OpenAI-compatible prefix)."""+ return f"{_CF_LITELLM_PREFIX}{model}"+++# Restrict `@cf/...` routing to models we've priced in COST_ALIASES. Unpriced models fall through+# to `default_fallback_cost_usd`, so the gateway would eat the real CF bill while charging the user+# a flat fallback. Derived from COST_ALIASES so the two can't drift — registering an alias auto-allows+# it, and you can't route a model without pricing it first.+CLOUDFLARE_ALLOWED_MODELS: frozenset[str] = frozenset(+ alias.removeprefix(_CF_LITELLM_PREFIX) for alias in COST_ALIASES if alias.startswith(f"{_CF_LITELLM_PREFIX}@cf/")+)+++def cloudflare_api_base(account_id: str) -> str:+ return f"https://api.cloudflare.com/client/v4/accounts/{account_id}/ai/v1"+++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:+ raise HTTPException(+ status_code=503,+ detail={"error": {"message": "Cloudflare Workers AI not configured", "type": "configuration_error"}},+ )+ return cloudflare_api_base(settings.cloudflare_account_id), settings.cloudflare_api_key+++def ensure_cloudflare_model_allowed(model: str) -> None:+ """Reject CF models we haven't explicitly priced — see CLOUDFLARE_ALLOWED_MODELS."""+ if model not in CLOUDFLARE_ALLOWED_MODELS:+ raise HTTPException(+ status_code=400,+ detail={+ "error": {+ "message": f"Model '{model}' is not supported on the cloudflare provider",+ "type": "invalid_request_error",+ }+ },+ )+++def _inject_cloudflare_params(kwargs: dict[str, Any], api_base: str, api_key: str) -> None:+ kwargs["api_base"] = api_base+ kwargs["api_key"] = api_key+ kwargs["model"] = cloudflare_litellm_model(kwargs["model"])+++def make_cloudflare_anthropic_call(api_base: str, api_key: str) -> Callable[..., Awaitable[Any]]:+ """Build an llm_call that adapts Anthropic Messages format to Cloudflare Workers AI.++ Uses litellm's built-in adapter to translate Anthropic <-> OpenAI chat/completions+ format, routing through CF's OpenAI-compatible endpoint.+ """++ async def llm_call(**kwargs: Any) -> Any:+ _inject_cloudflare_params(kwargs, api_base, api_key)+ return await LiteLLMMessagesToCompletionTransformationHandler.async_anthropic_messages_handler(**kwargs)++ return llm_call+++def make_cloudflare_completion_call(api_base: str, api_key: str) -> Callable[..., Awaitable[Any]]:+ """Build an llm_call that routes OpenAI chat/completions requests to Cloudflare."""++ async def llm_call(**kwargs: Any) -> Any:+ _inject_cloudflare_params(kwargs, api_base, api_key)+ return await litellm.acompletion(**kwargs)++ return llm_calldiff --git a/services/llm-gateway/src/llm_gateway/config.py b/services/llm-gateway/src/llm_gateway/config.pyindex ae8e12d42487..02f9d120c5f1 100644--- a/services/llm-gateway/src/llm_gateway/config.py+++ b/services/llm-gateway/src/llm_gateway/config.py@@ -138,15 +138,15 @@ class Settings(BaseSettings):openai_organization: str | None = Noneopenrouter_api_key: str | None = Nonefireworks_api_key: str | None = None+ cloudflare_api_key: str | None = None+ cloudflare_account_id: str | None = None# Project token for AI observability eventsposthog_project_token: str | None = Noneposthog_host: str = "https://us.i.posthog.com"- # Optional secondary capture target. When set, every $ai_generation event- # is mirrored to this PostHog instance after the primary capture, so the- # EU deployment can land EU customer events on EU PostHog (team_id=1)- # for the regional billing usage_report to attribute them.+ # Optional secondary capture target — mirrors every $ai_generation after the primary,+ # so the EU deployment lands EU events on EU PostHog (team_id=1) for regional billing.posthog_secondary_project_token: str | None = Noneposthog_secondary_host: str | None = None@@ -173,17 +173,14 @@ class Settings(BaseSettings):posthog_api_base_url: str = "https://us.posthog.com"plan_cache_ttl: int = 900 # 15 minutes- # Billing recomputes quota state on at most an hourly cadence, so we are- # comfortable letting a team go slightly over their limit in exchange for- # avoiding a Django roundtrip on every billable request.+ # Billing recomputes quota at most hourly, so we tolerate slight overage rather than+ # a Django roundtrip on every billable request.quota_cache_ttl: int = 300 # 5 minutesbilling_period_days: int = 30- # Anthropic -> Bedrock circuit breaker. When the trailing failure rate of the Anthropic- # path crosses `failure_threshold` (with at least `min_requests` observations in the- # window), the breaker is "open": each request that has opted in to Bedrock fallback- # gets routed straight to Bedrock with probability `bypass_probability`, leaving the- # remainder as probe traffic to detect recovery.+ # Anthropic → Bedrock circuit breaker. When the trailing failure rate crosses `failure_threshold`+ # (over ≥ `min_requests` in the window), the breaker opens: opted-in requests route straight to+ # Bedrock with probability `bypass_probability`, the rest stay as probe traffic to detect recovery.anthropic_circuit_breaker_enabled: bool = Trueanthropic_circuit_breaker_failure_threshold: float = 0.25anthropic_circuit_breaker_window_seconds: int = 300diff --git a/services/llm-gateway/src/llm_gateway/main.py b/services/llm-gateway/src/llm_gateway/main.pyindex e461c54d4e0c..5c9e1529a417 100644--- a/services/llm-gateway/src/llm_gateway/main.py+++ b/services/llm-gateway/src/llm_gateway/main.py@@ -132,6 +132,11 @@ def export_provider_credentials(settings: Settings) -> None:os.environ["OPENROUTER_API_KEY"] = settings.openrouter_api_keyif settings.fireworks_api_key:os.environ["FIREWORKS_API_KEY"] = settings.fireworks_api_key+ # Cloudflare credentials are deliberately *not* exported. Our CF path injects+ # api_key/api_base per-call through cloudflare.make_cloudflare_*_call, while+ # exporting CLOUDFLARE_API_KEY/ACCOUNT_ID would let litellm's native+ # `cloudflare/...` provider pick them up on the generic openai path and+ # bypass the CLOUDFLARE_ALLOWED_MODELS allowlist.@asynccontextmanagerdiff --git a/services/llm-gateway/src/llm_gateway/rate_limiting/cost_refresh.py b/services/llm-gateway/src/llm_gateway/rate_limiting/cost_refresh.pyindex f730927ab81f..20567a82d3ae 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@@ -1,6 +1,7 @@from __future__ import annotationsimport time+from typing import Anyimport litellmimport structlog@@ -13,6 +14,51 @@ logger = structlog.get_logger(__name__)CACHE_TTL_SECONDS = 300+# Models on non-canonical litellm providers (e.g. Cloudflare via openai/ prefix) don't match their+# cost map entry. Map the key we pass to litellm → the canonical cost-map key.+#+# CF entries: litellm publishes per-model CF prices only for a few legacy Llama-2/Mistral variants,+# so we alias to the vendor's direct rate (e.g. moonshot/kimi-k2.6) as a proxy — not CF's actual+# resold rate, and may drift if CF adds markup or flat-rate billing.+COST_ALIASES: dict[str, str] = {+ "openai/@cf/moonshotai/kimi-k2.6": "moonshot/kimi-k2.6",+}++# For aliased models, litellm's reported (provider, model) labels don't match what the user asked+# for. Map the litellm-view model key → the user-facing (provider, model) pair to emit in metrics.+# Separate from COST_ALIASES: cost lookups key on litellm.model_cost, metric labels on user intent.+ALIAS_METRIC_LABELS: dict[str, tuple[str, str]] = {+ "openai/@cf/moonshotai/kimi-k2.6": ("cloudflare", "@cf/moonshotai/kimi-k2.6"),+}+++def normalize_metric_labels(litellm_model: str, litellm_provider: str) -> tuple[str, str]:+ """Translate the (provider, model) labels litellm sees into the user-facing+ (provider, model) we want in metrics. Returns (provider, model).+ """+ override = ALIAS_METRIC_LABELS.get(litellm_model)+ if override is None:+ return litellm_provider, litellm_model+ return override+++def apply_cost_aliases(model_cost: dict[str, Any]) -> None:+ """Add alias keys for non-canonical provider routings. Prefer `set_litellm_model_cost`."""+ for alias, canonical in COST_ALIASES.items():+ if alias in model_cost:+ continue+ if canonical in model_cost:+ # Shallow copy so a future in-place mutation under one key doesn't bleed into the other.+ model_cost[alias] = dict(model_cost[canonical])+ else:+ logger.warning("cost_alias_canonical_missing", alias=alias, canonical=canonical)+++def set_litellm_model_cost(model_cost: dict[str, Any]) -> None:+ """Single writer for `litellm.model_cost` — applies aliases atomically."""+ apply_cost_aliases(model_cost)+ litellm.model_cost = model_cost+class CostRefreshService:"""Singleton service that periodically refreshes litellm.model_cost."""@@ -41,9 +87,8 @@ class CostRefreshService:try:model_cost = get_model_cost_map(url=model_cost_map_url)apply_model_cost_overrides(model_cost)- litellm.model_cost = model_cost- # Provider sets (anthropic_models, etc.) back get_llm_provider's inference- # for bare names — without re-running this they stay frozen at import time.+ set_litellm_model_cost(model_cost)+ # Re-register provider sets (anthropic_models, etc.); else they stay frozen at import time.litellm.add_known_models(model_cost)self._last_refresh = time.monotonic()logger.info("model_cost_refreshed", model_count=len(model_cost))diff --git a/services/llm-gateway/src/llm_gateway/rate_limiting/model_cost_service.py b/services/llm-gateway/src/llm_gateway/rate_limiting/model_cost_service.pyindex 9265b9a33088..43664a11bba6 100644--- a/services/llm-gateway/src/llm_gateway/rate_limiting/model_cost_service.py+++ b/services/llm-gateway/src/llm_gateway/rate_limiting/model_cost_service.py@@ -8,6 +8,7 @@ import structlogfrom litellm import model_cost_map_urlfrom litellm.litellm_core_utils.get_model_cost_map import get_model_cost_map+from llm_gateway.rate_limiting.cost_refresh import set_litellm_model_costfrom llm_gateway.rate_limiting.model_cost_overrides import apply_model_cost_overrideslogger = structlog.get_logger(__name__)@@ -76,13 +77,15 @@ class ModelCostService:cls._instance = Nonedef _should_refresh(self) -> bool:+ if self._last_refresh == 0:+ return Truereturn time.monotonic() - self._last_refresh > CACHE_TTL_SECONDSdef _refresh_cache(self) -> None:try:model_cost = get_model_cost_map(url=model_cost_map_url)apply_model_cost_overrides(model_cost)- litellm.model_cost = model_cost+ set_litellm_model_cost(model_cost)# Keep provider sets in sync — see cost_refresh.py.litellm.add_known_models(model_cost)self._costs = cast(dict[str, ModelCost], model_cost)diff --git a/services/llm-gateway/src/llm_gateway/request_context.py b/services/llm-gateway/src/llm_gateway/request_context.pyindex d5f40faec526..b816d0ff43f8 100644--- a/services/llm-gateway/src/llm_gateway/request_context.py+++ b/services/llm-gateway/src/llm_gateway/request_context.py@@ -20,6 +20,8 @@ POSTHOG_FLAG_PREFIX = "x-posthog-flag-"POSTHOG_PROVIDER_HEADER = "x-posthog-provider"POSTHOG_USE_BEDROCK_FALLBACK_HEADER = "x-posthog-use-bedrock-fallback"+_VALID_PROVIDERS = ("anthropic", "bedrock", "cloudflare")+@dataclassclass RequestContext:@@ -111,13 +113,12 @@ def extract_posthog_provider_from_headers(request: Request) -> str | None:if provider is None:return None+ expected = f"Expected one of: {', '.join(_VALID_PROVIDERS)}."normalized_provider = provider.strip().lower()if not normalized_provider:- raise ValueError(f"Invalid {POSTHOG_PROVIDER_HEADER} header value. Expected one of: anthropic, bedrock.")- if normalized_provider not in {"anthropic", "bedrock"}:- raise ValueError(- f"Invalid {POSTHOG_PROVIDER_HEADER} header value '{provider}'. Expected one of: anthropic, bedrock."- )+ raise ValueError(f"Invalid {POSTHOG_PROVIDER_HEADER} header value. {expected}")+ if normalized_provider not in _VALID_PROVIDERS:+ raise ValueError(f"Invalid {POSTHOG_PROVIDER_HEADER} header value '{provider}'. {expected}")return normalized_providerdiff --git a/services/llm-gateway/tests/integration/conftest.py b/services/llm-gateway/tests/integration/conftest.pyindex b4548529cf09..58d73702124a 100644--- a/services/llm-gateway/tests/integration/conftest.py+++ b/services/llm-gateway/tests/integration/conftest.py@@ -17,6 +17,8 @@ OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")ANTHROPIC_API_KEY = os.environ.get("ANTHROPIC_API_KEY")OPENROUTER_API_KEY = os.environ.get("OPENROUTER_API_KEY")FIREWORKS_API_KEY = os.environ.get("FIREWORKS_API_KEY")+CLOUDFLARE_API_KEY = os.environ.get("CLOUDFLARE_API_KEY")+CLOUDFLARE_ACCOUNT_ID = os.environ.get("CLOUDFLARE_ACCOUNT_ID")BEDROCK_REGION = (os.environ.get("LLM_GATEWAY_BEDROCK_REGION_NAME")or os.environ.get("AWS_REGION")@@ -24,6 +26,13 @@ BEDROCK_REGION = ()TEST_POSTHOG_API_KEY = "phx_fake_personal_api_key"+# Cloudflare Workers AI runs serverless and is slow + high-variance (cold starts on a large model+# can push a single completion past 3 minutes). Bound each CF call and disable SDK-level retries so+# a slow response can't blow the integration suite's CI time budget. The clients that talk to other+# providers keep the SDK defaults.+CLOUDFLARE_REQUEST_TIMEOUT = 120.0+CLOUDFLARE_MAX_RETRIES = 0+MOCK_MODEL_COSTS = {"gpt-4o": {"litellm_provider": "openai",@@ -81,6 +90,15 @@ MOCK_MODEL_COSTS = {"input_cost_per_token": 0.0000002,"output_cost_per_token": 0.0000002,},+ "openai/@cf/moonshotai/kimi-k2.6": {+ "litellm_provider": "openai",+ "max_input_tokens": 262144,+ "supports_vision": True,+ "supports_function_calling": True,+ "mode": "chat",+ "input_cost_per_token": 0.00000095,+ "output_cost_per_token": 0.000004,+ },}@@ -132,6 +150,13 @@ def run_gateway_server(configure_all_providers: bool = False, bedrock_region_namenv_patches["ANTHROPIC_API_KEY"] = "sk-ant-test-fake-key"env_patches["OPENROUTER_API_KEY"] = "or-test-fake-key"env_patches["FIREWORKS_API_KEY"] = "fw-test-fake-key"+ # Only LLM_GATEWAY_-prefixed vars are needed — Pydantic Settings reads them into+ # `settings.cloudflare_*`. Raw CLOUDFLARE_* vars aren't exported: the CF path injects creds+ # per-call, and exporting them would let litellm's native `cloudflare/...` provider pick them up.+ if CLOUDFLARE_API_KEY:+ env_patches["LLM_GATEWAY_CLOUDFLARE_API_KEY"] = CLOUDFLARE_API_KEY+ if CLOUDFLARE_ACCOUNT_ID:+ env_patches["LLM_GATEWAY_CLOUDFLARE_ACCOUNT_ID"] = CLOUDFLARE_ACCOUNT_IDwith patch.dict(os.environ, env_patches):get_settings.cache_clear()@@ -219,3 +244,30 @@ def bedrock_anthropic_client(bedrock_gateway_url):base_url=bedrock_gateway_url,default_headers={"X-PostHog-Provider": "bedrock"},)+++def cloudflare_gateway_url():+ with run_gateway_server() as url:+ yield url+++def cloudflare_anthropic_client(cloudflare_gateway_url):+ return Anthropic(+ api_key=TEST_POSTHOG_API_KEY,+ base_url=cloudflare_gateway_url,+ default_headers={"X-PostHog-Provider": "cloudflare"},+ timeout=CLOUDFLARE_REQUEST_TIMEOUT,+ max_retries=CLOUDFLARE_MAX_RETRIES,+ )+++def cloudflare_openai_client(cloudflare_gateway_url):+ return OpenAI(+ api_key=TEST_POSTHOG_API_KEY,+ base_url=f"{cloudflare_gateway_url}/v1",+ timeout=CLOUDFLARE_REQUEST_TIMEOUT,+ max_retries=CLOUDFLARE_MAX_RETRIES,+ )diff --git a/services/llm-gateway/tests/integration/test_anthropic_sdk.py b/services/llm-gateway/tests/integration/test_anthropic_sdk.pyindex 5460a91456bb..f46fdc9d4544 100644--- a/services/llm-gateway/tests/integration/test_anthropic_sdk.py+++ b/services/llm-gateway/tests/integration/test_anthropic_sdk.py@@ -17,15 +17,43 @@ import pytestfrom anthropic import Anthropic, BadRequestErrorfrom anthropic.types import TextBlock, ToolParam, ToolUseBlock-from .conftest import BEDROCK_REGION, TEST_POSTHOG_API_KEY+from .conftest import (+ BEDROCK_REGION,+ CLOUDFLARE_ACCOUNT_ID,+ CLOUDFLARE_API_KEY,+ CLOUDFLARE_MAX_RETRIES,+ CLOUDFLARE_REQUEST_TIMEOUT,+ TEST_POSTHOG_API_KEY,+)ANTHROPIC_API_KEY = os.environ.get("ANTHROPIC_API_KEY")+CLOUDFLARE_CONFIGURED = bool(CLOUDFLARE_API_KEY and CLOUDFLARE_ACCOUNT_ID)TEST_IMAGE_URL = "https://posthog.com/brand/posthog-logo.png"+pytestmark = pytest.mark.xfail(strict=False, reason="Anthropic may be rate-limited or temporarily unavailable")+def _get_text_block(response) -> TextBlock:+ """Extract the first TextBlock from a response, skipping ThinkingBlocks."""+ for block in response.content:+ if isinstance(block, TextBlock):+ return block+ raise AssertionError(f"No TextBlock found in response content: {response.content}")+++def _skip_cloudflare_full_matrix(provider: str) -> None:+ """Smoke-test the Cloudflare routing path, don't run the whole behavioural matrix against it.++ CF Workers AI calls are slow and high-variance, so running every SDK behaviour against them+ blows the CI time budget. The adapter paths that matter (non-streaming, streaming, tool use)+ are smoke-tested elsewhere in this file; the rest of the matrix is covered by the other providers.+ """+ if provider == "cloudflare":+ pytest.skip("Cloudflare routing covered by smoke tests; skipping full matrix to bound CI time")++@dataclassclass SDKTestConfig:client: Anthropic@@ -45,6 +73,11 @@ class SDKTestConfig:id="bedrock",marks=pytest.mark.skipif(not BEDROCK_REGION, reason="Bedrock region not configured"),),+ pytest.param(+ "cloudflare",+ id="cloudflare",+ marks=pytest.mark.skipif(not CLOUDFLARE_CONFIGURED, reason="CLOUDFLARE_API_KEY/ACCOUNT_ID not set"),+ ),])def sdk_config(request) -> SDKTestConfig:@@ -52,6 +85,16 @@ def sdk_config(request) -> SDKTestConfig:url = request.getfixturevalue("gateway_url")client = Anthropic(api_key=TEST_POSTHOG_API_KEY, base_url=url)return SDKTestConfig(client=client, model="claude-haiku-4-5-20251001", provider="anthropic")+ elif request.param == "cloudflare":+ url = request.getfixturevalue("cloudflare_gateway_url")+ client = Anthropic(+ api_key=TEST_POSTHOG_API_KEY,+ base_url=url,+ default_headers={"X-PostHog-Provider": "cloudflare"},+ timeout=CLOUDFLARE_REQUEST_TIMEOUT,+ max_retries=CLOUDFLARE_MAX_RETRIES,+ )+ return SDKTestConfig(client=client, model="@cf/moonshotai/kimi-k2.6", provider="cloudflare")else:url = request.getfixturevalue("bedrock_gateway_url")client = Anthropic(@@ -67,14 +110,13 @@ class TestAnthropicMessages:response = sdk_config.client.messages.create(model=sdk_config.model,messages=[{"role": "user", "content": "Say 'hello' and nothing else."}],- max_tokens=10,+ max_tokens=300,)assert response is not Noneassert len(response.content) > 0- first_block = response.content[0]- assert isinstance(first_block, TextBlock)- assert first_block.text is not None+ text_block = _get_text_block(response)+ assert text_block.text is not Noneassert response.usage is not Noneassert response.usage.input_tokens > 0assert response.usage.output_tokens > 0@@ -83,7 +125,7 @@ class TestAnthropicMessages:with sdk_config.client.messages.stream(model=sdk_config.model,messages=[{"role": "user", "content": "Say 'hi' and nothing else."}],- max_tokens=10,+ max_tokens=300,) as stream:text = stream.get_final_text()@@ -91,70 +133,68 @@ class TestAnthropicMessages:assert len(text) > 0def test_with_system_message(self, sdk_config: SDKTestConfig):+ _skip_cloudflare_full_matrix(sdk_config.provider)response = sdk_config.client.messages.create(model=sdk_config.model,system="You are a helpful assistant that only says 'OK'.",messages=[{"role": "user", "content": "Hello"}],- max_tokens=10,+ max_tokens=300,)assert response is not None- first_block = response.content[0]- assert isinstance(first_block, TextBlock)- assert first_block.text is not None+ text_block = _get_text_block(response)+ assert text_block.text is not Nonedef test_with_temperature(self, sdk_config: SDKTestConfig):+ _skip_cloudflare_full_matrix(sdk_config.provider)response = sdk_config.client.messages.create(model=sdk_config.model,messages=[{"role": "user", "content": "Say 'test'"}],- max_tokens=10,+ max_tokens=300,temperature=0.0,)assert response is not None- first_block = response.content[0]- assert isinstance(first_block, TextBlock)- assert first_block.text is not None+ text_block = _get_text_block(response)+ assert text_block.text is not Noneclass TestAnthropicMultipleModels:- def test_haiku_request(self, sdk_config: SDKTestConfig):+ def test_basic_request(self, sdk_config: SDKTestConfig):+ _skip_cloudflare_full_matrix(sdk_config.provider)response = sdk_config.client.messages.create(model=sdk_config.model,messages=[{"role": "user", "content": "Say 'A'"}],- max_tokens=5,+ max_tokens=200,)assert response is not None- first_block = response.content[0]- assert isinstance(first_block, TextBlock)- assert first_block.text is not None+ text_block = _get_text_block(response)+ assert text_block.text is not Nonedef test_sequential_requests_same_model(self, sdk_config: SDKTestConfig):+ _skip_cloudflare_full_matrix(sdk_config.provider)response1 = sdk_config.client.messages.create(model=sdk_config.model,messages=[{"role": "user", "content": "Say '1'"}],- max_tokens=5,+ max_tokens=200,)response2 = sdk_config.client.messages.create(model=sdk_config.model,messages=[{"role": "user", "content": "Say '2'"}],- max_tokens=5,+ max_tokens=200,)- first_block1 = response1.content[0]- first_block2 = response2.content[0]- assert isinstance(first_block1, TextBlock)- assert isinstance(first_block2, TextBlock)- assert first_block1.text is not None- assert first_block2.text is not None+ assert _get_text_block(response1).text is not None+ assert _get_text_block(response2).text is not Nonedef test_streaming_then_non_streaming(self, sdk_config: SDKTestConfig):+ _skip_cloudflare_full_matrix(sdk_config.provider)with sdk_config.client.messages.stream(model=sdk_config.model,messages=[{"role": "user", "content": "Say 'stream'"}],- max_tokens=10,+ max_tokens=300,) as stream:text = stream.get_final_text()assert len(text) > 0@@ -162,11 +202,9 @@ class TestAnthropicMultipleModels:response = sdk_config.client.messages.create(model=sdk_config.model,messages=[{"role": "user", "content": "Say 'sync'"}],- max_tokens=10,+ max_tokens=300,)- first_block = response.content[0]- assert isinstance(first_block, TextBlock)- assert first_block.text is not None+ assert _get_text_block(response).text is not Noneclass TestAnthropicToolUse:@@ -203,6 +241,7 @@ class TestAnthropicToolUse:assert "location" in tool_use.inputdef test_tool_choice_forced(self, sdk_config: SDKTestConfig):+ _skip_cloudflare_full_matrix(sdk_config.provider)tools: list[ToolParam] = [{"name": "calculate",@@ -232,8 +271,8 @@ class TestAnthropicToolUse:class TestAnthropicVision:def test_image_url_input(self, sdk_config: SDKTestConfig):- if sdk_config.provider == "bedrock":- pytest.skip("Bedrock does not support URL image source")+ if sdk_config.provider in ("bedrock", "cloudflare"):+ pytest.skip(f"{sdk_config.provider} does not support URL image source via Anthropic format")response = sdk_config.client.messages.create(model=sdk_config.model,@@ -249,16 +288,17 @@ class TestAnthropicVision:],}],- max_tokens=50,+ max_tokens=200,)assert response is not Noneassert len(response.content) > 0- first_block = response.content[0]- assert isinstance(first_block, TextBlock)- assert first_block.text is not None+ text_block = _get_text_block(response)+ assert text_block.text is not Nonedef test_image_base64_input(self, sdk_config: SDKTestConfig):+ if sdk_config.provider == "cloudflare":+ pytest.skip("Cloudflare adapter does not support Anthropic vision content blocks")image_data = urlopen(TEST_IMAGE_URL).read()base64_image = base64.standard_b64encode(image_data).decode("utf-8")@@ -280,18 +320,18 @@ class TestAnthropicVision:],}],- max_tokens=100,+ max_tokens=300,)assert response is not Noneassert len(response.content) > 0- first_block = response.content[0]- assert isinstance(first_block, TextBlock)- assert first_block.text is not None+ text_block = _get_text_block(response)+ assert text_block.text is not Noneclass TestAnthropicMultiTurn:def test_conversation_history(self, sdk_config: SDKTestConfig):+ _skip_cloudflare_full_matrix(sdk_config.provider)response = sdk_config.client.messages.create(model=sdk_config.model,system="You are a helpful assistant. Be very brief.",@@ -300,13 +340,12 @@ class TestAnthropicMultiTurn:{"role": "assistant", "content": "Hello Alice!"},{"role": "user", "content": "What is my name?"},],- max_tokens=20,+ max_tokens=300,)assert response is not None- first_block = response.content[0]- assert isinstance(first_block, TextBlock)- assert "alice" in first_block.text.lower()+ text_block = _get_text_block(response)+ assert "alice" in text_block.text.lower()class TestAnthropicValidationErrors:@@ -320,6 +359,8 @@ class TestAnthropicValidationErrors:def test_invalid_parameters_rejected(self, sdk_config: SDKTestConfig, invalid_param: str, value: float, expected_error: str):+ if sdk_config.provider == "cloudflare":+ pytest.skip("Cloudflare Workers AI handles parameter validation differently")kwargs: dict[str, Any] = {"model": sdk_config.model,"messages": [{"role": "user", "content": "Hi"}],@@ -331,6 +372,8 @@ class TestAnthropicValidationErrors:assert expected_error in str(exc_info.value).lower()def test_empty_messages_rejected(self, sdk_config: SDKTestConfig):+ if sdk_config.provider == "cloudflare":+ pytest.skip("Cloudflare Workers AI handles parameter validation differently")with pytest.raises(BadRequestError) as exc_info:sdk_config.client.messages.create(model=sdk_config.model,diff --git a/services/llm-gateway/tests/integration/test_openai_sdk.py b/services/llm-gateway/tests/integration/test_openai_sdk.pyindex f0ad398fa3cf..58bc50546242 100644--- a/services/llm-gateway/tests/integration/test_openai_sdk.py+++ b/services/llm-gateway/tests/integration/test_openai_sdk.py@@ -7,6 +7,7 @@ Run with: pytest tests/integration/test_openai_sdk.py -vimport jsonimport os+from dataclasses import dataclassfrom typing import Anyimport pytest@@ -14,7 +15,10 @@ from openai import BadRequestError, OpenAIfrom openai.types import Modelfrom openai.types.chat import ChatCompletionToolChoiceOptionParam, ChatCompletionToolParam+from .conftest import CLOUDFLARE_ACCOUNT_ID, CLOUDFLARE_API_KEY+OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")+CLOUDFLARE_CONFIGURED = bool(CLOUDFLARE_API_KEY and CLOUDFLARE_ACCOUNT_ID)skip_without_openai_key = pytest.mark.skipif(not OPENAI_API_KEY, reason="OPENAI_API_KEY not set")xfail_provider_unavailable = pytest.mark.xfail(@@ -24,6 +28,47 @@ xfail_provider_unavailable = pytest.mark.xfail(TEST_IMAGE_URL = "https://posthog.com/brand/posthog-logo.png"+def _skip_cloudflare_full_matrix(provider: str) -> None:+ """Smoke-test the Cloudflare routing path, don't run the whole behavioural matrix against it.++ CF Workers AI calls are slow and high-variance, so running every SDK behaviour against them+ blows the CI time budget. The core adapter paths (non-streaming, streaming) are smoke-tested+ elsewhere in this file; the rest of the matrix is covered by the OpenAI provider.+ """+ if provider == "cloudflare":+ pytest.skip("Cloudflare routing covered by smoke tests; skipping full matrix to bound CI time")+++@dataclass+class OpenAISDKTestConfig:+ client: OpenAI+ model: str+ provider: str+++ params=[+ pytest.param(+ "openai",+ id="openai",+ marks=[pytest.mark.skipif(not OPENAI_API_KEY, reason="OPENAI_API_KEY not set"), xfail_provider_unavailable],+ ),+ pytest.param(+ "cloudflare",+ id="cloudflare",+ marks=pytest.mark.skipif(not CLOUDFLARE_CONFIGURED, reason="CLOUDFLARE_API_KEY/ACCOUNT_ID not set"),+ ),+ ]+)+def oai_sdk_config(request) -> OpenAISDKTestConfig:+ if request.param == "openai":+ client = request.getfixturevalue("openai_client")+ return OpenAISDKTestConfig(client=client, model="gpt-4o-mini", provider="openai")+ else:+ client = request.getfixturevalue("cloudflare_openai_client")+ return OpenAISDKTestConfig(client=client, model="@cf/moonshotai/kimi-k2.6", provider="cloudflare")++class TestOpenAIModelsEndpoint:def test_sdk_models_list_returns_models(self, openai_client_all_providers: OpenAI):models = list(openai_client_all_providers.models.list())@@ -56,14 +101,12 @@ class TestOpenAIModelsEndpoint:assert model.object == "model"-@skip_without_openai_key-@xfail_provider_unavailable-class TestOpenAIChatCompletions:- def test_non_streaming_request(self, openai_client: OpenAI):- response = openai_client.chat.completions.create(- model="gpt-4o-mini",+class TestChatCompletions:+ def test_non_streaming_request(self, oai_sdk_config: OpenAISDKTestConfig):+ response = oai_sdk_config.client.chat.completions.create(+ model=oai_sdk_config.model,messages=[{"role": "user", "content": "Say 'hello' and nothing else."}],- max_tokens=10,+ max_tokens=300,)assert response is not None@@ -73,11 +116,11 @@ class TestOpenAIChatCompletions:assert response.usage.prompt_tokens > 0assert response.usage.completion_tokens > 0- def test_streaming_request(self, openai_client: OpenAI):- stream = openai_client.chat.completions.create(- model="gpt-4o-mini",+ def test_streaming_request(self, oai_sdk_config: OpenAISDKTestConfig):+ stream = oai_sdk_config.client.chat.completions.create(+ model=oai_sdk_config.model,messages=[{"role": "user", "content": "Say 'hi' and nothing else."}],- max_tokens=10,+ max_tokens=300,stream=True,)@@ -87,24 +130,26 @@ class TestOpenAIChatCompletions:content_chunks = [c for c in chunks if c.choices and c.choices[0].delta.content]assert len(content_chunks) > 0- def test_with_system_message(self, openai_client: OpenAI):- response = openai_client.chat.completions.create(- model="gpt-4o-mini",+ def test_with_system_message(self, oai_sdk_config: OpenAISDKTestConfig):+ _skip_cloudflare_full_matrix(oai_sdk_config.provider)+ response = oai_sdk_config.client.chat.completions.create(+ model=oai_sdk_config.model,messages=[{"role": "system", "content": "You are a helpful assistant that only says 'OK'."},{"role": "user", "content": "Hello"},],- max_tokens=10,+ max_tokens=300,)assert response is not Noneassert response.choices[0].message.content is not None- def test_with_temperature(self, openai_client: OpenAI):- response = openai_client.chat.completions.create(- model="gpt-4o-mini",+ def test_with_temperature(self, oai_sdk_config: OpenAISDKTestConfig):+ _skip_cloudflare_full_matrix(oai_sdk_config.provider)+ response = oai_sdk_config.client.chat.completions.create(+ model=oai_sdk_config.model,messages=[{"role": "user", "content": "Say 'test'"}],- max_tokens=10,+ max_tokens=300,temperature=0.0,)@@ -112,57 +157,57 @@ class TestOpenAIChatCompletions:assert response.choices[0].message.content is not None-@skip_without_openai_key-@xfail_provider_unavailable-class TestOpenAIMultipleModels:- def test_gpt4o_mini_request(self, openai_client: OpenAI):- response = openai_client.chat.completions.create(- model="gpt-4o-mini",+class TestMultipleModels:+ def test_basic_request(self, oai_sdk_config: OpenAISDKTestConfig):+ _skip_cloudflare_full_matrix(oai_sdk_config.provider)+ response = oai_sdk_config.client.chat.completions.create(+ model=oai_sdk_config.model,messages=[{"role": "user", "content": "Say 'A'"}],- max_tokens=5,+ max_tokens=300,)assert response is not Noneassert response.choices[0].message.content is not None- def test_sequential_requests_same_model(self, openai_client: OpenAI):- response1 = openai_client.chat.completions.create(- model="gpt-4o-mini",+ def test_sequential_requests_same_model(self, oai_sdk_config: OpenAISDKTestConfig):+ _skip_cloudflare_full_matrix(oai_sdk_config.provider)+ response1 = oai_sdk_config.client.chat.completions.create(+ model=oai_sdk_config.model,messages=[{"role": "user", "content": "Say '1'"}],- max_tokens=5,+ max_tokens=300,)- response2 = openai_client.chat.completions.create(- model="gpt-4o-mini",+ response2 = oai_sdk_config.client.chat.completions.create(+ model=oai_sdk_config.model,messages=[{"role": "user", "content": "Say '2'"}],- max_tokens=5,+ max_tokens=300,)assert response1.choices[0].message.content is not Noneassert response2.choices[0].message.content is not None- def test_streaming_then_non_streaming(self, openai_client: OpenAI):- stream = openai_client.chat.completions.create(- model="gpt-4o-mini",+ def test_streaming_then_non_streaming(self, oai_sdk_config: OpenAISDKTestConfig):+ _skip_cloudflare_full_matrix(oai_sdk_config.provider)+ stream = oai_sdk_config.client.chat.completions.create(+ model=oai_sdk_config.model,messages=[{"role": "user", "content": "Say 'stream'"}],- max_tokens=10,+ max_tokens=300,stream=True,)chunks = list(stream)assert len(chunks) > 0- response = openai_client.chat.completions.create(- model="gpt-4o-mini",+ response = oai_sdk_config.client.chat.completions.create(+ model=oai_sdk_config.model,messages=[{"role": "user", "content": "Say 'sync'"}],- max_tokens=10,+ max_tokens=300,)assert response.choices[0].message.content is not None-@skip_without_openai_key-@xfail_provider_unavailable-class TestOpenAIToolCalling:- def test_tool_definition_and_response(self, openai_client: OpenAI):+class TestToolCalling:+ def test_tool_definition_and_response(self, oai_sdk_config: OpenAISDKTestConfig):+ _skip_cloudflare_full_matrix(oai_sdk_config.provider)tools: list[ChatCompletionToolParam] = [{"type": "function",@@ -181,12 +226,12 @@ class TestOpenAIToolCalling:}]- response = openai_client.chat.completions.create(- model="gpt-4o-mini",+ response = oai_sdk_config.client.chat.completions.create(+ model=oai_sdk_config.model,messages=[{"role": "user", "content": "What's the weather in Paris?"}],tools=tools,tool_choice="auto",- max_tokens=100,+ max_tokens=200,)assert response is not None@@ -200,7 +245,10 @@ class TestOpenAIToolCalling:args = json.loads(tool_call.function.arguments)assert "location" in args- def test_tool_choice_required(self, openai_client: OpenAI):+ def test_tool_choice_required(self, oai_sdk_config: OpenAISDKTestConfig):+ if oai_sdk_config.provider == "cloudflare":+ pytest.skip("Cloudflare Workers AI does not support tool_choice with specific function")+tools: list[ChatCompletionToolParam] = [{"type": "function",@@ -220,12 +268,12 @@ class TestOpenAIToolCalling:tool_choice: ChatCompletionToolChoiceOptionParam = {"type": "function", "function": {"name": "calculate"}}- response = openai_client.chat.completions.create(- model="gpt-4o-mini",+ response = oai_sdk_config.client.chat.completions.create(+ model=oai_sdk_config.model,messages=[{"role": "user", "content": "What is 2+2?"}],tools=tools,tool_choice=tool_choice,- max_tokens=100,+ max_tokens=200,)tool_calls = response.choices[0].message.tool_calls@@ -235,6 +283,26 @@ class TestOpenAIToolCalling:assert tool_call.function.name == "calculate"+class TestMultiTurnParametrized:+ def test_conversation_history(self, oai_sdk_config: OpenAISDKTestConfig):+ _skip_cloudflare_full_matrix(oai_sdk_config.provider)+ response = oai_sdk_config.client.chat.completions.create(+ model=oai_sdk_config.model,+ messages=[+ {"role": "system", "content": "You are a helpful assistant. Be very brief."},+ {"role": "user", "content": "My name is Alice."},+ {"role": "assistant", "content": "Hello Alice!"},+ {"role": "user", "content": "What is my name?"},+ ],+ max_tokens=300,+ )++ assert response is not None+ content = response.choices[0].message.content+ assert content is not None+ assert "alice" in content.lower()++@skip_without_openai_key@xfail_provider_unavailableclass TestOpenAIVision:@@ -250,7 +318,7 @@ class TestOpenAIVision:],}],- max_tokens=50,+ max_tokens=300,)assert response is not None@@ -268,7 +336,7 @@ class TestOpenAIVision:],}],- max_tokens=100,+ max_tokens=300,)assert response is not None@@ -310,7 +378,7 @@ class TestOpenAIJSONMode:{"role": "user", "content": "Say hello"},],response_format={"type": "json_object"},- max_tokens=50,+ max_tokens=300,)assert response is not Nonediff --git a/services/llm-gateway/tests/test_anthropic.py b/services/llm-gateway/tests/test_anthropic.pyindex 114834270eb7..f7e7ac5fe141 100644--- a/services/llm-gateway/tests/test_anthropic.py+++ b/services/llm-gateway/tests/test_anthropic.py@@ -1,7 +1,7 @@import asyncioimport osfrom collections.abc import AsyncIterator-from typing import Any+from typing import Any, castfrom unittest.mock import AsyncMock, MagicMock, patchimport httpx@@ -502,6 +502,115 @@ class TestAnthropicMessagesEndpoint:assert "provider" not in call_kwargsassert "use_bedrock_fallback" not in call_kwargs+ @patch("llm_gateway.api.anthropic.litellm.anthropic_messages")+ def test_cloudflare_provider_routes_to_cloudflare(+ self,+ mock_anthropic: MagicMock,+ authenticated_client: TestClient,+ provider_mock_response: dict,+ ) -> None:+ 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_llm_call = AsyncMock(return_value=mock_response)+ mock_make_call.return_value = mock_llm_call++ 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/moonshotai/kimi-k2.6",+ "messages": [{"role": "user", "content": "Hello"}],+ },+ headers={+ "Authorization": "Bearer phx_test_key",+ "X-PostHog-Provider": "cloudflare",+ },+ )++ assert response.status_code == 200+ mock_make_call.assert_called_once()+ mock_anthropic.assert_not_called()++ @patch("llm_gateway.api.anthropic.litellm.anthropic_messages")+ def test_cloudflare_provider_streams_through_cloudflare(+ self,+ mock_anthropic: MagicMock,+ authenticated_client: TestClient,+ ) -> None:+ """Exercises the streaming branch of the Cloudflare Anthropic route end to end:+ the routed llm_call returns an async iterator of Anthropic-shaped events,+ format_sse_stream forwards them, and the gateway emits SSE chunks to the client.+ """++ async def fake_stream():+ yield b'event: message_start\ndata: {"type":"message_start"}\n\n'+ yield b'event: content_block_delta\ndata: {"type":"content_block_delta","delta":{"text":"hi"}}\n\n'+ yield b'event: message_stop\ndata: {"type":"message_stop"}\n\n'++ with patch(+ "llm_gateway.api.anthropic.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",+ return_value=("https://api.cloudflare.com/ai/v1", "test-key"),+ ):+ with authenticated_client.stream(+ "POST",+ "/v1/messages",+ json={+ "model": "@cf/moonshotai/kimi-k2.6",+ "messages": [{"role": "user", "content": "Hello"}],+ "stream": True,+ },+ headers={+ "Authorization": "Bearer phx_test_key",+ "X-PostHog-Provider": "cloudflare",+ },+ ) as response:+ assert response.status_code == 200+ body = "".join(response.iter_text())++ assert "message_start" in body+ assert "content_block_delta" in body+ assert "message_stop" in body+ mock_make_call.assert_called_once()+ mock_anthropic.assert_not_called()++ def test_cloudflare_provider_rejects_unpriced_model(+ 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:+ response = authenticated_client.post(+ "/v1/messages",+ json={+ "model": "@cf/meta/llama-3.3-70b-instruct",+ "messages": [{"role": "user", "content": "Hello"}],+ },+ headers={+ "Authorization": "Bearer phx_test_key",+ "X-PostHog-Provider": "cloudflare",+ },+ )++ 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, otherwise the+ # gateway eats the real CF bill while billing the user $0.01 fallback.+ mock_ensure_configured.assert_not_called()+ mock_make_call.assert_not_called()+def test_invalid_provider_header_returns_400(self,authenticated_client: TestClient,@@ -515,7 +624,7 @@ class TestAnthropicMessagesEndpoint:assert response.status_code == 400assert response.json()["error"]["type"] == "invalid_request_error"- assert "Expected one of: anthropic, bedrock" in response.json()["error"]["message"]+ assert "Expected one of: anthropic, bedrock, cloudflare" in response.json()["error"]["message"]def test_invalid_fallback_header_returns_400(self,@@ -1037,7 +1146,43 @@ class TestAnthropicCountTokensEndpoint:assert response.status_code == 400assert response.json()["error"]["type"] == "invalid_request_error"- assert "Expected one of: anthropic, bedrock" in response.json()["error"]["message"]+ assert "Expected one of: anthropic, bedrock, cloudflare" in response.json()["error"]["message"]++ def test_cloudflare_provider_approximates_count(+ self,+ authenticated_client: TestClient,+ ) -> None:+ response = authenticated_client.post(+ "/v1/messages/count_tokens",+ json={+ "model": "@cf/moonshotai/kimi-k2.6",+ "messages": [{"role": "user", "content": "Hello"}],+ },+ headers={"Authorization": "Bearer phx_test_key", "X-PostHog-Provider": "cloudflare"},+ )++ assert response.status_code == 200+ # Don't lock the exact value — litellm's tokenizer is the source of truth.+ # Just assert it's a positive integer so the Claude Agent SDK gets a usable budget.+ assert isinstance(response.json()["input_tokens"], int)+ assert response.json()["input_tokens"] > 0++ def test_cloudflare_provider_rejects_unpriced_model(+ self,+ authenticated_client: TestClient,+ ) -> None:+ response = authenticated_client.post(+ "/v1/messages/count_tokens",+ json={+ "model": "@cf/meta/llama-3.3-70b-instruct",+ "messages": [{"role": "user", "content": "Hello"}],+ },+ headers={"Authorization": "Bearer phx_test_key", "X-PostHog-Provider": "cloudflare"},+ )++ 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"]def test_invalid_fallback_header_returns_400(self,@@ -1358,7 +1503,7 @@ class TestAnthropicCircuitBreakerIntegration:wrapped = _wrap_stream_with_breaker(StreamingResponse(ok_iter()), breaker)async def consume() -> list[bytes]:- return [chunk async for chunk in wrapped.body_iterator]+ return cast(list[bytes], [chunk async for chunk in wrapped.body_iterator])chunks = asyncio.run(consume())assert len(chunks) == 2diff --git a/services/llm-gateway/tests/test_cloudflare.py b/services/llm-gateway/tests/test_cloudflare.pynew file mode 100644index 000000000000..57b910fc5144--- /dev/null+++ b/services/llm-gateway/tests/test_cloudflare.py@@ -0,0 +1,58 @@+import pytest+from fastapi import HTTPException++from llm_gateway.cloudflare import (+ CLOUDFLARE_ALLOWED_MODELS,+ _inject_cloudflare_params,+ ensure_cloudflare_model_allowed,+)+from llm_gateway.rate_limiting.cost_refresh import COST_ALIASES+++def test_inject_cloudflare_params_prefix_matches_cost_alias_keys() -> None:+ kwargs: dict = {"model": "@cf/moonshotai/kimi-k2.6"}+ _inject_cloudflare_params(kwargs, "https://api.cloudflare.com/test/ai/v1", "secret")++ assert kwargs["model"] == "openai/@cf/moonshotai/kimi-k2.6"+ assert kwargs["api_base"] == "https://api.cloudflare.com/test/ai/v1"+ assert kwargs["api_key"] == "secret"+ # Load-bearing: if this fails, _inject_cloudflare_params and COST_ALIASES no+ # longer agree on the prefix and cost lookup silently misses in production.+ assert kwargs["model"] in COST_ALIASES+++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.+ expected = {alias.removeprefix("openai/") for alias in COST_ALIASES if alias.startswith("openai/@cf/")}+ assert CLOUDFLARE_ALLOWED_MODELS == expected+ assert "@cf/moonshotai/kimi-k2.6" in CLOUDFLARE_ALLOWED_MODELS+++def test_ensure_cloudflare_model_allowed_accepts_priced_model() -> None:+ ensure_cloudflare_model_allowed("@cf/moonshotai/kimi-k2.6")+++ "model",+ [+ "@cf/meta/llama-3.3-70b-instruct",+ "@cf/openai/gpt-oss-120b",+ "@cf/unknown/model",+ ],+)+def test_ensure_cloudflare_model_allowed_rejects_unpriced_model(model: str) -> None:+ with pytest.raises(HTTPException) as exc_info:+ ensure_cloudflare_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"]+++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,+ )++ assert callable(LiteLLMMessagesToCompletionTransformationHandler.async_anthropic_messages_handler)diff --git a/services/llm-gateway/tests/test_cost_refresh.py b/services/llm-gateway/tests/test_cost_refresh.pyindex 8511d7618abc..ad4a40fe0a12 100644--- a/services/llm-gateway/tests/test_cost_refresh.py+++ b/services/llm-gateway/tests/test_cost_refresh.py@@ -1,12 +1,18 @@from __future__ import annotationsfrom collections.abc import Iterator+from typing import Anyfrom unittest.mock import MagicMock, patchimport litellmimport pytest-from llm_gateway.rate_limiting.cost_refresh import CostRefreshService+from llm_gateway.rate_limiting.cost_refresh import (+ COST_ALIASES,+ CostRefreshService,+ apply_cost_aliases,+ normalize_metric_labels,+)from llm_gateway.rate_limiting.model_cost_service import ModelCostService@@ -28,6 +34,88 @@ def restore_litellm_globals() -> Iterator[None]:litellm.open_ai_chat_completion_models.update(openai)+class TestApplyCostAliases:+ def test_adds_alias_when_canonical_present(self) -> None:+ cost: dict[str, Any] = {+ "moonshot/kimi-k2.6": {"input_cost_per_token": 0.001, "output_cost_per_token": 0.002},+ }+ apply_cost_aliases(cost)+ assert cost["openai/@cf/moonshotai/kimi-k2.6"] == cost["moonshot/kimi-k2.6"]+ # Load-bearing: the alias must be a copy, not a shared reference — otherwise an+ # in-place mutation under one key silently mutates the other.+ assert cost["openai/@cf/moonshotai/kimi-k2.6"] is not cost["moonshot/kimi-k2.6"]++ def test_does_not_overwrite_existing_alias(self) -> None:+ cost: dict[str, Any] = {+ "moonshot/kimi-k2.6": {"input_cost_per_token": 0.001},+ "openai/@cf/moonshotai/kimi-k2.6": {"input_cost_per_token": 0.999},+ }+ apply_cost_aliases(cost)+ assert cost["openai/@cf/moonshotai/kimi-k2.6"]["input_cost_per_token"] == 0.999++ @patch("llm_gateway.rate_limiting.cost_refresh.logger")+ def test_warns_when_canonical_missing(self, mock_logger: MagicMock) -> None:+ cost: dict[str, Any] = {"gpt-4o": {}}+ apply_cost_aliases(cost)+ assert "openai/@cf/moonshotai/kimi-k2.6" not in cost+ mock_logger.warning.assert_called_once_with(+ "cost_alias_canonical_missing",+ alias="openai/@cf/moonshotai/kimi-k2.6",+ canonical="moonshot/kimi-k2.6",+ )++ @patch("llm_gateway.rate_limiting.cost_refresh.logger")+ def test_does_not_warn_when_alias_already_present(self, mock_logger: MagicMock) -> None:+ cost: dict[str, Any] = {"openai/@cf/moonshotai/kimi-k2.6": {"input_cost_per_token": 0.999}}+ apply_cost_aliases(cost)+ mock_logger.warning.assert_not_called()++ def test_canonicals_exist_in_litellm_cost_map(self) -> None:+ """Lock in that every COST_ALIASES canonical is present in the pinned litellm+ cost map. If a litellm bump drops the canonical, this fails in CI rather than+ letting `apply_cost_aliases` log `cost_alias_canonical_missing` every refresh+ in production and falling back to the default cost for those models.+ """+ missing = [canonical for canonical in COST_ALIASES.values() if canonical not in litellm.model_cost]+ assert not missing, f"COST_ALIASES canonicals missing from litellm.model_cost: {missing}"+++class TestNormalizeMetricLabels:+ def test_returns_user_facing_labels_for_aliased_model(self) -> None:+ provider, model = normalize_metric_labels("openai/@cf/moonshotai/kimi-k2.6", "openai")+ assert provider == "cloudflare"+ assert model == "@cf/moonshotai/kimi-k2.6"++ def test_passes_through_unaliased_model(self) -> None:+ provider, model = normalize_metric_labels("gpt-4o", "openai")+ assert provider == "openai"+ assert model == "gpt-4o"++ def test_passes_through_unknown_model(self) -> None:+ provider, model = normalize_metric_labels("unknown", "unknown")+ assert provider == "unknown"+ assert model == "unknown"+++class TestModelCostServiceAliases:+ @pytest.fixture(autouse=True)+ def reset_singleton(self) -> Iterator[None]:+ ModelCostService.reset_instance()+ yield+ ModelCostService.reset_instance()++ @patch("llm_gateway.rate_limiting.model_cost_service.get_model_cost_map")+ def test_refresh_cache_applies_cost_aliases(self, mock_get_cost_map: MagicMock) -> None:+ mock_get_cost_map.return_value = {+ "moonshot/kimi-k2.6": {"input_cost_per_token": 0.001, "output_cost_per_token": 0.002},+ }+ service = ModelCostService.get_instance()+ cost_for_alias = service.get_costs("openai/@cf/moonshotai/kimi-k2.6")++ assert cost_for_alias == {"input_cost_per_token": 0.001, "output_cost_per_token": 0.002}+ assert "openai/@cf/moonshotai/kimi-k2.6" in litellm.model_cost++class TestCostRefreshService:@pytest.fixture(autouse=True)def reset_singleton(self) -> Iterator[None]:diff --git a/services/llm-gateway/tests/test_openai.py b/services/llm-gateway/tests/test_openai.pyindex 38c7917afeff..74bb0070afb1 100644--- a/services/llm-gateway/tests/test_openai.py+++ b/services/llm-gateway/tests/test_openai.py@@ -279,6 +279,103 @@ class TestChatCompletionsEndpoint:assert forwarded_metadata["safe"] == "value"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")+ def test_cf_model_routes_through_cloudflare(+ self,+ mock_ensure_configured: MagicMock,+ mock_make_call: MagicMock,+ mock_acompletion: MagicMock,+ authenticated_client: TestClient,+ mock_openai_response: dict,+ ) -> None:+ mock_ensure_configured.return_value = ("https://api.cloudflare.com/ai/v1", "test-key")+ mock_response = MagicMock()+ mock_response.model_dump = MagicMock(return_value=mock_openai_response)+ mock_make_call.return_value = AsyncMock(return_value=mock_response)++ response = authenticated_client.post(+ "/v1/chat/completions",+ json={+ "model": "@cf/moonshotai/kimi-k2.6",+ "messages": [{"role": "user", "content": "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")+ 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")+ def test_cf_model_streams_through_cloudflare(+ self,+ mock_ensure_configured: MagicMock,+ mock_make_call: MagicMock,+ mock_acompletion: MagicMock,+ authenticated_client: TestClient,+ ) -> None:+ """Exercises the streaming branch of the Cloudflare OpenAI route end to end:+ the routed llm_call returns an async iterator, format_sse_stream wraps it,+ and the gateway emits SSE chunks back to the client.+ """+ 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/chat/completions",+ json={+ "model": "@cf/moonshotai/kimi-k2.6",+ "messages": [{"role": "user", "content": "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_acompletion.assert_not_called()++ @patch("llm_gateway.api.openai.make_cloudflare_completion_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/chat/completions",+ json={+ "model": "@cf/meta/llama-3.3-70b-instruct",+ "messages": [{"role": "user", "content": "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"]+ # Critical: rejection must happen before we hand the model off to CF, otherwise the+ # gateway eats the real CF bill while billing the user $0.01 fallback.+ 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@@ -300,6 +397,11 @@ class TestUnsupportedModelRejection:"gemini-1.5-pro","gemini-2.0-flash","Gemini-3-Pro-Preview", # case-insensitive+ # The `cloudflare/...` prefix would route to litellm's native CF+ # provider and bypass CLOUDFLARE_ALLOWED_MODELS. Block at the edge.+ "cloudflare/@cf/meta/llama-3.3-70b-instruct",+ "cloudflare/@cf/moonshotai/kimi-k2.6",+ "CLOUDFLARE/@cf/foo",],)@patch("llm_gateway.api.openai.litellm.acompletion")