Repository navigation
feat(evaluation): track token usage in evaluation results - #13487
Conversation
Implement TODO: Track token usage in _evaluate_single_case.
- Add num_tokens_from_string import from common.token_utils
- Use full prompt from async_chat response when available for accurate
prompt_tokens (includes system prompt + knowledge base + query)
- Fallback to question token count when prompt not returned (e.g. solo chat)
- Store structured token_usage: {prompt_tokens, completion_tokens, total_tokens}
in each EvaluationResult instead of None
Made-with: Cursor
gambletan
left a comment
There was a problem hiding this comment.
The implementation addresses the TODO cleanly, but I have a few concerns:
-
Token counting accuracy:
num_tokens_from_stringuses tiktoken (cl100k_base), which gives accurate counts for OpenAI models but will be an approximation for other LLM providers (e.g., local models, Anthropic, etc.). This is acknowledged in the PR description as "approximate," which is fair, but it might be worth adding a comment in the code noting this is an estimate — especially since a "token_usage" field suggests precision to downstream consumers. -
The
else: ans = {}addition (line 421): This is a subtle but important fix — without it, if theforloop completes withoutbreak(i.e., all streamed chunks are consumed but none contain an answer),answould be unbound when accessed later atans.get("prompt", ""). Good catch. However, should there also be a log warning here? An evaluation case that produces no answer seems like it warrants visibility. -
Missing
promptkey scenario: Whenansdoesn't contain a"prompt"key (which seems possible depending onasync_chatbehavior), the fallback to counting only the question tokens significantly undercounts the actual prompt tokens, since the real prompt includes system instructions + retrieved chunks. This could be misleading for cost tracking. Consider documenting this limitation or logging when the fallback path is taken. -
No tests added: The PR description notes this, but given that this is a new feature (token tracking), even a minimal unit test verifying the
token_usagedict structure would add confidence, especially around theans.get("prompt", "")fallback behavior.
The change itself is straightforward and non-breaking. The else: ans = {} fix is a bonus improvement.
986d026 to
d1b05b9
Compare
Hi, @gambletan Thanks again. |
|
Hi, @gambletan |
|
Hi, @gambletan Thanks |
|
Hi, @gambletan |
|
Hi, @gambletan |
|
Hi, @gambletan , @KevinHuSh |
📝 WalkthroughWalkthroughEvaluationService now tracks token usage for each evaluation case by importing token-counting utilities, computing prompt tokens (from chat response or fallback to question), computing completion tokens from answers, handling empty chat responses with warnings, and storing the resulting token_usage dict in persisted evaluation results. Comprehensive unit tests validate token counting across scenarios including available prompts, missing prompts with fallback, empty responses, and metrics aggregation. ChangesToken Usage Tracking in Evaluation Service
🎯 3 (Moderate) | ⏱️ ~22 minutes
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@test/unit_test/api/db/services/test_evaluation_service_token_usage.py`:
- Around line 74-83: The current assertions in
test_evaluation_service_token_usage.py only check presence and positivity of
token counts (using captured_create and token_usage) but not exact behavior;
update the assertions for each scenario (full prompt, question-fallback,
empty-answer) to assert exact expected values for prompt_tokens,
completion_tokens, and total_tokens (e.g., computed constants or fixture-derived
expected counts) and keep the total_tokens == prompt_tokens + completion_tokens
check; apply the same tightening to the other assertion blocks referenced (lines
~111-120 and ~149-153) so each test asserts the exact numeric token counts for
that scenario rather than just >0.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
Run ID: 6dcb7e47-8c9d-44b4-9937-0613b3d89367
📒 Files selected for processing (2)
api/db/services/evaluation_service.pytest/unit_test/api/db/services/test_evaluation_service_token_usage.py
| assert result is not None | ||
| assert "token_usage" in captured_create | ||
| token_usage = captured_create["token_usage"] | ||
| assert "prompt_tokens" in token_usage | ||
| assert "completion_tokens" in token_usage | ||
| assert "total_tokens" in token_usage | ||
| assert token_usage["total_tokens"] == token_usage["prompt_tokens"] + token_usage["completion_tokens"] | ||
| assert token_usage["prompt_tokens"] > 0 | ||
| assert token_usage["completion_tokens"] > 0 | ||
|
|
There was a problem hiding this comment.
Strengthen token-count assertions to verify behavior, not just structure.
These assertions are too permissive and can pass even if prompt/fallback counting regresses. Please assert exact expected counts per scenario (full prompt, question fallback, empty answer case).
Proposed test-tightening diff
import pytest
from types import SimpleNamespace
from api.db.services.evaluation_service import EvaluationService
+from common.token_utils import num_tokens_from_string
@@
assert "total_tokens" in token_usage
assert token_usage["total_tokens"] == token_usage["prompt_tokens"] + token_usage["completion_tokens"]
- assert token_usage["prompt_tokens"] > 0
- assert token_usage["completion_tokens"] > 0
+ expected_prompt = num_tokens_from_string(
+ "System instructions here.\n\nKnowledge: Some context.\n\nQuery: What is the capital of France?"
+ )
+ expected_completion = num_tokens_from_string("Paris is the capital of France.")
+ assert token_usage["prompt_tokens"] == expected_prompt
+ assert token_usage["completion_tokens"] == expected_completion
@@
assert "total_tokens" in token_usage
assert token_usage["total_tokens"] == token_usage["prompt_tokens"] + token_usage["completion_tokens"]
- # With fallback, prompt_tokens should reflect question only (smaller than full prompt)
- assert token_usage["prompt_tokens"] >= 0
- assert token_usage["completion_tokens"] > 0
+ assert token_usage["prompt_tokens"] == num_tokens_from_string(minimal_case["question"])
+ assert token_usage["completion_tokens"] == num_tokens_from_string("Paris.")
@@
# No answer tokens in this case
assert token_usage["completion_tokens"] == 0
- assert token_usage["prompt_tokens"] >= 0
+ assert token_usage["prompt_tokens"] == num_tokens_from_string(minimal_case["question"])
assert token_usage["total_tokens"] == token_usage["prompt_tokens"]Also applies to: 111-120, 149-153
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@test/unit_test/api/db/services/test_evaluation_service_token_usage.py` around
lines 74 - 83, The current assertions in test_evaluation_service_token_usage.py
only check presence and positivity of token counts (using captured_create and
token_usage) but not exact behavior; update the assertions for each scenario
(full prompt, question-fallback, empty-answer) to assert exact expected values
for prompt_tokens, completion_tokens, and total_tokens (e.g., computed constants
or fixture-derived expected counts) and keep the total_tokens == prompt_tokens +
completion_tokens check; apply the same tightening to the other assertion blocks
referenced (lines ~111-120 and ~149-153) so each test asserts the exact numeric
token counts for that scenario rather than just >0.
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #13487 +/- ##
===========================================
+ Coverage 46.09% 93.12% +47.03%
===========================================
Files 44 10 -34
Lines 9910 713 -9197
Branches 110 116 +6
===========================================
- Hits 4568 664 -3904
+ Misses 5334 29 -5305
- Partials 8 20 +12 ☔ View full report in Codecov by Sentry. 🚀 New features to boost your workflow:
|
Summary
Implements the TODO in
evaluation_service.py: Track token usage in evaluation results.Changes
num_tokens_from_stringfromcommon.token_utilsasync_chatwhen available (includes system prompt + knowledge base + query), otherwise fall back to the question token counttoken_usageas{prompt_tokens, completion_tokens, total_tokens}in eachEvaluationResultinstead ofNoneWhy
The evaluation pipeline previously saved
token_usage: Nonefor every result. This change allows downstream consumers (e.g. evaluation dashboards, cost tracking) to see approximate token usage per test case using the same tokenizer (tiktoken cl100k_base) used elsewhere in RAGFlow.Testing
num_tokens_from_stringutility