Repository navigation
Add support for tool_choice for Gemini - #1269
Conversation
Resolves receptron#1268. Signed-off-by: Masashi Honma <[email protected]>
📝 WalkthroughWalkthroughAdds an optional Changes
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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related issues
Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
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. Comment |
|
Thanks for the PR! Two requests: 1. Currently, the code sends Please modify to set 2. Restore test log Please restore the |
Signed-off-by: Masashi Honma <[email protected]>
|
@ystknsh Thank you for comments!
According to official document [1], we can specify
I already set |
There was a problem hiding this comment.
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: Addtool_choiceto the inputs schema.The
tool_choiceparameter is now a valid input but is missing from theinputs.propertiesschema. 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: Missingtool_choicein inputs schema (same as TypeScript source).As noted in the TypeScript source review,
tool_choiceshould be added to the inputs properties for documentation completeness.
| 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, | ||
| }, | ||
| }; | ||
| } |
There was a problem hiding this comment.
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.
| const functionNames = | ||
| mode === FunctionCallingConfigMode.ANY || mode === FunctionCallingConfigMode.VALIDATED | ||
| ? tools?.map((tool: any) => { | ||
| return tool.function.name; | ||
| }) | ||
| : []; | ||
| generationConfig.toolConfig = { | ||
| functionCallingConfig: { | ||
| mode: mode, | ||
| allowedFunctionNames: functionNames, | ||
| }, | ||
| }; |
There was a problem hiding this comment.
🧩 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 infunction_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; ifallowedFunctionNamesis 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;allowedFunctionNamesrestricts 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.
There was a problem hiding this comment.
The
allowedFunctionNamesproperty 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.
There was a problem hiding this comment.
🧩 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_namesas “only set whenANY” and don’t includeVALIDATED, because that surface/version didn’t exposeVALIDATEDyet. [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.
|
@masap 1. The current fix sets 2. Test log
|
…ase. Signed-off-by: Masashi Honma <[email protected]>
|
@ystknsh Thank you for comment. Fixed. |
There was a problem hiding this comment.
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: Addtool_choicetoinputs.propertiesfor consistency.The
tool_choiceinput is missing from thegeminiAgentInfo.inputs.propertiesschema, 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 fortool_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;
Signed-off-by: Masashi Honma <[email protected]>
Signed-off-by: Masashi Honma <[email protected]>
|
Thanks for the quick fix!! |
Resolves #1268.
Summary by CodeRabbit
New Features
Tests
✏️ Tip: You can customize this high-level summary in your review settings.