Function Calling API

関数呼び出しにより、関連性の高いコンテキストに沿った回答を提供する LLM の能力が向上します。

Function Calling API を使用すると、生成 AI モデルにカスタム関数を提供できます。モデルは、これらの関数を直接呼び出すのではなく、関数名と推奨される引数を指定する構造化データ出力を生成します。

この出力により、外部 API や情報システム(データベース、顧客管理システム、ドキュメント リポジトリなど)を呼び出すことができます。生成された API 出力は、LLM で使用してレスポンスの品質を向上させることができます。

関数呼び出しに関するコンセプトの詳細については、関数の呼び出しをご覧ください。

サポートされているモデル:

モデル バージョン
Gemini 1.5 Flash gemini-1.5-flash-001
Gemini 1.5 Pro gemini-1.5-pro-001
Gemini 1.0 Pro gemini-1.0-pro-001
gemini-1.0-pro-002

制限事項:

  • リクエストで指定できる関数宣言の最大数は 128 です。
  • FunctionCallingConfig.Mode.ANYGemini 1.5 Pro モデルでのみ使用できます。

構文の例

関数呼び出し API リクエストを送信する構文。

curl

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \

https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/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

関数からの出力を OpenAPI JSON スキーマ オブジェクト形式(OpenAPI 3.0 仕様)で記述します。

Schema

スキーマは、関数呼び出しで入力データと出力データの形式を定義するために使用されます。OpenAPI 3.0 スキーマ仕様で定義されている関数宣言の構造化表現。

パラメータ
type

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 の可能性があるかどうかを示します。

FunctionCallingConfig(プレビュー)

FunctionCallingConfig はモデルの動作を制御し、呼び出す関数のタイプを決定します。

この機能は gemini-1.5-pro-preview-0409 モデルでのみご利用いただけます。

パラメータ

mode

省略可: enum/string[]

  • AUTO: デフォルトのモデル動作。モデルは、関数呼び出し形式または自然言語によるレスポンス形式で予測を行うことができます。モデルは、コンテキストに基づいて使用するフォームを決定します。
  • NONE: モデルは関数呼び出しの形式で予測を行いません。
  • ANY: モデルは常に単一の関数呼び出しを予測します。

allowed_function_names

省略可: string[]

呼び出す関数名。modeANY の場合にのみ設定されます。関数名は [FunctionDeclaration.name] と一致する必要があります。モードを ANY に設定すると、モデルは指定された関数名のセットから関数呼び出しを予測します。

関数宣言を送信する

次の例は、クエリと関数宣言をモデルに送信する基本的な例です。

REST

データをリクエストする前に、次のように置き換えます。

  • PROJECT_ID: 実際のプロジェクト ID
  • LOCATION: リクエストを処理するリージョン。
  • MODEL_ID: 処理中のモデルの ID。
  • ROLE: メッセージを作成するエンティティの ID
  • TEXT: モデルに送信するプロンプト。
  • NAME: 呼び出す関数の名前。
  • DESCRIPTION: 関数の説明と目的。
  • 他のフィールドについては、パラメータのリストの表をご覧ください。

HTTP メソッドと URL:

POST   https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:generateContent

リクエストの本文(JSON):

{
  "contents": [{
    "role": "ROLE",
    "parts": [{
      "text": "TEXT"
    }]
  }],
  "tools": [{
    "function_declarations": [
      {
        "name": "NAME",
        "description": "DESCRIPTION",
        "parameters": {
          "type": "TYPE",
          "properties": {
            "location": {
              "type": "TYPE",
              "description": "DESCRIPTION"
            }
          },
          "required": [
            "location"
          ]
        }
      }
    ]
  }]
}

リクエストを送信するには、次のいずれかのオプションを選択します。

curl

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
" https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:generateContent"

PowerShell

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri " https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/publishers/google/models/MODEL_ID:generateContent" | Select-Object -Expand Content

curl コマンドの例

PROJECT_ID=myproject
LOCATION=us-central1
MODEL_ID=gemini-1.0-pro-002

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}:generateContent \
  -d '{
    "contents": [{
      "role": "user",
      "parts": [{
        "text": "What is the weather in Boston?"
      }]
    }],
    "tools": [{
      "functionDeclarations": [
        {
          "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 (
    Content,
    FunctionDeclaration,
    GenerationConfig,
    GenerativeModel,
    Part,
    Tool,
)

# Initialize Vertex AI
# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
vertexai.init(project=project_id, location="us-central1")

# Initialize Gemini model
model = GenerativeModel(model_name="gemini-1.0-pro-001")

# Define the user's prompt in a Content object that we can reuse in model calls
user_prompt_content = Content(
    role="user",
    parts=[
        Part.from_text("What is the weather like in Boston?"),
    ],
)

# Specify a function declaration and parameters for an API request
function_name = "get_current_weather"
get_current_weather_func = FunctionDeclaration(
    name=function_name,
    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": "Location"}},
    },
)

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

# Send the prompt and instruct the model to generate content using the Tool that you just created
response = model.generate_content(
    user_prompt_content,
    generation_config=GenerationConfig(temperature=0),
    tools=[weather_tool],
)
function_call = response.candidates[0].function_calls[0]
print(function_call)

# Check the function name that the model responded with, and make an API call to an external system
if function_call.name == function_name:
    # Extract the arguments to use in your API call
    location = function_call.args["location"]  # noqa: F841

    # Here you can use your preferred method to make an API request to fetch the current weather, for example:
    # api_response = requests.post(weather_api_url, data={"location": location})

    # In this example, we'll use synthetic data to simulate a response payload from an external API
    api_response = """{ "location": "Boston, MA", "temperature": 38, "description": "Partly Cloudy",
                    "icon": "partly-cloudy", "humidity": 65, "wind": { "speed": 10, "direction": "NW" } }"""

# Return the API response to Gemini so it can generate a model response or request another function call
response = model.generate_content(
    [
        user_prompt_content,  # User prompt
        response.candidates[0].content,  # Function call response
        Content(
            parts=[
                Part.from_function_response(
                    name=function_name,
                    response={
                        "content": api_response,  # Return the API response to Gemini
                    },
                ),
            ],
        ),
    ],
    tools=[weather_tool],
)

# Get the model response
print(response.text)

Node.js

const {
  VertexAI,
  FunctionDeclarationSchemaType,
} = require('@google-cloud/vertexai');

const functionDeclarations = [
  {
    function_declarations: [
      {
        name: 'get_current_weather',
        description: 'get weather in a given location',
        parameters: {
          type: FunctionDeclarationSchemaType.OBJECT,
          properties: {
            location: {type: FunctionDeclarationSchemaType.STRING},
            unit: {
              type: FunctionDeclarationSchemaType.STRING,
              enum: ['celsius', 'fahrenheit'],
            },
          },
          required: ['location'],
        },
      },
    ],
  },
];

/**
 * TODO(developer): Update these variables before running the sample.
 */
async function functionCallingBasic(
  projectId = 'PROJECT_ID',
  location = 'us-central1',
  model = 'gemini-1.5-flash-001'
) {
  // Initialize Vertex with your Cloud project and location
  const vertexAI = new VertexAI({project: projectId, location: location});

  // Instantiate the model
  const generativeModel = vertexAI.preview.getGenerativeModel({
    model: model,
  });

  const request = {
    contents: [
      {role: 'user', parts: [{text: 'What is the weather in Boston?'}]},
    ],
    tools: functionDeclarations,
  };
  const result = await generativeModel.generateContent(request);
  console.log(JSON.stringify(result.response.candidates[0].content));
}

REST(OpenAI)

OpenAI ライブラリを使用して、Function Calling API を呼び出すことができます。詳細については、OpenAI ライブラリを使用して Gemini を呼び出すをご覧ください。

データをリクエストする前に、次のように置き換えます。

  • PROJECT_ID: 実際のプロジェクト ID
  • LOCATION: リクエストを処理するリージョン。
  • MODEL_ID: 処理中のモデルの ID。

HTTP メソッドと URL:

POST https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/endpoints/openapi/chat/completions

リクエストの本文(JSON):

{
  "model": "google/MODEL_ID",
  "messages": [
    {
      "role": "user",
      "content": "What is the weather in Boston?"
    }
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "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"]
        }
      }
    }
  ]
}

リクエストを送信するには、次のいずれかのオプションを選択します。

curl

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/endpoints/openapi/chat/completions"

PowerShell

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/endpoints/openapi/chat/completions" | Select-Object -Expand Content

Python(OpenAI)

OpenAI ライブラリを使用して、Function Calling API を呼び出すことができます。詳細については、OpenAI ライブラリを使用して Gemini を呼び出すをご覧ください。

import vertexai
import openai

from google.auth import default, transport

# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
# location = "us-central1"

vertexai.init(project=project_id, location=location)

# Programmatically get an access token
credentials, _ = default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
auth_request = transport.requests.Request()
credentials.refresh(auth_request)

# # OpenAI Client
client = openai.OpenAI(
    base_url=f"https://{location}-aiplatform.googleapis.com/v1beta1/projects/{project_id}/locations/{location}/endpoints/openapi",
    api_key=credentials.token,
)

tools = [
    {
        "type": "function",
        "function": {
            "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"],
            },
        },
    }
]

messages = []
messages.append(
    {
        "role": "system",
        "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.",
    }
)
messages.append({"role": "user", "content": "What is the weather in Boston?"})

response = client.chat.completions.create(
    model="google/gemini-1.5-flash-001",
    messages=messages,
    tools=tools,
)

print(response)

FunctionCallingConfig で関数宣言を送信する

次の例では、FunctionCallingConfig をモデルに渡す方法を示します。

functionCallingConfig を使用すると、モデルの出力が常に特定の関数呼び出しになるようにできます。構成するには:

  • mode を呼び出す関数を ANY に設定します。
  • allowed_function_names で使用する関数名を指定します。allowed_function_names が空の場合、指定された関数のいずれかが返される可能性があります。

REST

PROJECT_ID=myproject
LOCATION=us-central1
MODEL_ID=gemini-1.5-pro-preview-0409

curl -X POST \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  https://${LOCATION}-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/${LOCATION}/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": [{
      "functionDeclarations": [
        {
          "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"}
            },
          }
        }
      ]
    }],
    "toolConfig": {
        "functionCallingConfig": {
            "mode":"ANY",
            "allowedFunctionNames": ["get_product_sku"]
      }
    },
    "generationConfig": {
      "temperature": 0.95,
      "topP": 1.0,
      "maxOutputTokens": 8192
    }
  }'

Python

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

# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"

# Initialize Vertex AI
vertexai.init(project=project_id, location="us-central1")

# Specify a function declaration and parameters for an API request
get_product_sku_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_sku_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"],
    )
)

model = GenerativeModel(
    model_name="gemini-1.5-flash-001",
    tools=[retail_tool],
    tool_config=retail_tool_config,
)
response = model.generate_content(
    "Do you have the Pixel 8 Pro 128GB in stock?",
)

print(response.text)
print(response.candidates[0].function_calls)

Node.js

const {
  VertexAI,
  FunctionDeclarationSchemaType,
} = require('@google-cloud/vertexai');

const functionDeclarations = [
  {
    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: FunctionDeclarationSchemaType.OBJECT,
          properties: {
            productName: {type: FunctionDeclarationSchemaType.STRING},
          },
        },
      },
      {
        name: 'get_store_location',
        description: 'Get the location of the closest store',
        parameters: {
          type: FunctionDeclarationSchemaType.OBJECT,
          properties: {
            location: {type: FunctionDeclarationSchemaType.STRING},
          },
        },
      },
    ],
  },
];

const toolConfig = {
  function_calling_config: {
    mode: 'ANY',
    allowed_function_names: ['get_product_sku'],
  },
};

const generationConfig = {
  temperature: 0.95,
  topP: 1.0,
  maxOutputTokens: 8192,
};

/**
 * TODO(developer): Update these variables before running the sample.
 */
async function functionCallingAdvanced(
  projectId = 'PROJECT_ID',
  location = 'us-central1',
  model = 'gemini-1.5-flash-001'
) {
  // Initialize Vertex with your Cloud project and location
  const vertexAI = new VertexAI({project: projectId, location: location});

  // Instantiate the model
  const generativeModel = vertexAI.preview.getGenerativeModel({
    model: model,
  });

  const request = {
    contents: [
      {
        role: 'user',
        parts: [
          {text: 'Do you have the White Pixel 8 Pro 128GB in stock in the US?'},
        ],
      },
    ],
    tools: functionDeclarations,
    tool_config: toolConfig,
    generation_config: generationConfig,
  };
  const result = await generativeModel.generateContent(request);
  console.log(JSON.stringify(result.response.candidates[0].content));
}

REST(OpenAI)

OpenAI ライブラリを使用して、Function Calling API を呼び出すことができます。詳細については、OpenAI ライブラリを使用して Gemini を呼び出すをご覧ください。

データをリクエストする前に、次のように置き換えます。

  • PROJECT_ID: 実際のプロジェクト ID
  • LOCATION: リクエストを処理するリージョン。
  • MODEL_ID: 処理中のモデルの ID。

HTTP メソッドと URL:

POST https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/endpoints/openapi/chat/completions

リクエストの本文(JSON):

{
  "model": "google/MODEL_ID",
  "messages": [
  {
    "role": "user",
    "content": "What is the weather in Boston?"
  }
],
"tools": [
  {
    "type": "function",
    "function": {
      "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"]
      }
    }
  }
],
"tool_choice": "auto"
}

リクエストを送信するには、次のいずれかのオプションを選択します。

curl

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d @request.json \
"https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/endpoints/openapi/chat/completions"

PowerShell

リクエスト本文を request.json という名前のファイルに保存して、次のコマンドを実行します。

$cred = gcloud auth print-access-token
$headers = @{ "Authorization" = "Bearer $cred" }

Invoke-WebRequest `
-Method POST `
-Headers $headers `
-ContentType: "application/json; charset=utf-8" `
-InFile request.json `
-Uri "https://LOCATION-aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/LOCATION/endpoints/openapi/chat/completions" | Select-Object -Expand Content

Python(OpenAI)

OpenAI ライブラリを使用して、Function Calling API を呼び出すことができます。詳細については、OpenAI ライブラリを使用して Gemini を呼び出すをご覧ください。

import vertexai
import openai

from google.auth import default, transport

# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
# location = "us-central1"

vertexai.init(project=project_id, location=location)

# Programmatically get an access token
credentials, _ = default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
auth_request = transport.requests.Request()
credentials.refresh(auth_request)

# # OpenAI Client
client = openai.OpenAI(
    base_url=f"https://{location}-aiplatform.googleapis.com/v1beta1/projects/{project_id}/locations/{location}/endpoints/openapi",
    api_key=credentials.token,
)

tools = [
    {
        "type": "function",
        "function": {
            "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"],
            },
        },
    }
]

messages = []
messages.append(
    {
        "role": "system",
        "content": "Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.",
    }
)
messages.append({"role": "user", "content": "What is the weather in Boston?"})

response = client.chat.completions.create(
    model="google/gemini-1.5-flash-001",
    messages=messages,
    tools=tools,
    tool_choice="auto",
)

print(response)

次のステップ

詳細なドキュメントについては、以下をご覧ください。