Repository navigation
fix(llm): pass stream_options to preserve cache token metrics in streaming mode - #2897
Conversation
…aming mode
When streaming through a LiteLLM proxy, the proxy sends a final
usage-only chunk (empty choices) with prompt_tokens_details including
cached_tokens. Without stream_options={"include_usage": True} on
the client side, litellm's streaming handler silently discards this
chunk and falls back to calculate_total_usage() which only keeps
prompt_tokens/completion_tokens — losing cached_tokens entirely.
This is a display/reporting bug only: actual caching at the provider
still works, but cache_read_tokens and cache_write_tokens are always
reported as 0 in streaming mode, breaking cost tracking and cache hit
rate monitoring.
The fix sets stream_options={"include_usage": True} by default in
_transport_call() when streaming is enabled, ensuring the usage-only
chunk is not discarded and prompt_tokens_details survives through
stream_chunk_builder into telemetry metrics.
Fixes #2896
Co-authored-by: openhands <openhands@all-hands.dev>
Python API breakage checks — ✅ PASSEDResult: ✅ PASSED |
REST API breakage checks (OpenAPI) — ✅ PASSEDResult: ✅ PASSED |
Coverage Report •
|
||||||||||||||||||||
all-hands-bot
left a comment
There was a problem hiding this comment.
🟢 Good taste - Elegant, simple solution
This PR fixes a real reporting bug where cache token metrics were silently discarded during streaming. The one-line fix is minimal, well-commented, and thoroughly tested.
VERDICT: ✅ Worth merging
KEY INSIGHT: Using setdefault to add stream_options={"include_usage": True} ensures LiteLLM's streaming handler preserves detailed token breakdowns (including cached_tokens) without breaking existing overrides. The test validates both parameter passing and end-to-end metric preservation using realistic streaming chunks.
all-hands-bot
left a comment
There was a problem hiding this comment.
✅ QA Report: PASS WITH ISSUES
Successfully verified that stream_options={"include_usage": True} is now passed when streaming, preserving cache token metrics that were previously lost.
Does this PR achieve its stated goal?
Yes. The PR fixes the reporting bug where cache_read_tokens (and cache_write_tokens) are reported as 0 when stream=true, even though prompt caching works correctly at the provider level.
Evidence:
- Without the fix (main branch): Test fails because
stream_optionsisNone, causing LiteLLM's streaming handler to discard the usage-only chunk containingprompt_tokens_details.cached_tokens - With the fix (PR branch): Test passes —
stream_options={"include_usage": True}is correctly passed tolitellm_completion, and cache tokens are preserved in the response metrics - The one-line change in
_transport_call()usessetdefaultso callers can override if needed - All 626 LLM tests pass, confirming no regressions
| Phase | Result |
|---|---|
| Environment Setup | ✅ Dependencies installed, tests runnable |
| CI & Tests | |
| Functional Verification | ✅ Before/after test confirms fix works |
Functional Verification
Test 1: Reproduce the bug (without the fix)
Step 1 — Establish baseline on main branch:
Checked out main branch and copied the new test file to run it against the unfixed code:
git checkout main
git checkout pr-2897 -- tests/sdk/llm/test_llm_completion.py
uv run pytest tests/sdk/llm/test_llm_completion.py::test_llm_streaming_preserves_cache_read_tokens -xvsOutput:
FAILED tests/sdk/llm/test_llm_completion.py::test_llm_streaming_preserves_cache_read_tokens
AssertionError: Expected stream_options={include_usage: True}, got None
assert None == {'include_usage': True}
Interpretation: This confirms the bug exists on main — stream_options is not being set when streaming is enabled, which means LiteLLM's streaming handler will silently discard the usage-only chunk containing cache token details.
Step 2 — Apply the PR's changes:
Checked out the PR branch:
git checkout pr-2897Step 3 — Re-run with the fix in place:
uv run pytest tests/sdk/llm/test_llm_completion.py::test_llm_streaming_preserves_cache_read_tokens -xvsOutput:
tests/sdk/llm/test_llm_completion.py::test_llm_streaming_preserves_cache_read_tokens PASSED
======================== 1 passed, 5 warnings in 0.04s ==========================
Interpretation: The fix works. The test now passes because:
stream_options={"include_usage": True}is passed tolitellm_completion- The streaming handler no longer discards the usage-only chunk
cache_read_tokens=4000is correctly preserved inresponse.metrics.accumulated_token_usageprompt_tokens_details.cached_tokens=4000is correctly preserved inresponse.raw_response.usage
Test 2: Verify no regressions
Ran the full LLM test suite:
uv run pytest tests/sdk/llm/ --ignore=tests/sdk/llm/auth/test_openai.py -qResult: 626 passed, 11 warnings in 25.70s
Interpretation: All existing LLM tests continue to pass. The change is backward compatible and doesn't break any existing streaming or non-streaming behavior.
Issues Found
- 🟠 Important: Pre-commit type check fails with 9 pyright errors in the new test. See inline comments for details.
- 🟡 Minor: Ruff auto-formatted some lines (setdefault call, iter call). These changes were applied automatically and are cosmetic only.
|
I'm on it! xingyaoww can track my progress at all-hands.dev |
- Apply ruff formatting (collapse single-expression args to one line) - Use Any annotation for ModelResponse.usage access in test since litellm stores 'usage' as a dynamic extra field invisible to pyright Co-authored-by: openhands <openhands@all-hands.dev>
SummaryThe PR #2897 had a failing CI job (pre-commit checks). I identified and fixed two issues: Checklist
ConcisenessThe changes are minimal and targeted — only the two files that were already part of the PR were modified, with no extraneous changes. The edits consist of:
|
…aming mode (OpenHands#2897) Co-authored-by: openhands <openhands@all-hands.dev>
…aming mode (OpenHands#2897) Co-authored-by: openhands <openhands@all-hands.dev>
Summary
Fixes #2896 —
cache_read_tokens(andcache_write_tokens) are always reported as 0 whenstream=true, even though prompt caching works correctly at the provider level.This is a display/reporting bug only — actual caching at the provider still works and cost savings are realized, but cache hit rate monitoring, cost tracking dashboards, and telemetry are affected.
Root Cause
When the SDK streams through a LiteLLM proxy:
The proxy auto-adds
stream_options={"include_usage": True}to the upstream provider call, so the provider sends a final usage-only chunk withprompt_tokens_details.cached_tokens.The client-side litellm streaming handler discards this usage-only chunk because the SDK doesn't pass
stream_options:The handler falls back to
calculate_total_usage()which only keepsprompt_tokensandcompletion_tokens, droppingprompt_tokens_details(which containscached_tokens).Fix
A one-line change in
_transport_call(): when streaming is enabled, setstream_options={"include_usage": True}by default. This ensures the client-side streaming handler doesn't discard the usage-only chunk, andprompt_tokens_details.cached_tokenssurvives throughstream_chunk_builderinto telemetry metrics.Uses
setdefaultso callers can override if needed.Test
Added
test_llm_streaming_preserves_cache_read_tokenswhich:cached_tokens=4000(simulating what a LiteLLM proxy sends)stream_chunk_builderreassemble them (not mocked)stream_options={"include_usage": True}is passed tolitellm_completioncache_read_tokens=4000appears inresponse.metrics.accumulated_token_usageprompt_tokens_details.cached_tokens=4000is preserved inresponse.raw_response.usageThe test fails before the fix (
stream_optionsisNone) and passes after.Verification
All 626 LLM tests pass (1 pre-existing failure in
auth/test_openai.pyunrelated to this change).This PR was created by an AI assistant (OpenHands) on behalf of the user.
@xingyaoww can click here to continue refining the PR
Agent Server images for this PR
• GHCR package: https://github.com/OpenHands/agent-sdk/pkgs/container/agent-server
Variants & Base Images
eclipse-temurin:17-jdknikolaik/python-nodejs:python3.13-nodejs22-slimgolang:1.21-bookwormPull (multi-arch manifest)
# Each variant is a multi-arch manifest supporting both amd64 and arm64 docker pull ghcr.io/openhands/agent-server:c90a3ee-pythonRun
All tags pushed for this build
About Multi-Architecture Support
c90a3ee-python) is a multi-arch manifest supporting both amd64 and arm64c90a3ee-python-amd64) are also available if needed