Generative Modelle eignen sich hervorragend für die Lösung vieler Probleme. Sie sind jedoch durch folgende Einschränkungen eingeschränkt:
- Nach dem Training werden sie eingefroren, was zu veraltetem Wissen führt.
- Sie können keine externen Daten abfragen oder ändern.
Mit Funktionsaufrufen können Sie einige dieser Einschränkungen umgehen. Funktionsaufrufe werden manchmal auch als Tool-Nutzung bezeichnet, da ein Modell externe Tools wie APIs und Funktionen verwenden kann, um die endgültige Antwort zu generieren.
In dieser Anleitung wird gezeigt, wie Sie eine Funktion ähnlich wie im nächsten Abschnitt dieser Seite beschrieben aufrufen können. Im Folgenden finden Sie eine allgemeine Anleitung zum Einrichten von Funktionsaufrufen in Ihrer App:
Schritt 1: Schreiben Sie eine Funktion, die dem Modell Informationen zur Verfügung stellen kann, die es zum Generieren der endgültigen Antwort benötigt. Die Funktion kann beispielsweise eine externe API aufrufen.
Schritt 2: Erstellen Sie eine Funktionsdeklaration, in der die Funktion und ihre Parameter beschrieben werden.
Schritt 3: Geben Sie die Funktionsdeklaration während der Modellinitialisierung an, damit das Modell weiß, wie es die Funktion bei Bedarf verwenden kann.
Schritt 4: Richten Sie Ihre App so ein, dass das Modell die erforderlichen Informationen senden kann, damit Ihre App die Funktion aufrufen kann.
Schritt 5: Übergeben Sie die Antwort der Funktion an das Modell zurück, damit es die endgültige Antwort generieren kann.
Beispiel für einen Funktionsaufruf
Wenn Sie eine Anfrage an das Modell senden, können Sie ihm auch eine Reihe von „Tools“ (z. B. Funktionen) zur Verfügung stellen, mit denen es die endgültige Antwort generieren kann. Damit diese Funktionen verwendet und aufgerufen werden können („Funktionsaufruf“), müssen das Modell und Ihre App Informationen miteinander austauschen. Daher wird empfohlen, den Funktionsaufruf über die Chatoberfläche mit mehreren Antworten zu verwenden.
Angenommen, Sie haben eine App, in der ein Nutzer einen Prompt wie den folgenden eingeben kann:
What was the weather in Boston on October 17, 2024?
.
Die Gemini-Modelle kennen diese Wetterinformationen möglicherweise nicht. Angenommen, Sie kennen eine externe Wetterdienst-API, die diese Daten bereitstellen kann. Mithilfe von Funktionsaufrufen können Sie dem Gemini-Modell einen Pfad zu dieser API und ihren Wetterinformationen geben.
Zuerst schreiben Sie in Ihrer App eine Funktion fetchWeather
, die mit dieser hypothetischen externen API interagiert. Diese hat folgende Eingabe und Ausgabe:
Parameter | Typ | Erforderlich | Beschreibung |
---|---|---|---|
Eingabe | |||
location |
Objekt | Ja | Der Name der Stadt und des Bundesstaats, für die das Wetter abgerufen werden soll. Nur Städte in den USA werden unterstützt. Muss immer ein verschachteltes Objekt von city und state sein.
|
date |
String | Ja | Datum, für das das Wetter abgerufen werden soll (muss immer im Format YYYY-MM-DD sein).
|
Ausgabe | |||
temperature |
Ganzzahl | Ja | Temperatur (in Fahrenheit) |
chancePrecipitation |
String | Ja | Niederschlagswahrscheinlichkeit (in Prozent) |
cloudConditions |
String | Ja | Wolkenbedingungen (clear , partlyCloudy , mostlyCloudy , cloudy )
|
Beim Initialisieren des Modells teilen Sie dem Modell mit, dass diese fetchWeather
-Funktion vorhanden ist und wie sie bei Bedarf zur Verarbeitung eingehender Anfragen verwendet werden kann.
Dies wird als „Funktionsdeklaration“ bezeichnet. Das Modell ruft die Funktion nicht direkt auf. Stattdessen entscheidet das Modell bei der Verarbeitung der eingehenden Anfrage, ob die fetchWeather
-Funktion bei der Beantwortung der Anfrage helfen kann. Wenn das Modell entscheidet, dass die Funktion tatsächlich nützlich sein kann, generiert es strukturierte Daten, die Ihrer App helfen, die Funktion aufzurufen.
Sehen Sie sich die eingehende Anfrage noch einmal an:
What was the weather in Boston on October 17, 2024?
. Das Modell würde wahrscheinlich entscheiden, dass die Funktion fetchWeather
ihm helfen kann, eine Antwort zu generieren. Das Modell würde prüfen, welche Eingabeparameter für fetchWeather
erforderlich sind, und dann strukturierte Eingabedaten für die Funktion generieren, die in etwa so aussehen:
{
functionName: fetchWeather,
location: {
city: Boston,
state: Massachusetts // the model can infer the state from the prompt
},
date: 2024-10-17
}
Das Modell übergibt diese strukturierten Eingabedaten an Ihre App, damit diese die fetchWeather
-Funktion aufrufen kann. Wenn Ihre App die Wetterbedingungen von der API zurückerhält, werden die Informationen an das Modell übergeben. Anhand dieser Wetterinformationen kann das Modell die endgültige Verarbeitung abschließen und eine Antwort auf die ursprüngliche Anfrage von What was the weather in Boston on October 17, 2024?
generieren.
Das Modell kann eine endgültige Antwort in natürlicher Sprache wie die folgende liefern:
On October 17, 2024, in Boston, it was 38 degrees Fahrenheit with partly cloudy skies.
Funktionsaufrufe implementieren
In den folgenden Schritten dieses Leitfadens wird beschrieben, wie Sie eine Funktion ähnlich wie im Workflow unter Beispiel für einen Funktionsaufruf (oben auf dieser Seite) einrichten.
Hinweis
Klicke auf deinen Gemini API-Anbieter, um dir anbieterspezifische Inhalte und Code auf dieser Seite anzusehen. |
Sehen Sie sich den Startleitfaden an, in dem beschrieben wird, wie Sie Ihr Firebase-Projekt einrichten, Ihre App mit Firebase verbinden, das SDK hinzufügen, den Backend-Dienst für den ausgewählten Gemini API-Anbieter initialisieren und eine GenerativeModel
-Instanz erstellen.
Zum Testen und Iterieren Ihrer Prompts und zum Generieren eines Code-Snippets empfehlen wir die Verwendung von Google AI Studio.
Schritt 1: Funktion schreiben
Angenommen, Sie haben eine App, in der ein Nutzer einen Prompt wie den folgenden eingeben kann:
What was the weather in Boston on October 17, 2024?
. Die Gemini-Modelle kennen diese Wetterinformationen möglicherweise nicht. Angenommen, Sie kennen eine externe Wetterdienst-API, die diese Informationen bereitstellen kann. Das Szenario in diesem Leitfaden basiert auf dieser hypothetischen externen API.
Schreiben Sie die Funktion in Ihre App, die mit der hypothetischen externen API interagiert und dem Modell die Informationen zur Verfügung stellt, die es zum Generieren der endgültigen Anfrage benötigt. In diesem Wetterbeispiel ist es eine fetchWeather
-Funktion, die den Aufruf dieser hypothetischen externen API ausführt.
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;
}
Einheit
// 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"},
};
}
Schritt 2: Funktionsdeklaration erstellen
Erstellen Sie die Funktionsdeklaration, die Sie später dem Modell zur Verfügung stellen (nächster Schritt in dieser Anleitung).
Geben Sie in Ihrer Deklaration so viele Details wie möglich in den Beschreibungen für die Funktion und ihre Parameter an.
Das Modell verwendet die Informationen in der Funktionsdeklaration, um zu bestimmen, welche Funktion ausgewählt werden soll und wie Parameterwerte für den tatsächlichen Funktionsaufruf angegeben werden. Unter Zusätzliche Verhaltensweisen und Optionen weiter unten auf dieser Seite erfahren Sie, wie das Modell zwischen den Funktionen auswählen kann und wie Sie diese Auswahl steuern können.
Beachten Sie Folgendes zum von Ihnen bereitgestellten Schema:
Sie müssen Funktionsdeklarationen in einem Schemaformat angeben, das mit dem OpenAPI-Schema kompatibel ist. Vertex AI bietet eingeschränkte Unterstützung für das OpenAPI-Schema.
Die folgenden Attribute sind zulässig:
type
,nullable
,required
,format
,description
,properties
,items
,enum
.Die folgenden Attribute werden nicht unterstützt:
default
,optional
,maximum
undoneOf
.
Bei Firebase AI Logic-SDKs gelten standardmäßig alle Felder als erforderlich, es sei denn, Sie geben sie in einem
optionalProperties
-Array als optional an. Für diese optionalen Felder kann das Modell die Felder ausfüllen oder überspringen. Hinweis: Das ist das Gegenteil des Standardverhaltens der beiden Gemini API-Anbieter, wenn Sie deren Server-SDKs oder APIs direkt verwenden.
Best Practices für Funktionsdeklarationen, einschließlich Tipps zu Namen und Beschreibungen, finden Sie in der Google Cloud-Dokumentation unter Best Practices in der Gemini Developer API-Dokumentation.
So schreiben Sie eine Funktionsdeklaration:
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.'
),
},
);
Einheit
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."
)}
}
));
Schritt 3: Funktionsdeklaration bei der Modellinitialisierung angeben
Die maximale Anzahl von Funktionsdeklarationen, die Sie mit der Anfrage angeben können, beträgt 128. Im Abschnitt Zusätzliche Verhaltensweisen und Optionen weiter unten auf dieser Seite erfahren Sie, wie das Modell zwischen den Funktionen auswählen kann und wie Sie diese Auswahl steuern können (mit einem toolConfig
, um den Modus für Funktionsaufrufe festzulegen).
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]),
],
);
Einheit
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 }
);
Weitere Informationen zur Auswahl eines Modells
Schritt 4: Funktion aufrufen, um die externe API aufzurufen
Wenn das Modell feststellt, dass die fetchWeather
-Funktion tatsächlich dabei helfen kann, eine endgültige Antwort zu generieren, muss Ihre App diese Funktion mit den vom Modell bereitgestellten strukturierten Eingabedaten aufrufen.
Da Informationen zwischen dem Modell und der App hin- und hergeleitet werden müssen, wird empfohlen, Funktionsaufrufe über die Chatoberfläche mit mehreren Antworten zu verwenden.
Im folgenden Code-Snippet wird Ihrer App mitgeteilt, dass das Modell die Funktion fetchWeather
verwenden möchte. Außerdem sehen Sie, dass das Modell die erforderlichen Eingabeparameterwerte für den Funktionsaufruf (und die zugrunde liegende externe API) bereitgestellt hat.
In diesem Beispiel enthielt die eingehende Anfrage den Prompt What was the weather in Boston on October 17, 2024?
. Anhand dieses Prompts hat das Modell die Eingabeparameter abgeleitet, die für die fetchWeather
-Funktion erforderlich sind (city
, state
und 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}',
);
}
Einheit
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.
}
Schritt 5: Ausgabe der Funktion für das Modell bereitstellen, um die endgültige Antwort zu generieren
Nachdem die fetchWeather
-Funktion die Wetterinformationen zurückgegeben hat, muss Ihre App sie an das Modell zurückgeben.
Anschließend führt das Modell die endgültige Verarbeitung durch und generiert eine endgültige Antwort in natürlicher Sprache wie:
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));
Einheit
// 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.");
Zusätzliche Verhaltensweisen und Optionen
Im Folgenden finden Sie einige zusätzliche Verhaltensweisen für Funktionsaufrufe, die Sie in Ihrem Code berücksichtigen müssen, sowie Optionen, die Sie steuern können.
Das Modell fordert Sie möglicherweise auf, eine Funktion noch einmal oder eine andere Funktion aufzurufen.
Wenn die Antwort eines Funktionsaufrufs nicht ausreicht, um die endgültige Antwort des Modells zu generieren, fordert das Modell möglicherweise einen zusätzlichen Funktionsaufruf oder einen Aufruf einer ganz anderen Funktion an. Letzteres kann nur passieren, wenn Sie dem Modell in Ihrer Funktionsdeklarationsliste mehr als eine Funktion zur Verfügung stellen.
Ihre App muss berücksichtigen, dass das Modell möglicherweise zusätzliche Funktionsaufrufe anfordert.
Das Modell kann mehrere Funktionen gleichzeitig aufrufen.
Sie können dem Modell bis zu 128 Funktionen in der Funktionsdeklarationsliste zur Verfügung stellen. Daher kann das Modell entscheiden, dass mehrere Funktionen erforderlich sind, um die endgültige Antwort zu generieren. Es kann auch entscheiden, einige dieser Funktionen gleichzeitig aufzurufen. Dies wird als paralleler Funktionsaufruf bezeichnet.
Ihre App muss berücksichtigen, dass das Modell möglicherweise mehrere Funktionen gleichzeitig anfordert, und alle Antworten der Funktionen an das Modell zurückgeben.
Sie können festlegen, wie und ob das Modell Funktionsaufrufe anfordern darf.
Sie können einige Einschränkungen dafür festlegen, wie und ob das Modell die bereitgestellten Funktionsdeklarationen verwenden soll. Dies wird als Festlegen des Aufrufmodus der Funktion bezeichnet. Hier sind einige Beispiele:
Anstatt dem Modell zu erlauben, zwischen einer sofortigen Antwort in natürlicher Sprache und einem Funktionsaufruf zu wählen, können Sie erzwingen, dass immer Funktionsaufrufe verwendet werden. Dies wird als erzwungener Funktionsaufruf bezeichnet.
Wenn Sie mehrere Funktionsdeklarationen angeben, können Sie das Modell darauf beschränken, nur eine Teilmenge der bereitgestellten Funktionen zu verwenden.
Sie implementieren diese Einschränkungen (oder Modi), indem Sie eine Toolkonfiguration (toolConfig
) zusammen mit dem Prompt und den Funktionsdeklarationen hinzufügen. In der Toolkonfiguration können Sie einen der folgenden Modi angeben. Der nützlichste Modus ist ANY
.
Modus | Beschreibung |
---|---|
AUTO |
Das Standardverhalten des Modells. Das Modell entscheidet, ob ein Funktionsaufruf oder eine Antwort in natürlicher Sprache verwendet werden soll. |
ANY |
Das Modell muss Funktionsaufrufe („erzwungene Funktionsaufrufe“) verwenden. Wenn Sie das Modell auf eine Teilmenge von Funktionen beschränken möchten, geben Sie die zulässigen Funktionsnamen in allowedFunctionNames an.
|
NONE |
Das Modell darf keine Funktionsaufrufe verwenden. Dieses Verhalten entspricht einer Modellanfrage ohne zugehörige Funktionsdeklarationen. |
Was können Sie sonst noch tun?
Weitere Funktionen ausprobieren
- Unterhaltungen in mehreren Runden (Chat) erstellen
- Text aus nur Text-Prompts generieren
- Sie können Text generieren, indem Sie verschiedene Dateitypen als Prompt verwenden, z. B. Bilder, PDFs, Videos und Audio.
Inhaltserstellung steuern
- Informationen zum Prompt-Design, einschließlich Best Practices, Strategien und Beispiel-Prompts.
- Konfigurieren Sie Modellparameter wie Temperatur und maximale Ausgabetokens (für Gemini) oder Seitenverhältnis und Personengenerierung (für Imagen).
- Mit den Sicherheitseinstellungen können Sie die Wahrscheinlichkeit anpassen, dass Sie Antworten erhalten, die als schädlich eingestuft werden könnten.
Weitere Informationen zu den unterstützten Modellen
Hier finden Sie Informationen zu den Modellen, die für verschiedene Anwendungsfälle verfügbar sind, sowie zu ihren Kontingenten und Preisen.Feedback zu Firebase AI Logic geben