函式呼叫可讓您更輕鬆地從生成式模型中取得結構化資料輸出。接著,您可以使用這些輸出內容呼叫其他 API,並將相關回應資料傳回模型。換句話說,函式呼叫可協助您將生成式模型連結至外部系統,讓生成的內容獲得最新且準確的資訊。
您可以提供內含函式說明的 Gemini 模型。這些函式是以應用程式語言編寫的函式 (也就是非 Google Cloud Functions)。模型可能會要求您呼叫函式並傳回結果,協助模型處理您的查詢。
如果您尚未閱讀此課程,請參閱函式呼叫簡介以瞭解詳情。
設定專案
呼叫 Gemini API 之前,您需要設定 Xcode 專案,包括設定 API 金鑰、將 SDK 套件新增至 Xcode 專案,以及初始化模型。
設定函式呼叫
在本教學課程,您將讓模型與支援下列參數的假設貨幣交易平台 API 互動:
參數 | 類型 | 需要 | 說明 |
---|---|---|---|
currencyFrom |
字串 | 是 | 要用來轉換的貨幣 |
currencyTo |
字串 | 是 | 要轉換成的貨幣 |
API 要求範例
{
"currencyFrom": "USD",
"currencyTo": "SEK"
}
API 回應範例
{
"base": "USD",
"rates": {"SEK": 0.091}
}
步驟 1:建立發出 API 要求的函式
如果您尚未建立發出 API 要求的函式,請先完成這項操作。
為了進行示範,系統將按照實際 API 傳回的格式傳回硬式編碼值,而非傳送實際的 API 要求。
func makeAPIRequest(currencyFrom: String,
currencyTo: String) -> JSONObject {
// This hypothetical API returns a JSON such as:
// {"base":"USD","rates":{"SEK": 0.091}}
return [
"base": .string(currencyFrom),
"rates": .object([currencyTo: .number(0.091)]),
]
}
步驟 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
參數,在初始化生成式模型時指定函式宣告:
// Use a model that supports function calling, like a Gemini 1.5 model
let generativeModel = GenerativeModel(
name: "gemini-1.5-flash",
apiKey: apiKey,
// Specify the function declaration.
tools: [Tool(functionDeclarations: [getExchangeRate])]
)
步驟 4:產生函式呼叫
現在,您可以使用已定義的函式提示模型。
函式呼叫的建議方式是透過即時通訊介面使用,因為函式呼叫可充分融入即時通訊的多輪結構。
let chat = generativeModel.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)