fix(openai): guard null gemini generation config, non-object args, and snake_case fields

- Require numeric JSON types for Gemini generationConfig fields (and positive values for maxOutputTokens and candidateCount), and guard thinkingConfig level/budget types to avoid null coercion.
- Require object JSON values for functionCall.args before setting function.arguments so null or non-object arguments default to "{}".
- Support snake_case Gemini SDK fields for generation_config, thinking_config, function_declarations, parameters_json_schema, and tool_config with multi-name allowlist filtering.

Closes: #8113
This commit is contained in:
Luis Pater
2026-11-25 21:06:38 +08:00
parent 0c6681923c
commit dbd6729b90
2 changed files with 495 additions and 59 deletions

View File

@@ -30,34 +30,36 @@ func ConvertGeminiRequestToOpenAI(modelName string, inputRawJSON []byte, stream
// Model mapping
_ = outDoc.Set("model", modelName)
// Generation config mapping
if genConfig := root.Get("generationConfig"); genConfig.Exists() {
// Generation config mapping (supports both camelCase and snake_case Gemini SDK spellings)
if genConfig := firstGeminiObject(root, "generationConfig", "generation_config"); genConfig.Exists() {
// Temperature
if temp := genConfig.Get("temperature"); temp.Exists() {
if temp, ok := firstGeminiNumber(genConfig, "temperature"); ok {
_ = outDoc.Set("temperature", temp.Float())
}
// Max tokens
if maxTokens := genConfig.Get("maxOutputTokens"); maxTokens.Exists() {
if maxTokens, ok := firstGeminiNumber(genConfig, "maxOutputTokens", "max_output_tokens"); ok && maxTokens.Int() > 0 {
_ = outDoc.Set("max_tokens", maxTokens.Int())
}
// Top P
if topP := genConfig.Get("topP"); topP.Exists() {
if topP, ok := firstGeminiNumber(genConfig, "topP", "top_p"); ok {
_ = outDoc.Set("top_p", topP.Float())
}
// Top K (OpenAI doesn't have direct equivalent, but we can map it)
if topK := genConfig.Get("topK"); topK.Exists() {
if topK, ok := firstGeminiNumber(genConfig, "topK", "top_k"); ok {
// Store as custom parameter for potential use
_ = outDoc.Set("top_k", topK.Int())
}
// Stop sequences
if stopSequences := genConfig.Get("stopSequences"); stopSequences.Exists() && stopSequences.IsArray() {
if stopSequences := firstGeminiArray(genConfig, "stopSequences", "stop_sequences"); stopSequences.Exists() {
var stops []string
stopSequences.ForEach(func(_, value ojson.Result) bool {
stops = append(stops, value.String())
if value.Type == ojson.String {
stops = append(stops, value.String())
}
return true
})
if len(stops) > 0 {
@@ -66,13 +68,16 @@ func ConvertGeminiRequestToOpenAI(modelName string, inputRawJSON []byte, stream
}
// Candidate count (OpenAI 'n' parameter)
if candidateCount := genConfig.Get("candidateCount"); candidateCount.Exists() {
if candidateCount, ok := firstGeminiNumber(genConfig, "candidateCount", "candidate_count"); ok && candidateCount.Int() > 0 {
_ = outDoc.Set("n", candidateCount.Int())
}
if responseModalities := genConfig.Get("responseModalities"); responseModalities.Exists() && responseModalities.IsArray() {
if responseModalities := firstGeminiArray(genConfig, "responseModalities", "response_modalities"); responseModalities.Exists() {
var modalities []string
responseModalities.ForEach(func(_, value ojson.Result) bool {
if value.Type != ojson.String {
return true
}
switch strings.ToLower(strings.TrimSpace(value.String())) {
case "text":
modalities = append(modalities, "text")
@@ -90,27 +95,14 @@ func ConvertGeminiRequestToOpenAI(modelName string, inputRawJSON []byte, stream
// Map Gemini thinkingConfig to OpenAI reasoning_effort.
// Always perform conversion to support allowCompat models that may not be in registry.
// Note: Google official Python SDK sends snake_case fields (thinking_level/thinking_budget).
if thinkingConfig := genConfig.Get("thinkingConfig"); thinkingConfig.Exists() && thinkingConfig.IsObject() {
thinkingLevel := thinkingConfig.Get("thinkingLevel")
if !thinkingLevel.Exists() {
thinkingLevel = thinkingConfig.Get("thinking_level")
}
if thinkingLevel.Exists() {
effort := strings.ToLower(strings.TrimSpace(thinkingLevel.String()))
if effort != "" {
// Note: Google official Python SDK sends snake_case fields (thinking_config/thinking_level/thinking_budget).
if thinkingConfig := firstGeminiObject(genConfig, "thinkingConfig", "thinking_config"); thinkingConfig.Exists() {
if effort := strings.ToLower(firstGeminiNonEmptyString(thinkingConfig, "thinkingLevel", "thinking_level")); effort != "" {
_ = outDoc.Set("reasoning_effort", effort)
} else if thinkingBudget, ok := firstGeminiNumber(thinkingConfig, "thinkingBudget", "thinking_budget"); ok {
if effort, okConvert := thinking.ConvertBudgetToLevel(int(thinkingBudget.Int())); okConvert {
_ = outDoc.Set("reasoning_effort", effort)
}
} else {
thinkingBudget := thinkingConfig.Get("thinkingBudget")
if !thinkingBudget.Exists() {
thinkingBudget = thinkingConfig.Get("thinking_budget")
}
if thinkingBudget.Exists() {
if effort, ok := thinking.ConvertBudgetToLevel(int(thinkingBudget.Int())); ok {
_ = outDoc.Set("reasoning_effort", effort)
}
}
}
}
}
@@ -258,7 +250,7 @@ func ConvertGeminiRequestToOpenAI(modelName string, inputRawJSON []byte, stream
if functionCall := translatorcommon.GeminiPartFunctionCall(part); functionCall.Exists() {
funcName := functionCall.Get("name").String()
argsRaw := ""
if args := functionCall.Get("args"); args.Exists() {
if args := functionCall.Get("args"); args.IsObject() {
argsRaw = args.Raw
}
toolCallID := explicitGeminiToolID(functionCall)
@@ -452,55 +444,96 @@ func ConvertGeminiRequestToOpenAI(modelName string, inputRawJSON []byte, stream
translatorcommon.SetRawArrayItemsDoc(outDoc, "messages", messageItems)
// Tools mapping: Gemini tools -> OpenAI tools
type openAIToolEntry struct {
name string
raw []byte
}
var toolEntries []openAIToolEntry
if tools := root.Get("tools"); tools.Exists() && tools.IsArray() {
var toolItems [][]byte
tools.ForEach(func(_, tool ojson.Result) bool {
if functionDeclarations := tool.Get("functionDeclarations"); functionDeclarations.Exists() && functionDeclarations.IsArray() {
if functionDeclarations := firstGeminiArray(tool, "functionDeclarations", "function_declarations"); functionDeclarations.Exists() {
functionDeclarations.ForEach(func(_, funcDecl ojson.Result) bool {
funcName := funcDecl.Get("name").String()
openAIToolDoc := ojson.NewDocString(`{"type":"function","function":{"name":"","description":""}}`)
_ = openAIToolDoc.Set("function.name", funcDecl.Get("name").String())
_ = openAIToolDoc.Set("function.name", funcName)
_ = openAIToolDoc.Set("function.description", funcDecl.Get("description").String())
// Convert parameters schema
if parameters := funcDecl.Get("parameters"); parameters.Exists() {
normalizedParams := util.NormalizeJSONSchemaNumericConstraints(parameters.Raw)
_ = openAIToolDoc.SetRaw("function.parameters", normalizedParams)
} else if parameters := funcDecl.Get("parametersJsonSchema"); parameters.Exists() {
if parameters := firstGeminiObject(funcDecl, "parameters", "parametersJsonSchema", "parameters_json_schema"); parameters.Exists() {
normalizedParams := util.NormalizeJSONSchemaNumericConstraints(parameters.Raw)
_ = openAIToolDoc.SetRaw("function.parameters", normalizedParams)
}
toolItems = append(toolItems, openAIToolDoc.Bytes())
toolEntries = append(toolEntries, openAIToolEntry{
name: funcName,
raw: openAIToolDoc.Bytes(),
})
return true
})
}
return true
})
if len(toolItems) > 0 {
_ = outDoc.SetRawBytes("tools", translatorcommon.JoinRawArray(toolItems))
}
// Resolve tool choice and apply multi-tool allowlist filtering before serializing tools.
hadDeclaredTools := len(toolEntries) > 0
toolChoiceMode := ""
var allowedValidNames []string
allowedNameSet := make(map[string]struct{})
if functionCallingConfig := geminiFunctionCallingConfig(root); functionCallingConfig.Exists() {
if modeResult := functionCallingConfig.Get("mode"); modeResult.Type == ojson.String {
toolChoiceMode = strings.ToUpper(strings.TrimSpace(modeResult.String()))
if toolChoiceMode == "ANY" {
if allowedNames := firstGeminiArray(functionCallingConfig, "allowedFunctionNames", "allowed_function_names"); allowedNames.IsArray() {
for _, item := range allowedNames.Array() {
if item.Type != ojson.String {
continue
}
name := strings.TrimSpace(item.String())
if name == "" {
continue
}
if _, exists := allowedNameSet[name]; exists {
continue
}
allowedNameSet[name] = struct{}{}
allowedValidNames = append(allowedValidNames, name)
}
}
if len(allowedValidNames) > 1 && len(toolEntries) > 0 {
filtered := make([]openAIToolEntry, 0, len(toolEntries))
for _, entry := range toolEntries {
if _, okAllowed := allowedNameSet[entry.name]; okAllowed {
filtered = append(filtered, entry)
}
}
toolEntries = filtered
}
}
}
}
if len(toolEntries) > 0 {
toolItems := make([][]byte, 0, len(toolEntries))
for _, entry := range toolEntries {
toolItems = append(toolItems, entry.raw)
}
_ = outDoc.SetRawBytes("tools", translatorcommon.JoinRawArray(toolItems))
}
// Tool choice mapping (Gemini doesn't have direct equivalent, but we can handle it)
if toolConfig := root.Get("toolConfig"); toolConfig.Exists() {
if functionCallingConfig := toolConfig.Get("functionCallingConfig"); functionCallingConfig.Exists() {
mode := functionCallingConfig.Get("mode").String()
allowedNames := functionCallingConfig.Get("allowedFunctionNames")
switch mode {
case "NONE":
_ = outDoc.Set("tool_choice", "none")
case "AUTO":
_ = outDoc.Set("tool_choice", "auto")
case "ANY":
allowedNameItems := allowedNames.Array()
if allowedNames.IsArray() && len(allowedNameItems) == 1 {
choice := []byte(`{"type":"function","function":{"name":""}}`)
choice, _ = ojson.SetBytes(choice, "function.name", allowedNameItems[0].String())
_ = outDoc.SetRawBytes("tool_choice", choice)
} else {
_ = outDoc.Set("tool_choice", "required")
}
}
switch toolChoiceMode {
case "NONE":
_ = outDoc.Set("tool_choice", "none")
case "AUTO":
_ = outDoc.Set("tool_choice", "auto")
case "ANY":
if len(allowedValidNames) == 1 {
choiceDoc := ojson.NewDocString(`{"type":"function","function":{"name":""}}`)
_ = choiceDoc.Set("function.name", allowedValidNames[0])
_ = outDoc.SetRawBytes("tool_choice", choiceDoc.Bytes())
} else if !(len(allowedValidNames) > 1 && hadDeclaredTools && len(toolEntries) == 0) {
_ = outDoc.Set("tool_choice", "required")
}
}
@@ -512,12 +545,66 @@ func deterministicToolCallID(kind string, msgIdx, partIdx int, name, payload str
return "call_" + hex.EncodeToString(sum[:12])
}
func firstGeminiObject(obj ojson.Result, keys ...string) ojson.Result {
for _, key := range keys {
if v := obj.Get(key); v.IsObject() {
return v
}
}
return ojson.Result{}
}
func firstGeminiArray(obj ojson.Result, keys ...string) ojson.Result {
for _, key := range keys {
if v := obj.Get(key); v.IsArray() {
return v
}
}
return ojson.Result{}
}
func firstGeminiNumber(obj ojson.Result, keys ...string) (ojson.Result, bool) {
for _, key := range keys {
if v := obj.Get(key); v.Type == ojson.Number {
return v, true
}
}
return ojson.Result{}, false
}
func firstGeminiNonEmptyString(obj ojson.Result, keys ...string) string {
for _, key := range keys {
if v := obj.Get(key); v.Type == ojson.String {
if s := strings.TrimSpace(v.String()); s != "" {
return s
}
}
}
return ""
}
func geminiFunctionCallingConfig(root ojson.Result) ojson.Result {
for _, path := range []string{
"toolConfig.functionCallingConfig",
"toolConfig.function_calling_config",
"tool_config.function_calling_config",
"tool_config.functionCallingConfig",
} {
if cfg := root.Get(path); cfg.IsObject() {
return cfg
}
}
return ojson.Result{}
}
func geminiFunctionCallThoughtSignature(part ojson.Result) string {
for _, path := range []string{
"thoughtSignature",
"thought_signature",
"functionCall.thoughtSignature",
"functionCall.thought_signature",
"function_call.thoughtSignature",
"function_call.thought_signature",
"extra_content.google.thought_signature",
} {
if sig := part.Get(path); sig.Exists() && sig.String() != "" {

View File

@@ -910,3 +910,352 @@ func TestConvertGeminiRequestToOpenAI_NormalizesNumericProtoSchemaTypes_Issue803
}
}
}
func TestConvertGeminiRequestToOpenAI_SkipsNullAndInvalidGenerationConfigNumbers(t *testing.T) {
t.Run("null numeric fields are omitted", func(t *testing.T) {
inputJSON := []byte(`{
"contents": [{"role": "user", "parts": [{"text": "hello"}]}],
"generationConfig": {
"temperature": null,
"maxOutputTokens": null,
"topP": null,
"topK": null,
"candidateCount": null,
"thinkingConfig": {
"thinkingLevel": null,
"thinkingBudget": null
}
}
}`)
out, err := ConvertGeminiRequestToOpenAI("gpt-5", inputJSON, false)
if err != nil {
t.Fatalf("ConvertGeminiRequestToOpenAI returned error: %v", err)
}
for _, field := range []string{"temperature", "max_tokens", "top_p", "top_k", "n", "reasoning_effort"} {
if got := ojson.GetBytesNoCopy(out, field); got.Exists() {
t.Errorf("%s = %s, want omitted for null input; out=%s", field, got.Raw, string(out))
}
}
})
t.Run("non-positive maxOutputTokens and candidateCount are omitted while zero temperature and topP are kept", func(t *testing.T) {
inputJSON := []byte(`{
"contents": [{"role": "user", "parts": [{"text": "hello"}]}],
"generationConfig": {
"temperature": 0,
"maxOutputTokens": 0,
"topP": 0,
"topK": "bad",
"candidateCount": 0,
"thinkingConfig": {
"thinkingLevel": null,
"thinkingBudget": 4096
}
}
}`)
out, err := ConvertGeminiRequestToOpenAI("gpt-5", inputJSON, false)
if err != nil {
t.Fatalf("ConvertGeminiRequestToOpenAI returned error: %v", err)
}
if got := ojson.GetBytesNoCopy(out, "temperature"); !got.Exists() || got.Float() != 0 {
t.Errorf("temperature = %s, want 0", got.Raw)
}
if got := ojson.GetBytesNoCopy(out, "top_p"); !got.Exists() || got.Float() != 0 {
t.Errorf("top_p = %s, want 0", got.Raw)
}
for _, field := range []string{"max_tokens", "top_k", "n"} {
if got := ojson.GetBytesNoCopy(out, field); got.Exists() {
t.Errorf("%s = %s, want omitted; out=%s", field, got.Raw, string(out))
}
}
if got := ojson.GetBytesNoCopy(out, "reasoning_effort").String(); got != "medium" {
t.Errorf("reasoning_effort = %q, want %q when thinkingLevel is null and thinkingBudget is 4096; out=%s", got, "medium", string(out))
}
})
t.Run("null thinkingBudget is omitted while numeric zero maps to none", func(t *testing.T) {
nullBudgetOut, err := ConvertGeminiRequestToOpenAI("gpt-5", []byte(`{
"contents": [{"role": "user", "parts": [{"text": "hello"}]}],
"generationConfig": {
"maxOutputTokens": -1,
"candidateCount": -2,
"thinkingConfig": {"thinkingBudget": null}
}
}`), false)
if err != nil {
t.Fatalf("ConvertGeminiRequestToOpenAI returned error: %v", err)
}
for _, field := range []string{"max_tokens", "n", "reasoning_effort"} {
if got := ojson.GetBytesNoCopy(nullBudgetOut, field); got.Exists() {
t.Errorf("%s = %s, want omitted; out=%s", field, got.Raw, string(nullBudgetOut))
}
}
zeroBudgetOut, errZero := ConvertGeminiRequestToOpenAI("gpt-5", []byte(`{
"contents": [{"role": "user", "parts": [{"text": "hello"}]}],
"generation_config": {
"thinking_config": {"thinking_budget": 0}
}
}`), false)
if errZero != nil {
t.Fatalf("ConvertGeminiRequestToOpenAI returned error: %v", errZero)
}
if got := ojson.GetBytesNoCopy(zeroBudgetOut, "reasoning_effort").String(); got != "none" {
t.Errorf("reasoning_effort = %q, want none for numeric thinking_budget 0; out=%s", got, string(zeroBudgetOut))
}
})
}
func TestConvertGeminiRequestToOpenAI_DefaultsNonObjectFunctionCallArgsToEmptyObject(t *testing.T) {
tests := []struct {
name string
partJSON string
wantArgs string
}{
{name: "null args", partJSON: `{"functionCall":{"name":"lookup","args":null}}`, wantArgs: "{}"},
{name: "array args", partJSON: `{"functionCall":{"name":"lookup","args":[1,2]}}`, wantArgs: "{}"},
{name: "string args", partJSON: `{"functionCall":{"name":"lookup","args":"raw"}}`, wantArgs: "{}"},
{name: "number args", partJSON: `{"functionCall":{"name":"lookup","args":42}}`, wantArgs: "{}"},
{name: "omitted args", partJSON: `{"functionCall":{"name":"lookup"}}`, wantArgs: "{}"},
{name: "snake_case function_call null args", partJSON: `{"function_call":{"name":"lookup","args":null}}`, wantArgs: "{}"},
{name: "object args preserved", partJSON: `{"functionCall":{"name":"lookup","args":{"city":"Paris"}}}`, wantArgs: `{"city":"Paris"}`},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
inputJSON := []byte(`{"contents":[{"role":"model","parts":[` + tt.partJSON + `]}]}`)
out, err := ConvertGeminiRequestToOpenAI("gpt-5", inputJSON, false)
if err != nil {
t.Fatalf("ConvertGeminiRequestToOpenAI returned error: %v", err)
}
if got := ojson.GetBytesNoCopy(out, "messages.0.tool_calls.0.function.arguments").String(); got != tt.wantArgs {
t.Fatalf("function.arguments = %q, want %q; out=%s", got, tt.wantArgs, string(out))
}
})
}
}
func TestConvertGeminiRequestToOpenAI_SupportsSnakeCaseGeminiSDKFields(t *testing.T) {
inputJSON := []byte(`{
"contents": [{"role": "user", "parts": [{"text": "check weather"}]}],
"generation_config": {
"temperature": 0.4,
"max_output_tokens": 256,
"top_p": 0.85,
"top_k": 32,
"stop_sequences": ["END", "STOP"],
"candidate_count": 2,
"response_modalities": ["TEXT", "IMAGE"],
"thinking_config": {
"thinking_level": "HIGH"
}
},
"tools": [{
"function_declarations": [{
"name": "lookup_weather",
"description": "Look up weather",
"parameters": null,
"parameters_json_schema": {
"type": "object",
"properties": {
"city": {"type": "string"}
}
}
}]
}],
"tool_config": {
"function_calling_config": {
"mode": "ANY",
"allowed_function_names": ["lookup_weather"]
}
}
}`)
out, err := ConvertGeminiRequestToOpenAI("gpt-5", inputJSON, false)
if err != nil {
t.Fatalf("ConvertGeminiRequestToOpenAI returned error: %v", err)
}
if got := ojson.GetBytesNoCopy(out, "temperature").Float(); got != 0.4 {
t.Errorf("temperature = %v, want 0.4", got)
}
if got := ojson.GetBytesNoCopy(out, "max_tokens").Int(); got != 256 {
t.Errorf("max_tokens = %d, want 256", got)
}
if got := ojson.GetBytesNoCopy(out, "top_p").Float(); got != 0.85 {
t.Errorf("top_p = %v, want 0.85", got)
}
if got := ojson.GetBytesNoCopy(out, "top_k").Int(); got != 32 {
t.Errorf("top_k = %d, want 32", got)
}
if got := ojson.GetBytesNoCopy(out, "stop.0").String(); got != "END" {
t.Errorf("stop.0 = %q, want END", got)
}
if got := ojson.GetBytesNoCopy(out, "stop.1").String(); got != "STOP" {
t.Errorf("stop.1 = %q, want STOP", got)
}
if got := ojson.GetBytesNoCopy(out, "n").Int(); got != 2 {
t.Errorf("n = %d, want 2", got)
}
if got := ojson.GetBytesNoCopy(out, "modalities.0").String(); got != "text" {
t.Errorf("modalities.0 = %q, want text", got)
}
if got := ojson.GetBytesNoCopy(out, "modalities.1").String(); got != "image" {
t.Errorf("modalities.1 = %q, want image", got)
}
if got := ojson.GetBytesNoCopy(out, "reasoning_effort").String(); got != "high" {
t.Errorf("reasoning_effort = %q, want high", got)
}
if got := ojson.GetBytesNoCopy(out, "tools.0.function.name").String(); got != "lookup_weather" {
t.Errorf("tools.0.function.name = %q, want lookup_weather", got)
}
if got := ojson.GetBytesNoCopy(out, "tools.0.function.parameters.properties.city.type").String(); got != "string" {
t.Errorf("tools.0.function.parameters.properties.city.type = %q, want string", got)
}
if got := ojson.GetBytesNoCopy(out, "tool_choice.type").String(); got != "function" {
t.Errorf("tool_choice.type = %q, want function", got)
}
if got := ojson.GetBytesNoCopy(out, "tool_choice.function.name").String(); got != "lookup_weather" {
t.Errorf("tool_choice.function.name = %q, want lookup_weather", got)
}
t.Run("snake_case tool_config modes and mixed spellings", func(t *testing.T) {
cases := []struct {
name string
input string
wantPath string
wantVal string
}{
{
name: "snake NONE",
input: `{"contents":[{"role":"user","parts":[{"text":"hi"}]}],"tool_config":{"function_calling_config":{"mode":"NONE"}}}`,
wantPath: "tool_choice",
wantVal: "none",
},
{
name: "snake AUTO",
input: `{"contents":[{"role":"user","parts":[{"text":"hi"}]}],"tool_config":{"function_calling_config":{"mode":"AUTO"}}}`,
wantPath: "tool_choice",
wantVal: "auto",
},
{
name: "snake ANY multiple allowed_function_names",
input: `{"contents":[{"role":"user","parts":[{"text":"hi"}]}],"tool_config":{"function_calling_config":{"mode":"ANY","allowed_function_names":["a","b"]}}}`,
wantPath: "tool_choice",
wantVal: "required",
},
{
name: "mixed camel toolConfig with snake function_calling_config",
input: `{"contents":[{"role":"user","parts":[{"text":"hi"}]}],"toolConfig":{"function_calling_config":{"mode":"ANY","allowed_function_names":["only_tool"]}}}`,
wantPath: "tool_choice.function.name",
wantVal: "only_tool",
},
{
name: "snake ANY with non-string allowed_function_names falls back to required",
input: `{"contents":[{"role":"user","parts":[{"text":"hi"}]}],"tool_config":{"function_calling_config":{"mode":"ANY","allowed_function_names":[null,""]}}}`,
wantPath: "tool_choice",
wantVal: "required",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
gotOut, errConv := ConvertGeminiRequestToOpenAI("gpt-5", []byte(tc.input), false)
if errConv != nil {
t.Fatalf("ConvertGeminiRequestToOpenAI returned error: %v", errConv)
}
if got := ojson.GetBytesNoCopy(gotOut, tc.wantPath).String(); got != tc.wantVal {
t.Fatalf("%s = %q, want %q; out=%s", tc.wantPath, got, tc.wantVal, string(gotOut))
}
})
}
})
t.Run("multi-name allowed_function_names filters declared tools", func(t *testing.T) {
multiInput := []byte(`{
"contents": [{"role": "user", "parts": [{"text": "hi"}]}],
"tools": [{
"function_declarations": [
{"name": "a", "description": "Tool A"},
{"name": "b", "description": "Tool B"},
{"name": "c", "description": "Tool C"}
]
}],
"tool_config": {
"function_calling_config": {
"mode": "ANY",
"allowed_function_names": ["a", "b"]
}
}
}`)
gotOut, errConv := ConvertGeminiRequestToOpenAI("gpt-5", multiInput, false)
if errConv != nil {
t.Fatalf("ConvertGeminiRequestToOpenAI returned error: %v", errConv)
}
if got := ojson.GetBytesNoCopy(gotOut, "tool_choice").String(); got != "required" {
t.Fatalf("tool_choice = %q, want required; out=%s", got, string(gotOut))
}
gotTools := ojson.GetBytesNoCopy(gotOut, "tools").Array()
if len(gotTools) != 2 {
t.Fatalf("len(tools) = %d, want 2; out=%s", len(gotTools), string(gotOut))
}
if gotTools[0].Get("function.name").String() != "a" || gotTools[1].Get("function.name").String() != "b" {
t.Fatalf("filtered tool names = [%q, %q], want [a, b]; out=%s",
gotTools[0].Get("function.name").String(), gotTools[1].Get("function.name").String(), string(gotOut))
}
})
t.Run("multi-name allowed_function_names with no matching declared tools omits tools and tool_choice", func(t *testing.T) {
noMatchInput := []byte(`{
"contents": [{"role": "user", "parts": [{"text": "hi"}]}],
"tools": [{
"function_declarations": [
{"name": "c", "description": "Tool C"}
]
}],
"tool_config": {
"function_calling_config": {
"mode": "ANY",
"allowed_function_names": ["a", "b"]
}
}
}`)
gotOut, errConv := ConvertGeminiRequestToOpenAI("gpt-5", noMatchInput, false)
if errConv != nil {
t.Fatalf("ConvertGeminiRequestToOpenAI returned error: %v", errConv)
}
if ojson.GetBytesNoCopy(gotOut, "tools").Exists() {
t.Fatalf("tools should be omitted when no declared tools match allowlist; out=%s", string(gotOut))
}
if ojson.GetBytesNoCopy(gotOut, "tool_choice").Exists() {
t.Fatalf("tool_choice should be omitted when allowlist excludes all declared tools; out=%s", string(gotOut))
}
})
t.Run("camelCase functionDeclarations takes precedence without duplicating snake_case alias", func(t *testing.T) {
dualInput := []byte(`{
"contents": [{"role": "user", "parts": [{"text": "hi"}]}],
"tools": [{
"functionDeclarations": [{"name": "lookup", "description": "camel"}],
"function_declarations": [{"name": "lookup", "description": "snake"}]
}]
}`)
gotOut, errConv := ConvertGeminiRequestToOpenAI("gpt-5", dualInput, false)
if errConv != nil {
t.Fatalf("ConvertGeminiRequestToOpenAI returned error: %v", errConv)
}
gotTools := ojson.GetBytesNoCopy(gotOut, "tools").Array()
if len(gotTools) != 1 {
t.Fatalf("len(tools) = %d, want 1; out=%s", len(gotTools), string(gotOut))
}
if got := gotTools[0].Get("function.description").String(); got != "camel" {
t.Fatalf("tools.0.function.description = %q, want camel; out=%s", got, string(gotOut))
}
})
}