函式呼叫教學課程

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

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

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

燈光控制 API 範例

假設您有一個基本的照明控制系統 搭配應用程式設計 介面 (API),並希望使用者能透過簡單的 文字要求您可以使用函式呼叫功能解讀光線 將來自使用者的要求轉譯為 API 呼叫,藉此設定亮度 輕鬆分配獎金這款假設性的照明控制系統 燈光亮度以及色溫,定義為兩個分開的 參數:

參數 類型 必要 說明
brightness 數字 亮度介於 0 到 100 之間。零關閉,100 為全彩。
colorTemperature 字串 燈具的色溫,可能是 daylightcoolwarm

簡單來說,這個虛構的照明系統只有一盞燈,因此使用者 也不必指定會議室或地點以下是 JSON 要求示例 可以將燈光亮度調到 50% 利用日光色溫:

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

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

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

呼叫 Gemini 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
  };
}

建立函式宣告

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

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, colorTemperature }) => {
    return setLightValues( brightness, colorTemperature)
  }
};

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

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

const { GoogleGenerativeAI } = require("@google/generative-ai");

// Access your API key as an environment variable (see "Set up your API key" above)
const genAI = new GoogleGenerativeAI(process.env.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],
  },
});

生成函式呼叫

使用函式宣告來初始化模型後, 以已定義的函式提示模型請改用函式呼叫 使用即時通訊提示 (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 result2 = await chat.sendMessage([{functionResponse: {
    name: 'controlLight',
    response: apiResponse
  }}]);

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