Repository navigation
fix(python-sdk): report prompt-cache tokens for Gradient chat spans - #2007
Conversation
Reviewer's GuideImplementationExtract and retain cache usage from chat payloads, apply cache-aware pricing, and emit cache counts on spans and inference events.
Initialize cache-token state in sync and async Gradient stream scopes and apply it in the inline agent-chat response paths.
TestsAdd regression tests for cache-token extraction, retention and overrides, emitted attributes and events, pricing, and sync/async Gradient wrapper paths.
Tips and commandsInteracting with Sourcery
Customizing Your ExperienceAccess your dashboard to:
Getting Help
|
PR Summary by Qodofix(python-sdk): report cached prompt tokens on Gradient chat spans
AI Description
Merge Risk
|
Code Review by Qodo
1.
|
There was a problem hiding this comment.
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
| """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) |
There was a problem hiding this comment.
🟡 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`.
Merged PR summary
Generated from the merged PR description and bounded, component-scoped file evidence. Release preparation reuses this validated summary. |
Important
feat: ...orfix(client): ....Issue number: #2005
Change description:
Gradient chat spans read only
prompt_tokensandcompletion_tokens, callget_chat_model_costwith no cache arguments and never set the cache usage attributes. The siblingpydoinstrumentation 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 newapply_cache_usagereadscache_read_input_tokens(falling back toprompt_tokens_details.cached_tokens) andcache_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_scopestarts both counts at 0.common_chat_logicpassescache_read_tokens,cache_creation_tokensandprompt_tokens_include_cache=Truetoget_chat_model_cost, and setsgen_ai.usage.cache_read.input_tokensandgen_ai.usage.cache_creation.input_tokenson the span. The inference event carries both counts when they are non-zero.gradient.pyandasync_gradient.py: the stream wrapper classes initialise the two fields, and the inline agent-chat non-streaming path callsapply_cache_usage.prompt_tokens_include_cache=Trueis right because DigitalOcean documents both counts as subsets of the prompt tokens (completion_usagein their OpenAPI spec), and it is whatpydoand the OpenAI instrumentation use. The attributes are set even when the count is 0, as inpydo,openaiandanthropic.Tested with
sdk/python/tests/test_gradient_cache_tokens.py(16 tests, no network): it drives the realprocess_chunk,process_chat_responseand the sync and async stream wrappers with an in-memory span exporter, and a spy onget_chat_model_costasserts the exact arguments and an exact cost (2.1075 with cache against 4.5 without, hand-computed from the test pricing).assert None == 900ongen_ai.usage.cache_read.input_tokens.pylint10.00/10. The other cheapsdk/pythontests give the same pass and fail set with and without the change.Things a reviewer should know:
assets/pricing.jsonhas cache prices; today that is effectively theopenai/gpt-oss-*ids. For every other Gradient model the cost is unchanged and only the attributes are new.input_tokens_details.cached_tokens, which this PR does not read. Becausecommon_chat_logicis shared, Responses spans now carrycache_read=0. That is a separate follow-up.reasoning_content) touches the same file in different lines.Checklist
If your change doesn't seem to apply, please leave them unchecked.
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:
Enhancements:
Tests: