mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 08:05:12 +00:00
Chat Completions treats a missing response_format.json_schema.strict as false, while Responses validates text.format strictly and rejects schemas without additionalProperties: false. Forwarding the format unchanged therefore turned valid requests into upstream 400 invalid_json_schema. Make the intended mode explicit by adding strict=false only when the field is absent; explicit strict values are untouched. Fixes #8760
98 lines
2.1 KiB
Go
98 lines
2.1 KiB
Go
package apicompat
|
|
|
|
import "encoding/json"
|
|
|
|
func chatResponseFormatToResponsesTextFormat(raw json.RawMessage) json.RawMessage {
|
|
raw = normalizedRawJSON(raw)
|
|
if len(raw) == 0 {
|
|
return nil
|
|
}
|
|
|
|
obj, ok := rawJSONObject(raw)
|
|
if !ok || rawString(obj["type"]) != "json_schema" {
|
|
return raw
|
|
}
|
|
|
|
schemaRaw := normalizedRawJSON(obj["json_schema"])
|
|
if len(schemaRaw) == 0 {
|
|
return raw
|
|
}
|
|
|
|
var schema map[string]json.RawMessage
|
|
if err := json.Unmarshal(schemaRaw, &schema); err != nil {
|
|
return raw
|
|
}
|
|
schema["type"] = rawJSONString("json_schema")
|
|
// Chat Completions defaults strict to false while Responses defaults to strict,
|
|
// so make the intended mode explicit to avoid the upstream rejecting the schema.
|
|
if _, ok := schema["strict"]; !ok {
|
|
schema["strict"] = json.RawMessage("false")
|
|
}
|
|
|
|
out, err := json.Marshal(schema)
|
|
if err != nil {
|
|
return raw
|
|
}
|
|
return out
|
|
}
|
|
|
|
func responsesTextFormatToChatResponseFormat(raw json.RawMessage) json.RawMessage {
|
|
raw = normalizedRawJSON(raw)
|
|
if len(raw) == 0 {
|
|
return nil
|
|
}
|
|
|
|
obj, ok := rawJSONObject(raw)
|
|
if !ok || rawString(obj["type"]) != "json_schema" {
|
|
return raw
|
|
}
|
|
if _, alreadyChatShape := obj["json_schema"]; alreadyChatShape {
|
|
return raw
|
|
}
|
|
|
|
schema := make(map[string]json.RawMessage, len(obj))
|
|
for key, value := range obj {
|
|
if key == "type" {
|
|
continue
|
|
}
|
|
schema[key] = value
|
|
}
|
|
if len(schema) == 0 {
|
|
return raw
|
|
}
|
|
|
|
schemaRaw, err := json.Marshal(schema)
|
|
if err != nil {
|
|
return raw
|
|
}
|
|
out, err := json.Marshal(map[string]json.RawMessage{
|
|
"type": rawJSONString("json_schema"),
|
|
"json_schema": schemaRaw,
|
|
})
|
|
if err != nil {
|
|
return raw
|
|
}
|
|
return out
|
|
}
|
|
|
|
func normalizedRawJSON(raw json.RawMessage) json.RawMessage {
|
|
raw = bytesTrimSpace(raw)
|
|
if len(raw) == 0 || string(raw) == "null" {
|
|
return nil
|
|
}
|
|
return append(json.RawMessage(nil), raw...)
|
|
}
|
|
|
|
func rawJSONObject(raw json.RawMessage) (map[string]json.RawMessage, bool) {
|
|
var obj map[string]json.RawMessage
|
|
if err := json.Unmarshal(raw, &obj); err != nil {
|
|
return nil, false
|
|
}
|
|
return obj, true
|
|
}
|
|
|
|
func rawJSONString(value string) json.RawMessage {
|
|
data, _ := json.Marshal(value)
|
|
return data
|
|
}
|