Skip to content

Conversation

roomote[bot]
Copy link

@roomote roomote bot commented Oct 14, 2025

Related GitHub Issue

Closes: #8650

Roo Code Task Context (Optional)

This PR was created with assistance from Roo Code.

Description

This PR fixes the cost miscalculation issue when using Claude 3.5 Sonnet (and other models) through OpenRouter. The issue occurred because OpenRouter's API was returning incorrect cost values in the usage response.

Key implementation details:

  • Modified the OpenRouter handler to calculate costs locally using model pricing information instead of relying solely on the API response
  • Added fallback logic to use API-provided costs when model pricing information is unavailable
  • Uses the existing calculateApiCostOpenAI utility function for consistent cost calculation across the codebase

What reviewers should pay attention to:

  • The cost calculation logic in src/api/providers/openrouter.ts lines 199-226
  • The new test case that validates the fix for the reported scenario (527k input tokens showing /bin/sh.46 instead of ~.50+)

Test Procedure

How I tested:

  1. Added a specific test case that reproduces the exact issue reported (527k input tokens, 7.7k output tokens)
  2. Verified that the local calculation produces the correct cost (.6965) instead of the incorrect API value (/bin/sh.46)
  3. Ran all existing OpenRouter tests to ensure no regression
  4. All tests pass successfully

How reviewers can verify:

  1. Run the OpenRouter tests: cd src && npx vitest run api/providers/__tests__/openrouter.spec.ts
  2. Check the specific test case "calculates cost locally when OpenRouter API returns incorrect cost (issue [BUG] Cost miscalculation #8650)"
  3. The test validates that we calculate .6965 instead of using the incorrect /bin/sh.46 from the API

Pre-Submission Checklist

  • Issue Linked: This PR is linked to an approved GitHub Issue (see "Related GitHub Issue" above).
  • Scope: My changes are focused on the linked issue (one major feature/fix per PR).
  • Self-Review: I have performed a thorough self-review of my code.
  • Testing: New and/or updated tests have been added to cover my changes (if applicable).
  • Documentation Impact: I have considered if my changes require documentation updates (see "Documentation Updates" section below).
  • Contribution Guidelines: I have read and agree to the Contributor Guidelines.

Screenshots / Videos

Not applicable - this is a backend cost calculation fix with no UI changes.

Documentation Updates

  • No documentation updates are required.

The fix is transparent to users and doesn't change any APIs or user-facing behavior.

Additional Notes

This fix ensures that users see accurate cost calculations when using OpenRouter, particularly for high token count sessions. The fallback mechanism ensures backward compatibility if model pricing information is not available.

Get in Touch

Automated PR created via GitHub API


Important

Fix cost miscalculation in OpenRouterHandler by calculating costs locally using model pricing info and adding fallback to API costs.

  • Behavior:
    • Modify OpenRouterHandler in openrouter.ts to calculate costs locally using model pricing info.
    • Add fallback to API-provided costs if model pricing info is unavailable.
    • Use calculateApiCostOpenAI for consistent cost calculation.
  • Tests:
    • Add test case in openrouter.spec.ts to validate local cost calculation for 527k input tokens.
    • Ensure test case checks for correct cost (.6965) instead of incorrect API value (.46).
  • Misc:
    • Update cost calculation logic in createMessage() in openrouter.ts lines 199-226.

This description was created by Ellipsis for 1eecf1f. You can customize this summary. It will automatically update as commits are pushed.

- Calculate costs using model pricing info instead of relying on OpenRouter API response
- Fixes issue where OpenRouter returns incorrect cost values (e.g., $0.46 instead of $1.50+ for 527k tokens)
- Falls back to API cost if model pricing info is unavailable
- Added test case to verify fix for reported issue #8650
@roomote roomote bot requested review from cte, jr and mrubens as code owners October 14, 2025 09:08
@dosubot dosubot bot added size:M This PR changes 30-99 lines, ignoring generated files. bug Something isn't working labels Oct 14, 2025
// Use locally calculated cost, but fall back to API response if our calculation fails
// or if model pricing info is not available
const apiCost = (lastUsage.cost_details?.upstream_inference_cost || 0) + (lastUsage.cost || 0)
const totalCost = modelInfo.inputPrice && modelInfo.outputPrice ? localCost : apiCost
Copy link

Choose a reason for hiding this comment

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

Using modelInfo.inputPrice && modelInfo.outputPrice to decide whether to use locally calculated cost may misinterpret valid zero prices as missing. Consider checking explicitly for undefined/null (e.g. modelInfo.inputPrice != null && modelInfo.outputPrice != null) to ensure that a price of 0 isn’t treated as false.

Suggested change
const totalCost = modelInfo.inputPrice && modelInfo.outputPrice ? localCost : apiCost
const totalCost = modelInfo.inputPrice != null && modelInfo.outputPrice != null ? localCost : apiCost

// Use locally calculated cost, but fall back to API response if our calculation fails
// or if model pricing info is not available
const apiCost = (lastUsage.cost_details?.upstream_inference_cost || 0) + (lastUsage.cost || 0)
const totalCost = modelInfo.inputPrice && modelInfo.outputPrice ? localCost : apiCost
Copy link
Author

Choose a reason for hiding this comment

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

The truthy check here will incorrectly fall back to API cost when model prices are 0 (e.g., free tier models). If inputPrice or outputPrice is 0, the condition evaluates to false even though 0 is a valid price.

Suggested change
const totalCost = modelInfo.inputPrice && modelInfo.outputPrice ? localCost : apiCost
const totalCost = modelInfo.inputPrice !== undefined && modelInfo.outputPrice !== undefined ? localCost : apiCost

@hannesrudolph hannesrudolph added the Issue/PR - Triage New issue. Needs quick review to confirm validity and assign labels. label Oct 14, 2025
@roomote roomote bot mentioned this pull request Oct 14, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working Issue/PR - Triage New issue. Needs quick review to confirm validity and assign labels. size:M This PR changes 30-99 lines, ignoring generated files.

Projects

Status: Triage

Development

Successfully merging this pull request may close these issues.

[BUG] Cost miscalculation

2 participants