com um clique
gemini-function-calling
Implement tool use with Gemini - function declarations, tool modes, parallel/compositional calling, and MCP integration
Menu
Implement tool use with Gemini - function declarations, tool modes, parallel/compositional calling, and MCP integration
Production patterns, API key security, cost optimization, performance tuning, and monitoring
Reduce costs and latency with context caching - implicit and explicit cache management with TTL configuration
Execute Python code in Gemini's secure sandbox for data analysis, visualization, and file processing
Generate text embeddings for semantic search, RAG, and vector database integration
Implement robust error handling with retry logic, rate limiting, and circuit breaker patterns
Implement Google Search grounding for real-time information with citation parsing and attribution handling
| name | gemini-function-calling |
| description | Implement tool use with Gemini - function declarations, tool modes, parallel/compositional calling, and MCP integration |
| argument-hint | <function or tool to implement> |
| allowed-tools | Read, Write, Bash(pip install, npm install, go get) |
Implement tool use and function calling with Gemini: $ARGUMENTS
You are a Gemini API specialist with expertise in:
from google import genai
from google.genai.types import FunctionDeclaration, Tool, GenerateContentConfig
# Define a function
get_weather = FunctionDeclaration(
name="get_weather",
description="Get the current weather for a location",
parameters={
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City name, e.g., 'San Francisco, CA'"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "Temperature unit"
}
},
"required": ["location"]
}
)
# Create tool
weather_tool = Tool(function_declarations=[get_weather])
const getWeather = {
name: "get_weather",
description: "Get the current weather for a location",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description: "City name, e.g., 'San Francisco, CA'"
},
unit: {
type: "string",
enum: ["celsius", "fahrenheit"],
description: "Temperature unit"
}
},
required: ["location"]
}
};
const tools = [{ functionDeclarations: [getWeather] }];
| Mode | Behavior | Use Case |
|---|---|---|
AUTO | Model decides when to call functions | Default, flexible |
ANY | Model must call at least one function | Force tool use |
NONE | Disable function calling | Text-only response |
VALIDATED | Strict schema validation (Gemini 3) | Production safety |
from google.genai.types import ToolConfig, FunctionCallingConfig
config = GenerateContentConfig(
tools=[weather_tool],
tool_config=ToolConfig(
function_calling_config=FunctionCallingConfig(
mode="ANY", # AUTO, ANY, NONE, VALIDATED
allowed_function_names=["get_weather"] # Optional: restrict functions
)
)
)
from google import genai
from google.genai.types import (
FunctionDeclaration, Tool, GenerateContentConfig,
Content, Part, FunctionResponse
)
client = genai.Client()
# 1. Define functions
get_weather = FunctionDeclaration(
name="get_weather",
description="Get current weather for a location",
parameters={
"type": "object",
"properties": {
"location": {"type": "string", "description": "City name"}
},
"required": ["location"]
}
)
search_products = FunctionDeclaration(
name="search_products",
description="Search for products in inventory",
parameters={
"type": "object",
"properties": {
"query": {"type": "string", "description": "Search query"},
"max_results": {"type": "integer", "description": "Maximum results"}
},
"required": ["query"]
}
)
tools = Tool(function_declarations=[get_weather, search_products])
# 2. Send request
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="What's the weather in Tokyo and find me some umbrellas",
config=GenerateContentConfig(tools=[tools])
)
# 3. Check for function calls
if response.candidates[0].content.parts:
for part in response.candidates[0].content.parts:
if part.function_call:
function_name = part.function_call.name
function_args = part.function_call.args
print(f"Function: {function_name}")
print(f"Args: {function_args}")
# 4. Execute the function (your implementation)
if function_name == "get_weather":
result = {"temperature": 22, "condition": "cloudy"}
elif function_name == "search_products":
result = {"products": [{"name": "Umbrella", "price": 15.99}]}
# 5. Send result back to model
follow_up = client.models.generate_content(
model="gemini-2.5-flash",
contents=[
Content(role="user", parts=[Part(text="What's the weather in Tokyo and find me some umbrellas")]),
response.candidates[0].content,
Content(
role="user",
parts=[Part(function_response=FunctionResponse(
name=function_name,
response=result
))]
)
],
config=GenerateContentConfig(tools=[tools])
)
print(follow_up.text)
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: process.env.GOOGLE_API_KEY });
const tools = [{
functionDeclarations: [{
name: "get_weather",
description: "Get current weather",
parameters: {
type: "object",
properties: {
location: { type: "string", description: "City name" }
},
required: ["location"]
}
}]
}];
async function chat() {
const response = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: "What's the weather in Paris?",
tools: tools
});
const functionCall = response.candidates[0].content.parts[0].functionCall;
if (functionCall) {
console.log(`Calling ${functionCall.name} with`, functionCall.args);
// Execute and return result
const result = { temperature: 18, condition: "sunny" };
const followUp = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: [
{ role: "user", parts: [{ text: "What's the weather in Paris?" }] },
response.candidates[0].content,
{ role: "user", parts: [{ functionResponse: { name: functionCall.name, response: result } }] }
],
tools: tools
});
console.log(followUp.text);
}
}
Gemini can call multiple functions simultaneously:
# User: "What's the weather in Tokyo and New York?"
# Gemini will return TWO function calls in one response
for part in response.candidates[0].content.parts:
if part.function_call:
# Handle each function call
print(f"Parallel call: {part.function_call.name}({part.function_call.args})")
Gemini can chain function results internally:
# Define functions that can reference each other
calculate = FunctionDeclaration(
name="calculate",
description="Perform mathematical calculation",
parameters={
"type": "object",
"properties": {
"expression": {"type": "string", "description": "Math expression"}
},
"required": ["expression"]
}
)
# User: "Calculate 15% tip on a $45 bill, then convert to euros"
# Gemini will chain: calculate tip -> convert currency
Gemini 3 models support Model Context Protocol for tool orchestration:
from google.genai.types import MCPConfig
config = GenerateContentConfig(
mcp_config=MCPConfig(
servers=[
{
"name": "filesystem",
"transport": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@anthropic/mcp-filesystem", "/path/to/dir"]
}
}
]
)
)
response = client.models.generate_content(
model="gemini-3-flash-preview",
contents="List files in the project directory",
config=config
)
Let the SDK handle the function execution loop:
from google import genai
client = genai.Client()
def get_weather(location: str) -> dict:
"""Get weather for a location."""
return {"temperature": 22, "condition": "sunny"}
def search_products(query: str, max_results: int = 5) -> list:
"""Search for products."""
return [{"name": "Widget", "price": 9.99}]
# SDK automatically handles the call/response loop
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="What's the weather in Tokyo?",
config=GenerateContentConfig(
tools=[get_weather, search_products], # Pass functions directly
automatic_function_calling=True
)
)
print(response.text) # Final answer after function execution
def handle_function_call(function_call):
try:
result = execute_function(function_call.name, function_call.args)
return FunctionResponse(name=function_call.name, response=result)
except Exception as e:
return FunctionResponse(
name=function_call.name,
response={"error": str(e), "success": False}
)
config = GenerateContentConfig(
tools=[tools],
tool_config=ToolConfig(
function_calling_config=FunctionCallingConfig(
mode="VALIDATED" # Strict schema compliance
)
)
)
| Pattern | Description |
|---|---|
| Single function | Simple action execution |
| Multi-function | Multiple tools available |
| Parallel calling | Simultaneous function execution |
| Compositional | Chained function results |
| Agentic loop | Iterative tool use until complete |
For: $ARGUMENTS
Provide: