Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 39 additions & 1 deletion core/events/llm_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -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."""
Expand Down Expand Up @@ -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
39 changes: 39 additions & 0 deletions tests/test_llm_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
Loading