Los modelos generativos son potentes para resolver muchos tipos de problemas. Sin embargo, tienen las siguientes limitaciones:
- Se congelan después del entrenamiento, lo que lleva a un conocimiento inactivo.
- No pueden consultar ni modificar datos externos.
Las llamadas a función pueden ayudarte a superar algunas de estas limitaciones. A veces, la llamada a función se denomina uso de herramientas porque permite que un modelo use herramientas externas, como APIs y funciones, para generar su respuesta final.
En esta guía, se muestra cómo implementar una configuración de llamada a función similar a la situación que se describe en la siguiente sección principal de esta página. A grandes rasgos, estos son los pasos para configurar las llamadas a función en tu app:
Paso 1: Escribe una función que pueda proporcionarle al modelo la información que necesita para generar su respuesta final (por ejemplo, la función puede llamar a una API externa).
Paso 2: Crea una declaración de función que describa la función y sus parámetros.
Paso 3: Proporciona la declaración de la función durante la inicialización del modelo para que este sepa cómo usarla, si es necesario.
Paso 4: Configura tu app para que el modelo pueda enviar la información necesaria para que la app llame a la función.
Paso 5: Pasa la respuesta de la función al modelo para que este pueda generar su respuesta final.
Ir a la implementación de código
Descripción general de un ejemplo de llamada a función
Cuando envías una solicitud al modelo, también puedes proporcionarle un conjunto de “herramientas” (como funciones) que puede usar para generar su respuesta final. Para usar estas funciones y llamarlas ("llamadas a función"), el modelo y tu app deben pasar información entre sí, por lo que la forma recomendada de usar las llamadas a función es a través de la interfaz de chat de varias vueltas.
Imagina que tienes una app en la que un usuario podría ingresar un mensaje como el siguiente:
What was the weather in Boston on October 17, 2024?
.
Es posible que los modelos de Gemini no conozcan esta información del clima. Sin embargo, imagina que conoces una API de servicio meteorológico externo que puede proporcionarla. Puedes usar las llamadas a función para darle al modelo Gemini una ruta a esa API y su información del clima.
Primero, escribes una función fetchWeather
en tu app que interactúa con esta API externa hipotética, que tiene esta entrada y salida:
Parámetro | Tipo | Obligatorio | Descripción |
---|---|---|---|
Entrada | |||
location |
Objeto | Sí | Es el nombre de la ciudad y su estado para obtener el clima. Solo se admiten ciudades de EE.UU. Siempre debe ser un objeto anidado de city y state .
|
date |
String | Sí | Es la fecha para la que se recuperará el clima (siempre debe estar en formato YYYY-MM-DD ).
|
Salida | |||
temperature |
Número entero | Sí | Temperatura (en grados Fahrenheit) |
chancePrecipitation |
String | Sí | Probabilidad de precipitaciones (expresada como porcentaje) |
cloudConditions |
String | Sí | Condiciones de la nube (una de clear , partlyCloudy ,
mostlyCloudy , cloudy )
|
Cuando inicializas el modelo, le indicas que existe esta función fetchWeather
y cómo se puede usar para procesar las solicitudes entrantes, si es necesario.
Esto se denomina "declaración de función". El modelo no llama a la función
directamente. En cambio, a medida que el modelo procesa la solicitud entrante, decide si la función fetchWeather
puede ayudarlo a responderla. Si el modelo decide que la función puede ser útil, genera datos estructurados que ayudarán a que tu app llame a la función.
Vuelve a mirar la solicitud entrante: What was the weather in Boston on October 17, 2024?
. Es probable que el modelo decida que la función fetchWeather
puede ayudarlo a generar una respuesta. El
modelo analizaría qué parámetros de entrada se necesitan para fetchWeather
y, luego,
generaría datos de entrada estructurados para la función que se ven de la siguiente manera:
{
functionName: fetchWeather,
location: {
city: Boston,
state: Massachusetts // the model can infer the state from the prompt
},
date: 2024-10-17
}
El modelo pasa estos datos de entrada estructurados a tu app para que esta pueda llamar a la función fetchWeather
. Cuando tu app recibe las condiciones climáticas de la API, pasa la información al modelo. Esta información del clima permite que el modelo complete su procesamiento final y genere su respuesta a la solicitud inicial de What was the weather in Boston on October 17, 2024?
.
El modelo podría proporcionar una respuesta final de lenguaje natural, como la siguiente:
On October 17, 2024, in Boston, it was 38 degrees Fahrenheit with partly cloudy skies.
Implementa llamadas a función
En los siguientes pasos de esta guía, se muestra cómo implementar una configuración de llamada a función similar al flujo de trabajo que se describe en Descripción general de un ejemplo de llamada a función (consulta la sección superior de esta página).
Antes de comenzar
Haz clic en tu proveedor de Gemini API para ver el contenido y el código específicos del proveedor en esta página. |
Si aún no lo has hecho, completa la
guía de introducción, en la que se describe cómo
configurar tu proyecto de Firebase, conectar tu app a Firebase, agregar el SDK,
inicializar el servicio de backend para el proveedor de Gemini API que elijas y
crear una instancia de GenerativeModel
.
Para probar y iterar tus instrucciones y hasta conseguir un fragmento de código generado, te recomendamos usar Google AI Studio.
Paso 1: Escribe la función
Imagina que tienes una app en la que un usuario podría ingresar un mensaje como el siguiente:
What was the weather in Boston on October 17, 2024?
. Es posible que los modelos Gemini
no conozcan esta información del clima. Sin embargo, imagina que conoces una
API de servicio meteorológico externo que puede proporcionarla. La situación de esta guía depende de esta API externa hipotética.
Escribe la función en tu app que interactuará con la API externa hipotética y proporcionará al modelo la información que necesita para generar su solicitud final. En este ejemplo del clima, será una función fetchWeather
la que realice la llamada a esta hipotética API externa.
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"},
};
}
Paso 2: Crea una declaración de función
Crea la declaración de función que más adelante le proporcionarás al modelo (siguiente paso de esta guía).
En tu declaración, incluye tantos detalles como sea posible en las descripciones de la función y sus parámetros.
El modelo usa la información de la declaración de la función para determinar qué función seleccionar y cómo proporcionar valores de parámetros para la llamada real a la función. Consulta Opciones y comportamientos adicionales más adelante en esta página para saber cómo el modelo puede elegir entre las funciones y cómo puedes controlar esa elección.
Ten en cuenta lo siguiente sobre el esquema que proporciones:
Debes proporcionar declaraciones de funciones en un formato de esquema que sea compatible con el esquema de OpenAPI. Vertex AI ofrece asistencia limitada del esquema de OpenAPI.
Los siguientes atributos son compatibles:
type
,nullable
,required
,format
,description
,properties
,items
,enum
.Los siguientes atributos no son compatibles:
default
,optional
,maximum
,oneOf
.
De forma predeterminada, para los SDK de Firebase AI Logic, todos los campos se consideran obligatorios, a menos que los especifiques como opcionales en un array
optionalProperties
. En el caso de estos campos opcionales, el modelo puede propagarlos o omititlos. Ten en cuenta que esto es lo opuesto al comportamiento predeterminado de los dos proveedores de Gemini API si usas sus SDKs de servidor o su API directamente.
Para conocer las prácticas recomendadas relacionadas con las declaraciones de funciones, incluidas sugerencias de nombres y descripciones, consulta Prácticas recomendadas en la documentación de Gemini Developer API.
A continuación, te indicamos cómo puedes escribir una declaración de función:
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 = {
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."
)}
}
));
Paso 3: Proporciona la declaración de la función durante la inicialización del modelo
La cantidad máxima de declaraciones de funciones que puedes proporcionar con la solicitud es de 128. Consulta
Comportamientos y opciones adicionales
más adelante en esta página para saber cómo el modelo puede elegir entre las funciones y
cómo puedes controlar esa elección (con un toolConfig
para establecer el
modo de llamada a función).
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.0-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.0-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.0-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.0-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.0-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.0-flash",
// Provide the function declaration to the model.
tools: new Tool[] { fetchWeatherTool }
);
Aprende a elegir un modelo apropiado para tu caso de uso y tu app.
Paso 4: Llama a la función para invocar la API externa
Si el modelo decide que la función fetchWeather
puede ayudarlo a generar una respuesta final, tu app debe realizar la llamada real a esa función con los datos de entrada estructurados que proporciona el modelo.
Dado que la información debe pasarse entre el modelo y la app, la forma recomendada de usar las llamadas a función es a través de la interfaz de chat de varias vueltas.
En el siguiente fragmento de código, se muestra cómo se le indica a tu app que el modelo quiere usar la función fetchWeather
. También muestra que el modelo proporcionó los
valores de parámetros de entrada necesarios para la llamada a función (y su API
externa subyacente).
En este ejemplo, la solicitud entrante contenía la instrucción What was the weather in Boston on October 17, 2024?
. A partir de esta instrucción, el modelo infirió los parámetros de entrada que requiere la función fetchWeather
(es decir, city
, state
y 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) {
final functionCall = functionCalls.first;
if (functionCall.name == 'fetchWeather') {
// Forward the structured input data prepared by the model
// to the hypothetical external API.
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);
...
} 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.
}
Paso 5: Proporciona el resultado de la función al modelo para generar la respuesta final
Después de que la función fetchWeather
muestra la información del clima, tu app debe pasarla al modelo.
Luego, el modelo realiza su procesamiento final y genera una respuesta final de lenguaje natural, como la siguiente: 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.");
Opciones y comportamientos adicionales
Estos son algunos comportamientos adicionales de las llamadas a función que debes adaptar a tu código y las opciones que puedes controlar.
Es posible que el modelo solicite volver a llamar a una función o a otra.
Si la respuesta de una llamada a función no es suficiente para que el modelo genere su respuesta final, es posible que el modelo solicite una llamada a función adicional o una llamada a una función completamente diferente. Esto último solo puede ocurrir si le proporcionas más de una función al modelo en la lista de declaraciones de funciones.
Tu app debe adaptarse a que el modelo pueda solicitar llamadas de función adicionales.
Es posible que el modelo solicite llamar a varias funciones al mismo tiempo.
Puedes proporcionar hasta 128 funciones en la lista de declaración de funciones al modelo. Teniendo en cuenta esto, el modelo puede decidir que se necesitan varias funciones para ayudarlo a generar su respuesta final. Y puede decidir llamar a algunas de estas funciones al mismo tiempo, lo que se denomina llamada a función en paralelo.
Tu app debe adaptarse a que el modelo pueda solicitar que se ejecuten varias funciones al mismo tiempo y debe proporcionar todas las respuestas de las funciones al modelo.
Puedes controlar cómo y si el modelo puede solicitar llamar a funciones.
Puedes colocar algunas restricciones sobre cómo y si el modelo debe usar las declaraciones de funciones proporcionadas. Esto se denomina configuración del modo de llamada a función. Estos son algunos ejemplos:
En lugar de permitir que el modelo elija entre una respuesta inmediata de lenguaje natural y una llamada a función, puedes forzarlo para que siempre use llamadas a función. Esto se denomina llamada a función forzada.
Si proporcionas varias declaraciones de funciones, puedes restringir el modelo para que use solo un subconjunto de las funciones proporcionadas.
Para implementar estas restricciones (o modos), agrega una configuración de herramienta (toolConfig
) junto con la instrucción y las declaraciones de funciones. En la configuración de la herramienta, puedes especificar uno de los siguientes modos. El modo más útil es ANY
.
Mode | Descripción |
---|---|
AUTO |
El comportamiento predeterminado del modelo. El modelo decide si usar una llamada a función o una respuesta de lenguaje natural. |
ANY |
El modelo debe usar llamadas a función (“llamadas a función forzadas”). Para limitar el modelo a un subconjunto de funciones, especifica los nombres de las funciones permitidas en allowedFunctionNames .
|
NONE |
El modelo no debe usar llamadas a función. Este comportamiento es equivalente a una solicitud de modelo sin ninguna declaración de función asociada. |
¿Qué más puedes hacer?
Prueba otras funciones
- Crea conversaciones de varios turnos (chat).
- Generar texto a partir de instrucciones de solo texto
- Genera texto con instrucciones de varios tipos de archivos, como imágenes, PDF, video y audio.
Aprende a controlar la generación de contenido
- Comprende el diseño de instrucciones, incluidas las prácticas recomendadas, las estrategias y los ejemplos de instrucciones.
- Configura los parámetros del modelo, como la temperatura y la cantidad máxima de tokens de salida (para Gemini) o la relación de aspecto y la generación de personas (para Imagen).
- Usa la configuración de seguridad para ajustar la probabilidad de recibir respuestas que se puedan considerar dañinas.
Más información sobre los modelos compatibles
Obtén información sobre los modelos disponibles para varios casos de uso y sus cuotas y precios.Envía comentarios sobre tu experiencia con Firebase AI Logic