函式呼叫 SDK 平台教學課程

函式呼叫可讓您輕鬆從生成式模型取得結構化資料輸出內容。接著,您可以使用這些輸出內容呼叫其他 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 函式:

async function setLightValues(brightness, colorTemp) {
  // This mock API returns the requested lighting values
  return {
    brightness: brightness,
    colorTemperature: colorTemp
  };
}

建立函式宣告

建立您要傳遞至生成式模型的函式宣告。當您宣告用於模型的函式時,應在函式和參數說明中盡可能加入詳細資料。生成式模型會使用這項資訊來決定要選取哪個函式,以及如何為函式呼叫中的參數提供值。以下程式碼說明如何宣告光源控制功能:

// Function declaration, to pass to the model.
const controlLightFunctionDeclaration = {
  name: "controlLight",
  parameters: {
    type: "OBJECT",
    description: "Set the brightness and color temperature of a room light.",
    properties: {
      brightness: {
        type: "NUMBER",
        description: "Light level from 0 to 100. Zero is off and 100 is full brightness.",
      },
      colorTemperature: {
        type: "STRING",
        description: "Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.",
      },
    },
    required: ["brightness", "colorTemperature"],
  },
};

// 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 = {
  controlLight: ({ brightness, colorTemp }) => {
    return setLightValues( brightness, colorTemp)
  }
};

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

如要透過模型使用函式呼叫,您必須在初始化模型物件時提供函式宣告。您可以設定模型的 tools 參數來宣告函式:

<html>
  <body>
    <!-- ... Your HTML and CSS -->

    <script type="importmap">
      {
        "imports": {
          "@google/generative-ai": "https://esm.run/@google/generative-ai"
        }
      }
    </script>
    <script type="module">
      import { GoogleGenerativeAI } from "@google/generative-ai";

      // Fetch your API_KEY
      const API_KEY = "...";

      // Access your API key (see "Set up your API key" above)
      const genAI = new GoogleGenerativeAI(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: [controlLightFunctionDeclaration],
        },
      });
    </script>
  </body>
</html>

生成函式呼叫

使用函式宣告初始化模型後,您可以使用已定義的函式提示模型。您應利用即時通訊提示 (sendMessage()) 使用函式呼叫功能,因為函式呼叫通常利用先前的提示和回應內容進行呼叫。

const chat = generativeModel.startChat();
const prompt = "Dim the lights so the room feels cozy and warm.";

// 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 result = await chat.sendMessage([{functionResponse: {
    name: 'controlLight',
    response: apiResponse
  }}]);

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