Skip to content

Agent Zero AI framework

Report provider usage for streamed Chat Completions turns

linkliti8c6c2b315897
diff --git a/helpers/litellm_transport.py b/helpers/litellm_transport.py
index 2cf37c344..1b80c0328 100644
--- a/helpers/litellm_transport.py
+++ b/helpers/litellm_transport.py
@@ -47,6 +47,7 @@ NO_REASONING_EFFORT_ALIASES = {"", "0", "false", "no", "none", "off", "disabled"
RESPONSES_UNSUPPORTED_CACHE: set[str] = set()
RESPONSES_STATE_UNSUPPORTED_CACHE: set[str] = set()
RESPONSES_BUILTIN_UNSUPPORTED_CACHE: dict[str, set[str]] = {}
+STREAM_USAGE_UNSUPPORTED_CACHE: set[str] = set()
OPENAI_RESPONSES_EXTRA_BODY_PARAMS = {
"context_management",
"prompt_cache_retention",
@@ -182,6 +183,7 @@ class LiteLLMTransport:
last_request_state: str = field(init=False, default=RESPONSES_STATE_PROVIDER)
explicit_prompt_caching: bool = field(init=False, default=False)
history_prefix_hash: str = field(init=False, default="")
+ stream_usage_retried: bool = field(init=False, default=False)
def __post_init__(self) -> None:
self.kwargs = _without_stream_kwarg(dict(self.kwargs))
@@ -354,8 +356,24 @@ class LiteLLMTransport:
self.kwargs["responses_state"] = RESPONSES_STATE_LOCAL
self.kwargs.pop("previous_response_id", None)
return True
+ if self._recover_stream_usage_rejection(exc):
+ return True
return recovery is TransportRecovery.FALLBACK_TO_CHAT
+ def _recover_stream_usage_rejection(self, exc: Exception) -> bool:
+ if self.stream_usage_retried or not _is_stream_usage_rejected_error(exc):
+ return False
+ self.stream_usage_retried = True
+ if self.policy.cache_key:
+ STREAM_USAGE_UNSUPPORTED_CACHE.add(self.policy.cache_key)
+ options = dict(self.kwargs.get("stream_options") or {})
+ options.pop("include_usage", None)
+ if options:
+ self.kwargs["stream_options"] = options
+ else:
+ self.kwargs.pop("stream_options", None)
+ return True
+
def _chat_request(self, *, stream: bool) -> dict[str, Any]:
chat_kwargs = ChatCompletionsTransport.prepare_kwargs(
self.kwargs,
@@ -374,6 +392,14 @@ class LiteLLMTransport:
"stream": stream,
**chat_kwargs,
}
+ if stream and not self.stream_usage_retried:
+ options = {**(request.get("stream_options") or {})}
+ if self.policy.cache_key in STREAM_USAGE_UNSUPPORTED_CACHE:
+ options.pop("include_usage", None)
+ else:
+ options["include_usage"] = True
+ if options:
+ request["stream_options"] = options
if self.stop is not None:
request["stop"] = self.stop
return request
@@ -1413,6 +1439,7 @@ def clear_transport_capability_cache() -> None:
RESPONSES_UNSUPPORTED_CACHE.clear()
RESPONSES_STATE_UNSUPPORTED_CACHE.clear()
RESPONSES_BUILTIN_UNSUPPORTED_CACHE.clear()
+ STREAM_USAGE_UNSUPPORTED_CACHE.clear()
def delete_stored_response_ids(
@@ -1920,6 +1947,13 @@ def _is_bad_request_error(exc: Exception) -> bool:
return "400" in text and "bad request" in text
+def _is_stream_usage_rejected_error(exc: Exception) -> bool:
+ text = _exception_text(exc).lower()
+ if "stream_options" not in text:
+ return False
+ return _is_bad_request_error(exc) or _exception_status_code(exc) == 422
+
+
def _is_server_error(exc: Exception) -> bool:
status_code = _exception_status_code(exc)
if isinstance(status_code, int) and 500 <= status_code < 600:
diff --git a/helpers/litellm_transport.py.dox.md b/helpers/litellm_transport.py.dox.md
index 2af7cc65d..65e499444 100644
--- a/helpers/litellm_transport.py.dox.md
+++ b/helpers/litellm_transport.py.dox.md
@@ -36,6 +36,7 @@
- Fall back to Chat Completions when LiteLLM's Responses mock streaming path tries to JSON-decode a real SSE stream before any output.
- Preserve Chat Completions tool calls from both non-streaming responses and streaming deltas as canonical `LLMResult` function-call items.
- Preserve provider usage and LiteLLM response cost for both transports only when the response or stream actually supplies them; do not synthesize unavailable provider accounting.
+- Streaming Chat Completions requests include `stream_options.include_usage` so terminal usage events reach `LLMResult.usage` for OpenAI-compatible endpoints and Messages API providers alike. A caller-provided `stream_options` keeps its extra keys, and a pre-output rejection of the option retries once without `include_usage`, remembering the rejection per model configuration in a process-global cache that naturally clears when the framework process restarts; tests reset it through `clear_transport_capability_cache`.
- Recover all Responses output items from stream events when a terminal completed envelope omits them, including encrypted reasoning. Merge by item/call identity in output-index order; terminal non-null fields win without duplicating calls.
- Stream named native function arguments through canonical tool envelopes for display. Buffer interleaved calls until the active envelope closes; preserve independent original call metadata. Native execution still waits for the completed model turn.
- Fail incomplete Responses generations and native-call streams that end without completion; never promote partial call previews to a Chat result.
diff --git a/plugins/_context_window/AGENTS.md b/plugins/_context_window/AGENTS.md
index fea48f33c..fee9d7dfd 100644
--- a/plugins/_context_window/AGENTS.md
+++ b/plugins/_context_window/AGENTS.md
@@ -36,8 +36,10 @@
diagnostic detail rows.
- Provider rows are exposed only when the provider or transport reports their
values; unavailable price and cache data render no row.
-- Streamed OpenRouter main turns request LiteLLM's terminal usage event. The
- response callback still runs normally; only an actual Chat Completions result
+- Streaming main turns request LiteLLM's terminal usage event for every
+ provider through the transport's `stream_options.include_usage` injection,
+ so provider input/output and cache tokens reach the summary. The response
+ callback still runs normally; only an actual Chat Completions result
restores the accepted response after the accounting tail is drained.
- Responses API turns keep their native result and callback behavior unchanged.
- Older chats without a stored breakdown show the explanatory empty state.
diff --git a/plugins/_context_window/README.md b/plugins/_context_window/README.md
index bdb1b293a..a043867c1 100644
--- a/plugins/_context_window/README.md
+++ b/plugins/_context_window/README.md
@@ -12,6 +12,7 @@ When a model provider reports usage, the popover shows price, cache-hit rate,
and input/output tokens. Unreported price and cache data are omitted. The
context breakdown does not guess model-specific image token costs.
-For streamed OpenRouter chat calls, the plugin requests and drains LiteLLM's
-terminal usage event after Agent Zero has accepted the response. Price remains
-hidden when LiteLLM does not report a cost or map the selected model.
+For streamed chat calls, the transport requests LiteLLM's terminal usage
+event and the plugin drains it after Agent Zero has accepted the response.
+Price remains hidden when LiteLLM does not report a cost or map the selected
+model.
diff --git a/plugins/_context_window/extensions/python/_functions/models/LiteLLMChatWrapper/unified_turn/start/_10_drain_provider_usage.py b/plugins/_context_window/extensions/python/_functions/models/LiteLLMChatWrapper/unified_turn/start/_10_drain_provider_usage.py
index cbc90db4c..19858e693 100644
--- a/plugins/_context_window/extensions/python/_functions/models/LiteLLMChatWrapper/unified_turn/start/_10_drain_provider_usage.py
+++ b/plugins/_context_window/extensions/python/_functions/models/LiteLLMChatWrapper/unified_turn/start/_10_drain_provider_usage.py
@@ -6,21 +6,10 @@ RESPONSE_KEY = "_context_window_accepted_response"
class DrainProviderUsage(Extension):
def execute(self, data: dict, **kwargs):
- model = data["args"][0]
callback = data["kwargs"].get("response_callback")
if callback is None:
return
- if (
- model.provider == "openrouter"
- and data["kwargs"].get("explicit_caching")
- ):
- data["kwargs"]["stream_options"] = {
- **model.kwargs.get("stream_options", {}),
- **data["kwargs"].get("stream_options", {}),
- "include_usage": True,
- }
-
async def drain_callback(chunk: str, full: str):
response = await callback(chunk, full)
if response is not None and RESPONSE_KEY not in data:
diff --git a/tests/test_responses_architecture.py b/tests/test_responses_architecture.py
index f90a8ecf9..68e710e1e 100644
--- a/tests/test_responses_architecture.py
+++ b/tests/test_responses_architecture.py
@@ -249,6 +249,97 @@ async def test_chat_completion_transport_preserves_reported_usage(monkeypatch):
}
+async def test_chat_stream_requests_and_records_terminal_usage(monkeypatch):
+ calls: list[dict] = []
+
+ async def fake_acompletion(**kwargs):
+ calls.append(kwargs)
+
+ async def stream():
+ yield {"choices": [{"delta": {"content": "done"}}]}
+ yield {
+ "choices": [],
+ "usage": {
+ "prompt_tokens": 120,
+ "completion_tokens": 8,
+ "total_tokens": 128,
+ },
+ }
+
+ return stream()
+
+ monkeypatch.setattr(litellm_transport, "acompletion", fake_acompletion)
+ transport = litellm_transport.LiteLLMTransport(
+ model="custom/model",
+ messages=[{"role": "user", "content": "question"}],
+ kwargs={"a0_api_mode": "chat_completions"},
+ )
+
+ async for _chunk in transport.astream():
+ pass
+
+ assert calls[0]["stream"] is True
+ assert calls[0]["stream_options"] == {"include_usage": True}
+ assert transport.last_result is not None
+ assert transport.last_result.usage == {
+ "prompt_tokens": 120,
+ "completion_tokens": 8,
+ "total_tokens": 128,
+ }
+
+
+async def test_chat_stream_retries_without_usage_when_stream_options_rejected(
+ monkeypatch,
+):
+ calls: list[dict] = []
+
+ class BadRequestError(Exception):
+ pass
+
+ async def fake_acompletion(**kwargs):
+ calls.append(kwargs)
+ if kwargs.get("stream_options", {}).get("include_usage"):
+ raise BadRequestError("Unknown parameter: 'stream_options'.")
+
+ async def stream():
+ yield {"choices": [{"delta": {"content": "done"}}]}
+
+ return stream()
+
+ monkeypatch.setattr(litellm_transport, "acompletion", fake_acompletion)
+ transport = litellm_transport.LiteLLMTransport(
+ model="custom/model",
+ messages=[{"role": "user", "content": "question"}],
+ kwargs={
+ "a0_api_mode": "chat_completions",
+ "stream_options": {"include_usage": True, "custom": "keep"},
+ },
+ )
+
+ async for _chunk in transport.astream():
+ pass
+
+ assert calls[0]["stream_options"] == {
+ "include_usage": True,
+ "custom": "keep",
+ }
+ assert calls[1]["stream_options"] == {"custom": "keep"}
+ assert len(calls) == 2
+
+ next_transport = litellm_transport.LiteLLMTransport(
+ model="custom/model",
+ messages=[{"role": "user", "content": "again"}],
+ kwargs={
+ "a0_api_mode": "chat_completions",
+ "stream_options": {"include_usage": True, "custom": "keep"},
+ },
+ )
+ request = next_transport._chat_request(stream=True)
+ assert request["stream_options"] == {"custom": "keep"}
+
+
def test_responses_provider_state_uses_previous_response_and_new_items():
new_items = [{"type": "function_call_output", "call_id": "call_1", "output": "done"}]
local_items = [{"role": "user", "content": "full replay"}]