Repository navigation
feat(agent): report accurate aggregated token usage and propagate session/user + input/output to Langfuse for agent runs - #16420
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds per-run token aggregation with shared context state, updates chat model usage tracking, normalizes Langfuse reporting, installs run context in canvas execution, and forwards aggregated usage through agent completion events. ChangesToken Usage Tracking and Langfuse Attribution
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
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: 5
🧹 Nitpick comments (1)
common/token_utils.py (1)
65-66: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winLog token aggregation failures instead of silently swallowing them.
A malformed sink or unexpected token value currently disables run usage tracking with no trace. Add low-volume debug logging in this exception path.
Proposed fix
+import logging import contextvars import os import threading ... - except Exception: - pass + except Exception: + logging.debug("Failed to record run token usage", exc_info=True)As per coding guidelines,
**/*.py: Add logging for new flows.🤖 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 `@common/token_utils.py` around lines 65 - 66, The token aggregation logic in token_utils is silently swallowing unexpected errors, which hides malformed sink or token value issues and disables usage tracking without any trace. Update the except Exception path to emit low-volume debug logging with enough context to identify the failing aggregation/input, then keep the fallback behavior unchanged so the flow still degrades safely. Use the existing token aggregation helper in common/token_utils and add logging consistent with the Python logging guidelines for new flows.Source: Coding guidelines
🤖 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 `@agent/canvas.py`:
- Around line 887-895: The run-scoped usage in _build_message_end() is being
attached to every message_end event, which can cause cumulative double counting
across multi-message graphs. Update the usage emission logic in
Canvas._build_message_end so it only includes _run_token_usage on a single final
event, or move this data to a dedicated run-level payload; use the existing
_run_token_usage and message_end handling to locate the change.
- Around line 388-391: The run aggregate is missing token usage from sync
executor work because `run_in_executor` drops the current context. Update the
executor path in `canvas.py` so the callable submitted from the run setup
inherits the active context, using `contextvars.copy_context().run(...)` around
the target (or switching that path to `asyncio.to_thread`) so `token_usage_sink`
and `langfuse_run_attrs` remain available to LLMBundle calls inside sync
components.
- Around line 388-401: Reset the run-scoped ContextVars in Canvas.run when the
stream finishes by storing the tokens returned from token_usage_sink.set(...)
and langfuse_run_attrs.set(...), then resetting both in a finally block. This
fixes the stale per-run state so later LLM calls in the same request do not keep
writing into the previous _run_token_usage or inherit old user_id/session_id
values. Use the existing Canvas.run setup around token_usage_sink and
langfuse_run_attrs as the place to make the change.
In `@rag/llm/chat_model.py`:
- Around line 427-428: The Base tool-call paths are still discarding the
prompt/completion usage split and only storing totals in last_usage. Update the
non-streaming and streaming branches in chat_model.py’s Base tool-call handling
to use usage_from_response(response) for the normal response path, and enable
stream_options.include_usage for the streaming path instead of estimating from
deltas. Make sure the affected tool-call flow methods and the last_usage
assignment preserve prompt_tokens, completion_tokens, and total_tokens
consistently.
---
Nitpick comments:
In `@common/token_utils.py`:
- Around line 65-66: The token aggregation logic in token_utils is silently
swallowing unexpected errors, which hides malformed sink or token value issues
and disables usage tracking without any trace. Update the except Exception path
to emit low-volume debug logging with enough context to identify the failing
aggregation/input, then keep the fallback behavior unchanged so the flow still
degrades safely. Use the existing token aggregation helper in common/token_utils
and add logging consistent with the Python logging guidelines for new flows.
🪄 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: b5444b85-3ca5-490b-bb59-5e972dbb74a4
📒 Files selected for processing (5)
agent/canvas.pyapi/db/services/canvas_service.pyapi/db/services/llm_service.pycommon/token_utils.pyrag/llm/chat_model.py
|
Thanks for the thorough review @coderabbitai 🙏 — all five actionable comments plus the nitpick are addressed (replies inline on each thread). Summary:
|
|
Tip For best results, initiate chat on the files or code changes.
🐇✨ If you found this review helpful, would you consider giving us a shout-out on X? Thank you for using CodeRabbit! |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
rag/llm/chat_model.py (3)
559-573: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winInclude reasoning deltas in fallback token estimates.
When provider usage is absent, reasoning chunks yield
_reasoning, but the fallback estimate only countsdelta.content, which is often empty for reasoning deltas.Proposed fix
- if not _u["total_tokens"]: - round_estimate += num_tokens_from_string(delta.content) + if not _u["total_tokens"]: + round_estimate += num_tokens_from_string(_reasoning or delta.content)🤖 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 `@rag/llm/chat_model.py` around lines 559 - 573, The fallback token estimate in the streaming branch of chat_model.py is skipping reasoning-only chunks because it only counts delta.content. Update the logic around the _reasoning handling in the streaming loop to include reasoning text when usage data is missing, so round_estimate reflects both delta.content and the reasoning delta source used to build the emitted <think> block.
224-260: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winPreserve authoritative usage in this streaming path. Usage-only final chunks are skipped here, so
last_usagestays zero and the method keeps returning estimated totals instead of the provider’s split/usage values. Mirror the handling used in the later streaming implementation and readusage_from_response(resp)before thechoicesguard.🤖 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 `@rag/llm/chat_model.py` around lines 224 - 260, The streaming path in async_chat_streamly is ignoring provider usage on final usage-only chunks, so last_usage stays zero and estimated token totals are returned instead of authoritative values. Update the streaming loop in async_chat_streamly to read usage_from_response(resp) before the choices check, and when usage is present, populate self.last_usage from it and avoid skipping that chunk; mirror the handling used in the later streaming implementation so split usage values are preserved.
174-176: 🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick winAvoid sharing
last_usageacross overlapping callsLLMBundle._report_usage()reads mutable instance state after the await, so concurrent calls on the same model instance can report the wrong prompt/completion split. Thread the usage through the return value or keep the bundle run-scoped.🤖 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 `@rag/llm/chat_model.py` around lines 174 - 176, The mutable last_usage state on ChatModel is shared across overlapping chat calls, which can cause LLMBundle._report_usage() to read the wrong token split after await. Update the ChatModel chat path so usage is returned with each call instead of stored on the instance, and adjust LLMBundle and any related call sites to consume that per-call usage data; use the ChatModel and LLMBundle._report_usage symbols to locate the affected flow.
🤖 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 `@agent/canvas.py`:
- Around line 405-415: The cleanup fallback in the finally block silently clears
ContextVar state when reset() raises ValueError, so add debug logging with
exc_info=True before the fallback set(None) calls. Update the exception handlers
around token_usage_sink.reset(sink_token) and
langfuse_run_attrs.reset(attrs_token) in canvas.py to log the reset failure
context so disconnect/finalization attribution gaps are traceable. Keep the
existing fallback behavior, but make the fallback path observable through debug
logs.
In `@api/apps/restful_apis/agent_api.py`:
- Around line 559-562: The streaming filter in agent_api.py is forwarding the
entire workflow_finished payload via the event handling around yield ans, which
exposes Canvas.workflow_finished internals. Update the workflow_finished branch
to emit only a sanitized run-level usage payload, preserving message/message_end
behavior while stripping data.inputs and full data.outputs from the completion
stream.
---
Outside diff comments:
In `@rag/llm/chat_model.py`:
- Around line 559-573: The fallback token estimate in the streaming branch of
chat_model.py is skipping reasoning-only chunks because it only counts
delta.content. Update the logic around the _reasoning handling in the streaming
loop to include reasoning text when usage data is missing, so round_estimate
reflects both delta.content and the reasoning delta source used to build the
emitted <think> block.
- Around line 224-260: The streaming path in async_chat_streamly is ignoring
provider usage on final usage-only chunks, so last_usage stays zero and
estimated token totals are returned instead of authoritative values. Update the
streaming loop in async_chat_streamly to read usage_from_response(resp) before
the choices check, and when usage is present, populate self.last_usage from it
and avoid skipping that chunk; mirror the handling used in the later streaming
implementation so split usage values are preserved.
- Around line 174-176: The mutable last_usage state on ChatModel is shared
across overlapping chat calls, which can cause LLMBundle._report_usage() to read
the wrong token split after await. Update the ChatModel chat path so usage is
returned with each call instead of stored on the instance, and adjust LLMBundle
and any related call sites to consume that per-call usage data; use the
ChatModel and LLMBundle._report_usage symbols to locate the affected flow.
🪄 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: 2500281f-1bde-4403-ab17-f05914f55cd2
📒 Files selected for processing (5)
agent/canvas.pyapi/apps/restful_apis/agent_api.pyapi/db/services/llm_service.pycommon/token_utils.pyrag/llm/chat_model.py
🚧 Files skipped from review as they are similar to previous changes (2)
- common/token_utils.py
- api/db/services/llm_service.py
78db4e9 to
f86a0e7
Compare
There was a problem hiding this comment.
Pull request overview
This PR adds run-scoped token accounting for Agent (Canvas) executions so that token usage from all underlying LLM calls in a single agent turn is aggregated and reported once, and improves Langfuse correlation/usage reporting (prompt vs completion split + session/user propagation) for agent runs.
Changes:
- Introduces contextvar-based per-run usage accumulation (
token_usage_sink) plus a helper to extract prompt/completion/total usage from provider responses. - Captures prompt/completion/total usage in the provider layer (including streaming + multi-round tool loops) and reports it via LLMBundle to both Langfuse and the active run sink.
- Installs the per-run sink/attrs in
Canvas.run()and emits aggregated usage on the terminal event; forwards session_id into Canvas runs for correct Langfuse grouping.
Reviewed changes
Copilot reviewed 6 out of 6 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
rag/llm/chat_model.py |
Captures and aggregates per-call usage (incl. streaming and multi-round tool calls) into last_usage. |
common/token_utils.py |
Adds run-scoped contextvars, sink recording, and usage_from_response() extraction helper. |
api/db/services/llm_service.py |
Records per-call usage into the run sink and enriches Langfuse usage_details + session/user propagation. |
api/db/services/canvas_service.py |
Passes session_id into Canvas.run() for run-level correlation. |
api/apps/restful_apis/agent_api.py |
Attempts to forward only run-level usage for workflow_finished in session completion flows and attaches usage to non-stream final response. |
agent/canvas.py |
Installs/reset run-scoped sink/attrs, propagates context into executor threads, and emits aggregated run usage on workflow_finished. |
…sion/user + input/output to Langfuse for agent runs Rebuilt on current upstream/main after force-push; cherry-pick of the 7 PR-original commits collapsed into a single net diff to avoid conflicts with intervening commits pulled in by repeated merges of upstream/main. Original PR work (commits dropped during rebuild because their content already lives on upstream/main or was a merge of upstream/main): c7339ae Enhance LLMService with token usage reporting 0266cf0 Implement token usage tracking and Langfuse integration ab2b267 Include session_id in run_kwargs 8bf937c Implement token usage tracking in chat model c955988 Enhance token tracking with context variables and functions 3e88ed5 fix(agent): address CodeRabbit review on token usage tracking 74b8c8c fix(agent): address CodeRabbit follow-up review Forced-upstream duplicates dropped (already merged to main): 70546ea (infiniflow#16396), 5b09910 (infiniflow#16403), 5d7f0fd (infiniflow#16405), 730f33b (infiniflow#16407), a06343e (infiniflow#16408), f90be41 (infiniflow#16410), c4fe68e (infiniflow#16409), d4a0e71 (infiniflow#14773), ef42fd7 (infiniflow#15436), ab1015d (infiniflow#16363), db188cc (infiniflow#15446), 56ece68 (infiniflow#15609), 2589b6e (infiniflow#15644), 74c2944 (infiniflow#15374), 78832ff (infiniflow#14985), bf18b59 (infiniflow#15457), 6c87225 (infiniflow#14890), e16d1a0 (infiniflow#15426), 4712fcb (infiniflow#16169), 0536233 (infiniflow#14589), 08c807a (infiniflow#15145) Plus 18 'Merge branch main into main' commits dropped (polluted topology). Co-authored-by: yzc <[email protected]>
…code) Copilot review: in the streaming session-completion path, "workflow_finished" was listed in the broad `event in [...]` branch that does `yield ans; continue`, so the dedicated block that forwards only the aggregated usage (stripping the terminal inputs/outputs payload) was unreachable. The full workflow_finished payload was therefore streamed, contradicting the code's own comment. Drop "workflow_finished" from the broad branch so it falls through to the usage-only block, which now also logs and continues. message/message_end/ user_inputs behaviour is unchanged. Co-authored-by: Cursor <[email protected]>
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #16420 +/- ##
=======================================
Coverage 93.16% 93.16%
=======================================
Files 10 10
Lines 717 717
Branches 118 118
=======================================
Hits 668 668
Misses 29 29
Partials 20 20 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
### Summary Port the following PRs to GO in this PR infiniflow#16420 infiniflow#13295
### Summary Port the following PRs to GO in this PR infiniflow#16420 infiniflow#13295
What problem does this PR solve?
Briefly describe what this PR aims to solve. Include background context that will help reviewers understand the purpose of the PR.
Type of change
Summary
Agent (Canvas) runs previously did not surface token usage in the SSE stream, and RAGFlow's own Langfuse generations for agent runs were missing the prompt/completion split and the session/user correlation. This made it impossible for an external caller (or Langfuse) to reconcile an agent turn's cost with the upstream provider (e.g. OpenRouter), because a single turn can issue several distinct LLM calls (query rewriting / cross-language translation, multi-round tool reasoning, nested sub-agents, and the final answer).
This PR introduces a per-run token usage sink so that every LLM call in a run is aggregated and reported once, and enriches Langfuse generations with the prompt/completion split plus session/user attributes.
What changes
1. Per-run token usage sink (
common/token_utils.py)contextvars:token_usage_sink(a mutable per-run accumulator) andlangfuse_run_attrs(session_id/user_id for the run).record_run_token_usage(...)(thread-safe via a lock, becausethread_pool_execcopies the context into worker threads that share the sink dict) andusage_from_response(...)which extracts a{prompt_tokens, completion_tokens, total_tokens}split from OpenAI/OpenRouter-style responses.2. Provider layer captures the prompt/completion split (
rag/llm/chat_model.py)LiteLLMBaseandBasenow storeself.last_usage(prompt/completion/total) for the most recent chat call, in both the plain and tool-calling paths.stream_options.include_usage = True(LiteLLM path) so the authoritative usage arrives on the final chunk; this is read even on the usage-only chunk that carries nochoices.*_with_tools: token totals were overwritten by each round (total_tokens = tol) instead of accumulated, undercounting multi-round tool conversations. Each round is now committed to a running aggregate.3. LLMBundle reports usage once, per call (
api/db/services/llm_service.py)_report_usage(total_tokens)records the call's usage into the active run sink and returns the prompt/completion/total split for Langfuse. The split is only used when it is consistent with the authoritative total; otherwise only the total is reported.async_chat,async_chat_streamly,async_chat_streamly_delta) now emitusage_detailswithinput/output/totalinstead of total-only._start_langfuse_observationnow appliessession_id/user_idfrom the per-run context (langfuse_run_attrs) so agent-run generations are correctly grouped, even though agent LLMBundles are constructed without those attributes.4. Canvas installs the sink and emits the aggregate (
agent/canvas.py)Canvas.run()installs a freshtoken_usage_sinkandlangfuse_run_attrs(fromuser_id/session_id) at the start of every turn.message_endnow includes an aggregatedusageobject:{prompt_tokens, completion_tokens, total_tokens, calls}covering all LLM calls in the run.5. Pass session id into the run (
api/db/services/canvas_service.py)completion()forwardssession_idtoCanvas.run()for Langfuse session correlation.Why a context variable
LLM calls in an agent run originate from many places that each build their own
LLMBundle(e.g.cross_languages/keyword_extractionhelpers, the Agent component, and nested sub-agents invoked as tools). A run-scoped context variable is the only non-invasive chokepoint that captures all of them exactly once, including nested agents (which run in the same async context) and thread-pool tools (the executor copies the context).Behavior / compatibility
message_endgains an additional optionalusagefield; existing consumers are unaffected.Pipeline, syncGraph.run) are untouched.Testing
message_end.usage.total_tokensmatches provider usage.