Grok 모델의 함수 호출

함수 호출을 사용하면 커스텀 함수를 정의하고 LLM에 함수를 호출하여 실시간 정보를 검색하거나 SQL 데이터베이스 또는 고객 서비스 도구와 같은 외부 시스템과 상호작용하는 기능을 제공할 수 있습니다.

함수 호출에 관한 자세한 개념 정보는 함수 호출 소개를 참조하세요.

Responses API와 함께 함수 호출 사용

상태 비저장 기능을 사용하려면 요청에서 storefalse (또는 Python의 경우 False)로 명시적으로 설정하세요. store의 기본값은 true입니다.

상태 저장 기능을 사용하려면 조직 정책 서비스가 이를 허용하도록 구성해야 합니다. 특히 허용된 값에 publishers/xai/models/MODEL_NAME:stateful_responses_api (예: publishers/xai/models/grok-4.20-reasoning:stateful_responses_api)를 추가하여 제약조건 constraints/vertexai.allowedPartnerModelFeatures를 업데이트합니다. 자세한 내용은 모델 액세스 제어를 참고하세요.

다음 템플릿은 Responses API와 함께 함수 호출을 사용하는 방법을 보여줍니다.

Python

이 샘플을 사용해 보기 전에 Python Agent Platform 빠른 시작: 클라이언트 라이브러리 사용의 설정 안내를 따르세요.

Agent Platform에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

이 샘플을 실행하기 전에 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: Google Cloud 프로젝트 ID입니다.
  • MODEL: 사용하려는 모델 이름입니다(예: xai/grok-4.20-reasoning).
  • INPUT: 모델의 프롬프트 또는 입력입니다.
  • FUNCTION_NAME: 호출하려는 함수의 이름입니다.
  • FUNCTION_DESCRIPTION: 함수에 대한 설명입니다.
  • PARAMETERS_OBJECT: 함수 파라미터를 정의하는 JSON 객체입니다.

HTTP 메서드 및 URL:

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

이 샘플을 사용해 보기 전에 Python Agent Platform 빠른 시작: 클라이언트 라이브러리 사용의 설정 안내를 따르세요.

Agent Platform에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

이 샘플을 실행하기 전에 OPENAI_BASE_URL 환경 변수를 설정하거나 OAuth 사용자 인증 정보를 설정해야 합니다. 자세한 내용은 인증 및 사용자 인증 정보를 참조하세요.

from openai import OpenAI
client = OpenAI()

response = client.responses.create( model="xai/grok-4.20-reasoning", 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.20-reasoning",
  "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: Google Cloud 프로젝트 ID입니다.

응답 예시

다음은 모델 출력의 예시입니다.

{
  "background": false,
  "completed_at": 1778893466,
  "created_at": 1778893464,
  "error": null,
  "frequency_penalty": 0,
  "id": "mMIHaqfCCIjUmAb_mMIHaqfCCIjUmAb_6LbAAg",
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": null,
  "max_tool_calls": null,
  "metadata": {
    "system_fingerprint": "fp_39c5j0a3e9"
  },
  "model": "xai/grok-4.20-reasoning",
  "object": "response",
  "output": [
    {
      "arguments": "{\"location\":\"San Francisco\"}",
      "call_id": "call-81ad585c-9e8d-47bd-85ef-2ced8a8fc898-0",
      "id": "fc_mMIHaqfCCIjUmAb_6LbAAg",
      "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": "medium",
    "summary": "detailed"
  },
  "safety_identifier": null,
  "service_tier": "default",
  "status": "completed",
  "store": true,
  "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": {
    "extra_properties": {
      "google": {
        "traffic_type": "ON_DEMAND"
      }
    },
    "input_tokens": 462,
    "input_tokens_details": {
      "cached_tokens": 320
    },
    "num_server_side_tools_used": 0,
    "num_sources_used": 0,
    "output_tokens": 187,
    "output_tokens_details": {
      "reasoning_tokens": 175
    },
    "total_tokens": 649
  },
  "user": null
}

Chat Completions API와 함께 함수 호출 사용

다음 샘플은 채팅 완성에서 함수 호출을 사용하는 방법을 보여줍니다.

Python

이 샘플을 사용해 보기 전에 Python Agent Platform 빠른 시작: 클라이언트 라이브러리 사용의 설정 안내를 따르세요.

Agent Platform에 인증하려면 애플리케이션 기본 사용자 인증 정보를 설정합니다. 자세한 내용은 로컬 개발 환경의 인증 설정을 참조하세요.

이 샘플을 실행하기 전에 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.1-fast-reasoning).
  • 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 메서드 및 URL:

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.1-fast-reasoning",
  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.1-fast-reasoning",
  "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.1-fast-reasoning",
 "object": "chat.completion",
 "system_fingerprint": "",
 "usage": {
  "completion_tokens": 66,
  "prompt_tokens": 217,
  "total_tokens": 283
 }
}

다음 단계