Function Calling with Gemini Flash 2.0
Function calling allows Gemini to analyze input and call specific functions based on that analysis. This is particularly useful for tasks like categorization, data extraction, or any scenario where you want Gemini to process information and take specific actions.
- Python
- Typescript
from google import genai
from google.genai import types
client = genai.Client()
def set_website_category(website: str, category: str) -> dict[str, str]:
"""Set the website and category of a website.
Args:
website: website name
category: category of the website, e.g. search engine, news, social media, etc.
Returns:
Dictionary containing the categorization details
"""
return {
"website": website,
"category": category,
}
# Configure function calling
config = types.GenerateContentConfig(
tools=[set_website_category],
automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True)
)
def analyze_urls(urls: list[str]):
try:
urls_str = "\n".join(urls)
response = client.models.generate_content(
model="gemini-2.0-flash",
contents=[f"""{urls_str}
Identify the categories of websites call set_website_category to set the category of the website you have determined.
"""],
config=config
)
results = []
if response.function_calls:
for fn in response.function_calls:
results.append({
"website": fn.args["website"],
"category": fn.args["category"]
})
return results
except Exception as e:
print(f"Error analyzing urls: {e}")
return []
# Example usage
urls = [
"google.com",
"cnn.com"
]
results = analyze_urls(urls)
print(results)
import { FunctionCallingMode, GoogleGenerativeAI } from "@google/generative-ai";
interface WebsiteCategory {
website: string;
category: string;
}
const websiteCategoryFunctionDeclaration = {
name: "setWebsiteCategory",
description: "Set the website, category",
parameters: {
type: "OBJECT",
properties: {
website: {
type: "STRING",
description: "Website name",
},
category: {
type: "STRING",
description: "Category of the website, e.g. search engine, news, social media, etc.",
},
},
required: ["website", "category"],
},
};
const genAI = new GoogleGenerativeAI(apiKey);
const model = genAI.getGenerativeModel({
model: "gemini-2.0-flash-exp",
tools: [{
functionDeclarations: [websiteCategoryFunctionDeclaration],
}],
toolConfig: {
functionCallingConfig: {
mode: FunctionCallingMode.ANY,
},
},
});
const urlList = urls.split('\n').filter(url => url.trim());
const urlsStr = urlList.join('\n');
const chat = model.startChat();
const result = await chat.sendMessage(
`${urlsStr}\nIdentify the categories of websites and call setWebsiteCategory to set the category of the website you have determined.`
);
const functionCalls = result.response.functionCalls();
const categorizations: WebsiteCategory[] = [];
for (const call of functionCalls) {
if (call.name === 'setWebsiteCategory') {
const args = call.args as {
website: string;
category: string;
};
categorizations.push({
website: args.website,
category: args.category,
});
}
}
This example demonstrates how to use Gemini's function calling capabilities to analyze URLs and categorize them. The code:
- Defines a function that will be called by Gemini (
set_website_category
) - Configures function calling with the model
- Sends content to Gemini for analysis
- Processes the function calls in the response
Function calling is particularly useful for:
- Data extraction and categorization
- Structured information processing
- Automated decision making
- API integration