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


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

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

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

設定專案

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

設定函式呼叫

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

參數 類型 必要 說明
currencyFrom 字串 要用來轉換的貨幣
currencyTo 字串 要轉換成的貨幣

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 Gemini 1.0 Pro
  // (see "Supported models" in the "Introduction to function calling" page)
  modelName = "gemini-1.0-pro",
  // 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)
}