Skip to content

fix(claude): forward thinking.block_binding and every anthropic-beta value - #7732

Merged
seefs001 merged 1 commit into
QuantumNous:mainfrom
RedwindA:fix/claude-thinking-block-binding
Oct 12, 2026
Merged

seefs001 merged 1 commit into
QuantumNous:mainfrom
RedwindA:fix/claude-thinking-block-binding

Conversation

@RedwindA

@RedwindA RedwindA commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ 提交说明 / PR Notice

English template: .github/PULL_REQUEST_TEMPLATE/en.md

Important

  • 描述可用 AI 辅助。提交前请审阅并精炼全文,仅保留维护者需要复核的要点,并声明对其负责。PR 正文及后续评论均不得直接粘贴未经人工过滤的大段 AI 文本;多次提交此类内容可能会被 block。
  • 开启透传请勿反馈问题;透传会直接发送内容,不会经过 new-api 的逻辑处理。
  • 请按本模板填写后再提交。

🔗 关联任务 / Related Issue

  • Closes #

🚀 变更类型 / Type of change

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

📝 变更描述 / Description

问题:客户端(如 LibreChat)对 Opus 5.5 / Sonnet 5.5 / Fable 5.1 发送
thinking.block_binding.prefix_mismatch_behavior: "drop_block"(beta thinking-binding-controls-2026-08-01)。dto.Thinking 没有这个字段,重新序列化时它被丢掉了。上游因此按默认值 "error" 处理,客户端改了 system 或 tools 后,多轮对话会返回 400:Invalid signature in thinking block. The block is bound to a different conversation。

改动:

  • relaykit/dto/claude.go:Thinking 新增 BlockBinding(json.RawMessage,原样转发)。thinking 里还没定义的字段由自定义 (Un)MarshalJSON 保留并写回,Anthropic 以后再加字段也不会被丢掉。这个字段必须导出(json:"-"),因为 common.DeepCopy(copier)会跳过未导出字段。
  • relay/channel/claude/adaptor.go:
    • 模型带思考后缀时(如 claude-opus-5-5-high),model_modifier 会清空 thinking 再重建。重建结果仍为 adaptive 时,从原始请求补回 block_binding;其他类型(如 between_tools)不补。网关不会主动加这个字段。
    • anthropic-beta:客户端分多行发送时,合并为一行逗号分隔的值转发(原先只转发第一行)。
  • relay/channel/aws/dto.go:Bedrock 的 anthropic_beta 数组去掉多余空格和空项(原先 "a, b" 会变成 " b")。
  • Vertex 直接复用 *dto.Thinking,已被上面的改动覆盖。响应里的 input_transformations 在 Claude 格式下本来就原样转发,这次补了测试。

本 PR 由 AI 辅助编写(Claude Code),已经人工审阅。

📸 运行证明 / Proof of Work

单元测试

  • 新增测试:
    • TestConvertClaudeRequestForwardsThinkingBlockBinding:原生请求、-high 后缀、-none 后缀(变成 between_tools)、未带该字段,共 4 种情况。
    • TestSetupRequestHeaderForwardsEveryAnthropicBetaValue
    • TestClaudeResponsePassesInputTransformationsThrough:流式和非流式。
    • TestDoAwsClientRequest_ForwardsThinkingBlockBindingAndBetaList
  • 去掉修复后,"原生请求"和"后缀"两个用例会失败;加上修复后通过。
  • go test ./...(根模块)通过。cd relaykit && GOWORK=off go build ./... && GOWORK=off go test ./... 通过。
  • go test -race -count=5 ./relay/channel/aws/ ./relay/channel/claude/ 通过。

本地端到端

  • 用本分支编译 new-api,以 SQLite 方式在本机启动,建一个 Anthropic 渠道,上游指向抓包调试服务。经 /v1/messages 发出 5 组请求,history 里都回放了带 signature 的 thinking 块。
  • 抓到的上游请求:
请求 上游实际收到
claude-opus-5-5,thinking 带 display / block_binding / future_field,anthropic-beta 分两行发送 thinking 四个字段都在;Anthropic-Beta: fast-mode-2026-02-01,thinking-binding-controls-2026-08-01
同上,stream: true thinking 带 block_binding,beta 头原样
claude-opus-5-5-high model: claude-opus-5-5;thinking: {"type":"adaptive","display":"summarized","block_binding":{"prefix_mismatch_behavior":"drop_block"}};output_config.effort: "high"
claude-sonnet-5-5-none model: claude-sonnet-5-5;thinking: {"type":"between_tools"},不带 block_binding
claude-opus-5-5,不带 block_binding,不带 beta 头 不带 block_binding,不带 anthropic-beta

真实上游端到端(部署本分支,经 new-api 的 Anthropic 渠道调用 claude-opus-5-5;该账号受 preserved thinking 强制检查)

步骤:

  1. 第 1 轮:system: "You are assistant A.",thinking: {"type":"adaptive","display":"summarized","block_binding":{"prefix_mismatch_behavior":"drop_block"}},请求头带 anthropic-beta: thinking-binding-controls-2026-08-01。保存返回的 content(含带 signature 的 thinking 块)。
  2. 第 2 轮:system 改为 "You are assistant B, a different persona.",原样回放第 1 轮的 assistant content,再追加一条 user 消息;thinking 和 beta 头与第 1 轮相同。
  3. 对照组:与第 2 轮相同,但去掉 block_binding 和 beta 头。
请求 HTTP 响应
第 1 轮 200 input_transformations: []
第 2 轮(drop_block) 200 input_transformations: [{"type":"thinking_dropped","path":"messages.1.content.0","reason":"prefix_binding_mismatch"}]
对照组 400 Invalid signature in thinking block. The block is bound to a different conversation … The system prompt differs from the one this block was created with.

第 2 轮返回 200:block_binding 和 beta 头都到达了上游,上游按 drop_block 丢弃了失配的块,响应中的 input_transformations 也经 new-api 透传回客户端。对照组的 400 与修复前线上的报错相同。

✅ 提交前检查项 / Checklist

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

Summary by CodeRabbit

  • Compatibility
    • Claude requests now preserve thinking-block bindings and other unrecognized thinking fields when forwarded.
    • Multiple anthropic-beta header values are forwarded together, and comma-separated values are handled without empty entries.
    • Claude responses now retain input_transformations in both standard and streamed responses.

…value

Claude requests are decoded into dto.Thinking, which had no block_binding
field, so thinking.block_binding.prefix_mismatch_behavior: "drop_block"
was dropped before reaching the upstream. Multi-turn conversations whose
system prompt or tools change then failed with "The block is bound to a
different conversation".

- Thinking keeps block_binding verbatim and round-trips thinking fields
  it does not model yet.
- When a model reasoning suffix re-renders thinking as adaptive, restore
  the client's block_binding; never add one the client did not send.
- Forward every anthropic-beta header line as one comma-separated value,
  and trim entries in the Bedrock anthropic_beta list.
@coderabbitai

coderabbitai Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 3028fa12-5c77-4af3-a078-c6325b869a0f

📥 Commits

Reviewing files that changed from the base of the PR and between 0f38a14 and 9834d9b.


📒 Files selected for processing (6)
  • relay/channel/aws/dto.go
  • relay/channel/aws/relay_aws_test.go
  • relay/channel/claude/adaptor.go
  • relay/channel/claude/adaptor_test.go
  • relay/channel/claude/relay_claude_test.go
  • relaykit/dto/claude.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.



Walkthrough

The relay preserves Claude thinking fields during request conversion, handles multiple anthropic-beta values in Claude and AWS request paths, and adds coverage for input_transformations in streamed and non-streamed Claude responses.

Changes

Anthropic relay forwarding

Layer / File(s) Summary
Preserve Claude thinking fields
relaykit/dto/claude.go, relay/channel/claude/adaptor.go, relay/channel/claude/adaptor_test.go, relay/channel/claude/relay_claude_test.go
Thinking now models block_binding and preserves unmodeled JSON fields. Claude request conversion retains block_binding in adaptive mode. Tests cover thinking conversion and verify input_transformations in streamed and non-streamed responses.
Forward multiple beta header values
relay/channel/aws/dto.go, relay/channel/aws/relay_aws_test.go, relay/channel/claude/adaptor.go, relay/channel/claude/adaptor_test.go
Claude forwards all anthropic-beta header values as a comma-separated value. AWS formatting trims comma-separated values and omits empty entries. Tests check both request paths.

Priority: ➖ Normal

Estimated code review effort: 2 (Simple) | ~10 minutes

Change: Bug fix

Suggested reviewers: calcium-ion

Merge Risk: ⚪ Minimal · up to 9834d

No actionable issue remains from the inspected forwarding paths; the change appears mergeable after normal checks.

Pre-merge checks | Passed 4 | Failed 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%. Docstring coverage is scoped to functions touched by this diff. Analyzed 11 functions across 6 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check Passed The title clearly and concisely summarizes the main changes: forwarding thinking.block_binding and all anthropic-beta values.
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.

  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • 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

I’m a rabbit with fields tucked away,
Keeping each thinking block in play.
Beta values hop in a row,
Empty ones have nowhere to go.
I nibble the tests and bound on my way.

Comment @coderabbitai help to get the list of available commands.

@seefs001
seefs001 merged commit 767a82b into QuantumNous:main Oct 12, 2026
3 checks passed
shirosoralumie648 added a commit to shirosoralumie648/newapi-rev that referenced this pull request Oct 17, 2026
Sync 54 upstream commit(s) via merge (fork history preserved).
Behavior changes from upstream:
- 4013729 fix: disable sensitive word filtering by default and clear the default word list (QuantumNous#7814)

Upstream commits:
- 5e95951 feat(channels): add drag mode for channel priority ordering
- 5a59d69 fix(pricing): hide task prices left at zero when another price is set
- 3e2ce2c fix: align model card summary with status bar hours (QuantumNous#7847)
- b0a98ac fix(web): apply theme class before first paint so Dark Reader detects dark mode (QuantumNous#7571)
- f92c576 fix(web): cover Cloudflare clef and NVIDIA model families in provider rules (QuantumNous#7840)
- ff36846 fix(relayconvert): 保留 Chat/Claude → Responses 转换中 input_image 的 detail 字段 (QuantumNous#7855)
- 09109ec fix(middleware): 过载哨兵改用容器口径并加入连续性与新鲜度判定 (QuantumNous#7317)
- d032204 feat(aws): add Mantle Messages API support
- ca2cae6 fix(relaykit): emit summary on reasoning items announced without one (QuantumNous#7833)
- 45fbb14 fix(rate-limit): count each group with its own limit separately
- 6549a17 fix(dashboard): draw flow chart labels in the theme text color (QuantumNous#7821)
- c9179d3 fix(playground): support the reasoning field in chat responses (QuantumNous#7831)
- 908f94d fix(web): hide pages the user cannot open from console search
- 19d435e fix(relay): mask only the custom upstream address in error messages (QuantumNous#7822)
- 718a4e7 fix(vertex): use the multi-region hostnames for us and eu
- f196934 feat(plugins): bind Hailuo, Vidu and Veo plugins to New API channels
- bfdad29 fix(vidu): bill the model, duration and resolution Vidu generates
- 150ab3c chore(licenses): refresh the third-party dependency inventory
- 76cd511 build: upgrade moejs to v0.1.0-alpha.7
- 1b63c28 fix(claude): preserve explicit zero usage and cache-only billing (QuantumNous#7816)
- c9f7b62 fix(web): sort pricing models by input, output and per-request price (QuantumNous#7813)
- a0bf6a8 fix(vertex): pass project_id in API Key mode to avoid 404 on official endpoints (QuantumNous#6330)
- 4013729 fix: disable sensitive word filtering by default and clear the default word list (QuantumNous#7814)
- 7de10f2 feat(token): let an API key read its owner's quota
- ef60ef2 fix(relay): keep the cause of a failed body read for every later reader
- d10eafb fix(relay): report the real cause when a request body cannot be read
- 63cecab feat(channel): support Sub2API balance queries (QuantumNous#7749)
- b4be2a7 feat(ui): show newly added pricing groups at the top (QuantumNous#7782)
- 633b4c5 feat(logs): export usage logs from the common log page (QuantumNous#7774)
- dd59854 chore(deps-dev): bump undici from 6.28.0 to 6.29.0 in /electron (QuantumNous#7624)
- 93cf4ba chore(deps-dev): bump js-yaml from 4.3.1 to 4.3.2 in /electron (QuantumNous#7327)
- 3c9fb2a chore(deps-dev): bump brace-expansion from 1.1.16 to 1.1.21 in /electron (QuantumNous#7623)
- 9f04810 chore(deps): bump ai from 7.0.31 to 7.0.136 in /web (QuantumNous#7767)
- 3fe394c chore(deps): bump github.com/gorilla/websocket from 1.5.0 to 1.5.3 (QuantumNous#7001)
- 1c58f3d chore(deps-dev): bump fast-uri from 3.1.5 to 3.1.7 in /electron (QuantumNous#7169)
- 7f51a97 chore(deps-dev): bump js-yaml from 4.3.1 to 4.3.2 in /electron (QuantumNous#7327)
- 7e25797 chore(deps-dev): bump electron from 39.8.10 to 41.10.6 in /electron (QuantumNous#7625)
- bf4e1eb build(deps-dev): bump oxfmt from 0.57.0 to 0.72.0 in /web (QuantumNous#7766)
- 82306b3 build(deps-dev): bump @tanstack/router-plugin in /web (QuantumNous#7768)
- c730add build(deps): bump stream-markdown-parser from 1.1.3 to 1.2.18 in /web (QuantumNous#7769)
- b8c2dc1 build(deps): bump yace from 1.1.0 to 1.1.1 in /web (QuantumNous#7770)
- ba29f06 chore(deps-dev): bump @xmldom/xmldom from 0.8.13 to 0.8.15 in /electron (QuantumNous#7187)
- 767a82b fix(claude): forward thinking.block_binding and every anthropic-beta value (QuantumNous#7732)
- 2b85a8f fix(auth): show legal consent warning on password login (QuantumNous#7771)
- 2ed0587 fix(ci): stabilize checks and configure Bun dependency updates (QuantumNous#7765)
- 9948b1e fix(pricing): accept declared endpoint arrays in pricing conversion (QuantumNous#7724)
- 4bfcf28 chore(web): bump @lobehub/icons to 5.22.0 (QuantumNous#7764)
- fc08b76 fix(web): preserve recorded billing tiers in usage log previews (QuantumNous#7763)
- ba0e478 fix(relaykit): preserve assistant text with tool calls (QuantumNous#6871)
- 34b1942 fix(pricing): allow root access when the model square is disabled (QuantumNous#7761)
- b22a43b fix: mark task settlement logs with is_task for tiered billing display (QuantumNous#7446)
- bbf60b4 fix(logs): vertically align billing source icons on mobile (QuantumNous#7760)
- 3f926c3 fix(metrics): count completed streams after context cancellation (QuantumNous#7638)
- 3827fd8 fix(web): show cache read price on expression model cards (QuantumNous#7757)

Local tests not run (CI-only).
timwenx pushed a commit to timwenx/new-api that referenced this pull request Nov 18, 2026
…value (QuantumNous#7732)

Claude requests are decoded into dto.Thinking, which had no block_binding
field, so thinking.block_binding.prefix_mismatch_behavior: "drop_block"
was dropped before reaching the upstream. Multi-turn conversations whose
system prompt or tools change then failed with "The block is bound to a
different conversation".

- Thinking keeps block_binding verbatim and round-trips thinking fields
  it does not model yet.
- When a model reasoning suffix re-renders thinking as adaptive, restore
  the client's block_binding; never add one the client did not send.
- Forward every anthropic-beta header line as one comma-separated value,
  and trim entries in the Bedrock anthropic_beta list.
xiaolanawaqaq pushed a commit to xiaolanawaqaq/new-apiaaa that referenced this pull request Nov 26, 2026
…value (QuantumNous#7732)

Claude requests are decoded into dto.Thinking, which had no block_binding
field, so thinking.block_binding.prefix_mismatch_behavior: "drop_block"
was dropped before reaching the upstream. Multi-turn conversations whose
system prompt or tools change then failed with "The block is bound to a
different conversation".

- Thinking keeps block_binding verbatim and round-trips thinking fields
  it does not model yet.
- When a model reasoning suffix re-renders thinking as adaptive, restore
  the client's block_binding; never add one the client did not send.
- Forward every anthropic-beta header line as one comma-separated value,
  and trim entries in the Bedrock anthropic_beta list.
lizhongyi1209 pushed a commit to lizhongyi1209/new-api that referenced this pull request Nov 28, 2026
…value (QuantumNous#7732)

Claude requests are decoded into dto.Thinking, which had no block_binding
field, so thinking.block_binding.prefix_mismatch_behavior: "drop_block"
was dropped before reaching the upstream. Multi-turn conversations whose
system prompt or tools change then failed with "The block is bound to a
different conversation".

- Thinking keeps block_binding verbatim and round-trips thinking fields
  it does not model yet.
- When a model reasoning suffix re-renders thinking as adaptive, restore
  the client's block_binding; never add one the client did not send.
- Forward every anthropic-beta header line as one comma-separated value,
  and trim entries in the Bedrock anthropic_beta list.

Ported to the fork: the none-suffix test case expects this branch's disabled
rendering instead of upstream's between_tools; block_binding is still dropped.

(cherry picked from commit 767a82b)
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