Skip to content

feat(evaluation): track token usage in evaluation results - #13487

Merged
KevinHuSh merged 2 commits into
infiniflow:mainfrom
kiannidev:feat/track-evaluation-token-usage
May 22, 2026
Merged

KevinHuSh merged 2 commits into
infiniflow:mainfrom
kiannidev:feat/track-evaluation-token-usage

Conversation

@kiannidev

Copy link
Copy Markdown
Contributor

Summary

Implements the TODO in evaluation_service.py: Track token usage in evaluation results.

Changes

  • Import num_tokens_from_string from common.token_utils
  • Prompt tokens: Use the full prompt returned by async_chat when available (includes system prompt + knowledge base + query), otherwise fall back to the question token count
  • Completion tokens: Count tokens in the generated answer
  • Storage: Store token_usage as {prompt_tokens, completion_tokens, total_tokens} in each EvaluationResult instead of None

Why

The evaluation pipeline previously saved token_usage: None for 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

  • No new tests added; existing evaluation flow unchanged
  • Token counting uses existing num_tokens_from_string utility

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
@dosubot dosubot Bot added the size:S This PR changes 10-29 lines, ignoring generated files. label Mar 9, 2026

@gambletan gambletan left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The implementation addresses the TODO cleanly, but I have a few concerns:

  1. Token counting accuracy: num_tokens_from_string uses 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.

  2. The else: ans = {} addition (line 421): This is a subtle but important fix — without it, if the for loop completes without break (i.e., all streamed chunks are consumed but none contain an answer), ans would be unbound when accessed later at ans.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.

  3. Missing prompt key scenario: When ans doesn't contain a "prompt" key (which seems possible depending on async_chat behavior), 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.

  4. 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_usage dict structure would add confidence, especially around the ans.get("prompt", "") fallback behavior.

The change itself is straightforward and non-breaking. The else: ans = {} fix is a bonus improvement.

@dosubot dosubot Bot added size:L This PR changes 100-499 lines, ignoring generated files. and removed size:S This PR changes 10-29 lines, ignoring generated files. labels Mar 10, 2026
@kiannidev
kiannidev force-pushed the feat/track-evaluation-token-usage branch from 986d026 to d1b05b9 Compare March 11, 2026 17:29
@kiannidev

Copy link
Copy Markdown
Contributor Author

The implementation addresses the TODO cleanly, but I have a few concerns:

  1. Token counting accuracy: num_tokens_from_string uses 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.
  2. The else: ans = {} addition (line 421): This is a subtle but important fix — without it, if the for loop completes without break (i.e., all streamed chunks are consumed but none contain an answer), ans would be unbound when accessed later at ans.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.
  3. Missing prompt key scenario: When ans doesn't contain a "prompt" key (which seems possible depending on async_chat behavior), 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.
  4. 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_usage dict structure would add confidence, especially around the ans.get("prompt", "") fallback behavior.

The change itself is straightforward and non-breaking. The else: ans = {} fix is a bonus improvement.

Hi, @gambletan
Thanks for your review.
I updated code from your feedback.
Please check it.

Thanks again.

@kiannidev
kiannidev requested a review from gambletan March 11, 2026 18:31
@kiannidev

Copy link
Copy Markdown
Contributor Author

Hi, @gambletan
Please review this PR..
Thanks

@kiannidev

Copy link
Copy Markdown
Contributor Author

Hi, @gambletan
Please review this PR when you have time.

Thanks

@kiannidev

Copy link
Copy Markdown
Contributor Author

Hi, @gambletan
Please review this PR

@kiannidev

Copy link
Copy Markdown
Contributor Author

Hi, @gambletan
Can you review this PR?

@kiannidev

Copy link
Copy Markdown
Contributor Author

Hi, @gambletan , @KevinHuSh
Please check this PR

@KevinHuSh KevinHuSh added the ci Continue Integration label May 22, 2026
@KevinHuSh
KevinHuSh marked this pull request as draft May 22, 2026 06:04
@KevinHuSh
KevinHuSh marked this pull request as ready for review May 22, 2026 06:04
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. 🌈 python Pull requests that update Python code 💞 feature Feature request, pull request that fullfill a new feature. and removed size:L This PR changes 100-499 lines, ignoring generated files. labels May 22, 2026
@coderabbitai

coderabbitai Bot commented May 22, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

EvaluationService 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.

Changes

Token Usage Tracking in Evaluation Service

Layer / File(s) Summary
Token usage computation and persistence
api/db/services/evaluation_service.py
Imports num_tokens_from_string for token estimation. When chat yields no answer, logs a warning and records empty output. Computes prompt_tokens from response prompt field or falls back to question-only counting; computes completion_tokens from answer; builds and persists token_usage dict in EvaluationResult instead of None.
Token usage tracking unit tests
test/unit_test/api/db/services/test_evaluation_service_token_usage.py
Test fixtures provide mock dialog service and baseline case data. Tests verify token usage structure when prompt is present, fallback token counting when prompt missing, warning logs and zero completion tokens when chat returns no answer, and _compute_summary_metrics aggregates result totals and averages.

🎯 3 (Moderate) | ⏱️ ~22 minutes

A rabbit hops through tokens, counting each word with care,
Prompts and answers tallied, with fallback logic fair,
No response? Just a warning—empty tokens stored with grace,
Tests confirm each scenario in evaluation's tracked space! 🐰✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 53.85% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately and concisely describes the main change: adding token usage tracking to evaluation results.
Description check ✅ Passed The description covers the problem, type of change, specific modifications, rationale, and testing approach, but is missing checkbox selections for the PR type template.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ 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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between 440153c and d1b05b9.

📒 Files selected for processing (2)
  • api/db/services/evaluation_service.py
  • test/unit_test/api/db/services/test_evaluation_service_token_usage.py

Comment on lines +74 to +83
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

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

codecov Bot commented May 22, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 93.12%. Comparing base (4f507c0) to head (d1b05b9).
⚠️ Report is 889 commits behind head on main.

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.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@KevinHuSh
KevinHuSh merged commit faf77a5 into infiniflow:main May 22, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ci Continue Integration 💞 feature Feature request, pull request that fullfill a new feature. 🌈 python Pull requests that update Python code size:M This PR changes 30-99 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants