Skip to content

fix: support OpenAI custom tools across Chat Completions and Responses conversion - #8520

Open
seefs001 wants to merge 1 commit into
QuantumNous:mainfrom
seefs001:fix/openai-custom-tools-8496
Open

seefs001 wants to merge 1 commit into
QuantumNous:mainfrom
seefs001:fix/openai-custom-tools-8496

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 官方 type: "custom" 工具在 Chat Completions 原生转发、Chat 与 Responses 双向转换以及响应回程中的协议损坏与字段丢失问题。

处理的请求与响应类型

路由与请求类型 请求形态 处理结果
原生 /v1/chat/completions(官方嵌套 custom) {"type":"custom","custom":{"name":"...","format":{...}}} 原样无损转发,不再注入 "function":{"name":""}
原生 /v1/chat/completions(非标扁平 custom / 其他非 function 工具) {"type":"custom","name":"...","format":{...}} 原样保留顶层字段,不丢 name/format,不注入空 function,也不改写结构
chat_completions_to_responses_policy(官方嵌套 custom 工具与 tool_choice) Chat 官方嵌套 tools(含 format.type="text" 及嵌套 format.grammar.{syntax,definition})与 tool_choice 转为 Responses 官方扁平格式(format.grammar 展平到 format 顶层,tool_choice 转为 {"type":"custom","name":"..."})
chat_completions_to_responses_policy(多轮 custom 历史) assistant.tool_calls 中 type="custom" 及其后同 tool_call_id 的 role="tool" 分别转为 Responses 的 custom_tool_call 与 custom_tool_call_output
chat_completions_to_responses_policy(非标扁平 custom 入参) 顶层无 custom 对象的扁平写法 不在转换层兜底改写,按规范报错返回 400
Responses 回程 / 直连 Chat 响应(含 force_format 与 thinking_to_content) 上游返回 custom_tool_call(非流式 / 流式 SSE / 缓冲流)或直连 Chat 返回 type="custom" 统一输出 OpenAI 官方 {"id":"...","type":"custom","custom":{"name":"...","input":"..."}},不含 function,完整保留 input

请求转换示例(OpenAI 官方 Chat 嵌套格式转 Responses 扁平格式)

// 客户端发送到 /v1/chat/completions(OpenAI 官方嵌套写法)
{
  "tools": [
    {
      "type": "custom",
      "custom": {
        "name": "ApplyPatch",
        "description": "Apply a patch",
        "format": {
          "type": "grammar",
          "grammar": { "syntax": "lark", "definition": "start: \"x\"" }
        }
      }
    }
  ],
  "tool_choice": { "type": "custom", "custom": { "name": "ApplyPatch" } }
}
// 开启 chat_completions_to_responses_policy 后发往上游 /v1/responses
{
  "tools": [
    {
      "type": "custom",
      "name": "ApplyPatch",
      "description": "Apply a patch",
      "format": { "type": "grammar", "syntax": "lark", "definition": "start: \"x\"" }
    }
  ],
  "tool_choice": { "type": "custom", "name": "ApplyPatch" }
}

改动前后的流转变化

flowchart LR
    A["Chat 请求: type=custom"] --> B["dto.ToolCallRequest"]
    B -->|"原生 /v1/chat/completions"| C["保留原始字段, 不再输出空 function"]
    B -->|"chat_completions_to_responses_policy (官方嵌套)"| D["toolconv + oai_chat"]
    D --> E["Responses 请求: 扁平 custom, 展开 format.grammar, custom_tool_call 历史"]
    E --> F["上游 /v1/responses 返回 custom_tool_call (input)"]
    F --> G["oai_responses 非流式 / 流式 / 缓冲流"]
    G --> H["Chat 响应: type=custom, custom.name 与 custom.input"]
Loading

根因与改动文件

模块与文件 修复前问题 修复后行为
relaykit/dto/openai_request.go ToolCallRequest.Function 无 omitempty,非 function 工具序列化必带 "function":{"name":""};未知顶层字段反序列化时丢失 非 function 且 Function 为空时不输出 function;保留含未知顶层字段的原始 JSON,不做改写
relaykit/dto/openai_response.go ToolCallResponse 无 Custom 字段,开启 force_format 或 thinking_to_content 会剥离 custom 调用;ResponsesOutput 无 InputString() 新增 CustomToolCallResponse 并在 Custom 非空时省略 function;新增 ResponsesOutput.InputString()
relaykit/relayconvert/internal/toolconv/decode.go
relaykit/relayconvert/internal/toolconv/encode.go
Chat 来源的嵌套 type: "custom" 工具与 tool_choice 在转换层被丢弃 解码 Chat 嵌套 custom 工具(含展平 format.grammar)与 custom 的 tool_choice,映射到 Responses 扁平结构
relaykit/relayconvert/internal/oai_chat/to_oai_responses_req.go
relaykit/relayconvert/internal/oai_chat/to_oai_responses_resp.go
多轮历史跳过 type: "custom" 的 tool_calls,role: "tool" 固定写成 function_call_output 合并重复循环,支持 custom_tool_call 与 custom_tool_call_output 多轮历史,响应侧同步识别官方 type: "custom"
relaykit/relayconvert/internal/oai_responses/to_oai_chat_resp.go
relaykit/relayconvert/internal/oai_responses/to_oai_chat_stream_resp.go
回程强转为 type: "function",且非流式、终态补发与 ResponsesBufferedAccumulator 只读 Arguments 导致 Input 丢空 非流式与流式统一输出官方 type: "custom" 与 custom: {name, input};全路径改读并写回 Input
relaykit/relayconvert/internal/oai_responses/to_oai_chat_resp_test.go TestResponsesStreamEventToChatChunksCustomToolAndReasoning 沿用旧降级断言,将纯文本 patch body 断言到 Function.Arguments 更新为断言 Type == "custom" 与 Custom.Name / Custom.Input

合并风险评估

  • Door: two-way(纯 relaykit/ 编解码与转换层改动,无数据库与状态迁移,回滚成本低)
  • Blast Radius: relaykit(普通 function 工具调用及 /v1/responses 经 Chat 转发链路不受影响)

📸 运行证明 / Proof of Work

Before / After 对比

  • Before
    • 原生嵌套 {"type":"custom","custom":{"name":"ApplyPatch","format":{"type":"text"}}} 经 ToolCallRequest 序列化后变成 {"type":"custom","function":{"name":""},"custom":{...}}。
    • Chat 到 Responses 转换直接丢弃 type: "custom" 工具与多轮 custom_tool_call 历史。
    • Responses 返回 custom_tool_call(input: "*** Begin Patch")经 ResponsesResponseToChatCompletionsResponse 转换后变成 {"type":"function","function":{"name":"ApplyPatch","arguments":""}},input 丢失。
  • After
    • 原生嵌套工具保留原样且不含 function;扁平工具原样保留顶层 name 与 format 且不含 function。
    • Chat 到 Responses 正确输出扁平 tools(展平 format.grammar)、tool_choice、custom_tool_call 与 custom_tool_call_output。
    • Responses 到 Chat 非流式、流式 SSE 与缓冲流均输出 {"id":"call_c1","type":"custom","custom":{"name":"ApplyPatch","input":"..."}},不含 function。

本地验证命令与结果

cd relaykit && GOWORK=off go build ./... && GOWORK=off go test ./...
  • 全部 relaykit/ 子包编译与测试通过(含 relaykit/dto、relaykit/relayconvert、internal/toolconv、internal/oai_chat、internal/oai_responses)。
CGO_ENABLED=0 go build ./relay/... ./service/...
CGO_ENABLED=0 go test ./relay/channel/openai/...
CGO_ENABLED=0 go test ./service -run "TestConvert|TestChatCompletions|TestResponses"
  • relay/channel/openai 与 service 转换相关测试全部通过。
  • 通过本地验证程序对 7 条链路(嵌套请求、扁平请求保真、Chat 到 Responses 转换、Responses 到 Chat 非流式、流式 SSE、缓冲累加器、force_format 直连流式重编)逐项检查序列化 JSON,全部符合预期。

✅ 提交前检查项 / 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

  • New Features
    • Added support for custom tool calls, tool outputs, and named custom tool choices when converting between OpenAI request and response formats.
    • Custom tool calls are supported in both streamed and buffered responses, with their names and input preserved.
    • Additional fields in non-function tool definitions are retained during conversion.
  • Bug Fixes
    • Custom tool responses now keep their input and name when converted, and streamed completion updates avoid replacing longer accumulated input.

…nversion

Preserve non-function tool definitions in dto.ToolCallRequest without
emitting an empty function object, and add CustomToolCallResponse to
dto.ToolCallResponse so custom tool calls survive Chat Completions
marshaling and force_format paths.

Translate OpenAI Chat Completions custom tools (including nested grammar
formats), custom tool_choice, and multi-turn custom_tool_call history
into Responses requests. Return Responses custom_tool_call outputs as
type "custom" with custom.name and custom.input across non-streaming,
streaming, and buffered accumulator paths.

Closes QuantumNous#8496
@coderabbitai

coderabbitai Bot commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

Explain Change →

No actionable comments were generated in the recent review.

Walkthrough

The changes add custom tool payload handling across DTOs and relay conversion. They preserve custom definitions and choices in request conversion, and map custom tool outputs and streamed input back to Chat Completions custom tool calls.

Changes

Custom Tool Conversion

Layer / File(s) Summary
Custom tool DTO handling
relaykit/dto/openai_request.go, relaykit/dto/openai_response.go
Request DTOs retain eligible raw tool JSON for marshaling and token counting. Response DTOs represent custom payloads, clear custom names, and expose response input as a string.
Custom tool decoding and encoding
relaykit/relayconvert/internal/toolconv/decode.go, relaykit/relayconvert/internal/toolconv/encode.go
Tool decoding handles custom definitions and named choices, including nested grammar formats. Responses encoding preserves eligible native custom definitions and encodes named custom choices.
Chat Completions to Responses requests
relaykit/relayconvert/internal/oai_chat/to_oai_responses_req.go
Request conversion maps custom calls and matching outputs, converts custom definitions and choices, and consolidates string and multipart message handling.
Responses to Chat Completions output
relaykit/relayconvert/internal/oai_chat/to_oai_responses_resp.go, relaykit/relayconvert/internal/oai_responses/to_oai_chat_resp.go, relaykit/relayconvert/internal/oai_responses/to_oai_chat_stream_resp.go, relaykit/relayconvert/internal/oai_responses/to_oai_chat_resp_test.go
Response conversion maps custom tool outputs and input to custom Chat tool calls. Streaming and buffered paths distinguish custom input from function arguments. The test checks custom type, name, and input.

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

Change: Bug fix · Severity of issue fixed: Medium

Sequence Diagram(s)

sequenceDiagram
  participant Responses as OpenAI Responses
  participant Converter as ResponsesResponseToChatCompletionsResponse
  participant Chat as Chat Completions
  Responses->>Converter: custom_tool_call with name, call ID, and input
  Converter->>Chat: custom tool call with name, call ID, and input
Loading

Suggested reviewers: calcium-ion, sicnuyudidi

Merge Risk: Minimal · up to 72629

This change preserves custom tools across Chat Completions and Responses conversion, including request mapping and the custom tool-call shape in responses. No merge-blocking defect was established in the changed code. One adjacent, pre-existing gap exists: streaming a Chat custom tool call back out as a Responses stream may not carry the custom name and input. It is outside this PR's stated scope and could be tracked as a follow-up.

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 "fix: support OpenAI custom tools across Chat Completions and Responses conversion" matches the main change. The raw summary and PR objectives show the changes preserve OpenAI custom tools (…
Linked Issues check Passed Directly linked issue #8496 has three coding requirements. (1) Flat and nested custom definitions keep name and format on the native /v1/chat/completions route. The reviewed head changes ToolCallReque…
Out of Scope Changes check Passed All changed areas map to #8496 or to required support for it. Changes are in relaykit/dto (request and response tool structures), relayconvert/internal/toolconv (custom tool and tool_choice decode and…
Full details: Title check

Explanation

The title "fix: support OpenAI custom tools across Chat Completions and Responses conversion" matches the main change. The raw summary and PR objectives show the changes preserve OpenAI custom tools (type "custom") across native Chat Completions handling, Chat-to-Responses request conversion, and Responses-to-Chat response conversion, including custom_tool_call and custom_tool_call_output items. The title is concise, specific, and in one sentence. It does not cover every detail, such as streaming accumulation or the flat-input limitation, which is acceptable.

Full details: Linked Issues check

Explanation

Directly linked issue #8496 has three coding requirements. (1) Flat and nested custom definitions keep name and format on the native /v1/chat/completions route. The reviewed head changes ToolCallRequest in relaykit/dto/openai_request.go to keep raw JSON for non-function tools with extra top-level keys, and to omit the empty function object. Nested custom remains in the Custom field. (2) Upstream custom_tool_call is returned to Chat clients as type "custom", not function. Changes in relaykit/relayconvert/internal/oai_responses/to_oai_chat_resp.go (non-streaming), to_oai_chat_stream_resp.go (SSE and buffered accumulator), and dto/openai_response.go (ToolCallResponse.Custom, custom MarshalJSON) implement this, including the force_format and thinking_to_content paths. (3) custom input is preserved. The stream and buffered paths read and write Input / InputString() instead of Arguments. The PR also converts Chat custom history and tools to Responses custom_tool_call and flat tool formats. Limitation: under chat_completions_to_responses_policy, flat custom input without a nested custom object returns HTTP 400 instead of being converted. The issue's expected result 1 asks that flat definitions keep name and format. The PR states this is a deliberate error, not silent field loss, and the native route keeps the flat fields. This is a narrower outcome, and it is noted here as a remaining gap relative to the issue text. Test evidence: the PR updates TestResponsesStreamEventToChatChunksCustomToolAndReasoning to assert Type custom and Custom.Name/Input. The PR reports go test runs for relaykit, relay/channel/openai, and service, but these were not re-run in this review.

Full details: Out of Scope Changes check

Explanation

All changed areas map to #8496 or to required support for it. Changes are in relaykit/dto (request and response tool structures), relayconvert/internal/toolconv (custom tool and tool_choice decode and encode), oai_chat (custom history and tool conversion), oai_responses (custom return path and buffered accumulator), and the matching test update. The shared message-content conversion path in to_oai_responses_req.go is a refactor. The PR states that multipart text, image, audio, file, and video mappings are retained. This refactor is not directly required by the issue. It is a supporting change for the request conversion, and it is not shown to change behavior for function tools. The stream change that updates completion arguments only when longer is a behavior change tied to custom input handling. No unrelated feature or file is identified. Uncertainty: the content-path refactor was not diffed line by line in this review.

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

A rabbit checks the custom call,
Its name and input travel all.
From Responses into Chat they go,
Through buffered paths and streams that flow.
The rabbit thumps beside the code,
And nibbles greens along the road.

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: 91592608-77cb-4516-9563-f2f45ccd8d85
Commits

Reviewing files that changed from the base of the PR and between 04dfcbb and 72629ee.

Files selected for processing: 9

  • relaykit/dto/openai_request.go
  • relaykit/dto/openai_response.go
  • relaykit/relayconvert/internal/oai_chat/to_oai_responses_req.go
  • relaykit/relayconvert/internal/oai_chat/to_oai_responses_resp.go
  • relaykit/relayconvert/internal/oai_responses/to_oai_chat_resp.go
  • relaykit/relayconvert/internal/oai_responses/to_oai_chat_resp_test.go
  • relaykit/relayconvert/internal/oai_responses/to_oai_chat_stream_resp.go
  • relaykit/relayconvert/internal/toolconv/decode.go
  • relaykit/relayconvert/internal/toolconv/encode.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: Chat Completions 扁平 type:custom 工具丢失 name/format,Responses→Chat 把 custom_tool_call 收成 function

1 participant