函式呼叫教學課程

函式呼叫可讓您輕鬆從生成式模型取得結構化資料輸出內容。接著,您可以使用這些輸出內容呼叫其他 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 要求的函式。這個函式應在應用程式的程式碼中定義,但可以在應用程式外部呼叫服務或 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{"currencyDate", "currencyFrom"},
        },
    }},
}

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

如要透過模型使用函式呼叫,您必須在初始化模型物件時提供函式宣告。您可以設定模型的 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)
}