Chiamate di funzione utilizzando l'API Gemini

I modelli generativi sono molto efficaci nel risolvere molti tipi di problemi. Tuttavia, sono vincolate da limitazioni quali:

  • Vengono bloccati dopo l'addestramento, il che porta a informazioni obsolete.
  • Non possono eseguire query o modificare i dati esterni.

Le chiamate di funzioni possono aiutarti a superare alcuni di questi limiti. A volte le chiamate di funzione sono chiamate utilizzo di strumenti perché consentono a un modello di utilizzare strumenti esterni come API e funzioni per generare la risposta finale.


Questa guida mostra come implementare una configurazione di chiamata di funzione simile allo scenario descritto nella prossima sezione principale di questa pagina. In linea di massima, Ecco i passaggi per configurare le chiamate di funzione nella tua app:

  • Passaggio 1: scrivi una funzione che possa fornire al modello le informazioni di cui ha bisogno per generare la risposta finale (ad esempio, la funzione può chiamare un'API esterna).

  • Passaggio 2: crea una dichiarazione di funzione che descriva la funzione e i relativi parametri.

  • Passaggio 3: fornisci la dichiarazione della funzione durante l'inizializzazione del modello in modo che il modello sappia come utilizzare la funzione, se necessario.

  • Passaggio 4: configura l'app in modo che il modello possa inviare le informazioni richieste per chiamare la funzione.

  • Passaggio 5: passa la risposta della funzione al modello in modo che possa generare la risposta finale.

Vai all'implementazione del codice

Panoramica di un esempio di chiamata di funzione

Quando invii una richiesta al modello, puoi anche fornirgli un insieme di "strumenti" (come le funzioni) che può utilizzare per generare la risposta finale. Per utilizzare queste funzioni e chiamarle ("chiamate di funzione"), il modello e la tua app devono scambiarsi informazioni, pertanto il modo consigliato per utilizzare le chiamate di funzione è tramite l'interfaccia di chat con più turni.

Immagina di avere un'app in cui un utente potrebbe inserire un prompt come: What was the weather in Boston on October 17, 2024?.

I modelli Gemini potrebbero non conoscere queste informazioni meteo. Tuttavia, immagina di conoscere un'API di servizio meteo esterno che può fornirle. Puoi utilizzare la chiamata di funzione per indicare al modello Gemini un percorso per accedere all'API e alle relative informazioni meteo.

Innanzitutto, scrivi una funzione fetchWeather nella tua app che interagisce con questa ipotetica API esterna, che ha questo input e output:

Parametro Tipo Obbligatorio Descrizione
Input
location Oggetto Il nome della città e del suo stato per cui ottenere il meteo.
Sono supportate solo le città degli Stati Uniti. Deve sempre essere un oggetto nidificato di city e state.
date Stringa Data per cui recuperare il meteo (deve sempre essere nel formato YYYY-MM-DD).
Output
temperature Numero intero Temperatura (in Fahrenheit)
chancePrecipitation Stringa Probabilità di precipitazioni (espressa in percentuale)
cloudConditions Stringa Condizioni cloud (una di clear, partlyCloudy, mostlyCloudy, cloudy)

Quando lo inzializzi, devi indicare al modello che questa funzione fetchWeather esiste e come può essere utilizzata per elaborare le richieste in arrivo, se necessario. Questa è una "dichiarazione di funzione". Il modello non chiama la funzione direttamente. Invece, durante l'elaborazione della richiesta in arrivo, il modello decide se la funzione fetchWeather può aiutarlo a rispondere alla richiesta. Se il modello decide che la funzione può essere effettivamente utile, genera dati strutturati che aiuteranno la tua app a chiamare la funzione.

Esamina di nuovo la richiesta in arrivo: What was the weather in Boston on October 17, 2024?. Il modello probabilmente deciderà che la funzione fetchWeather può aiutarlo a generare una risposta. Il modello esaminerà i parametri di input necessari per fetchWeather e poi genererà dati di input strutturati per la funzione che hanno all'incirca il seguente aspetto:

{
  functionName: fetchWeather,
  location: {
    city: Boston,
    state: Massachusetts  // the model can infer the state from the prompt
  },
  date: 2024-10-17
}

Il modello passa questi dati di input strutturati all'app in modo che possa chiamare la funzione fetchWeather. Quando l'app riceve le condizioni meteorologiche dall'API, le passa al modello. Queste informazioni sul clima consentono al modello di completare l'elaborazione finale e di generare la risposta alla richiesta iniziale di What was the weather in Boston on October 17, 2024?

Il modello potrebbe fornire una risposta finale in linguaggio naturale, ad esempio: On October 17, 2024, in Boston, it was 38 degrees Fahrenheit with partly cloudy skies.

Diagramma che mostra come la chiamata di funzione implichi l'interazione del modello con una funzione nell'app 

Puoi scoprire di più sulle chiamate di funzione nella documentazione di Gemini Developer API.

Implementare la chiamata di funzione

I passaggi successivi di questa guida mostrano come implementare una configurazione di chiamata di funzione simile al flusso di lavoro descritto in Panoramica di un esempio di chiamata di funzione (vedi la sezione in alto di questa pagina).

Prima di iniziare

Fai clic sul tuo fornitore Gemini API per visualizzare i contenuti e il codice specifici del fornitore in questa pagina.

Se non l'hai ancora fatto, consulta la guida introduttiva, che descrive come configurare il progetto Firebase, collegare l'app a Firebase, aggiungere l'SDK, inizializzare il servizio di backend per il provider Gemini API scelto e creare un'istanza GenerativeModel.

Per testare e eseguire l'iterazione sui prompt e persino per ottenere uno snippet di codice generato, ti consigliamo di utilizzare Google AI Studio.

Passaggio 1: scrivi la funzione

Immagina di avere un'app in cui un utente potrebbe inserire un prompt come: What was the weather in Boston on October 17, 2024?. I Gemini modelli potrebbero non conoscere queste informazioni meteo. Tuttavia, immagina di conoscere un'API di servizio meteo esterno che può fornirle. Lo scenario descritto in questa guida si basa su questa ipotetica API esterna.

Scrivi nella tua app la funzione che interagirà con l'ipotetica API esterna e fornirà al modello le informazioni di cui ha bisogno per generare la richiesta finale. In questo esempio di meteo, sarà una funzione fetchWeather che effettuerà la chiamata a questa ipotetica API esterna.

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"},
  };
}

Passaggio 2: crea una dichiarazione di funzione

Crea la dichiarazione della funzione che fornirai in un secondo momento al modello (passaggio successivo di questa guida).

Nella dichiarazione, includi il maggior numero di dettagli possibile nelle descrizioni della funzione e dei relativi parametri.

Il modello utilizza le informazioni nella dichiarazione della funzione per determinare quale funzione selezionare e come fornire i valori dei parametri per la chiamata effettiva alla funzione. Consulta la sezione Comportamenti e opzioni aggiuntivi di questa pagina per scoprire in che modo il modello può scegliere tra le funzioni e come puoi controllare questa scelta.

Tieni presente quanto segue in merito allo schema fornito:

  • Devi fornire le dichiarazioni di funzione in un formato dello schema compatibile con lo schema OpenAPI. Vertex AI offre un supporto limitato dello schema OpenAPI.

    • Sono supportati i seguenti attributi: type, nullable, required, format, description, properties, items, enum.

    • I seguenti attributi non sono supportati: default, optional, maximum, oneOf.

  • Per impostazione predefinita, per gli SDK Firebase AI Logic tutti i campi sono considerati obbligatori, a meno che non li specifichi come facoltativi in un array optionalProperties. Per questi campi facoltativi, il modello può completarli o ignorarli. Tieni presente che questo è il comportamento opposto a quello predefinito dei due fornitoriGemini API se utilizzi direttamente i loro SDK server o le loro API.

Per le best practice relative alle dichiarazioni di funzione, inclusi suggerimenti per nomi e descrizioni, consulta Best practice nella documentazione di Gemini Developer API.

Ecco come scrivere una dichiarazione di funzione:

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."
    )}
  }
));

Passaggio 3: fornisci la dichiarazione della funzione durante l'inizializzazione del modello

Il numero massimo di dichiarazioni di funzioni che puoi fornire con la richiesta è 128. Consulta la sezione Comportamenti e opzioni aggiuntivi di questa pagina per scoprire in che modo il modello può scegliere tra le funzioni e come puoi controllare questa scelta (utilizzando un toolConfig per impostare la modalità di chiamata delle funzioni).

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 }
);

Scopri come scegliere un modello appropriato per il tuo caso d'uso e la tua app.

Passaggio 4: chiama la funzione per richiamare l'API esterna

Se il modello decide che la funzione fetchWeather può effettivamente aiutarlo a generare una risposta finale, l'app deve effettuare la chiamata effettiva a questa funzione utilizzando i dati di input strutturati forniti dal modello.

Poiché le informazioni devono essere trasmesse avanti e indietro tra il modello e l'app, il modo consigliato per utilizzare le chiamate di funzione è tramite l'interfaccia di chat con più turni.

Il seguente snippet di codice mostra come viene comunicato all'app che il modello vuole utilizzare la funzione fetchWeather. Mostra anche che il modello ha fornito i valori dei parametri di input necessari per la chiamata della funzione (e la relativa API esterna di base).

In questo esempio, la richiesta in arrivo conteneva il prompt What was the weather in Boston on October 17, 2024?. Da questo prompt, il modello ha dedotto i parametri di input richiesti dalla funzione fetchWeather (ovvero 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) {
  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.
}

Passaggio 5: fornisci l'output della funzione al modello per generare la risposta finale

Dopo che la funzione fetchWeather restituisce le informazioni meteo, la tua app deve trasmetterle nuovamente al modello.

Il modello esegue l'elaborazione finale e genera una risposta finale in linguaggio naturale, ad esempio: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.");

Comportamenti e opzioni aggiuntivi

Di seguito sono riportati alcuni comportamenti aggiuntivi per le chiamate di funzioni che devi considerare nel codice e le opzioni che puoi controllare.

Il modello potrebbe chiedere di chiamare di nuovo una funzione o un'altra funzione.

Se la risposta di una chiamata di funzione non è sufficiente per consentire al modello di generare la risposta finale, il modello potrebbe richiedere un'altra chiamata di funzione o una chiamata a una funzione completamente diversa. Quest'ultimo può verificarsi solo se fornisci più di una funzione al modello nell'elenco di dichiarazione delle funzioni.

L'app deve tenere conto del fatto che il modello potrebbe richiedere chiamate di funzioni aggiuntive.

Il modello potrebbe richiedere di chiamare più funzioni contemporaneamente.

Puoi fornire fino a 128 funzioni nell'elenco delle dichiarazioni di funzione al modello. Di conseguenza, il modello potrebbe decidere che sono necessarie più funzioni per aiutarlo a generare la risposta finale. Potrebbe anche decidere di chiamare alcune di queste funzioni contemporaneamente: si tratta della chiamata di funzioni in parallelo.

L'app deve tenere conto del fatto che il modello potrebbe richiedere l'esecuzione di più funzioni contemporaneamente e deve fornire tutte le risposte delle funzioni al modello.

Puoi controllare come e se il modello può chiedere di chiamare funzioni.

Puoi applicare alcuni vincoli su come e se il modello deve utilizzare le dichiarazioni di funzione fornite. Questa operazione viene chiamata impostazione della modalità di chiamata di funzione. Ecco alcuni esempi:

  • Anziché consentire al modello di scegliere tra una risposta immediata in linguaggio naturale e una chiamata di funzione, puoi forzarlo a utilizzare sempre le chiamate di funzione. Questa operazione è chiamata chiamata di funzione forzata.

  • Se fornisci più dichiarazioni di funzioni, puoi limitare il modello a utilizzare solo un sottoinsieme delle funzioni fornite.

Implementi questi vincoli (o modalità) aggiungendo una configurazione dello strumento (toolConfig) insieme al prompt e alle dichiarazioni di funzione. Nella configurazione dello strumento, puoi specificare una delle seguenti modalità. La modalità più utile è ANY.

Modalità Descrizione
AUTO Il comportamento predefinito del modello. Il modello decide se utilizzare una chiamata di funzione o una risposta in linguaggio naturale.
ANY Il modello deve utilizzare chiamate di funzione ("chiamate di funzione forzate"). Per limitare il modello a un sottoinsieme di funzioni, specifica i nomi delle funzioni consentite in allowedFunctionNames.
NONE Il modello non deve utilizzare chiamate di funzione. Questo comportamento è equivalente a una richiesta di modello senza dichiarazioni di funzioni associate.



Cos'altro puoi fare?

Provare altre funzionalità

Scopri come controllare la generazione di contenuti

Puoi anche sperimentare con i prompt e le configurazioni del modello e persino ottenere uno snippet di codice generato utilizzando Google AI Studio.

Scopri di più sui modelli supportati

Scopri i modelli disponibili per vari casi d'uso e le relative quote e prezzi.


Inviare un feedback sulla tua esperienza con Firebase AI Logic