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 cache & reasoning token breakdown on $ai_generation events (#60403)

Vojta Bartoš5a2f0dde1e35
diff --git a/services/llm-gateway/src/llm_gateway/callbacks/posthog.py b/services/llm-gateway/src/llm_gateway/callbacks/posthog.py
index 34441a76220f..3a77cb28a40f 100644
--- a/services/llm-gateway/src/llm_gateway/callbacks/posthog.py
+++ b/services/llm-gateway/src/llm_gateway/callbacks/posthog.py
@@ -145,6 +145,7 @@ class PostHogCallback(InstrumentedCallback):
)
is_streaming = standard_logging_object.get("stream", False)
+ usage_object = (standard_logging_object.get("metadata") or {}).get("usage_object") or {}
properties: dict[str, Any] = {
"$ai_model": standard_logging_object.get("model", ""),
@@ -160,6 +161,23 @@ class PostHogCallback(InstrumentedCallback):
"$ai_billable": _is_product_billable(product),
}
+ # Cache and reasoning token breakdowns are reported by LiteLLM in the
+ # response usage object for providers that support them (Anthropic for
+ # cache, OpenAI o-series for reasoning). Emit the fields only when
+ # present so providers that don't report them don't pollute events with
+ # zeros, matching the schema in posthog/models/ai_events/sql.py and the
+ # parity established by posthoganalytics' langchain CallbackHandler.
+ cache_read_input_tokens = usage_object.get("cache_read_input_tokens")
+ if cache_read_input_tokens is not None:
+ properties["$ai_cache_read_input_tokens"] = cache_read_input_tokens
+ cache_creation_input_tokens = usage_object.get("cache_creation_input_tokens")
+ if cache_creation_input_tokens is not None:
+ properties["$ai_cache_creation_input_tokens"] = cache_creation_input_tokens
+ completion_tokens_details = usage_object.get("completion_tokens_details") or {}
+ reasoning_tokens = completion_tokens_details.get("reasoning_tokens")
+ if reasoning_tokens is not None:
+ properties["$ai_reasoning_tokens"] = reasoning_tokens
+
posthog_properties = get_posthog_properties() or {}
if isinstance(posthog_properties, dict):
for key, value in posthog_properties.items():
diff --git a/services/llm-gateway/tests/callbacks/test_posthog.py b/services/llm-gateway/tests/callbacks/test_posthog.py
index 1d50233ccfaf..53e3743f0dd2 100644
--- a/services/llm-gateway/tests/callbacks/test_posthog.py
+++ b/services/llm-gateway/tests/callbacks/test_posthog.py
@@ -254,6 +254,107 @@ class TestPostHogCallback:
def test_callback_name_is_posthog(self, callback: PostHogCallback) -> None:
assert callback.callback_name == "posthog"
+ @pytest.mark.asyncio
+ async def test_on_success_emits_cache_tokens_when_present(
+ self, callback: PostHogCallback, auth_user: AuthenticatedUser, mock_posthog_client: tuple
+ ) -> 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,
+ "metadata": {
+ "usage_object": {
+ "cache_read_input_tokens": 60,
+ "cache_creation_input_tokens": 30,
+ },
+ },
+ },
+ "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 props["$ai_cache_read_input_tokens"] == 60
+ assert props["$ai_cache_creation_input_tokens"] == 30
+
+ @pytest.mark.asyncio
+ async def test_on_success_omits_cache_tokens_when_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_cache_read_input_tokens" not in props
+ assert "$ai_cache_creation_input_tokens" 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
+ ) -> None:
+ _, mock_client = mock_posthog_client
+ kwargs = {
+ "standard_logging_object": {
+ "model": "gpt-5.2",
+ "custom_llm_provider": "openai",
+ "prompt_tokens": 50,
+ "completion_tokens": 200,
+ "metadata": {
+ "usage_object": {
+ "completion_tokens_details": {"reasoning_tokens": 120},
+ },
+ },
+ },
+ "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_routing"),
+ ):
+ await callback._on_success(kwargs, None, 0.0, 1.0, end_user_id=None)
+
+ props = mock_client.capture.call_args.kwargs["properties"]
+ assert props["$ai_reasoning_tokens"] == 120
+
+ @pytest.mark.asyncio
+ async def test_on_success_omits_reasoning_tokens_when_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_reasoning_tokens" not in props
+
@pytest.mark.asyncio
@pytest.mark.parametrize("product", ["wizard", "posthog_code", "llm_gateway"])
async def test_on_success_includes_ai_product(