From 773437d056730f3594813140013a9bde65413b5e Mon Sep 17 00:00:00 2001 From: raymondginger Date: Mon, 30 Nov 2026 18:58:25 +0800 Subject: [PATCH] feat(events): report prompt-cache hits as cached_tokens `UsageInfo` folded everything into `prompt_tokens`, so a host could not show whether a long prefix was actually cached. Providers already report the hit count under different names (DeepSeek `prompt_cache_hit_tokens`, OpenAI `prompt_tokens_details.cached_tokens`, Anthropic `cache_read_input_tokens`); read the first one that carries a count and expose it as `cached_tokens`, a subset of `prompt_tokens`. Tests: DeepSeek and OpenAI shapes, plus the uncached default. --- core/events/llm_events.py | 40 ++++++++++++++++++++++++++++++++++++++- tests/test_llm_events.py | 39 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 78 insertions(+), 1 deletion(-) diff --git a/core/events/llm_events.py b/core/events/llm_events.py index 1035ac271..0617d492d 100644 --- a/core/events/llm_events.py +++ b/core/events/llm_events.py @@ -73,14 +73,51 @@ class ToolCallEnd: @dataclass(frozen=True) class UsageInfo: - """Token accounting for the completed model turn.""" + """Token accounting for the completed model turn. + + ``cached_tokens`` is the prompt-prefix cache hit count the provider + reported (DeepSeek: ``prompt_cache_hit_tokens``; OpenAI: nested + ``prompt_tokens_details.cached_tokens``). It is a subset of + ``prompt_tokens`` and is kept separate so hosts can show cache + effectiveness instead of folding it into the input count. + """ prompt_tokens: int = 0 completion_tokens: int = 0 total_tokens: int = 0 + cached_tokens: int = 0 type: str = field(default="usage", init=False) +def _usage_int(usage: dict[str, Any], *path: str) -> int: + """Read an int from nested usage keys, missing or non-numeric → 0.""" + + current: Any = usage + for segment in path: + if not isinstance(current, dict): + return 0 + current = current.get(segment) + try: + return int(current or 0) + except (TypeError, ValueError): + return 0 + + +def _cached_tokens(usage: dict[str, Any]) -> int: + """First provider cache-hit field that carries a count.""" + + for path in ( + ("cached_tokens",), + ("prompt_cache_hit_tokens",), + ("cache_read_input_tokens",), + ("prompt_tokens_details", "cached_tokens"), + ): + value = _usage_int(usage, *path) + if value: + return value + return 0 + + @dataclass(frozen=True) class StreamError: """A terminal error. Errors are data, never exceptions on the stream.""" @@ -164,6 +201,7 @@ def llm_response_to_events(response: LLMResponse) -> list[LLMEvent]: + int(usage.get("completion_tokens", 0) or 0) ) ), + cached_tokens=_cached_tokens(usage), ) ) return events diff --git a/tests/test_llm_events.py b/tests/test_llm_events.py index 92bde8fbc..46e2b7b45 100644 --- a/tests/test_llm_events.py +++ b/tests/test_llm_events.py @@ -77,6 +77,45 @@ def test_tool_calls_become_tool_call_end(): assert usage.total_tokens == 15 # derived when not provided +def test_usage_carries_provider_cache_hits(): + deepseek = llm_response_to_events( + LLMResponse( + content="hi", + finish_reason="stop", + usage={ + "prompt_tokens": 1000, + "completion_tokens": 20, + "prompt_cache_hit_tokens": 900, + }, + ) + ) + usage = [e for e in deepseek if isinstance(e, UsageInfo)][0] + assert usage.cached_tokens == 900 + assert serialize_llm_event(usage)["cached_tokens"] == 900 + + openai = llm_response_to_events( + LLMResponse( + content="hi", + finish_reason="stop", + usage={ + "prompt_tokens": 1000, + "completion_tokens": 20, + "prompt_tokens_details": {"cached_tokens": 640}, + }, + ) + ) + assert [e for e in openai if isinstance(e, UsageInfo)][0].cached_tokens == 640 + + uncached = llm_response_to_events( + LLMResponse( + content="hi", + finish_reason="stop", + usage={"prompt_tokens": 10, "completion_tokens": 2}, + ) + ) + assert [e for e in uncached if isinstance(e, UsageInfo)][0].cached_tokens == 0 + + def test_error_response_is_single_stream_error(): events = llm_response_to_events( LLMResponse(content="boom", finish_reason="error", error_kind="timeout")