Merge pull request #617 from mikezobern/fix/stream-usage-double-count

fix: count streamed LLM usage once per completion
This commit is contained in:
Bingxi Zhao
2026-07-19 00:51:48 +08:00
committed by GitHub
3 changed files with 87 additions and 10 deletions

View File

@@ -471,6 +471,11 @@ class AgentLoop:
kwargs["tool_choice"] = "auto"
before_usage_calls = self.pipeline.usage.calls
# Providers (esp. Gemini OpenAI-compat) may attach ``usage`` to more
# than one stream chunk. Keep the latest frame and record it once —
# same contract as ``run_labeled_step`` — so ``total_calls`` / tokens
# are not inflated by N× for a single completion.
usage_seen: Any = None
text_parts: list[str] = []
tool_acc: dict[int, dict[str, str]] = {}
output_chars = 0
@@ -494,7 +499,7 @@ class AgentLoop:
async for chunk in response_stream:
usage = getattr(chunk, "usage", None)
if usage is not None:
self.pipeline.usage.add_from_response(usage)
usage_seen = usage
choices = getattr(chunk, "choices", None) or []
if not choices:
continue
@@ -552,7 +557,9 @@ class AgentLoop:
await _emit_segments(think_filter.flush())
text = "".join(text_parts)
if self.pipeline.usage.calls == before_usage_calls:
if usage_seen is not None:
self.pipeline.usage.add_from_response(usage_seen)
elif self.pipeline.usage.calls == before_usage_calls:
self.pipeline.usage.add_estimated(
input_chars=sum(_message_content_chars(message) for message in messages),
output_chars=output_chars,

View File

@@ -1032,17 +1032,15 @@ class QuestionPipeline:
pass
chunks: list[str] = []
# Keep the latest usage frame only — some providers emit usage on
# multiple stream chunks; recording each one would N× inflate calls.
usage_seen = None
try:
response_stream = await client.chat.completions.create(**kwargs)
async for chunk in response_stream:
# Usage frames have no choices; surface them to the usage
# tracker so the cost summary reflects the summarizer too.
usage_frame = getattr(chunk, "usage", None)
if usage_frame and self.usage is not None:
try:
self.usage.add_from_response(usage_frame)
except Exception:
logger.debug("usage recording failed for summarizer", exc_info=True)
if usage_frame is not None:
usage_seen = usage_frame
if not getattr(chunk, "choices", None):
continue
delta = chunk.choices[0].delta
@@ -1058,6 +1056,11 @@ class QuestionPipeline:
stage=STAGE_EXPLORING,
metadata=merge_trace_metadata(meta, {"trace_kind": "llm_chunk"}),
)
if usage_seen is not None and self.usage is not None:
try:
self.usage.add_from_response(usage_seen)
except Exception:
logger.debug("usage recording failed for summarizer", exc_info=True)
except Exception as exc:
logger.warning("Tool summarizer failed for %s: %s", tool_name, exc)
await stream.progress(

View File

@@ -33,6 +33,8 @@ def _llm_chunk(
*,
content: str | None = None,
tool_calls: list[dict[str, Any]] | None = None,
usage: Any = None,
finish_reason: str | None = None,
) -> SimpleNamespace:
delta_fields: dict[str, Any] = {"content": content}
if tool_calls is not None:
@@ -49,7 +51,26 @@ def _llm_chunk(
]
else:
delta_fields["tool_calls"] = None
return SimpleNamespace(choices=[SimpleNamespace(delta=SimpleNamespace(**delta_fields))])
return SimpleNamespace(
choices=[
SimpleNamespace(
delta=SimpleNamespace(**delta_fields),
finish_reason=finish_reason,
)
],
usage=usage,
)
def _usage_only_chunk(*, prompt: int, completion: int, total: int) -> SimpleNamespace:
return SimpleNamespace(
choices=[],
usage=SimpleNamespace(
prompt_tokens=prompt,
completion_tokens=completion,
total_tokens=total,
),
)
async def _async_llm_stream(chunks: list[SimpleNamespace]):
@@ -256,6 +277,52 @@ async def test_inline_think_streams_to_trace_not_bubble(
assert result.metadata["completed"] is True
@pytest.mark.asyncio
async def test_multi_chunk_usage_counts_as_one_call(
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""Gemini OpenAI-compat (and similar) may attach usage to several stream
chunks. Each completion must still count as one call with the final
token totals — not N× inflated ``total_calls`` / tokens."""
usage_partial = SimpleNamespace(prompt_tokens=100, completion_tokens=2, total_tokens=102)
usage_final = SimpleNamespace(prompt_tokens=100, completion_tokens=5, total_tokens=105)
registry = _Registry()
client = _ScriptedChatClient(
[
[
_llm_chunk(content="Hello", usage=usage_partial),
_llm_chunk(content=" world", usage=usage_partial),
_llm_chunk(content=".", finish_reason="stop", usage=usage_partial),
_usage_only_chunk(prompt=100, completion=5, total=105),
]
]
)
pipeline = AgenticChatPipeline(language="en")
pipeline.registry = registry
monkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _context: [])
monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)
events = await _run(pipeline, UnifiedContext(session_id="s1", user_message="Hi"))
assert "".join(_contents(events)) == "Hello world."
assert client.call_count == 1
summary = pipeline.usage.summary()
assert summary is not None
assert summary["total_calls"] == 1
assert summary["prompt_tokens"] == 100
assert summary["completion_tokens"] == 5
assert summary["total_tokens"] == 105
# Final usage frame wins over earlier partials.
assert usage_final.total_tokens == summary["total_tokens"]
result = _result(events)
cost = (result.metadata.get("metadata") or {}).get("cost_summary") or result.metadata.get(
"cost_summary"
)
if cost is not None:
assert cost["total_calls"] == 1
assert cost["total_tokens"] == 105
@pytest.mark.asyncio
async def test_empty_finish_gets_one_nudge_then_recovers(
monkeypatch: pytest.MonkeyPatch,