Skip to content

fix: json_schema 结构化输出按 Chat Completions 规范包装 - #124

Merged
sheepbox8646 merged 1 commit into
mainfrom
fix/twi-12-json-schema-wrapper
Oct 15, 2026
Merged

sheepbox8646 merged 1 commit into
mainfrom
fix/twi-12-json-schema-wrapper

Conversation

@sheepbox8646

Copy link
Copy Markdown
Member

概要

Chat Completions 在 ResponseFormat 为 json_schema 时,把 JSON Schema 直接放进 response_format.json_schema。按规范,schema 应该放在 json_schema.schema 下,并带上 name。DeepInfra、阿里云等严格校验的上游因此拒绝请求。

  • 包装 schema:现在发出 {"type":"json_schema","json_schema":{"name":"response","schema":{...}}}。name 固定为 response,与 Responses provider 的 text.format 一致。
  • 不发送 strict:Responses 的 text.format 也没有设置它。打开 strict 会让很多用户 schema 在 OpenAI 官方端点被拒。
  • schema 为空时降级为 json_object:修复前这种情况发出的 {"type":"json_schema"} 本来就缺必填字段,阿里云也会拒绝。
  • text 与 json_object 不变:它们仍只发送 type。之前如果 json_object 上带了 schema,会多发一个无意义的 json_schema 字段,现在不会了。
  • GitHub Copilot provider:它有一份相同的 chatRespFormat 实现,存在同样的问题,按同样方式修复。opencode/go 复用 completions 包,自动得到修复。
  • 文档:docs/providers.md 补充了 OpenAI Completions 与 Copilot 的 response_format 线上格式。

关联

验证

  • 新增单元测试,逐字比对 response_format 的线上 JSON。覆盖未设置、text、json_object、json_schema、schema 为空和 Kimi 兼容模式;completions 同时覆盖 DoGenerate 与 DoStream。
  • 本地运行 go build ./...、go vet ./...、go vet -tags integration ./...、go test ./... -short -count=1 -race、golangci-lint run ./...,全部通过。go mod tidy 无变化。
  • 真实接口(OpenRouter,强制指定上游,不允许回退):
模型 上游 修复前 修复后
deepseek/deepseek-v4.1-flash DeepInfra 422 Input should be 'text' 200,输出符合 schema
meta-llama/llama-4-scout DeepInfra 422 Input should be 'text' 200,输出符合 schema
qwen/qwen3.8-flash Alibaba 400 None is not of type 'object', 'boolean' 200,输出符合 schema
openai/gpt-oss-120b Groq / Together / Vertex 未测 200,输出符合 schema

未验证

  • OpenAI 官方端点:测试用的 Key 调用 OpenAI 上游的任何请求都返回 403(服务条款限制,与本改动无关),没能实测。
  • Copilot:只有单元测试,没有真实调用。

🤖 Generated with Claude Code

response_format.json_schema 原来直接放裸 schema,DeepInfra、阿里云等严格校验的上游会拒绝请求。现在包装为 {"name":"response","schema":{...}},与 Responses provider 的 text.format 一致;schema 为空时降级为 json_object。GitHub Copilot provider 有同样的实现,一并修复。

Linear: TWI-12

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sheepbox8646
sheepbox8646 merged commit df74a4f into main Oct 15, 2026
4 checks passed
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.

1 participant