您可以使用 OpenAI 程式庫 (Python、TypeScript 和 JavaScript) 和 REST API 存取 Gemini 模型。在 Gemini Enterprise Agent Platform 中,使用 OpenAI 程式庫時,僅支援 Google Cloud Auth。如果您尚未開始使用 OpenAI 程式庫,請直接呼叫 Gemini API。如果您使用 OpenAI 程式庫,並想遷移至 Agent Platform SDK,請參閱「從 OpenAI SDK 遷移至 Google Gen 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 程式庫將要求傳送至與 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
使用任何要求資料之前,請先修改下列項目的值:
- PROJECT_ID: 您的專案 ID。 。
請展開以下其中一個選項,以傳送要求:
您應該會收到如下的 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 小時。過期後必須重新整理。詳情請參閱「重新整理憑證」。
後續步驟
使用 Google 生成式 AI 程式庫直接呼叫 Gemini 模型。
如要查看更多使用 Chat Completions API 的範例,請參閱 OpenAI 相容語法。
如要查看支援的 Gemini 模型和參數,請參閱「搭配 Agent Platform 使用 OpenAI 程式庫」。