函式呼叫可讓您輕鬆從生成式模型取得結構化資料輸出內容。接著,您可以使用這些輸出內容呼叫其他 API,並將相關的回應資料傳回模型。換句話說,函式呼叫可協助您將生成式模型連結至外部系統,讓產生的內容包含最新且準確的資訊。
您可以為 Gemini 模型提供函式說明。這些函式會以應用程式的語言編寫 (也就是非 Google Cloud Functions)。模型可能會要求您呼叫函式並傳回結果,協助模型處理查詢。
請參閱「函式呼叫簡介」一文瞭解詳情。
燈光控制 API 範例
假設您有一個基本的照明控制系統,搭配應用程式設計介面 (API),並想讓使用者透過簡單的文字要求控制燈光。您可以使用函式呼叫功能解讀使用者的光源變更要求,並轉譯為 API 呼叫來設定亮度值。這個假設的光源控制系統可讓您控制光源的亮度和色溫,定義為兩個獨立的參數:
參數 | 類型 | 需要 | 說明 |
---|---|---|---|
brightness |
號碼 | 是 | 亮度介於 0 到 100 之間。零關閉,100 為全彩。 |
colorTemperature |
字串 | 是 | 燈具的色溫,可能是 daylight 、cool 或 warm 。 |
為求簡單起見,這個虛構光源系統只有一盞燈,因此使用者不必指定房間或位置。以下是您可以傳送至光源控制 API 的 JSON 要求範例,使用日光色溫將亮度變更為 50%:
{
"brightness": "50",
"colorTemperature": "daylight"
}
本教學課程說明如何設定 Gemini API 的函式呼叫,以解讀使用者的照明要求,並將這些要求對應至 API 設定,藉此控制燈具亮度和色溫值。
事前準備:設定專案和 API 金鑰
呼叫 Gemini API 之前,您必須設定專案並設定 API 金鑰。
定義 API 函式
建立可提出 API 要求的函式。這個函式應在應用程式的程式碼中定義,但可以在應用程式外部呼叫服務或 API。Gemini API 不會直接呼叫這個函式,因此您可以控管透過應用程式程式碼執行這個函式的方式和時機。為了進行示範,本教學課程定義只會傳回所要求的亮度值的模擬 API 函式:
Future<Map<String, Object?>> setLightValues(
Map<String, Object?> arguments,
) async =>
// This mock API returns the requested lighting values
{
'brightness': arguments['brightness'],
'colorTemperature': arguments['colorTemp'],
};
建立函式宣告
建立您要傳遞至生成式模型的函式宣告。當您宣告用於模型的函式時,應在函式和參數說明中盡可能加入詳細資料。生成式模型會使用這項資訊來決定要選取哪個函式,以及如何為函式呼叫中的參數提供值。以下程式碼說明如何宣告光源控制功能:
final lightControlTool = FunctionDeclaration(
'setLightValues',
'Set the brightness and color temperature of a room light.',
Schema(SchemaType.object, properties: {
'brightness': Schema(SchemaType.number,
description: 'Light level from 0 to 100. '
'Zero is off and 100 is full brightness.'),
'colorTemperature': Schema(SchemaType.string,
description: 'Color temperature of the light fixture, '
'which can be `daylight`, `cool` or `warm`.'),
}, requiredProperties: [
'brightness',
'colorTemperature'
]));
在模型初始化期間宣告函式
如要透過模型使用函式呼叫,您必須在初始化模型物件時提供函式宣告。您可以設定模型的 tools
參數來宣告函式。Dart SDK 也支援將函式宣告為對 generateContent
或 generateContentStream
API 的引數。
final model = GenerativeModel(
model: 'gemini-1.5-flash',
apiKey: apiKey,
// Specify the function declaration.
tools: [
Tool(functionDeclarations: [lightControlTool])
],
);
生成函式呼叫
使用函式宣告初始化模型後,您可以使用已定義的函式提示模型。您應利用即時通訊提示 (sendMessage()
) 使用函式呼叫功能,因為函式呼叫通常利用先前的提示和回應內容進行呼叫。
final chat = model.startChat(); final prompt =
'Dim the lights so the room feels cozy and warm.';
// Send the message to the generative model.
var response = await chat.sendMessage(Content.text(prompt));
final functionCalls = response.functionCalls.toList();
// When the model response with a function call, invoke the function.
if (functionCalls.isNotEmpty) {
final functionCall = functionCalls.first;
final result = switch (functionCall.name) {
// Forward arguments to the hypothetical API.
'setLightValues' => await setLightValues(functionCall.args),
// Throw an exception if the model attempted to call a function that was
// not declared.
_ => throw UnimplementedError(
'Function not implemented: ${functionCall.name}')
};
// Send the response to the model so that it can use the result to generate
// text for the user.
response = await chat
.sendMessage(Content.functionResponse(functionCall.name, result));
}
// When the model responds with non-null text content, print it.
if (response.text case final text?) {
print(text);
}