Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

refactor(agentic): one shared once-per-stream usage recorder

Bingxi Zhao (Frank)3f03d4eabdf5
diff --git a/deeptutor/agents/chat/agent_loop.py b/deeptutor/agents/chat/agent_loop.py
index cdddb9d2c..3983da8d5 100644
--- a/deeptutor/agents/chat/agent_loop.py
+++ b/deeptutor/agents/chat/agent_loop.py
@@ -33,6 +33,7 @@ from typing import TYPE_CHECKING, Any
from deeptutor.agents._shared.capability_result import emit_capability_result
from deeptutor.core.agentic.messages import assistant_message_with_tool_calls
from deeptutor.core.agentic.tool_dispatch import DispatchOutcome
+from deeptutor.core.agentic.usage import message_content_chars, record_streamed_usage
from deeptutor.core.context import UnifiedContext
from deeptutor.core.stream_bus import StreamBus
from deeptutor.core.trace import build_trace_metadata, merge_trace_metadata, new_call_id
@@ -470,11 +471,9 @@ class AgentLoop:
kwargs["tools"] = tool_schemas
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.
+ # than one stream chunk. Keep the latest frame; it is recorded once
+ # after the stream via ``record_streamed_usage``.
usage_seen: Any = None
text_parts: list[str] = []
tool_acc: dict[int, dict[str, str]] = {}
@@ -557,13 +556,12 @@ class AgentLoop:
await _emit_segments(think_filter.flush())
text = "".join(text_parts)
- 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,
- )
+ record_streamed_usage(
+ self.pipeline.usage,
+ usage_seen,
+ input_chars=sum(message_content_chars(message) for message in messages),
+ output_chars=output_chars,
+ )
tool_calls = [
{
@@ -645,21 +643,6 @@ class AgentLoop:
raise
-def _message_content_chars(message: dict[str, Any]) -> int:
- content = message.get("content")
- if isinstance(content, str):
- return len(content)
- if isinstance(content, list):
- total = 0
- for part in content:
- if isinstance(part, dict):
- total += len(str(part.get("text") or ""))
- elif isinstance(part, str):
- total += len(part)
- return total
- return 0
-
-
def _last_context_checkpoint_summary(dispatch: DispatchOutcome) -> str:
summary = ""
for tool_message in dispatch.tool_messages:
diff --git a/deeptutor/agents/question/pipeline.py b/deeptutor/agents/question/pipeline.py
index a056d86ee..41c3f4e48 100644
--- a/deeptutor/agents/question/pipeline.py
+++ b/deeptutor/agents/question/pipeline.py
@@ -56,6 +56,7 @@ from deeptutor.core.agentic import (
)
from deeptutor.core.agentic.labels import find_inline_labels
from deeptutor.core.agentic.tool_dispatch import MAX_PARALLEL_TOOL_CALLS
+from deeptutor.core.agentic.usage import record_streamed_usage
from deeptutor.core.context import Attachment, UnifiedContext
from deeptutor.core.stream_bus import StreamBus
from deeptutor.core.trace import (
@@ -1026,10 +1027,7 @@ class QuestionPipeline:
reasoning_effort=self.reasoning_effort,
),
}
- try:
- kwargs["stream_options"] = {"include_usage": True}
- except Exception:
- pass
+ kwargs["stream_options"] = {"include_usage": True}
chunks: list[str] = []
# Keep the latest usage frame only — some providers emit usage on
@@ -1056,11 +1054,8 @@ 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)
+ # Zero-char defaults: the summarizer has no estimate fallback.
+ record_streamed_usage(self.usage, usage_seen)
except Exception as exc:
logger.warning("Tool summarizer failed for %s: %s", tool_name, exc)
await stream.progress(
diff --git a/deeptutor/core/agentic/labeled_step.py b/deeptutor/core/agentic/labeled_step.py
index 7c240c880..56a6fd312 100644
--- a/deeptutor/core/agentic/labeled_step.py
+++ b/deeptutor/core/agentic/labeled_step.py
@@ -44,7 +44,11 @@ from deeptutor.core.agentic.labels import (
classify_label,
strip_label_probe_prefix,
)
-from deeptutor.core.agentic.usage import UsageTracker
+from deeptutor.core.agentic.usage import (
+ UsageTracker,
+ message_content_chars,
+ record_streamed_usage,
+)
from deeptutor.core.stream_bus import StreamBus
from deeptutor.core.trace import merge_trace_metadata
from deeptutor.services.llm import clean_thinking_tags
@@ -97,34 +101,6 @@ class LabeledStepResult:
tool_calls: list[dict[str, Any]] = field(default_factory=list)
-class _UsageShim:
- """Adapt streaming ``CompletionUsage`` to the shape ``UsageTracker`` wants."""
-
- def __init__(self, raw: Any) -> None:
- self.usage = raw
-
-
-def _message_content_chars(message: dict[str, Any]) -> int:
- """Best-effort character count for usage fallback estimates."""
- content = message.get("content")
- if isinstance(content, str):
- return len(content)
- if isinstance(content, list):
- total = 0
- for part in content:
- if isinstance(part, dict):
- if part.get("type") == "text":
- total += len(str(part.get("text") or ""))
- elif "text" in part:
- total += len(str(part.get("text") or ""))
- elif isinstance(part, str):
- total += len(part)
- return total
- if content is None:
- return 0
- return len(str(content))
-
-
async def run_labeled_step(
*,
client: Any,
@@ -561,15 +537,12 @@ async def run_labeled_step(
await _emit_text(label_buf)
label_buf = ""
- if usage_seen is not None and usage is not None:
- usage.add_from_response(_UsageShim(usage_seen))
- elif usage is not None:
- input_chars = sum(_message_content_chars(message) for message in messages)
- if input_chars or output_chars_seen:
- usage.add_estimated(
- input_chars=input_chars,
- output_chars=output_chars_seen,
- )
+ record_streamed_usage(
+ usage,
+ usage_seen,
+ input_chars=sum(message_content_chars(message) for message in messages),
+ output_chars=output_chars_seen,
+ )
if sub_trace_opened:
await stream.progress(
diff --git a/deeptutor/core/agentic/usage.py b/deeptutor/core/agentic/usage.py
index c0bf401e1..e42553d78 100644
--- a/deeptutor/core/agentic/usage.py
+++ b/deeptutor/core/agentic/usage.py
@@ -2,8 +2,11 @@
from __future__ import annotations
+import logging
from typing import Any
+logger = logging.getLogger(__name__)
+
class UsageTracker:
"""Accumulate prompt/completion tokens across many streaming LLM calls.
@@ -93,3 +96,49 @@ class UsageTracker:
"prompt_tokens": self.prompt_tokens,
"completion_tokens": self.completion_tokens,
}
+
+
+def message_content_chars(message: dict[str, Any]) -> int:
+ """Best-effort character count of one chat message, for usage estimates."""
+ content = message.get("content")
+ if isinstance(content, str):
+ return len(content)
+ if isinstance(content, list):
+ total = 0
+ for part in content:
+ if isinstance(part, dict):
+ total += len(str(part.get("text") or ""))
+ elif isinstance(part, str):
+ total += len(part)
+ return total
+ if content is None:
+ return 0
+ return len(str(content))
+
+
+def record_streamed_usage(
+ tracker: UsageTracker | None,
+ usage_frame: Any,
+ *,
+ input_chars: int = 0,
+ output_chars: int = 0,
+) -> None:
+ """Record one completed stream's usage exactly once.
+
+ Providers (esp. Gemini's OpenAI-compat API) may attach ``usage`` to more
+ than one stream chunk — callers keep only the *latest* frame and hand it
+ here after the stream ends, so ``total_calls``/tokens are never inflated
+ N× for a single completion. When no frame arrived, falls back to the
+ coarse char-based estimate (pass zero chars to skip the fallback).
+ Accounting must never break a completed stream, so failures are
+ swallowed and debug-logged.
+ """
+ if tracker is None:
+ return
+ try:
+ if usage_frame is not None:
+ tracker.add_from_response(usage_frame)
+ elif input_chars or output_chars:
+ tracker.add_estimated(input_chars=input_chars, output_chars=output_chars)
+ except Exception:
+ logger.debug("stream usage recording failed", exc_info=True)
diff --git a/tests/core/test_record_streamed_usage.py b/tests/core/test_record_streamed_usage.py
new file mode 100644
index 000000000..afccaabc6
--- /dev/null
+++ b/tests/core/test_record_streamed_usage.py
@@ -0,0 +1,74 @@
+"""Contract tests for the shared once-per-stream usage recorder.
+
+``record_streamed_usage`` is the single seam used by ``run_labeled_step``,
+chat's ``_call_llm``, and the question pipeline's tool summarizer after
+PR #617 unified their triplicated post-stream accounting.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from deeptutor.core.agentic.usage import (
+ UsageTracker,
+ message_content_chars,
+ record_streamed_usage,
+)
+
+
+def _frame(prompt: int, completion: int) -> SimpleNamespace:
+ return SimpleNamespace(
+ prompt_tokens=prompt,
+ completion_tokens=completion,
+ total_tokens=prompt + completion,
+ )
+
+
+def test_records_frame_exactly_once() -> None:
+ tracker = UsageTracker()
+ record_streamed_usage(tracker, _frame(100, 20), input_chars=9999, output_chars=9999)
+
+ assert tracker.calls == 1
+ assert tracker.prompt_tokens == 100
+ assert tracker.completion_tokens == 20
+
+
+def test_falls_back_to_estimate_without_frame() -> None:
+ tracker = UsageTracker()
+ record_streamed_usage(tracker, None, input_chars=35, output_chars=70)
+
+ assert tracker.calls == 1
+ assert tracker.prompt_tokens == 10 # 35 / 3.5
+ assert tracker.completion_tokens == 20
+
+
+def test_zero_chars_skip_the_fallback() -> None:
+ tracker = UsageTracker()
+ record_streamed_usage(tracker, None)
+
+ assert tracker.calls == 0
+
+
+def test_none_tracker_is_a_noop() -> None:
+ record_streamed_usage(None, _frame(1, 1)) # must not raise
+
+
+def test_accounting_errors_never_propagate() -> None:
+ tracker = UsageTracker()
+ malformed = SimpleNamespace(prompt_tokens="not-a-number", completion_tokens=None)
+
+ record_streamed_usage(tracker, malformed, input_chars=10, output_chars=10) # must not raise
+
+ assert tracker.calls == 0
+
+
+def test_message_content_chars_handles_all_shapes() -> None:
+ assert message_content_chars({"content": "hello"}) == 5
+ assert message_content_chars({"content": None}) == 0
+ assert (
+ message_content_chars(
+ {"content": [{"type": "text", "text": "ab"}, "cd", {"type": "image_url"}]}
+ )
+ == 4
+ )
+ assert message_content_chars({"content": 1234}) == 4 # len(str(content))