Skip to content

fix(chat): use estimateTokens helper for chat token calculation - #537

Merged
steebchen merged 2 commits into
mainfrom
cursor/use-estimatetokens-helper-for-chat-token-calculation-f120
Jul 28, 2025
Merged

steebchen merged 2 commits into
mainfrom
cursor/use-estimatetokens-helper-for-chat-token-calculation-f120

Conversation

@steebchen

@steebchen steebchen commented Jul 28, 2025

Copy link
Copy Markdown
Member

Replace manual token calculations with the estimateTokens helper function for consistent and accurate estimation.

Previously, some token estimations relied on a simple division by 4, which is less accurate and inconsistent with other parts of the codebase. This PR leverages the existing estimateTokens function, which uses proper tokenization and a more robust fallback strategy, ensuring a unified and more precise approach to token counting across the application.


Open in WebOpen in CursorOpen Docs

Summary by CodeRabbit

  • Refactor
    • Improved consistency and accuracy of token usage estimates across chat providers by centralizing token estimation logic.

Co-authored-by: contact <contact@polarlights.llc>
@coderabbitai

coderabbitai Bot commented Jul 28, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

This change refactors token count estimation in the chat module by replacing all manual and duplicated logic with calls to a centralized estimateTokens helper function. All previous direct encoding, length heuristics, and try-catch blocks for token estimation are removed, delegating token counting to the shared function for consistency.

Changes

Cohort / File(s) Change Summary
Token Estimation Refactor
apps/gateway/src/chat/chat.ts
Replaces all manual token estimation (encoding, length heuristics, try-catch) with calls to estimateTokens in all relevant locations; unifies logic for prompt and completion token calculation across providers.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~8 minutes

Possibly related PRs

Note

⚡️ Unit Test Generation is now available in beta!

Learn more here, or try it out under "Finishing Touches" below.


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8fd91fe and 9c28a5e.

📒 Files selected for processing (1)
  • apps/gateway/src/chat/chat.ts (5 hunks)
🧰 Additional context used
📓 Path-based instructions (4)
**/*.{js,jsx,ts,tsx}

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

Use localStorage instead of cookies for client-side data persistence

Files:

  • apps/gateway/src/chat/chat.ts
**/*.{js,ts}

📄 CodeRabbit Inference Engine (.github/copilot-instructions.md)

**/*.{js,ts}: Use drizzle with the latest object syntax for database operations
For read queries, always use db().query.<table>.findMany() or db().query.<table>.findFirst()

Files:

  • apps/gateway/src/chat/chat.ts
{apps/api,apps/gateway,packages/db}/**/*.ts

📄 CodeRabbit Inference Engine (CLAUDE.md)

{apps/api,apps/gateway,packages/db}/**/*.ts: Use Drizzle ORM with latest object syntax for database operations
For reads, use db().query.<table>.findMany() or db().query.<table>.findFirst()

Files:

  • apps/gateway/src/chat/chat.ts
**/*.{ts,tsx}

📄 CodeRabbit Inference Engine (.cursor/rules/general.mdc)

Never use as any or : any in TypeScript files.

Files:

  • apps/gateway/src/chat/chat.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: e2e / run
🔇 Additional comments (5)
apps/gateway/src/chat/chat.ts (5)

168-176: LGTM! Good refactoring to use centralized token estimation.

The replacement of manual token calculation with the estimateTokens helper function improves consistency and removes duplicated try-catch logic. The parameters are correctly set with an empty messages array since only completion tokens are being estimated from content.


362-370: LGTM! Consistent refactoring pattern.

This change maintains the same improvement as the previous segment, replacing manual token estimation with the centralized estimateTokens helper. The parameter usage is consistent and appropriate for estimating completion tokens from streaming content.


2099-2107: LGTM! Proper prompt token estimation.

The refactoring correctly uses estimateTokens to calculate prompt tokens from the messages array when streaming data indicates completion. The function call parameters and result extraction are appropriate for this use case.


2183-2191: LGTM! Consistent Anthropic provider token estimation.

The refactoring properly applies the centralized token estimation approach to Anthropic streaming usage data. The variable naming and parameter usage are clear and consistent with the overall refactoring pattern.


2301-2309: LGTM! Completes the token estimation refactoring.

This final replacement of manual token calculation with the estimateTokens helper completes the consistent refactoring throughout the streaming response handling. All token estimation logic is now centralized and unified across different providers and scenarios.

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch cursor/use-estimatetokens-helper-for-chat-token-calculation-f120

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@steebchen
steebchen marked this pull request as ready for review July 28, 2025 12:30
@steebchen steebchen changed the title Use estimateTokens helper for chat token calculation fix(chat): use estimateTokens helper for chat token calculation Jul 28, 2025
@steebchen
steebchen added this pull request to the merge queue Jul 28, 2025
github-merge-queue Bot pushed a commit that referenced this pull request Jul 28, 2025
Replace manual token calculations with the `estimateTokens` helper
function for consistent and accurate estimation.

Previously, some token estimations relied on a simple division by 4,
which is less accurate and inconsistent with other parts of the
codebase. This PR leverages the existing `estimateTokens` function,
which uses proper tokenization and a more robust fallback strategy,
ensuring a unified and more precise approach to token counting across
the application.

---

[Open in
Web](https://cursor.com/agents?id=bc-4bacdae3-19e8-4fc4-a58a-aef2e5e1a8e2)
• [Open in
Cursor](https://cursor.com/background-agent?bcId=bc-4bacdae3-19e8-4fc4-a58a-aef2e5e1a8e2)
• [Open Docs](https://docs.cursor.com/background-agent/web-and-mobile)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->

## Summary by CodeRabbit

* **Refactor**
* Improved consistency and accuracy of token usage estimates across chat
providers by centralizing token estimation logic.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Cursor Agent <cursoragent@cursor.com>
Co-authored-by: contact <contact@polarlights.llc>
@steebchen
steebchen removed this pull request from the merge queue due to a manual request Jul 28, 2025
@steebchen
steebchen merged commit eec7ca8 into main Jul 28, 2025
@steebchen
steebchen deleted the cursor/use-estimatetokens-helper-for-chat-token-calculation-f120 branch July 28, 2025 12:37
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