Skip to content

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

refactor(llm): centralise provider usage-payload coercion

Bingxi Zhao (Frank)faac01815283
diff --git a/deeptutor/core/agentic/usage.py b/deeptutor/core/agentic/usage.py
index 5b5b904c8..1e87376ca 100644
--- a/deeptutor/core/agentic/usage.py
+++ b/deeptutor/core/agentic/usage.py
@@ -5,6 +5,8 @@ from __future__ import annotations
import logging
from typing import Any
+from deeptutor.services.llm.usage_frame import token_counts
+
logger = logging.getLogger(__name__)
@@ -30,23 +32,13 @@ class UsageTracker:
self.model: str | None = model
def add_from_response(self, response_or_usage: Any) -> None:
- usage = getattr(response_or_usage, "usage", None) or response_or_usage
- if hasattr(usage, "model_dump"):
- usage = usage.model_dump()
- elif not isinstance(usage, dict):
- usage = {
- key: getattr(usage, key, None)
- for key in ("prompt_tokens", "completion_tokens", "total_tokens")
- if hasattr(usage, key)
- }
- prompt = int(usage.get("prompt_tokens") or 0)
- completion = int(usage.get("completion_tokens") or 0)
- total = int(usage.get("total_tokens") or prompt + completion)
- if prompt or completion or total:
- self.prompt_tokens += prompt
- self.completion_tokens += completion
- self.total_tokens += total
- self.calls += 1
+ counts = token_counts(getattr(response_or_usage, "usage", None) or response_or_usage)
+ if not counts:
+ return
+ self.prompt_tokens += counts["prompt_tokens"]
+ self.completion_tokens += counts["completion_tokens"]
+ self.total_tokens += counts["total_tokens"]
+ self.calls += 1
def add_estimated(self, *, input_chars: int, output_chars: int) -> None:
est_input = int(input_chars / 3.5)
diff --git a/deeptutor/services/llm/provider_core/openai_compat_provider.py b/deeptutor/services/llm/provider_core/openai_compat_provider.py
index 4809707c7..abdef0a96 100644
--- a/deeptutor/services/llm/provider_core/openai_compat_provider.py
+++ b/deeptutor/services/llm/provider_core/openai_compat_provider.py
@@ -32,6 +32,7 @@ from deeptutor.services.llm.provider_core.openai_responses import (
from deeptutor.services.llm.reasoning_params import (
build_openai_compatible_reasoning_kwargs,
)
+from deeptutor.services.llm.usage_frame import token_counts
if TYPE_CHECKING:
from deeptutor.services.provider_registry import ProviderSpec
@@ -490,27 +491,12 @@ class OpenAICompatProvider(LLMProvider):
@classmethod
def _extract_usage(cls, response: Any) -> dict[str, int]:
- usage_obj = None
response_map = cls._maybe_mapping(response)
if response_map is not None:
usage_obj = response_map.get("usage")
- elif hasattr(response, "usage") and response.usage:
- usage_obj = response.usage
-
- usage_map = cls._maybe_mapping(usage_obj)
- if usage_map is not None:
- return {
- "prompt_tokens": int(usage_map.get("prompt_tokens") or 0),
- "completion_tokens": int(usage_map.get("completion_tokens") or 0),
- "total_tokens": int(usage_map.get("total_tokens") or 0),
- }
- if usage_obj:
- return {
- "prompt_tokens": getattr(usage_obj, "prompt_tokens", 0) or 0,
- "completion_tokens": getattr(usage_obj, "completion_tokens", 0) or 0,
- "total_tokens": getattr(usage_obj, "total_tokens", 0) or 0,
- }
- return {}
+ else:
+ usage_obj = getattr(response, "usage", None)
+ return token_counts(usage_obj)
def _parse(self, response: Any) -> LLMResponse:
if isinstance(response, str):
diff --git a/deeptutor/services/llm/provider_core/openai_responses/parsing.py b/deeptutor/services/llm/provider_core/openai_responses/parsing.py
index a977648a3..4a84f385d 100644
--- a/deeptutor/services/llm/provider_core/openai_responses/parsing.py
+++ b/deeptutor/services/llm/provider_core/openai_responses/parsing.py
@@ -12,6 +12,7 @@ import json_repair
from loguru import logger
from deeptutor.services.llm.provider_core.base import LLMResponse, ToolCallRequest
+from deeptutor.services.llm.usage_frame import token_counts
FINISH_REASON_MAP = {
"completed": "stop",
@@ -292,17 +293,8 @@ def parse_response_output(response: Any) -> LLMResponse:
)
)
- usage_raw = response.get("usage") or {}
- if not isinstance(usage_raw, dict):
- dump = getattr(usage_raw, "model_dump", None)
- usage_raw = dump() if callable(dump) else vars(usage_raw)
- usage = {}
- if usage_raw:
- usage = {
- "prompt_tokens": int(usage_raw.get("input_tokens") or 0),
- "completion_tokens": int(usage_raw.get("output_tokens") or 0),
- "total_tokens": int(usage_raw.get("total_tokens") or 0),
- }
+ # The Responses API names its counters input_/output_tokens.
+ usage = token_counts(response.get("usage"), prompt="input_tokens", completion="output_tokens")
finish_reason = map_finish_reason(response.get("status"))
return LLMResponse(
@@ -387,12 +379,9 @@ async def consume_sdk_stream(
status = getattr(response, "status", None) if response is not None else None
usage_obj = getattr(response, "usage", None) if response is not None else None
finish_reason = map_finish_reason(status)
- if usage_obj is not None:
- usage = {
- "prompt_tokens": int(getattr(usage_obj, "input_tokens", 0) or 0),
- "completion_tokens": int(getattr(usage_obj, "output_tokens", 0) or 0),
- "total_tokens": int(getattr(usage_obj, "total_tokens", 0) or 0),
- }
+ usage = (
+ token_counts(usage_obj, prompt="input_tokens", completion="output_tokens") or usage
+ )
elif event_type in {"error", "response.failed"}:
raise RuntimeError(f"Response failed: {_response_error_detail(event)[:500]}")
diff --git a/deeptutor/services/llm/usage_frame.py b/deeptutor/services/llm/usage_frame.py
new file mode 100644
index 000000000..d819b1406
--- /dev/null
+++ b/deeptutor/services/llm/usage_frame.py
@@ -0,0 +1,87 @@
+"""Coercion for provider ``usage`` payloads.
+
+Token counts arrive in three shapes and every reader used to guess for itself:
+
+* a plain dict — DeepTutor's own :class:`~deeptutor.services.llm.types.TutorStreamChunk`
+ carries ``usage: dict[str, int]``, and the native adapters build one directly;
+* a pydantic model — the OpenAI SDK's ``CompletionUsage``;
+* a bare object with attributes — some gateways and the Responses API SDK.
+
+Four call sites each re-derived that guess, so teaching the codebase a new
+shape meant finding all four (the bug fixed in #919 was exactly one of them
+missing the dict case). This module is the only place the guessing happens.
+
+Key names differ by API dialect — chat completions says ``prompt_tokens`` while
+the Responses API says ``input_tokens`` — so :func:`token_counts` takes the
+source names and always returns DeepTutor's canonical triple.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Mapping, Sequence
+from typing import Any
+
+CANONICAL_KEYS: tuple[str, str, str] = ("prompt_tokens", "completion_tokens", "total_tokens")
+
+
+def usage_mapping(payload: Any, *, keys: Sequence[str] = CANONICAL_KEYS) -> dict[str, Any]:
+ """Return *payload* as a plain mapping, or ``{}`` when it carries nothing.
+
+ ``keys`` is only consulted for the bare-object case: a mapping and a
+ pydantic model already hand over every field they have, while an arbitrary
+ object has to be asked for names.
+ """
+ if payload is None:
+ return {}
+ if isinstance(payload, Mapping):
+ return dict(payload)
+ dump = getattr(payload, "model_dump", None)
+ if callable(dump):
+ try:
+ dumped = dump()
+ except Exception: # a model_dump that needs arguments is not ours to call
+ dumped = None
+ if isinstance(dumped, Mapping):
+ return dict(dumped)
+ return {key: getattr(payload, key) for key in keys if hasattr(payload, key)}
+
+
+def token_counts(
+ payload: Any,
+ *,
+ prompt: str = "prompt_tokens",
+ completion: str = "completion_tokens",
+ total: str = "total_tokens",
+) -> dict[str, int]:
+ """Canonical ``{prompt,completion,total}_tokens`` triple from any usage shape.
+
+ Returns ``{}`` when the payload reports no tokens at all, so callers can
+ keep using truthiness to mean "this frame had no usage report" — a
+ zero-filled dict would look like a real report of zero.
+
+ ``total`` falls back to ``prompt + completion``: providers that omit it
+ (or send it as 0) still get a usable total.
+ """
+ frame = usage_mapping(payload, keys=(prompt, completion, total))
+ if not frame:
+ return {}
+ prompt_tokens = _as_int(frame.get(prompt))
+ completion_tokens = _as_int(frame.get(completion))
+ total_tokens = _as_int(frame.get(total)) or prompt_tokens + completion_tokens
+ if not (prompt_tokens or completion_tokens or total_tokens):
+ return {}
+ return {
+ "prompt_tokens": prompt_tokens,
+ "completion_tokens": completion_tokens,
+ "total_tokens": total_tokens,
+ }
+
+
+def _as_int(value: Any) -> int:
+ try:
+ return int(value or 0)
+ except (TypeError, ValueError):
+ return 0
+
+
+__all__ = ["CANONICAL_KEYS", "token_counts", "usage_mapping"]
diff --git a/tests/services/llm/test_usage_frame.py b/tests/services/llm/test_usage_frame.py
new file mode 100644
index 000000000..5f692eed4
--- /dev/null
+++ b/tests/services/llm/test_usage_frame.py
@@ -0,0 +1,107 @@
+"""``usage_frame`` is the one place that guesses a provider usage payload's shape.
+
+Four readers used to re-derive that guess (#919 was one of them missing the
+plain-dict case). These tests pin all three shapes plus the two API dialects.
+"""
+
+from __future__ import annotations
+
+from deeptutor.services.llm.usage_frame import token_counts, usage_mapping
+
+
+class _PydanticLike:
+ def model_dump(self) -> dict[str, int]:
+ return {"prompt_tokens": 7, "completion_tokens": 3, "total_tokens": 10}
+
+
+class _AttrsOnly:
+ prompt_tokens = 11
+ completion_tokens = 4
+ total_tokens = 15
+
+
+class _NeedsArgs:
+ """A model_dump that cannot be called bare — must not blow up the caller."""
+
+ prompt_tokens = 1
+ completion_tokens = 2
+
+ def model_dump(self, mode): # noqa: D102 - deliberately arity-mismatched
+ raise AssertionError("unreachable")
+
+
+# ---- usage_mapping ---------------------------------------------------------
+
+
+def test_mapping_passthrough() -> None:
+ assert usage_mapping({"prompt_tokens": 1, "extra": "kept"}) == {
+ "prompt_tokens": 1,
+ "extra": "kept",
+ }
+
+
+def test_mapping_from_model_dump() -> None:
+ assert usage_mapping(_PydanticLike())["total_tokens"] == 10
+
+
+def test_mapping_from_attributes_reads_requested_keys_only() -> None:
+ assert usage_mapping(_AttrsOnly()) == {
+ "prompt_tokens": 11,
+ "completion_tokens": 4,
+ "total_tokens": 15,
+ }
+
+
+def test_mapping_of_none_is_empty() -> None:
+ assert usage_mapping(None) == {}
+
+
+def test_mapping_falls_back_when_model_dump_is_unusable() -> None:
+ assert usage_mapping(_NeedsArgs()) == {"prompt_tokens": 1, "completion_tokens": 2}
+
+
+# ---- token_counts ---------------------------------------------------------
+
+
+def test_counts_from_plain_dict() -> None:
+ # The shape DeepTutor's own TutorStreamChunk and native adapters emit.
+ assert token_counts(
+ {"prompt_tokens": 1200, "completion_tokens": 400, "total_tokens": 1600}
+ ) == {
+ "prompt_tokens": 1200,
+ "completion_tokens": 400,
+ "total_tokens": 1600,
+ }
+
+
+def test_counts_derive_total_when_absent() -> None:
+ assert token_counts({"prompt_tokens": 5, "completion_tokens": 6})["total_tokens"] == 11
+
+
+def test_counts_empty_frame_is_falsy_not_zero_filled() -> None:
+ # Callers use truthiness to mean "this frame carried no usage report".
+ assert token_counts(None) == {}
+ assert token_counts({}) == {}
+ assert token_counts({"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}) == {}
+
+
+def test_counts_tolerate_unparseable_values() -> None:
+ assert token_counts({"prompt_tokens": "nope", "completion_tokens": 4})["prompt_tokens"] == 0
+
+
+def test_counts_map_responses_api_dialect() -> None:
+ responses_usage = {"input_tokens": 30, "output_tokens": 12, "total_tokens": 42}
+ assert token_counts(responses_usage, prompt="input_tokens", completion="output_tokens") == {
+ "prompt_tokens": 30,
+ "completion_tokens": 12,
+ "total_tokens": 42,
+ }
+
+
+def test_counts_map_responses_api_dialect_from_attributes() -> None:
+ obj = type("U", (), {"input_tokens": 8, "output_tokens": 2})()
+ assert token_counts(obj, prompt="input_tokens", completion="output_tokens") == {
+ "prompt_tokens": 8,
+ "completion_tokens": 2,
+ "total_tokens": 10,
+ }