教程:函数调用

<ph type="x-smartling-placeholder"></ph>

函数调用可让您更轻松地从 Google Cloud 控制台获取结构化数据输出 生成模型。然后,您可以使用这些输出来调用其他 API 并返回 将相关的响应数据提供给模型。换句话说,函数调用有助于 将生成模型连接到外部系统, 可提供最新、最准确的信息。

您可以向 Gemini 模型提供函数说明。这些是 以应用语言编写的函数(也就是说,它们 Google Cloud Functions)。模型可能会要求您调用一个函数并返回 帮助模型处理您的查询。

如果您还没看过 函数调用简介(用于学习相关知识)

照明控制示例 API

假设您有一个基本的照明控制系统,其中包含一个应用编程接口, 并且希望让用户能够通过简单的 文本请求。您可以使用函数调用功能来解释光照 更改来自用户的请求,并将其转换为 API 调用,以设置光照 值。这个假设的照明控制系统可让您控制 即光的亮度和色温,两者定义为 参数:

参数 类型 必需 说明
brightness number 光级范围为 0 到 100。0 表示关闭,100 表示完整亮度。
colorTemperature 字符串 灯具的色温,可以是 daylightcoolwarm

为简单起见,这个虚构的照明系统只有一个光源,因此用户 不需要指定房间或地点。下面是一个 JSON 请求示例 您可以发送到照明控制 API,将亮度更改为 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());
}