Skip to content

fix: 工具调用 arguments 为空时保留 tool_use 块 - #5543

Merged
seefs001 merged 1 commit into
QuantumNous:mainfrom
feitianbubu:pr/08bfed8a40ef105f23366d1b08ce4a22b9ad1e18
Jun 17, 2026
Merged

seefs001 merged 1 commit into
QuantumNous:mainfrom
feitianbubu:pr/08bfed8a40ef105f23366d1b08ce4a22b9ad1e18

Conversation

@feitianbubu

@feitianbubu feitianbubu commented Jun 16, 2026 •

Copy link
Copy Markdown
Member

📝 变更描述 / Description

OpenAI 格式转 Claude 时,RequestOpenAI2ClaudeMessage 会把 tool_calls 转成 tool_use 块。原逻辑对 function.arguments 直接 json.Unmarshal,解析失败就 continue 跳过整个块。

部分模型在无参数工具调用时 arguments 为空字符串 "",反序列化必然失败,导致对应的 tool_use 块被整个丢弃。而 Claude 要求 tool_use 与后续 tool_result 一一对应,块丢失后请求结构被破坏,会触发上游报错。

修复:仅在 arguments 非空时才反序列化;即使解析失败也不再跳过,照常追加 tool_use(input 为空对象),保证块完整。

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix)

修复前:
image
修复后:
image

Summary by CodeRabbit

  • Bug Fixes
    • Enhanced error handling for tool calls in Claude relay. Tool calls with malformed or invalid JSON arguments are now processed with appropriate logging instead of being silently discarded. This improvement provides better error visibility and simplifies troubleshooting of tool integration issues.

@coderabbitai

coderabbitai Bot commented Jun 16, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

In RequestOpenAI2ClaudeMessage, tool-call argument parsing now skips json.Unmarshal when Arguments is empty, and on unmarshal failure the code logs the error but continues to construct and append the Claude tool_use block instead of skipping it entirely.

Changes

Claude Tool-Call Argument Parsing

Layer / File(s) Summary
Guard unmarshal and remove skip-on-error
relay/channel/claude/relay-claude.go
Wraps json.Unmarshal in a non-empty check for Arguments; replaces the continue on unmarshal error with a log statement so the tool_use entry is still built and appended even when argument JSON is malformed or absent.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~5 minutes

Possibly related PRs

  • QuantumNous/new-api#2397: Directly modifies the same OpenAI→Claude tool-call conversion path, specifically handling tool_call.function.arguments and tool_use block emission.
  • QuantumNous/new-api#1531: Modifies Claude tool-call and message conversion in the OpenAI→Claude path, overlapping with tool-call formatting logic touched here.

Poem

🐇 A tool call came in, but its JSON was bare,
No arguments found — just a wisp of cold air.
I once skipped those calls, left them lost in the void,
Now I log and move on — no tool left destroyed.
With an empty-check guard and a soft warning logged,
Every tool_use gets built — no call left unclogged! 🛠️

🚥 Pre-merge checks | ✅ 4 | ❌ 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 (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title is in Chinese and states 'fix: 工具调用 arguments 为空时保留 tool_use 块' (fix: preserve tool_use block when tool call arguments are empty), which directly describes the main change: handling empty arguments in tool calls to preserve tool_use blocks.
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.

✏️ 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.

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

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@relay/channel/claude/relay-claude.go`:
- Line 414: Replace the direct json.Unmarshal call on line 414 with
common.Unmarshal from the common/json.go wrapper package. Change
json.Unmarshal([]byte(args), &inputObj) to use the common.Unmarshal wrapper
function instead, which is the standardized approach for all JSON
marshal/unmarshal operations in business logic throughout the repository.
- Line 415: The SysLog call at line 415 logs the raw toolCall.Function.Arguments
which can contain sensitive data. Replace the logging of the full raw arguments
with metadata instead: log the tool function name (toolCall.Function.Name) and
the byte length of the arguments (using len() on the serialized form) rather
than the full content using fmt.Sprintf("%v", toolCall.Function.Arguments). This
preserves debugging information while avoiding exposure of sensitive user/tool
data in logs.
🪄 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: b670e4f0-b44c-408f-8301-1e389abf0503

📥 Commits

Reviewing files that changed from the base of the PR and between eb86311 and 437bbd6.

📒 Files selected for processing (1)
  • relay/channel/claude/relay-claude.go

common.SysLog("tool call function arguments is not a map[string]any: " + fmt.Sprintf("%v", toolCall.Function.Arguments))
continue
if args := toolCall.Function.Arguments; args != "" {
if err := json.Unmarshal([]byte(args), &inputObj); err != nil {

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Replace direct json.Unmarshal with common.Unmarshal.

Line 414 directly calls encoding/json in business logic, which violates the repository rule for Go JSON handling.

Proposed fix
-						if err := json.Unmarshal([]byte(args), &inputObj); err != nil {
+						if err := common.Unmarshal([]byte(args), &inputObj); err != nil {
 							common.SysLog("tool call function arguments is not a map[string]any: " + fmt.Sprintf("%v", toolCall.Function.Arguments))
 						}

As per coding guidelines, all JSON marshal/unmarshal operations in business code must use wrappers from common/json.go, and this path is application-level parsing rather than a Gin response-helper exemption.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if err := json.Unmarshal([]byte(args), &inputObj); err != nil {
if err := common.Unmarshal([]byte(args), &inputObj); err != nil {
common.SysLog("tool call function arguments is not a map[string]any: " + fmt.Sprintf("%v", toolCall.Function.Arguments))
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@relay/channel/claude/relay-claude.go` at line 414, Replace the direct
json.Unmarshal call on line 414 with common.Unmarshal from the common/json.go
wrapper package. Change json.Unmarshal([]byte(args), &inputObj) to use the
common.Unmarshal wrapper function instead, which is the standardized approach
for all JSON marshal/unmarshal operations in business logic throughout the
repository.

Sources: Coding guidelines, Learnings

continue
if args := toolCall.Function.Arguments; args != "" {
if err := json.Unmarshal([]byte(args), &inputObj); err != nil {
common.SysLog("tool call function arguments is not a map[string]any: " + fmt.Sprintf("%v", toolCall.Function.Arguments))

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.

⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Do not log raw tool arguments on parse failure.

Line 415 logs full toolCall.Function.Arguments; malformed payloads can still contain sensitive user/tool data. Log metadata (tool id/name + byte length) instead of raw content.

Proposed fix
-							common.SysLog("tool call function arguments is not a map[string]any: " + fmt.Sprintf("%v", toolCall.Function.Arguments))
+							common.SysLog(fmt.Sprintf(
+								"tool call arguments parse failed: tool_id=%s tool_name=%s args_len=%d",
+								toolCall.ID, toolCall.Function.Name, len(args),
+							))
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
common.SysLog("tool call function arguments is not a map[string]any: " + fmt.Sprintf("%v", toolCall.Function.Arguments))
common.SysLog(fmt.Sprintf(
"tool call arguments parse failed: tool_id=%s tool_name=%s args_len=%d",
toolCall.ID, toolCall.Function.Name, len(args),
))
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@relay/channel/claude/relay-claude.go` at line 415, The SysLog call at line
415 logs the raw toolCall.Function.Arguments which can contain sensitive data.
Replace the logging of the full raw arguments with metadata instead: log the
tool function name (toolCall.Function.Name) and the byte length of the arguments
(using len() on the serialized form) rather than the full content using
fmt.Sprintf("%v", toolCall.Function.Arguments). This preserves debugging
information while avoiding exposure of sensitive user/tool data in logs.

@seefs001
seefs001 merged commit 502858d into QuantumNous:main Jun 17, 2026
1 check passed
QQhuxuhui added a commit to QQhuxuhui/new-api that referenced this pull request Jun 30, 2026
dev 与 upstream 无共同祖先、不能 cherry-pick,按文件手工 port:
- 502858d fix(QuantumNous#5543): tool 调用 arguments 为空时保留 tool_use 块
- 45cc95a fix(gemini): ToolConfig 加 IncludeServerSideToolInvocations 字段
- 8ca1033 fix: ReasoningContent/Reasoning 改 *string,修复空思考内容转发被静默丢弃
  (并适配 dev 自研 openaicompat/responses_to_chat.go 的 *string 赋值)
- 867d8ac fix(QuantumNous#5390): kimi-k2.6 温度归一化(import 冲突已解,去掉未用的 channelconstant)
- ff06067 fix(QuantumNous#5095): 移除 fcIdx -1 偏移,修复并发工具调用撞键

go build ./... 与 go vet 均通过。

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
QQhuxuhui added a commit to QQhuxuhui/new-api that referenced this pull request Jun 30, 2026
包含:QuantumNous#5543 tool_use / gemini 字段 / ReasoningContent *string / QuantumNous#5390 kimi 温度 /
QuantumNous#5095 并发工具撞键 / aa56667 A 防上游 request-id 覆盖
ruanhangjian pushed a commit to ruanhangjian/new-api that referenced this pull request Jul 11, 2026
noah-wung pushed a commit to noah-wung/new-api that referenced this pull request Jul 17, 2026
zhaodechao2008 pushed a commit to zhaodechao2008/new-api that referenced this pull request Jul 27, 2026
330079598 pushed a commit to 330079598/new-api that referenced this pull request Aug 19, 2026
salem-2007 added a commit to salem-2007/new-api that referenced this pull request Sep 10, 2026
junjundesk pushed a commit to junjundesk/new-api that referenced this pull request Oct 3, 2026
NaturalSelect pushed a commit to NaturalSelect/new-api that referenced this pull request Nov 5, 2026
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