Skip to content

feat: enhance token usage details for upstream OpenRouter - #1120

Merged
Calcium-Ion merged 10 commits into
QuantumNous:alphafrom
neotf:feat-04
Jun 21, 2025
Merged

feat: enhance token usage details for upstream OpenRouter#1120
Calcium-Ion merged 10 commits into
QuantumNous:alphafrom
neotf:feat-04

Conversation

@neotf

@neotf neotf commented May 28, 2025

Copy link
Copy Markdown
Contributor

Enhanced OpenRouter token usage details.

Reference

Summary by CodeRabbit

  • New Features
    • Added support for tracking and including additional usage and cost details in AI request and response data.
    • Enhanced usage statistics with new fields for cached creation and read tokens.
  • Bug Fixes
    • Improved accuracy in calculating cached creation tokens for certain channel types.
  • Chores
    • Updated internal logic to better handle usage data and quota calculations.

@coderabbitai

coderabbitai Bot commented Jun 18, 2025

Copy link
Copy Markdown
Contributor

"""

Walkthrough

The changes introduce new fields to OpenAI request and response data structures for enhanced usage and cost tracking, update request adaptation logic for OpenRouter channels, refine usage statistics handling in Claude conversion, and add a function for recalculating cached creation tokens based on cost in quota management.

Changes

File(s) Change Summary
dto/openai_request.go Added Usage json.RawMessage field to GeneralOpenAIRequest struct.
dto/openai_response.go Added Cost float64 field to Usage struct.
relay/channel/openai/adaptor.go Set Usage field to {"include": true} for OpenRouter channel type in ConvertOpenAIRequest.
service/convert.go Improved usage handling in StreamResponseOpenAI2Claude; added fields for cache token tracking.
service/quota.go Adjusted cached token calculation for OpenRouter in PostClaudeConsumeQuota; added CalcOpenRouterCacheCreateTokens function.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Adaptor
    participant Service
    participant QuotaManager

    Client->>Adaptor: Send OpenAI request (OpenRouter channel)
    Adaptor->>Adaptor: Set Usage = {"include": true}
    Adaptor->>Service: Forward adapted request
    Service->>Service: Process response, update usage stats
    Service->>QuotaManager: Call PostClaudeConsumeQuota with usage/cost info
    QuotaManager->>QuotaManager: If OpenRouter, recalculate cached tokens using cost
Loading

Poem

🐇
A nibble here, a token there,
Now with cost, we’re well aware!
Usage fields, new stats in tow,
OpenRouter’s numbers grow.
Cache and quota, finely spun—
Hopping forward, work well done!

"""


📜 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 2ac0dda and 16c63b3.

📒 Files selected for processing (1)
  • service/quota.go (3 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • service/quota.go
✨ Finishing Touches
  • 📝 Generate Docstrings

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

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

🧹 Nitpick comments (2)
dto/openai_response.go (1)

181-183: Expose negative-cost guard / doc comment?

Cost may be zero or even negative when upstream returns unexpected data. Down-stream math (e.g. CalcOpenRouterCacheCreateTokens) currently assumes a non-negative value.
Recommend clamping to >=0 or documenting the expected range at the struct site.

relay/channel/openai/adaptor.go (1)

162-164: Minor readability: use raw string literal.

Back-ticks avoid the noisy escape sequences.

-    request.Usage = json.RawMessage("{\"include\": true}")
+    request.Usage = json.RawMessage(`{"include":true}`)
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 0b9b21e and 81bc096.

📒 Files selected for processing (5)
  • dto/openai_request.go (1 hunks)
  • dto/openai_response.go (1 hunks)
  • relay/channel/openai/adaptor.go (1 hunks)
  • service/convert.go (1 hunks)
  • service/quota.go (3 hunks)
🔇 Additional comments (2)
dto/openai_request.go (1)

59-60: Looks good – new field integrates cleanly.

No functional concerns. The new Usage field is correctly typed as json.RawMessage and keeps the struct backward-compatible via omitempty.

service/convert.go (1)

279-288: Nil-safety handled – good update.

The extra guard around oaiUsage prevents a latent nil-pointer panic and the new cache fields align with dto.Usage.
LGTM.

Comment thread relay/channel/openai/adaptor.go
Comment thread service/quota.go Outdated
Comment thread service/quota.go
neotf and others added 3 commits June 18, 2025 15:29
use review's suggestion

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
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