Repository navigation
feat(interactions): cost tracking for the Google Interactions API - #33297
mateo-berri wants to merge 2 commits into
Conversation
… success-handler billing
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Greptile SummaryThis PR fixes zero-dollar billing for the Google Interactions API by implementing
Confidence Score: 4/5The 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
|
| 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)
-
litellm/litellm_core_utils/litellm_logging.py, line 1899 (link)Streaming result skips usage transformation.
_transform_usage_objectsis called with the originalresult, which for the streaming path is still anInteractionsAPIStreamingResponse— not theInteractionsAPIResponsethatnormalize_logging_resultproduced. Theisinstance(result, InteractionsAPIResponse)branch therefore never matches, so theresultforwarded to logging callbacks carries rawusage: Dict | Nonerather than a typedUsageobject. Non-streaming interactions are correctly transformed; streaming interactions are not, creating a format inconsistency for any callback accessingresult.usagedirectly. The billing itself is correct because it flows throughstandard_logging_object.
Reviews (1): Last reviewed commit: "test(interactions): cover usage transfor..." | Re-trigger Greptile
| def _tokens_by_modality(modality_entries: object) -> Mapping[str, int]: | ||
| if not isinstance(modality_entries, Sequence): | ||
| return {} |
There was a problem hiding this comment.
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.
| 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) |
There was a problem hiding this comment.
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.
| 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) |
| 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 | ||
| ) |
There was a problem hiding this comment.
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"), |
There was a problem hiding this comment.
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.
PR overviewThis 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 |
|
Ran this branch at The biggest is Second, Third, agent-only interactions are still unpriced. One supporting note on Happy to send any of these as commits to this branch if that is useful |
|
Superseded by #33310, which shipped the complete cost and spend tracking for the Google Interactions API and merged. Closing this earlier version. |
Relevant issues
Linear ticket
Pre-Submission checklist
Please complete all items before asking a LiteLLM maintainer to review your PR
@greptileaito 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 withapi_key: os.environ/GEMINI_API_KEY. The port differs between runs because another proxy was occupying 4000 during the after runBefore, captured at 668df94 (port 4000):
The interaction completes with real usage (
"total_input_tokens": 6, "total_output_tokens": 0, "total_thought_tokens": 103) but the request is billed at zeroAfter, 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}}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 thatType
🆕 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'sUsage, 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 innerlitellm.responses()call. This matters more now that gemini-omni-flash-preview serves exclusively through the Interactions APIInteractionsUsageObjectTransformation(inllm_cost_calc/usage_object_transformation.py, next to the existing transcription transformation) converts an Interactions usage dict into a chatUsage:total_input_tokensbecomes prompt tokens,total_output_tokensplus thought tokens becomes completion tokens (matching the Gemini generateContent convention where completion includes reasoning), thought tokens land incompletion_tokens_details.reasoning_tokens(both the live API'stotal_thought_tokenskey and the OpenAPI spec'stotal_reasoning_tokensare handled),total_cached_tokenslands inprompt_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 theoutput_cost_per_video_tokensupport from #33274 lands; the two PRs compose without double countingThe cost calculator sniffs this usage shape in
_get_usage_objectand in thecompletion_costextraction loop, mirroring how Responses API usage is detected. The logging layer recognizesInteractionsAPIResponseresults forcreate_interaction/acreate_interaction(newCallTypesmembers), computes response cost and the standard logging payload for them, and converts the terminalinteraction.completedstreaming event into anInteractionsAPIResponseso 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 pollFinal Attestation