AIAI Club
← Back to articles
ENGLISH GUIDE

Advanced Function Calling in Practice: Let Gemini Autonomously Call External Tool APIs

Give large models the ability to take action! This step-by-step guide shows you how to define Python function specifications, teach the model to decide autonomously when to call a weather query API, and integrate the final answer throughout the entire process.

1. What Is Function Calling?

Large models themselves cannot go online to check real-time stock prices or query a company's internal database.
Function calling lets you tell the model about your own local functions (Tools). After interpreting the user's question, the model returns a JSON instruction containing structured parameters, telling your program: Please run this function and return the result to me!

2. Core Hands-On Code Framework

def get_current_weather(location: str):
return f"{location} currently has sunny weather, with a temperature of 25 degrees Celsius"

model = genai.GenerativeModel(
model_name="gemini-1.5-flash",
tools=[get_current_weather]
)
chat = model.start_chat(enable_automatic_function_calling=True)
response = chat.send_message("What is the weather in Hangzhou today?")
print(response.text)
After enabling automatic function calling, the SDK autonomously handles parameter extraction, function execution, and final language polishing in the background, all in one go!

This English translation is based on a Chinese source article. Prices are approximate where stated and conditions should be confirmed with the official provider or seller.