Files
sub2api/backend/internal/pkg/apicompat/response_format.go
T
李建琦 6d655c9903
Release / update-version (push) Has been cancelled
Release / build-frontend (push) Has been cancelled
Release / release (push) Has been cancelled
Release / sync-version-file (push) Has been cancelled
CI / shell (push) Canceled after 0s
CI / test (push) Canceled after 0s
CI / frontend (push) Canceled after 0s
CI / golangci-lint (push) Canceled after 0s
Security Scan / backend-security (push) Canceled after 0s
Security Scan / frontend-security (push) Canceled after 0s
Sub2API v1.0 - AI API 网关(二开初始版本,基于上游 Wei-Shaw/sub2api)
2026-08-21 18:30:13 +08:00

93 lines
1.9 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")
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
}