Os modelos do Gemini podem ser acessados usando as bibliotecas da OpenAI (Python, TypeScript e JavaScript) e a API REST. Somente a autenticação Google Cloud é compatível com a biblioteca da OpenAI na Gemini Enterprise Agent Platform. Se você ainda não usa as bibliotecas da OpenAI, chame a API Gemini diretamente. Se você estiver usando bibliotecas da OpenAI e quiser migrar para SDKs da plataforma de agentes, consulte Migrar do SDK da OpenAI para o SDK de IA generativa do Google.
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)
Observe as seguintes diferenças em relação à configuração padrão do cliente da OpenAI:
api_key=credentials.token: usa um token de acesso OAuth obtido com as Google Cloud Application Default Credentials.base_url: direciona a biblioteca da OpenAI para enviar solicitações ao endpoint compatível com a OpenAI da plataforma de agente em vez do URL padrão.model="google/gemini-3.5-flash": seleciona um modelo do Gemini compatível hospedado na Agent Platform.
Pensando
Os modelos do Gemini 3 geram um processo de raciocínio interno antes de retornar uma resposta, melhorando o desempenho em tarefas complexas de várias etapas. Na API Gemini, o parâmetro thinking_level controla a profundidade do raciocínio em níveis discretos (MINIMAL, LOW, MEDIUM e HIGH).
Na API Chat Completions compatível com a OpenAI, você controla a profundidade do raciocínio com o parâmetro reasoning_effort ("minimal", "low", "medium" ou "high"), que é mapeado para a configuração thinking_level correspondente dos modelos do Gemini 3.
Se você omitir reasoning_effort, a configuração de raciocínio padrão do modelo será usada.
Para ter controle direto sobre os parâmetros de configuração de pensamento da
API compatível com a OpenAI, use
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)
Streaming
A API Gemini oferece suporte a respostas de streaming.
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)
Chamadas de função
A chamada de função facilita a obtenção de saídas de dados estruturados de modelos generativos e é compatível com a API Gemini.
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)
Compreensão de imagens
Os modelos do Gemini são multimodais por natureza e oferecem suporte a muitas tarefas comuns de visão.
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])
Gerar uma imagem
REST
Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:
- PROJECT_ID: o ID do projeto. .
Para enviar a solicitação, expanda uma destas opções:
Você receberá uma resposta JSON semelhante a esta:
{
"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
}
}
Compreensão de áudio
O exemplo a seguir mostra como analisar a entrada de áudio:
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)
Resposta estruturada
Os modelos do Gemini podem gerar objetos JSON em qualquer estrutura que você definir.
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)
Limitações atuais
Considere a seguinte limitação ao usar a API compatível com a OpenAI:
- Por padrão, os tokens de acesso duram 1 hora. Depois da expiração, eles precisam ser atualizados. Para mais informações, consulte Atualizar suas credenciais.
A seguir
Use as bibliotecas de IA generativa do Google para chamar os modelos do Gemini diretamente.
Confira mais exemplos usando a API Chat Completions com a sintaxe compatível com OpenAI.
Consulte os modelos e parâmetros do Gemini compatíveis em Usar bibliotecas da OpenAI com a Agent Platform.