Skip to content

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

fix(llm-gateway): report OpenAI prompt cache tokens on $ai_generation (#80321)

Georgiy Tarasovd8a5c93b1753
diff --git a/services/llm-gateway/src/llm_gateway/callbacks/posthog.py b/services/llm-gateway/src/llm_gateway/callbacks/posthog.py
index c0efa7a015d8..2e2365d1f767 100644
--- a/services/llm-gateway/src/llm_gateway/callbacks/posthog.py
+++ b/services/llm-gateway/src/llm_gateway/callbacks/posthog.py
@@ -240,10 +240,22 @@ class PostHogCallback(InstrumentedCallback):
# 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.
+ # convention in posthoganalytics' posthog/ai/utils.py.
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
+ else:
+ # `cache_read_input_tokens` is Anthropic's spelling, and LiteLLM only
+ # populates it from Anthropic-shaped usage. OpenAI reports its cached
+ # prompt tokens on `prompt_tokens_details.cached_tokens` for both Chat
+ # Completions and the Responses API, because LiteLLM normalizes the
+ # Responses API's `input_tokens_details` onto that same field. Zero here
+ # means the request missed the cache rather than the provider not
+ # reporting, so it is dropped to keep the property meaning "a cache read
+ # happened", which is how posthoganalytics treats non-Anthropic providers.
+ cached_tokens = (usage_object.get("prompt_tokens_details") or {}).get("cached_tokens")
+ if cached_tokens:
+ properties["$ai_cache_read_input_tokens"] = cached_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
diff --git a/services/llm-gateway/tests/callbacks/test_posthog.py b/services/llm-gateway/tests/callbacks/test_posthog.py
index 5b644a93d6c4..d46899583c6d 100644
--- a/services/llm-gateway/tests/callbacks/test_posthog.py
+++ b/services/llm-gateway/tests/callbacks/test_posthog.py
@@ -436,23 +436,59 @@ class TestPostHogCallback:
def test_callback_name_is_posthog(self, callback: PostHogCallback) -> None:
assert callback.callback_name == "posthog"
+ @pytest.mark.parametrize(
+ "model,provider,usage_object,expected",
+ [
+ pytest.param(
+ "claude-sonnet-4-6",
+ "anthropic",
+ {"cache_read_input_tokens": 60, "cache_creation_input_tokens": 30},
+ {"$ai_cache_read_input_tokens": 60, "$ai_cache_creation_input_tokens": 30},
+ id="anthropic_reports_cache_read_and_write",
+ ),
+ pytest.param(
+ "claude-sonnet-4-6",
+ "anthropic",
+ {"cache_read_input_tokens": 0, "cache_creation_input_tokens": 0},
+ {"$ai_cache_read_input_tokens": 0, "$ai_cache_creation_input_tokens": 0},
+ id="anthropic_keeps_explicit_zeros",
+ ),
+ pytest.param(
+ "gpt-5.2",
+ "openai",
+ {"prompt_tokens_details": {"cached_tokens": 60}},
+ {"$ai_cache_read_input_tokens": 60},
+ id="openai_reports_cached_tokens_on_details",
+ ),
+ pytest.param(
+ "gpt-5.2",
+ "openai",
+ {"prompt_tokens_details": {"cached_tokens": 0}},
+ {},
+ id="openai_drops_cache_miss",
+ ),
+ pytest.param("gpt-5.2", "openai", {}, {}, id="provider_reports_no_cache_usage"),
+ ],
+ )
@pytest.mark.asyncio
- async def test_on_success_emits_cache_tokens_when_present(
- self, callback: PostHogCallback, auth_user: AuthenticatedUser, mock_posthog_client: tuple
+ async def test_on_success_maps_cache_tokens_for_each_provider_usage_shape(
+ self,
+ callback: PostHogCallback,
+ auth_user: AuthenticatedUser,
+ mock_posthog_client: tuple,
+ model: str,
+ provider: str,
+ usage_object: dict,
+ expected: dict,
) -> None:
_, mock_client = mock_posthog_client
kwargs = {
"standard_logging_object": {
- "model": "claude-sonnet-4-6",
- "custom_llm_provider": "anthropic",
+ "model": model,
+ "custom_llm_provider": provider,
"prompt_tokens": 100,
"completion_tokens": 20,
- "metadata": {
- "usage_object": {
- "cache_read_input_tokens": 60,
- "cache_creation_input_tokens": 30,
- },
- },
+ "metadata": {"usage_object": usage_object},
},
"litellm_params": {},
}
@@ -464,29 +500,11 @@ class TestPostHogCallback:
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
+ assert {
+ key: props[key]
+ for key in ("$ai_cache_read_input_tokens", "$ai_cache_creation_input_tokens")
+ if key in props
+ } == expected
@pytest.mark.parametrize(
"cost_breakdown,expected_props",