Skip to content

feat(interactions): cost tracking for the Google Interactions API - #33297

Closed
mateo-berri wants to merge 2 commits into
litellm_internal_stagingfrom
litellm_interactions_cost_tracking
Closed

mateo-berri wants to merge 2 commits into
litellm_internal_stagingfrom
litellm_interactions_cost_tracking

Conversation

@mateo-berri

Copy link
Copy Markdown
Contributor

Relevant issues

Linear ticket

Pre-Submission checklist

Please complete all items before asking a LiteLLM maintainer to review your PR

  • I have added meaningful tests
  • My PR passes all CI/CD checks (e.g., lint, format, unit tests)
  • My PR's scope is as isolated as possible; it only solves 1 specific problem
  • I have received a Greptile Confidence Score of at least 4/5 before requesting a maintainer review (Greptile reviews automatically once the PR is opened; only comment @greptileai to re-request a review after pushing changes)

Delays in PR merge?

If you're seeing a delay in your PR being merged, ping the LiteLLM Team on Slack (#pr-review).

Screenshots / Proof of Fix

Both proofs are live proxy calls against the real Google API with gemini/gemini-3.5-flash (input $1.50/1M, output and reasoning $9/1M in the cost map), config being a plain model_list entry with api_key: os.environ/GEMINI_API_KEY. The port differs between runs because another proxy was occupying 4000 during the after run

Before, captured at 668df94 (port 4000):

curl -s -D - http://localhost:4000/v1beta/interactions \
  -H "Authorization: Bearer sk-1234" -H "Content-Type: application/json" \
  -d '{"model": "gemini-3.5-flash", "input": "Reply with exactly: pong"}'

The interaction completes with real usage ("total_input_tokens": 6, "total_output_tokens": 0, "total_thought_tokens": 103) but the request is billed at zero

x-litellm-response-cost-original: 0.0

After, captured at a798aca (port 4100), same command:

{"status": "completed", "usage": {"total_tokens": 93, "total_input_tokens": 6, "input_tokens_by_modality": [{"modality": "text", "tokens": 6}], "total_cached_tokens": 0, "total_output_tokens": 1, "total_tool_use_tokens": 0, "total_thought_tokens": 86}}
x-litellm-response-cost: 0.0007920000000000001

That is exactly 6 * $1.5e-06 + (1 + 86) * $9e-06 = $0.000792, so the header lands on the rate card to the digit

A follow-up GET of the same interaction (GET /v1beta/interactions/{id}) reports the interaction's cost in the display header but is excluded from success-handler billing, so polling a background interaction cannot write spend repeatedly; there is a regression test pinning that

Type

🆕 New Feature
🐛 Bug Fix

Changes

The Google Interactions API surface (/v1beta/interactions, litellm.create_interaction) never mapped its usage shape (total_input_tokens, output_tokens_by_modality, total_thought_tokens, ...) into LiteLLM's Usage, so every native Gemini interaction was billed $0 in the response cost header, spend logs, and logging callbacks. Only the bridge path for non-Interactions providers tracked cost, via the inner litellm.responses() call. This matters more now that gemini-omni-flash-preview serves exclusively through the Interactions API

InteractionsUsageObjectTransformation (in llm_cost_calc/usage_object_transformation.py, next to the existing transcription transformation) converts an Interactions usage dict into a chat Usage: total_input_tokens becomes prompt tokens, total_output_tokens plus thought tokens becomes completion tokens (matching the Gemini generateContent convention where completion includes reasoning), thought tokens land in completion_tokens_details.reasoning_tokens (both the live API's total_thought_tokens key and the OpenAPI spec's total_reasoning_tokens are handled), total_cached_tokens lands in prompt_tokens_details.cached_tokens, and the per-modality breakdowns fill text, image, audio, and video token detail fields on both sides. The video detail fields mean video output (gemini-omni-flash-preview) will price at the video rate as soon as the output_cost_per_video_token support from #33274 lands; the two PRs compose without double counting

The cost calculator sniffs this usage shape in _get_usage_object and in the completion_cost extraction loop, mirroring how Responses API usage is detected. The logging layer recognizes InteractionsAPIResponse results for create_interaction/acreate_interaction (new CallTypes members), computes response cost and the standard logging payload for them, and converts the terminal interaction.completed streaming event into an InteractionsAPIResponse so the streaming path is billed identically; the standard payload and callback copies carry the transformed chat-shaped usage. Recognition is gated on the create call types so GET polling of background interactions does not generate spend entries per poll

Final Attestation

  • The tests check the right things, including the edge cases, and regressions in the respective real-world customer use-cases are not possible after this PR

@mateo-berri
mateo-berri requested review from tin-berri and removed request for ryan-crabbe-berri July 14, 2026 23:27
@codecov

codecov Bot commented Jul 14, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.03922% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
litellm/litellm_core_utils/litellm_logging.py 95.65% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@greptile-apps

greptile-apps Bot commented Jul 14, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes zero-dollar billing for the Google Interactions API by implementing InteractionsUsageObjectTransformation, which maps the Interactions usage shape (total_input_tokens, total_output_tokens, total_thought_tokens, per-modality breakdowns) into LiteLLM's standard Usage object. The transformation is wired into the cost calculator, the standard logging payload builder, and the success-handler billing path for both streaming and non-streaming create_interaction calls.

  • InteractionsUsageObjectTransformation.transform_interactions_usage_to_chat_usage converts Interactions usage to chat Usage, with thought tokens added to completion_tokens and placed in completion_tokens_details.reasoning_tokens, matching the Gemini generateContent convention.
  • The logging layer converts the terminal interaction.completed streaming event to an InteractionsAPIResponse so streaming interactions are billed identically to non-streaming ones; GET poll calls are explicitly excluded from billing.
  • Three new integration-level tests pin the end-to-end billing math for create (non-streaming), create (streaming), and GET poll scenarios.

Confidence Score: 4/5

The core billing fix is correct and well-tested; the non-blocking findings are minor edge cases in the transformation helpers that do not affect real-world cost accuracy.

The billing math, streaming terminal-event detection, and GET-poll exclusion all work correctly and are covered by unit tests. Three minor concerns exist in usage_object_transformation.py: str matches isinstance(modality_entries, Sequence) so a malformed string silently returns {}; total_tokens=0 is treated as falsy and replaced by the computed sum; and the is_interactions_usage_dict heuristic is broad enough that a future provider using total_input_tokens or total_output_tokens could be misclassified. Additionally, the streaming result returned from _success_handler_helper_fn is not passed through _transform_usage_objects, so callbacks that inspect result.usage directly see a raw dict rather than a typed Usage object for streaming interactions. None of these affect the spend tracking or response-cost header.

litellm/litellm_core_utils/llm_cost_calc/usage_object_transformation.py — the detection heuristic and the total_tokens fallback; litellm/litellm_core_utils/litellm_logging.py — the streaming result is not transformed in _transform_usage_objects.

Important Files Changed

Filename Overview
litellm/litellm_core_utils/llm_cost_calc/usage_object_transformation.py Adds InteractionsUsageObjectTransformation with usage dict detection and token mapping; minor issues with str-as-Sequence guard, total_tokens=0 falsy override, and broad heuristic keys.
litellm/litellm_core_utils/litellm_logging.py Wires InteractionsAPIResponse and streaming terminal event into the success-handler billing path; streaming result not transformed in _transform_usage_objects, but billing via standard_logging_object is correct.
litellm/cost_calculator.py Adds Interactions usage detection in _get_usage_object and completion_cost extraction loop, mirroring the existing Responses API pattern; ordering is correct.
litellm/types/utils.py Adds create_interaction and acreate_interaction to CallTypes enum and updates the UI schema TypeScript definition accordingly.
tests/test_litellm/litellm_core_utils/llm_cost_calc/test_usage_object_transformation.py New unit tests covering modality mapping, reasoning key fallback, cached tokens, and empty input; no real network calls, all mock data.
tests/test_litellm/litellm_core_utils/test_litellm_logging.py Adds three regression tests: non-streaming create bills correctly, streaming terminal event bills correctly, GET poll does not generate spend entries.
tests/test_litellm/test_cost_calculator.py Adds test_completion_cost_interactions_api_response which validates end-to-end cost calculation from raw Interactions usage, including thought tokens.
ui/litellm-dashboard/src/lib/http/schema.d.ts Generated TypeScript schema updated to include create_interaction and acreate_interaction in the CallTypes union type.

Comments Outside Diff (1)

  1. litellm/litellm_core_utils/litellm_logging.py, line 1899 (link)

    P2 Streaming result skips usage transformation. _transform_usage_objects is called with the original result, which for the streaming path is still an InteractionsAPIStreamingResponse — not the InteractionsAPIResponse that normalize_logging_result produced. The isinstance(result, InteractionsAPIResponse) branch therefore never matches, so the result forwarded to logging callbacks carries raw usage: Dict | None rather than a typed Usage object. Non-streaming interactions are correctly transformed; streaming interactions are not, creating a format inconsistency for any callback accessing result.usage directly. The billing itself is correct because it flows through standard_logging_object.

Reviews (1): Last reviewed commit: "test(interactions): cover usage transfor..." | Re-trigger Greptile

Comment on lines +44 to +46
def _tokens_by_modality(modality_entries: object) -> Mapping[str, int]:
if not isinstance(modality_entries, Sequence):
return {}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 str is a Sequence in Python, so not isinstance(modality_entries, Sequence) is False for strings. If the API ever returns a malformed string in place of a list, the function would silently iterate over individual characters — none of which pass isinstance(entry, Mapping), so it returns {} rather than raising. Using list (or (list, tuple)) is a narrower and more intent-revealing check.

Suggested change
def _tokens_by_modality(modality_entries: object) -> Mapping[str, int]:
if not isinstance(modality_entries, Sequence):
return {}
def _tokens_by_modality(modality_entries: object) -> Mapping[str, int]:
if not isinstance(modality_entries, list):
return {}

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

)
completion_tokens = _coerce_optional_token_count(usage.get("total_output_tokens")) + reasoning_tokens
cached_tokens = _coerce_optional_token_count(usage.get("total_cached_tokens"))
total_tokens = _coerce_optional_token_count(usage.get("total_tokens")) or (prompt_tokens + completion_tokens)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 The or short-circuits on falsiness, so when the API explicitly reports total_tokens=0 the expression falls through to prompt_tokens + completion_tokens. In practice 0 total tokens is extremely rare, but if both the API field and the computed sum happen to differ (e.g. partial-request errors), the stored total will silently disagree with what the API returned. Using is not None avoids this.

Suggested change
total_tokens = _coerce_optional_token_count(usage.get("total_tokens")) or (prompt_tokens + completion_tokens)
_api_total = usage.get("total_tokens")
total_tokens = _coerce_optional_token_count(_api_total) if _api_total is not None else (prompt_tokens + completion_tokens)

Comment on lines +57 to +62
return (
"total_input_tokens" in usage_object
or "total_output_tokens" in usage_object
or "input_tokens_by_modality" in usage_object
or "output_tokens_by_modality" in usage_object
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 is_interactions_usage_dict uses four independent or branches, so any dict that happens to contain total_input_tokens or total_output_tokens — including a future provider that adopts similar key naming — would be silently routed through the Interactions transformation path in _get_usage_object and completion_cost. Adding a composite check (e.g. requiring at least two of the keys, or requiring total_tool_use_tokens) would tighten the heuristic and reduce false-positive risk.

Note: If this suggestion doesn't match your team's coding style, reply to this and let me know. I'll remember it for next time!

text_tokens=output_tokens_by_modality.get("text"),
image_tokens=output_tokens_by_modality.get("image"),
audio_tokens=output_tokens_by_modality.get("audio"),
video_tokens=output_tokens_by_modality.get("video"),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

High: Video output tokens are not billed

An authenticated user can generate video while being charged only for text and reasoning tokens. This stores video usage in completion_tokens_details.video_tokens, but _parse_completion_tokens_details() and generic_cost_per_token() do not read that field; because text_tokens is explicitly populated, they also do not bill the unclassified remainder of completion_tokens. The included 17,376-video-token example is therefore billed for only 855 output tokens. Extend the downstream cost calculation to include video tokens at the configured video or fallback output rate, and add an end-to-end cost assertion using this multimodal example.

@veria-ai

veria-ai Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

PR overview

This pull request adds cost tracking support for the Google Interactions API, including transformation of usage details so token categories can feed into LiteLLM’s cost calculation path.

There is one open issue affecting billing correctness for generated video output. An authenticated user could generate video while the downstream cost calculation charges only text and reasoning tokens, leaving video token usage unbilled and creating a clear cost-abuse risk. No issues have been addressed yet, so the PR still needs a targeted fix before the cost tracking can be considered reliable.

Open issues (1)

Fixed/addressed: 0 · PR risk: 7/10

@codspeed

codspeed Bot commented Jul 14, 2026

Copy link
Copy Markdown
Contributor

Merging this PR will not alter performance

✅ 31 untouched benchmarks


Comparing litellm_interactions_cost_tracking (a798aca) with litellm_internal_staging (668df94)

Open in CodSpeed

@GanymedeNil

Copy link
Copy Markdown

Ran this branch at a798aca9a0 against mocked Interactions responses. The base case works exactly as advertised, 1000 input and 500 output tokens on gemini/gemini-2.5-flash costs 0.00155, so the InteractionsUsageObjectTransformation approach lands. Three usage fields that the API does return are still dropped, though, and one of them is expensive

The biggest is grounding_tool_count. It is in the live spec at https://ai.google.dev/static/api/interactions.openapi.json as an array of {type, count} with type in google_search, google_maps, retrieval, and it is the Interactions equivalent of the grounding requests that cost_per_web_search_request already prices for generateContent off search_context_cost_per_query. A response carrying "grounding_tool_count": [{"type": "google_search", "count": 3}] still costs 0.00155 on this branch, where the token cost plus three grounded queries at $0.035 would be 0.10655. Grounding dominates the bill for a search-heavy interaction, so this is the gap most likely to show up as real under-billing

Second, total_tool_use_tokens is not read. Injecting "total_tool_use_tokens": 200 leaves the cost at 0.00155 where 0.00161 is expected. For comparison VertexGeminiConfig._calculate_usage does fold toolUsePromptTokenCount into prompt_tokens, and zeroes it only when the response has search grounding, so the two Google surfaces currently disagree on whether tool-use prompt tokens are billable

Third, agent-only interactions are still unpriced. litellm.interactions.acreate(agent="deep-research-pro-preview-12-2025", input=...) never sets a model, so _hidden_params["response_cost"] comes back None rather than a number. A rate card for gemini/deep-research-pro-preview-12-2025 already exists in the cost map, so the missing piece is just carrying the agent name through as the pricing key. Every proof in the description uses model=, which is why this path stayed hidden

One supporting note on total_thought_tokens. Reading both that and total_reasoning_tokens is the right call, and worth keeping, but only the former appears in the live spec. litellm/types/interactions/generated.py declares total_reasoning_tokens and no total_thought_tokens, so the vendored types have drifted from the API and are worth regenerating separately

Happy to send any of these as commits to this branch if that is useful

@mateo-berri

Copy link
Copy Markdown
Contributor Author

Superseded by #33310, which shipped the complete cost and spend tracking for the Google Interactions API and merged. Closing this earlier version.

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.

3 participants