Skip to content

fix(llm): pass stream_options to preserve cache token metrics in streaming mode - #2897

Merged
xingyaoww merged 2 commits into
mainfrom
fix/streaming-cache-token-reporting
Apr 21, 2026
Merged

xingyaoww merged 2 commits into
mainfrom
fix/streaming-cache-token-reporting

Conversation

@xingyaoww

@xingyaoww xingyaoww commented Apr 20, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #2896 — cache_read_tokens (and cache_write_tokens) are always reported as 0 when stream=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:

  1. The proxy auto-adds stream_options={"include_usage": True} to the upstream provider call, so the provider sends a final usage-only chunk with prompt_tokens_details.cached_tokens.

  2. The client-side litellm streaming handler discards this usage-only chunk because the SDK doesn't pass stream_options:

    # streaming_handler.py — usage-only chunk (empty choices)
    else:
        if (self.stream_options is not None
            and self.stream_options["include_usage"] is True):
            return model_response  # ← Not taken
        return  # ← Silently discarded!
  3. The handler falls back to calculate_total_usage() which only keeps prompt_tokens and completion_tokens, dropping prompt_tokens_details (which contains cached_tokens).

Fix

A one-line change in _transport_call(): when streaming is enabled, set stream_options={"include_usage": True} by default. This ensures the client-side streaming handler doesn't discard the usage-only chunk, and prompt_tokens_details.cached_tokens survives through stream_chunk_builder into telemetry metrics.

Uses setdefault so callers can override if needed.

Test

Added test_llm_streaming_preserves_cache_read_tokens which:

  • Creates realistic streaming chunks including a usage-only final chunk with cached_tokens=4000 (simulating what a LiteLLM proxy sends)
  • Lets the real stream_chunk_builder reassemble them (not mocked)
  • Verifies stream_options={"include_usage": True} is passed to litellm_completion
  • Verifies cache_read_tokens=4000 appears in response.metrics.accumulated_token_usage
  • Verifies prompt_tokens_details.cached_tokens=4000 is preserved in response.raw_response.usage

The test fails before the fix (stream_options is None) and passes after.

Verification

$ python -m pytest tests/sdk/llm/ --ignore=tests/sdk/llm/auth/test_openai.py
======================= 626 passed, 8 warnings in 24.86s =======================

All 626 LLM tests pass (1 pre-existing failure in auth/test_openai.py unrelated 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

Variant Architectures Base Image Docs / Tags
java amd64, arm64 eclipse-temurin:17-jdk Link
python amd64, arm64 nikolaik/python-nodejs:python3.13-nodejs22-slim Link
golang amd64, arm64 golang:1.21-bookworm Link

Pull (multi-arch manifest)

# Each variant is a multi-arch manifest supporting both amd64 and arm64
docker pull ghcr.io/openhands/agent-server:c90a3ee-python

Run

docker run -it --rm \
  -p 8000:8000 \
  --name agent-server-c90a3ee-python \
  ghcr.io/openhands/agent-server:c90a3ee-python

All tags pushed for this build

ghcr.io/openhands/agent-server:c90a3ee-golang-amd64
ghcr.io/openhands/agent-server:c90a3ee-golang_tag_1.21-bookworm-amd64
ghcr.io/openhands/agent-server:c90a3ee-golang-arm64
ghcr.io/openhands/agent-server:c90a3ee-golang_tag_1.21-bookworm-arm64
ghcr.io/openhands/agent-server:c90a3ee-java-amd64
ghcr.io/openhands/agent-server:c90a3ee-eclipse-temurin_tag_17-jdk-amd64
ghcr.io/openhands/agent-server:c90a3ee-java-arm64
ghcr.io/openhands/agent-server:c90a3ee-eclipse-temurin_tag_17-jdk-arm64
ghcr.io/openhands/agent-server:c90a3ee-python-amd64
ghcr.io/openhands/agent-server:c90a3ee-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim-amd64
ghcr.io/openhands/agent-server:c90a3ee-python-arm64
ghcr.io/openhands/agent-server:c90a3ee-nikolaik_s_python-nodejs_tag_python3.13-nodejs22-slim-arm64
ghcr.io/openhands/agent-server:c90a3ee-golang
ghcr.io/openhands/agent-server:c90a3ee-java
ghcr.io/openhands/agent-server:c90a3ee-python

About Multi-Architecture Support

  • Each variant tag (e.g., c90a3ee-python) is a multi-arch manifest supporting both amd64 and arm64
  • Docker automatically pulls the correct architecture for your platform
  • Individual architecture tags (e.g., c90a3ee-python-amd64) are also available if needed

…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>
@xingyaoww
xingyaoww marked this pull request as ready for review April 20, 2026 20:25
@github-actions

github-actions Bot commented Apr 20, 2026 •

Copy link
Copy Markdown
Contributor

Python API breakage checks — ✅ PASSED

Result: ✅ PASSED

Action log

@github-actions

github-actions Bot commented Apr 20, 2026 •

Copy link
Copy Markdown
Contributor

REST API breakage checks (OpenAPI) — ✅ PASSED

Result: ✅ PASSED

Action log

@github-actions

github-actions Bot commented Apr 20, 2026 •

Copy link
Copy Markdown
Contributor

Coverage

Coverage Report •
FileStmtsMissCoverMissing
openhands-sdk/openhands/sdk/llm
   llm.py5207885%466, 485, 541, 801, 907, 909–910, 938, 984, 995–997, 1001–1005, 1013–1015, 1025–1027, 1030–1031, 1035, 1037–1038, 1040, 1271–1272, 1469–1470, 1479, 1492, 1494–1499, 1501–1518, 1521–1525, 1527–1528, 1534–1543, 1598, 1600
TOTAL22972646971% 

@all-hands-bot all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🟢 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 all-hands-bot left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

✅ 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_options is None, causing LiteLLM's streaming handler to discard the usage-only chunk containing prompt_tokens_details.cached_tokens
  • With the fix (PR branch): Test passes — stream_options={"include_usage": True} is correctly passed to litellm_completion, and cache tokens are preserved in the response metrics
  • The one-line change in _transport_call() uses setdefault so callers can override if needed
  • All 626 LLM tests pass, confirming no regressions
Phase Result
Environment Setup ✅ Dependencies installed, tests runnable
CI & Tests ⚠️ 626/626 LLM tests pass, pre-commit has type check errors
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 -xvs

Output:

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-2897

Step 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 -xvs

Output:

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:

  1. stream_options={"include_usage": True} is passed to litellm_completion
  2. The streaming handler no longer discards the usage-only chunk
  3. cache_read_tokens=4000 is correctly preserved in response.metrics.accumulated_token_usage
  4. prompt_tokens_details.cached_tokens=4000 is correctly preserved in response.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 -q

Result: 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.

Comment thread tests/sdk/llm/test_llm_completion.py Resolved
@xingyaoww

Copy link
Copy Markdown
Contributor Author

@OpenHands please fix https://github.com/OpenHands/software-agent-sdk/actions/runs/24688577311/job/72204253034?pr=2897

@openhands-ai

openhands-ai Bot commented Apr 20, 2026

Copy link
Copy Markdown

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>
@openhands-ai

openhands-ai Bot commented Apr 20, 2026

Copy link
Copy Markdown

Summary

The PR #2897 had a failing CI job (pre-commit checks). I identified and fixed two issues:

Checklist

  • Ruff format errors: Two files (llm.py and test_llm_completion.py) had multi-line expressions that ruff wanted collapsed to single lines. Fixed by accepting ruff's formatting.
  • Pyright type errors (9 errors): ModelResponse.usage is a dynamic extra field from litellm (extra = "allow"), invisible to pyright's static analysis. Fixed by introducing a raw_resp: Any intermediate variable in the test, which is the appropriate pattern when accessing dynamic attributes on third-party Pydantic models.
  • All pre-commit hooks pass locally (ruff format, ruff lint, pycodestyle, pyright, import dependency rules, tool subclass registration).
  • The test still passes after the changes.
  • Changes pushed to the PR branch, CI workflows triggered.

Conciseness

The 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:

  1. One formatting fix in llm.py (collapsing a 3-line setdefault call to 1 line)
  2. In test_llm_completion.py: adding Any to imports, using raw_resp: Any for dynamic attribute access, and accepting ruff's reformatting of a few lines

@xingyaoww
xingyaoww merged commit 6d828ed into main Apr 21, 2026
31 of 32 checks passed
@xingyaoww
xingyaoww deleted the fix/streaming-cache-token-reporting branch April 21, 2026 13:34
StressTestor pushed a commit to StressTestor/software-agent-sdk that referenced this pull request Jun 1, 2026
…aming mode (OpenHands#2897)

Co-authored-by: openhands <openhands@all-hands.dev>
pengzhang-create pushed a commit to Pyromind-Dynamics/software-agent-sdk that referenced this pull request Aug 13, 2026
…aming mode (OpenHands#2897)

Co-authored-by: openhands <openhands@all-hands.dev>
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.

fix(llm): cache token usage (cache_read_tokens) always reported as 0 when streaming is enabled

4 participants