函式呼叫教學課程

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

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

請參閱「函式呼叫簡介」一文瞭解詳情。

燈光控制 API 範例

假設您有一個基本的照明控制系統,搭配應用程式設計介面 (API),並想讓使用者透過簡單的文字要求控制燈光。您可以使用函式呼叫功能解讀使用者的光源變更要求,並轉譯為 API 呼叫來設定亮度值。這個假設的光源控制系統可讓您控制光源的亮度和色溫,定義為兩個獨立的參數:

參數 類型 需要 說明
brightness 號碼 亮度介於 0 到 100 之間。零關閉,100 為全彩。
colorTemperature 字串 燈具的色溫,可能是 daylightcoolwarm

為求簡單起見,這個虛構光源系統只有一盞燈,因此使用者不必指定房間或位置。以下是您可以傳送至光源控制 API 的 JSON 要求範例,使用日光色溫將亮度變更為 50%:

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

本教學課程說明如何設定 Gemini API 的函式呼叫,以解讀使用者的照明要求,並將這些要求對應至 API 設定,藉此控制燈具亮度和色溫值。

事前準備:設定專案和 API 金鑰

呼叫 Gemini API 之前,您必須設定專案並設定 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)
}