教學課程:使用 Gemini API 呼叫函式


函式呼叫可讓您更輕鬆地從生成式模型中取得結構化資料輸出。接著,您可以使用這些輸出內容呼叫其他 API,並將相關回應資料傳回模型。換句話說,函式呼叫可協助您將生成式模型連結至外部系統,讓生成的內容獲得最新且準確的資訊。

您可以提供內含函式說明的 Gemini 模型。這些函式是以應用程式語言編寫的函式 (也就是非 Google Cloud Functions)。模型可能會要求您呼叫函式並傳回結果,協助模型處理您的查詢。

如果您尚未閱讀此課程,請參閱函式呼叫簡介以瞭解詳情。

設定專案

呼叫 Gemini API 之前,您需要先設定專案,包括設定 API 金鑰、將 SDK 新增至發布商依附元件,以及初始化模型。

設定函式呼叫

在本教學課程,您將讓模型與支援下列參數的假設貨幣交易平台 API 互動:

參數 類型 必要 說明
currencyDate 字串 用於擷取
匯率的日期 (一律為 YYYY-MM-DD 格式,如未指定時間範圍,則為 latest 值)
currencyFrom 字串 要用來轉換的貨幣
currencyTo 字串 要轉換成的貨幣

API 要求範例

{
  "currencyDate": "2024-04-17",
  "currencyFrom": "USD",
  "currencyTo": "SEK"
}

API 回應範例

{
  "base": "USD",
  "date": "2024-04-17",
  "rates": {"SEK": 0.091}
}

步驟 1:建立發出 API 要求的函式

如果您尚未建立發出 API 要求的函式,請先完成這項操作。

為了進行示範,系統將按照實際 API 傳回的格式傳回硬式編碼值,而非傳送實際的 API 要求。

Future<Map<String, Object?>> findExchangeRate(
  Map<String, Object?> arguments,
) async =>
    // This hypothetical API returns a JSON such as:
    // {"base":"USD","date":"2024-04-17","rates":{"SEK": 0.091}}
    {
      'date': arguments['currencyDate'],
      'base': arguments['currencyFrom'],
      'rates': <String, Object?>{arguments['currencyTo'] as String: 0.091}
    };

步驟 2:建立函式宣告

建立要傳遞至生成式模型的函式宣告 (本教學課程的下一步)。

在函式和參數說明中,盡可能加入更多詳細資料。 生成式模型會使用這項資訊來決定要選取哪個函式,以及如何在函式呼叫中提供參數值。

final exchangeRateTool = FunctionDeclaration(
    'findExchangeRate',
    'Returns the exchange rate between currencies on given date.',
    Schema(SchemaType.object, properties: {
      'currencyDate': Schema(SchemaType.string,
          description: 'A date in YYYY-MM-DD format or '
              'the exact value "latest" if a time period is not specified.'),
      'currencyFrom': Schema(SchemaType.string,
          description: 'The currency code of the currency to convert from, '
              'such as "USD".'),
      'currencyTo': Schema(SchemaType.string,
          description: 'The currency code of the currency to convert to, '
              'such as "USD".')
    }, requiredProperties: [
      'currencyDate',
      'currencyFrom'
    ]));

步驟 3:在模型初始化期間指定函式宣告

在初始化生成式模型時指定函式宣告,方法是將函式傳入模型的 tools 參數:

final model = GenerativeModel(
  // Use a model that supports function calling, like Gemini 1.0 Pro
  // See "Supported models" in the "Introduction to function calling" page.
  model: 'gemini-1.0-pro',
  apiKey: apiKey,

  // Specify the function declaration.
  tools: [
    Tool(functionDeclarations: [exchangeRateTool])
  ],
);

步驟 4:產生函式呼叫

現在,您可以使用已定義的函式提示模型。

函式呼叫的建議方式是透過即時通訊介面使用,因為函式呼叫可充分融入即時通訊的多輪結構。

final chat = model.startChat();
final prompt = 'How much is 50 US dollars worth in Swedish krona?';

// 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.
    'findExchangeRate' => await findExchangeRate(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);
}