Modele generatywne są skuteczne w rozwiązywaniu wielu typów problemów. Są one jednak ograniczone przez takie czynniki jak:
- Po trenowaniu są zamrażane, co prowadzi do nieaktualnej wiedzy.
- Nie mogą wysyłać zapytań do danych zewnętrznych ani ich modyfikować.
Wywołania funkcji mogą pomóc w pokonywaniu niektórych z tych ograniczeń. Funkcja wywoływania jest czasami nazywana używaniem narzędzia, ponieważ pozwala modelowi korzystać z zewnętrznych narzędzi, takich jak interfejsy API i funkcje, do generowania ostatecznej odpowiedzi.
Ten przewodnik pokazuje, jak zaimplementować wywołanie funkcji w sposób podobny do opisanego w następującej głównej sekcji tej strony. Ogólnie rzecz biorąc, aby skonfigurować wywoływanie funkcji w aplikacji:
Krok 1. Napisz funkcję, która może przekazać modelowi informacje potrzebne do wygenerowania ostatecznej odpowiedzi (funkcja może na przykład wywołać zewnętrzny interfejs API).
Krok 2. Utwórz deklarację funkcji, która opisuje funkcję i jej parametry.
Krok 3. Podczas inicjalizacji modelu podaj deklarację funkcji, aby model wiedział, jak z niej korzystać w razie potrzeby.
Krok 4. Skonfiguruj aplikację, aby model mógł wysłać wymagane informacje, które pozwolą aplikacji wywołać funkcję.
Krok 5. Przekaż odpowiedź funkcji z powrotem do modelu, aby mógł wygenerować ostateczną odpowiedź.
Omówienie przykładu wywołania funkcji
Wysyłając żądanie do modelu, możesz też przekazać mu zestaw „narzędzi” (np. funkcji), których może użyć do wygenerowania ostatecznej odpowiedzi. Aby korzystać z tych funkcji i je wywoływać (czyli „wywoływać funkcje”), model i Twoja aplikacja muszą wymieniać się informacjami. Dlatego zalecany sposób wywoływania funkcji to interfejs czatu wielostronnego.
Wyobraź sobie, że masz aplikację, w której użytkownik może wpisać prośbę o dostęp do danych:What was the weather in Boston on October 17, 2024?
.
Modele Gemini mogą nie znać tych informacji o pogodzie. Załóżmy jednak, że znasz interfejs API zewnętrznej usługi pogodowej, która może je udostępnić. Możesz wywołać funkcję, aby model Gemini uzyskał dostęp do tego interfejsu API i jego informacji o pogodzie.
Najpierw w aplikacji piszesz funkcję fetchWeather
, która współpracuje z tym hipotetycznym zewnętrznym interfejsem API i ma te dane wejściowe i wyjściowe:
Parametr | Typ | Wymagany | Opis |
---|---|---|---|
Dane wejściowe | |||
location |
Obiekt | Tak | Nazwa miasta i stanu, dla których ma być sprawdzana pogoda. Obsługiwane są tylko miasta w Stanach Zjednoczonych. Musi być zawsze zagnieżdżonym obiektem typu city lub state .
|
date |
Ciąg znaków | Tak | Data, dla której ma być pobierana pogoda (musi być zawsze w formacie YYYY-MM-DD ).
|
Wyniki | |||
temperature |
Liczba całkowita | Tak | Temperatura (w stopniach Fahrenheita) |
chancePrecipitation |
Ciąg znaków | Tak | Prawdopodobieństwo opadów (wyrażone w procentach) |
cloudConditions |
Ciąg znaków | Tak | Warunki Cloud (jeden z tych: clear , partlyCloudy ,
mostlyCloudy , cloudy )
|
Podczas inicjowania modelu informujesz go, że istnieje funkcja fetchWeather
i jak można jej używać do przetwarzania przychodzących żądań (jeśli to konieczne).
Jest to tzw. „deklaracja funkcji”. Model nie wywołuje funkcji bezpośrednio. Gdy model przetwarza przychodzące żądanie, decyduje, czy funkcja fetchWeather
może pomóc mu w odpowiedzi na to żądanie. Jeśli model uzna, że funkcja może być przydatna, wygeneruje uporządkowane dane, które pomogą Twojej aplikacji wywołać tę funkcję.
Ponownie spójrz na przychodzące żądanie:
What was the weather in Boston on October 17, 2024?
. Model z dużą dozą prawdopodobieństwa uzna, że funkcja fetchWeather
może pomóc w wygenerowaniu odpowiedzi. Model sprawdziłby, jakie parametry wejściowe są potrzebne do funkcji fetchWeather
, a następnie wygenerowałby uporządkowane dane wejściowe dla tej funkcji, które wyglądałyby mniej więcej tak:
{
functionName: fetchWeather,
location: {
city: Boston,
state: Massachusetts // the model can infer the state from the prompt
},
date: 2024-10-17
}
Model przekazuje te uporządkowane dane wejściowe do aplikacji, aby mogła ona wywołać funkcję fetchWeather
. Gdy aplikacja otrzyma warunki pogodowe z interfejsu API, przekaże te informacje do modelu. Te informacje o pogodzie umożliwiają modelowi przeprowadzenie końcowego przetwarzania i wygenerowanie odpowiedzi na początkowe żądanie What was the weather in Boston on October 17, 2024?
Model może podać ostateczną odpowiedź w języku naturalnym, np.:
On October 17, 2024, in Boston, it was 38 degrees Fahrenheit with partly cloudy skies.
Implementacja wywoływania funkcji
W tym przewodniku znajdziesz instrukcje implementacji konfiguracji wywołania funkcji podobnej do omówionej w sekcji Przykładowy proces wywoływania funkcji (patrz górna część tej strony).
Zanim zaczniesz
Kliknij dostawcę Gemini API, aby wyświetlić na tej stronie treści i kod związane z tym dostawcą. |
Jeśli jeszcze tego nie zrobisz, przeczytaj przewodnik dla początkujących, w którym znajdziesz instrukcje konfigurowania projektu Firebase, łączenia aplikacji z Firebase, dodawania pakietu SDK, inicjowania usługi backendowej wybranego dostawcy Gemini API oraz tworzenia instancji GenerativeModel
.
Aby przetestować prompty i przeprowadzić ich iterację, a także uzyskać wygenerowany fragment kodu, zalecamy użycie Google AI Studio.
Krok 1. Napisz funkcję
Wyobraź sobie, że masz aplikację, w której użytkownik może wpisać prośbę o dostęp do danych:What was the weather in Boston on October 17, 2024?
. Modele Gemini mogą nie znać tych informacji o pogodzie. Załóżmy jednak, że znasz interfejs API zewnętrznej usługi pogodowej, która może je udostępnić. Scenariusz w tym przewodniku opiera się na tym hipotetycznym zewnętrznym interfejsie API.
W aplikacji napisz funkcję, która będzie współpracować z hipotetycznym zewnętrznym interfejsem API i przekazywać modelowi informacje potrzebne do wygenerowania ostatecznego żądania. W tym przykładzie pogody będzie to funkcja fetchWeather
, która wykonuje wywołanie do tego hipotetycznego zewnętrznego interfejsu API.
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"},
};
}
Krok 2. Utwórz deklarację funkcji
Utwórz deklarację funkcji, którą później przekażesz modelowi (następny krok w tym przewodniku).
W deklaracji podaj jak najwięcej szczegółów w opisach funkcji i jej parametrów.
Model korzysta z informacji w deklaracji funkcji, aby określić, którą funkcję wybrać i jak podać wartości parametrów dla rzeczywistego wywołania funkcji. Aby dowiedzieć się, jak model może wybierać spośród funkcji i jak możesz kontrolować ten wybór, przeczytaj sekcję „Dodatkowe zachowania i opcje” na tej stronie.
Pamiętaj o tych kwestiach dotyczących przesłanego schematu:
Deklaracje funkcji muszą być podane w formacie schematu zgodnym z schematem OpenAPI. Vertex AI obsługuje schemat OpenAPI w ograniczonym zakresie.
Obsługiwane są te atrybuty:
type
,nullable
,required
,format
,description
,properties
,items
,enum
.Te atrybuty nie są obsługiwane:
default
,optional
,maximum
,oneOf
.
Domyślnie w SDK Firebase AI Logic wszystkie pola są uważane za wymagane, chyba że w tablicy
optionalProperties
zostaną określone jako opcjonalne. W przypadku tych pól opcjonalnych model może wypełnić pola lub je pominąć. Pamiętaj, że jest to działanie przeciwne do domyślnego działania tych dwóchGemini API dostawców, jeśli używasz ich pakietów SDK serwera lub interfejsów API bezpośrednio.
Sprawdzone metody dotyczące deklaracji funkcji, w tym wskazówki dotyczące nazw i opisów, znajdziesz w dokumentacji Sprawdzone metody w dokumentacji Gemini Developer API.
Oto jak napisać deklarację funkcji:
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."
)}
}
));
Krok 3. Podaj deklarację funkcji podczas inicjalizacji modelu
Maksymalna liczba deklaracji funkcji, które możesz podać w prośbie, to 128. Więcej informacji o tym, jak model może wybierać funkcje, a także o tym, jak możesz kontrolować ten wybór (za pomocą toolConfig
do ustawienia trybu wywoływania funkcji), znajdziesz w sekcji Dodatkowe zachowania i opcje na tej stronie.
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 }
);
Dowiedz się, jak wybrać model odpowiedni do Twojego przypadku użycia i aplikacji.
Krok 4. Wywołaj funkcję, aby wywołać zewnętrzny interfejs API.
Jeśli model uzna, że funkcja fetchWeather
może mu pomóc w wygenerowaniu ostatecznej odpowiedzi, aplikacja musi wywołać tę funkcję, korzystając ze strukturyzowanych danych wejściowych dostarczonych przez model.
Informacje muszą być przekazywane między modelem a aplikacją, dlatego zalecamy używanie wywoływania funkcji za pomocą interfejsu czatu wieloetapowego.
Ten fragment kodu pokazuje, jak aplikacja jest informowana, że model chce użyć funkcji fetchWeather
. Pokazuje też, że model podał niezbędne wartości parametrów wejściowych do wywołania funkcji (i powiązanego z nim zewnętrznego interfejsu API).
W tym przykładzie żądanie przychodzące zawierało prompt What was the weather in Boston on October 17, 2024?
. Na podstawie tego prompta model wywnioskował parametry wejściowe wymagane przez funkcję fetchWeather
(czyli city
, state
i 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.
}
Krok 5. Przekaż wyjście funkcji do modelu, aby wygenerować ostateczną odpowiedź
Gdy funkcja fetchWeather
zwróci informacje o pogodzie, aplikacja musi przekazać je do modelu.
Następnie model wykonuje ostatnie przetwarzanie i generuje ostateczną odpowiedź w języku naturalnym, np.:
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.");
Dodatkowe zachowania i opcje
Oto kilka dodatkowych zachowań wywoływania funkcji, które musisz uwzględnić w kodzie, oraz opcje, którymi możesz zarządzać.
Model może poprosić o ponowne wywołanie funkcji lub innej funkcji.
Jeśli odpowiedzi z jednego wywołania funkcji nie wystarczają do wygenerowania ostatecznej odpowiedzi, model może poprosić o dodatkowe wywołanie funkcji lub wywołanie zupełnie innej funkcji. Może się to zdarzyć tylko wtedy, gdy w deklaracji funkcji w liście funkcji podasz więcej niż jedną funkcję.
Aplikacja musi uwzględniać możliwość, że model może poprosić o dodatkowe funkcje.
Model może wywołać kilka funkcji jednocześnie.
Na liście deklaracji funkcji, którą przekazujesz modelowi, możesz podać maksymalnie 128 funkcji. W związku z tym model może uznać, że do wygenerowania ostatecznej odpowiedzi potrzebne są różne funkcje. Może też zdecydować się wywołać niektóre z tych funkcji jednocześnie – nazywa się to równoległym wywoływaniem funkcji.
Aplikacja musi uwzględniać fakt, że model może jednocześnie wykonywać wiele funkcji, a także przekazywać modelowi wszystkie odpowiedzi z tych funkcji.
Możesz kontrolować, czy i w jaki sposób model może prosić o wywołanie funkcji.
Możesz określić, czy i w jaki sposób model ma używać podanych deklaracji funkcji. Jest to tzw. ustawienie trybu wywoływania funkcji. Oto przykłady:
Zamiast zezwalać modelowi na wybór między natychmiastową odpowiedzią w naturalnym języku a wywołaniem funkcji, możesz zmusić go do zawsze używania wywołań funkcji. Jest to tzw. wymuszone wywołanie funkcji.
Jeśli podasz kilka deklaracji funkcji, możesz ograniczyć model do korzystania tylko z podzbioru podanych funkcji.
Te ograniczenia (czyli tryby) wdrażasz, dodając konfigurację narzędzia (toolConfig
) wraz z promptem i deklaracjami funkcji. W konfiguracji narzędzia możesz wybrać jeden z tych trybów. Najbardziej przydatny tryb to ANY
.
Tryb | Opis |
---|---|
AUTO |
Domyślne zachowanie modelu. Model decyduje, czy użyć wywołania funkcji czy odpowiedzi w języku naturalnym. |
ANY |
Model musi używać wywołań funkcji („wymuszone wywoływanie funkcji”). Aby ograniczyć model do podzbioru funkcji, w polu allowedFunctionNames podaj dozwolone nazwy funkcji.
|
NONE |
Model nie może używać wywołań funkcji. Takie działanie jest równoważne żądaniu modelu bez żadnych powiązanych deklaracji funkcji. |
Co jeszcze możesz zrobić?
Wypróbuj inne funkcje
- tworzyć rozmowy wieloetapowe (czat);
- generować tekst na podstawie promptów tekstowych,
- generować tekst, wyświetlając prompty z różnymi typami plików, takimi jak obrazy, pliki PDF, filmy i dźwięk;
Dowiedz się, jak kontrolować generowanie treści
- Zrozumieć projektowanie promptów, w tym sprawdzone metody, strategie i przykładowe prompty.
- Skonfiguruj parametry modelu, takie jak temperatura i maksymalna liczba tokenów wyjściowych (w przypadku Gemini) lub format obrazu i generowanie osób (w przypadku Imagen).
- Używaj ustawień bezpieczeństwa, aby dostosować prawdopodobieństwo otrzymywania odpowiedzi, które mogą być uważane za szkodliwe.
Więcej informacji o obsługiwanych modelach
Dowiedz się więcej o modelach dostępnych w różnych przypadkach użycia oraz o ich limitach i cenach.Prześlij opinię o swoich wrażeniach związanych z usługą Firebase AI Logic