Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(metrics): persist the provider-reported total token count (#5623)

Ehsan10bacd499f27
diff --git a/changelog.d/5623.bugfix.md b/changelog.d/5623.bugfix.md
new file mode 100644
index 0000000000..f138d39b79
--- /dev/null
+++ b/changelog.d/5623.bugfix.md
@@ -0,0 +1,5 @@
+Token metrics now persist the total the provider reported instead of
+recomputing it as prompt + completion, so the metrics dashboard and the
+in-session counter no longer disagree about the same response. A provider
+that reports usage without a total is now counted as prompt + completion
+rather than as zero tokens.
diff --git a/src/local_deep_research/database/thread_metrics.py b/src/local_deep_research/database/thread_metrics.py
index 261232aee5..d8e1e45eac 100644
--- a/src/local_deep_research/database/thread_metrics.py
+++ b/src/local_deep_research/database/thread_metrics.py
@@ -130,6 +130,14 @@ class ThreadSafeMetricsWriter:
# Import here to avoid circular imports
from .models import ModelUsage, TokenUsage
+ # The caller resolves the provider-reported total; fall back to
+ # the sum only when it did not supply one.
+ total_tokens = token_data.get("total_tokens")
+ if total_tokens is None:
+ total_tokens = token_data.get(
+ "prompt_tokens", 0
+ ) + token_data.get("completion_tokens", 0)
+
# Create TokenUsage record
token_usage = TokenUsage(
research_id=research_id,
@@ -137,8 +145,7 @@ class ThreadSafeMetricsWriter:
model_provider=token_data.get("provider"),
prompt_tokens=token_data.get("prompt_tokens", 0),
completion_tokens=token_data.get("completion_tokens", 0),
- total_tokens=token_data.get("prompt_tokens", 0)
- + token_data.get("completion_tokens", 0),
+ total_tokens=total_tokens,
# Research context
research_query=token_data.get("research_query"),
research_mode=token_data.get("research_mode"),
@@ -176,9 +183,6 @@ class ThreadSafeMetricsWriter:
# Update or create model usage statistics (matches MainThread
# path in token_counter.py _save_to_db).
- total_tokens = token_data.get("prompt_tokens", 0) + token_data.get(
- "completion_tokens", 0
- )
model_name = token_data.get("model_name")
model_usage = (
session.query(ModelUsage)
diff --git a/src/local_deep_research/metrics/token_counter.py b/src/local_deep_research/metrics/token_counter.py
index d6f61fd684..8c40e53d3a 100644
--- a/src/local_deep_research/metrics/token_counter.py
+++ b/src/local_deep_research/metrics/token_counter.py
@@ -426,8 +426,19 @@ class TokenCountingCallback(BaseCallbackHandler):
"completion_tokens": usage_meta.get(
"output_tokens", 0
),
- "total_tokens": usage_meta.get(
- "total_tokens", 0
+ # Fall back to the sum: a provider that omits
+ # the total otherwise contributes 0 here.
+ # `or` rather than `is None` is deliberate: a
+ # reported total of 0 alongside nonzero input
+ # and output is bad data, and the sum recovers
+ # it. The `is None` checks further down
+ # (_save_to_db, thread_metrics) persist a real
+ # 0, because the total has already been
+ # resolved by the time they run.
+ "total_tokens": usage_meta.get("total_tokens")
+ or (
+ usage_meta.get("input_tokens", 0)
+ + usage_meta.get("output_tokens", 0)
),
}
# Check context overflow before breaking
@@ -577,7 +588,12 @@ class TokenCountingCallback(BaseCallbackHandler):
# Save to database if we have a research_id
if self.research_id:
- self._save_to_db(prompt_tokens, completion_tokens, call_meta)
+ self._save_to_db(
+ prompt_tokens,
+ completion_tokens,
+ call_meta,
+ total_tokens=total_tokens,
+ )
elif self.research_id:
# The provider returned no usage data at all (e.g. OpenAI-
# compatible servers that omit `usage` on streamed responses,
@@ -702,12 +718,16 @@ class TokenCountingCallback(BaseCallbackHandler):
prompt_tokens: int,
completion_tokens: int,
call_meta: Optional[Dict[str, Any]] = None,
+ total_tokens: Optional[int] = None,
):
"""Save token usage to the database.
Args:
prompt_tokens: Prompt-side token count for this call.
completion_tokens: Completion-side token count for this call.
+ total_tokens: Total reported by the provider, as resolved by
+ the caller. Defaults to the sum of the two counts above
+ when the caller has no provider-reported total.
call_meta: Per-run call metadata captured by on_llm_start
(calling_file / calling_function / call_stack). When the
callback is invoked outside on_llm_end / on_llm_error
@@ -715,6 +735,8 @@ class TokenCountingCallback(BaseCallbackHandler):
``call_meta`` may be ``None`` and the instance attributes
are used as a fallback.
"""
+ if total_tokens is None:
+ total_tokens = prompt_tokens + completion_tokens
if call_meta is None:
with self._lock:
call_meta = {
@@ -749,6 +771,7 @@ class TokenCountingCallback(BaseCallbackHandler):
"provider": self.current_provider,
"prompt_tokens": prompt_tokens,
"completion_tokens": completion_tokens,
+ "total_tokens": total_tokens,
"research_query": self.research_context.get("research_query"),
"research_mode": self.research_context.get("research_mode"),
"research_phase": self.research_context.get("research_phase"),
@@ -862,7 +885,7 @@ class TokenCountingCallback(BaseCallbackHandler):
# for accurate cost tracking
prompt_tokens=prompt_tokens,
completion_tokens=completion_tokens,
- total_tokens=prompt_tokens + completion_tokens,
+ total_tokens=total_tokens,
# Phase 1 Enhancement: Research context
research_query=research_query,
research_mode=research_mode,
@@ -894,15 +917,13 @@ class TokenCountingCallback(BaseCallbackHandler):
)
if model_usage:
- model_usage.total_tokens += (
- prompt_tokens + completion_tokens
- )
+ model_usage.total_tokens += total_tokens
model_usage.total_calls += 1
else:
model_usage = ModelUsage(
model_name=self.current_model,
model_provider=self.current_provider,
- total_tokens=prompt_tokens + completion_tokens,
+ total_tokens=total_tokens,
total_calls=1,
)
session.add(model_usage)
diff --git a/tests/database/test_thread_metrics_writer.py b/tests/database/test_thread_metrics_writer.py
index 5aae5cfe19..89d27acbb9 100644
--- a/tests/database/test_thread_metrics_writer.py
+++ b/tests/database/test_thread_metrics_writer.py
@@ -508,6 +508,60 @@ class TestWriteTokenMetrics:
)
assert mock_session.add.call_count == 2
+ def test_provider_total_is_used_when_supplied(
+ self, writer_with_password, mock_db_manager
+ ):
+ """A total_tokens in token_data overrides the recomputed sum."""
+ token_data = {
+ "model_name": "gpt-4",
+ "provider": "openai",
+ "prompt_tokens": 100,
+ "completion_tokens": 50,
+ "total_tokens": 175,
+ }
+
+ mock_db, mock_session = mock_db_manager
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+
+ with patch(
+ "local_deep_research.database.models.TokenUsage"
+ ) as mock_token_cls:
+ with patch(
+ "local_deep_research.database.models.ModelUsage"
+ ) as mock_model_cls:
+ writer_with_password.write_token_metrics(
+ "testuser", 1, token_data
+ )
+
+ assert mock_token_cls.call_args[1]["total_tokens"] == 175
+ assert mock_model_cls.call_args[1]["total_tokens"] == 175
+
+ def test_provider_total_increments_existing_model_usage(
+ self, writer_with_password, mock_db_manager
+ ):
+ """An existing ModelUsage row is incremented by the provider total."""
+ token_data = {
+ "model_name": "gpt-4",
+ "provider": "openai",
+ "prompt_tokens": 100,
+ "completion_tokens": 50,
+ "total_tokens": 175,
+ }
+
+ mock_db, mock_session = mock_db_manager
+ existing = MagicMock()
+ existing.total_tokens = 1000
+ existing.total_calls = 5
+ mock_session.query.return_value.filter_by.return_value.first.return_value = existing
+
+ with patch(
+ "local_deep_research.database.models.TokenUsage", MagicMock()
+ ):
+ writer_with_password.write_token_metrics("testuser", 1, token_data)
+
+ assert existing.total_tokens == 1175
+ assert existing.total_calls == 6
+
def test_updates_existing_model_usage(
self, writer_with_password, mock_db_manager
):
diff --git a/tests/metrics/test_token_counter_db.py b/tests/metrics/test_token_counter_db.py
index a8c3b67755..1dba2eca7e 100644
--- a/tests/metrics/test_token_counter_db.py
+++ b/tests/metrics/test_token_counter_db.py
@@ -3,6 +3,8 @@
import threading
from unittest.mock import MagicMock, Mock, patch
+from langchain_core.outputs import LLMResult
+
from local_deep_research.metrics.token_counter import (
TokenCountingCallback,
)
@@ -226,3 +228,149 @@ class TestSaveToDbThread:
cb._save_to_db(100, 50)
mock_writer.write_token_metrics.assert_not_called()
+
+
+# ── persisted total vs provider-reported total ─────────────────────
+
+
+class TestPersistedTotalMatchesSessionCounter:
+ """The persisted total must equal the total the session counter used.
+
+ The counter honours the provider's own ``total_tokens`` while every
+ database write used to recompute it as prompt + completion, so one
+ response produced two different totals.
+ """
+
+ def _make_callback(self, model="gpt-4", provider="openai"):
+ cb = TokenCountingCallback(
+ research_id="r-123",
+ research_context={"research_query": "test"},
+ )
+ cb.current_model = model
+ cb.current_provider = provider
+ cb.counts["by_model"][model] = {
+ "prompt_tokens": 0,
+ "completion_tokens": 0,
+ "total_tokens": 0,
+ "calls": 1,
+ "provider": provider,
+ }
+ return cb
+
+ def _drive(self, cb, response):
+ """Run on_llm_end on the MainThread path, return the added records."""
+ mock_session = MagicMock()
+ mock_session.query.return_value.filter_by.return_value.first.return_value = None
+
+ mock_thread = MagicMock()
+ mock_thread.name = "MainThread"
+
+ with patch.object(
+ threading, "current_thread", return_value=mock_thread
+ ):
+ with patch("flask.session", {"username": "testuser"}, create=True):
+ with patch(
+ "local_deep_research.database.session_context.get_user_db_session"
+ ) as mock_gs:
+ mock_gs.return_value.__enter__ = Mock(
+ return_value=mock_session
+ )
+ mock_gs.return_value.__exit__ = Mock(return_value=False)
+
+ cb.on_llm_end(response)
+
+ return [c.args[0] for c in mock_session.add.call_args_list]
+
+ def test_provider_total_is_persisted(self):
+ """A provider total above prompt + completion reaches the database."""
+ cb = self._make_callback()
+
+ response = Mock(spec=LLMResult)
+ response.llm_output = {
+ "token_usage": {
+ "prompt_tokens": 100,
+ "completion_tokens": 50,
+ "total_tokens": 175,
+ }
+ }
+ response.generations = []
+
+ added = self._drive(cb, response)
+
+ assert cb.counts["total_tokens"] == 175
+ assert [r.total_tokens for r in added] == [175, 175]
+
+ def test_usage_metadata_without_total_falls_back_to_the_sum(self):
+ """A provider that omits the total must not count as zero tokens."""
+ cb = self._make_callback(model="llama3", provider="ollama")
+
+ message = Mock()
+ message.usage_metadata = {"input_tokens": 100, "output_tokens": 50}
+ message.response_metadata = {}
+ generation = Mock()
+ generation.message = message
+
+ response = Mock(spec=LLMResult)
+ response.llm_output = None
+ response.generations = [[generation]]
+
+ added = self._drive(cb, response)
+
+ assert cb.counts["total_tokens"] == 150
+ assert [r.total_tokens for r in added] == [150, 150]
+
+ def test_thread_path_forwards_the_provider_total(self):
+ """The background-thread writer receives the resolved total."""
+ cb = TokenCountingCallback(
+ research_id="r-1",
+ research_context={
+ "username": "testuser",
+ "user_password": "pass",
+ },
+ )
+ cb.current_model = "gpt-4"
+ cb.current_provider = "openai"
+
+ mock_thread = MagicMock()
+ mock_thread.name = "WorkerThread"
+ mock_writer = MagicMock()
+
+ with patch.object(
+ threading, "current_thread", return_value=mock_thread
+ ):
+ with patch(
+ "local_deep_research.database.thread_metrics.metrics_writer",
+ mock_writer,
+ ):
+ cb._save_to_db(100, 50, total_tokens=175)
+
+ token_data = mock_writer.write_token_metrics.call_args.args[2]
+ assert token_data["total_tokens"] == 175
+
+ def test_thread_path_defaults_to_the_sum(self):
+ """Callers with no provider total still persist prompt + completion."""
+ cb = TokenCountingCallback(
+ research_id="r-1",
+ research_context={
+ "username": "testuser",
+ "user_password": "pass",
+ },
+ )
+ cb.current_model = "gpt-4"
+ cb.current_provider = "openai"
+
+ mock_thread = MagicMock()
+ mock_thread.name = "WorkerThread"
+ mock_writer = MagicMock()
+
+ with patch.object(
+ threading, "current_thread", return_value=mock_thread
+ ):
+ with patch(
+ "local_deep_research.database.thread_metrics.metrics_writer",
+ mock_writer,
+ ):
+ cb._save_to_db(100, 50)
+
+ token_data = mock_writer.write_token_metrics.call_args.args[2]
+ assert token_data["total_tokens"] == 150
diff --git a/tests/test_token_counter_coverage.py b/tests/test_token_counter_coverage.py
index c68fed8f6e..3535c6ee0f 100644
--- a/tests/test_token_counter_coverage.py
+++ b/tests/test_token_counter_coverage.py
@@ -458,6 +458,7 @@ class TestOnLlmEnd:
"calling_function": None,
"call_stack": None,
},
+ total_tokens=30,
)
def test_save_to_db_not_called_without_research_id(self):