オープンモデルの関数呼び出し

関数呼び出しを使用すると、カスタム関数を定義して LLM で呼び出し、リアルタイムで情報を取得したり、SQL データベースや顧客サービスツールなどの外部システムとやり取りすることができます。

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

始める前に

Gemini Enterprise Agent Platform でオープンモデルを使用するには、次の操作を行う必要があります。Gemini Enterprise Agent Platform でオープンモデルを使用するには、Agent Platform API(aiplatform.googleapis.com)と Cloud Commerce Consumer Procurement API(cloudcommerceconsumerprocurement.googleapis.com)を有効にする必要があります。これらの API が有効になっている既存のプロジェクトがある場合は、新しいプロジェクトを作成する代わりに、そのプロジェクトを使用できます。

  1. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  2. If you're using an existing project for this guide, verify that you have the permissions required to complete this guide. If you created a new project, then you already have the required permissions.

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Gemini Enterprise Agent Platform and Cloud Commerce Consumer Procurement APIs, if any are not already enabled.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the APIs

  5. 使用するモデルの Model Garden モデルカードに移動し、[有効にする] をクリックして、モデルを有効にしてプロジェクトで使用できるようにします。

    Model Garden に移動

必要なロール

オープンモデルを有効にして使用するために必要な権限を取得するには、プロジェクトに対する次の IAM ロールを付与するよう管理者に依頼してください。

ロールの付与については、プロジェクト、フォルダ、組織へのアクセス権の管理をご覧ください。

必要な権限は、カスタムロールや他の事前定義ロールから取得することもできます。

オープンモデルの権限の付与と組織のポリシーの構成の詳細については、ユーザーにオープンモデルへのアクセス権を付与するをご覧ください。

関数呼び出しを使用する

次のサンプルは、関数呼び出しの使用方法を示しています。

Python

このサンプルを試す前に、クライアント ライブラリを使用した Agent Platform クイックスタートの Python の手順に沿って設定を行ってください。

Agent Platform への認証を行うには、アプリケーションのデフォルト認証情報を設定します。詳細については、ローカル開発環境の認証の設定をご覧ください。

このサンプルを実行する前に、必ず OPENAI_BASE_URL 環境変数を設定してください。詳細については、認証と認証情報をご覧ください。

from openai import OpenAI
client = OpenAI()

response = client.chat.completions.create(
  model="MODEL",
  messages=[
    {"role": "user", "content": "CONTENT"}
  ],
  tools=[
    {
      "type": "function",
      "function": {
        "name": "FUNCTION_NAME",
        "description": "FUNCTION_DESCRIPTION",
        "parameters": PARAMETERS_OBJECT,
      }
    }
  ],
  tool_choice="auto",
)
  • MODEL: 使用するモデル名(zai-org/glm-5.2-maas など)。
  • CONTENT: モデルに送信するユーザー プロンプト。
  • FUNCTION_NAME: 呼び出す関数の名前。
  • FUNCTION_DESCRIPTION: 関数の説明。
  • PARAMETERS_OBJECT: 関数パラメータを定義する辞書。例:
    {"type": "object", "properties": {"location": {"type": "string", "description": "The city and state"}}, "required": ["location"]}

REST

環境をセットアップしたら、REST を使用してテキスト プロンプトをテストできます。次のサンプルは、パブリッシャー モデルのエンドポイントにリクエストを送信します。

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

  • PROJECT_ID: Google Cloud プロジェクト ID。
  • MODEL: 使用するモデル名(zai-org/glm-5.2-maas など)。
  • CONTENT: モデルに送信するユーザー プロンプト。
  • FUNCTION_NAME: 呼び出す関数の名前。
  • FUNCTION_DESCRIPTION: 関数の説明。
  • PARAMETERS_OBJECT: 関数パラメータを定義する JSON スキーマ オブジェクト。例:
    {"type": "object", "properties": {"location": {"type": "string", "description": "The city and state"}}, "required": ["location"]}

HTTP メソッドと URL:

POST https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/endpoints/openapi/chat/completions

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

{
  "model": "MODEL",
  "messages": [
    {
      "role": "user",
      "content": "CONTENT"
    }
  ],
  "tools": [
    {
      "type": "function",
      "function": {
        "name": "FUNCTION_NAME",
        "description": "FUNCTION_DESCRIPTION",
        "parameters": PARAMETERS_OBJECT
      }
    }
  ],
  "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://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/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://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/endpoints/openapi/chat/completions" | Select-Object -Expand Content

成功したことを示すステータス コード(2xx)と空のレスポンスが返されます。

例

get_current_weather 関数を使用して気象情報を取得した後に想定される完全な出力は次のとおりです。

Python

from openai import OpenAI
client = OpenAI()

response = client.chat.completions.create(
  model="zai-org/glm-5.2-maas",
  messages=[
    {
      "role": "user",
      "content": "Which city has a higher temperature, Boston or new Delhi and by how much in F?"
    },
    {
      "role": "assistant",
      "content": "I'll check the current temperatures for Boston and New Delhi in Fahrenheit and compare them. I'll call the weather function for both cities.",
      "tool_calls": [{"function":{"arguments":"{\"location\":\"Boston, MA\",\"unit\":\"fahrenheit\"}","name":"get_current_weather"},"id":"get_current_weather","type":"function"},{"function":{"arguments":"{\"location\":\"New Delhi, India\",\"unit\":\"fahrenheit\"}","name":"get_current_weather"},"id":"get_current_weather","type":"function"}]
    },
    {
      "role": "tool",
      "content": "The temperature in Boston is 75 degrees Fahrenheit.",
      "tool_call_id": "get_current_weather"
    },
    {
      "role": "tool",
      "content": "The temperature in New Delhi is 50 degrees Fahrenheit.",
      "tool_call_id": "get_current_weather"
    }
  ],
  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"
            },
            "unit": {
              "type": "string",
              "enum": ["celsius", "fahrenheit"]
            }
          },
          "required": ["location"]
        }
      }
    }
  ],
  tool_choice="auto"
)

curl

curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json" \
https://aiplatform.googleapis.com/v1/projects/sample-project/locations/global/endpoints/openapi/chat/completions -d \
'{
  "model": "zai-org/glm-5.2-maas",
  "messages": [
    {
      "role": "user",
      "content": "Which city has a higher temperature, Boston or new Delhi and by how much in F?"
    },
    {
      "role": "assistant",
      "content": "I'll check the current temperatures for Boston and New Delhi in Fahrenheit and compare them. I'll call the weather function for both cities.",
      "tool_calls": [{"function":{"arguments":"{\"location\":\"Boston, MA\",\"unit\":\"fahrenheit\"}","name":"get_current_weather"},"id":"get_current_weather","type":"function"},{"function":{"arguments":"{\"location\":\"New Delhi, India\",\"unit\":\"fahrenheit\"}","name":"get_current_weather"},"id":"get_current_weather","type":"function"}]
    },
    {
      "role": "tool",
      "content": "The temperature in Boston is 75 degrees Fahrenheit.",
      "tool_call_id": "get_current_weather"
    },
    {
      "role": "tool",
      "content": "The temperature in New Delhi is 50 degrees Fahrenheit.",
      "tool_call_id": "get_current_weather"
    }
  ],
  "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"
            },
            "unit": {
              "type": "string",
              "enum": ["celsius", "fahrenheit"]
            }
          },
          "required": ["location"]
        }
      }
    }
  ],
  "tool_choice": "auto"
}'
外部の get_current_weather 関数を呼び出して取得した情報を受け取ると、モデルは 2 つの tool レスポンスから情報を合成し、ユーザーの質問に回答できます。モデル出力の例を次に示します。
{
 "choices": [
  {
   "finish_reason": "stop",
   "index": 0,
   "logprobs": null,
   "message": {
    "content": "Based on the current weather data:\n\n- **Boston, MA**: 75°F
    \n- **New Delhi, India**: 50°F  \n\n**Comparison**:
    \nBoston is **25°F warmer** than New Delhi.  \n\n**Answer**:
    \nBoston has a higher temperature than New Delhi by 25 degrees Fahrenheit.",
    "role": "assistant"
   }
  }
 ],
 "created": 1750450289,
 "id": "2025-06-20|13:11:29.240295-07|6.230.75.101|-987540014",
 "model": "zai-org/glm-5.2-maas",
 "object": "chat.completion",
 "system_fingerprint": "",
 "usage": {
  "completion_tokens": 66,
  "prompt_tokens": 217,
  "total_tokens": 283
 }
}

モデル固有のガイダンス

以降のセクションでは、関数呼び出しに関するモデル固有のガイダンスを提供します。

DeepSeek

システム プロンプトを使用すると、DeepSeek モデルは関数呼び出しで十分なパフォーマンスを発揮しません。DeepSeek モデルで関数呼び出しを使用する場合は、最適なパフォーマンスを得るため、システム プロンプトを省略します。

Llama

meta/llama3-405b-instruct-maas は、tool_choice = 'required' をサポートしていません。

OpenAI

openai/gpt-oss-120b-maas を使用する場合は、最適なパフォーマンスを得るため、ツール定義をシステム プロンプトに配置します。次に例を示します。

{"messages": [
    {"role": "system", "content": "You are a helpful assistant with access to the following functions. Use them if required:\n..."},
    {"role": "user", "content": "What's the weather like in Boston?"},
    ...
]}

このモデルは、tool_choice = 'required' または名前付きツール呼び出しをサポートしていません。

次のステップ