headroom/tests/test_litellm_nonstream_cache_usage.py
Abhay Singh 43a7b578a1
fix(backends): don't crash the OpenAI->Anthropic converter on empty choices (#2484)
## Description

`_to_anthropic_response` in both backends converts a non-streaming
OpenAI-shape response to Anthropic shape and indexes the first choice
directly:

```python
# headroom/backends/litellm.py
choice = litellm_response.choices[0]
# headroom/backends/anyllm.py
choice = response.choices[0]
```

A non-streaming upstream response can be HTTP 200 with an **empty**
`choices` list: Azure OpenAI content filtering does exactly this, and
any OpenAI-compatible gateway can return a usage-only / filtered turn
the same way. With `choices: []`, `choices[0]` raises `IndexError`,
which surfaces as a 500 for the request instead of a normal (if empty)
turn.

This is an intra-file asymmetry: the streaming siblings in the same two
files already guard it (`if not chunk.choices: continue` / `if
hasattr(chunk, "choices") and chunk.choices:`), and
`headroom/proxy/handlers/openai.py` documents the exact hazard in
`_apply_stream_usage_option`: "the common `chunk.choices[0].delta`
pattern then raises IndexError" on a usage-only `choices: []` chunk. The
non-streaming converters just never got the same guard.

## Fix

Return a valid empty assistant turn (`content: []`, `stop_reason:
"end_turn"`, usage still mapped) when `choices` is empty, before
indexing. The client gets a clean empty response instead of a 500,
matching how the streaming path already tolerates the same shape.
Non-empty responses are unchanged.

## Type of Change

- [x] Bug fix (non-breaking change that fixes an issue)
- [ ] New feature (non-breaking change that adds functionality)
- [ ] Breaking change (fix or feature that would cause existing
functionality to change)
- [ ] Documentation update
- [ ] Performance improvement
- [ ] Code refactoring (no functional changes)

## Changes Made

- `headroom/backends/litellm.py`: empty-`choices` guard at the top of
`_to_anthropic_response`, returning an empty assistant turn with mapped
usage.
- `headroom/backends/anyllm.py`: same guard in its
`_to_anthropic_response`.
- `tests/test_litellm_nonstream_cache_usage.py`,
`tests/test_backend_anyllm.py`: regressions passing an empty-`choices`
response through each converter and asserting an empty turn instead of
IndexError.

## Testing

- [x] Unit tests pass (`pytest`)
- [x] Linting passes (`ruff check .`)
- [x] Type checking passes (`mypy headroom`)
- [x] New tests added for new functionality
- [ ] Manual testing performed

### Test Output

```text
$ python -m pytest tests/test_litellm_nonstream_cache_usage.py::test_to_anthropic_response_empty_choices_returns_empty_turn tests/test_backend_anyllm.py::test_to_anthropic_response_empty_choices_returns_empty_turn -q
2 passed

# with the fix reverted, both fail with
# IndexError: list index out of range

$ uvx ruff@0.15.17 check headroom/backends/litellm.py headroom/backends/anyllm.py tests/test_backend_anyllm.py tests/test_litellm_nonstream_cache_usage.py
All checks passed!
$ uvx mypy@1.20.2 --ignore-missing-imports headroom/backends/litellm.py headroom/backends/anyllm.py
Success: no issues found in 2 source files
```

Note: `tests/test_backend_anyllm.py` has 7 `@pytest.mark.asyncio` tests
that fail locally because pytest-asyncio is not configured in this
environment (`Unknown config option: asyncio_mode`); they are unrelated
to this change and pass in CI. The two new tests here are synchronous
and pass locally.

## Real Behavior Proof

- Environment: Windows 11, Python 3.12, project venv (`uv sync --extra
proxy`), `uvx ruff@0.15.17` / `uvx mypy@1.20.2`, pytest in the venv.
- Exact command / steps: built a response stand-in with `choices=[]` and
a usage object, called `LiteLLMBackend._to_anthropic_response` (on a
bare `object.__new__` instance) and
`AnyLLMBackend._to_anthropic_response` (via the file's fake-backend
fixture); then reverted both backend files and re-ran.
- Observed result: with the fix each converter returns `{type: message,
role: assistant, content: [], stop_reason: end_turn, usage: {...}}` with
the input/output token counts mapped; with the fix reverted both raise
`IndexError: list index out of range`. Ran against the actual modules
via the two test files.
- Not tested: a live Azure OpenAI content-filtered response routed
through the backend end to end.

## Review Readiness

- [x] I have performed a self-review
- [x] This PR is ready for human review

## Checklist

- [x] My code follows the project's style guidelines
- [x] I have performed a self-review of my code
- [x] I have commented my code, particularly in hard-to-understand areas
- [ ] I have made corresponding changes to the documentation
- [x] My changes generate no new warnings
- [x] I have added tests that prove my fix is effective or that my
feature works
- [x] New and existing unit tests pass locally with my changes
- [ ] I have updated the CHANGELOG.md if applicable
2026-07-22 06:08:10 -07:00

110 lines
4.1 KiB
Python

"""Non-streaming LiteLLM responses must surface Bedrock cache token usage (GH #1345).
LiteLLM reports ``prompt_tokens`` as the total prompt size including cached
tokens, while the Anthropic response shape expects ``input_tokens`` to exclude
cache reads/writes and to carry ``cache_read_input_tokens`` /
``cache_creation_input_tokens`` alongside. The streaming and OpenAI paths
already map these fields; the non-streaming ``complete_message`` path dropped
them, so a working Bedrock prompt cache was indistinguishable from a broken
one for non-streaming clients.
"""
from __future__ import annotations
from types import SimpleNamespace
import pytest
litellm_backend = pytest.importorskip("headroom.backends.litellm")
_anthropic_usage_from_litellm = litellm_backend._anthropic_usage_from_litellm
def test_plain_usage_without_cache_fields() -> None:
usage = _anthropic_usage_from_litellm(SimpleNamespace(prompt_tokens=100, completion_tokens=7))
assert usage == {"input_tokens": 100, "output_tokens": 7}
def test_cache_read_surfaced_and_input_excludes_cached() -> None:
usage = _anthropic_usage_from_litellm(
SimpleNamespace(
prompt_tokens=1213,
completion_tokens=4,
cache_read_input_tokens=1202,
cache_creation_input_tokens=0,
)
)
assert usage["input_tokens"] == 11
assert usage["cache_read_input_tokens"] == 1202
assert usage["cache_creation_input_tokens"] == 0
def test_cache_write_on_first_call() -> None:
usage = _anthropic_usage_from_litellm(
SimpleNamespace(
prompt_tokens=1237,
completion_tokens=4,
cache_read_input_tokens=0,
cache_creation_input_tokens=1226,
)
)
assert usage["input_tokens"] == 11
assert usage["cache_creation_input_tokens"] == 1226
def test_prompt_tokens_details_fallback() -> None:
usage = _anthropic_usage_from_litellm(
SimpleNamespace(
prompt_tokens=1213,
completion_tokens=4,
prompt_tokens_details=SimpleNamespace(cached_tokens=1202, cache_creation_tokens=0),
)
)
assert usage["input_tokens"] == 11
assert usage["cache_read_input_tokens"] == 1202
def test_input_tokens_never_negative() -> None:
usage = _anthropic_usage_from_litellm(
SimpleNamespace(
prompt_tokens=10,
completion_tokens=1,
cache_read_input_tokens=15,
)
)
assert usage["input_tokens"] == 0
def test_output_tokens_none_coerced_to_zero() -> None:
# A provider can carry the completion_tokens attribute but leave it None.
# The mapping must emit an int (0), not None, so RequestOutcome's int
# contract holds downstream (prometheus does tokens_output_total +=
# output_tokens, which would raise TypeError on None).
usage = _anthropic_usage_from_litellm(
SimpleNamespace(prompt_tokens=100, completion_tokens=None)
)
assert usage["output_tokens"] == 0
assert isinstance(usage["output_tokens"], int)
def test_to_anthropic_response_empty_choices_returns_empty_turn() -> None:
# A content-filtered / usage-only upstream response can be HTTP 200 with an
# empty choices list (e.g. Azure OpenAI content filtering). Indexing
# choices[0] would raise IndexError and 500 the request; the converter must
# return a valid empty assistant turn, the way the streaming path already
# `continue`s on an empty-choice chunk. _to_anthropic_response uses no
# instance state, so exercise it on a bare instance.
backend = object.__new__(litellm_backend.LiteLLMBackend)
response = SimpleNamespace(
choices=[],
usage=SimpleNamespace(prompt_tokens=42, completion_tokens=0),
)
converted = backend._to_anthropic_response(response, "claude-sonnet")
assert converted["type"] == "message"
assert converted["role"] == "assistant"
assert converted["model"] == "claude-sonnet"
assert converted["content"] == []
assert converted["stop_reason"] == "end_turn"
assert converted["usage"]["input_tokens"] == 42
assert converted["usage"]["output_tokens"] == 0