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


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

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

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

プロジェクトを設定する

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

関数呼び出しを設定する

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

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

API リクエストの例

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

API レスポンスの例

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

ステップ 1: API リクエストを行う関数を作成する

API リクエストを行う関数を作成します(まだ作成していない場合)。

このチュートリアルではデモのために、実際の API リクエストを送信するのではなく、実際の API が返すのと同じ形式でハードコードされた値を返します。

async function makeApiRequest(currencyFrom, currencyTo) {
  // This hypothetical API returns a JSON such as:
  // {"base":"USD","rates":{"SEK": 0.091}}
  return {
    base: currencyFrom,
    rates: { [currencyTo]: 0.091 },
  };
}

ステップ 2: 関数宣言を作成する

生成モデルに渡す関数宣言を作成します(このチュートリアルの次のステップ)。

関数とパラメータの説明には、できる限り詳しく説明してください。生成モデルは、この情報を使用して、選択する関数と、関数呼び出しでパラメータの値を指定する方法を決定します。

// Function declaration, to pass to the model.
const getExchangeRateFunctionDeclaration = {
  name: "getExchangeRate",
  parameters: {
    type: "OBJECT",
    description: "Get the exchange rate for currencies between countries",
    properties: {
      currencyFrom: {
        type: "STRING",
        description: "The currency to convert from.",
      },
      currencyTo: {
        type: "STRING",
        description: "The currency to convert to.",
      },
    },
    required: ["currencyTo", "currencyFrom"],
  },
};

// Executable function code. Put it in a map keyed by the function name
// so that you can call it once you get the name string from the model.
const functions = {
  getExchangeRate: ({ currencyFrom, currencyTo }) => {
    return makeApiRequest( currencyFrom, currencyTo)
  }
};

ステップ 3: モデルの初期化時に関数宣言を指定する

生成モデルを初期化するときにモデルの tools パラメータを設定して、関数宣言を指定します。

const { GoogleGenerativeAI } = require("@google/generative-ai");

// Access your API key as an environment variable (see "Set up your API key" above)
const genAI = new GoogleGenerativeAI(process.env.API_KEY);

// ...

const generativeModel = genAI.getGenerativeModel({
  // Use a model that supports function calling, like a Gemini 1.5 model
  model: "gemini-1.5-flash",

  // Specify the function declaration.
  tools: {
    functionDeclarations: [getExchangeRateFunctionDeclaration],
  },
});

ステップ 4: 関数呼び出しを生成する

これで、定義した関数を使用してモデルにプロンプトを入力できるようになりました。

関数呼び出しはチャットのマルチターン構造にうまく適合するため、関数呼び出しの使用にはチャット インターフェースを使用することをおすすめします。

const chat = generativeModel.startChat();
const prompt = "How much is 50 US dollars worth in Swedish krona?";

// Send the message to the model.
const result = await chat.sendMessage(prompt);

// For simplicity, this uses the first function call found.
const call = result.response.functionCalls()[0];

if (call) {
  // Call the executable function named in the function call
  // with the arguments specified in the function call and
  // let it call the hypothetical API.
  const apiResponse = await functions[call.name](call.args);

  // Send the API response back to the model so it can generate
  // a text response that can be displayed to the user.
  const result2 = await chat.sendMessage([{functionResponse: {
    name: 'getExchangeRate',
    response: apiResponse
  }}]);

  // Log the text response.
  console.log(result2.response.text());
}