Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(llm-gateway): emit $ai_input_cost_usd and $ai_output_cost_usd (#60660)

Vojta Bartoše9a438ee8aa0
diff --git a/services/llm-gateway/src/llm_gateway/callbacks/posthog.py b/services/llm-gateway/src/llm_gateway/callbacks/posthog.py
index 7b303823ceb8..bbc471bfc289 100644
--- a/services/llm-gateway/src/llm_gateway/callbacks/posthog.py
+++ b/services/llm-gateway/src/llm_gateway/callbacks/posthog.py
@@ -220,6 +220,19 @@ class PostHogCallback(InstrumentedCallback):
if response_cost is not None:
properties["$ai_total_cost_usd"] = response_cost
+ # Forward LiteLLM's cost_breakdown so ingestion passes the per-side
+ # numbers through instead of rederiving them and mispricing cache.
+ cost_breakdown = standard_logging_object.get("cost_breakdown") or {}
+ for breakdown_key, property_key in (
+ ("input_cost", "$ai_input_cost_usd"),
+ ("output_cost", "$ai_output_cost_usd"),
+ ("cache_read_cost", "$ai_cache_read_cost_usd"),
+ ("cache_creation_cost", "$ai_cache_creation_cost_usd"),
+ ):
+ cost_value = cost_breakdown.get(breakdown_key)
+ if cost_value is not None:
+ properties[property_key] = cost_value
+
response = standard_logging_object.get("response")
if response:
properties["$ai_output_choices"] = response
diff --git a/services/llm-gateway/tests/callbacks/test_posthog.py b/services/llm-gateway/tests/callbacks/test_posthog.py
index c2ea64d319e1..7d1c6b346181 100644
--- a/services/llm-gateway/tests/callbacks/test_posthog.py
+++ b/services/llm-gateway/tests/callbacks/test_posthog.py
@@ -309,6 +309,92 @@ class TestPostHogCallback:
assert "$ai_cache_read_input_tokens" not in props
assert "$ai_cache_creation_input_tokens" not in props
+ @pytest.mark.parametrize(
+ "cost_breakdown,expected_props",
+ [
+ pytest.param(
+ {
+ "input_cost": 0.003,
+ "cache_read_cost": 0.001,
+ "cache_creation_cost": 0.002,
+ "output_cost": 0.006,
+ "total_cost": 0.012,
+ },
+ {
+ "$ai_input_cost_usd": 0.003,
+ "$ai_output_cost_usd": 0.006,
+ "$ai_cache_read_cost_usd": 0.001,
+ "$ai_cache_creation_cost_usd": 0.002,
+ },
+ id="anthropic_with_cache",
+ ),
+ pytest.param(
+ {"input_cost": 0.02, "output_cost": 0.03},
+ {"$ai_input_cost_usd": 0.02, "$ai_output_cost_usd": 0.03},
+ id="no_cache_components",
+ ),
+ ],
+ )
+ @pytest.mark.asyncio
+ async def test_on_success_emits_cost_breakdown(
+ self,
+ callback: PostHogCallback,
+ auth_user: AuthenticatedUser,
+ mock_posthog_client: tuple,
+ cost_breakdown: dict,
+ expected_props: dict,
+ ) -> None:
+ _, mock_client = mock_posthog_client
+ kwargs = {
+ "standard_logging_object": {
+ "model": "claude-sonnet-4-6",
+ "custom_llm_provider": "anthropic",
+ "prompt_tokens": 100,
+ "completion_tokens": 20,
+ "response_cost": cost_breakdown.get("total_cost"),
+ "cost_breakdown": cost_breakdown,
+ },
+ "litellm_params": {},
+ }
+
+ with (
+ patch("llm_gateway.callbacks.posthog.get_auth_user", return_value=auth_user),
+ patch("llm_gateway.callbacks.posthog.get_product", return_value="slack_app"),
+ ):
+ await callback._on_success(kwargs, None, 0.0, 1.0, end_user_id=None)
+
+ props = mock_client.capture.call_args.kwargs["properties"]
+ # Each LiteLLM cost_breakdown component maps 1:1 to its own PostHog
+ # property — disjoint, so the sum reconciles to $ai_total_cost_usd.
+ for key, value in expected_props.items():
+ assert props[key] == value
+ for key in ("$ai_cache_read_cost_usd", "$ai_cache_creation_cost_usd"):
+ if key not in expected_props:
+ assert key not in props
+
+ @pytest.mark.asyncio
+ async def test_on_success_omits_per_side_cost_when_breakdown_absent(
+ self,
+ callback: PostHogCallback,
+ auth_user: AuthenticatedUser,
+ standard_logging_object: dict,
+ mock_posthog_client: tuple,
+ ) -> None:
+ _, mock_client = mock_posthog_client
+ kwargs = {"standard_logging_object": standard_logging_object, "litellm_params": {}}
+
+ with (
+ patch("llm_gateway.callbacks.posthog.get_auth_user", return_value=auth_user),
+ patch("llm_gateway.callbacks.posthog.get_product", return_value="slack_app"),
+ ):
+ await callback._on_success(kwargs, None, 0.0, 1.0, end_user_id=None)
+
+ props = mock_client.capture.call_args.kwargs["properties"]
+ assert "$ai_input_cost_usd" not in props
+ assert "$ai_output_cost_usd" not in props
+ assert "$ai_cache_read_cost_usd" not in props
+ assert "$ai_cache_creation_cost_usd" not in props
+
@pytest.mark.asyncio
async def test_on_success_emits_reasoning_tokens_when_present(
self, callback: PostHogCallback, auth_user: AuthenticatedUser, mock_posthog_client: tuple