チュートリアル: Gemini API を使用した関数呼び出し


関数呼び出しを使用すると、生成モデルから構造化データ出力を簡単に取得できます。これらの出力を使用して他の API を呼び出し、関連するレスポンス データをモデルに返すことができます。つまり、関数呼び出しを使用すると、生成モデルを外部システムに接続できるため、生成されるコンテンツに最新かつ正確な情報が含まれるようになります。

Gemini モデルに関数の説明を提供できます。これらは、アプリの言語で記述する関数です(Google Cloud Functions ではありません)。クエリの処理を支援するために、関数を呼び出して結果を返すよう、モデルから求められる場合があります。

まだ理解していない場合は、関数呼び出しの概要で詳細をご覧ください。

プロジェクトを設定する

Gemini API を呼び出す前に、プロジェクトをセットアップする必要があります。これには、API キーの設定、パブリッシャーの依存関係への SDK の追加、モデルの初期化が含まれます。

関数呼び出しを設定する

このチュートリアルでは、次のパラメータをサポートする仮想通貨交換 API をモデルとやり取りします。

パラメータ タイプ 必須 説明
currencyDate 文字列
の為替レートを取得する日付(常に YYYY-MM-DD 形式、または期間が指定されていない場合は値 latest にする必要があります)
currencyFrom string あり 換算元の通貨
currencyTo string × 換算後の通貨

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 a Gemini 1.5 model
  model: 'gemini-1.5-flash',
  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);
}