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


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

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

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

プロジェクトを設定する

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

関数呼び出しを設定する

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

パラメータ タイプ 必須 説明
currencyFrom string あり 換算元の通貨
currencyTo string あり 換算後の通貨

API リクエストの例

{
  "currencyFrom": "USD",
  "currencyTo": "SEK"
}

API レスポンスの例

{
  "base": "USD",
  "rates": {"SEK": 0.091}
}

ステップ 1: API リクエストを行う関数を作成する

API リクエストを行う関数を作成します(まだ作成していない場合)。

このチュートリアルではデモのために、実際の API リクエストを送信するのではなく、実際の API が返すのと同じ形式でハードコードされた値を返します。

suspend fun makeApiRequest(
    currencyFrom: String,
    currencyTo: String
): JSONObject {
    // This hypothetical API returns a JSON such as:
    // {"base":"USD","rates":{"SEK": 0.091}}
    return JSONObject().apply {
        put("base", currencyFrom)
        put("rates", hashMapOf(currencyTo to 0.091))
    }
}

ステップ 2: 関数宣言を作成する

生成モデルに渡す関数宣言を作成します(このチュートリアルの次のステップ)。

関数とパラメータの説明には、できる限り詳しく説明してください。生成モデルは、この情報を使用して、選択する関数と、関数呼び出しでパラメータの値を指定する方法を決定します。

val getExchangeRate = defineFunction(
  name = "getExchangeRate",
  description = "Get the exchange rate for currencies between countries",
  Schema.str("currencyFrom", "The currency to convert from."),
  Schema.str("currencyTo", "The currency to convert to.")
) { from, to ->
    // Call the function that you declared above
    makeApiRequest(from, to)
}

ステップ 3: モデルの初期化時に関数宣言を指定する

生成モデルを初期化するときに、関数の宣言をモデルの tools パラメータに渡します。

val generativeModel = GenerativeModel(
  // Use a model that supports function calling, like a Gemini 1.5 model
  modelName = "gemini-1.5-flash",
  // Access your API key as a Build Configuration variable (see "Set up your API key" above)
  apiKey = BuildConfig.apiKey,
  // Specify the function declaration.
  tools = listOf(Tool(listOf(getExchangeRate)))
)

ステップ 4: 関数呼び出しを生成する

これで、定義した関数を使用してモデルにプロンプトを入力できるようになりました。

関数呼び出しはチャットのマルチターン構造にうまく適合するため、関数呼び出しの使用にはチャット インターフェースを使用することをおすすめします。

val chat = generativeModel.startChat()

val prompt = "How much is 50 US dollars worth in Swedish krona?"

// 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)
}