Function Calling API

函数调用提高了 LLM 提供相关且符合情境的回答的能力。

您可以使用 Function Calling API 为生成式 AI 模型提供自定义函数。模型不会直接调用这些函数,而是生成指定函数名称和建议的参数的结构化数据输出。此输出可以调用外部 API 或信息系统(如数据库、客户关系管理系统和文档仓库)。生成的 API 输出可供 LLM 用于提高回答质量。

支持的模型

  • Gemini 1.0 Pro
    • gemini-1.0-pro
    • gemini-1.0-pro-001
    • gemini-1.0-pro-002
  • Gemini 1.5 Pro
    • gemini-1.5-pro-preview-0409

限制

  • 最多可以提供 64 个函数。
  • FunctionCallingConfig 为预览版,仅适用于“gemini-1.5-pro-preview-0409”。

语法

  • PROJECT_ID = PROJECT_ID
  • REGION = REGION
  • MODEL_ID = MODEL_ID

curl

https://${REGION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${REGION}/publishers/google/models/${MODEL_ID}:generateContent \
  -d '{
    "contents": [{
      ...
    }],
    "tools": [{
      "function_declarations": [
        {
          ...
        }
      ]
    }]
  }'

Python

gemini_model = GenerativeModel(
    MODEL_ID,
    generation_config=generation_config,
    tools=[
        Tool(
            function_declarations=[
                FunctionDeclaration(
                    ...
                )
            ]
        )
    ],
)

参数列表

FunctionDeclaration

OpenAPI 3.0 规范定义的函数声明的结构化表示形式,表示模型可能会为其生成 JSON 输入的函数。

参数

name

string

要调用的函数名称。

description

可选:string

函数的说明和用途。

parameters

可选:Schema

以 OpenAPI JSON 架构对象格式(OpenAPI 3.0 规范)描述此函数的参数

response

可选:Schema

以 JSON 架构格式描述此函数的输出。

FunctionCallingConfig [预览版]

这是使用函数调用功能的额外配置,仅适用于 gemini-1.5-pro-preview-0409

参数

mode

可选:enum/string[]

  • AUTO:默认模型行为,模型决定预测函数调用或自然语言回答。
  • NONE:模型不会预测任何函数调用。模型行为与不传递任何函数声明时的行为相同。
  • ANY:模型仅限于预测单个函数调用。

设置 allowed_function_names 后,预测函数调用仅限于任何 allowed_function_names。默认情况下,预测函数调用将来自提供的任何 function_declarations

allowed_function_names

可选:string[]

要调用的函数名称。仅在 modeANY 时设置。函数名称应与 [FunctionDeclaration.name] 匹配。将模式设置为 ANY 时,模型将根据提供的一组函数名称预测函数调用。

架构

架构用于定义函数调用中输入和输出数据的格式。OpenAPI 3.0 架构规范定义的函数声明的结构化表示形式。

参数
类型

string

枚举。数据的类型。必须为以下项之一:

  • STRING
  • INTEGER
  • BOOLEAN
  • NUMBER
  • ARRAY
  • OBJECT
description

可选:string

数据的说明。

enum

可选:string[]

Type.STRING 的元素可能的具有枚举格式的值。

items

可选:Schema[]

Type.ARRAY 的元素架构

properties

可选:Schema

Type.OBJECT 的属性的架构

required

可选:string[]

Type.OBJECT 的必要属性。

nullable

可选:bool

指示值是否为 null

示例

  • PROJECT_ID = PROJECT_ID
  • REGION = REGION
  • MODEL_ID = MODEL_ID

基本用例

以下示例展示了如何向模型提交查询和函数声明。

curl

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  https://${REGION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${REGION}/publishers/google/models/${MODEL_ID}:generateContent \
  -d '{
    "contents": [{
      "role": "user",
      "parts": [{
        "text": "What is the weather in Boston?"
      }]
    }],
    "tools": [{
      "function_declarations": [
        {
          "name": "get_current_weather",
          "description": "Get the current weather in a given location",
          "parameters": {
            "type": "object",
            "properties": {
              "location": {
                "type": "string",
                "description": "The city and state, e.g. San Francisco, CA or a zip code e.g. 95616"
              }
            },
            "required": [
              "location"
            ]
          }
        }
      ]
    }]
  }'

Python

import vertexai
from vertexai.generative_models import (
    FunctionDeclaration,
    GenerativeModel,
    GenerationConfig,
    Part,
    Tool,
)

vertexai.init(project=PROJECT_ID, location=REGION)

# Specify a function declaration and parameters for an API request
get_current_weather_func = FunctionDeclaration(
    name="get_current_weather",
    description="Get the current weather in a given location",
    # Function parameters are specified in OpenAPI JSON schema format
    parameters={
        "type": "object",
        "properties": {"location": {"type": "string", "description": "The city and state, e.g. San Francisco, CA or a zip code e.g. 95616"}},
    },
)

# Define a tool that includes the above get_current_weather_func
weather_tool = Tool(
    function_declarations=[get_current_weather_func],
)

gemini_model = GenerativeModel(
    MODEL_ID, generation_config={"temperature": 0}, tools=[weather_tool]
)
model_response = gemini_model.generate_content("What is the weather in Boston?")

print(model_response)

高级用例

以下示例展示了如何将生成配置和工具配置传递给模型。函数调用配置可用于确保模型输出始终是特定的函数调用。为此,请将函数调用模式设置为 ANY,并在 allowed_function_names 参数中指定允许的函数名称。当 allowed_function_names 为空时,可以返回所提供的任何函数。

  • MODEL_ID = gemini-1.5-pro-preview-0409

curl

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  https://${REGION}-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/${REGION}/publishers/google/models/${MODEL_ID}:generateContent \
  -d '{
    "contents": [{
      "role": "user",
      "parts": [{
        "text": "Do you have the White Pixel 8 Pro 128GB in stock in the US?"
      }]
    }],
    "tools": [{
      "function_declarations": [
        {
          "name": "get_product_sku",
          "description": "Get the available inventory for a Google products, e.g: Pixel phones, Pixel Watches, Google Home etc",
          "parameters": {
            "type": "object",
            "properties": {
                "product_name": {"type": "string", "description": "Product name"}
            }
          }
        },
        {
          "name": "get_store_location",
          "description": "Get the location of the closest store",
          "parameters": {
            "type": "object",
            "properties": {"location": {"type": "string", "description": "Location"}},
          }
        }
      ]
    }],
    "tool_config": {
        "function_calling_config": {
            "mode":"ANY",
            "allowed_function_names": ["get_product_sku"]
       }
    },
    "generationConfig": {
      "temperature": 0.95,
      "topP": 1.0,
      "maxOutputTokens": 8192
    }
  }'

Python

import vertexai
from vertexai.generative_models import (
    FunctionDeclaration,
    GenerativeModel,
    GenerationConfig,
    Part,
    Tool,
    ToolConfig,
)

vertexai.init(project=PROJECT_ID, location=REGION)

# Specify a function declaration and parameters for an API request
get_product_info_func = FunctionDeclaration(
    name="get_product_sku",
    description="Get the available inventory for a Google products, e.g: Pixel phones, Pixel Watches, Google Home etc",
    # Function parameters are specified in OpenAPI JSON schema format
    parameters={
        "type": "object",
        "properties": {
            "product_name": {"type": "string", "description": "Product name"}
        },
    },
)

# Specify another function declaration and parameters for an API request
get_store_location_func = FunctionDeclaration(
    name="get_store_location",
    description="Get the location of the closest store",
    # Function parameters are specified in OpenAPI JSON schema format
    parameters={
        "type": "object",
        "properties": {"location": {"type": "string", "description": "Location"}},
    },
)

# Define a tool that includes the above functions
retail_tool = Tool(
    function_declarations=[
        get_product_info_func,
        get_store_location_func,
    ],
)

# Define a tool config for the above functions
retail_tool_config = ToolConfig(
    function_calling_config=ToolConfig.FunctionCallingConfig(
        # ANY mode forces the model to predict a function call
        mode=ToolConfig.FunctionCallingConfig.Mode.ANY,
        # List of functions that can be returned when the mode is ANY.
        # If the list is empty, any declared function can be returned.
        allowed_function_names=["get_product_sku"],
    )
)

generation_config = GenerationConfig(
    temperature=0.95, top_p=1.0, max_output_tokens=8192
)

gemini_model = GenerativeModel(
    MODEL_ID,
    generation_config=generation_config,
    tools=[retail_tool],
    tool_config=retail_tool_config,
)
model_response = gemini_model.generate_content(
    "Do you have the White Pixel 8 Pro 128GB in stock in the US?"
)

print(model_response)

深入探索

如需详细文档,请参阅以下内容: