OpenAI 호환성

Gemini 모델은 REST API와 함께 OpenAI 라이브러리 (Python, TypeScript, JavaScript)를 사용하여 액세스할 수 있습니다. Gemini Enterprise Agent Platform에서 OpenAI 라이브러리를 사용하려면 Google Cloud Auth만 지원됩니다. 아직 OpenAI 라이브러리를 사용하고 있지 않다면 Gemini API를 직접 호출하세요. OpenAI 라이브러리를 사용하고 있고 Agent Platform SDK로 마이그레이션하려면 OpenAI SDK에서 Google 생성형 AI SDK로 마이그레이션을 참고하세요.

Python

import openai
from google.auth import default
import google.auth.transport.requests

# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
# location = "global"

# Programmatically get an access token
credentials, _ = default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
credentials.refresh(google.auth.transport.requests.Request())

# OpenAI Client
client = openai.OpenAI(
  base_url=f"https://aiplatform.googleapis.com/v1/projects/{project_id}/locations/{location}/endpoints/openapi",
  api_key=credentials.token
)

response = client.chat.completions.create(
  model="google/gemini-3.5-flash",
  messages=[
      {"role": "system", "content": "You are a helpful assistant."},
      {"role": "user", "content": "Explain to me how AI works"}
  ]
)

print(response.choices[0].message)

표준 OpenAI 클라이언트 구성과의 차이점은 다음과 같습니다.

  • api_key=credentials.token:Google Cloud 애플리케이션 기본 사용자 인증 정보에서 가져온 OAuth 액세스 토큰을 사용합니다.

  • base_url: OpenAI 라이브러리에 기본 URL 대신 Agent Platform OpenAI 호환 엔드포인트에 요청을 전송하도록 지시합니다.

  • model="google/gemini-3.5-flash": Agent Platform에서 호스팅되는 호환되는 Gemini 모델을 선택합니다.

생각 중

Gemini 3 모델은 대답을 반환하기 전에 내부 추론 프로세스를 생성하여 복잡한 다단계 작업의 성능을 개선합니다. Gemini API에서 thinking_level 매개변수는 개별 계층 (MINIMAL, LOW, MEDIUM, HIGH) 전반의 추론 깊이를 제어합니다.

OpenAI 호환 Chat Completions API에서 reasoning_effort 파라미터 ("minimal", "low", "medium" 또는 "high")를 사용하여 추론 깊이를 제어합니다. 이 파라미터는 Gemini 3 모델의 해당 thinking_level 설정에 매핑됩니다.

reasoning_effort를 생략하면 모델의 기본 사고 구성이 사용됩니다.

OpenAI 호환 API에서 사고 구성 매개변수를 직접 제어하려면 extra_body.google.thinking_config를 사용하세요.

Python

import openai
from google.auth import default
import google.auth.transport.requests

# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
# location = "global"

# Programmatically get an access token
credentials, _ = default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
credentials.refresh(google.auth.transport.requests.Request())

# OpenAI Client
client = openai.OpenAI(
  base_url=f"https://aiplatform.googleapis.com/v1/projects/{project_id}/locations/{location}/endpoints/openapi",
  api_key=credentials.token
)

response = client.chat.completions.create(
  model="google/gemini-3.5-flash",
  reasoning_effort="low",
  messages=[
      {"role": "system", "content": "You are a helpful assistant."},
      {
          "role": "user",
          "content": "Explain to me how AI works"
      }
  ]
)
print(response.choices[0].message)

스트리밍

Gemini API는 스트리밍 응답을 지원합니다.

Python

import openai
from google.auth import default
import google.auth.transport.requests

# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
# location = "global"

credentials, _ = default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
credentials.refresh(google.auth.transport.requests.Request())

client = openai.OpenAI(
  base_url=f"https://aiplatform.googleapis.com/v1/projects/{project_id}/locations/{location}/endpoints/openapi",
  api_key=credentials.token
)
response = client.chat.completions.create(
  model="google/gemini-3.5-flash",
  messages=[
    {"role": "system", "content": "You are a helpful assistant."},
    {"role": "user", "content": "Hello!"}
  ],
  stream=True
)

for chunk in response:
  print(chunk.choices[0].delta)

함수 호출

함수 호출을 사용하면 생성형 모델에서 구조화된 데이터 출력을 더 쉽게 가져올 수 있는데, 이는 Gemini API에서 지원됩니다.

Python

import openai
from google.auth import default
import google.auth.transport.requests

# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
# location = "global"

credentials, _ = default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
credentials.refresh(google.auth.transport.requests.Request())

client = openai.OpenAI(
  base_url=f"https://aiplatform.googleapis.com/v1/projects/{project_id}/locations/{location}/endpoints/openapi",
  api_key=credentials.token
)

tools = [
  {
    "type": "function",
    "function": {
      "name": "get_weather",
      "description": "Get the weather in a given location",
      "parameters": {
        "type": "object",
        "properties": {
          "location": {
            "type": "string",
            "description": "The city and state, e.g. Chicago, IL",
          },
          "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]},
        },
        "required": ["location"],
      },
    }
  }
]

messages = [{"role": "user", "content": "What's the weather like in Chicago today?"}]
response = client.chat.completions.create(
  model="google/gemini-3.5-flash",
  messages=messages,
  tools=tools,
  tool_choice="auto"
)

print(response)

이미지 이해

Gemini 모델은 네이티브 멀티모달이며 다양한 일반적인 비전 작업을 지원합니다.

Python

from google.auth import default
import google.auth.transport.requests

import base64
from openai import OpenAI

# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
# location = "global"

# Programmatically get an access token
credentials, _ = default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
credentials.refresh(google.auth.transport.requests.Request())

# OpenAI Client
client = openai.OpenAI(
  base_url=f"https://aiplatform.googleapis.com/v1/projects/{project_id}/locations/{location}/endpoints/openapi",
  api_key=credentials.token,
)

# Function to encode the image
def encode_image(image_path):
  with open(image_path, "rb") as image_file:
    return base64.b64encode(image_file.read()).decode('utf-8')

# Getting the base64 string
# base64_image = encode_image("Path/to/image.jpeg")

response = client.chat.completions.create(
  model="google/gemini-3.5-flash",
  messages=[
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "What is in this image?",
        },
        {
          "type": "image_url",
          "image_url": {
            "url":  f"data:image/jpeg;base64,{base64_image}"
          },
        },
      ],
    }
  ],
)

print(response.choices[0])

이미지 생성

REST

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

요청을 보내려면 다음 옵션 중 하나를 펼칩니다.

다음과 비슷한 JSON 응답이 표시됩니다.

{
  "choices": [{
    "finish_reason": "stop",
    "index": 0,
    "image": {
      "data":"IMAGE_DATA",
      "extra_content": {
        "google": {
          "mime_type":"image/png"
        }
      }
    },
    "content":"Here is an image of a banana: ",
    "role":"assistant"
  }],
  "created":1757099999,
  "id":"sample_response_id",
  "model":"google/gemini-3.1-flash-image",
  "object":"chat.completion",
  "system_fingerprint":"",
  "usage": {
    "completion_tokens":1299,
    "prompt_tokens":7,
    "total_tokens":1306
  }
}

오디오 이해

다음 샘플은 오디오 입력을 분석하는 방법을 보여줍니다.

Python

from google.auth import default
import google.auth.transport.requests

import base64
from openai import OpenAI

# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
# location = "global"

# Programmatically get an access token
credentials, _ = default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
credentials.refresh(google.auth.transport.requests.Request())

# OpenAI Client
client = openai.OpenAI(
  base_url=f"https://aiplatform.googleapis.com/v1/projects/{project_id}/locations/{location}/endpoints/openapi",
  api_key=credentials.token,
)

with open("/path/to/your/audio/file.wav", "rb") as audio_file:
  base64_audio = base64.b64encode(audio_file.read()).decode('utf-8')

response = client.chat.completions.create(
  model="google/gemini-3.5-flash",
  messages=[
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "Transcribe this audio",
        },
        {
              "type": "input_audio",
              "input_audio": {
                "data": base64_audio,
                "format": "wav"
          }
        }
      ],
    }
  ],
)

print(response.choices[0].message.content)

구조화된 출력

Gemini 모델은 내가 정의한 구조로 JSON 객체를 출력할 수 있습니다.

Python

from google.auth import default
import google.auth.transport.requests

from pydantic import BaseModel
from openai import OpenAI

# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
# location = "global"

# Programmatically get an access token
credentials, _ = default(scopes=["https://www.googleapis.com/auth/cloud-platform"])
credentials.refresh(google.auth.transport.requests.Request())

# OpenAI Client
client = openai.OpenAI(
  base_url=f"https://aiplatform.googleapis.com/v1/projects/{project_id}/locations/{location}/endpoints/openapi",
  api_key=credentials.token,
)

class CalendarEvent(BaseModel):
  name: str
  date: str
  participants: list[str]

completion = client.beta.chat.completions.parse(
  model="google/gemini-3.5-flash",
  messages=[
      {"role": "system", "content": "Extract the event information."},
      {"role": "user", "content": "John and Susan are going to an AI conference on Friday."},
  ],
  response_format=CalendarEvent,
)

print(completion.choices[0].message.parsed)

현재 제한사항

OpenAI 호환 API를 사용할 때는 다음 제한사항을 고려하세요.

  • 액세스 토큰은 기본적으로 1시간 동안 유효합니다. 만료 후에는 다시 인증해야 합니다. 자세한 내용은 사용자 인증 정보 새로고침을 참고하세요.

다음 단계