Skip to content

feat: serialize prompt-cache creation tokens on LlmResponse - #6821

Open
gurjot-05 wants to merge 1 commit into
google:mainfrom
gurjot-05:feat/serialize-cache-creation-tokens
Open

feat: serialize prompt-cache creation tokens on LlmResponse#6821
gurjot-05 wants to merge 1 commit into
google:mainfrom
gurjot-05:feat/serialize-cache-creation-tokens

Conversation

@gurjot-05

@gurjot-05 gurjot-05 commented Aug 19, 2026

Copy link
Copy Markdown
Contributor

What

Adds a serializable LlmResponse.cache_creation_token_count field (inherited by Event, emitted as cacheCreationTokenCount) for prompt-cache write tokens.

Why

#5835 / d0b33a0 extract cache-creation tokens and attach them to GenerateContentResponseUsageMetadata via object.__setattr__ for OpenTelemetry. But google.genai's usage type is extra='forbid', so that attribute is dropped by model_dump() — it never reaches serialized events. So the Dev UI, persisted sessions, and SSE consumers can't see cache-write (only OTel / in-memory getattr can).

This surfaces the same value on the serializable LlmResponse — the cache-write counterpart to usage_metadata.cached_content_token_count (read) — next to the existing top-level cache_metadata field. (It can't live inside usage_metadata: an extra key there makes event reload raise a ValidationError, breaking session persistence.)

Changes

  • llm_response.py: new cache_creation_token_count: Optional[int] field.
  • anthropic_llm.py / lite_llm.py: populate it from the already-extracted value (streaming + non-streaming). OTel path unchanged.
  • Tests extended to assert the serialized field.

Companion PR

Dev-UI counterpart that displays this value: google/adk-web#492 — please merge together.

Commit d0b33a0 extracts cache-creation (write) tokens and attaches them
to the GenerateContentResponseUsageMetadata object via object.__setattr__
so they reach OpenTelemetry. But google.genai's usage type forbids extra
fields, so that attribute is dropped by model_dump() and never appears in
serialized events -- the dev UI, persisted sessions, and SSE consumers
cannot see cache-write tokens.

Surface the same count on a serializable
LlmResponse.cache_creation_token_count field (inherited by Event, emitted
as cacheCreationTokenCount, omitted when None). It is the cache-write
counterpart to usage_metadata.cached_content_token_count. Populated from
the already-extracted value in the Anthropic and LiteLLM paths (streaming
and non-streaming); the OpenTelemetry path is left unchanged.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants