Grok 模型的函式呼叫

您可以透過函式呼叫定義自訂函式,並讓 LLM 呼叫這些函式,擷取即時資訊或與外部系統 (例如 SQL 資料庫或客戶服務工具) 互動。

如要進一步瞭解呼叫函式的概念,請參閱「呼叫函式簡介」。

搭配 Responses API 使用函式呼叫

store 的預設值為 false,因此除非您將 store 設為 true (或 Python 中的 True),否則要求為無狀態。如要儲存回應,請參閱「對 Responses API 進行有狀態呼叫」。

下列範本說明如何搭配使用 Responses API 和函式呼叫:

Python

在試用這個範例之前,請先按照「使用用戶端程式庫的 Agent Platform 快速入門導覽課程」中的 Python 設定說明操作。

如要向 Agent Platform 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr。

執行這個範例前,請務必設定 OPENAI_BASE_URL 環境變數或 OAuth 憑證。詳情請參閱「驗證和憑證」。

from openai import OpenAI
client = OpenAI()

response = client.responses.create( model="MODEL", input=[ {"role": "user", "content": "CONTENT"} ], tools=[ { "type": "function", "name": "FUNCTION_NAME", "description": "FUNCTION_DESCRIPTION", "parameters": PARAMETERS_OBJECT, } ], tool_choice="auto", )

  • MODEL:要使用的模型名稱,例如 xai/grok-4.20-reasoning。
  • CONTENT:要傳送至模型的使用者提示。
  • FUNCTION_NAME:要呼叫的函式名稱。
  • FUNCTION_DESCRIPTION:函式說明。
  • PARAMETERS_OBJECT:定義函式參數的字典,例如:
    {"type": "object", "properties": {"location": {"type": "string", "description": "The city and state"}}, "required": ["location"]}

REST

使用任何要求資料之前,請先修改下列項目的值:

  • PROJECT_ID: Cloud de Confiance 專案 ID。
  • MODEL:要使用的模型名稱,例如 xai/grok-4.20-reasoning。
  • INPUT:模型的提示或輸入內容。
  • FUNCTION_NAME:要呼叫的函式名稱。
  • FUNCTION_DESCRIPTION:函式說明。
  • PARAMETERS_OBJECT:定義函式參數的 JSON 物件。

HTTP 方法和網址:

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

JSON 要求內文:

{
  "model": "MODEL",
  "input": [
    {"role": "user", "content": "INPUT"}
  ],
  "tools": [
    {
      "type": "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/responses"

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/responses" | Select-Object -Expand Content
 

範例

以下範例說明如何搭配使用 Responses API 和函式呼叫:

Python

在試用這個範例之前,請先按照「使用用戶端程式庫的 Agent Platform 快速入門導覽課程」中的 Python 設定說明操作。

如要向 Agent Platform 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr。

執行這個範例前,請務必設定 OPENAI_BASE_URL 環境變數或 OAuth 憑證。詳情請參閱「驗證和憑證」。

from openai import OpenAI
client = OpenAI()

response = client.responses.create( model="xai/grok-4.7", input=[ {"role": "user", "content": "What is the temperature in San Francisco?"} ], tools=[ { "type": "function", "name": "get_temperature", "description": "Get current temperature for a location", "parameters": { "type": "object", "properties": { "location": {"type": "string", "description": "City name"}, "unit": {"type": "string", "enum": ["celsius", "fahrenheit"], "default": "fahrenheit"} }, "required": ["location"] } } ], tool_choice="auto", ) print(response)

REST

curl -X POST \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json" \
https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/endpoints/openapi/responses -d \
'{
  "model": "xai/grok-4.7",
  "input": [
    {"role": "user", "content": "What is the temperature in San Francisco?"}
  ],
  "tools": [
    {
      "type": "function",
      "name": "get_temperature",
      "description": "Get current temperature for a location",
      "parameters": {
        "type": "object",
        "properties": {
          "location": {"type": "string", "description": "City name"},
          "unit": {"type": "string", "enum": ["celsius", "fahrenheit"], "default": "fahrenheit"}
        },
        "required": ["location"]
      }
    }
  ]
}'
  • PROJECT_ID: Cloud de Confiance 專案 ID。

回應範例

以下是模型輸出的範例:

{
  "background": false,
  "completed_at": 1793837405,
  "created_at": 1793837405,
  "error": null,
  "frequency_penalty": 0,
  "id": "01740aca-cb19-4ced-a0ad-1d9d66823486",
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": null,
  "max_tool_calls": null,
  "metadata": {
    "system_fingerprint": "fp_grok47_0"
  },
  "model": "xai/grok-4.7",
  "object": "response",
  "output": [
    {
      "arguments": "{\"location\":\"San Francisco\"}",
      "call_id": "call-bf667907-754b-4848-a95b-d2fae296d56e-0",
      "id": "01740aca-cb19-4ced-a0ad-1d9d66823486",
      "name": "get_temperature",
      "status": "completed",
      "type": "function_call"
    }
  ],
  "parallel_tool_calls": true,
  "presence_penalty": 0,
  "previous_response_id": null,
  "prompt_cache_key": null,
  "reasoning": {
    "effort": "high",
    "summary": "detailed"
  },
  "safety_identifier": null,
  "service_tier": "default",
  "status": "completed",
  "store": false,
  "temperature": 0.7,
  "text": {
    "format": {
      "type": "text"
    }
  },
  "tool_choice": "auto",
  "tools": [
    {
      "description": "Get current temperature for a location",
      "name": "get_temperature",
      "parameters": {
        "properties": {
          "location": {
            "description": "City name",
            "type": "string"
          },
          "unit": {
            "default": "fahrenheit",
            "enum": [
              "celsius",
              "fahrenheit"
            ],
            "type": "string"
          }
        },
        "required": [
          "location"
        ],
        "type": "object"
      },
      "strict": false,
      "type": "function"
    }
  ],
  "top_logprobs": 0,
  "top_p": 0.95,
  "truncation": "disabled",
  "usage": {
    "context_details": {
      "input_tokens": 325,
      "output_tokens": 31
    },
    "extra_properties": {
      "google": {
        "traffic_type": "ON_DEMAND"
      }
    },
    "input_tokens": 325,
    "input_tokens_details": {
      "cached_tokens": 0
    },
    "num_server_side_tools_used": 0,
    "num_sources_used": 0,
    "output_tokens": 31,
    "output_tokens_details": {
      "reasoning_tokens": 18
    },
    "total_tokens": 356
  },
  "user": null
}

搭配 Chat Completions API 使用函式呼叫

下列範例說明如何搭配使用函式呼叫和對話完成。

Python

在試用這個範例之前,請先按照「使用用戶端程式庫的 Agent Platform 快速入門導覽課程」中的 Python 設定說明操作。

如要向 Agent Platform 進行驗證,請設定應用程式預設憑證。詳情請參閱「為本機開發環境設定驗證機制」。

執行程式碼範例前,請將 GOOGLE_CLOUD_UNIVERSE_DOMAIN 環境變數設為 s3nsapis.fr。

執行這個範例前,請務必設定 OPENAI_BASE_URL 環境變數或 OAuth 憑證。詳情請參閱「驗證和憑證」。

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:要使用的模型名稱,例如 xai/grok-4.6。
  • CONTENT:要傳送至模型的使用者提示。
  • FUNCTION_NAME:要呼叫的函式名稱。
  • FUNCTION_DESCRIPTION:函式說明。
  • PARAMETERS_OBJECT:定義函式參數的字典,例如:
    {"type": "object", "properties": {"location": {"type": "string", "description": "The city and state"}}, "required": ["location"]}

REST

使用任何要求資料之前,請先修改下列項目的值:

  • PROJECT_ID:您的 Google Cloud 專案 ID。
  • LOCATION:支援 Grok 模型的區域。
  • MODEL:要使用的模型名稱,例如 xai/grok-4.1-fast-reasoning。
  • CONTENT:要傳送至模型的使用者提示。
  • FUNCTION_NAME:要呼叫的函式名稱。
  • FUNCTION_DESCRIPTION:函式說明。
  • PARAMETERS_OBJECT:定義函式參數的 JSON 結構定義物件,例如:
    {"type": "object", "properties": {"location": {"type": "string", "description": "The city and state"}}, "required": ["location"]}

HTTP 方法和網址:

POST https://LOCATION-aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/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://LOCATION-aiplatform.googleapis.com/v1/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/v1/projects/PROJECT_ID/locations/LOCATION/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="xai/grok-4.6",
  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 application-default print-access-token)" \
-H "Content-Type: application/json" \
https://us-central1-aiplatform.googleapis.com/v1/projects/sample-project/locations/us-central1/endpoints/openapi/chat/completions -d \
'{
  "model": "xai/grok-4.6",
  "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` 函式擷取的資訊後,就能整合兩個 `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": "xai/grok-4.6",
 "object": "chat.completion",
 "system_fingerprint": "",
 "usage": {
  "completion_tokens": 66,
  "prompt_tokens": 217,
  "total_tokens": 283
 }
}

後續步驟