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

<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 関数では、 リクエストされた照明の値を返すだけです。

suspend fun setLightValues(
    brightness: Int,
    colorTemp: String
): JSONObject {
    // This mock API returns the requested lighting values
    return JSONObject().apply {
        put("brightness", brightness)
        put("colorTemperature", colorTemp)
    }
}

関数宣言を作成する

生成モデルに渡す関数宣言を作成します。日時 モデルで使用する関数を宣言する場合は、その関数を 可能な限り多くしてください。生成モデル この情報を基に、どの機能を選択するのか、またどのような機能を パラメータの値です。次のコードは、 照明コントロール関数を宣言します。

val lightControlTool = defineFunction(
  name = "setLightValues",
  description = "Set the brightness and color temperature of a room light.",
  Schema.int("brightness", "Light level from 0 to 100. Zero is off and 100" +
    " is full brightness."),
  Schema.str("colorTemperature", "Color temperature of the light fixture" +
    " which can be `daylight`, `cool` or `warm`.")
) { brightness, colorTemp ->
    // Call the function you declared above
    setLightValues(brightness.toInt(), colorTemp)
}

モデルの初期化時に関数を宣言する

モデルで関数呼び出しを使用する場合は、 モデル オブジェクトを初期化するときに明示的に指定します。関数を宣言する モデルの tools パラメータを設定します。

val generativeModel = GenerativeModel(
    modelName = "gemini-1.5-flash",

    // Access your API key as a Build Configuration variable
    apiKey = BuildConfig.apiKey,

    // Specify the function declaration.
    tools = listOf(Tool(listOf(lightControlTool)))
)

関数呼び出しを生成する

関数宣言でモデルを初期化したら、プロンプトを使用して、 モデルを定義します。関数呼び出しを使用するには、 チャット プロンプト(sendMessage())。関数呼び出しのメリットは一般的に プロンプトやレスポンスのコンテキストがあります。

val chat = generativeModel.startChat()

val prompt = "Dim the lights so the room feels cozy and warm."

// Send the message to the generative model
var response = chat.sendMessage(prompt)

// Check if the model responded with a function call
response.functionCall?.let { functionCall ->
  // Try to retrieve the stored lambda from the model's tools and
  // throw an exception if the returned function was not declared
  val matchedFunction = generativeModel.tools?.flatMap { it.functionDeclarations }
      ?.first { it.name == functionCall.name }
      ?: throw InvalidStateException("Function not found: ${functionCall.name}")

  // Call the lambda retrieved above
  val apiResponse: JSONObject = matchedFunction.execute(functionCall)

  // Send the API response back to the generative model
  // so that it generates a text response that can be displayed to the user
  response = chat.sendMessage(
    content(role = "function") {
        part(FunctionResponsePart(functionCall.name, apiResponse))
    }
  )
}

// Whenever the model responds with text, show it in the UI
response.text?.let { modelResponse ->
    println(modelResponse)
}