Skip to content

Add support for tool_choice for Gemini - #1269

Merged
ystknsh merged 5 commits into
receptron:mainfrom
masap:fix-1268
Jan 28, 2026
Merged

ystknsh merged 5 commits into
receptron:mainfrom
masap:fix-1268

Conversation

@masap

@masap masap commented Jan 25, 2026 •

Copy link
Copy Markdown
Contributor

Resolves #1268.

Summary by CodeRabbit

  • New Features

    • Added a tool_choice setting to control Gemini agent function-calling modes ("auto", "any", "none", "validated") and to tailor allowed tool usage; invalid or unspecified values will leave tool behavior unchanged and emit a warning.
  • Tests

    • Updated tests for the new modes and added a test verifying tools are not invoked when "none" is selected.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Jan 25, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Adds an optional tool_choice input to the Gemini agent, mapping values ("auto", "any", "none", "validated") to FunctionCallingConfigMode and, when applicable, populating generationConfig.toolConfig with mode and allowed function names derived from available tools; tests updated to exercise behaviors.

Changes

Cohort / File(s) Summary
Types / Declarations
llm_agents/gemini_agent/lib/gemini_agent.d.ts
Added tool_choice?: string to exported GeminiInputs.
Runtime Implementation
llm_agents/gemini_agent/src/gemini_agent.ts, llm_agents/gemini_agent/lib/gemini_agent.js
Introduced parsing of tool_choice; map `"auto"
Tests
llm_agents/gemini_agent/tests/run_gemini.ts
Updated tests to include tool_choice: "any" for tool-enabled scenarios; added a new test with tool_choice: "none" ensuring tools are not invoked.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant Client
  participant GeminiAgent
  participant Tools
  participant Model

  Client->>GeminiAgent: call with inputs (prompt, tool_choice, tools, ...)
  GeminiAgent->>GeminiAgent: map tool_choice -> FunctionCallingConfigMode
  GeminiAgent->>Tools: enumerate available tool names
  GeminiAgent->>GeminiAgent: build generationConfig.toolConfig (mode, allowedFunctionNames)
  GeminiAgent->>Model: send generation request with generationConfig
  Model->>GeminiAgent: response (may include function call)
  alt Model requested a function call and mode allows
    GeminiAgent->>Tools: dispatch function call
    Tools->>GeminiAgent: return function result
    GeminiAgent->>Client: return final response
  else No function call or not allowed
    GeminiAgent->>Client: return model response
  end
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

Poem

"I twitch my whiskers, tap the keys, 🐇
tool_choice decides which tools to please,
'any', 'none', 'validated' in hand—
Gemini answers at my command,
Hoppity-hop, the tests expand!"

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly and clearly describes the main change: adding support for the tool_choice parameter for Gemini, which is the primary focus of all code modifications.
Linked Issues check ✅ Passed The code changes implement tool_choice support for Gemini as required by issue #1268, mapping values to FunctionCallingConfigMode and configuring toolConfig appropriately with allowedFunctionNames for ANY/VALIDATED modes.
Out of Scope Changes check ✅ Passed All changes are directly related to implementing tool_choice support for Gemini; test updates add tool_choice parameter usage and a new test for the 'none' mode, which are within scope.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@isamu
isamu requested a review from ystknsh January 25, 2026 09:21
@ystknsh

ystknsh commented Jan 26, 2026

Copy link
Copy Markdown
Contributor

Thanks for the PR! Two requests:

1. allowedFunctionNames configuration

Currently, the code sends allowedFunctionNames for all tool_choice values, but Gemini API only accepts it when mode is ANY.

Please modify to set allowedFunctionNames only when tool_choice === "any".

  Error [ApiError]: {"error":{"message":"{\n  \"error\": {\n    \"code\": 400,\n    \"message\": \"Please set allowed_function_names only when function calling mode is ANY.\",\n    \"status\": \"INVALID_ARGUMENT\"\n  }\n}\n","code":400,"status":"Bad Request"}}

2. Restore test log

Please restore the console.log('tool_calls.length: ...') that was previously added to test gemini multiple tools.

@masap

masap commented Jan 26, 2026

Copy link
Copy Markdown
Contributor Author

@ystknsh Thank you for comments!

  1. allowedFunctionNames configuration

According to official document [1], we can specify allowed_function_names with ANY and VALIDATED. I fixed the code.

  1. Restore test log

I already set tool_choice: "any" to test gemini multiple tools test. With this configuration, I expect Gemini to always call the function twice. Are you experiencing an issue where it doesn't call it twice in your environment?

[1] https://ai.google.dev/gemini-api/docs/function-calling?example=meeting#function_calling_modes

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🤖 Fix all issues with AI agents
In `@llm_agents/gemini_agent/lib/gemini_agent.js`:
- Around line 113-125: The compiled JS sets
generationConfig.toolConfig.functionCallingConfig.allowedFunctionNames for modes
other than ANY; update the logic so allowedFunctionNames is only assigned when
mode === genai_1.FunctionCallingConfigMode.ANY (use tools?.map(tool =>
tool.function.name) only in that branch) and leave it unset for other modes,
then rebuild/regenerate the compiled file so gemini_agent.js reflects the
corrected TypeScript change; key symbols: generationConfig,
functionCallingConfig, allowedFunctionNames, mode,
genai_1.FunctionCallingConfigMode, tools.

In `@llm_agents/gemini_agent/src/gemini_agent.ts`:
- Around line 179-190: The code sets
generationConfig.toolConfig.functionCallingConfig.allowedFunctionNames for both
ANY and VALIDATED modes which violates Gemini API (allowedFunctionNames must
only be present when mode === FunctionCallingConfigMode.ANY); update the logic
around functionNames and building generationConfig.toolConfig so that
allowedFunctionNames is only added to the functionCallingConfig when mode ===
FunctionCallingConfigMode.ANY (keep the mapping that builds functionNames from
tools?.map(...), but only include allowedFunctionNames in the config when mode
is ANY and omit it entirely for VALIDATED, AUTO, NONE), ensuring you adjust the
block that assigns generationConfig.toolConfig and reference
FunctionCallingConfigMode, mode, functionNames, and generationConfig.toolConfig
in your change.
🧹 Nitpick comments (2)
llm_agents/gemini_agent/src/gemini_agent.ts (1)

288-303: Add tool_choice to the inputs schema.

The tool_choice parameter is now a valid input but is missing from the inputs.properties schema. This should be added for documentation and validation purposes.

📝 Proposed addition
       messages: {
         anyOf: [{ type: "string" }, { type: "integer" }, { type: "object" }, { type: "array" }],
         description: "chat messages",
       },
+      tool_choice: {
+        type: "string",
+        description: "Tool choice mode: 'auto', 'any', 'none', or 'validated'",
+      },
     },
llm_agents/gemini_agent/lib/gemini_agent.js (1)

216-232: Missing tool_choice in inputs schema (same as TypeScript source).

As noted in the TypeScript source review, tool_choice should be added to the inputs properties for documentation completeness.

Comment on lines +113 to +125
else {
const functionNames = mode === genai_1.FunctionCallingConfigMode.ANY || mode === genai_1.FunctionCallingConfigMode.VALIDATED
? tools?.map((tool) => {
return tool.function.name;
})
: [];
generationConfig.toolConfig = {
functionCallingConfig: {
mode: mode,
allowedFunctionNames: functionNames,
},
};
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Same issue as TypeScript source: allowedFunctionNames handling.

This compiled output reflects the same issue identified in the TypeScript source file. Once the source is corrected to only set allowedFunctionNames when mode is ANY, this file should be regenerated.

🤖 Prompt for AI Agents
In `@llm_agents/gemini_agent/lib/gemini_agent.js` around lines 113 - 125, The
compiled JS sets
generationConfig.toolConfig.functionCallingConfig.allowedFunctionNames for modes
other than ANY; update the logic so allowedFunctionNames is only assigned when
mode === genai_1.FunctionCallingConfigMode.ANY (use tools?.map(tool =>
tool.function.name) only in that branch) and leave it unset for other modes,
then rebuild/regenerate the compiled file so gemini_agent.js reflects the
corrected TypeScript change; key symbols: generationConfig,
functionCallingConfig, allowedFunctionNames, mode,
genai_1.FunctionCallingConfigMode, tools.

Comment on lines +179 to +190
const functionNames =
mode === FunctionCallingConfigMode.ANY || mode === FunctionCallingConfigMode.VALIDATED
? tools?.map((tool: any) => {
return tool.function.name;
})
: [];
generationConfig.toolConfig = {
functionCallingConfig: {
mode: mode,
allowedFunctionNames: functionNames,
},
};

@coderabbitai coderabbitai Bot Jan 26, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🌐 Web query:

Gemini API allowedFunctionNames function calling mode ANY requirement documentation

💡 Result:

In the Gemini API function calling config, mode: "ANY" means the model is forced to return a function call (not normal text) and will adhere to the function schema. allowedFunctionNames (a.k.a. allowed_function_names) is optional in mode ANY:

  • If you do not set allowedFunctionNames, the model may choose any of the functions you provided in function_declarations. [1]
  • If you do set allowedFunctionNames, the model is restricted to calling only one of the named functions in that list. [1], [3]

Protocol/SDK reference notes: allowed_function_names is an optional field and “should only be set when the Mode is ANY” (i.e., don’t use it for AUTO/NONE). [2]

Sources: Gemini API function calling docs [1], Generative Language API FunctionCallingConfig reference (Go/proto) [2], Vertex AI function calling mode reference [3].


🌐 Web query:

Gemini API functionCallingConfig allowedFunctionNames supported modes

💡 Result:

In the Gemini API (toolConfig.functionCallingConfig / function_calling_config), the supported mode values are: AUTO (default), ANY, NONE, and VALIDATED (Preview). [1]

allowedFunctionNames (a.k.a. allowed_function_names) is an optional allowlist of function names (must match your FunctionDeclaration.name). Behavior depends on mode:

  • ANY: model is forced to return a function call; if allowedFunctionNames is set, it can only pick from that list; if omitted/empty, it can pick from any provided function declaration. [1]
  • AUTO: model decides between text vs function call. [1]
  • NONE: model will not call functions (same as sending no tools). [1]
  • VALIDATED (Preview): model may return text or function calls, but with schema adherence; allowedFunctionNames restricts selection similarly when provided. [1]

(For Vertex AI’s FunctionCallingMode enum, the documented modes are AUTO, ANY, NONE; and allowedFunctionNames is described as applicable when mode is ANY.) [5] [7]


allowedFunctionNames should only be set when mode is ANY.

The Gemini API documentation explicitly states that allowedFunctionNames should only be set when the function calling mode is ANY. The current implementation incorrectly includes VALIDATED mode in the condition and sets an empty array for AUTO and NONE modes, both of which violate the API requirement and will cause 400 errors.

The allowedFunctionNames property must be conditionally included only when mode is ANY, as shown in the proposed fix.

🔧 Proposed fix
     } else {
-      const functionNames =
-        mode === FunctionCallingConfigMode.ANY || mode === FunctionCallingConfigMode.VALIDATED
-          ? tools?.map((tool: any) => {
-              return tool.function.name;
-            })
-          : [];
-      generationConfig.toolConfig = {
-        functionCallingConfig: {
-          mode: mode,
-          allowedFunctionNames: functionNames,
-        },
-      };
+      const functionCallingConfig: { mode: FunctionCallingConfigMode; allowedFunctionNames?: string[] } = {
+        mode: mode,
+      };
+      if (mode === FunctionCallingConfigMode.ANY) {
+        functionCallingConfig.allowedFunctionNames = tools?.map((tool: any) => tool.function.name);
+      }
+      generationConfig.toolConfig = {
+        functionCallingConfig,
+      };
     }
🤖 Prompt for AI Agents
In `@llm_agents/gemini_agent/src/gemini_agent.ts` around lines 179 - 190, The code
sets generationConfig.toolConfig.functionCallingConfig.allowedFunctionNames for
both ANY and VALIDATED modes which violates Gemini API (allowedFunctionNames
must only be present when mode === FunctionCallingConfigMode.ANY); update the
logic around functionNames and building generationConfig.toolConfig so that
allowedFunctionNames is only added to the functionCallingConfig when mode ===
FunctionCallingConfigMode.ANY (keep the mapping that builds functionNames from
tools?.map(...), but only include allowedFunctionNames in the config when mode
is ANY and omit it entirely for VALIDATED, AUTO, NONE), ensuring you adjust the
block that assigns generationConfig.toolConfig and reference
FunctionCallingConfigMode, mode, functionNames, and generationConfig.toolConfig
in your change.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The allowedFunctionNames property must be conditionally included only when mode is ANY, as shown in the proposed fix.

According to document [1], allowed_function_names could be used with ANY and VALIDATED.

[1] https://ai.google.dev/gemini-api/docs/function-calling?example=meeting#function_calling_modes

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Fetch the Gemini API documentation about function calling modes
curl -s "https://ai.google.dev/gemini-api/docs/function-calling?example=meeting" | python3 -c "
import sys
import re
from html.parser import HTMLParser

class ContentExtractor(HTMLParser):
    def __init__(self):
        super().__init__()
        self.in_content = False
        self.content = []
        self.capture_level = 0
        
    def handle_starttag(self, tag, attrs):
        if tag in ['h1', 'h2', 'h3', 'h4', 'p', 'li', 'code', 'pre']:
            self.in_content = True
            self.capture_level += 1
    
    def handle_endtag(self, tag):
        if tag in ['h1', 'h2', 'h3', 'h4', 'p', 'li', 'code', 'pre']:
            self.capture_level -= 1
            if self.capture_level == 0:
                self.in_content = False
                self.content.append('\n')
    
    def handle_data(self, data):
        if self.in_content:
            self.content.append(data)

html = sys.stdin.read()
parser = ContentExtractor()
parser.feed(html)
text = ''.join(parser.content)

# Find the section about function calling modes
lines = text.split('\n')
mode_section = []
capture = False
for line in lines:
    if 'function calling mode' in line.lower() or 'allowed_function_names' in line.lower():
        capture = True
    if capture:
        mode_section.append(line)
        if len(mode_section) > 100:  # Limit output
            break

print('\n'.join(mode_section))
"

Length of output: 3171


🌐 Web query:

Gemini API allowed_function_names VALIDATED mode function calling

💡 Result:

In the Gemini API, allowed_function_names is supported in VALIDATED mode (currently Preview) to restrict which declared tools/functions the model is allowed to call. In VALIDATED, the model may return either natural language or a function call, but any function call is generated with schema adherence (“constrained decoding/validation”). If you don’t set allowed_function_names, the model can choose from all provided function declarations. [1][2][3]

Example (Python SDK style):

  • Set mode="VALIDATED"
  • Optionally set allowed_function_names=["your_func_name", ...] [1]

Notes on confusion you may see:

  • Some older/other surfaces (for example certain v1alpha Generative Language docs) document allowed_function_names as “only set when ANY” and don’t include VALIDATED, because that surface/version didn’t expose VALIDATED yet. [5]

Sources: Gemini function calling modes (including VALIDATED + allowed_function_names) [1]; Vertex AI/Generative AI proto reference showing allowed_function_names behavior for ANY and VALIDATED [2]; Python API types doc stating allowed_function_names applies to ANY or VALIDATED [3]; older v1alpha types doc showing only ANY/no VALIDATED [5].


@masap, you are absolutely correct, and I apologize for the confusion in my initial review.

According to the latest Gemini API documentation, allowed_function_names is indeed supported in both ANY and VALIDATED modes. In VALIDATED mode (currently in Preview), the model may return either natural language or a function call with schema adherence, and allowed_function_names can be used to restrict which functions the model is allowed to call.

The confusion arose because some older API documentation (particularly v1alpha surfaces) only documented allowed_function_names for ANY mode, as VALIDATED mode wasn't exposed in those earlier versions.

Your current implementation is correct — setting allowedFunctionNames for both ANY and VALIDATED modes aligns with the current Gemini API specification. Thank you for pointing this out and providing the documentation link!

     (\(\ 
     (-.-)  
     o_(")(")  Learned something new!

✏️ Learnings added
Learnt from: masap
Repo: receptron/graphai PR: 1269
File: llm_agents/gemini_agent/src/gemini_agent.ts:179-190
Timestamp: 2026-01-26T10:01:57.925Z
Learning: In the Gemini API, `allowed_function_names` (allowedFunctionNames) is supported in both `ANY` and `VALIDATED` function calling modes. It restricts which declared functions the model is allowed to call. In VALIDATED mode (Preview), the model may return either natural language or a function call with schema adherence.

Note: Learnings are effective only in the context of similar code segments. To apply general coding guidelines, please configure review instructions. You can manage existing learnings in the app.

@ystknsh

ystknsh commented Jan 27, 2026

Copy link
Copy Markdown
Contributor

@masap
Thanks for the fix!

1. allowedFunctionNames with empty array

The current fix sets allowedFunctionNames: [] for AUTO/NONE modes. No error is thrown now, but the Gemini docs only mention allowedFunctionNames for ANY and VALIDATED modes — it's not documented for AUTO/NONE. It would be safer to omit the field entirely rather than sending an empty array.

2. Test log

tool_choice: "any" does not guarantee multiple tool calls. Please restore the console.log('tool_calls.length: ...') to test gemini multiple tools so we can verify the behavior.

[
  {
    id: 'dummy',
    name: 'generalToolAgent--get_weather',
    arguments: { city: 'Tokyo' }
  }
]

@masap

masap commented Jan 27, 2026

Copy link
Copy Markdown
Contributor Author

@ystknsh Thank you for comment. Fixed.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
llm_agents/gemini_agent/src/gemini_agent.ts (1)

287-304: Add tool_choice to inputs.properties for consistency.

The tool_choice input is missing from the geminiAgentInfo.inputs.properties schema, creating an inconsistency with the actual inputs the agent accepts. This affects schema-based documentation and validation.

🔧 Proposed fix
   inputs: {
     type: "object",
     properties: {
       model: { type: "string" },
       system: { type: "string" },
       tools: { type: "object" },
+      tool_choice: { 
+        type: "string",
+        description: "function calling mode: auto, any, none, or validated",
+      },
       max_tokens: { type: "number" },
       temperature: { type: "number" },
       prompt: {
         type: "string",
         description: "query string",
       },
       messages: {
         anyOf: [{ type: "string" }, { type: "integer" }, { type: "object" }, { type: "array" }],
         description: "chat messages",
       },
+      response_format: { type: "object" },
     },
   },
🧹 Nitpick comments (1)
llm_agents/gemini_agent/src/gemini_agent.ts (1)

42-42: Consider using a stricter union type for tool_choice.

Using a union type would provide better type safety and IDE autocomplete support.

♻️ Suggested improvement
+type GeminiToolChoice = "auto" | "any" | "none" | "validated";
+
 type GeminiInputs = {
   model?: string;
   temperature?: number;
   max_tokens?: number;
   tools?: Array<Record<string, any>>;
-  tool_choice?: string;
+  tool_choice?: GeminiToolChoice;
   response_format?: GeminiResponseFormat;
   messages?: Array<GraphAILlmMessage>;
 } & GraphAILLMInputBase;

masap added 2 commits January 28, 2026 07:58
Signed-off-by: Masashi Honma <[email protected]>
Signed-off-by: Masashi Honma <[email protected]>
@ystknsh

ystknsh commented Jan 28, 2026

Copy link
Copy Markdown
Contributor

Thanks for the quick fix!!
The allowedFunctionNames is now properly omitted for AUTO/NONE, and the test log is restored.

@ystknsh
ystknsh merged commit fa714d9 into receptron:main Jan 28, 2026
@masap
masap deleted the fix-1268 branch January 28, 2026 01:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add support for tool_choice for Gemini

2 participants