Skip to content

fix: prevent double-counting of image count n in billing - #3512

Merged
Calcium-Ion merged 2 commits into
QuantumNous:mainfrom
imlhb:patch-2
Apr 1, 2026
Merged

Calcium-Ion merged 2 commits into
QuantumNous:mainfrom
imlhb:patch-2

Conversation

@imlhb

@imlhb imlhb commented Mar 31, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fix double-counting of image count n in billing for channels that set OtherRatio("n") (e.g. Ali/Bailian qwen-image-2.0 series).

Problem

The image count n was applied twice in quota calculation:

  1. ImagePriceRatio in GetTokenCountMeta() included n, which multiplied modelPrice by n in ModelPriceHelper (price billing), and promptTokens was set to n in ImageHelper (ratio billing).
  2. Channel adaptors (e.g. Ali) added OtherRatio("n"), which multiplied the quota again in calculateTextQuotaSummary.

This resulted in n² billing instead of n. For example with n=3 and base price $0.2:

  • Before: model price = $0.2 × 3 = $0.6, then × OtherRatio(3) → charged 9× base
  • After: model price = $0.2, then × OtherRatio(3) → charged 3× base ✓

Changes

  • dto/openai_image.go: Remove n from ImagePriceRatio in GetTokenCountMeta(). Keep only sizeRatio * qualityRatio (DALL-E size/quality adjustments).
  • relay/image_handler.go: Set fallback tokens to 1 (base unit) instead of imageN. Add default OtherRatio("n", imageN) only when the adaptor hasn't already set one — ensures n is applied exactly once across all billing paths.
  • relay/channel/ali/image.go: Keep AddOtherRatio("n") intact (minor comment cleanup only). The Ali adaptor uses actual upstream parameters/response count, which prevents billing evasion via extra["parameters"].

Test plan

  • Test Ali/Bailian qwen-image-2.0 with n=3: verify model price shows base price (e.g. $0.2), not $0.2 × n
  • Test DALL-E models with various sizes/qualities/n: verify billing unchanged
  • Test Ali image with n specified via extra["parameters"]: verify billing uses actual parameter count
  • Test ratio-based billing path for image models: verify n applied once

Summary by CodeRabbit

  • Bug Fixes

    • Corrected image pricing so multiple-image requests are counted once without double-counting.
    • Improved token usage reporting for image generation by decoupling token defaults from image count.
  • Refactor

    • Consolidated pricing/quota logic to ensure image count is applied reliably and only when not already provided.

Comment out code that modifies price data based on image count.
测试发现,如果是接入阿里百炼平台的qwen-image-2.0系列模型,这边计费的时候会出现 0.2*n*倍率*n的情况,最前面的0.2*n会直接显示为模型价格。
例如:
日志详情	模型价格 $0.600000,专属倍率 0.3
其他详情	大小 1080*1920, 品质 standard, 生成数量 3, 其他倍率 n: 3.000000
计费过程	模型价格:$0.600000 * 专属倍率:0.3 = $0.180000
@coderabbitai

coderabbitai Bot commented Mar 31, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: c1614142-f639-48dc-a227-f029db46c4df

📥 Commits

Reviewing files that changed from the base of the PR and between e299f4d and ab99c30.

📒 Files selected for processing (3)
  • dto/openai_image.go
  • relay/channel/ali/image.go
  • relay/image_handler.go
💤 Files with no reviewable changes (1)
  • relay/channel/ali/image.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • dto/openai_image.go
  • relay/image_handler.go

Walkthrough

Image billing logic was adjusted so image count n is applied exactly once: ImagePriceRatio no longer multiplies by n; the image handler adds OtherRatio("n") only if absent and defaults missing token usage fields to 1. Ali channel received comment-only cleanup.

Changes

Cohort / File(s) Summary
Ali channel: minor cleanup
relay/channel/ali/image.go
Removed two explanatory comments around existing OtherRatio("n", ...) pricing-ratio logic; no functional change.
Image DTO: price ratio calc
dto/openai_image.go
ImageRequest.GetTokenCountMeta() no longer multiplies ImagePriceRatio by n; ratio now computed as sizeRatio * qualityRatio only.
Image handler: quota & fallback tokens
relay/image_handler.go
Adds OtherRatio("n") only when missing to avoid double-counting; when usage token fields are zero, defaults TotalTokens and PromptTokens to 1 instead of imageN.

Sequence Diagram(s)

sequenceDiagram
    rect rgba(200,220,255,0.5)
    Client->>ImageHandler: Send image request (n, size, quality)
    end
    rect rgba(220,255,200,0.5)
    ImageHandler->>AliAdapter: Forward/convert request (adapter may provide usage.n)
    AliAdapter->>ImageHandler: Return response (usage.imageCount or data length)
    end
    rect rgba(255,230,200,0.5)
    ImageHandler->>DTO: Call GetTokenCountMeta() -> compute sizeRatio * qualityRatio (no n)
    ImageHandler->>PriceData: Ensure OtherRatio("n") present (set only if missing)
    PriceData->>QuotaCalculator: Compute final quota/price (applies OtherRatios including n once)
    end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I nibbled counts and hopped about,
One little n now stands without a doubt.
No double-hop, no extra spin—
Just tidy math and carrots to win! 🥕📸

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix: prevent double-counting of image count n in billing' directly and specifically describes the main change—resolving a billing calculation bug where image count was multiplied twice. It accurately reflects the core issue being fixed.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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 and usage tips.

@imlhb

imlhb commented Mar 31, 2026

Copy link
Copy Markdown
Contributor Author
image

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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@relay/channel/ali/image.go`:
- Around line 58-60: The per-image multiplier `n` was removed from both request-
and response-side updates so PriceData.OtherRatios no longer records image
count; restore a single source-of-truth for `n` by ensuring exactly one
AddOtherRatio("n", ...) call is executed (either when reading
imageRequest.Parameters.N in the request path or when computing results in the
response path) and remove the duplicate commented write, or make both paths
explicitly overwrite the same key via info.PriceData.AddOtherRatio("n",
float64(imageRequest.Parameters.N)) / info.PriceData.AddOtherRatio("n",
float64(result.N)) so quota code (relay_task.go and service/text_quota.go) sees
the correct multiplier. Ensure you reference and update the AddOtherRatio call
used in the functions handling imageRequest and response/result in image.go so
`OtherRatios["n"]` is always set once with the correct value.
🪄 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: 041a4c10-2d53-4283-ab5b-37e00e5287f7

📥 Commits

Reviewing files that changed from the base of the PR and between 5238f27 and 53aeee4.

📒 Files selected for processing (1)
  • relay/channel/ali/image.go

Comment thread relay/channel/ali/image.go Resolved
@Calcium-Ion

Copy link
Copy Markdown
Member

不应该直接注释,这样会有逃费的风险,应当在注入图片数量相关的参数的时候,先检测一次是否已经注入过

@imlhb

imlhb commented Mar 31, 2026

Copy link
Copy Markdown
Contributor Author

@Calcium-Ion 这个应该怎么检测呢,目前的确是有重复乘次数的问题,而且也是客户发现计费不对,因为目前0.20.5倍率的图,出5张图,本应该是0.5元,最终客户被扣费0.250.55=2.5元,目前这是接的qwen-image-2.0 ,我看到这个应该之前是接入z-image,这个我没去测试这个模型有没有问题,不过qwen-image-2.0的确会出现这个问题

@imlhb

imlhb commented Mar 31, 2026

Copy link
Copy Markdown
Contributor Author

@Calcium-Ion 目前这我发现 情况是模型价格提前就*n了,这边我请求体是:

{
  "model": "qwen-image-2.0", // 还支持 qwen-image-max、qwen-image-plus
  "prompt": "生成一只可爱的猫咪",
  "size": "1024*1024", // qwen-image-2.0系列模型:输出图像总像素需在512*512至2048*2048之间,默认分辨率为1024*1024。
  "n": 2 // 输出图像的数量,默认值为1。对于qwen-image-2.0系列模型,可选择输出1-6张图片。 实际价格 = 单图价格 x  数量
}

测试可以请求,只是计费不对,我临时先注释掉img内部的n先用用

@Calcium-Ion Calcium-Ion changed the title Comment out price data adjustment logic fix: prevent double-counting of image count n in billing Mar 31, 2026
The previous commit commented out AddOtherRatio("n") in the Ali
adaptor to fix double-counting but this could cause billing evasion
when n is specified via extra["parameters"] instead of request.N.

Root cause: ImagePriceRatio in GetTokenCountMeta() already included
n, AND channel adaptors added OtherRatio("n"), resulting in n²
billing.

Proper fix:
- Remove n from ImagePriceRatio (keep sizeRatio * qualityRatio only)
- In ImageHelper, add default OtherRatio("n") when adaptor hasn't
  set one; set fallback tokens to 1 (base unit)
- Restore Ali adaptor's AddOtherRatio("n") — it uses actual upstream
  parameters/response count, preventing billing evasion
@Calcium-Ion

Copy link
Copy Markdown
Member

我在你的修改上完善了一下,可以试试是否符合预期

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

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@relay/image_handler.go`:
- Around line 121-127: The code sets info.PriceData.AddOtherRatio("n",
float64(imageN)) even when imageN (derived from request.N) can be 0, which
yields a zero billing multiplier; change the guard so you only set the "n"
OtherRatio when imageN > 0 (or substitute a safe minimum like 1) — update the
conditional around info.PriceData.AddOtherRatio("n", ...) that checks
info.PriceData.OtherRatios and uses the imageN variable so adapters that didn’t
set "n" don’t introduce a zero multiplier.
🪄 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: 75b43b83-7814-479f-aeff-035ddfd5df46

📥 Commits

Reviewing files that changed from the base of the PR and between 53aeee4 and e299f4d.

📒 Files selected for processing (3)
  • dto/openai_image.go
  • relay/channel/ali/image.go
  • relay/image_handler.go
💤 Files with no reviewable changes (1)
  • relay/channel/ali/image.go

Comment thread relay/image_handler.go Resolved
@Calcium-Ion
Calcium-Ion merged commit 89fe99f into QuantumNous:main Apr 1, 2026
VeryGoodUser1 pushed a commit to xmz-ai/new-api that referenced this pull request Apr 3, 2026
fix: prevent double-counting of image count n in billing
salem-2007 added a commit to salem-2007/new-api that referenced this pull request Sep 10, 2026
fix: prevent double-counting of image count n in billing
junjundesk pushed a commit to junjundesk/new-api that referenced this pull request Oct 3, 2026
fix: prevent double-counting of image count n in billing
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