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


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

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

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

プロジェクトを設定する

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

関数呼び出しを設定する

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

パラメータ タイプ 必須 説明
currencyDate 文字列
の為替レートを取得する日付(常に YYYY-MM-DD 形式、または期間が指定されていない場合は値 latest にする必要があります)
currencyFrom string あり 換算元の通貨
currencyTo string × 換算後の通貨

API リクエストの例

{
  "currencyDate": "2024-04-17",
  "currencyFrom": "USD",
  "currencyTo": "SEK"
}

API レスポンスの例

{
  "base": "USD",
  "date": "2024-04-17",
  "rates": {"SEK": 0.091}
}

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

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

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

func exchangeRate(currencyDate string,
    currencyFrom string, currencyTo string) map[string]any {
    // This hypothetical API returns a JSON such as:
    // {"base":"USD","date":"2024-04-17","rates":{"SEK": 0.091}}
    return map[string]any{
        "base":  currencyFrom,
        "date":  currencyDate,
        "rates": map[string]any{currencyTo: 0.091}}
}

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

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

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

currencyExchangeTool := &genai.Tool{
    FunctionDeclarations: []*genai.FunctionDeclaration{{
        Name:        "exchangeRate",
        Description: "Lookup currency exchange rates by date",
        Parameters: &genai.Schema{
            Type: genai.TypeObject,
            Properties: map[string]*genai.Schema{
                "currencyDate": {
                    Type:        genai.TypeString,
                    Description: "A date that must always be in YYYY-MM-DD format" +
                        " or the value 'latest' if a time period is not specified",
                },
                "currencyFrom": {
                    Type:        genai.TypeString,
                    Description: "Currency to convert from",
                },
                "currencyTo": {
                    Type:        genai.TypeString,
                    Description: "Currency to convert to",
                },
            },
            Required: []string{"currencyDate", "currencyFrom"},
        },
    }},
}

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

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

// ...

currencyExchangeTool := &genai.Tool{
  // ...
}

// Use a model that supports function calling, like a Gemini 1.5 model
model := client.GenerativeModel("gemini-1.5-flash")

// Specify the function declaration.
model.Tools = []*genai.Tool{currencyExchangeTool}

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

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

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

// Start new chat session.
session := model.StartChat()

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

// Send the message to the generative model.
resp, err := session.SendMessage(ctx, genai.Text(prompt))
if err != nil {
    log.Fatalf("Error sending message: %v\n", err)
}

// Check that you got the expected function call back.
part := resp.Candidates[0].Content.Parts[0]
funcall, ok := part.(genai.FunctionCall)
if !ok {
    log.Fatalf("Expected type FunctionCall, got %T", part)
}
if g, e := funcall.Name, currencyExchangeTool.FunctionDeclarations[0].Name; g != e {
    log.Fatalf("Expected FunctionCall.Name %q, got %q", e, g)
}
fmt.Printf("Received function call response:\n%q\n\n", part)

apiResult := map[string]any{
    "base":  "USD",
    "date":  "2024-04-17",
    "rates": map[string]any{"SEK": 0.091}}

// Send the hypothetical API result back to the generative model.
fmt.Printf("Sending API result:\n%q\n\n", apiResult)
resp, err = session.SendMessage(ctx, genai.FunctionResponse{
    Name:     currencyExchangeTool.FunctionDeclarations[0].Name,
    Response: apiResult,
})
if err != nil {
    log.Fatalf("Error sending message: %v\n", err)
}

// Show the model's response, which is expected to be text.
for _, part := range resp.Candidates[0].Content.Parts {
    fmt.Printf("%v\n", part)
}