Skip to main content

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.

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)

This example demonstrates how to use Gemini's function calling capabilities to analyze URLs and categorize them. The code:

  1. Defines a function that will be called by Gemini (set_website_category)
  2. Configures function calling with the model
  3. Sends content to Gemini for analysis
  4. 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