教學課程:使用 Gemini API 呼叫函式


函式呼叫可讓您更輕鬆地從生成式模型中取得結構化資料輸出。接著,您可以使用這些輸出內容呼叫其他 API,並將相關回應資料傳回模型。換句話說,函式呼叫可協助您將生成式模型連結至外部系統,讓生成的內容獲得最新且準確的資訊。

您可以提供內含函式說明的 Gemini 模型。這些函式是以應用程式語言編寫的函式 (也就是非 Google Cloud Functions)。模型可能會要求您呼叫函式並傳回結果,協助模型處理您的查詢。

如果您尚未閱讀此課程,請參閱函式呼叫簡介以瞭解詳情。

設定專案

呼叫 Gemini API 之前,您需要先設定專案,包括設定 API 金鑰、安裝 SDK 套件及初始化模型。

設定函式呼叫

在本教學課程,您將讓模型與支援下列參數的假設貨幣交易平台 API 互動:

參數 類型 必要 說明
currencyDate 字串 用於擷取
匯率的日期 (一律為 YYYY-MM-DD 格式,如未指定時間範圍,則為 latest 值)
currencyFrom 字串 要用來轉換的貨幣
currencyTo 字串 要轉換成的貨幣

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 Gemini 1.0 Pro.
// See "Supported models" in the "Introduction to function calling" page.
model := client.GenerativeModel("gemini-1.0-pro")

// 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)
}