生成式模型擅長解決許多類型的問題,不過,這類模型仍受限於以下限制:
- 訓練完成後,模型知識就會凍結,導致知識過時。
- 無法查詢或修改外部資料。
函式呼叫可協助您克服部分限制。 函式呼叫有時也稱為「工具使用」,因為模型可透過這項功能使用外部工具 (例如 API 和函式) 生成最終回覆。
本指南說明如何實作函式呼叫設定,類似於本頁下一節主要內容所述情境。如要在應用程式中設定函式呼叫,大致需要完成下列步驟:
步驟 1:編寫函式,向模型提供生成最終回覆所需的資訊 (例如,函式可以呼叫外部 API)。
步驟 2:建立函式宣告,說明函式及其參數。
步驟 3:在模型初始化期間提供函式宣告,讓模型瞭解如何使用函式 (如有需要)。
步驟 4:設定應用程式,讓模型可以傳送必要資訊,供應用程式呼叫函式。
步驟 5:將函式的回應傳回模型,讓模型生成最終回應。
函式呼叫範例總覽
傳送要求給模型時,您也可以提供一組「工具」(例如函式),供模型用來生成最終回覆。如要使用這些函式並呼叫函式 (即「函式呼叫」),模型和應用程式需要彼此傳遞資訊,因此建議透過多輪對話介面使用函式呼叫。
假設您有一個應用程式,使用者可以輸入類似以下的提示:
What was the weather in Boston on October 17, 2024?。
Gemini 模型可能不知道這項天氣資訊,但假設您知道可提供這項資訊的外部天氣服務 API。您可以使用函式呼叫,為 Gemini 模型提供該 API 和天氣資訊的路徑。
首先,您要在應用程式中編寫與這個假設外部 API 互動的函式 fetchWeather,該函式具有下列輸入和輸出內容:
| 參數 | 類型 | 必要 | 說明 |
|---|---|---|---|
| 輸入 | |||
location |
物件 | 是 | 要取得天氣資訊的城市名稱和所在州別。 目前僅支援美國境內的城市。一律須為 city 和 state 的巢狀物件。 |
date |
字串 | 是 | 要擷取天氣資訊的日期 (一律須採用 YYYY-MM-DD 格式)。 |
| 輸出 | |||
temperature |
整數 | 是 | 溫度 (華氏) |
chancePrecipitation |
字串 | 是 | 降水機率 (以百分比表示) |
cloudConditions |
字串 | 是 | 雲端條件 (clear、partlyCloudy、mostlyCloudy、cloudy 其中之一)
|
初始化模型時,您會告知模型有這個 fetchWeather 函式,以及如何使用該函式處理傳入的要求 (如有需要)。這稱為「函式宣告」。模型不會直接呼叫函式。模型在處理傳入的要求時,會判斷 fetchWeather 函式是否能協助回覆要求。如果模型判斷函式確實有用,就會產生結構化資料,協助應用程式呼叫函式。
再次查看傳入的要求:
What was the weather in Boston on October 17, 2024?. 模型可能會判斷 fetchWeather 函式有助於生成回覆。模型會查看 fetchWeather 需要哪些輸入參數,然後為函式產生結構化輸入資料,大致如下:
{
functionName: fetchWeather,
location: {
city: Boston,
state: Massachusetts // the model can infer the state from the prompt
},
date: 2024-10-17
}
模型會將這項結構化輸入資料傳遞至應用程式,讓應用程式可以呼叫 fetchWeather 函式。應用程式從 API 收到天氣狀況後,會將資訊傳遞給模型。模型會根據這項天氣資訊完成最終處理程序,並生成對 What was the weather in Boston on October 17, 2024? 初始要求的相關回覆。
模型可能會提供最終的自然語言回覆,例如:
On October 17, 2024, in Boston, it was 38 degrees Fahrenheit with partly cloudy skies.
實作函式呼叫
本指南的後續步驟會說明如何實作函式呼叫設定,類似於「函式呼叫範例總覽」(請參閱本頁頂端部分) 中所述的工作流程。
支援的模型
gemini-3.1-pro-previewgemini-3.8-flash(以及舊版gemini-3.7-flash、gemini-3.6-flash和gemini-3.5-flash)gemini-3.5-flash-lite(和舊版gemini-3.1-flash-lite)
一般用途 Gemini 2.5 模型支援這項功能,但都已淘汰。
Gemini Live API 模型也支援這項功能,但本指南中的所有程式碼範例都適用於一般用途的 Gemini 模型。
事前準備
|
按一下 Gemini API 供應商,即可在這個頁面查看供應商專屬內容和程式碼。 |
如果尚未完成,請參閱入門指南,瞭解如何設定 Firebase 專案、將應用程式連結至 Firebase、新增 SDK、為所選Gemini API供應商初始化後端服務,以及建立 GenerativeModel 執行個體。
如要測試及反覆調整提示,建議使用 Google AI Studio。
步驟 1:編寫函式
假設您有一個應用程式,使用者可以輸入提示,例如:
What was the weather in Boston on October 17, 2024?. Gemini模型可能不知道這項天氣資訊,但假設您知道可提供這項資訊的外部天氣服務 API,本指南的情境會用到這個假設的外部 API。
在應用程式中編寫函式,與假設的外部 API 互動,並提供模型生成最終要求所需的資訊。在這個天氣範例中,fetchWeather 函式會呼叫這個假設的外部 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"},
};
}
步驟 2:建立函式宣告
建立函式宣告,稍後提供給模型 (本指南的下一個步驟)。
在宣告中,請盡可能詳細說明函式及其參數。
模型會根據函式宣告中的資訊,判斷要選取哪個函式,以及如何為實際的函式呼叫提供參數值。如要瞭解模型如何選擇函式,以及如何控管這項選擇,請參閱本頁稍後的「其他行為和選項」。
請注意您提供的結構定義:
您必須以與 OpenAPI 結構定義相容的結構定義格式提供函式宣告。Agent Platform 僅支援部分 OpenAPI 結構定義。
支援的屬性包括:
type、nullable、required、format、description、properties、items、enum。系統不支援下列屬性:
default、optional、maximum、oneOf。
根據預設,對於 Firebase AI Logic SDK,所有欄位都會視為必填,除非您在
optionalProperties陣列中將欄位指定為選填。對於這些選項欄位,模型可以填入或略過。請注意,如果您使用這兩個Gemini API供應商的伺服器 SDK 或 API,預設行為會與上述相反。
如要瞭解函式宣告的最佳做法,包括名稱和說明的撰寫訣竅,請參閱 Google Cloud 說明文件中的「最佳做法」 最佳做法 請參閱 Gemini Developer API 說明文件。
函式宣告的撰寫方式如下:
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."
)}
}
));
步驟 3:在模型初始化期間提供函式宣告
您最多可以在要求中提供 128 個函式宣告。如要瞭解模型如何選擇函式,以及如何控管這項選擇 (使用 toolConfig 設定函式呼叫模式),請參閱本頁稍後的「其他行為和選項」。
Swift
import FirebaseAILogic
// 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_MODEL_NAME",
// 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 = "<var>GEMINI_MODEL_NAME</var>",
// 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("<var>GEMINI_MODEL_NAME</var>",
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_MODEL_NAME",
// 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_MODEL_NAME',
// 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_MODEL_NAME",
// Provide the function declaration to the model.
tools: new Tool[] { fetchWeatherTool }
);
瞭解如何選擇適合應用程式和用途的模型, 。
步驟 4:呼叫函式來叫用外部 API
如果模型判斷fetchWeather函式確實有助於生成最終回覆,應用程式就必須使用模型提供的結構化輸入資料,實際呼叫該函式。
由於模型和應用程式之間需要來回傳遞資訊,建議透過多輪對話介面使用函式呼叫。
下列程式碼片段顯示應用程式如何得知模型要使用 fetchWeather 函式。這也表示模型已為函式呼叫 (和其基礎外部 API) 提供必要的輸入參數值。
在本範例中,傳入的要求包含提示 What was the weather in Boston on October 17, 2024?。根據這項提示,模型推斷 fetchWeather 函式所需的輸入參數 (即 city、state 和 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.
}
步驟 5:將函式輸出內容提供給模型,生成最終回覆
fetchWeather 函式傳回天氣資訊後,應用程式必須將資訊傳回模型。
接著,模型會執行最終處理作業,並生成最終的自然語言回覆,例如:
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: "user", 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("user") {
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("user",
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.");
其他行為和選項
以下是函式呼叫的其他行為,您需要在程式碼中配合調整,並可控制相關選項。
模型可能會要求再次呼叫函式或呼叫其他函式。
如果模型無法根據一次函式呼叫的回覆生成最終回覆,可能會要求額外呼叫函式,或要求呼叫完全不同的函式。只有在函式宣告清單中提供多個函式給模型時,才會發生後者情況。
您的應用程式必須配合模型要求,可能需要額外呼叫函式。
模型可能會要求同時呼叫多個函式。
您可以在函式宣告清單中,向模型提供最多 128 個函式。因此,模型可能會判斷需要多個函式,才能生成最終回覆。模型可能會決定同時呼叫部分函式,這稱為平行函式呼叫。
應用程式必須能同時執行多個函式,並將所有函式的回應傳回模型。
您可以控管模型是否能要求呼叫函式,以及呼叫方式。
您可以對模型使用提供的函式宣告方式和時機設下一些限制。這稱為設定「函式呼叫模式」。 例如:
您可以強制模型一律使用函式呼叫,而非允許模型在即時自然語言回應和函式呼叫之間選擇。這稱為「強制呼叫函式」。
如果您提供多個函式宣告,可以限制模型只使用提供的部分函式。
如要實作這些限制 (或模式),請新增工具設定 (toolConfig),並提供提示和函式宣告。在工具設定中,您可以指定下列其中一種模式。最實用的模式是 ANY。
| 眾數 | 說明 |
|---|---|
AUTO |
預設模型行為。模型會判斷要使用函式呼叫或自然語言回覆。 |
ANY |
模型必須使用函式呼叫 (「強制函式呼叫」)。如要將模型限制為一組函式,請在 allowedFunctionNames 中指定允許的函式名稱。 |
NONE |
模型不得使用函式呼叫。這項行為等同於沒有任何相關聯函式宣告的模型要求。 |
你還可以做些什麼?
試試其他功能
瞭解如何控管內容生成功能
您也可以使用 Google AI Studio 測試提示和模型設定,甚至取得生成的程式碼片段。
進一步瞭解支援的機型
瞭解各種用途適用的模型,以及這些模型的配額和價格。提供有關 Firebase AI Logic 的使用體驗意見回饋