Os modelos generativos são poderosos na resolução de muitos tipos de problemas. No entanto, eles são limitados por restrições como:
- Eles são congelados após o treinamento, levando a um conhecimento desatualizado.
- Eles não podem consultar nem modificar dados externos.
As chamadas de função podem ajudar você a superar algumas dessas limitações. A chamada de função às vezes é chamada de uso de ferramentas porque permite que um modelo use ferramentas externas, como APIs e funções, para gerar a resposta final.
Neste guia, mostramos como implementar uma configuração de chamada de função semelhante ao cenário descrito na próxima seção principal desta página. De modo geral, estas são as etapas para configurar a chamada de função no seu app:
Etapa 1: escreva uma função que possa fornecer ao modelo as informações necessárias para gerar a resposta final. Por exemplo, a função pode chamar uma API externa.
Etapa 2: crie uma declaração de função que descreva a função e os parâmetros dela.
Etapa 3: forneça a declaração de função durante a inicialização do modelo para que ele saiba como usar a função, se necessário.
Etapa 4: configure o app para que o modelo possa enviar as informações necessárias para que ele chame a função.
Etapa 5: transmita a resposta da função de volta ao modelo para que ele gere a resposta final.
Ir para a implementação do código
Visão geral de um exemplo de chamada de função
Ao enviar uma solicitação ao modelo, você também pode fornecer um conjunto de "ferramentas" (como funções) que ele pode usar para gerar a resposta final. Para usar e chamar essas funções (chamada de função), o modelo e o app precisam trocar informações entre si. Por isso, a maneira recomendada de usar a chamada de função é pela interface de chat em várias rodadas.
Imagine que você tenha um app em que um usuário possa inserir um comando como:
What was the weather in Boston on October 17, 2024?
.
Os modelos Gemini podem não ter essas informações, mas imagine que você conhece uma API de serviço meteorológico externo que pode fornecê-las. É possível usar a chamada de função para dar ao modelo Gemini um caminho para essa API e as informações meteorológicas dela.
Primeiro, escreva uma função fetchWeather
no seu app que interaja com essa
API externa hipotética, que tem esta entrada e saída:
Parâmetro | Tipo | Obrigatório | Descrição |
---|---|---|---|
Entrada | |||
location |
Objeto | Sim | O nome da cidade e do estado para receber a previsão do tempo. Somente cidades nos EUA são aceitas. Precisa ser sempre um objeto aninhado de city e state .
|
date |
String | Sim | Data para buscar a previsão do tempo (sempre no formato YYYY-MM-DD ).
|
Saída | |||
temperature |
Inteiro | Sim | Temperatura (em Fahrenheit) |
chancePrecipitation |
String | Sim | Possibilidade de chuva (expressa como uma porcentagem) |
cloudConditions |
String | Sim | Condições do Cloud (uma de clear , partlyCloudy , mostlyCloudy , cloudy )
|
Ao inicializar o modelo, você informa que essa função fetchWeather
existe e como ela pode ser usada para processar solicitações recebidas, se necessário.
Isso é chamado de "declaração de função". O modelo não chama a função
diretamente. Em vez disso, enquanto o modelo processa a solicitação recebida, ele
decide se a função fetchWeather
pode ajudar a responder à solicitação. Se
o modelo decidir que a função pode ser útil, ele vai gerar
dados estruturados que vão ajudar seu app a chamar a função.
Analise novamente a solicitação de entrada:
What was the weather in Boston on October 17, 2024?
. O modelo provavelmente
decidirá que a função fetchWeather
pode ajudar a gerar uma resposta. O modelo analisaria quais parâmetros de entrada são necessários para fetchWeather
e geraria dados de entrada estruturados para a função, que seriam parecidos com isto:
{
functionName: fetchWeather,
location: {
city: Boston,
state: Massachusetts // the model can infer the state from the prompt
},
date: 2024-10-17
}
O modelo transmite esses dados de entrada estruturados para o app, para que ele possa
chamar a função fetchWeather
. Quando o app recebe as condições climáticas
da API, ele transmite as informações para o modelo. Essas informações permitem que o modelo conclua o processamento final e gere a resposta à solicitação inicial de What was the weather in Boston on October 17, 2024?
.
O modelo pode fornecer uma resposta final em linguagem natural como:
On October 17, 2024, in Boston, it was 38 degrees Fahrenheit with partly cloudy skies.
Implementar chamadas de função
As etapas a seguir neste guia mostram como implementar uma configuração de chamada de função semelhante ao fluxo de trabalho descrito em Visão geral de um exemplo de chamada de função (consulte a seção superior desta página).
Antes de começar
Clique no seu provedor de Gemini API para conferir o conteúdo e o código específicos do provedor nesta página. |
Se ainda não tiver feito isso, conclua o
guia de primeiros passos, que descreve como
configurar seu projeto do Firebase, conectar seu app ao Firebase, adicionar o SDK,
inicializar o serviço de back-end para o provedor Gemini API escolhido e
criar uma instância GenerativeModel
.
Para testar e iterar em seus comandos e até mesmo receber um snippet de código gerado, recomendamos usar Google AI Studio.
Etapa 1: escrever a função
Imagine que você tenha um app em que um usuário possa inserir um comando como:
What was the weather in Boston on October 17, 2024?
. Os modelos Gemini podem não conhecer essas informações meteorológicas. No entanto, imagine que você conhece uma API de serviço meteorológico externo que pode fornecê-las. O cenário neste guia depende dessa API externa hipotética.
Escreva a função no app que vai interagir com a API externa hipotética e fornecer ao modelo as informações necessárias para gerar a solicitação final. Neste exemplo de clima, será uma função fetchWeather
que
faz a chamada para essa API externa hipotética.
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"},
};
}
Etapa 2: criar uma declaração de função
Crie a declaração de função que você vai fornecer ao modelo mais tarde (próxima etapa deste guia).
Na declaração, inclua o máximo de detalhes possível nas descrições da função e dos parâmetros dela.
O modelo usa as informações na declaração de função para determinar qual função selecionar e como fornecer valores de parâmetro para a chamada real da função. Consulte Outros comportamentos e opções mais adiante nesta página para saber como o modelo pode escolher entre as funções e como você pode controlar essa escolha.
Observe o seguinte sobre o esquema fornecido:
Você precisa fornecer declarações de função em um formato de esquema compatível com o esquema da OpenAPI. O Vertex AI oferece suporte limitado ao esquema da OpenAPI.
Os seguintes atributos são aceitos:
type
,nullable
,required
,format
,description
,properties
,items
,enum
.Os seguintes atributos não são aceitos:
default
,optional
,maximum
,oneOf
.
Por padrão, para SDKs Firebase AI Logic, todos os campos são considerados obrigatórios, a menos que você os especifique como opcionais em uma matriz
optionalProperties
. Para esses campos opcionais, o modelo pode preencher ou pular os campos. Isso é o oposto do comportamento padrão dos dois provedores Gemini API se você usar os SDKs do servidor ou a API deles diretamente.
Para conferir as práticas recomendadas relacionadas às declarações de função, incluindo dicas para nomes e descrições, consulte Práticas recomendadas na documentação do Gemini Developer API.
Veja como escrever uma declaração de função:
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."
)}
}
));
Etapa 3: fornecer a declaração de função durante a inicialização do modelo
O número máximo de declarações de função que podem ser fornecidas com a
solicitação é 128. Consulte Outros comportamentos e opções mais adiante nesta página para saber como o modelo pode escolher entre as funções e como controlar essa escolha (usando um toolConfig
para definir o modo de chamada de função).
Swift
import FirebaseAI
// 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-2.5-flash",
// 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 = "gemini-2.5-flash",
// 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("gemini-2.5-flash",
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-2.5-flash",
// 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-2.5-flash',
// 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-2.5-flash",
// Provide the function declaration to the model.
tools: new Tool[] { fetchWeatherTool }
);
Saiba como escolher um modelo adequado para seu caso de uso e app.
Etapa 4: chamar a função para invocar a API externa
Se o modelo decidir que a função fetchWeather
pode ajudar a gerar uma resposta final, seu app precisará fazer a chamada real para essa função usando os dados de entrada estruturados fornecidos pelo modelo.
Como as informações precisam ser transmitidas entre o modelo e o app, a maneira recomendada de usar a chamada de função é pela interface de chat em várias rodadas.
O snippet de código a seguir mostra como o app é informado de que o modelo quer
usar a função fetchWeather
. Ele também mostra que o modelo forneceu os valores de parâmetro de entrada necessários para a chamada de função (e a API externa subjacente).
Neste exemplo, a solicitação recebida continha o comando
What was the weather in Boston on October 17, 2024?
. Com base nesse comando, o modelo inferiu os parâmetros de entrada necessários para a função fetchWeather
(ou seja, city
, state
e 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.
}
Etapa 5: fornecer a saída da função ao modelo para gerar a resposta final
Depois que a função fetchWeather
retornar as informações meteorológicas, seu app
precisa transmiti-las de volta ao modelo.
Em seguida, o modelo realiza o processamento final e gera uma resposta final
em linguagem natural, como:
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: "function", 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("function") {
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("function",
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.");
Outros comportamentos e opções
Confira alguns comportamentos adicionais para chamadas de função que você precisa acomodar no seu código e opções que podem ser controladas.
O modelo pode pedir para chamar uma função novamente ou outra função.
Se a resposta de uma chamada de função for insuficiente para o modelo gerar a resposta final, ele poderá pedir uma chamada de função adicional ou uma chamada para uma função completamente diferente. Isso só acontece se você fornecer mais de uma função ao modelo na lista de declarações de função.
O app precisa acomodar o fato de que o modelo pode pedir mais chamadas de função.
O modelo pode pedir para chamar várias funções ao mesmo tempo.
É possível fornecer até 128 funções na lista de declarações de função para o modelo. Por isso, o modelo pode decidir que várias funções são necessárias para ajudar a gerar a resposta final. Ele pode decidir chamar algumas dessas funções ao mesmo tempo, o que é chamado de chamada de função paralela.
Seu app precisa acomodar o fato de que o modelo pode pedir várias funções em execução ao mesmo tempo, e seu app precisa fornecer todas as respostas das funções de volta ao modelo.
É possível controlar como e se o modelo pode pedir para chamar funções.
É possível impor algumas restrições sobre como e se o modelo precisa usar as declarações de função fornecidas. Isso é chamado de definição do modo de chamada de função. Veja alguns exemplos:
Em vez de permitir que o modelo escolha entre uma resposta imediata de linguagem natural e uma chamada de função, é possível forçar o uso de chamadas de função. Isso é chamado de chamada de função forçada.
Se você fornecer várias declarações de função, poderá restringir o modelo para usar apenas um subconjunto das funções fornecidas.
Para implementar essas restrições (ou modos), adicione uma configuração de ferramenta (toolConfig
) com o comando e as declarações de função. Na configuração da ferramenta, é possível especificar um dos seguintes modos. O modo mais útil é ANY
.
Moda | Descrição |
---|---|
AUTO |
O comportamento padrão do modelo. O modelo decide se quer usar uma chamada de função ou uma resposta de linguagem natural. |
ANY |
O modelo precisa usar chamadas de função ("chamada de função forçada"). Para limitar
o modelo a um subconjunto de funções, especifique os nomes das funções permitidas em
allowedFunctionNames .
|
NONE |
O modelo não pode usar chamadas de função. Esse comportamento é equivalente a uma solicitação de modelo sem declarações de função associadas. |
O que mais você sabe fazer?
Testar outros recursos
- Crie conversas multiturno (chat).
- Gerar texto com base em comandos somente de texto.
- Gere texto usando comandos com vários tipos de arquivos, como imagens, PDFs, vídeos e áudios.
Saiba como controlar a geração de conteúdo
- Entenda o design de comandos, incluindo práticas recomendadas, estratégias e exemplos de comandos.
- Configure parâmetros do modelo, como temperatura e máximo de tokens de saída (para Gemini) ou proporção e geração de pessoas (para Imagen).
- Use as configurações de segurança para ajustar a probabilidade de receber respostas que possam ser consideradas prejudiciais.
Saiba mais sobre os modelos compatíveis
Saiba mais sobre os modelos disponíveis para vários casos de uso e as respectivas cotas e preços.Enviar feedback sobre sua experiência com Firebase AI Logic