Grok 모델의 함수 호출

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

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

함수 호출 사용

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

Python

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

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

이 샘플을 실행하기 전에 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: 사용하려는 모델 이름입니다(예: 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

환경을 설정하면 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 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
 }
}

다음 단계