Генеративные модели могут решать многие типы задач. Однако у них есть ограничения, например:
- После обучения они замораживаются, что приводит к устареванию знаний.
- Они не могут запрашивать или изменять внешние данные.
Функция вызова функций помогает преодолеть некоторые из этих ограничений. Иногда вызов функций называют использованием инструментов, поскольку он позволяет модели использовать внешние инструменты, такие как API и функции, для создания окончательного ответа.
В этом руководстве рассказывается, как настроить вызов функций, похожий на описанный в следующем разделе. Чтобы настроить вызов функций в приложении, выполните следующие действия:
Шаг 1. Напишите функцию, которая может предоставить модели информацию, необходимую для создания окончательного ответа (например, функция может вызывать внешний API).
Шаг 2. Создайте декларацию функции, в которой описывается функция и ее параметры.
Шаг 3. При инициализации модели укажите декларацию функции, чтобы модель знала, как ее можно использовать, если это необходимо.
Шаг 4. Настройте приложение так, чтобы модель могла передавать необходимую информацию для вызова функции.
Шаг 5. Передайте ответ функции обратно модели, чтобы она могла сгенерировать окончательный ответ.
Обзор примера использования вызова функций
При отправке запроса модели можно также предоставить ей набор "инструментов" (например, функций), которые она может использовать для создания окончательного ответа. Чтобы использовать эти функции и вызывать их (вызов функций), модели и приложению необходимо обмениваться информацией. Рекомендуемый способ использования вызова функций – многоходовый чат.
Предположим, что в вашем приложении пользователь может ввести запрос, например:
What was the weather in Boston on October 17, 2024?.
Модели Gemini могут не знать эту информацию о погоде, но предположим, что вам известен внешний API сервиса погоды, который может ее предоставить. Вы можете использовать вызов функций, чтобы предоставить модели Gemini доступ к этому API и его информации о погоде.
Сначала вы пишете функцию fetchWeather в приложении, которая взаимодействует с гипотетическим внешним API, имеющим следующие входные и выходные данные:
| Параметр | Тип | Обязательно | Описание |
|---|---|---|---|
| Запрос | |||
location |
Объект | Да | Название города и штата, для которых нужно получить прогноз погоды. Поддерживаются только города в США. Всегда должен быть вложенным объектом city и state.
|
date |
Строка | Да | Дата, для которой нужно получить прогноз погоды (всегда должна быть в формате YYYY-MM-DD).
|
| Результат | |||
temperature |
Целое число | Да | Температура (в градусах Фаренгейта) |
chancePrecipitation |
Строка | Да | Вероятность осадков (в процентах) |
cloudConditions |
Строка | Да | Условия облачности (одно из значений: clear, partlyCloudy, mostlyCloudy, cloudy)
|
При инициализации модели вы сообщаете ей, что существует функция fetchWeather и как ее можно использовать для обработки входящих запросов, если это необходимо.
Это называется объявлением функции. Модель не вызывает функцию напрямую. Вместо этого, когда модель обрабатывает входящий запрос, она решает, может ли функция fetchWeather помочь ей ответить на запрос. Если модель решит, что функция может быть полезной, она сгенерирует структурированные данные, которые помогут вашему приложению вызвать функцию.
Ещё раз проверьте входящий запрос:
What was the weather in Boston on October 17, 2024?. Модель, скорее всего, решит, что функция fetchWeather поможет ей сгенерировать ответ. Модель определит, какие входные параметры нужны для функции fetchWeather, а затем сгенерирует структурированные входные данные для функции, которые будут выглядеть примерно так:
{
functionName: fetchWeather,
location: {
city: Boston,
state: Massachusetts // the model can infer the state from the prompt
},
date: 2024-10-17
}
Модель передает эти структурированные входные данные в ваше приложение, чтобы оно могло вызвать функцию fetchWeather. Когда приложение получает от API данные о погодных условиях, оно передает их модели. Эта информация о погоде позволяет модели завершить обработку и сгенерировать ответ на исходный запрос What was the weather in Boston on October 17, 2024?.
Модель может предоставить окончательный ответ на естественном языке, например:
On October 17, 2024, in Boston, it was 38 degrees Fahrenheit with partly cloudy skies.
Как реализовать вызов функций
В этой статье описано, как настроить вызов функции, аналогичный описанному в разделе Обзор примера вызова функции.
Поддерживаемые модели
gemini-3.1-pro-previewgemini-3.8-flash(а также более старыеgemini-3.7-flash,gemini-3.6-flashиgemini-3.5-flash)gemini-3.5-flash-lite(и более ранние версии, напримерgemini-3.1-flash-lite)
Модели общего назначения Gemini 2.5 поддерживают эту функцию, но все они устарели.
Модели Gemini Live API также поддерживают эту возможность, но все примеры кода в этом руководстве предназначены для моделей Gemini общего назначения.
Подготовка
|
Нажмите на поставщика Gemini API, чтобы посмотреть контент и код, относящиеся к нему. |
Если вы ещё этого не сделали, ознакомьтесь с руководством по началу работы. В нем рассказывается, как настроить проект Firebase, подключить к нему приложение, добавить SDK, инициализировать бэкенд-службу для выбранного поставщика Gemini API и создать экземпляр GenerativeModel.
Для тестирования и доработки запросов рекомендуем использовать Google AI Studio.
Шаг 1. Напишите функцию
Предположим, что в вашем приложении пользователь может ввести запрос, например:
What was the weather in Boston on October 17, 2024?. GeminiМодели могут не знать эту информацию о погоде, но предположим, что вам известен внешний API сервиса погоды, который может ее предоставить. В сценарии, описанном в этом руководстве, используется гипотетический внешний API.
Напишите в приложении функцию, которая будет взаимодействовать с гипотетическим внешним API и предоставлять модели информацию, необходимую для создания окончательного запроса. В примере с погодой это будет функция fetchWeather, которая вызывает гипотетический внешний API.
Swift
// This function calls a hypothetical external API that returns
// a collection of weather information for a given location on a given date.
func fetchWeather(city: String, state: String, date: String) -> JSONObject {
// TODO(developer): Write a standard function that would call an external weather API.
// For demo purposes, this hypothetical response is hardcoded here in the expected format.
return [
"temperature": .number(38),
"chancePrecipitation": .string("56%"),
"cloudConditions": .string("partlyCloudy"),
]
}
Kotlin
// This function calls a hypothetical external API that returns
// a collection of weather information for a given location on a given date.
// `location` is an object of the form { city: string, state: string }
data class Location(val city: String, val state: String)
suspend fun fetchWeather(location: Location, date: String): JsonObject {
// TODO(developer): Write a standard function that would call to an external weather API.
// For demo purposes, this hypothetical response is hardcoded here in the expected format.
return JsonObject(mapOf(
"temperature" to JsonPrimitive(38),
"chancePrecipitation" to JsonPrimitive("56%"),
"cloudConditions" to JsonPrimitive("partlyCloudy")
))
}
Java
// This function calls a hypothetical external API that returns
// a collection of weather information for a given location on a given date.
// `location` is an object of the form { city: string, state: string }
public JsonObject fetchWeather(Location location, String date) {
// TODO(developer): Write a standard function that would call to an external weather API.
// For demo purposes, this hypothetical response is hardcoded here in the expected format.
return new JsonObject(Map.of(
"temperature", JsonPrimitive(38),
"chancePrecipitation", JsonPrimitive("56%"),
"cloudConditions", JsonPrimitive("partlyCloudy")));
}
Web
// This function calls a hypothetical external API that returns
// a collection of weather information for a given location on a given date.
// `location` is an object of the form { city: string, state: string }
async function fetchWeather({ location, date }) {
// TODO(developer): Write a standard function that would call to an external weather API.
// For demo purposes, this hypothetical response is hardcoded here in the expected format.
return {
temperature: 38,
chancePrecipitation: "56%",
cloudConditions: "partlyCloudy",
};
}
Dart
// This function calls a hypothetical external API that returns
// a collection of weather information for a given location on a given date.
// `location` is an object of the form { city: string, state: string }
Future<Map<String, Object?>> fetchWeather(
Location location, String date
) async {
// TODO(developer): Write a standard function that would call to an external weather API.
// For demo purposes, this hypothetical response is hardcoded here in the expected format.
final apiResponse = {
'temperature': 38,
'chancePrecipitation': '56%',
'cloudConditions': 'partlyCloudy',
};
return apiResponse;
}
Unity
// This function calls a hypothetical external API that returns
// a collection of weather information for a given location on a given date.
System.Collections.Generic.Dictionary<string, object> FetchWeather(
string city, string state, string date) {
// TODO(developer): Write a standard function that would call an external weather API.
// For demo purposes, this hypothetical response is hardcoded here in the expected format.
return new System.Collections.Generic.Dictionary<string, object>() {
{"temperature", 38},
{"chancePrecipitation", "56%"},
{"cloudConditions", "partlyCloudy"},
};
}
Шаг 2. Создайте объявление функции
Создайте декларацию функции, которую вы позже предоставите модели (следующий шаг этого руководства).
В декларации укажите как можно больше подробностей в описаниях функции и ее параметров.
Модель использует информацию в объявлении функции, чтобы определить, какую функцию выбрать и как предоставить значения параметров для фактического вызова функции. О том, как модель выбирает функции и как вы можете управлять этим выбором, рассказывается в разделе Дополнительные варианты поведения и настройки ниже на этой странице.
Обратите внимание на следующие особенности схемы:
Декларации функций должны быть представлены в формате схемы, совместимом с OpenAPI. Agent Platform поддерживает схему OpenAPI с ограничениями.
Поддерживаются следующие атрибуты:
type,nullable,required,format,description,properties,items,enum.Следующие атрибуты не поддерживаются:
default,optional,maximum,oneOf.
По умолчанию в Firebase AI Logic SDK все поля считаются обязательными, если вы не укажете их как необязательные в массиве
optionalProperties. Для этих необязательных полей параметров модель может заполнить поля или пропустить их. Обратите внимание, что это противоположно режиму работы по умолчанию двух поставщиков Gemini API, если вы используете их серверные SDK или их API напрямую.
Рекомендации по объявлениям функций, в том числе советы по названиям и описаниям, можно найти в разделе Рекомендации документации Google Cloud: Рекомендации в документации Gemini Developer API.
Вот как можно объявить функцию:
Swift
let fetchWeatherTool = FunctionDeclaration(
name: "fetchWeather",
description: "Get the weather conditions for a specific city on a specific date.",
parameters: [
"location": .object(
properties: [
"city": .string(description: "The city of the location."),
"state": .string(description: "The US state of the location."),
],
description: """
The name of the city and its state for which to get the weather. Only cities in the
USA are supported.
"""
),
"date": .string(
description: """
The date for which to get the weather. Date must be in the format: YYYY-MM-DD.
"""
),
]
)
Kotlin
val fetchWeatherTool = FunctionDeclaration(
"fetchWeather",
"Get the weather conditions for a specific city on a specific date.",
mapOf(
"location" to Schema.obj(
mapOf(
"city" to Schema.string("The city of the location."),
"state" to Schema.string("The US state of the location."),
),
description = "The name of the city and its state for which " +
"to get the weather. Only cities in the " +
"USA are supported."
),
"date" to Schema.string("The date for which to get the weather." +
" Date must be in the format: YYYY-MM-DD."
),
),
)
Java
FunctionDeclaration fetchWeatherTool = new FunctionDeclaration(
"fetchWeather",
"Get the weather conditions for a specific city on a specific date.",
Map.of("location",
Schema.obj(Map.of(
"city", Schema.str("The city of the location."),
"state", Schema.str("The US state of the location."))),
"date",
Schema.str("The date for which to get the weather. " +
"Date must be in the format: YYYY-MM-DD.")),
Collections.emptyList());
Web
const fetchWeatherTool: FunctionDeclarationsTool = {
functionDeclarations: [
{
name: "fetchWeather",
description:
"Get the weather conditions for a specific city on a specific date",
parameters: Schema.object({
properties: {
location: Schema.object({
description:
"The name of the city and its state for which to get " +
"the weather. Only cities in the USA are supported.",
properties: {
city: Schema.string({
description: "The city of the location."
}),
state: Schema.string({
description: "The US state of the location."
}),
},
}),
date: Schema.string({
description:
"The date for which to get the weather. Date must be in the" +
" format: YYYY-MM-DD.",
}),
},
}),
},
],
};
Dart
final fetchWeatherTool = FunctionDeclaration(
'fetchWeather',
'Get the weather conditions for a specific city on a specific date.',
parameters: {
'location': Schema.object(
description:
'The name of the city and its state for which to get'
'the weather. Only cities in the USA are supported.',
properties: {
'city': Schema.string(
description: 'The city of the location.'
),
'state': Schema.string(
description: 'The US state of the location.'
),
},
),
'date': Schema.string(
description:
'The date for which to get the weather. Date must be in the format: YYYY-MM-DD.'
),
},
);
Unity
var fetchWeatherTool = new Tool(new FunctionDeclaration(
name: "fetchWeather",
description: "Get the weather conditions for a specific city on a specific date.",
parameters: new System.Collections.Generic.Dictionary<string, Schema>() {
{ "location", Schema.Object(
properties: new System.Collections.Generic.Dictionary<string, Schema>() {
{ "city", Schema.String(description: "The city of the location.") },
{ "state", Schema.String(description: "The US state of the location.")}
},
description: "The name of the city and its state for which to get the weather. Only cities in the USA are supported."
) },
{ "date", Schema.String(
description: "The date for which to get the weather. Date must be in the format: YYYY-MM-DD."
)}
}
));
Шаг 3. Укажите декларацию функции при инициализации модели
В запросе можно указать не более 128 объявлений функций. Подробнее о том, как модель выбирает функции и как вы можете управлять этим выбором (используя toolConfig для настройки режима вызова функций), рассказывается в разделе Дополнительные варианты поведения и настройки.
Swift
import FirebaseAILogic
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
let model = FirebaseAI.firebaseAI(backend: .googleAI()).generativeModel(
modelName: "GEMINI_MODEL_NAME",
// Provide the function declaration to the model.
tools: [.functionDeclarations([fetchWeatherTool])]
)
Kotlin
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
modelName = "<var>GEMINI_MODEL_NAME</var>",
// Provide the function declaration to the model.
tools = listOf(Tool.functionDeclarations(listOf(fetchWeatherTool)))
)
Java
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
GenerativeModelFutures model = GenerativeModelFutures.from(
FirebaseAI.getInstance(GenerativeBackend.googleAI())
.generativeModel("<var>GEMINI_MODEL_NAME</var>",
null,
null,
// Provide the function declaration to the model.
List.of(Tool.functionDeclarations(List.of(fetchWeatherTool)))));
Web
import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";
// TODO(developer): Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
// ...
};
// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);
// Initialize the Gemini Developer API backend service.
const firebaseAI = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Create a `GenerativeModel` instance with a model that supports your use case.
const model = getGenerativeModel(firebaseAI, {
model: "GEMINI_MODEL_NAME",
// Provide the function declaration to the model.
tools: fetchWeatherTool
});
Dart
import 'package:firebase_ai/firebase_ai.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
// Initialize FirebaseApp
await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
_functionCallModel = FirebaseAI.googleAI().generativeModel(
model: 'GEMINI_MODEL_NAME',
// Provide the function declaration to the model.
tools: [
Tool.functionDeclarations([fetchWeatherTool]),
],
);
Unity
using Firebase;
using Firebase.AI;
// Initialize the Gemini Developer API backend service.
// Create a `GenerativeModel` instance with a model that supports your use case.
var model = FirebaseAI.DefaultInstance.GetGenerativeModel(
modelName: "GEMINI_MODEL_NAME",
// Provide the function declaration to the model.
tools: new Tool[] { fetchWeatherTool }
);
Узнайте, как выбрать модель для вашего приложения и варианта использования.
Шаг 4. Вызовите функцию, чтобы вызвать внешний API
Если модель решит, что функция fetchWeather действительно поможет ей сгенерировать окончательный ответ, ваше приложение должно выполнить фактический вызов этой функции, используя структурированные входные данные, предоставленные моделью.
Поскольку между моделью и приложением необходимо передавать информацию, рекомендуется использовать вызов функций через интерфейс многоходового чата.
В приведенном ниже фрагменте кода показано, как приложение получает информацию о том, что модель хочет использовать функцию fetchWeather. Также видно, что модель предоставила необходимые значения входных параметров для вызова функции (и ее базового внешнего API).
В этом примере входящий запрос содержал подсказку What was the weather in Boston on October 17, 2024?. На основе этого запроса модель определила входные параметры, необходимые для функции fetchWeather (то есть city, state и date).
Swift
let chat = model.startChat()
let prompt = "What was the weather in Boston on October 17, 2024?"
// Send the user's question (the prompt) to the model using multi-turn chat.
let response = try await chat.sendMessage(prompt)
var functionResponses = [FunctionResponsePart]()
// When the model responds with one or more function calls, invoke the function(s).
for functionCall in response.functionCalls {
if functionCall.name == "fetchWeather" {
// TODO(developer): Handle invalid arguments.
guard case let .object(location) = functionCall.args["location"] else { fatalError() }
guard case let .string(city) = location["city"] else { fatalError() }
guard case let .string(state) = location["state"] else { fatalError() }
guard case let .string(date) = functionCall.args["date"] else { fatalError() }
functionResponses.append(FunctionResponsePart(
name: functionCall.name,
// Forward the structured input data prepared by the model
// to the hypothetical external API.
response: fetchWeather(city: city, state: state, date: date)
))
}
// TODO(developer): Handle other potential function calls, if any.
}
Kotlin
val prompt = "What was the weather in Boston on October 17, 2024?"
val chat = model.startChat()
// Send the user's question (the prompt) to the model using multi-turn chat.
val result = chat.sendMessage(prompt)
val functionCalls = result.functionCalls
// When the model responds with one or more function calls, invoke the function(s).
val fetchWeatherCall = functionCalls.find { it.name == "fetchWeather" }
// Forward the structured input data prepared by the model
// to the hypothetical external API.
val functionResponse = fetchWeatherCall?.let {
// Alternatively, if your `Location` class is marked as @Serializable, you can use
// val location = Json.decodeFromJsonElement<Location>(it.args["location"]!!)
val location = Location(
it.args["location"]!!.jsonObject["city"]!!.jsonPrimitive.content,
it.args["location"]!!.jsonObject["state"]!!.jsonPrimitive.content
)
val date = it.args["date"]!!.jsonPrimitive.content
fetchWeather(location, date)
}
Java
String prompt = "What was the weather in Boston on October 17, 2024?";
ChatFutures chatFutures = model.startChat();
// Send the user's question (the prompt) to the model using multi-turn chat.
ListenableFuture<GenerateContentResponse> response =
chatFutures.sendMessage(new Content("user", List.of(new TextPart(prompt))));
ListenableFuture<JsonObject> handleFunctionCallFuture = Futures.transform(response, result -> {
for (FunctionCallPart functionCall : result.getFunctionCalls()) {
if (functionCall.getName().equals("fetchWeather")) {
Map<String, JsonElement> args = functionCall.getArgs();
JsonObject locationJsonObject =
JsonElementKt.getJsonObject(args.get("location"));
String city =
JsonElementKt.getContentOrNull(
JsonElementKt.getJsonPrimitive(
locationJsonObject.get("city")));
String state =
JsonElementKt.getContentOrNull(
JsonElementKt.getJsonPrimitive(
locationJsonObject.get("state")));
Location location = new Location(city, state);
String date = JsonElementKt.getContentOrNull(
JsonElementKt.getJsonPrimitive(
args.get("date")));
return fetchWeather(location, date);
}
}
return null;
}, Executors.newSingleThreadExecutor());
Web
const chat = model.startChat();
const prompt = "What was the weather in Boston on October 17, 2024?";
// Send the user's question (the prompt) to the model using multi-turn chat.
let result = await chat.sendMessage(prompt);
const functionCalls = result.response.functionCalls();
let functionCall;
let functionResult;
// When the model responds with one or more function calls, invoke the function(s).
if (functionCalls.length > 0) {
for (const call of functionCalls) {
if (call.name === "fetchWeather") {
// Forward the structured input data prepared by the model
// to the hypothetical external API.
functionResult = await fetchWeather(call.args);
functionCall = call;
}
}
}
Dart
final chat = _functionCallModel.startChat();
const prompt = 'What was the weather in Boston on October 17, 2024?';
// Send the user's question (the prompt) to the model using multi-turn chat.
var response = await chat.sendMessage(Content.text(prompt));
final functionCalls = response.functionCalls.toList();
// When the model responds with one or more function calls, invoke the function(s).
if (functionCalls.isNotEmpty) {
for (final functionCall in functionCalls) {
if (functionCall.name == 'fetchWeather') {
Map<String, dynamic> location =
functionCall.args['location']! as Map<String, dynamic>;
var date = functionCall.args['date']! as String;
var city = location['city'] as String;
var state = location['state'] as String;
final functionResult =
await fetchWeather(Location(city, state), date);
// Send the response to the model so that it can use the result to
// generate text for the user.
response = await functionCallChat.sendMessage(
Content.functionResponse(functionCall.name, functionResult),
);
}
}
} else {
throw UnimplementedError(
'Function not declared to the model: ${functionCall.name}',
);
}
Unity
var chat = model.StartChat();
var prompt = "What was the weather in Boston on October 17, 2024?";
// Send the user's question (the prompt) to the model using multi-turn chat.
var response = await chat.SendMessageAsync(prompt);
var functionResponses = new List<ModelContent>();
foreach (var functionCall in response.FunctionCalls) {
if (functionCall.Name == "fetchWeather") {
// TODO(developer): Handle invalid arguments.
var city = functionCall.Args["city"] as string;
var state = functionCall.Args["state"] as string;
var date = functionCall.Args["date"] as string;
functionResponses.Add(ModelContent.FunctionResponse(
name: functionCall.Name,
// Forward the structured input data prepared by the model
// to the hypothetical external API.
response: FetchWeather(city: city, state: state, date: date)
));
}
// TODO(developer): Handle other potential function calls, if any.
}
Шаг 5. Передайте выходные данные функции модели, чтобы сгенерировать окончательный ответ
После того как функция fetchWeather вернет информацию о погоде, ваше приложение должно передать ее обратно модели.
Затем модель выполняет окончательную обработку и генерирует ответ на естественном языке, например:
On October 17, 2024 in Boston, it was 38 degrees Fahrenheit with partly cloudy skies.
Swift
// Send the response(s) from the function back to the model
// so that the model can use it to generate its final response.
let finalResponse = try await chat.sendMessage(
[ModelContent(role: "user", parts: functionResponses)]
)
// Log the text response.
print(finalResponse.text ?? "No text in response.")
Kotlin
// Send the response(s) from the function back to the model
// so that the model can use it to generate its final response.
val finalResponse = chat.sendMessage(content("user") {
part(FunctionResponsePart("fetchWeather", functionResponse!!))
})
// Log the text response.
println(finalResponse.text ?: "No text in response")
Java
ListenableFuture<GenerateContentResponse> modelResponseFuture = Futures.transformAsync(
handleFunctionCallFuture,
// Send the response(s) from the function back to the model
// so that the model can use it to generate its final response.
functionCallResult -> chatFutures.sendMessage(new Content("user",
List.of(new FunctionResponsePart(
"fetchWeather", functionCallResult)))),
Executors.newSingleThreadExecutor());
Futures.addCallback(modelResponseFuture, new FutureCallback<GenerateContentResponse>() {
@Override
public void onSuccess(GenerateContentResponse result) {
if (result.getText() != null) {
// Log the text response.
System.out.println(result.getText());
}
}
@Override
public void onFailure(Throwable t) {
// handle error
}
}, Executors.newSingleThreadExecutor());
Web
// Send the response from the function back to the model
// so that the model can use it to generate its final response.
result = await chat.sendMessage([
{
functionResponse: {
name: functionCall.name, // "fetchWeather"
response: functionResult,
},
},
]);
console.log(result.response.text());
Dart
// Send the response from the function back to the model
// so that the model can use it to generate its final response.
response = await chat
.sendMessage(Content.functionResponse(functionCall.name, functionResult));
Unity
// Send the response(s) from the function back to the model
// so that the model can use it to generate its final response.
var finalResponse = await chat.SendMessageAsync(functionResponses);
// Log the text response.
UnityEngine.Debug.Log(finalResponse.Text ?? "No text in response.");
Дополнительные действия и параметры
Ниже описаны дополнительные особенности вызова функций, которые необходимо учитывать в коде, и параметры, которыми можно управлять.
Модель может попросить вызвать функцию ещё раз или другую функцию.
Если ответа на вызов функции недостаточно для того, чтобы модель сгенерировала окончательный ответ, она может запросить дополнительный вызов функции или вызов совершенно другой функции. Это может произойти, только если в списке объявлений функций вы предоставили модели более одной функции.
Приложение должно быть готово к тому, что модель может запросить дополнительные вызовы функций.
Модель может запросить вызов нескольких функций одновременно.
В списке деклараций функций для модели можно указать до 128 функций. Поэтому модель может решить, что для создания окончательного ответа ей нужно использовать несколько функций. Иногда модель может решить вызвать некоторые из этих функций одновременно – это называется параллельным вызовом функций.
Ваше приложение должно быть готово к тому, что модель может запросить выполнение нескольких функций одновременно, и должно предоставить модели все ответы от этих функций.
Вы можете указать, как и может ли модель запрашивать вызов функций.
Вы можете задать ограничения на то, как и будет ли модель использовать предоставленные объявления функций. Это называется режимом вызова функций. Вот несколько примеров:
Вместо того чтобы позволить модели выбирать между немедленным ответом на естественном языке и вызовом функции, вы можете заставить ее всегда использовать вызовы функций. Это называется принудительным вызовом функций.
Если вы предоставите несколько объявлений функций, то сможете ограничить модель, чтобы она использовала только некоторые из них.
Вы реализуете эти ограничения (или режимы), добавив конфигурацию инструмента (toolConfig) вместе с запросом и объявлениями функций. В конфигурации инструмента можно указать один из следующих режимов. Наиболее полезный режим – ANY.
| Режим | Описание |
|---|---|
AUTO |
Поведение модели по умолчанию. Модель решает, использовать ли вызов функции или ответ на естественном языке. |
ANY |
Модель должна использовать вызовы функций ("принудительный вызов функций"). Чтобы ограничить модель подмножеством функций, укажите разрешенные названия функций в allowedFunctionNames.
|
NONE |
Модель не должна использовать вызовы функций. Это поведение аналогично запросу к модели без объявлений функций. |
Что ещё ты умеешь делать?
Попробуйте другие функции
- Создавайте многоходовые диалоги (чат).
- Создавать текст на основе текстовых запросов.
- Создавайте текст на основе различных типов файлов, например изображений, PDF-файлов, видео и аудио.
Как управлять созданием контента
- Изучите принципы создания запросов, в том числе рекомендации, стратегии и примеры.
- Настройте параметры модели, например максимальное количество выходных токенов, вероятность повторения выходных токенов и т. д.
- Настройки безопасности позволяют регулировать вероятность получения ответов, которые могут быть восприняты как вредоносные.
Подробнее о поддерживаемых моделях…
Узнайте больше о моделях, доступных для разных вариантов использования, а также об их квотах и тарифах.Оставить отзыв о работе Firebase AI Logic