Function Calling
Gemini Function Calling API - Enable Gemini Pro to call external tools and APIs. Build AI agents with tool use for automated workflows and integrations.
Function Calling (Tools)
Function calling allows Gemini models to interact with external systems by generating structured function calls. The model doesn't execute functions directly—it generates the parameters, and your code executes them.
Supported Models: All Gemini 1.5+ models support function calling.
How It Works
- Define functions with JSON schemas
- Send the definitions with your request
- Model decides if/which function to call
- Model generates function parameters
- Your code executes the function
- Send the result back to the model
Defining Functions
curl -X POST "https://api.uniterouter.ai/v1beta/models/gemini-2.0-flash:generateContent" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $UNITEROUTER_API_KEY" \
-d '{
"contents": [
{
"role": "user",
"parts": [{"text": "What is the weather in Tokyo?"}]
}
],
"tools": [
{
"functionDeclarations": [
{
"name": "get_weather",
"description": "Get the current weather for a location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "City name, e.g., Tokyo, New York"
},
"unit": {
"type": "string",
"enum": ["celsius", "fahrenheit"],
"description": "Temperature unit"
}
},
"required": ["location"]
}
}
]
}
]
}'import google.generativeai as genai
genai.configure(
api_key="your_uniterouter_api_key",
transport="rest",
client_options={"api_endpoint": "api.uniterouter.ai"}
)
# Define the function
def get_weather(location: str, unit: str = "celsius") -> dict:
"""Get weather for a location (mock implementation)"""
return {
"location": location,
"temperature": 22,
"unit": unit,
"condition": "sunny"
}
# Create model with tools
model = genai.GenerativeModel(
"gemini-2.0-flash",
tools=[get_weather]
)
# Start chat
chat = model.start_chat(enable_automatic_function_calling=True)
response = chat.send_message("What's the weather in Tokyo?")
print(response.text)import { GoogleGenerativeAI, FunctionDeclarationSchemaType } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI("your_uniterouter_api_key", {
baseUrl: "https://api.uniterouter.ai"
});
const model = genAI.getGenerativeModel({
model: "gemini-2.0-flash",
tools: [{
functionDeclarations: [{
name: "get_weather",
description: "Get the current weather for a location",
parameters: {
type: FunctionDeclarationSchemaType.OBJECT,
properties: {
location: {
type: FunctionDeclarationSchemaType.STRING,
description: "City name"
},
unit: {
type: FunctionDeclarationSchemaType.STRING,
enum: ["celsius", "fahrenheit"]
}
},
required: ["location"]
}
}]
}]
});
const result = await model.generateContent("What's the weather in Tokyo?");
const call = result.response.functionCalls()?.[0];
if (call) {
console.log("Function:", call.name);
console.log("Args:", call.args);
}Function Call Response
When the model decides to call a function:
{
"candidates": [
{
"content": {
"parts": [
{
"functionCall": {
"name": "get_weather",
"args": {
"location": "Tokyo",
"unit": "celsius"
}
}
}
],
"role": "model"
}
}
]
}Sending Function Results
After executing the function, send the result back:
# Execute the function
result = get_weather("Tokyo", "celsius")
# Send result back
response = chat.send_message(
genai.protos.Content(
parts=[
genai.protos.Part(
function_response=genai.protos.FunctionResponse(
name="get_weather",
response={"result": result}
)
)
]
)
)
print(response.text) # "The weather in Tokyo is 22°C and sunny."Tool Config
Control function calling behavior:
{
"toolConfig": {
"functionCallingConfig": {
"mode": "AUTO",
"allowedFunctionNames": ["get_weather", "get_time"]
}
}
}| Mode | Description |
|---|---|
AUTO | Model decides when to call functions |
ANY | Model must call at least one function |
NONE | Disable function calling |
Multiple Functions
tools = [
{
"functionDeclarations": [
{
"name": "get_weather",
"description": "Get current weather",
"parameters": {...}
},
{
"name": "get_time",
"description": "Get current time in a timezone",
"parameters": {...}
},
{
"name": "search_web",
"description": "Search the web for information",
"parameters": {...}
}
]
}
]Parallel Function Calls
Gemini can call multiple functions in parallel:
{
"candidates": [{
"content": {
"parts": [
{
"functionCall": {
"name": "get_weather",
"args": {"location": "Tokyo"}
}
},
{
"functionCall": {
"name": "get_weather",
"args": {"location": "New York"}
}
}
]
}
}]
}Best Practices
- Clear descriptions - Write detailed function and parameter descriptions
- Use enums - Constrain parameter values when possible
- Handle errors - Always handle function execution errors gracefully
- Validate inputs - Validate parameters before executing functions
- Keep it simple - Fewer, focused functions work better than many generic ones
Related
- Generate Content - Basic generation
- Code Execution - Run code directly
- Grounding - Google Search integration
How is this guide?
Vision
Gemini Vision API - Analyze images and videos with Gemini Pro Vision, Gemini 1.5. Multimodal AI for image understanding, video analysis, and document processing.
Code Execution
Gemini Code Execution API - Let Gemini 2.0 write and run Python code. Solve math, data analysis, and complex problems with AI-generated executable code.