mirror of
https://github.com/Wei-Shaw/sub2api.git
synced 2026-12-05 16:07:33 +00:00
fix(gemini): send only Vertex Schema fields in tool parameters
Vertex rejects a function declaration whose parameters carry a keyword outside its Schema type: a live call with propertyNames returns 400 Unknown name "propertyNames" on every Gemini 4 model. zod-generated MCP tool schemas emit propertyNames for records, and Claude Code adds a deferred tool to tools[] once ToolSearch loads it, so every later request in the session fails with a 400. The cleaner now keeps only the fields of the Vertex v1 Schema type (https://docs.cloud.google.com/vertex-ai/docs/reference/rest/v1/Schema). The keywords it already dropped stay dropped. oneOf becomes anyOf when the node has no anyOf. A format value stays only when the reference lists it for the node's type. Every other dropped keyword is appended to the node's description as "[Constraint: key: value, ...]", in key order, the same hint shape as the antigravity schema cleaner. No tool is removed. Failure modes this commit guards against: - A non-Vertex keyword (propertyNames, not, if/then/else, allOf, prefixItems, contains, uniqueItems, multipleOf, exclusiveMaximum, unevaluated*, dependentSchemas, dependencies, ...) reaches parameters at any depth and Vertex returns 400. - oneOf is sent under its own name, or its branches are lost. - A format the reference does not list (uri, uuid) is sent, or a listed one (date, date-time, int64, double) is dropped. - A dropped constraint disappears without a trace for the model. - A property whose name equals a keyword (not, format, propertyNames) is dropped. - The same schema gives different request bytes on two turns, which breaks implicit prefix caching. - A tool is removed from functionDeclarations. Test changes: - TestCleanToolSchema_PreservesNestedOneOfCombinator becomes TestCleanToolSchema_MapsNestedOneOfToAnyOf: oneOf is not a Vertex Schema field, so the branches now arrive under anyOf. - TestCleanToolSchema_TraversesRetainedSchemaValuedKeywords becomes TestCleanToolSchema_DropsNonVertexSchemaValuedKeywordsIntoDescription: additionalItems, unevaluatedItems, unevaluatedProperties and dependencies are not Vertex Schema fields, so they move into the description hint. - New: gemini_messages_tool_schema_test.go.
This commit is contained in:
1 parent
f53641e53c
commit
b089e60895
3 files changed
+239
-58
No files matched your search
@@ -3909,6 +3909,23 @@ func cleanToolSchema(schema any) any {
|
||||
return cleanToolSchemaNode(schema, true)
|
||||
}
|
||||
|
||||
// vertexSchemaFields 是 Vertex AI v1 Schema 类型的字段,其它关键字会被上游以 400 拒收
|
||||
// (如 Unknown name "propertyNames"),见 https://docs.cloud.google.com/vertex-ai/docs/reference/rest/v1/Schema
|
||||
var vertexSchemaFields = map[string]bool{
|
||||
"type": true, "format": true, "title": true, "description": true, "nullable": true, "default": true,
|
||||
"items": true, "minItems": true, "maxItems": true, "enum": true, "properties": true, "propertyOrdering": true,
|
||||
"required": true, "minProperties": true, "maxProperties": true, "minimum": true, "maximum": true,
|
||||
"minLength": true, "maxLength": true, "pattern": true, "example": true, "anyOf": true,
|
||||
"additionalProperties": true, "ref": true, "defs": true,
|
||||
}
|
||||
|
||||
// vertexSchemaFormats 是同一参考页按类型列出的 format 取值。
|
||||
var vertexSchemaFormats = map[string]map[string]bool{
|
||||
"STRING": {"email": true, "byte": true, "date": true, "date-time": true, "password": true, "enum": true},
|
||||
"NUMBER": {"float": true, "double": true},
|
||||
"INTEGER": {"int32": true, "int64": true},
|
||||
}
|
||||
|
||||
func cleanToolSchemaNode(schema any, schemaNode bool) any {
|
||||
if schema == nil {
|
||||
return nil
|
||||
@@ -3925,6 +3942,7 @@ func cleanToolSchemaNode(schema any, schemaNode bool) any {
|
||||
}
|
||||
|
||||
cleaned := make(map[string]any)
|
||||
dropped := make(map[string]any)
|
||||
for key, value := range v {
|
||||
// 跳过不支持的字段
|
||||
if key == "$schema" || key == "$id" || key == "$ref" ||
|
||||
@@ -3934,9 +3952,22 @@ func cleanToolSchemaNode(schema any, schemaNode bool) any {
|
||||
key == "deprecated" || key == "examples" {
|
||||
continue
|
||||
}
|
||||
// const 在下方折算为 enum。
|
||||
if key == "const" {
|
||||
continue
|
||||
}
|
||||
if key == "oneOf" {
|
||||
if _, hasAnyOf := v["anyOf"]; !hasAnyOf {
|
||||
key = "anyOf"
|
||||
}
|
||||
}
|
||||
if !vertexSchemaFields[key] {
|
||||
dropped[key] = value
|
||||
continue
|
||||
}
|
||||
|
||||
switch key {
|
||||
case "properties", "dependentSchemas":
|
||||
case "properties", "defs":
|
||||
if propertySchemas, ok := value.(map[string]any); ok {
|
||||
cleanedProperties := make(map[string]any, len(propertySchemas))
|
||||
for propertyName, propertySchema := range propertySchemas {
|
||||
@@ -3946,24 +3977,9 @@ func cleanToolSchemaNode(schema any, schemaNode bool) any {
|
||||
} else {
|
||||
cleaned[key] = cleanToolSchemaNode(value, false)
|
||||
}
|
||||
case "items", "contains", "propertyNames", "if", "then", "else", "not", "contentSchema",
|
||||
"additionalItems", "unevaluatedItems", "unevaluatedProperties":
|
||||
case "items":
|
||||
cleaned[key] = cleanToolSchemaNode(value, true)
|
||||
case "dependencies":
|
||||
if dependencies, ok := value.(map[string]any); ok {
|
||||
cleanedDependencies := make(map[string]any, len(dependencies))
|
||||
for propertyName, dependency := range dependencies {
|
||||
if dependencySchema, ok := dependency.(map[string]any); ok {
|
||||
cleanedDependencies[propertyName] = cleanToolSchemaNode(dependencySchema, true)
|
||||
} else {
|
||||
cleanedDependencies[propertyName] = cleanToolSchemaNode(dependency, false)
|
||||
}
|
||||
}
|
||||
cleaned[key] = cleanedDependencies
|
||||
} else {
|
||||
cleaned[key] = cleanToolSchemaNode(value, false)
|
||||
}
|
||||
case "anyOf", "allOf", "oneOf", "prefixItems":
|
||||
case "anyOf":
|
||||
if schemas, ok := value.([]any); ok {
|
||||
cleanedSchemas := make([]any, len(schemas))
|
||||
for i, childSchema := range schemas {
|
||||
@@ -4028,6 +4044,14 @@ func cleanToolSchemaNode(schema any, schemaNode bool) any {
|
||||
}
|
||||
}
|
||||
}
|
||||
if format, ok := cleaned["format"].(string); ok {
|
||||
typeName, _ := cleaned["type"].(string)
|
||||
if !vertexSchemaFormats[typeName][format] {
|
||||
dropped["format"] = format
|
||||
delete(cleaned, "format")
|
||||
}
|
||||
}
|
||||
appendDroppedSchemaConstraints(cleaned, dropped)
|
||||
return cleaned
|
||||
case []any:
|
||||
cleaned := make([]any, len(v))
|
||||
@@ -4040,6 +4064,38 @@ func cleanToolSchemaNode(schema any, schemaNode bool) any {
|
||||
}
|
||||
}
|
||||
|
||||
// appendDroppedSchemaConstraints 把删掉的关键字以提示写进 description 末尾,模型仍能读到这些约束。
|
||||
// 按关键字排序,同一份 schema 每次得到相同的请求体。
|
||||
func appendDroppedSchemaConstraints(schema map[string]any, dropped map[string]any) {
|
||||
keys := make([]string, 0, len(dropped))
|
||||
for key := range dropped {
|
||||
if !strings.HasPrefix(key, "$") {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
}
|
||||
if len(keys) == 0 {
|
||||
return
|
||||
}
|
||||
sort.Strings(keys)
|
||||
hints := make([]string, 0, len(keys))
|
||||
for _, key := range keys {
|
||||
value, isString := dropped[key].(string)
|
||||
if !isString {
|
||||
encoded, err := json.Marshal(dropped[key])
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
value = string(encoded)
|
||||
}
|
||||
hints = append(hints, key+": "+value)
|
||||
}
|
||||
hint := "[Constraint: " + strings.Join(hints, ", ") + "]"
|
||||
if description, _ := schema["description"].(string); strings.TrimSpace(description) != "" {
|
||||
hint = description + " " + hint
|
||||
}
|
||||
schema["description"] = hint
|
||||
}
|
||||
|
||||
func normalizeGeminiEnum(values []any) ([]any, bool) {
|
||||
normalized := make([]any, len(values))
|
||||
for i, value := range values {
|
||||
|
||||
@@ -589,57 +589,37 @@ func TestCleanToolSchema_NormalizesConstAndExamplesAtNestedSchemaNodes(t *testin
|
||||
require.NotContains(t, secondBranch, "examples")
|
||||
}
|
||||
|
||||
func TestCleanToolSchema_TraversesRetainedSchemaValuedKeywords(t *testing.T) {
|
||||
func TestCleanToolSchema_DropsNonVertexSchemaValuedKeywordsIntoDescription(t *testing.T) {
|
||||
schema := map[string]any{
|
||||
"type": "object",
|
||||
"additionalItems": map[string]any{
|
||||
"type": "string",
|
||||
"const": "additional",
|
||||
"examples": []any{"additional example"},
|
||||
"type": "string",
|
||||
"const": "additional",
|
||||
},
|
||||
"unevaluatedItems": map[string]any{
|
||||
"type": "string",
|
||||
"const": "unevaluated item",
|
||||
"examples": []any{"item example"},
|
||||
"type": "string",
|
||||
"const": "unevaluated item",
|
||||
},
|
||||
"unevaluatedProperties": map[string]any{
|
||||
"type": "string",
|
||||
"const": "unevaluated property",
|
||||
"examples": []any{"property example"},
|
||||
"type": "string",
|
||||
"const": "unevaluated property",
|
||||
},
|
||||
"dependencies": map[string]any{
|
||||
"schema dependency": map[string]any{
|
||||
"type": "string",
|
||||
"const": "dependency",
|
||||
"examples": []any{"dependency example"},
|
||||
},
|
||||
"required dependency": []any{"first", "second"},
|
||||
},
|
||||
}
|
||||
|
||||
cleaned, ok := cleanToolSchema(schema).(map[string]any)
|
||||
require.True(t, ok)
|
||||
expectedEnums := map[string][]any{
|
||||
"additionalItems": {"additional"},
|
||||
"unevaluatedItems": {"unevaluated item"},
|
||||
"unevaluatedProperties": {"unevaluated property"},
|
||||
for _, keyword := range []string{"additionalItems", "unevaluatedItems", "unevaluatedProperties", "dependencies"} {
|
||||
require.NotContains(t, cleaned, keyword)
|
||||
}
|
||||
for keyword, expectedEnum := range expectedEnums {
|
||||
child, ok := cleaned[keyword].(map[string]any)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, expectedEnum, child["enum"])
|
||||
require.NotContains(t, child, "const")
|
||||
require.NotContains(t, child, "examples")
|
||||
}
|
||||
|
||||
dependencies, ok := cleaned["dependencies"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
dependencySchema, ok := dependencies["schema dependency"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, []any{"dependency"}, dependencySchema["enum"])
|
||||
require.NotContains(t, dependencySchema, "const")
|
||||
require.NotContains(t, dependencySchema, "examples")
|
||||
require.Equal(t, []any{"first", "second"}, dependencies["required dependency"])
|
||||
require.Equal(t,
|
||||
`[Constraint: additionalItems: {"const":"additional","type":"string"}, `+
|
||||
`dependencies: {"required dependency":["first","second"]}, `+
|
||||
`unevaluatedItems: {"const":"unevaluated item","type":"string"}, `+
|
||||
`unevaluatedProperties: {"const":"unevaluated property","type":"string"}]`,
|
||||
cleaned["description"])
|
||||
}
|
||||
|
||||
func TestCleanToolSchema_IntersectsStringConstWithEnum(t *testing.T) {
|
||||
@@ -699,7 +679,7 @@ func TestCleanToolSchema_DropsNonStringConstAndRetainsExistingTypeAndEnum(t *tes
|
||||
require.Equal(t, []any{"8"}, cleaned["enum"])
|
||||
}
|
||||
|
||||
func TestCleanToolSchema_PreservesNestedOneOfCombinator(t *testing.T) {
|
||||
func TestCleanToolSchema_MapsNestedOneOfToAnyOf(t *testing.T) {
|
||||
schema := map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
@@ -718,12 +698,13 @@ func TestCleanToolSchema_PreservesNestedOneOfCombinator(t *testing.T) {
|
||||
require.True(t, ok)
|
||||
valueSchema, ok := properties["value"].(map[string]any)
|
||||
require.True(t, ok)
|
||||
oneOf, ok := valueSchema["oneOf"].([]any)
|
||||
require.NotContains(t, valueSchema, "oneOf")
|
||||
anyOf, ok := valueSchema["anyOf"].([]any)
|
||||
require.True(t, ok)
|
||||
require.Len(t, oneOf, 2)
|
||||
firstBranch, ok := oneOf[0].(map[string]any)
|
||||
require.Len(t, anyOf, 2)
|
||||
firstBranch, ok := anyOf[0].(map[string]any)
|
||||
require.True(t, ok)
|
||||
secondBranch, ok := oneOf[1].(map[string]any)
|
||||
secondBranch, ok := anyOf[1].(map[string]any)
|
||||
require.True(t, ok)
|
||||
require.Equal(t, []any{"a"}, firstBranch["enum"])
|
||||
require.Equal(t, []any{"b"}, secondBranch["enum"])
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
//go:build unit
|
||||
|
||||
package service
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestCleanToolSchema_KeepsOnlyVertexSchemaFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
schema string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "record with propertyNames",
|
||||
schema: `{"type":"object","propertyNames":{"type":"string"},"additionalProperties":{"type":"string"}}`,
|
||||
want: `{"type":"OBJECT","description":"[Constraint: propertyNames: {\"type\":\"string\"}]"}`,
|
||||
},
|
||||
{
|
||||
name: "discriminated union oneOf becomes anyOf",
|
||||
schema: `{"oneOf":[{"type":"object","properties":{"action":{"type":"string","const":"click"}}},{"type":"object","properties":{"action":{"type":"string","const":"type"}}}]}`,
|
||||
want: `{"anyOf":[{"type":"OBJECT","properties":{"action":{"type":"STRING","enum":["click"]}}},{"type":"OBJECT","properties":{"action":{"type":"STRING","enum":["type"]}}}]}`,
|
||||
},
|
||||
{
|
||||
name: "oneOf next to anyOf is dropped into the description",
|
||||
schema: `{"anyOf":[{"type":"string"}],"oneOf":[{"type":"number"}]}`,
|
||||
want: `{"anyOf":[{"type":"STRING"}],"description":"[Constraint: oneOf: [{\"type\":\"number\"}]]"}`,
|
||||
},
|
||||
{
|
||||
name: "only listed formats survive",
|
||||
schema: `{"type":"object","properties":{"url":{"type":"string","format":"uri"},"id":{"type":"string","format":"uuid","description":"Row id."},"day":{"type":"string","format":"date"},"at":{"type":"string","format":"date-time"},"n":{"type":"integer","format":"int64"},"x":{"type":"number","format":"double"},"wrongType":{"type":"integer","format":"float"},"untyped":{"format":"date"}}}`,
|
||||
want: `{"type":"OBJECT","properties":{` +
|
||||
`"url":{"type":"STRING","description":"[Constraint: format: uri]"},` +
|
||||
`"id":{"type":"STRING","description":"Row id. [Constraint: format: uuid]"},` +
|
||||
`"day":{"type":"STRING","format":"date"},` +
|
||||
`"at":{"type":"STRING","format":"date-time"},` +
|
||||
`"n":{"type":"INTEGER","format":"int64"},` +
|
||||
`"x":{"type":"NUMBER","format":"double"},` +
|
||||
`"wrongType":{"type":"INTEGER","description":"[Constraint: format: float]"},` +
|
||||
`"untyped":{"description":"[Constraint: format: date]"}}}`,
|
||||
},
|
||||
{
|
||||
name: "conditional and composition keywords",
|
||||
schema: `{"type":"object","description":"Pick one.","properties":{"a":{"type":"string"}},"if":{"required":["a"]},"then":{"required":["b"]},"else":{"required":["c"]},"not":{"required":["d"]},"allOf":[{"required":["a"]}],"dependentSchemas":{"a":{"required":["b"]}}}`,
|
||||
want: `{"type":"OBJECT","properties":{"a":{"type":"STRING"}},"description":"Pick one. [Constraint: ` +
|
||||
`allOf: [{\"required\":[\"a\"]}], dependentSchemas: {\"a\":{\"required\":[\"b\"]}}, else: {\"required\":[\"c\"]}, ` +
|
||||
`if: {\"required\":[\"a\"]}, not: {\"required\":[\"d\"]}, then: {\"required\":[\"b\"]}]"}`,
|
||||
},
|
||||
{
|
||||
name: "array and number constraints nested under items",
|
||||
schema: `{"type":"array","items":{"type":"number","minimum":0,"maximum":10,"multipleOf":0.5,"exclusiveMaximum":10},"prefixItems":[{"type":"string"}],"contains":{"type":"number"},"uniqueItems":true}`,
|
||||
want: `{"type":"ARRAY","items":{"type":"NUMBER","minimum":0,"maximum":10,"description":"[Constraint: exclusiveMaximum: 10, multipleOf: 0.5]"},` +
|
||||
`"description":"[Constraint: contains: {\"type\":\"number\"}, prefixItems: [{\"type\":\"string\"}], uniqueItems: true]"}`,
|
||||
},
|
||||
{
|
||||
name: "properties named like keywords stay",
|
||||
schema: `{"type":"object","properties":{"not":{"type":"boolean"},"format":{"type":"string"},"propertyNames":{"type":"array","items":{"type":"string"}}},"required":["not"]}`,
|
||||
want: `{"type":"OBJECT","properties":{"not":{"type":"BOOLEAN"},"format":{"type":"STRING"},"propertyNames":{"type":"ARRAY","items":{"type":"STRING"}}},"required":["not"]}`,
|
||||
},
|
||||
{
|
||||
name: "meta keywords are dropped without a hint",
|
||||
schema: `{"type":"string","$comment":"internal","title":"Name","nullable":true,"default":"x","example":"y","pattern":"^a"}`,
|
||||
want: `{"type":"STRING","title":"Name","nullable":true,"default":"x","example":"y","pattern":"^a"}`,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
var schema any
|
||||
require.NoError(t, json.Unmarshal([]byte(tt.schema), &schema))
|
||||
got, err := json.Marshal(cleanToolSchema(schema))
|
||||
require.NoError(t, err)
|
||||
require.JSONEq(t, tt.want, string(got))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// requireOnlyVertexSchemaFields 断言 schema 每个节点只剩 Vertex Schema 字段。
|
||||
func requireOnlyVertexSchemaFields(t *testing.T, path string, node any) {
|
||||
t.Helper()
|
||||
schema, ok := node.(map[string]any)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if format, ok := schema["format"]; ok {
|
||||
typeName, _ := schema["type"].(string)
|
||||
require.True(t, vertexSchemaFormats[typeName][format.(string)], "%s: format %v not listed for %s", path, format, typeName)
|
||||
}
|
||||
for key, value := range schema {
|
||||
require.True(t, vertexSchemaFields[key], "%s: non-Vertex key %q", path, key)
|
||||
switch key {
|
||||
case "properties", "defs":
|
||||
for name, child := range value.(map[string]any) {
|
||||
requireOnlyVertexSchemaFields(t, path+"."+key+"."+name, child)
|
||||
}
|
||||
case "items":
|
||||
requireOnlyVertexSchemaFields(t, path+".items", value)
|
||||
case "anyOf":
|
||||
for _, child := range value.([]any) {
|
||||
requireOnlyVertexSchemaFields(t, path+".anyOf", child)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestConvertClaudeToolsToGeminiTools_SendsOnlyVertexSchemaFieldsAndKeepsEveryTool(t *testing.T) {
|
||||
// Shapes that zod-generated MCP tool schemas produce, plus a deferred tool.
|
||||
toolsJSON := `[
|
||||
{"name":"render_flow","description":"Render a flow.","input_schema":{"$schema":"http://json-schema.org/draft-07/schema#","type":"object","properties":{
|
||||
"vars":{"type":"object","propertyNames":{"type":"string"},"additionalProperties":{"type":"string","minLength":1}},
|
||||
"steps":{"type":"array","minItems":1,"uniqueItems":true,"contains":{"type":"object"},"maxContains":3,"items":{"oneOf":[
|
||||
{"type":"object","properties":{"action":{"type":"string","const":"click"},"target":{"type":"string","format":"uri"}},"required":["action","target"],"additionalProperties":false},
|
||||
{"type":"object","properties":{"action":{"type":"string","const":"wait"},"ms":{"type":"integer","exclusiveMinimum":0,"maximum":60000}},"required":["action","ms"]}
|
||||
]}},
|
||||
"runId":{"type":"string","format":"uuid"}
|
||||
},"required":["steps"],"additionalProperties":false}},
|
||||
{"name":"Read","description":"Read a file.","input_schema":{"type":"object","properties":{"file_path":{"type":"string"},"limit":{"type":"integer","exclusiveMinimum":0}},"required":["file_path"]}},
|
||||
{"name":"DeferredToolPlaceholder","description":"Placeholder.","defer_loading":true,"input_schema":{"type":"object","properties":{}}}
|
||||
]`
|
||||
var tools []any
|
||||
require.NoError(t, json.Unmarshal([]byte(toolsJSON), &tools))
|
||||
|
||||
first := convertClaudeToolsToGeminiTools(tools)
|
||||
firstJSON, err := json.Marshal(first)
|
||||
require.NoError(t, err)
|
||||
require.Contains(t, string(firstJSON), `[Constraint: contains: {\"type\":\"object\"}, maxContains: 3, uniqueItems: true]`)
|
||||
for i := 0; i < 20; i++ {
|
||||
again, err := json.Marshal(convertClaudeToolsToGeminiTools(tools))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, string(firstJSON), string(again), "the same tools must produce the same request bytes")
|
||||
}
|
||||
|
||||
require.Len(t, first, 1)
|
||||
decls := first[0].(map[string]any)["functionDeclarations"].([]any)
|
||||
require.Len(t, decls, 3)
|
||||
for _, decl := range decls {
|
||||
d := decl.(map[string]any)
|
||||
requireOnlyVertexSchemaFields(t, d["name"].(string), d["parameters"])
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user