使用 Gemini API 呼叫函式


函式呼叫可讓您輕鬆取得結構化資料輸出內容 生成式模型您可以運用這些輸出內容呼叫其他 API,並傳回 傳送給模型的相關回應資料換句話說,函式呼叫有助於 必須連結生成式模型與外部系統 內含最新且準確的資訊。

您可以為 Gemini 模型提供函式說明。這些 您以應用程式語言編寫的函式 (換句話說,非 Cloud Functions)。模型可能會要求您呼叫函式,然後傳回 以便模型處理查詢

你可以 進一步瞭解函式呼叫

事前準備

如果您尚未完成 Vertex AI for Firebase SDK 入門指南。 請確認您已完成下列所有步驟:

  • 設定新的或現有的 Firebase 專案,包括使用 Blaze 定價方案並啟用必要的 API。

  • 將應用程式連結至 Firebase,包括註冊應用程式及新增 為應用程式啟用 Firebase 設定。

  • 新增 SDK,並初始化 Vertex AI 服務和生成式模型 。

將應用程式連結至 Firebase 後,加入 SDK 並初始化 以及生成式模型 你準備好呼叫 Gemini API 了

設定函式呼叫

在這個教學課程中,您會讓模型採用假設的貨幣 Exchange API,支援下列參數:

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

API 要求範例

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

API 回應範例

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

步驟 1:建立提出 API 要求的函式

如果您尚未建立函式,請先建立能 API 要求。

為進行本教學課程的示範,而非傳送實際的 API 您就能傳回硬式編碼值,格式應與 API 會傳回該欄位

func makeAPIRequest(currencyFrom: String,
                    currencyTo: String) -> JSONObject {
  // This hypothetical API returns a JSON such as:
  // {"base":"USD","rates":{"SEK": 10.99}}
  return [
    "base": .string(currencyFrom),
    "rates": .object([currencyTo: .number(10.99)]),
  ]
}

步驟 2:建立函式宣告

建立要傳遞至生成式模型的函式宣告 (本教學課程的下一個步驟)。

在函式和參數說明中盡量加入詳細資料。 生成式模型會根據這項資訊來決定要選取哪個函式 以及如何在函式呼叫中提供參數值。

let getExchangeRate = FunctionDeclaration(
  name: "getExchangeRate",
  description: "Get the exchange rate for currencies between countries",
  parameters: [
    "currencyFrom": Schema(
      type: .string,
      description: "The currency to convert from."
    ),
    "currencyTo": Schema(
      type: .string,
      description: "The currency to convert to."
    ),
  ],
  requiredParameters: ["currencyFrom", "currencyTo"]
)

步驟 3:指定模型初始化期間的函式宣告

指定將生成式模型初始化時的函式宣告,方法為 設定模型的 tools 參數:

import FirebaseVertexAI

// Initialize the Vertex AI service
let vertex = VertexAI.vertexAI()

// Initialize the generative model
// Use a model that supports function calling, like a Gemini 1.5 model
let model = vertex.generativeModel(
  modelName: "gemini-1.5-flash",
  // Specify the function declaration.
  tools: [Tool(functionDeclarations: [getExchangeRate])]
)

瞭解如何選擇 Gemini 模型 以及可選擇的位置 選擇適合您的用途和應用程式

步驟 4:產生函式呼叫

現在,您可以使用已定義的函式提示模型。

建議您使用即時通訊介面來使用函式呼叫,因為 函式呼叫很適合即時通訊的多輪轉式結構。

let chat = model.startChat()

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

// Send the message to the generative model
let response1 = try await chat.sendMessage(prompt)

// Check if the model responded with a function call
guard let functionCall = response1.functionCalls.first else {
  fatalError("Model did not respond with a function call.")
}
// Print an error if the returned function was not declared
guard functionCall.name == "getExchangeRate" else {
  fatalError("Unexpected function called: \(functionCall.name)")
}
// Verify that the names and types of the parameters match the declaration
guard case let .string(currencyFrom) = functionCall.args["currencyFrom"] else {
  fatalError("Missing argument: currencyFrom")
}
guard case let .string(currencyTo) = functionCall.args["currencyTo"] else {
  fatalError("Missing argument: currencyTo")
}

// Call the hypothetical API
let apiResponse = makeAPIRequest(currencyFrom: currencyFrom, currencyTo: currencyTo)

// Send the API response back to the model so it can generate a text response that can be
// displayed to the user.
let response = try await chat.sendMessage([ModelContent(
  role: "function",
  parts: [.functionResponse(FunctionResponse(
    name: functionCall.name,
    response: apiResponse
  ))]
)])

// Log the text response.
guard let modelResponse = response.text else {
  fatalError("Model did not respond with text.")
}
print(modelResponse)

您還能做些什麼?

試用 Gemini API 的其他功能

瞭解如何控管內容生成功能

您也可以使用 Vertex AI Studio

進一步瞭解 Gemini 模型

進一步瞭解 適用於各種用途配額與定價


提供意見 您對 Vertex AI for Firebase 的使用體驗