函式呼叫教學課程

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

您可以為 Gemini 模型提供函式說明。這些函式是使用應用程式語言編寫的函式 (也就是說,它們不是 Google Cloud Functions)。模型可能會要求您呼叫函式,然後傳回 以便模型處理查詢

如果您還不瞭解 函式呼叫簡介: 詳情

照明控制 API 範例

假設您有一個基本的照明控制系統 搭配應用程式設計 介面 (API),並希望使用者能透過簡單的 文字要求您可以使用函式呼叫功能,解讀使用者提出的燈光變更要求,並將這些要求轉譯為 API 呼叫,以便設定燈光值。這個假設的照明控制系統可讓您控制燈光的亮度和色溫,這兩個參數分別定義如下:

參數 類型 必要 說明
brightness 數字 光線強度從 0 到 100。零關閉,100 為全彩。
colorTemperature 字串 燈具的色溫,可能是 daylightcoolwarm

為簡化說明,這個假想的照明系統只有一盞燈,因此使用者不必指定房間或位置。以下是您可以傳送至照明控制 API 的 JSON 要求範例,藉此使用日光色溫將燈光亮度變更為 50%:

{
  "brightness": "50",
  "colorTemperature": "daylight"
}

本教學課程將說明如何設定函式呼叫,供 Gemini API 執行下列操作: 解讀使用者的光源要求並對應至 API 設定, 亮度和色溫值。

事前準備:設定專案和 API 金鑰

呼叫 Gemini API 前,請先設定專案並設定 您的 API 金鑰。

定義 API 函式

建立可提出 API 要求的函式。應定義這個函式 程式碼,但可以在 應用程式Gemini API 不會直接呼叫這個函式,因此您可以透過應用程式程式碼控制這個函式的執行方式和時機。為方便示範,本教學課程定義了一個模擬 API 函式 只會傳回要求的亮度值:

func setLightValues(brightness int, colorTemp string) map[string]any {
    // This mock API returns the requested lighting values
    return map[string]any{
        "brightness":       brightness,
        "colorTemperature": colorTemp}
}

建立函式宣告

建立要傳遞至生成式模型的函式宣告。宣告模型可使用的函式時,請盡可能在函式和參數說明中加入詳細資料。生成式模型 會依據這些資訊決定要選取哪個函式,以及如何提供 值。以下程式碼顯示如何宣告照明控制函式:

lightControlTool := &genai.Tool{
    FunctionDeclarations: []*genai.FunctionDeclaration{{
        Name:        "controlLight",
        Description: "Set the brightness and color temperature of a room light.",
        Parameters: &genai.Schema{
            Type: genai.TypeObject,
            Properties: map[string]*genai.Schema{
                "brightness": {
                    Type:        genai.TypeString,
                    Description: "Light level from 0 to 100. Zero is off and"+
                        " 100 is full brightness.",
                },
                "colorTemperature": {
                    Type:        genai.TypeString,
                    Description: "Color temperature of the light fixture which" +
                        " can be `daylight`, `cool` or `warm`.",
                },
            },
            Required: []string{"brightness", "colorTemperature"},
        },
    }},
}

在模型初始化期間宣告函式

如要透過模型使用函式呼叫,您必須提供 函式宣告。您可以設定模型的 Tools 參數來宣告函式:

// ...

lightControlTool := &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{lightControlTool}

產生函式呼叫

使用函式宣告初始化模型後,您可以 加入已定義函式的模型您應使用聊天提示 (SendMessage()) 進行函式呼叫,因為函式呼叫通常會受益於先前提示和回應的內容。

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

prompt := "Dim the lights so the room feels cozy and warm."

// 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, lightControlTool.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{
    "brightness":  "30",
    "colorTemperature":  "warm" }

// 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:     lightControlTool.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)
}