Skip to content

fix: token usage tracking in AI models and UI components - #710

Merged
lixun910 merged 3 commits into
mainfrom
xli-fix-token-usage
Jun 23, 2026
Merged

lixun910 merged 3 commits into
mainfrom
xli-fix-token-usage

Conversation

@lixun910

@lixun910 lixun910 commented Jun 11, 2026 •

Copy link
Copy Markdown
Collaborator

improves the accuracy and consistency of token usage tracking and reporting across the AI agent framework and UI

  • ensuring that token usage information is reliably included in all relevant API calls
  • use estimateMessageTokens if provider doesn't return actual token usage
  • refining how token usage is calculated and displayed in the UI
  • updating the internal data structures to support more precise token usage
  • Removed the unused onFinish callback from the agent creation options in createLocalChatTransportFactory, as token usage is now handled centrally.

Summary by CodeRabbit

  • New Features
    • Enabled token usage tracking for OpenAI-compatible model interactions, allowing responses to expose usage details.
    • Enhanced the token usage indicator to display both context tokens (for the next-turn window) and cumulative tokens (total consumption).
    • Improved token accounting accuracy by preferring final session usage when available and updating context/token estimates using the most recent step’s input tokens, including refined tooltip and total-consumption messaging.

@coderabbitai

coderabbitai Bot commented Jun 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 4e24c3ab-f479-47ad-bea0-ecdb86e309a7

📥 Commits

Reviewing files that changed from the base of the PR and between 4659889 and 1fdbe59.

📒 Files selected for processing (2)
  • packages/ai-core/src/chatTransport.ts
  • packages/ai-core/src/components/ContextUsageIndicator.tsx
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/ai-core/src/chatTransport.ts
  • packages/ai-core/src/components/ContextUsageIndicator.tsx

📝 Walkthrough

Walkthrough

This PR enables token usage tracking across model clients and refactors how token usage is persisted and displayed. It introduces lastStepInputTokens to track the most recent step's input tokens, shifts session token tracking from onFinish callbacks to streaming metadata handlers, and updates the usage indicator component to distinguish between context-window fill and cumulative token consumption across conversation turns.

Changes

Token Usage Tracking and Display

Layer / File(s) Summary
Token usage type extension
packages/ai-core/src/types.ts
MessageTokenUsage gains optional lastStepInputTokens?: number field to capture input tokens from the most recent step.
Enable usage collection in model clients
apps/sqlrooms-cli-ui/src/createDashboardAgent.ts, examples/ai-agent/src/skills/getModel.ts, examples/ai-nextjs/src/app/api/chat/route.ts, examples/ai-subagents/src/agents/TravelPlannerAgent.ts, packages/ai-core/src/AiSlice.ts, packages/ai-core/src/chatTransport.ts
Set includeUsage: true in createOpenAICompatible configurations across dashboard agent, example skills, Next.js route, subagent, sendPrompt path, and local chat transport factory.
Refactor session token tracking to streaming metadata
packages/ai-core/src/chatTransport.ts
Remove ToolLoopAgent onFinish callback; track lastStepInputTokens during finish-step events; compute and store final usage from finish event (preferring totalUsage over accumulated per-step) in streaming messageMetadata handler.
Update usage indicator to show context vs cumulative tokens
packages/ai-core/src/components/ContextUsageIndicator.tsx
Implement computeTokenUsage to derive contextTokens (context-window fill) and cumulativeTokens (total across turns); estimate tokens per-message and system instructions as fallback; display contextTokens-based percentage with tooltip showing context usage and conditional cumulative line.

Sequence Diagram

sequenceDiagram
  participant ToolLoopAgent
  participant StreamHandler
  participant MessageMetadata
  ToolLoopAgent->>StreamHandler: emit finish-step event with inputTokens
  StreamHandler->>StreamHandler: record inputTokens to lastStepInputTokens
  ToolLoopAgent->>StreamHandler: emit finish event with totalUsage
  StreamHandler->>MessageMetadata: compute final usage (prefer totalUsage)
  StreamHandler->>MessageMetadata: attach lastStepInputTokens
  MessageMetadata->>MessageMetadata: store in session token usage
Loading

Estimated Code Review Effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Suggested Reviewers

  • dmitriy-kostianetskiy
  • ilyabo

Poem

🐰 A rabbit hops through tokens bright,
Tracking context, left to right.
Usage flows through streams now clear,
Each step's whisper, crisp and dear.
Context window, now in sight! ✨

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.00% 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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix: token usage tracking in AI models and UI components' directly and accurately reflects the main changes across the PR, which involve enabling usage tracking via includeUsage: true across multiple files and refining token usage computation in UI components.
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.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch xli-fix-token-usage

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint install failed. For unrecoverable errors, disable the tool in CodeRabbit configuration.


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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4659889b41

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread packages/ai-core/src/components/ContextUsageIndicator.tsx

@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: 2

🤖 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 `@packages/ai-core/src/chatTransport.ts`:
- Around line 389-401: The finish branch only reads (part as {totalUsage?:
LanguageModelUsage}).totalUsage and ignores a possible (part as {usage?:
LanguageModelUsage}).usage payload, which can contain final usage when
totalUsage is missing; update the logic in chatTransport.ts around
toMessageTokenUsage/finishUsage so it checks both totalUsage and usage (e.g.,
prefer totalUsage, else use usage) before falling back to accumulatedUsage, then
set finalUsage.lastStepInputTokens and call rememberSessionTokenUsage(sessionId,
finalUsage) as before; reference toMessageTokenUsage, finishUsage,
accumulatedUsage, finalUsage, lastStepInputTokens, and rememberSessionTokenUsage
to locate the change.

In `@packages/ai-core/src/components/ContextUsageIndicator.tsx`:
- Around line 71-104: The loop currently mixes reported assistant tokenUsage
with per-message estimates, inflating cumulativeTokens; change the logic so
reported usage and fallback estimates are mutually exclusive: when an assistant
message has metadata.tokenUsage (reported.totalTokens), add only
reported.totalTokens to cumulativeTokens and set lastContextTokens from
reported.lastStepInputTokens/inputTokens as before, and set
hasAnyReportedUsage=true; when hasAnyReportedUsage is true, do NOT call
estimateMessageTokens for any other messages (skip estimating user/assistant
messages without usage); only when no reported usage at all fall back to
estimating every message and include systemInstructions via
estimateTokenCount(systemInstructions). Ensure contextTokens uses
lastContextTokens when hasAnyReportedUsage, otherwise uses cumulativeTokens.
🪄 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: defaults

Review profile: CHILL

Plan: Pro

Run ID: c4fad06d-7318-44a7-bcf8-9c7052fe1b2e

📥 Commits

Reviewing files that changed from the base of the PR and between b790206 and 4659889.

📒 Files selected for processing (8)
  • apps/sqlrooms-cli-ui/src/createDashboardAgent.ts
  • examples/ai-agent/src/skills/getModel.ts
  • examples/ai-nextjs/src/app/api/chat/route.ts
  • examples/ai-subagents/src/agents/TravelPlannerAgent.ts
  • packages/ai-core/src/AiSlice.ts
  • packages/ai-core/src/chatTransport.ts
  • packages/ai-core/src/components/ContextUsageIndicator.tsx
  • packages/ai-core/src/types.ts

Comment thread packages/ai-core/src/chatTransport.ts
Comment thread packages/ai-core/src/components/ContextUsageIndicator.tsx
@lixun910
lixun910 merged commit d3db72d into main Jun 23, 2026
6 checks passed
@lixun910
lixun910 deleted the xli-fix-token-usage branch June 23, 2026 23:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants