Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.
Python agentaianthropicclaude-codecompressioncontext-engineeringcontext-windowcursorfastapilangchainllmmcpopenaiprompt-engineeringproxypythonragtoken-optimizationtokenstypescript
fix(proxy/openai): respect explicit stream_options.include_usage (#2026)
Abhay Singh19201e842f30
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a6823eb91..2c2fceb9d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -104,6 +104,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0* **ccr:** don't crash `parse_tool_call` on a CCR tool call whose arguments aren't an object. For the OpenAI/`openai_responses` shape the arguments are `json.loads`-decoded and only `JSONDecodeError` was caught, so a model that emitted `arguments='[]'`/`'"abc"'`/`'123'` (decoding to a list/str/number) — or a non-dict Anthropic `input` — reached `input_data.get("hash")` and raised `AttributeError`; a null `arguments` raised an uncaught `TypeError` from `json.loads(None)`. Both are now handled: the decode also catches `TypeError`, and a non-dict `input_data` returns `None` (not a valid CCR call) instead of crashing CCR response processing.* **proxy/anthropic:** give each Anthropic conversation its own session id. `SessionTrackerStore.compute_session_id` derived its fallback id from `model` + system text harvested only from `role:"system"` entries inside `messages` — but Anthropic carries the system prompt as a top-level `body["system"]` field, so genuine Anthropic requests (which never carry `x-headroom-session-id`) collapsed to `md5(model:[])` and every conversation on the same model shared one `PrefixCacheTracker`. That let session-sticky state cross-contaminate: conversation A's sticky `headroom_retrieve`/memory tools and `anthropic-beta` headers were injected into conversation B, and frozen-prefix/compression-cache state mixed across conversations. The Anthropic handler now folds the top-level `system` into the session-id inputs (prepending a synthetic `role:"system"` message used only to derive the id), giving distinct conversations distinct ids.* **cache/semantic:** key entries by the full-context hash, not the trailing query text. `SemanticCache.put` stored each response under `sha256(query)[:16]` where `query` is only the last user message, and the exact-match branch of `get` returned the slot without checking the stored entry's `messages_hash`. Two requests that share a trailing message ("continue", "yes", "run the tests") but differ in earlier context therefore collided on one slot — the second overwrote the first, and the first's hash then resolved to the second's cached response (wrong data served). Entries are now keyed by `messages_hash` when present, and `get` verifies `entry.messages_hash` before returning.+* **proxy/openai:** stop overriding an explicit client `stream_options.include_usage` on the streaming chat path. To count tokens from the trailing usage chunk, the handler set `include_usage: True` unconditionally — including flipping an explicit client `false` to `true`. The upstream then appended a usage-only chunk (`choices: []`) the client never requested, and the common `chunk.choices[0].delta` loop raised `IndexError`. The option is now only filled in when the client left the choice open (no `stream_options`, or a dict without `include_usage`); an explicit `true`/`false` is respected.* **proxy/openai:** stop PRE_SEND from reintroducing `tools: []` after the direct #728 fix. The OpenAI request handler now mirrors the existing `tools or _original_tools is not None` body-write guard during PRE_SEND write-back, so providers that reject empty tool arrays no longer see a tools field when the client omitted it, while explicit client `tools: []` remains preserved ([#1983](https://github.com/headroomlabs-ai/headroom/issues/1983)).* **proxy/openai:** keep the exact Responses function name `terminal` resident during OpenAI tool-search deferral so cache-mode optimization stops forwarding `terminal.terminal` and triggering the reserved-namespace 400 on Codex Responses ([#1946](https://github.com/headroomlabs-ai/headroom/issues/1946)).* **subscription/copilot:** show a fully-consumed Copilot quota as 100% used instead of unknown. `parse_copilot_quota` read `remaining = raw.get("remaining") or raw.get("quota_remaining")`, so a category reporting `remaining: 0` (quota fully spent) had that legitimate `0` treated as falsy and — with no `quota_remaining` alias in the real payload — collapsed to `None`. `CopilotQuotaCategory.used`/`used_percent` then returned `None`, so the dashboard rendered the exhausted category as `used: -` / 0% (green gauge) rather than `300/300` / 100%. Now uses an explicit `is None` check.diff --git a/headroom/proxy/handlers/openai.py b/headroom/proxy/handlers/openai.pyindex e111dccdd..f1324d6a6 100644--- a/headroom/proxy/handlers/openai.py+++ b/headroom/proxy/handlers/openai.py@@ -120,6 +120,24 @@ def _normalize_openai_max_tokens(body: dict[str, Any]) -> None:body.pop("max_tokens", None)+def _apply_stream_usage_option(body: dict[str, Any]) -> None:+ """Ask the upstream for a usage chunk (for token counting) in-place, without+ overriding an explicit client ``stream_options.include_usage``.++ Forcing ``include_usage`` on a client that passed ``false`` (or that set the+ dict without the key) makes the upstream append a trailing usage-only chunk+ (``choices: []``) the client never asked for; the common+ ``chunk.choices[0].delta`` pattern then raises ``IndexError``. So only inject+ the option when the client left the choice open: no ``stream_options`` at all,+ or a ``stream_options`` dict that does not mention ``include_usage``.+ """+ stream_options = body.get("stream_options")+ if stream_options is None:+ body["stream_options"] = {"include_usage": True}+ elif isinstance(stream_options, dict) and "include_usage" not in stream_options:+ stream_options["include_usage"] = True++def _header_get(headers: dict[str, str], name: str) -> str | None:"""Case-insensitive header lookup for plain dicts."""lowered = name.lower()@@ -3160,12 +3178,10 @@ class OpenAIHandlerMixin:try:if stream:- # Inject stream_options to get usage stats in streaming response- # This allows accurate token counting instead of byte-based estimation- if "stream_options" not in body:- body["stream_options"] = {"include_usage": True}- elif isinstance(body.get("stream_options"), dict):- body["stream_options"]["include_usage"] = True+ # Request usage stats for accurate token counting instead of+ # byte-based estimation — without overriding an explicit client+ # choice (see _apply_stream_usage_option).+ _apply_stream_usage_option(body)self.pipeline_extensions.emit(PipelineStage.POST_SEND,diff --git a/tests/test_proxy/test_openai_stream_usage_option.py b/tests/test_proxy/test_openai_stream_usage_option.pynew file mode 100644index 000000000..a3d18fe60--- /dev/null+++ b/tests/test_proxy/test_openai_stream_usage_option.py@@ -0,0 +1,45 @@+"""Regression: the direct OpenAI streaming path must not override an explicit+client ``stream_options.include_usage``.++The handler injects ``include_usage`` so it can count tokens from the trailing+usage chunk. Forcing it on a client that passed ``include_usage: false`` (or that+never opted in) makes the upstream append a usage-only chunk (``choices: []``)+the client did not ask for — and the common ``chunk.choices[0].delta`` loop then+raises ``IndexError``. The injection now only fills in the option when the client+left the choice open.+"""++from __future__ import annotations++import pytest++fastapi = pytest.importorskip("fastapi")++from headroom.proxy.handlers.openai import _apply_stream_usage_option # noqa: E402+++def test_respects_explicit_include_usage_false():+ body = {"stream_options": {"include_usage": False}}+ _apply_stream_usage_option(body)+ assert body["stream_options"]["include_usage"] is False+++def test_preserves_explicit_include_usage_true():+ body = {"stream_options": {"include_usage": True}}+ _apply_stream_usage_option(body)+ assert body["stream_options"]["include_usage"] is True+++def test_injects_when_stream_options_absent():+ body = {"messages": []}+ _apply_stream_usage_option(body)+ assert body["stream_options"] == {"include_usage": True}+++def test_fills_in_when_dict_present_without_key():+ body = {"stream_options": {"continuous_usage_stats": True}}+ _apply_stream_usage_option(body)+ assert body["stream_options"] == {+ "continuous_usage_stats": True,+ "include_usage": True,+ }