From a1d5f6a55b550758663950c9aeaa13ea007aa9e8 Mon Sep 17 00:00:00 2001 From: mikezobern Date: Fri, 10 Jul 2026 16:56:47 +0400 Subject: [PATCH] fix: count streamed LLM usage once per completion Providers such as Gemini's OpenAI-compat API attach usage to multiple stream chunks. Recording each frame inflated total_calls and tokens for a single agent-loop round. Keep the latest usage and record it once, matching run_labeled_step, and cover the regression with a test. Co-authored-by: Cursor --- deeptutor/agents/chat/agent_loop.py | 11 ++++- deeptutor/agents/question/pipeline.py | 17 ++++--- tests/agents/chat/test_agent_loop.py | 69 ++++++++++++++++++++++++++- 3 files changed, 87 insertions(+), 10 deletions(-) diff --git a/deeptutor/agents/chat/agent_loop.py b/deeptutor/agents/chat/agent_loop.py index d1c6a5047..abfef9ded 100644 --- a/deeptutor/agents/chat/agent_loop.py +++ b/deeptutor/agents/chat/agent_loop.py @@ -465,6 +465,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 @@ -488,7 +493,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 @@ -546,7 +551,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, diff --git a/deeptutor/agents/question/pipeline.py b/deeptutor/agents/question/pipeline.py index f799239bc..64e2c9ef8 100644 --- a/deeptutor/agents/question/pipeline.py +++ b/deeptutor/agents/question/pipeline.py @@ -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( diff --git a/tests/agents/chat/test_agent_loop.py b/tests/agents/chat/test_agent_loop.py index 59278a6a3..ab035d53c 100644 --- a/tests/agents/chat/test_agent_loop.py +++ b/tests/agents/chat/test_agent_loop.py @@ -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,