diff --git a/relaykit/relayconvert/internal/oai_chat/to_claude_messages_req.go b/relaykit/relayconvert/internal/oai_chat/to_claude_messages_req.go index d29a325108..5f8da79109 100644 --- a/relaykit/relayconvert/internal/oai_chat/to_claude_messages_req.go +++ b/relaykit/relayconvert/internal/oai_chat/to_claude_messages_req.go @@ -24,7 +24,7 @@ func OpenAIChatRequestToClaudeMessages(c context.Context, info convmeta.Meta, te if kitutil.GetJsonType(tool.Function.Parameters) != "object" && tool.Type != "function" { continue } - inputSchema, _ := sharedclaude.FunctionParametersToInputSchema(tool.Function.Parameters) + inputSchema, _, _ := sharedclaude.FunctionParametersToInputSchema(tool.Function.Parameters) claudeTools = append(claudeTools, &dto.Tool{ Name: tool.Function.Name, Description: tool.Function.Description, diff --git a/relaykit/relayconvert/internal/oai_responses/to_claude_messages_req.go b/relaykit/relayconvert/internal/oai_responses/to_claude_messages_req.go index 423f966399..6e5d0a36fe 100644 --- a/relaykit/relayconvert/internal/oai_responses/to_claude_messages_req.go +++ b/relaykit/relayconvert/internal/oai_responses/to_claude_messages_req.go @@ -171,7 +171,7 @@ func OpenAIResponsesRequestToClaudeMessages(c context.Context, info convmeta.Met func responsesFunctionDeclarationsToClaudeTools(functions []dto.FunctionRequest) []any { tools := make([]any, 0, len(functions)) for _, function := range functions { - inputSchema, _ := sharedclaude.FunctionParametersToInputSchema(function.Parameters) + inputSchema, _, _ := sharedclaude.FunctionParametersToInputSchema(function.Parameters) tools = append(tools, &dto.Tool{ Name: function.Name, Description: function.Description, diff --git a/relaykit/relayconvert/internal/shared/claude/schema.go b/relaykit/relayconvert/internal/shared/claude/schema.go index 5d167194d3..eaa22e293c 100644 --- a/relaykit/relayconvert/internal/shared/claude/schema.go +++ b/relaykit/relayconvert/internal/shared/claude/schema.go @@ -2,43 +2,197 @@ package claude import ( "encoding/json" + "reflect" + "slices" "github.com/MoeForge/moego/ojson" kitutil "github.com/QuantumNous/new-api/relaykit/relayconvert/kitutil" ) +// topLevelUnionKeys are the schema combinators Claude rejects at the top level +// of input_schema ("input_schema does not support oneOf, allOf, or anyOf at the +// top level"). +var topLevelUnionKeys = []string{"oneOf", "anyOf", "allOf"} + // FunctionParametersToInputSchema returns function parameters as a Claude // input_schema, adding type and properties when they are missing or null. -// Otherwise the client's bytes are kept, so the properties keep their order. -// ok is false when parameters are not a JSON object; the result is then an -// empty object schema. -func FunctionParametersToInputSchema(parameters json.RawMessage) (schema json.RawMessage, ok bool) { +// A top-level oneOf, anyOf or allOf is flattened into one object schema (see +// flattenTopLevelUnion) and its keywords are returned in flattened, so the +// caller can report the loss. Otherwise the client's bytes are kept, so the +// properties keep their order. ok is false when parameters are not a JSON +// object; the result is then an empty object schema. +func FunctionParametersToInputSchema(parameters json.RawMessage) (schema json.RawMessage, flattened []string, ok bool) { empty := json.RawMessage(`{"type":"object","properties":{}}`) switch kitutil.GetJsonType(parameters) { case "unknown", "null": - return empty, true + return empty, nil, true case "object": default: - return empty, false + return empty, nil, false } var fields struct { Type json.RawMessage `json:"type"` Properties json.RawMessage `json:"properties"` } if err := kitutil.Unmarshal(parameters, &fields); err != nil { - return empty, false + return empty, nil, false } schema = parameters var err error + if schema, flattened, err = flattenTopLevelUnion(schema); err != nil { + return empty, nil, false + } + if len(flattened) > 0 { + fields.Type = json.RawMessage(`"object"`) + fields.Properties = json.RawMessage(`{}`) + } if len(fields.Type) == 0 || kitutil.GetJsonType(fields.Type) == "null" { if schema, err = ojson.SetRawBytes(schema, "type", []byte(`"object"`)); err != nil { - return empty, false + return empty, nil, false } } if len(fields.Properties) == 0 || kitutil.GetJsonType(fields.Properties) == "null" { if schema, err = ojson.SetRawBytes(schema, "properties", []byte(`{}`)); err != nil { - return empty, false + return empty, nil, false } } - return schema, true + return schema, flattened, true +} + +// flattenTopLevelUnion rewrites a schema whose top level is a oneOf, anyOf or +// allOf into a single object schema Claude accepts: +// +// - properties of the top level and of every branch are merged in document +// order; a name whose schemas differ becomes a nested anyOf of the +// distinct schemas; +// - required is the top level's required plus, per keyword, the +// intersection of the branches' required for oneOf/anyOf and the union +// for allOf; +// - the union keywords are removed and type is set to "object"; every other +// top-level keyword (description, additionalProperties, ...) is kept. +// +// The schema is returned unchanged, with flattened nil, when no union keyword +// is present at the top level. +func flattenTopLevelUnion(schema json.RawMessage) (json.RawMessage, []string, error) { + root := ojson.ParseBytes(schema) + var flattened []string + for _, key := range topLevelUnionKeys { + if root.Get(key).Exists() { + flattened = append(flattened, key) + } + } + if len(flattened) == 0 { + return schema, nil, nil + } + + var names []string + variants := map[string][]json.RawMessage{} + addProperties := func(object ojson.Result) { + object.Get("properties").ForEach(func(name, value ojson.Result) bool { + key := name.String() + raw := json.RawMessage(value.Raw) + existing, seen := variants[key] + if !seen { + names = append(names, key) + } + var decoded any + if err := kitutil.Unmarshal(raw, &decoded); err != nil { + decoded = value.Raw + } + if !slices.ContainsFunc(existing, func(other json.RawMessage) bool { + var otherDecoded any + if err := kitutil.Unmarshal(other, &otherDecoded); err != nil { + otherDecoded = string(other) + } + return reflect.DeepEqual(otherDecoded, decoded) + }) { + variants[key] = append(existing, raw) + } + return true + }) + } + required := stringArray(root.Get("required")) + addProperties(root) + for _, key := range flattened { + var branchRequired []string + first := true + for _, branch := range root.Get(key).Array() { + addProperties(branch) + branchNames := stringArray(branch.Get("required")) + switch { + case key == "allOf": + branchRequired = appendMissing(branchRequired, branchNames...) + case first: + branchRequired = branchNames + default: + branchRequired = slices.DeleteFunc(branchRequired, func(name string) bool { return !slices.Contains(branchNames, name) }) + } + first = false + } + required = appendMissing(required, branchRequired...) + } + + properties := []byte{'{'} + for i, name := range names { + if i > 0 { + properties = append(properties, ',') + } + properties = ojson.AppendJSONString(properties, name) + properties = append(properties, ':') + if schemas := variants[name]; len(schemas) == 1 { + properties = append(properties, schemas[0]...) + } else { + anyOf, err := kitutil.Marshal(map[string][]json.RawMessage{"anyOf": schemas}) + if err != nil { + return nil, nil, err + } + properties = append(properties, anyOf...) + } + } + properties = append(properties, '}') + + out := slices.Clone(schema) + var err error + for _, key := range flattened { + if out, err = ojson.DeleteBytes(out, key); err != nil { + return nil, nil, err + } + } + if out, err = ojson.SetRawBytes(out, "type", []byte(`"object"`)); err != nil { + return nil, nil, err + } + if out, err = ojson.SetRawBytes(out, "properties", properties); err != nil { + return nil, nil, err + } + if len(required) == 0 { + out, err = ojson.DeleteBytes(out, "required") + } else { + var requiredJSON []byte + if requiredJSON, err = kitutil.Marshal(required); err == nil { + out, err = ojson.SetRawBytes(out, "required", requiredJSON) + } + } + if err != nil { + return nil, nil, err + } + return out, flattened, nil +} + +func stringArray(value ojson.Result) []string { + var values []string + for _, item := range value.Array() { + if item.Type == ojson.String { + values = appendMissing(values, item.String()) + } + } + return values +} + +func appendMissing(values []string, items ...string) []string { + for _, item := range items { + if !slices.Contains(values, item) { + values = append(values, item) + } + } + return values } diff --git a/relaykit/relayconvert/internal/shared/claude/schema_test.go b/relaykit/relayconvert/internal/shared/claude/schema_test.go new file mode 100644 index 0000000000..67dd3fcda3 --- /dev/null +++ b/relaykit/relayconvert/internal/shared/claude/schema_test.go @@ -0,0 +1,63 @@ +package claude + +import ( + "encoding/json" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestFunctionParametersToInputSchemaFlattensTopLevelUnion(t *testing.T) { + t.Parallel() + + tests := []struct { + name string + in string + want string + flattened []string + }{ + { + name: "no union keeps the client's bytes", + in: `{"type":"object","properties":{"z":{"type":"string"},"a":{"type":"integer","anyOf":[{"minimum":1}]}},"required":["z"]}`, + want: `{"type":"object","properties":{"z":{"type":"string"},"a":{"type":"integer","anyOf":[{"minimum":1}]}},"required":["z"]}`, + }, + { + name: "oneOf with disjoint properties", + in: `{"description":"Update an automation","oneOf":[{"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"}},"required":["id","name"]},{"type":"object","properties":{"id":{"type":"string"},"enabled":{"type":"boolean"}},"required":["id","enabled"]}],"additionalProperties":false}`, + want: `{"description":"Update an automation","additionalProperties":false,"type":"object","properties":{"id":{"type":"string"},"name":{"type":"string"},"enabled":{"type":"boolean"}},"required":["id"]}`, + flattened: []string{"oneOf"}, + }, + { + name: "same-name properties with different schemas become anyOf", + in: `{"anyOf":[{"properties":{"when":{"type":"string"}}},{"properties":{"when":{"type":"integer"}}},{"properties":{"when":{ "type" : "string" }}}]}`, + want: `{"type":"object","properties":{"when":{"anyOf":[{"type":"string"},{"type":"integer"}]}}}`, + flattened: []string{"anyOf"}, + }, + { + name: "allOf required is the union plus the top level's", + in: `{"type":"object","required":["mode"],"properties":{"mode":{"type":"string"}},"allOf":[{"properties":{"a":{"type":"string"}},"required":["a"]},{"properties":{"b":{"type":"string"}},"required":["b","a"]}]}`, + want: `{"type":"object","required":["mode","a","b"],"properties":{"mode":{"type":"string"},"a":{"type":"string"},"b":{"type":"string"}}}`, + flattened: []string{"allOf"}, + }, + { + name: "branches without properties contribute nothing and empty required is dropped", + in: `{"oneOf":[{"properties":{"id":{"type":"string"}},"required":["id"]},{"required":["id"]},{"type":"object"}]}`, + want: `{"type":"object","properties":{"id":{"type":"string"}}}`, + flattened: []string{"oneOf"}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + t.Parallel() + got, flattened, ok := FunctionParametersToInputSchema(json.RawMessage(tt.in)) + require.True(t, ok) + assert.Equal(t, tt.flattened, flattened) + if tt.flattened == nil { + assert.Equal(t, tt.want, string(got)) + return + } + assert.JSONEq(t, tt.want, string(got)) + }) + } +} diff --git a/relaykit/relayconvert/internal/toolconv/encode.go b/relaykit/relayconvert/internal/toolconv/encode.go index c5ff535851..ce5a8ee7d0 100644 --- a/relaykit/relayconvert/internal/toolconv/encode.go +++ b/relaykit/relayconvert/internal/toolconv/encode.go @@ -554,10 +554,17 @@ func attachClaudeRequest(request any, set Set, options *convmeta.Options) (any, return nil, diagnostics, err } diagnostics = append(diagnostics, schemaDiagnostics...) - inputSchema, ok := sharedclaude.FunctionParametersToInputSchema(parameters) + inputSchema, flattened, ok := sharedclaude.FunctionParametersToInputSchema(parameters) if !ok { return nil, diagnostics, fmt.Errorf("tools[%d].input_schema: function parameters must be a JSON object", index) } + if len(flattened) > 0 { + diagnostics = append(diagnostics, presentationLoss( + fmt.Sprintf("tools[%d].input_schema", index), + "claude_top_level_schema_union_flattened", + fmt.Sprintf("Claude input_schema does not support %s at the top level; the branches were merged into one object schema", strings.Join(flattened, ", ")), + )) + } tools = append(tools, &dto.Tool{ Name: definition.Function.Name, Description: definition.Function.Description, diff --git a/relaykit/relayconvert/internal/toolconv/policy_test.go b/relaykit/relayconvert/internal/toolconv/policy_test.go index e77e601721..ee276f2a02 100644 --- a/relaykit/relayconvert/internal/toolconv/policy_test.go +++ b/relaykit/relayconvert/internal/toolconv/policy_test.go @@ -279,3 +279,34 @@ func TestResponsesCustomToolNameConflictIsDropped(t *testing.T) { }) } } + +func TestResponsesFunctionWithTopLevelOneOfIsFlattenedForClaude(t *testing.T) { + t.Parallel() + + _, set, err := ExtractRequest(types.RelayFormatOpenAIResponses, codexResponsesToolsRequest(t, nil, map[string]any{ + "type": "function", + "name": "automation_update", + "parameters": map[string]any{ + "oneOf": []any{ + map[string]any{"type": "object", "properties": map[string]any{"id": map[string]any{"type": "string"}, "prompt": map[string]any{"type": "string"}}, "required": []any{"id", "prompt"}}, + map[string]any{"type": "object", "properties": map[string]any{"id": map[string]any{"type": "string"}, "paused": map[string]any{"type": "boolean"}}, "required": []any{"id", "paused"}}, + }, + }, + })) + require.NoError(t, err) + + out, diagnostics, err := AttachRequest(types.RelayFormatClaude, &dto.ClaudeRequest{Model: "claude-test"}, set, nil) + require.NoError(t, err) + functions, _ := attachedFunctions(t, out) + require.Len(t, functions, 3) + assert.Equal(t, map[string]any{ + "type": "object", + "properties": map[string]any{ + "id": map[string]any{"type": "string"}, + "prompt": map[string]any{"type": "string"}, + "paused": map[string]any{"type": "boolean"}, + }, + "required": []any{"id"}, + }, functions[2]["input_schema"]) + assert.True(t, hasDiagnosticCode(diagnostics, "claude_top_level_schema_union_flattened")) +}