Skip to content

fix(billing): honor OpenAI Responses tool_usage web search counts - #8511

Open
seefs001 wants to merge 1 commit into
mainfrom
fix/openai-responses-web-search-billing
Open

seefs001 wants to merge 1 commit into
mainfrom
fix/openai-responses-web-search-billing

Conversation

@seefs001

@seefs001 seefs001 commented Dec 1, 2026 •

Copy link
Copy Markdown
Collaborator

🔗 关联任务 / Related Issue

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix)
  • ✨ 新功能 (New feature)
  • ⚡ 性能优化 / 重构 (Refactor)
  • 📝 文档更新 (Documentation)

📝 变更描述 / Description

修复普通 OpenAI Responses 渠道在流式与非流式路径中将 open_page / find_in_page 及失败项误计为付费搜索、且未读取 tool_usage.web_search.num_requests 的问题:

  • relay/channel/openai/web_search.go、relay/channel/openai/adaptor.go:为非 Azure 的 OpenAI Responses 渠道接入 openAIResponsesToolUsage,优先按 tool_usage.web_search.num_requests(流式取终帧 response.tool_usage.web_search.num_requests)结算;使用线性时间零展开的原始 JSON 数字解析验证非负整数,超限时返回 MaxBillableToolCallCount + 1 以保留 service/text_quota.go 的超限告警与截断。Azure 继续保留 bing_web_search 逻辑。
  • relay/common/relay_info.go、relay/common/tool_usage.go、relay/channel/openai/relay_responses.go、service/responses_usage.go:新增 RelayInfo.WebSearchBillsSearchActionsOnly(由 openai.Adaptor.Init 对非 Azure Responses 渠道启用),缺回执回退按项计数时仅计入 completed/空状态且 search/空动作项,不改变 DeepSeek、Ali、xAI、Azure 的回退行为;同时将 web_search_2*(如 web_search_2025_08_26)归入 web_search 价格键而非 web_search_preview。

📸 运行证明 / Proof of Work

在 relay/channel/openai/relay_responses_billing_test.go 新增 23 组场景(45 个流式与非流式子测试),覆盖 1 search + 2 open_page 且 num_requests=1(按 1 次结算)、num_requests=0、无回执回退(忽略 open_page/find_in_page/failed/in_progress)、web_search_2025_08_26、极端科学计数(1e100000000、1e-100000000、9999.9999999999999、±1e-400)、Azure bing_web_search 与 DeepSeek 断流保留 open_page。

gofmt -l relay/common/relay_info.go relay/common/tool_usage.go relay/channel/openai/web_search.go relay/channel/openai/adaptor.go relay/channel/openai/relay_responses.go service/responses_usage.go relay/channel/openai/relay_responses_billing_test.go
# 无输出,exit 0

go vet ./relay/channel/openai
# 无输出,exit 0

go test -count=1 ./relay/channel/openai ./service ./relay/common ./relay/channel/deepseek ./relay/channel/ali ./relay/channel/xai
# ok github.com/QuantumNous/new-api/relay/channel/openai 0.688s (45/45 子测试通过)
# ok github.com/QuantumNous/new-api/service 14.184s
# ok github.com/QuantumNous/new-api/relay/common 0.287s
# ok github.com/QuantumNous/new-api/relay/channel/deepseek 0.667s
# ok github.com/QuantumNous/new-api/relay/channel/ali 0.673s

✅ 提交前检查项 / Checklist

  • 人工确认: 无论描述是否由 AI 生成,我已审阅并精炼全文,仅保留可复核的要点,并声明对其准确性与完整性负责。PR 正文及后续评论均未直接粘贴未经人工过滤的大段 AI 文本。
  • 非重复提交: 我已搜索现有的 Issues 与 PRs,确认不是重复提交。
  • 新功能关联 Issue: 本 PR 为 Bug 修复。
  • 事前沟通: 本 PR 为聚焦的计费 Bug 修复。
  • 功能范围: 本 PR 不是 Coding Plan、逆向渠道、第三方封装接口,也不是对 Codex 渠道类型的改动。
  • 非透传: 本 PR 不是针对开启透传后的转发行为;透传会直接发送内容,不会经过 new-api 的逻辑处理。
  • 范围聚焦: 本 PR 为一项聚焦改动,未包含无关代码。
  • 本地验证: 已按变更路径实际验证,并写明命令与观察结果。仅声明 go build 通过或测试通过,不视为有效证明。
  • 安全合规: 代码中无敏感凭据,且符合项目代码规范。

Summary by CodeRabbit

  • Bug Fixes
    • Improved web search usage billing across OpenAI Responses and Azure, using reported request counts when valid and falling back to eligible search actions when unavailable.
    • Corrected handling of completed search actions and supported tool-name variants, helping prevent inaccurate usage totals.
    • Improved billing consistency for streaming responses, including interrupted streams.

Read tool_usage.web_search.num_requests with exact zero-expansion JSON number parsing for non-Azure OpenAI Responses channels, bill dated web_search_2* versions under web_search, and limit per-item fallback counting on OpenAI channels to completed search actions without affecting DeepSeek/Ali/xAI/Azure fallbacks.

Closes #8507
@coderabbitai

coderabbitai Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

Responses web-search billing now uses valid tool_usage.web_search.num_requests counts when available. Otherwise, the relevant response paths count eligible web-search items. Channel setup selects the applicable billing key and action-counting rules.

Changes

Responses web-search billing

Layer / File(s) Summary
Web-search billing rules
relay/common/relay_info.go, relay/common/tool_usage.go
RelayInfo adds a flag for action-based billing. Tool usage logic resolves the billing key from configuration or declared tool names and determines whether a web-search item is billable.
Channel setup and receipt mapping
relay/channel/openai/adaptor.go, relay/channel/openai/web_search.go
Responses channel setup configures web-search billing. Shared parsing accepts exact, nonnegative whole-number counts from supported usage paths. Azure maps valid counts to bing_web_search; OpenAI Responses maps them to the resolved web-search tool key.
Response counting and validation
relay/channel/openai/relay_responses.go, service/responses_usage.go, relay/channel/openai/relay_responses_billing_test.go
Non-streaming and streaming paths filter per-item web-search counts according to channel rules. Tests cover usage receipts, fallback counts, numeric edge cases, Azure billing, and interrupted DeepSeek streams.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant AdaptorInit
  participant RelayInfo
  participant OaiResponsesHandler
  participant ResponsesUsageAccumulator
  AdaptorInit->>RelayInfo: Configure Responses web-search billing
  OaiResponsesHandler->>RelayInfo: Check web-search item eligibility
  ResponsesUsageAccumulator->>RelayInfo: Check streamed web-search item eligibility
Loading

Possibly related issues

  • QuantumNous/new-api#6230 — This change adds Responses web-search usage parsing, but the issue also identifies xAI and Chat-path gaps that this PR does not address.

Possibly related PRs

  • QuantumNous/new-api#8510 — This PR changes the same OpenAI Responses web-search billing path and addresses the same overcounting case.

Suggested reviewers: calcium-ion

Merge Risk: Minimal · up to 05fc6

This change makes OpenAI Responses web-search billing use the upstream usage receipt when one is present. Without a receipt, it counts only completed search actions, which stops overcharging for open_page actions. Azure, DeepSeek, Ali and xAI keep their existing behaviour. I found no concrete merge-blocking risk in the reviewed changes.

Pre-merge checks: Passed 4

Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title names the main change: web-search billing for OpenAI Responses now uses the tool_usage.web_search.num_requests count. The summary shows this in web_search.go, relay_responses.go, and tool_us…
Linked Issues check Passed [#8507] Objective: for a non-streaming OpenAI Responses reply with one search, two open_page actions and tool_usage.web_search.num_requests=1, bill one search (5,000 tool quota plus 100 token quota). …
Out of Scope Changes check Passed All changes are in the web-search billing path for OpenAI Responses. adaptor.go wires the hook and flag for non-Azure Responses channels. relay_responses.go and service/responses_usage.go apply the pe…
Full details: Title check

Explanation

The title names the main change: web-search billing for OpenAI Responses now uses the tool_usage.web_search.num_requests count. The summary shows this in web_search.go, relay_responses.go, and tool_usage.go. The fix(billing) prefix fits the billing-correction scope of the PR.

Full details: Linked Issues check

Explanation

[#8507] Objective: for a non-streaming OpenAI Responses reply with one search, two open_page actions and tool_usage.web_search.num_requests=1, bill one search (5,000 tool quota plus 100 token quota). Evidence at head: relay/channel/openai/adaptor.go Init now sets info.VendorToolUsage = openAIResponsesToolUsage(info) for non-Azure Responses mode. That function reads tool_usage.web_search.num_requests through responsesWebSearchRequests and bills it under info.WebSearchToolKey(). relay_responses.go counts a web_search_call only when info.IsBillableWebSearchCall returns true. With WebSearchBillsSearchActionsOnly set, open_page items are excluded from item counting, and the receipt count replaces item counting when present. Result for the issue fixture: one web-search count, so 5,000 tool quota plus 100 token quota. Streaming path: the same hook is used for the terminal frame's response.tool_usage. Tests reported in the PR cover these cases in relay_responses_billing_test.go. Not directly verified: the settlement code that consumes VendorToolUsage (it is the mechanism already used by Azure), and the test run output. The issue's example is therefore addressed by the code path. Related issue #7889 is context only.

Full details: Out of Scope Changes check

Explanation

All changes are in the web-search billing path for OpenAI Responses. adaptor.go wires the hook and flag for non-Azure Responses channels. relay_responses.go and service/responses_usage.go apply the per-item filter. web_search.go adds the receipt parser, which is shared with Azure. relay_info.go and tool_usage.go add the flag, the key resolution and the predicate. The tests cover the behavior. The PR-only additions are the strict JSON-number parser (exponents, fractions and negatives), the mapping of web_search_2* dated keys to the web_search price key, and the fallback restriction to completed or empty-status search or empty-action items. These are part of the same billing computation for the same tool, so they are connected to the objective. They are not unrelated. The DeepSeek, Ali and xAI fallback is stated as unchanged, and the diff shows the new flag applies only to the OpenAI adaptor path. No unrelated files appear in the summary.

Finishing Touches

Generate unit tests (beta)

  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

A rabbit checks the search receipt,
One counted request makes billing neat.
Open pages pass without a fee,
The tool key finds its proper tree.
Then hops away, quite satisfied.

Recent review info

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 377166de-1638-4dc9-8e13-99cfaf2ea22e
Commits

Reviewing files that changed from the base of the PR and between 04dfcbb and 05fc668.

Files selected for processing: 7

  • relay/channel/openai/adaptor.go
  • relay/channel/openai/relay_responses.go
  • relay/channel/openai/relay_responses_billing_test.go
  • relay/channel/openai/web_search.go
  • relay/common/relay_info.go
  • relay/common/tool_usage.go
  • service/responses_usage.go

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.

This branch has not been deployed

No deployments
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.

[Bug] 普通 OpenAI Responses 将 open_page 算作付费搜索,回执 1 次实际扣 3 次

1 participant