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


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

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

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

プロジェクトを設定する

Gemini API を呼び出す前に、Xcode プロジェクトを設定する必要があります。これには、API キーの設定、Xcode プロジェクトへの SDK パッケージの追加、モデルの初期化が含まれます。

関数呼び出しを設定する

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

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

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)