Вызов функций позволяет подключать модели к внешним инструментам и API. Вместо генерации текстовых ответов модель определяет, когда вызывать конкретные функции, и предоставляет необходимые параметры для выполнения реальных действий. Это позволяет модели выступать связующим звеном между естественным языком и реальными действиями и данными. Вызов функций имеет 3 основных варианта использования:
- Расширяйте знания: получайте доступ к информации из внешних источников, таких как базы данных, API и базы знаний.
- Расширение возможностей: используйте внешние инструменты для выполнения вычислений и расширения ограничений модели, например, использование калькулятора или создание диаграмм.
- Выполнение действий: взаимодействие с внешними системами с помощью API, например планирование встреч, создание счетов, отправка электронных писем или управление умными домашними устройствами.
Как работает вызов функций
Вызов функций подразумевает структурированное взаимодействие между вашим приложением, моделью и внешними функциями. Вот как выглядит этот процесс:
- Определение объявления функции: определите объявление функции в коде приложения. Объявления функций описывают имя функции, параметры и назначение для модели.
- Вызов LLM с объявлениями функций: отправка запроса пользователя вместе с объявлениями функций модели. Модель анализирует запрос и определяет, будет ли полезен вызов функции. Если да, то модель отвечает структурированным JSON-объектом.
- Выполнение кода функции (ваша ответственность): Модель не выполняет функцию сама по себе. Ваше приложение отвечает за обработку ответа и проверку вызова функции, если таковой имеется.
- Да : извлеките имя и аргументы функции и выполните соответствующую функцию в вашем приложении.
- Нет: модель предоставила прямой текстовый ответ на подсказку (этот поток менее акцентирован в примере, но является возможным результатом).
- Создайте удобный для пользователя ответ: если функция была выполнена, сохраните результат и отправьте его обратно модели в следующем этапе диалога. Модель использует этот результат для формирования окончательного удобного для пользователя ответа, включающего информацию из вызова функции.
Этот процесс может повторяться несколько раз, что позволяет реализовать сложные взаимодействия и рабочие процессы. Модель также поддерживает вызов нескольких функций за один раз ( параллельный вызов функций ) и последовательно ( композиционный вызов функций ).
Шаг 1: Определите объявление функции
Определите функцию и её объявление в коде приложения, позволяющее пользователям устанавливать значения освещения и выполнять запросы к API. Эта функция может вызывать внешние сервисы или API.
Питон
# Define a function that the model can call to control smart lights
set_light_values_declaration = {
"name": "set_light_values",
"description": "Sets the brightness and color temperature of a light.",
"parameters": {
"type": "object",
"properties": {
"brightness": {
"type": "integer",
"description": "Light level from 0 to 100. Zero is off and 100 is full brightness",
},
"color_temp": {
"type": "string",
"enum": ["daylight", "cool", "warm"],
"description": "Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.",
},
},
"required": ["brightness", "color_temp"],
},
}
# This is the actual function that would be called based on the model's suggestion
def set_light_values(brightness: int, color_temp: str) -> dict[str, int | str]:
"""Set the brightness and color temperature of a room light. (mock API).
Args:
brightness: Light level from 0 to 100. Zero is off and 100 is full brightness
color_temp: Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.
Returns:
A dictionary containing the set brightness and color temperature.
"""
return {"brightness": brightness, "colorTemperature": color_temp}
JavaScript
import { Type } from '@google/genai';
// Define a function that the model can call to control smart lights
const setLightValuesFunctionDeclaration = {
name: 'set_light_values',
description: 'Sets the brightness and color temperature of a light.',
parameters: {
type: Type.OBJECT,
properties: {
brightness: {
type: Type.NUMBER,
description: 'Light level from 0 to 100. Zero is off and 100 is full brightness',
},
color_temp: {
type: Type.STRING,
enum: ['daylight', 'cool', 'warm'],
description: 'Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.',
},
},
required: ['brightness', 'color_temp'],
},
};
/**
* Set the brightness and color temperature of a room light. (mock API)
* @param {number} brightness - Light level from 0 to 100. Zero is off and 100 is full brightness
* @param {string} color_temp - Color temperature of the light fixture, which can be `daylight`, `cool` or `warm`.
* @return {Object} A dictionary containing the set brightness and color temperature.
*/
function setLightValues(brightness, color_temp) {
return {
brightness: brightness,
colorTemperature: color_temp
};
}
Шаг 2: Вызов модели с объявлениями функций
После определения объявлений функций вы можете предложить модели использовать их. Она анализирует приглашение и объявления функций и решает, отвечать ли напрямую или вызывать функцию. При вызове функции объект ответа будет содержать предложение по вызову функции.
Питон
from google.genai import types
# Configure the client and tools
client = genai.Client()
tools = types.Tool(function_declarations=[set_light_values_declaration])
config = types.GenerateContentConfig(tools=[tools])
# Define user prompt
contents = [
types.Content(
role="user", parts=[types.Part(text="Turn the lights down to a romantic level")]
)
]
# Send request with function declarations
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=contents
config=config,
)
print(response.candidates[0].content.parts[0].function_call)
JavaScript
import { GoogleGenAI } from '@google/genai';
// Generation config with function declaration
const config = {
tools: [{
functionDeclarations: [setLightValuesFunctionDeclaration]
}]
};
// Configure the client
const ai = new GoogleGenAI({});
// Define user prompt
const contents = [
{
role: 'user',
parts: [{ text: 'Turn the lights down to a romantic level' }]
}
];
// Send request with function declarations
const response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: contents,
config: config
});
console.log(response.functionCalls[0]);
Затем модель возвращает объект functionCall
в схеме, совместимой с OpenAPI, указывающей, как вызвать одну или несколько объявленных функций, чтобы ответить на вопрос пользователя.
Питон
id=None args={'color_temp': 'warm', 'brightness': 25} name='set_light_values'
JavaScript
{
name: 'set_light_values',
args: { brightness: 25, color_temp: 'warm' }
}
Шаг 3: Выполнить код функции set_light_values
Извлеките сведения о вызове функции из ответа модели, проанализируйте аргументы и выполните функцию set_light_values
.
Питон
# Extract tool call details, it may not be in the first part.
tool_call = response.candidates[0].content.parts[0].function_call
if tool_call.name == "set_light_values":
result = set_light_values(**tool_call.args)
print(f"Function execution result: {result}")
JavaScript
// Extract tool call details
const tool_call = response.functionCalls[0]
let result;
if (tool_call.name === 'set_light_values') {
result = setLightValues(tool_call.args.brightness, tool_call.args.color_temp);
console.log(`Function execution result: ${JSON.stringify(result)}`);
}
Шаг 4: Создайте удобный для пользователя ответ с результатом функции и снова вызовите модель.
Наконец, отправьте результат выполнения функции обратно в модель, чтобы она могла включить эту информацию в свой окончательный ответ пользователю.
Питон
# Create a function response part
function_response_part = types.Part.from_function_response(
name=tool_call.name,
response={"result": result},
)
# Append function call and result of the function execution to contents
contents.append(response.candidates[0].content) # Append the content from the model's response.
contents.append(types.Content(role="user", parts=[function_response_part])) # Append the function response
final_response = client.models.generate_content(
model="gemini-2.5-flash",
config=config,
contents=contents,
)
print(final_response.text)
JavaScript
// Create a function response part
const function_response_part = {
name: tool_call.name,
response: { result }
}
// Append function call and result of the function execution to contents
contents.push(response.candidates[0].content);
contents.push({ role: 'user', parts: [{ functionResponse: function_response_part }] });
// Get the final response from the model
const final_response = await ai.models.generateContent({
model: 'gemini-2.5-flash',
contents: contents,
config: config
});
console.log(final_response.text);
На этом процесс вызова функции завершен. Модель успешно использовала функцию set_light_values
для выполнения действия, запрошенного пользователем.
Объявления функций
При реализации вызова функции в командной строке создается объект tools
, содержащий одно или несколько function declarations
. Функции определяются с помощью JSON, в частности, с использованием выбранного подмножества формата схемы OpenAPI . Одно объявление функции может включать следующие параметры:
-
name
(строка): Уникальное имя функции (get_weather_forecast
,send_email
). Используйте описательные имена без пробелов и специальных символов (используйте подчёркивание или «camelCase»). -
description
(строка): Чёткое и подробное описание назначения и возможностей функции. Это важно для понимания моделью того, когда использовать функцию. Описание должно быть конкретным и, если необходимо, приведите примеры («Находит кинотеатры по местоположению и, при необходимости, названию фильма, который сейчас идёт в кинотеатрах»). -
parameters
(объект): определяет входные параметры, которые ожидает функция.-
type
(строка): определяет общий тип данных, напримерobject
. -
properties
(объект): перечисляет отдельные параметры, каждый из которых имеет:-
type
(строка): тип данных параметра, напримерstring
,integer
,boolean, array
. -
description
(строка): Описание назначения и формата параметра. Приведите примеры и ограничения («Город и штат, например, «Сан-Франциско, Калифорния», или почтовый индекс, например, «95616»). -
enum
(массив, необязательно): если значения параметров взяты из фиксированного набора, используйте enum для перечисления допустимых значений, а не просто укажите их в описании. Это повышает точность ("enum": ["дневной свет", "холодный", "тёплый"]).
-
-
required
(массив): массив строк, в котором перечислены имена параметров, обязательных для работы функции.
-
Вы также можете создавать FunctionDeclarations из функций Python напрямую, используя types.FunctionDeclaration.from_callable(client=client, callable=your_function)
.
Вызов функций с мышлением
Включение « мышления » может повысить производительность вызовов функций, позволяя модели обдумать запрос, прежде чем предлагать вызовы функций. API Gemini не сохраняет состояние, поэтому контекст рассуждений модели будет потерян между ходами в многоходовом диалоге. Чтобы сохранить этот контекст, можно использовать сигнатуры мыслей. Сигнатура мыслей — это зашифрованное представление внутреннего мыслительного процесса модели, которое вы передаёте обратно в модель на последующих ходах.
Стандартный шаблон использования инструмента Multi-turn — добавление полного предыдущего ответа модели к истории разговора. Объект content
автоматически включает thought_signatures
. При использовании этого шаблона никаких изменений в коде не требуется .
Ручное управление мысленными подписями
Если вы изменяете историю разговора вручную, вместо того чтобы отправлять полный предыдущий ответ и хотите воспользоваться преимуществами размышлений, вам необходимо правильно обрабатывать thought_signature
включенную в ход модели.
Чтобы сохранить контекст модели, следуйте этим правилам:
- Всегда отправляйте
thought_signature
обратно в модель внутри ее исходнойPart
. - Не объединяйте
Part
, содержащую подпись, с частью, не содержащей её. Это нарушает позиционный контекст мысли. - Не объединяйте две
Parts
, обе из которых содержат подписи, так как строки подписей не могут быть объединены.
Проверка мысленных сигнатур
Хотя это и не является обязательным для реализации, вы можете просмотреть ответ и увидеть thought_signature
для отладки или образовательных целей.
Питон
import base64
# After receiving a response from a model with thinking enabled
# response = client.models.generate_content(...)
# The signature is attached to the response part containing the function call
part = response.candidates[0].content.parts[0]
if part.thought_signature:
print(base64.b64encode(part.thought_signature).decode("utf-8"))
JavaScript
// After receiving a response from a model with thinking enabled
// const response = await ai.models.generateContent(...)
// The signature is attached to the response part containing the function call
const part = response.candidates[0].content.parts[0];
if (part.thoughtSignature) {
console.log(part.thoughtSignature);
}
Подробнее об ограничениях и использовании мысленных сигнатур, а также о моделях мышления в целом можно узнать на странице «Мышление» .
Параллельный вызов функций
Помимо однократного вызова функций, вы также можете вызывать несколько функций одновременно. Параллельный вызов функций позволяет выполнять несколько функций одновременно и используется, когда функции не зависят друг от друга. Это полезно в таких сценариях, как сбор данных из нескольких независимых источников, например, для получения информации о клиентах из разных баз данных, проверки уровня запасов на разных складах или выполнения нескольких действий, например, для переоборудования квартиры в дискотеку.
Питон
power_disco_ball = {
"name": "power_disco_ball",
"description": "Powers the spinning disco ball.",
"parameters": {
"type": "object",
"properties": {
"power": {
"type": "boolean",
"description": "Whether to turn the disco ball on or off.",
}
},
"required": ["power"],
},
}
start_music = {
"name": "start_music",
"description": "Play some music matching the specified parameters.",
"parameters": {
"type": "object",
"properties": {
"energetic": {
"type": "boolean",
"description": "Whether the music is energetic or not.",
},
"loud": {
"type": "boolean",
"description": "Whether the music is loud or not.",
},
},
"required": ["energetic", "loud"],
},
}
dim_lights = {
"name": "dim_lights",
"description": "Dim the lights.",
"parameters": {
"type": "object",
"properties": {
"brightness": {
"type": "number",
"description": "The brightness of the lights, 0.0 is off, 1.0 is full.",
}
},
"required": ["brightness"],
},
}
JavaScript
import { Type } from '@google/genai';
const powerDiscoBall = {
name: 'power_disco_ball',
description: 'Powers the spinning disco ball.',
parameters: {
type: Type.OBJECT,
properties: {
power: {
type: Type.BOOLEAN,
description: 'Whether to turn the disco ball on or off.'
}
},
required: ['power']
}
};
const startMusic = {
name: 'start_music',
description: 'Play some music matching the specified parameters.',
parameters: {
type: Type.OBJECT,
properties: {
energetic: {
type: Type.BOOLEAN,
description: 'Whether the music is energetic or not.'
},
loud: {
type: Type.BOOLEAN,
description: 'Whether the music is loud or not.'
}
},
required: ['energetic', 'loud']
}
};
const dimLights = {
name: 'dim_lights',
description: 'Dim the lights.',
parameters: {
type: Type.OBJECT,
properties: {
brightness: {
type: Type.NUMBER,
description: 'The brightness of the lights, 0.0 is off, 1.0 is full.'
}
},
required: ['brightness']
}
};
Настройте режим вызова функций, чтобы разрешить использование всех указанных инструментов. Подробнее см. в статье о настройке вызова функций .
Питон
from google import genai
from google.genai import types
# Configure the client and tools
client = genai.Client()
house_tools = [
types.Tool(function_declarations=[power_disco_ball, start_music, dim_lights])
]
config = types.GenerateContentConfig(
tools=house_tools,
automatic_function_calling=types.AutomaticFunctionCallingConfig(
disable=True
),
# Force the model to call 'any' function, instead of chatting.
tool_config=types.ToolConfig(
function_calling_config=types.FunctionCallingConfig(mode='ANY')
),
)
chat = client.chats.create(model="gemini-2.5-flash", config=config)
response = chat.send_message("Turn this place into a party!")
# Print out each of the function calls requested from this single call
print("Example 1: Forced function calling")
for fn in response.function_calls:
args = ", ".join(f"{key}={val}" for key, val in fn.args.items())
print(f"{fn.name}({args})")
JavaScript
import { GoogleGenAI } from '@google/genai';
// Set up function declarations
const houseFns = [powerDiscoBall, startMusic, dimLights];
const config = {
tools: [{
functionDeclarations: houseFns
}],
// Force the model to call 'any' function, instead of chatting.
toolConfig: {
functionCallingConfig: {
mode: 'any'
}
}
};
// Configure the client
const ai = new GoogleGenAI({});
// Create a chat session
const chat = ai.chats.create({
model: 'gemini-2.5-flash',
config: config
});
const response = await chat.sendMessage({message: 'Turn this place into a party!'});
// Print out each of the function calls requested from this single call
console.log("Example 1: Forced function calling");
for (const fn of response.functionCalls) {
const args = Object.entries(fn.args)
.map(([key, val]) => `${key}=${val}`)
.join(', ');
console.log(`${fn.name}(${args})`);
}
Каждый из выводимых результатов отражает один вызов функции, запрошенный моделью. Чтобы отправить результаты обратно, включите ответы в том же порядке, в котором они были запрошены.
Python SDK поддерживает автоматический вызов функций , который автоматически преобразует функции Python в объявления, берёт на себя выполнение вызова функций и цикл ответа. Ниже приведён пример для сценария использования Disco.
Питон
from google import genai
from google.genai import types
# Actual function implementations
def power_disco_ball_impl(power: bool) -> dict:
"""Powers the spinning disco ball.
Args:
power: Whether to turn the disco ball on or off.
Returns:
A status dictionary indicating the current state.
"""
return {"status": f"Disco ball powered {'on' if power else 'off'}"}
def start_music_impl(energetic: bool, loud: bool) -> dict:
"""Play some music matching the specified parameters.
Args:
energetic: Whether the music is energetic or not.
loud: Whether the music is loud or not.
Returns:
A dictionary containing the music settings.
"""
music_type = "energetic" if energetic else "chill"
volume = "loud" if loud else "quiet"
return {"music_type": music_type, "volume": volume}
def dim_lights_impl(brightness: float) -> dict:
"""Dim the lights.
Args:
brightness: The brightness of the lights, 0.0 is off, 1.0 is full.
Returns:
A dictionary containing the new brightness setting.
"""
return {"brightness": brightness}
# Configure the client
client = genai.Client()
config = types.GenerateContentConfig(
tools=[power_disco_ball_impl, start_music_impl, dim_lights_impl]
)
# Make the request
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="Do everything you need to this place into party!",
config=config,
)
print("\nExample 2: Automatic function calling")
print(response.text)
# I've turned on the disco ball, started playing loud and energetic music, and dimmed the lights to 50% brightness. Let's get this party started!
Вызов композиционной функции
Композиционный или последовательный вызов функций позволяет Gemini объединять несколько вызовов функций в цепочку для выполнения сложного запроса. Например, чтобы ответить на запрос «Узнать температуру в моём текущем местоположении», API Gemini может сначала вызвать функцию get_current_location()
а затем функцию get_weather()
, которая принимает местоположение в качестве параметра.
В следующем примере показано, как реализовать композиционный вызов функций с использованием Python SDK и автоматического вызова функций.
Питон
В этом примере используется функция автоматического вызова функций из пакета SDK Python google-genai
. SDK автоматически преобразует функции Python в требуемую схему, выполняет вызовы функций по запросу модели и отправляет результаты обратно модели для завершения задачи.
import os
from google import genai
from google.genai import types
# Example Functions
def get_weather_forecast(location: str) -> dict:
"""Gets the current weather temperature for a given location."""
print(f"Tool Call: get_weather_forecast(location={location})")
# TODO: Make API call
print("Tool Response: {'temperature': 25, 'unit': 'celsius'}")
return {"temperature": 25, "unit": "celsius"} # Dummy response
def set_thermostat_temperature(temperature: int) -> dict:
"""Sets the thermostat to a desired temperature."""
print(f"Tool Call: set_thermostat_temperature(temperature={temperature})")
# TODO: Interact with a thermostat API
print("Tool Response: {'status': 'success'}")
return {"status": "success"}
# Configure the client and model
client = genai.Client()
config = types.GenerateContentConfig(
tools=[get_weather_forecast, set_thermostat_temperature]
)
# Make the request
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise set it to 18°C.",
config=config,
)
# Print the final, user-facing response
print(response.text)
Ожидаемый результат
При запуске кода вы увидите, как SDK управляет вызовами функций. Модель сначала вызывает get_weather_forecast
, получает значение температуры, а затем вызывает set_thermostat_temperature
с правильным значением, основанным на логике в командной строке.
Tool Call: get_weather_forecast(location=London)
Tool Response: {'temperature': 25, 'unit': 'celsius'}
Tool Call: set_thermostat_temperature(temperature=20)
Tool Response: {'status': 'success'}
OK. I've set the thermostat to 20°C.
JavaScript
В этом примере показано, как использовать JavaScript/TypeScript SDK для вызова композиционных функций с использованием ручного цикла выполнения.
import { GoogleGenAI, Type } from "@google/genai";
// Configure the client
const ai = new GoogleGenAI({});
// Example Functions
function get_weather_forecast({ location }) {
console.log(`Tool Call: get_weather_forecast(location=${location})`);
// TODO: Make API call
console.log("Tool Response: {'temperature': 25, 'unit': 'celsius'}");
return { temperature: 25, unit: "celsius" };
}
function set_thermostat_temperature({ temperature }) {
console.log(
`Tool Call: set_thermostat_temperature(temperature=${temperature})`,
);
// TODO: Make API call
console.log("Tool Response: {'status': 'success'}");
return { status: "success" };
}
const toolFunctions = {
get_weather_forecast,
set_thermostat_temperature,
};
const tools = [
{
functionDeclarations: [
{
name: "get_weather_forecast",
description:
"Gets the current weather temperature for a given location.",
parameters: {
type: Type.OBJECT,
properties: {
location: {
type: Type.STRING,
},
},
required: ["location"],
},
},
{
name: "set_thermostat_temperature",
description: "Sets the thermostat to a desired temperature.",
parameters: {
type: Type.OBJECT,
properties: {
temperature: {
type: Type.NUMBER,
},
},
required: ["temperature"],
},
},
],
},
];
// Prompt for the model
let contents = [
{
role: "user",
parts: [
{
text: "If it's warmer than 20°C in London, set the thermostat to 20°C, otherwise set it to 18°C.",
},
],
},
];
// Loop until the model has no more function calls to make
while (true) {
const result = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents,
config: { tools },
});
if (result.functionCalls && result.functionCalls.length > 0) {
const functionCall = result.functionCalls[0];
const { name, args } = functionCall;
if (!toolFunctions[name]) {
throw new Error(`Unknown function call: ${name}`);
}
// Call the function and get the response.
const toolResponse = toolFunctions[name](args);
const functionResponsePart = {
name: functionCall.name,
response: {
result: toolResponse,
},
};
// Send the function response back to the model.
contents.push({
role: "model",
parts: [
{
functionCall: functionCall,
},
],
});
contents.push({
role: "user",
parts: [
{
functionResponse: functionResponsePart,
},
],
});
} else {
// No more function calls, break the loop.
console.log(result.text);
break;
}
}
Ожидаемый результат
При запуске кода вы увидите, как SDK управляет вызовами функций. Модель сначала вызывает get_weather_forecast
, получает значение температуры, а затем вызывает set_thermostat_temperature
с правильным значением, основанным на логике в командной строке.
Tool Call: get_weather_forecast(location=London)
Tool Response: {'temperature': 25, 'unit': 'celsius'}
Tool Call: set_thermostat_temperature(temperature=20)
Tool Response: {'status': 'success'}
OK. It's 25°C in London, so I've set the thermostat to 20°C.
Композиционный вызов функций — это встроенная функция Live API . Это означает, что Live API может обрабатывать вызов функций аналогично Python SDK.
Питон
# Light control schemas
turn_on_the_lights_schema = {'name': 'turn_on_the_lights'}
turn_off_the_lights_schema = {'name': 'turn_off_the_lights'}
prompt = """
Hey, can you write run some python code to turn on the lights, wait 10s and then turn off the lights?
"""
tools = [
{'code_execution': {}},
{'function_declarations': [turn_on_the_lights_schema, turn_off_the_lights_schema]}
]
await run(prompt, tools=tools, modality="AUDIO")
JavaScript
// Light control schemas
const turnOnTheLightsSchema = { name: 'turn_on_the_lights' };
const turnOffTheLightsSchema = { name: 'turn_off_the_lights' };
const prompt = `
Hey, can you write run some python code to turn on the lights, wait 10s and then turn off the lights?
`;
const tools = [
{ codeExecution: {} },
{ functionDeclarations: [turnOnTheLightsSchema, turnOffTheLightsSchema] }
];
await run(prompt, tools=tools, modality="AUDIO")
Режимы вызова функций
API Gemini позволяет управлять тем, как модель использует предоставленные инструменты (объявления функций). В частности, режим можно задать в файле function_calling_config
.
-
AUTO (Default)
: модель решает, генерировать ли ответ на естественном языке или предлагать вызов функции, основываясь на подсказке и контексте. Это наиболее гибкий режим, рекомендуемый для большинства сценариев. -
ANY
: Модель ограничена тем, чтобы всегда предсказывать вызов функции и гарантировать соответствие схеме функций. Еслиallowed_function_names
не указано, модель может выбрать любое из предоставленных объявлений функций. Еслиallowed_function_names
указано в виде списка, модель может выбрать только функции из этого списка. Используйте этот режим, если требуется ответ на вызов функции на каждый запрос (если применимо). NONE
: модели запрещено выполнять вызовы функций. Это эквивалентно отправке запроса без объявлений функций. Используйте это, чтобы временно отключить вызов функций, не удаляя определения инструментов.
Питон
from google.genai import types
# Configure function calling mode
tool_config = types.ToolConfig(
function_calling_config=types.FunctionCallingConfig(
mode="ANY", allowed_function_names=["get_current_temperature"]
)
)
# Create the generation config
config = types.GenerateContentConfig(
tools=[tools], # not defined here.
tool_config=tool_config,
)
JavaScript
import { FunctionCallingConfigMode } from '@google/genai';
// Configure function calling mode
const toolConfig = {
functionCallingConfig: {
mode: FunctionCallingConfigMode.ANY,
allowedFunctionNames: ['get_current_temperature']
}
};
// Create the generation config
const config = {
tools: tools, // not defined here.
toolConfig: toolConfig,
};
Автоматический вызов функций (только Python)
Используя Python SDK, вы можете предоставлять функции Python непосредственно в качестве инструментов. SDK автоматически преобразует функции Python в объявления, управляет вызовом функций и циклом ответов. Затем Python SDK автоматически:
- Обнаруживает ответы на вызовы функций из модели.
- Вызовите соответствующую функцию Python в вашем коде.
- Отправляет ответ функции обратно в модель.
- Возвращает окончательный текстовый ответ модели.
Чтобы использовать это, определите свою функцию с подсказками типов и строкой документации, а затем передайте саму функцию (не объявление JSON) в качестве инструмента:
Питон
from google import genai
from google.genai import types
# Define the function with type hints and docstring
def get_current_temperature(location: str) -> dict:
"""Gets the current temperature for a given location.
Args:
location: The city and state, e.g. San Francisco, CA
Returns:
A dictionary containing the temperature and unit.
"""
# ... (implementation) ...
return {"temperature": 25, "unit": "Celsius"}
# Configure the client
client = genai.Client()
config = types.GenerateContentConfig(
tools=[get_current_temperature]
) # Pass the function itself
# Make the request
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="What's the temperature in Boston?",
config=config,
)
print(response.text) # The SDK handles the function call and returns the final text
Вы можете отключить автоматический вызов функций с помощью:
Питон
config = types.GenerateContentConfig(
tools=[get_current_temperature],
automatic_function_calling=types.AutomaticFunctionCallingConfig(disable=True)
)
Автоматическое объявление схемы функции
Автоматическое извлечение схемы из функций Python работает не во всех случаях. Например, оно не обрабатывает случаи, когда вы описываете поля вложенного объекта-словаря. API может описывать любой из следующих типов:
Питон
AllowedType = (int | float | bool | str | list['AllowedType'] | dict[str, AllowedType])
Чтобы увидеть, как выглядит выведенная схема, вы можете преобразовать ее с помощью from_callable
:
Питон
def multiply(a: float, b: float):
"""Returns a * b."""
return a * b
fn_decl = types.FunctionDeclaration.from_callable(callable=multiply, client=client)
# to_json_dict() provides a clean JSON representation.
print(fn_decl.to_json_dict())
Использование нескольких инструментов: объединение собственных инструментов с вызовом функций
Вы можете включить несколько инструментов, сочетая встроенные инструменты с вызовом функций одновременно. Вот пример, который включает два инструмента: Grounding with Google Search и code execution в запросе с использованием Live API .
Питон
# Multiple tasks example - combining lights, code execution, and search
prompt = """
Hey, I need you to do three things for me.
1. Turn on the lights.
2. Then compute the largest prime palindrome under 100000.
3. Then use Google Search to look up information about the largest earthquake in California the week of Dec 5 2024.
Thanks!
"""
tools = [
{'google_search': {}},
{'code_execution': {}},
{'function_declarations': [turn_on_the_lights_schema, turn_off_the_lights_schema]} # not defined here.
]
# Execute the prompt with specified tools in audio modality
await run(prompt, tools=tools, modality="AUDIO")
JavaScript
// Multiple tasks example - combining lights, code execution, and search
const prompt = `
Hey, I need you to do three things for me.
1. Turn on the lights.
2. Then compute the largest prime palindrome under 100000.
3. Then use Google Search to look up information about the largest earthquake in California the week of Dec 5 2024.
Thanks!
`;
const tools = [
{ googleSearch: {} },
{ codeExecution: {} },
{ functionDeclarations: [turnOnTheLightsSchema, turnOffTheLightsSchema] } // not defined here.
];
// Execute the prompt with specified tools in audio modality
await run(prompt, {tools: tools, modality: "AUDIO"});
Разработчики Python могут опробовать это в блокноте Live API Tool Use .
Протокол контекста модели (MCP)
Протокол контекста модели (MCP) — это открытый стандарт для подключения приложений искусственного интеллекта к внешним инструментам и данным. MCP предоставляет общий протокол для доступа моделей к контексту, такому как функции (инструменты), источники данных (ресурсы) или предопределенные подсказки.
Пакеты Gemini SDK имеют встроенную поддержку MCP, что сокращает объём шаблонного кода и обеспечивает автоматический вызов инструментов MCP. Когда модель генерирует вызов инструмента MCP, клиентский SDK Python и JavaScript может автоматически выполнить инструмент MCP и отправить ответ обратно модели в следующем запросе, продолжая этот цикл до тех пор, пока модель не прекратит вызывать инструменты.
Здесь вы можете найти пример использования локального сервера MCP с Gemini и mcp
SDK.
Питон
Убедитесь, что на выбранной вами платформе установлена последняя версия mcp
SDK .
pip install mcp
import os
import asyncio
from datetime import datetime
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
from google import genai
client = genai.Client()
# Create server parameters for stdio connection
server_params = StdioServerParameters(
command="npx", # Executable
args=["-y", "@philschmid/weather-mcp"], # MCP Server
env=None, # Optional environment variables
)
async def run():
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
# Prompt to get the weather for the current day in London.
prompt = f"What is the weather in London in {datetime.now().strftime('%Y-%m-%d')}?"
# Initialize the connection between client and server
await session.initialize()
# Send request to the model with MCP function declarations
response = await client.aio.models.generate_content(
model="gemini-2.5-flash",
contents=prompt,
config=genai.types.GenerateContentConfig(
temperature=0,
tools=[session], # uses the session, will automatically call the tool
# Uncomment if you **don't** want the SDK to automatically call the tool
# automatic_function_calling=genai.types.AutomaticFunctionCallingConfig(
# disable=True
# ),
),
)
print(response.text)
# Start the asyncio event loop and run the main function
asyncio.run(run())
JavaScript
Убедитесь, что на выбранной вами платформе установлена последняя версия mcp
SDK.
npm install @modelcontextprotocol/sdk
import { GoogleGenAI, FunctionCallingConfigMode , mcpToTool} from '@google/genai';
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
// Create server parameters for stdio connection
const serverParams = new StdioClientTransport({
command: "npx", // Executable
args: ["-y", "@philschmid/weather-mcp"] // MCP Server
});
const client = new Client(
{
name: "example-client",
version: "1.0.0"
}
);
// Configure the client
const ai = new GoogleGenAI({});
// Initialize the connection between client and server
await client.connect(serverParams);
// Send request to the model with MCP tools
const response = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: `What is the weather in London in ${new Date().toLocaleDateString()}?`,
config: {
tools: [mcpToTool(client)], // uses the session, will automatically call the tool
// Uncomment if you **don't** want the sdk to automatically call the tool
// automaticFunctionCalling: {
// disable: true,
// },
},
});
console.log(response.text)
// Close the connection
await client.close();
Ограничения при встроенной поддержке MCP
Встроенная поддержка MCP является экспериментальной функцией наших SDK и имеет следующие ограничения:
- Поддерживаются только инструменты, а не ресурсы и подсказки.
- Он доступен для Python и JavaScript/TypeScript SDK.
- В будущих версиях могут произойти критические изменения.
Ручная интеграция серверов MCP всегда является вариантом, если они ограничивают то, что вы разрабатываете.
Поддерживаемые модели
В этом разделе перечислены модели и их возможности вызова функций. Экспериментальные модели не включены. Подробный обзор возможностей доступен на странице обзора моделей .
Модель | Вызов функции | Параллельный вызов функций | Вызов композиционных функций |
---|---|---|---|
Джемини 2.5 Про | ✔️ | ✔️ | ✔️ |
Близнецы 2.5 Флэш | ✔️ | ✔️ | ✔️ |
Gemini 2.5 Flash-Lite | ✔️ | ✔️ | ✔️ |
Gemini 2.0 Flash | ✔️ | ✔️ | ✔️ |
Gemini 2.0 Flash-Lite | Х | Х | Х |
Лучшие практики
- Описания функций и параметров: будьте предельно чёткими и конкретными в своих описаниях. Модель опирается на них для выбора правильной функции и предоставления соответствующих аргументов.
- Именование: используйте описательные имена функций (без пробелов, точек и тире).
- Строгая типизация: используйте определённые типы (целое число, строка, перечисление) для параметров, чтобы уменьшить количество ошибок. Если параметр имеет ограниченный набор допустимых значений, используйте перечисление.
- Выбор инструментов: Хотя модель может использовать произвольное количество инструментов, предоставление слишком большого их количества может увеличить риск выбора неверного или неоптимального инструмента. Для достижения наилучших результатов старайтесь предоставлять только инструменты, соответствующие контексту или задаче, в идеале ограничивая активный набор 10–20 инструментами. Рассмотрите возможность динамического выбора инструментов на основе контекста обсуждения, если у вас много инструментов.
- Оперативное проектирование:
- Предоставьте контекст: расскажите модели о ее роли (например, «Вы полезный помощник, который предсказывает погоду»).
- Дайте инструкции: укажите, как и когда использовать функции (например, «Не угадывайте даты; всегда используйте будущую дату для прогнозов»).
- Поощряйте уточнения: попросите модель задавать уточняющие вопросы при необходимости.
- Температура: используйте низкую температуру (например, 0) для более детерминированных и надежных вызовов функций.
- Проверка: если вызов функции имеет существенные последствия (например, размещение заказа), проверьте вызов у пользователя, прежде чем выполнять его.
- Обработка ошибок : реализуйте надежную обработку ошибок в своих функциях для корректной обработки непредвиденных входных данных или сбоев API. Возвращайте информативные сообщения об ошибках, которые модель может использовать для генерации полезных ответов пользователю.
- Безопасность: Помните о безопасности при вызове внешних API. Используйте соответствующие механизмы аутентификации и авторизации. Избегайте раскрытия конфиденциальных данных при вызовах функций.
- Ограничение токенов: описания функций и параметры учитываются при подсчёте лимита входных токенов. Если вы достигаете лимита токенов, рассмотрите возможность ограничения количества функций или длины описаний, разбивайте сложные задачи на более мелкие, более узкие наборы функций.
Примечания и ограничения
- Поддерживается только подмножество схемы OpenAPI .
- Поддерживаемые типы параметров в Python ограничены.
- Автоматический вызов функций доступен только в Python SDK.