関数呼び出しのチュートリアル

<ph type="x-smartling-placeholder"></ph>

関数呼び出しを使用すると、構造化データの出力を 説明します。その後、これらの出力を使用して他の API を呼び出し、 レスポンス データをモデルに送ります。つまり関数呼び出しは 生成モデルを外部システムに接続して、生成されたコンテンツが に最新の正確な情報が含まれています。

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

まだご覧になっていない場合は、 関数呼び出しの概要で学習する できます。

照明制御用の API の例

基本的な照明制御システムとアプリケーション プログラミング インターフェース(API)を使用していて、ユーザーがシンプルな テキスト リクエスト。関数呼び出し機能を使用してライティングを解釈できる API 呼び出しに変換して照明を設定する API 呼び出しに変換し、 使用できます。この架空の照明制御システムを使用して、 明るさと色温度です parameters:

パラメータ タイプ 必須 / 省略可 説明
brightness 数値 あり 光レベル(0 ~ 100)。ゼロがオフで、100 が最大の明るさです。
colorTemperature 文字列 あり 照明器具の色温度(daylightcoolwarm)。

わかりやすくするため、この架空の照明システムにはライトが 1 つしかないため、ユーザーは 客室や場所を指定する必要はありません。これが JSON リクエストの例です。 照明制御 API に送信して照明レベルを 50% に 昼光色温度を使うと次の式になります

{
  "brightness": "50",
  "colorTemperature": "daylight"
}

このチュートリアルでは、Gemini API の関数呼び出しを設定して、 ユーザーの照明リクエストを解釈し、API 設定にマッピングして 明るさと色温度の値に基づいて変化します

始める前に: プロジェクトと API キーを設定する

Gemini 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);
}