Skip to content

fix(python-sdk): report prompt-cache tokens for Gradient chat spans - #2007

Merged
AmanAgarwal041 merged 2 commits into
openlit:mainfrom
basil-k-aji-dev:fix/gradient-cache-tokens
Nov 29, 2026
Merged

AmanAgarwal041 merged 2 commits into
openlit:mainfrom
basil-k-aji-dev:fix/gradient-cache-tokens

Conversation

@basil-k-aji-dev

@basil-k-aji-dev basil-k-aji-dev commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Important

  1. We strictly follow a issue-first approach, please first open an issue relating to this Pull Request.
  2. PR title follows Conventional Commit format, for example feat: ... or
    fix(client): ....

Issue number: #2005

Change description:

Gradient chat spans read only prompt_tokens and completion_tokens, call get_chat_model_cost with no cache arguments and never set the cache usage attributes. The sibling pydo instrumentation covers the same DigitalOcean inference endpoint and handles all of it, so cached prompt tokens were missing from Gradient spans and were priced as ordinary input wherever the pricing table has cache prices.

What changed, mirroring pydo:

  • gradient/utils.py: a new apply_cache_usage reads cache_read_input_tokens (falling back to prompt_tokens_details.cached_tokens) and cache_created_input_tokens, and keeps an earlier value when a later chunk carries none. It is called for streaming chunks and for non-streaming responses. _new_scope starts both counts at 0. common_chat_logic passes cache_read_tokens, cache_creation_tokens and prompt_tokens_include_cache=True to get_chat_model_cost, and sets gen_ai.usage.cache_read.input_tokens and gen_ai.usage.cache_creation.input_tokens on the span. The inference event carries both counts when they are non-zero.
  • gradient.py and async_gradient.py: the stream wrapper classes initialise the two fields, and the inline agent-chat non-streaming path calls apply_cache_usage.

prompt_tokens_include_cache=True is right because DigitalOcean documents both counts as subsets of the prompt tokens (completion_usage in their OpenAPI spec), and it is what pydo and the OpenAI instrumentation use. The attributes are set even when the count is 0, as in pydo, openai and anthropic.

Tested with sdk/python/tests/test_gradient_cache_tokens.py (16 tests, no network): it drives the real process_chunk, process_chat_response and the sync and async stream wrappers with an in-memory span exporter, and a spy on get_chat_model_cost asserts the exact arguments and an exact cost (2.1075 with cache against 4.5 without, hand-computed from the test pricing).

  • Without the change: 15 of the 16 fail, for example assert None == 900 on gen_ai.usage.cache_read.input_tokens.
  • With the change: 16 passed. 20 mutants (dropping each read, cost argument, attribute, event key, wrapper init and agent path, plus wrong keys and flag values) were each caught. pylint 10.00/10. The other cheap sdk/python tests give the same pass and fail set with and without the change.

Things a reviewer should know:

  • The cost only changes for models whose entry in assets/pricing.json has cache prices; today that is effectively the openai/gpt-oss-* ids. For every other Gradient model the cost is unchanged and only the attributes are new.
  • The Gradient Responses API reports cached tokens under input_tokens_details.cached_tokens, which this PR does not read. Because common_chat_logic is shared, Responses spans now carry cache_read=0. That is a separate follow-up.
  • fix(python-sdk): end gradient streaming spans on close, drop, or error #1807 changes Gradient span lifecycle in the same package; the two merge cleanly. Bug: Python SDK Gradient streaming drops delta.reasoning_content #2006 (streamed reasoning_content) touches the same file in different lines.

Checklist

If your change doesn't seem to apply, please leave them unchecked.

  • PR title follows Conventional Commit format.
  • I have reviewed the contributing guidelines
  • Have you checked to ensure there aren't other open Pull Requests for the same update/change?
  • I have performed a self-review of this change
  • Changes have been tested
  • Changes are documented

Acknowledgment

By submitting this pull request, I confirm that you can use, modify, copy, and redistribute this contribution, under the terms of the project license.

Summary by Sourcery

Record and price prompt-cache usage for Gradient chat instrumentation.

Bug Fixes:

  • Report Gradient chat prompt-cache read and creation token usage on spans and inference events for both streaming and non-streaming responses.
  • Apply cache-aware pricing to Gradient chat spans while preserving explicit zero values and previously reported counts when later chunks omit cache data.

Enhancements:

  • Support both DigitalOcean flat cache usage fields and OpenAI-style cached prompt token details in Gradient instrumentation.

Tests:

  • Add regression coverage for synchronous and asynchronous streaming, non-streaming, agent-chat paths, cache usage fallbacks, event attributes, and cache-aware cost calculations.

@basil-k-aji-dev
basil-k-aji-dev requested review from a team and ishanjainn as code owners November 24, 2026 20:40
@sourcery-ai

sourcery-ai Bot commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Implementation

Extract and retain cache usage from chat payloads, apply cache-aware pricing, and emit cache counts on spans and inference events.

  • sdk/python/src/openlit/instrumentation/gradient/utils.py L310-317, L335-351, L611-618 (+5 small edits)

Initialize cache-token state in sync and async Gradient stream scopes and apply it in the inline agent-chat response paths.

  • sdk/python/src/openlit/instrumentation/gradient/async_gradient.py L19, L69-70, L293
  • sdk/python/src/openlit/instrumentation/gradient/gradient.py L18, L107-108, L329

Tests

Add regression tests for cache-token extraction, retention and overrides, emitted attributes and events, pricing, and sync/async Gradient wrapper paths.

  • sdk/python/tests/test_gradient_cache_tokens.py L1-615

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

PR Summary by Qodo

fix(python-sdk): report cached prompt tokens on Gradient chat spans

🐞 Bug fix 🧪 Tests 🕐 20-40 Minutes

Grey Divider

AI Description

• Record prompt-cache reads and creations across Gradient chat responses and streams.
• Apply cache-aware pricing and expose cache counts on spans and inference events.
• Add regression tests for sync, async, streaming, and non-streaming paths.
Merge Risk 🟡 Medium

Blast radius 🟢 Low 💥 1 capability

  • 1 affected end-to-end capability after fault-specific containment; implementation boundaries do not widen its functional scope.
  • The sync wrapper, async wrapper, streaming processors, non-streaming processor, common finalizer, span attributes and inference event all implement one bounded outcome: recording usage and estimated cost for Gradient chat completions.
  • They are technical hops of the same integration rather than independent capabilities.
  • No separate functional scope is supported by the changed code.
Sources

sdk/python/src/openlit/instrumentation/gradient/utils.py[335-349]

def apply_cache_usage(scope, usage):
    """Read prompt-cache counts from a chat-completions `usage` payload."""
    reported = [
        count
        for count in (
            usage.get("cache_read_input_tokens"),
            (usage.get("prompt_tokens_details") or {}).get("cached_tokens"),
        )
        if count is not None
    ]
    if reported:
        scope._cache_read_input_tokens = next((count for count in reported if count), 0)
    created = usage.get("cache_created_input_tokens")
    if created is not None:
        scope._cache_creation_input_tokens = created
Behavioral complexity 🟡 Medium 🧩 Multiple interactions

  • Before: Gradient instrumentation recorded prompt_tokens and completion_tokens and passed the prompt count directly to the existing cost helper; cache usage was absent from scope state, span attributes and inference-event payloads.
  • After: usage can arrive under either cache_read_input_tokens or prompt_tokens_details.cached_tokens, cache creation uses cache_created_input_tokens, repeated streaming chunks preserve prior values when fields are omitted and explicit zero values override prior values, and common finalization subtracts cache counts from inclusive prompt tokens before applying cache-specific prices.
  • New correctness conditions: (1) precedence between flat and nested cache-read formats must be deterministic; (2) null, omitted and explicit-zero values must have different state semantics across multiple streaming chunks; (3) the same cache state must remain consistent across sync, async, streaming, non-streaming, span, event and cost outputs; and (4) cache tokens must not be billed twice when prompt_tokens already includes them.
  • These are new interactions around an existing cost helper and response pipeline, not complexity inherited merely from using that helper.
Sources

sdk/python/src/openlit/instrumentation/gradient/utils.py[335-349]

def apply_cache_usage(scope, usage):
    """Read prompt-cache counts from a chat-completions `usage` payload."""
    reported = [
        count
        for count in (
            usage.get("cache_read_input_tokens"),
            (usage.get("prompt_tokens_details") or {}).get("cached_tokens"),
        )
        if count is not None
    ]
    if reported:
        scope._cache_read_input_tokens = next((count for count in reported if count), 0)
    created = usage.get("cache_created_input_tokens")
    if created is not None:
        scope._cache_creation_input_tokens = created
Potential damage 🟡 Medium 🩹 Incorrect results

  • If the changed parsing, precedence, state retention or cache-aware repricing regresses, the affected Gradient chat capability can emit incorrect cache token attributes, inference-event fields or estimated cost.
  • The effect is limited to observability and cost-accounting results for those instrumented calls; it does not alter the provider request, model output, user data or persistent application state.
  • Correcting the code prevents future incorrect records, but already exported telemetry or derived cost records are not automatically repaired and may require reprocessing or manual correction.
  • Equal-importance baseline is used; no business-criticality declaration was supplied.
  • Code rollback or correction restores future accounting.
  • Previously exported spans/events and downstream cost aggregates require whatever retention, reprocessing or manual correction facilities the external telemetry system provides; those facilities were not present in the repository.
Sources

sdk/python/src/openlit/instrumentation/gradient/utils.py[335-349]

def apply_cache_usage(scope, usage):
    """Read prompt-cache counts from a chat-completions `usage` payload."""
    reported = [
        count
        for count in (
            usage.get("cache_read_input_tokens"),
            (usage.get("prompt_tokens_details") or {}).get("cached_tokens"),
        )
        if count is not None
    ]
    if reported:
        scope._cache_read_input_tokens = next((count for count in reported if count), 0)
    created = usage.get("cache_created_input_tokens")
    if created is not None:
        scope._cache_creation_input_tokens = created
Assessed commit 5d1249d
Diagram

graph TD
  S["Sync wrapper"] --> P["Chat processing"] --> U["Cache usage"] --> F["Chat finalization"] --> C["Cache pricing"] --> T["Spans and events"]
  A["Async wrapper"] --> P
Loading
High-Level Assessment

The following are alternative approaches to this PR:

1. Share DigitalOcean cache parsing with pydo
  • ➕ Reduces duplicated parsing rules across instrumentations for the same inference endpoint.
  • ➖ Broadens this targeted fix into a cross-instrumentation refactor and requires pydo regression coverage.

Recommendation: Keep the scoped Gradient helper for this fix: it follows pydo’s existing token-accounting convention without changing another instrumentation. Consider a shared DigitalOcean usage parser if the two implementations continue to evolve together.

Files changed (4) +542 / -1

Bug fix (3) +53 / -1
async_gradient.pyCapture cache usage in asynchronous Gradient chat paths +4/-0

Capture cache usage in asynchronous Gradient chat paths

• Initializes cache counts on async stream wrappers and reads them from non-streaming agent-chat responses before finalization.

sdk/python/src/openlit/instrumentation/gradient/async_gradient.py

gradient.pyCapture cache usage in synchronous Gradient chat paths +4/-0

Capture cache usage in synchronous Gradient chat paths

• Initializes cache counts on sync stream wrappers and reads them from non-streaming agent-chat responses before finalization.

sdk/python/src/openlit/instrumentation/gradient/gradient.py

utils.pyPrice and report Gradient prompt-cache tokens +45/-1

Price and report Gradient prompt-cache tokens

• Extracts cache counts from chat usage, including a cached-token fallback, and retains counts when later chunks omit them. Passes the counts to inclusive-prompt cache pricing, sets span attributes even for zero counts, and includes nonzero counts in inference events.

sdk/python/src/openlit/instrumentation/gradient/utils.py

Tests (1) +489 / -0
test_gradient_cache_tokens.pyCover Gradient cache accounting across chat paths +489/-0

Cover Gradient cache accounting across chat paths

• Adds in-memory span and event tests for usage formats, chunk retention, cache-aware cost, and zero-cache behavior. Exercises sync and async streaming wrappers and non-streaming agent-chat paths without network calls.

sdk/python/tests/test_gradient_cache_tokens.py

@qodo-free-for-open-source-projects

qodo-free-for-open-source-projects Bot commented Nov 24, 2026 •

Copy link
Copy Markdown

Code Review by Qodo

🐞 Bugs (1) 📘 Rule violations (0) 📎 Requirement gaps (0) 🎨 UX issues (0) 🔗 Cross-repo conflicts (0) 📜 Skill insights (0)

Grey Divider


Remediation recommended

1. Later zero counts leave stale cache usage ✓ Resolved
Description
apply_cache_usage uses or to retain the previous cache counts, so an explicit zero in a later
usage chunk is treated as though the count were absent. If a stream reports nonzero counts and then
reports zero, the earlier counts remain on its span and are used to calculate its cost.

2. Responses spans report false zero counts 🐞 Bug ≡ Correctness
Description
common_chat_logic now writes zero-valued cache attributes for every scope, but the Responses API
processors never populate those fields from usage.input_tokens_details.cached_tokens. When a
Responses call has cached input, its span therefore reports zero cache-read tokens rather than
leaving that unmeasured count unset.
Code

sdk/python/src/openlit/instrumentation/gradient/utils.py[R606-609]

+    scope._span.set_attribute(
+        SemanticConvention.GEN_AI_USAGE_CACHE_READ_INPUT_TOKENS,
+        getattr(scope, "_cache_read_input_tokens", 0) or 0,
+    )
Evidence
_new_scope initializes both counts to zero, while the streaming and non-streaming Responses
processors read ordinary token usage without updating either cache count. Both paths reach the
shared attribute setter, which now emits those zeros; the Responses wrappers select these
processors.

sdk/python/src/openlit/instrumentation/gradient/utils.py[752-756]
sdk/python/src/openlit/instrumentation/gradient/utils.py[441-453]
sdk/python/src/openlit/instrumentation/gradient/utils.py[886-900]
sdk/python/src/openlit/instrumentation/gradient/gradient.py[350-383]
sdk/python/src/openlit/instrumentation/gradient/utils.py[605-613]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
The new unconditional cache attributes report zero for Responses API calls even when their usage contains cached input tokens.
## Fix Focus Areas
- sdk/python/src/openlit/instrumentation/gradient/utils.py[605-613]
- sdk/python/src/openlit/instrumentation/gradient/utils.py[441-453]
- sdk/python/src/openlit/instrumentation/gradient/utils.py[886-900]
## Recommended Fix
Parse Responses API cache usage in both streaming and non-streaming processors before the shared finalizer, or omit cache attributes for Responses calls until those counts are parsed. Test a Responses payload with `input_tokens_details.cached_tokens`.

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

Tip of the day
💡 Did you know, you can switch off images and animations for a plain-text comment

More tips ↗ | Customize Qodo ↗ | Qodo docs ↗

Grey Divider

Qodo Logo

@sourcery-ai sourcery-ai Bot left a comment

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.

Hey - I've found 2 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="sdk/python/src/openlit/instrumentation/gradient/utils.py" line_range="339" />
<code_context>
+    """Read prompt-cache counts from a chat-completions `usage` payload."""
+    scope._cache_read_input_tokens = (
+        usage.get("cache_read_input_tokens")
+        or (usage.get("prompt_tokens_details") or {}).get("cached_tokens", 0)
+        or scope._cache_read_input_tokens
+    )
</code_context>
<issue_to_address>
**Responses cache usage is missed**

When a Responses reply or completed stream places cached tokens in `usage.input_tokens_details.cached_tokens`, `process_responses_response` and `process_response_chunk` do not pass that count through `apply_cache_usage`, so `common_chat_logic` records zero cache-read tokens and prices them as ordinary input; callers see incorrect span usage and cost.

Extract `input_tokens_details.cached_tokens` in both Responses paths and pass it to `apply_cache_usage` before calling `common_chat_logic`.

Also at `sdk/python/src/openlit/instrumentation/gradient/utils.py:490-492`, `sdk/python/src/openlit/instrumentation/gradient/utils.py:607-613`.
</issue_to_address>

### Comment 2
<location path="sdk/python/src/openlit/instrumentation/gradient/utils.py" line_range="340" />
<code_context>
+    scope._cache_read_input_tokens = (
+        usage.get("cache_read_input_tokens")
+        or (usage.get("prompt_tokens_details") or {}).get("cached_tokens", 0)
+        or scope._cache_read_input_tokens
+    )
+    scope._cache_creation_input_tokens = (
</code_context>
<issue_to_address>
**Explicit zero cache counts stay stale**

When a stream first reports a nonzero cache count and a later usage payload explicitly reports zero, `apply_cache_usage` uses `or` for both cache counters, so the later zero preserves the earlier count and the finalized span, event, and cache-aware cost report stale cache usage.

Use presence or `None` checks instead of truthiness fallbacks so an explicit zero replaces the earlier count.

Also at `sdk/python/src/openlit/instrumentation/gradient/utils.py:344`.
</issue_to_address>

Sourcery assessment

Needs a human reviewer. 2 findings to address first, and if the cache counts are interpreted incorrectly, spans and inference events can retain inaccurate token and cost values after a revert. That affects bounded telemetry rather than moving money or changing request behavior, and the affected records can be corrected if the underlying usage data is available.

Blocking findings: sdk/python/src/openlit/instrumentation/gradient/utils.py:339, sdk/python/src/openlit/instrumentation/gradient/utils.py:340


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

"""Read prompt-cache counts from a chat-completions `usage` payload."""
scope._cache_read_input_tokens = (
usage.get("cache_read_input_tokens")
or (usage.get("prompt_tokens_details") or {}).get("cached_tokens", 0)

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.

🟡 Medium · Responses cache usage is missed

When a Responses reply or completed stream places cached tokens in usage.input_tokens_details.cached_tokens, process_responses_response and process_response_chunk do not pass that count through apply_cache_usage, so common_chat_logic records zero cache-read tokens and prices them as ordinary input; callers see incorrect span usage and cost.

Extract input_tokens_details.cached_tokens in both Responses paths and pass it to apply_cache_usage before calling common_chat_logic.

Also at sdk/python/src/openlit/instrumentation/gradient/utils.py:490-492, sdk/python/src/openlit/instrumentation/gradient/utils.py:607-613.

Prompt for AI agents
In `sdk/python/src/openlit/instrumentation/gradient/utils.py` at line 339:

**Responses cache usage is missed**

When a Responses reply or completed stream places cached tokens in `usage.input_tokens_details.cached_tokens`, `process_responses_response` and `process_response_chunk` do not pass that count through `apply_cache_usage`, so `common_chat_logic` records zero cache-read tokens and prices them as ordinary input; callers see incorrect span usage and cost.

Extract `input_tokens_details.cached_tokens` in both Responses paths and pass it to `apply_cache_usage` before calling `common_chat_logic`.

Also at `sdk/python/src/openlit/instrumentation/gradient/utils.py:490-492`, `sdk/python/src/openlit/instrumentation/gradient/utils.py:607-613`.

@AmanAgarwal041
AmanAgarwal041 merged commit da7953c into openlit:main Nov 29, 2026
13 of 14 checks passed
@github-actions

Copy link
Copy Markdown

Merged PR summary

  • Python SDK · Fixes — Gradient chat spans now report and price prompt-cache read and creation tokens for streaming and non-streaming responses.

Generated from the merged PR description and bounded, component-scoped file evidence. Release preparation reuses this validated summary.

This branch was successfully deployed

1 active deployment
release-notes — 5d1249d9 Deployed Nov 29, 2026 by AmanAgarwal041 via Summarize / Merged pull request #358
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants