: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
fix(llm-gateway): request stream usage and fix provider labels (#94154)
Alessandro Pogliaghi483e80f57f02
diff --git a/services/llm-gateway/src/llm_gateway/anthropic_request.py b/services/llm-gateway/src/llm_gateway/anthropic_request.pyindex 96593fff0673..811664aedb2a 100644--- a/services/llm-gateway/src/llm_gateway/anthropic_request.py+++ b/services/llm-gateway/src/llm_gateway/anthropic_request.py@@ -53,6 +53,19 @@ def convert_enabled_thinking_to_adaptive(request_data: dict[str, Any]) -> dict[sreturn normalized+def force_stream_usage(kwargs: dict[str, Any], *, continuous_usage_stats: bool) -> None:+ if not kwargs.get("stream"):+ return+ stream_options = dict(kwargs.get("stream_options") or {})+ stream_options["include_usage"] = True+ if continuous_usage_stats:+ stream_options["continuous_usage_stats"] = True+ kwargs["stream_options"] = stream_options+ extra_body = dict(kwargs.get("extra_body") or {})+ extra_body["stream_options"] = stream_options+ kwargs["extra_body"] = extra_body++def drop_orphaned_clear_thinking(request_data: dict[str, Any], *, product: str) -> dict[str, Any]:"""Strip a `clear_thinking_20251015` edit the request can't legally carry.diff --git a/services/llm-gateway/src/llm_gateway/baseten.py b/services/llm-gateway/src/llm_gateway/baseten.pyindex 91d39af1d56f..ad2865176056 100644--- a/services/llm-gateway/src/llm_gateway/baseten.py+++ b/services/llm-gateway/src/llm_gateway/baseten.py@@ -9,7 +9,7 @@ from litellm.llms.anthropic.experimental_pass_through.adapters.handler import (LiteLLMMessagesToCompletionTransformationHandler,)-from llm_gateway.anthropic_request import convert_enabled_thinking_to_adaptive+from llm_gateway.anthropic_request import convert_enabled_thinking_to_adaptive, force_stream_usagefrom llm_gateway.anthropic_stream import observe_anthropic_streamfrom llm_gateway.config import Settings@@ -62,10 +62,7 @@ def _inject_baseten_params(kwargs: dict[str, Any], api_base: str, api_key: str)kwargs["extra_headers"] = {"Authorization": f"Bearer {api_key}"}kwargs["model"] = f"openai/{BASETEN_MODELS[model]}"kwargs.setdefault("drop_params", True)- if kwargs.get("stream"):- stream_options = dict(kwargs.get("stream_options") or {})- stream_options.update(include_usage=True, continuous_usage_stats=True)- kwargs["stream_options"] = stream_options+ force_stream_usage(kwargs, continuous_usage_stats=True)def make_baseten_anthropic_call(api_base: str, api_key: str) -> Callable[..., Awaitable[Any]]:diff --git a/services/llm-gateway/src/llm_gateway/callbacks/posthog.py b/services/llm-gateway/src/llm_gateway/callbacks/posthog.pyindex 98a6bc909087..40031888df35 100644--- a/services/llm-gateway/src/llm_gateway/callbacks/posthog.py+++ b/services/llm-gateway/src/llm_gateway/callbacks/posthog.py@@ -363,9 +363,14 @@ class PostHogCallback(InstrumentedCallback):product=product,)+ 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_trace_id": trace_id,"$ai_is_error": True,"$ai_error": standard_logging_object.get("error_str", ""),diff --git a/services/llm-gateway/src/llm_gateway/cloudflare.py b/services/llm-gateway/src/llm_gateway/cloudflare.pyindex f30ade2d1345..c1ef58d1f0bd 100644--- a/services/llm-gateway/src/llm_gateway/cloudflare.py+++ b/services/llm-gateway/src/llm_gateway/cloudflare.py@@ -11,7 +11,7 @@ from litellm.llms.anthropic.experimental_pass_through.adapters.handler import (LiteLLMMessagesToCompletionTransformationHandler,)-from llm_gateway.anthropic_request import convert_enabled_thinking_to_adaptive+from llm_gateway.anthropic_request import convert_enabled_thinking_to_adaptive, force_stream_usagefrom llm_gateway.anthropic_stream import observe_anthropic_streamfrom llm_gateway.config import Settingsfrom llm_gateway.rate_limiting.cost_refresh import COST_ALIASES@@ -87,6 +87,7 @@ def _inject_cloudflare_params(kwargs: dict[str, Any], api_base: str, api_key: st# provider-specific params a caller's runtime sends (e.g. Anthropic's reasoning_effort /# context_management). Drop the unsupported ones instead of failing the request.kwargs.setdefault("drop_params", True)+ force_stream_usage(kwargs, continuous_usage_stats=False)def make_cloudflare_anthropic_call(api_base: str, api_key: str) -> Callable[..., Awaitable[Any]]:diff --git a/services/llm-gateway/src/llm_gateway/modal.py b/services/llm-gateway/src/llm_gateway/modal.pyindex 21c39d82cda1..a1fdd45c66c1 100644--- a/services/llm-gateway/src/llm_gateway/modal.py+++ b/services/llm-gateway/src/llm_gateway/modal.py@@ -13,7 +13,7 @@ from litellm.llms.anthropic.experimental_pass_through.adapters.handler import (LiteLLMMessagesToCompletionTransformationHandler,)-from llm_gateway.anthropic_request import convert_enabled_thinking_to_adaptive+from llm_gateway.anthropic_request import convert_enabled_thinking_to_adaptive, force_stream_usagefrom llm_gateway.anthropic_stream import observe_anthropic_streamfrom llm_gateway.config import Settings, _normalize_cost_key@@ -141,6 +141,7 @@ def _inject_modal_params(kwargs: dict[str, Any], api_base: str, modal_key: str,kwargs["model"] = modal_litellm_model(kwargs["model"])# The OpenAI-compatible surface rejects provider-specific params (see cloudflare.py).kwargs.setdefault("drop_params", True)+ force_stream_usage(kwargs, continuous_usage_stats=True)def make_modal_anthropic_call(api_base: str, modal_key: str, modal_secret: str) -> Callable[..., Awaitable[Any]]:diff --git a/services/llm-gateway/src/llm_gateway/rate_limiting/cost_refresh.py b/services/llm-gateway/src/llm_gateway/rate_limiting/cost_refresh.pyindex 61c9aac269cc..b74c2e9ed5ad 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@@ -11,11 +11,15 @@ from litellm.litellm_core_utils.get_model_cost_map import get_model_cost_mapfrom llm_gateway.baseten import (BASETEN_DEEPSEEK_METRIC_MODEL,BASETEN_DEEPSEEK_MODEL,+ BASETEN_DEEPSEEK_PUBLIC_MODEL,BASETEN_GLM53_FLASH_METRIC_MODEL,BASETEN_GLM53_FLASH_MODEL,+ BASETEN_GLM53_FLASH_PUBLIC_MODEL,BASETEN_GLM53_METRIC_MODEL,BASETEN_GLM53_MODEL,+ BASETEN_GLM53_PUBLIC_MODEL,BASETEN_METRIC_MODEL,+ BASETEN_PUBLIC_MODEL,)from llm_gateway.rate_limiting.model_cost_overrides import apply_model_cost_overrides@@ -49,10 +53,10 @@ ALIAS_METRIC_LABELS: dict[str, tuple[str, str]] = {"openai/@cf/zai-org/glm-5.2": ("cloudflare", "@cf/zai-org/glm-5.2"),# Same public model id as the CF entry so dashboards slice one model across both backends."openai/zai-org/GLM-5.2-FP8": ("modal", "@cf/zai-org/glm-5.2"),- "openai/zai-org/GLM-5.2": ("baseten", BASETEN_METRIC_MODEL),- f"openai/{BASETEN_DEEPSEEK_MODEL}": ("baseten", BASETEN_DEEPSEEK_METRIC_MODEL),- f"openai/{BASETEN_GLM53_MODEL}": ("baseten", BASETEN_GLM53_METRIC_MODEL),- f"openai/{BASETEN_GLM53_FLASH_MODEL}": ("baseten", BASETEN_GLM53_FLASH_METRIC_MODEL),+ "openai/zai-org/GLM-5.2": ("baseten", BASETEN_PUBLIC_MODEL),+ f"openai/{BASETEN_DEEPSEEK_MODEL}": ("baseten", BASETEN_DEEPSEEK_PUBLIC_MODEL),+ f"openai/{BASETEN_GLM53_MODEL}": ("baseten", BASETEN_GLM53_PUBLIC_MODEL),+ f"openai/{BASETEN_GLM53_FLASH_MODEL}": ("baseten", BASETEN_GLM53_FLASH_PUBLIC_MODEL),"openai/moonshotai/kimi-k3": ("modal", "moonshotai/kimi-k3"),}@@ -61,7 +65,7 @@ def normalize_metric_labels(litellm_model: str, litellm_provider: str) -> tuple["""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)+ override = ALIAS_METRIC_LABELS.get(litellm_model) or ALIAS_METRIC_LABELS.get(f"{litellm_provider}/{litellm_model}")if override is None:return litellm_provider, litellm_modelreturn overridediff --git a/services/llm-gateway/tests/callbacks/test_posthog.py b/services/llm-gateway/tests/callbacks/test_posthog.pyindex a57e3c085585..4c91a1962566 100644--- a/services/llm-gateway/tests/callbacks/test_posthog.py+++ b/services/llm-gateway/tests/callbacks/test_posthog.py@@ -634,6 +634,41 @@ class TestPostHogCallback:if key in props} == expected+ @pytest.mark.parametrize("hook", ["_on_success", "_on_failure"])+ @pytest.mark.parametrize(+ ("model", "provider", "expected_provider", "expected_model"),+ [+ pytest.param("moonshotai/kimi-k3", "openai", "modal", "moonshotai/kimi-k3", id="modal_kimi"),+ pytest.param("gpt-5.2", "openai", "openai", "gpt-5.2", id="unaliased_passthrough"),+ ],+ )+ @pytest.mark.asyncio+ async def test_relabels_aliased_provider(+ self,+ callback: PostHogCallback,+ auth_user: AuthenticatedUser,+ mock_posthog_client: tuple[MagicMock, MagicMock],+ hook: str,+ model: str,+ provider: str,+ expected_provider: str,+ expected_model: str,+ ) -> None:+ _, mock_client = mock_posthog_client+ kwargs = {+ "standard_logging_object": {"model": model, "custom_llm_provider": provider},+ "litellm_params": {},+ }++ with (+ patch("llm_gateway.callbacks.posthog.get_auth_user", return_value=auth_user),+ patch("llm_gateway.callbacks.posthog.get_product", return_value="posthog_code"),+ ):+ await getattr(callback, hook)(kwargs, None, 0.0, 1.0, end_user_id=None)++ props = mock_client.capture.call_args.kwargs["properties"]+ assert (props["$ai_provider"], props["$ai_model"]) == (expected_provider, expected_model)+@pytest.mark.parametrize("cost_breakdown,expected_props",[diff --git a/services/llm-gateway/tests/test_baseten.py b/services/llm-gateway/tests/test_baseten.pyindex 590e608c2cfe..5c8cdfb630fb 100644--- a/services/llm-gateway/tests/test_baseten.py+++ b/services/llm-gateway/tests/test_baseten.py@@ -58,7 +58,7 @@ def test_inject_baseten_params_maps_model_and_pins_api_key(assert MODEL_COST_OVERRIDES[metric_model]["input_cost_per_token"] == input_costassert MODEL_COST_OVERRIDES[metric_model]["cache_read_input_token_cost"] == cache_read_costassert MODEL_COST_OVERRIDES[metric_model]["output_cost_per_token"] == output_cost- assert normalize_metric_labels(litellm_model, "openai") == ("baseten", metric_model)+ assert normalize_metric_labels(litellm_model, "openai") == ("baseten", public_model)@pytest.mark.parametrize("public_model", sorted(BASETEN_MODELS))@@ -67,8 +67,9 @@ def test_every_baseten_model_is_priced_and_labeled(public_model: str) -> None:# billing nothing: the usage reporter drops any generation whose $ai_total_cost_usd is 0.litellm_key = f"openai/{BASETEN_MODELS[public_model]}"assert litellm_key in COST_ALIASES or litellm_key in MODEL_COST_OVERRIDES- provider, _ = ALIAS_METRIC_LABELS[litellm_key]+ provider, metric_model = ALIAS_METRIC_LABELS[litellm_key]assert provider == "baseten"+ assert metric_model == public_modeldef test_inject_baseten_params_forces_streaming_usage() -> None:diff --git a/services/llm-gateway/tests/test_cloudflare.py b/services/llm-gateway/tests/test_cloudflare.pyindex 594cca0b2269..a91373cb39b6 100644--- a/services/llm-gateway/tests/test_cloudflare.py+++ b/services/llm-gateway/tests/test_cloudflare.py@@ -1,3 +1,4 @@+from typing import Anyfrom unittest.mock import AsyncMock, patchimport litellm@@ -44,6 +45,22 @@ def test_inject_cloudflare_params_preserves_explicit_drop_params() -> None:assert kwargs["drop_params"] is False+ ("initial", "expected"),+ [+ ({"stream": True, "stream_options": {"include_usage": False}}, {"include_usage": True}),+ ({"stream": True}, {"include_usage": True}),+ ({}, None),+ ],+)+def test_inject_cloudflare_params_forces_streaming_usage(+ initial: dict[str, Any], expected: dict[str, bool] | None+) -> None:+ kwargs: dict[str, Any] = {"model": "@cf/zai-org/glm-5.2", **initial}+ _inject_cloudflare_params(kwargs, "https://api.cloudflare.com/test/ai/v1", "secret")+ assert kwargs.get("stream_options") == expected++def test_allowlist_derived_from_cost_aliases() -> None:# Any @cf/ entry in COST_ALIASES must be reachable through the allowlist,# otherwise we'd have a priced model we refuse to route.diff --git a/services/llm-gateway/tests/test_cost_refresh.py b/services/llm-gateway/tests/test_cost_refresh.pyindex 5d1791b2e838..caa446c12b0b 100644--- a/services/llm-gateway/tests/test_cost_refresh.py+++ b/services/llm-gateway/tests/test_cost_refresh.py@@ -8,6 +8,7 @@ import litellmimport pytestfrom llm_gateway.rate_limiting.cost_refresh import (+ ALIAS_METRIC_LABELS,COST_ALIASES,CostRefreshService,apply_cost_aliases,@@ -152,6 +153,10 @@ class TestNormalizeMetricLabels:assert provider == "cloudflare"assert model == "@cf/moonshotai/kimi-k2.6"+ @pytest.mark.parametrize("alias", sorted(ALIAS_METRIC_LABELS))+ def test_resolves_alias_with_provider_prefix_stripped(self, alias: str) -> None:+ assert normalize_metric_labels(alias.removeprefix("openai/"), "openai") == ALIAS_METRIC_LABELS[alias]+def test_passes_through_unaliased_model(self) -> None:provider, model = normalize_metric_labels("gpt-4o", "openai")assert provider == "openai"diff --git a/services/llm-gateway/tests/test_modal.py b/services/llm-gateway/tests/test_modal.pyindex 6c4fcf020059..63eded7e202b 100644--- a/services/llm-gateway/tests/test_modal.py+++ b/services/llm-gateway/tests/test_modal.py@@ -1,6 +1,7 @@from typing import Anyfrom unittest.mock import AsyncMock, MagicMock, patch+import litellmimport pytestfrom fastapi import HTTPException@@ -11,6 +12,7 @@ from llm_gateway.modal import (_inject_modal_params,ensure_modal_model_allowed,ensure_modal_model_configured,+ make_modal_anthropic_call,make_modal_responses_call,should_route_glm_to_modal,)@@ -56,6 +58,24 @@ def test_inject_modal_params_maps_model_and_pins_proxy_auth() -> None:assert kwargs["model"] in ALIAS_METRIC_LABELS+ ("initial", "expected"),+ [+ (+ {"stream": True, "stream_options": {"include_usage": False}},+ {"include_usage": True, "continuous_usage_stats": True},+ ),+ ({"stream": True}, {"include_usage": True, "continuous_usage_stats": True}),+ ({}, None),+ ],+)+def test_inject_modal_params_forces_streaming_usage(initial: dict[str, Any], expected: dict[str, bool] | None) -> None:+ kwargs: dict[str, Any] = {"model": KIMI_MODEL, **initial}+ _inject_modal_params(kwargs, "https://modal.test/v1", "wk", "ws")+ assert kwargs.get("stream_options") == expected+ assert kwargs.get("extra_body") == ({"stream_options": expected} if expected is not None else None)++@pytest.mark.parametrize(("initial", "expected"), [({}, True), ({"drop_params": False}, False)])def test_inject_modal_params_drop_params(initial: dict, expected: bool) -> None:# drop_params must default on (the OpenAI-compatible surface 400s on Anthropic-only params)@@ -186,6 +206,33 @@ def test_partial_fraction_splits_pinned_users() -> None:assert should_route_glm_to_modal(GLM_MODEL, product="posthog_code", user_key="2", settings=settings) is False+async def test_modal_anthropic_stream_usage_survives_messages_bridge_to_acompletion() -> None:+ llm_call = make_modal_anthropic_call("https://modal.test/v1", "wk", "ws")++ with patch("litellm.acompletion", new=AsyncMock(side_effect=RuntimeError("captured"))) as mock_acompletion:+ with pytest.raises(RuntimeError):+ await llm_call(model=GLM_MODEL, max_tokens=16, messages=[{"role": "user", "content": "hi"}], stream=True)++ kwargs = mock_acompletion.call_args.kwargs+ assert kwargs["model"] == "openai/zai-org/GLM-5.2-FP8"+ assert kwargs["stream"] is True+ assert kwargs["extra_body"]["stream_options"] == {"include_usage": True, "continuous_usage_stats": True}+++async def test_modal_responses_stream_usage_survives_responses_bridge_to_acompletion() -> None:+ llm_call = make_modal_responses_call("https://modal.test/v1", "wk", "ws")++ with patch("litellm.acompletion", new=AsyncMock(side_effect=RuntimeError("captured"))) as mock_acompletion:+ with pytest.raises(litellm.exceptions.APIConnectionError):+ await llm_call(model=GLM_MODEL, input="hi", stream=True)++ kwargs = mock_acompletion.call_args.kwargs+ assert kwargs["model"] == "zai-org/GLM-5.2-FP8"+ assert kwargs["custom_llm_provider"] == "openai"+ assert kwargs["stream"] is True+ assert kwargs["extra_body"]["stream_options"] == {"include_usage": True, "continuous_usage_stats": True}++async def test_make_modal_responses_call_forces_bridge_and_ignores_smuggled_flag() -> None:# vLLM has no /responses route, so the Responses->chat/completions bridge must be forced and a# caller-smuggled use_chat_completions_api=False must not escape it (same bug class as CF).