Skip to content

fix(billing): bill cache tokens on chat calls served over the Responses API - #296

Merged
Yuchengw merged 2 commits into
mainfrom
fix/responses-conversion-cache-billing
Nov 18, 2026
Merged

Yuchengw merged 2 commits into
mainfrom
fix/responses-conversion-cache-billing

Conversation

@Yuchengw

Copy link
Copy Markdown

⚠️ 提交说明 / PR Notice

AI-assisted: written by an agent session (Claude) for the operator. The fix itself is upstream's, taken verbatim.

📝 变更描述 / Description

The defect. When global.chat_completions_to_responses_policy serves a /v1/chat/completions call over the Responses API, the converted usage carries a billing snapshot of the raw Responses usage. That snapshot holds the cache counts under input_tokens_details. Settlement (usageFromOpenAIBillingUsage) prefers the snapshot and reads only prompt_tokens_details, so cached and cache-write tokens were billed as fresh input.

Production evidence: channel 189 (gpt-6-astra, policy on since 2026-11-16) logged 0 cached and 0 cache-write tokens on 117 converted calls, against 88% cache reads on the same channel the week before. All 117 are one internal account; roughly $8 overbilled.

The fix. Cherry-pick of upstream QuantumNous/new-api QuantumNous#6892 (f11641428, -x), unmodified: 23 lines in service/billing_usage.go that fill prompt_tokens_details from input_tokens_details (and from prompt_cache_hit_tokens) only where the canonical field is zero. Taken verbatim so the next upstream merge carries no conflict.

What number moves, and for whom. Only calls whose billing snapshot is OpenAI-shaped, i.e. format-converted calls:

  • cache reads on a converted call: billed at the cache price instead of the input price (down);
  • cache writes on a converted call: billed at the write price (1.25x input) instead of 1x (up, and it is what the supplier charges us);
  • a chat-shaped snapshot that reports only prompt_cache_hit_tokens: now billed as a cache read (down);
  • no cache, native /v1/chat/completions, native /v1/responses, Claude and Gemini snapshots: unchanged.

No price, ratio, discount or catalogue row is touched.

Why code and not configuration. gpt-6.2-sol / gpt-6.2-astra answer 400 to every tool-bearing chat-completions call ("use /v1/responses"). Checked: param_override cannot help (the models reject reasoning_effort: "none", the Luna workaround); the Responses policy is the configuration answer, and it is this bug that makes it unsafe to switch on. After this ships, enabling the policy for channels 225/226 is a configuration change.

Existing test file changed (service/text_quota_test.go, three test functions added by the upstream commit; no existing assertion is edited or removed):

  1. Why it must change: upstream put its regression tests in that file; moving them would make the next upstream merge define the same functions twice.
  2. What it asserts afterwards that it does not today: Responses-shaped snapshots settle cache reads/writes; canonical values are not overwritten; prompt_cache_hit_tokens is honoured.
  3. What regression it could let through: none; additions only.

New file service/unifyapi_responses_conversion_cache_billing_test.go drives the real producer into the production gpt-6.2-sol expression with hand-typed quotas (7,550 / 248,750 / 12,500).

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix)

🔗 关联任务 / Related Issue

✅ 提交前检查项 / Checklist

  • 变更理解: traced producer (relaykit UsageFromResponsesUsage) → snapshot → effectiveBillingUsage → BuildTieredTokenParams; stream, buffered-stream and non-stream handlers share that producer.
  • 范围聚焦: two files from upstream plus one new test file.
  • 本地验证: see below.
  • 安全合规

📸 运行证明 / Proof of Work

go test ./service/... ./relay/... ./pkg/billingexpr/... ./setting/... -count=1   -> all ok
mutation (billing_usage.go reverted to main):
  --- FAIL: TestConvertedResponsesUsageBillsCacheAtCachePrices/standard_tier      expected: 6000  actual: 0
  --- FAIL: TestConvertedResponsesUsageBillsCacheAtCachePrices/long_context_tier  expected: 200000 actual: 0

For the release (staging): exercise a policy-converted chat call with cache against a fake Responses upstream on the exact image: input 10000 / cached 6000 / cache_write 3000 / output 500 on the gpt-6.2-sol expression must bill 7,550 quota at group ratio 1 (12,500 before), stream and non-stream; a native chat call and a native /v1/responses call with the same usage must bill the same before and after. No migration, seed, option or env var.

🤖 Generated with Claude Code

LiaoQi98 and others added 2 commits November 18, 2026 09:28
…nses API

The cherry-picked upstream fix (QuantumNous#6892) makes settlement read the cache counts
a Responses upstream reports under input_tokens_details. This test drives the
real producer (relayconvert.UsageFromResponsesUsage) into the gpt-6.2-sol
expression production carries and checks hand-typed quotas for the standard
tier, the 272K long-context tier and a cache-free call.

Why: the conversion is what lets gpt-6.2 take tools on /v1/chat/completions,
and it was left off for those models because it billed cached and cache-write
tokens at the full input price (117 converted gpt-6-astra calls in production
logged 0 cached tokens). The test fails on the pre-fix source with
"expected 6000, actual 0".

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@Yuchengw

Copy link
Copy Markdown
Author

APPROVED-TEST-CHANGE 1b5ccdf -- agent self-approval (operator rule 2026-11-18): service/text_quota_test.go only gains three test functions from upstream QuantumNous#6892; no existing assertion is edited or removed.

@Yuchengw
Yuchengw merged commit 669f9d3 into main Nov 18, 2026
8 checks passed
Yuchengw added a commit that referenced this pull request Nov 18, 2026
…ep their system prompt cacheable (#297)

gpt-6.2-sol and gpt-6.2-astra refuse function tools on
/v1/chat/completions ("use /v1/responses"). The chat-to-Responses policy is
the way to serve those calls, and with #296 it bills cache correctly. Turning
it on for 6.2 in production showed two more reasons it could not stay on:

1. The policy converts every matching call. A plain chat call already works
   natively; converting it gains nothing and loses whatever the Responses API
   has no field for (stop, n, logprobs, the penalties).
2. The conversion lifts system messages into `instructions`, and gpt-6.2
   never caches `instructions`: four identical 8.7K-token prompts in a row
   reported no cache write and no cache read, against a write then reads for
   the same text sent as a leading developer message. gpt-6-astra caches
   both. Measured against the supplier directly on 2026-11-18. A converted
   call paid the full input price for a prompt native chat bills at a tenth.

Two options on the policy row, both false by default so upstream's behaviour
is unchanged until a row asks for them:

- only_with_tools: a matching call that carries no tools stays native.
- instructions_as_input: a converted call sends its system prompt as the
  first input message (role developer) instead of `instructions`.

The logic lives in two new files; the upstream files gain one struct field
pair and three one-line hooks, each marked UNIFYAPI-FORK.

Configuration was checked first: param_override runs on the chat body before
conversion, so it cannot reach `instructions`, and nothing in the policy can
see the request body.

Verified with a local build against a fake upstream, production's own
billing rows and the policy set to both options: 16 billed cases exact;
plain gpt-6.2 chat reached /v1/chat/completions, tool calls reached
/v1/responses with input[0].role=developer and no instructions.

Co-authored-by: Claude Fable 5.2 <[email protected]>
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