Call Responses API

Gemini Enterprise Agent Platform의 XAI Grok 모델은 응답 생성을 위한 Responses API를 지원합니다.

이 페이지에서는 Responses API를 사용하여 Grok 모델을 호출하는 방법을 보여줍니다.

시작하기 전에

Gemini Enterprise Agent Platform에서 Grok 모델을 사용하려면 다음 단계를 실행해야 합니다. Gemini Enterprise Agent Platform API (aiplatform.googleapis.com)를 사용 설정해야 합니다.

  1. In the Cloud de Confiance console, on the project selector page, select or create a Cloud de Confiance 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. Verify that billing is enabled for your Cloud de Confiance project.

  3. Enable the Gemini Enterprise Agent Platform API, if it is 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 API

Responses API에 비스트리밍 호출하기

다음 샘플은 Responses API에 비스트리밍 호출을 하는 방법을 보여줍니다.

Python

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

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="INPUT",
    max_output_tokens=MAX_OUTPUT_TOKENS,
    stream=False,
)
print(response)
  • MODEL: 사용하려는 모델 이름입니다(예: xai/grok-4.20-reasoning).
  • INPUT: 모델의 프롬프트 또는 입력입니다.
  • MAX_OUTPUT_TOKENS: 응답에서 생성될 수 있는 토큰의 최대 개수입니다. 토큰은 약 4자(영문 기준)입니다. 토큰 100개는 단어 약 60~80개에 해당합니다.

    응답이 짧을수록 낮은 값을 지정하고 잠재적으로 응답이 길면 높은 값을 지정합니다.

REST

환경을 설정하면 REST를 사용하여 텍스트 프롬프트를 테스트할 수 있습니다. 다음 샘플은 요청을 게시자 모델 엔드포인트에 전송합니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트 ID입니다.
  • MODEL: 사용하려는 모델 이름입니다(예: xai/grok-4.20-reasoning).
  • INPUT: 모델의 프롬프트 또는 입력입니다.
  • MAX_OUTPUT_TOKENS: 응답에서 생성될 수 있는 토큰의 최대 개수입니다. 토큰은 약 4자(영문 기준)입니다. 토큰 100개는 단어 약 60~80개에 해당합니다.

    응답이 짧을수록 낮은 값을 지정하고 잠재적으로 응답이 길면 높은 값을 지정합니다.

HTTP 메서드 및 URL:

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

JSON 요청 본문:

{
  "model": "MODEL",
  "input": "INPUT",
  "max_output_tokens": MAX_OUTPUT_TOKENS,
  "stream": false
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

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

다음 예는 전체 curl 요청을 보여줍니다.

curl -s -X POST \
  -H "Authorization: Bearer $(gcloud auth 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": "Explain black holes in one short sentence.",
    "max_output_tokens": 100,
    "stream": false
  }'

Responses API 정의에 따라 비스트리밍 응답에는 고유 ID, 모델 메타데이터, 사용 통계, 생성된 텍스트가 포함된 출력 배열이 포함됩니다.

{
  "background": false,
  "completed_at": 1778892918,
  "created_at": 1778892916,
  "error": null,
  "frequency_penalty": 0,
  "id": "c8AHavnIMP6UifEPgIfcgAg",
  "incomplete_details": null,
  "instructions": null,
  "max_output_tokens": null,
  "max_tool_calls": null,
  "metadata": {
    "system_fingerprint": "fp_39c5j0a3e9"
  },
  "model": "MODEL",
  "object": "response",
  "output": [
    {
      "content": [
        {
          "annotations": [],
          "logprobs": [],
          "text": "OUTPUT_TEXT",
          "type": "output_text"
        }
      ],
      "id": "msg_c8AHavnIMP6UifEPgIfcgAg",
      "role": "assistant",
      "status": "completed",
      "type": "message"
    }
  ],
  "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": false,
  "temperature": 0.7,
  "text": {
    "format": {
      "type": "text"
    }
  },
  "tool_choice": "auto",
  "tools": [],
  "top_logprobs": 0,
  "top_p": 0.95,
  "truncation": "disabled",
  "usage": {
    "extra_properties": {
      "google": {
        "traffic_type": "ON_DEMAND"
      }
    },
    "input_tokens": 335,
    "input_tokens_details": {
      "cached_tokens": 320
    },
    "num_server_side_tools_used": 0,
    "num_sources_used": 0,
    "output_tokens": 305,
    "output_tokens_details": {
      "reasoning_tokens": 284
    },
    "total_tokens": 640
  },
  "user": null
}

Responses API에 스트리밍 호출하기

다음 샘플은 Responses API에 스트리밍 호출을 하는 방법을 보여줍니다.

Python

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

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

코드 샘플을 실행하기 전에 GOOGLE_CLOUD_UNIVERSE_DOMAIN 환경 변수를 s3nsapis.fr으로 설정합니다.

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

from openai import OpenAI
client = OpenAI()
stream = client.responses.create(
    model="MODEL",
    input="INPUT",
    max_output_tokens=MAX_OUTPUT_TOKENS,
    stream=True,
)
for event in stream:
    if event.type == "response.output_text.delta":
        print(event.delta, end="")
  • MODEL: 사용하려는 모델 이름입니다(예: xai/grok-4.20-reasoning).
  • INPUT: 모델의 프롬프트 또는 입력입니다.
  • MAX_OUTPUT_TOKENS: 응답에서 생성될 수 있는 토큰의 최대 개수입니다. 토큰은 약 4자(영문 기준)입니다. 토큰 100개는 단어 약 60~80개에 해당합니다.

    응답이 짧을수록 낮은 값을 지정하고 잠재적으로 응답이 길면 높은 값을 지정합니다.

REST

환경을 설정하면 REST를 사용하여 텍스트 프롬프트를 테스트할 수 있습니다. 다음 샘플은 요청을 게시자 모델 엔드포인트에 전송합니다.

요청 데이터를 사용하기 전에 다음을 바꿉니다.

  • PROJECT_ID: Google Cloud 프로젝트 ID입니다.
  • MODEL: 사용하려는 모델 이름입니다(예: xai/grok-4.20-reasoning).
  • INPUT: 모델의 프롬프트 또는 입력입니다.
  • MAX_OUTPUT_TOKENS: 응답에서 생성될 수 있는 토큰의 최대 개수입니다. 토큰은 약 4자(영문 기준)입니다. 토큰 100개는 단어 약 60~80개에 해당합니다.

    응답이 짧을수록 낮은 값을 지정하고 잠재적으로 응답이 길면 높은 값을 지정합니다.

HTTP 메서드 및 URL:

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

JSON 요청 본문:

{
  "model": "MODEL",
  "input": "INPUT",
  "max_output_tokens": MAX_OUTPUT_TOKENS,
  "stream": true
}

요청을 보내려면 다음 옵션 중 하나를 선택합니다.

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
 

다음 단계