Chiamate di funzione utilizzando l'API Gemini

I modelli generativi sono efficaci nella risoluzione di molti tipi di problemi. Tuttavia, sono vincolati da limitazioni quali:

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

La chiamata di funzioni può aiutarti a superare alcune di queste limitazioni. La chiamata di funzione viene a volte definita utilizzo di strumenti perché consente 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 sezione principale successiva di questa pagina. A livello generale, ecco i passaggi per configurare la chiamata di funzioni 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 utilizzarla, se necessario.

  • Passaggio 4: configura l'app in modo che il modello possa inviare le informazioni richieste per consentire all'app di 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 funzioni) che può utilizzare per generare la risposta finale. Per utilizzare queste funzioni e chiamarle ("chiamata di funzione"), il modello e la tua app devono scambiarsi informazioni, quindi il modo consigliato per utilizzare la chiamata di funzione è tramite l'interfaccia di chat multi-turno.

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

I modelli Gemini potrebbero non conoscere queste informazioni meteo, ma immagina di conoscere un'API di un servizio meteo esterno che può fornirle. Puoi utilizzare la chiamata di funzioni per fornire 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 dello stato per cui ottenere le previsioni 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 le previsioni 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 tra clear, partlyCloudy, mostlyCloudy, cloudy)

Quando inizializzi il modello, gli comunichi che questa funzione fetchWeather esiste e come può essere utilizzata per elaborare le richieste in entrata, se necessario. Questa operazione è chiamata "dichiarazione di funzione". Il modello non chiama la funzione direttamente. Al contrario, mentre il modello elabora la richiesta in entrata, decide se la funzione fetchWeather può aiutarlo a rispondere alla richiesta. Se il modello decide che la funzione può effettivamente essere 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 esaminerebbe i parametri di input necessari per fetchWeather e poi genererebbe dati di input strutturati per la funzione, che si presentano più o meno così:

{
  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 alla tua app in modo che possa chiamare la funzione fetchWeather. Quando la tua app riceve le condizioni meteo dall'API, trasmette le informazioni al modello. Queste informazioni meteo consentono al modello di completare l'elaborazione finale e 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 come: On October 17, 2024, in Boston, it was 38 degrees Fahrenheit with partly cloudy skies.

Diagramma che mostra in che modo la chiamata di funzioni prevede l'interazione del modello con una funzione nella tua app 

Puoi scoprire di più sulla chiamata di funzione nella documentazione di Gemini Developer API.

Implementare la chiamata di funzione

I passaggi seguenti 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, completa la guida introduttiva, che descrive come configurare il progetto Firebase, connettere 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 perfezionare i prompt e persino 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 può 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 un servizio meteo esterno che può fornirle. Lo scenario descritto in questa guida si basa su questa API esterna ipotetica.

Scrivi nella tua app la funzione che interagirà con l'API esterna ipotetica e fornirà al modello le informazioni necessarie per generare la richiesta finale. In questo esempio meteo, sarà una funzione fetchWeather che effettua 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 aggiuntive più avanti in questa pagina per scoprire come il modello può scegliere tra le funzioni e come puoi controllare questa scelta.

Tieni presente quanto segue in merito allo schema che fornisci:

  • Devi fornire dichiarazioni di funzione in un formato di 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ò compilare i campi o saltarli. Tieni presente che questo comportamento è opposto a quello predefinito dei due provider Gemini API se utilizzi i loro SDK server o la loro API direttamente.

Per le best practice relative alle dichiarazioni di funzione, inclusi suggerimenti per nomi e descrizioni, consulta Best practice nella documentazione di Google Cloud. 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 più avanti in questa pagina per scoprire come il modello può scegliere tra le funzioni, nonché come puoi controllare questa scelta (utilizzando 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.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 }
);

Scopri come scegliere un modello adatta al tuo caso d'uso e alla 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, la tua 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 la chiamata di funzione è tramite l'interfaccia di chat multi-turno.

Il seguente snippet di codice mostra come viene comunicato alla tua 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 di funzione (e la relativa API esterna sottostante).

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) {
  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.
}

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

Dopo che la funzione fetchWeather restituisce le informazioni meteo, l'app deve trasmetterle di nuovo al modello.

Successivamente, il modello esegue l'elaborazione finale e genera una risposta in linguaggio naturale come: 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 la chiamata di funzioni che devi integrare nel tuo 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 una chiamata di funzione aggiuntiva o una chiamata a una funzione completamente diversa. Ciò può accadere solo se fornisci più di una funzione al modello nell'elenco delle dichiarazioni di funzioni.

La tua app deve prevedere che il modello possa richiedere chiamate di funzioni aggiuntive.

Il modello potrebbe chiedere di chiamare più funzioni contemporaneamente.

Puoi fornire fino a 128 funzioni nell'elenco delle dichiarazioni di funzioni al modello. Per questo motivo, il modello potrebbe decidere che sono necessarie più funzioni per aiutarlo a generare la risposta finale. e potrebbe decidere di chiamare alcune di queste funzioni contemporaneamente. Questa operazione è chiamata chiamata di funzioni parallela.

La tua app deve prevedere che il modello possa richiedere l'esecuzione di più funzioni contemporaneamente e deve fornire al modello tutte le risposte delle funzioni.

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

Puoi inserire alcuni vincoli su come e se il modello deve utilizzare le dichiarazioni di funzioni 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 forzata di funzioni.

  • Se fornisci più dichiarazioni di funzioni, puoi limitare l'utilizzo del modello solo a un sottoinsieme delle funzioni fornite.

Implementa 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 le chiamate di funzione ("chiamata di funzione forzata"). 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 funzioni. Questo comportamento equivale a una richiesta di modello senza dichiarazioni di funzioni associate.



Cos'altro puoi fare?

Prova altre funzionalità

Scopri come controllare la generazione di contenuti

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

Scopri di più sui modelli supportati

Scopri di più sui modelli disponibili per vari casi d'uso e sulle relative quote e prezzi.


Fornisci un feedback sulla tua esperienza con Firebase AI Logic