只要更新三行程式碼並使用 Gemini API 金鑰,即可透過 OpenAI 程式庫 (Python 和 TypeScript/JavaScript) 和 REST API 存取 Gemini 模型。如果您尚未採用 OpenAI 程式庫,建議您直接呼叫 Gemini API。
Python
from openai import OpenAI
client = OpenAI(
api_key="GEMINI_API_KEY",
base_url="https://generativelanguage.googleapis.com/v1beta/openai/"
)
response = client.chat.completions.create(
model="gemini-3-flash-preview",
messages=[
{ "role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Explain to me how AI works"
}
]
)
print(response.choices[0].message)
JavaScript
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: "GEMINI_API_KEY",
baseURL: "https://generativelanguage.googleapis.com/v1beta/openai/"
});
const response = await openai.chat.completions.create({
model: "gemini-3-flash-preview",
messages: [
{ role: "system",
content: "You are a helpful assistant."
},
{
role: "user",
content: "Explain to me how AI works",
},
],
});
console.log(response.choices[0].message);
REST
curl "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"messages": [
{
"role": "user",
"content": "Explain to me how AI works"
}
]
}'
異動內容只要三行!
api_key="GEMINI_API_KEY":將「GEMINI_API_KEY」替換為實際的 Gemini API 金鑰,您可以在 Google AI Studio 中取得。base_url="https://generativelanguage.googleapis.com/v1beta/openai/":這會告知 OpenAI 程式庫將要求傳送至 Gemini API 端點,而非預設網址。model="gemini-3-flash-preview":選擇相容的 Gemini 模型
思考中
Gemini 模型經過訓練,能夠思考複雜問題,因此推理能力大幅提升。Gemini API 隨附思考參數,可精細控管模型的思考量。
不同的 Gemini 模型有不同的推理設定,您可以參閱下表,瞭解這些設定如何對應到 OpenAI 的推理工作:
reasoning_effort (OpenAI) |
thinking_level (Gemini 3.1 Pro) |
thinking_level (Gemini 3.1 Flash-Lite) |
thinking_level (Gemini 3 Flash) |
thinking_budget (Gemini 2.5) |
|---|---|---|---|---|
minimal |
low |
minimal |
minimal |
1,024 |
low |
low |
low |
low |
1,024 |
medium |
medium |
medium |
medium |
8,192 |
high |
high |
high |
high |
24,576 |
如未指定 reasoning_effort,Gemini 會使用模型的預設層級或預算。
如要停用思考功能,請將 2.5 模型的 reasoning_effort 設為 "none"。Gemini 2.5 Pro 或 3 模型無法關閉推理功能。
Python
from openai import OpenAI
client = OpenAI(
api_key="GEMINI_API_KEY",
base_url="https://generativelanguage.googleapis.com/v1beta/openai/"
)
response = client.chat.completions.create(
model="gemini-3-flash-preview",
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)
JavaScript
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: "GEMINI_API_KEY",
baseURL: "https://generativelanguage.googleapis.com/v1beta/openai/"
});
const response = await openai.chat.completions.create({
model: "gemini-3-flash-preview",
reasoning_effort: "low",
messages: [
{ role: "system",
content: "You are a helpful assistant."
},
{
role: "user",
content: "Explain to me how AI works",
},
],
});
console.log(response.choices[0].message);
REST
curl "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"reasoning_effort": "low",
"messages": [
{
"role": "user",
"content": "Explain to me how AI works"
}
]
}'
Gemini 思考模型也會產生想法摘要。
您可以使用 extra_body 欄位,在要求中加入 Gemini 欄位。
請注意,reasoning_effort 和 thinking_level/thinking_budget 的功能重疊,因此無法同時使用。
Python
from openai import OpenAI
client = OpenAI(
api_key="GEMINI_API_KEY",
base_url="https://generativelanguage.googleapis.com/v1beta/openai/"
)
response = client.chat.completions.create(
model="gemini-3-flash-preview",
messages=[{"role": "user", "content": "Explain to me how AI works"}],
extra_body={
'extra_body': {
"google": {
"thinking_config": {
"thinking_level": "low",
"include_thoughts": True
}
}
}
}
)
print(response.choices[0].message)
JavaScript
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: "GEMINI_API_KEY",
baseURL: "https://generativelanguage.googleapis.com/v1beta/openai/"
});
const response = await openai.chat.completions.create({
model: "gemini-3-flash-preview",
messages: [{role: "user", content: "Explain to me how AI works",}],
extra_body: {
"google": {
"thinking_config": {
"thinking_level": "low",
"include_thoughts": true
}
}
}
});
console.log(response.choices[0].message);
REST
curl "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"messages": [{"role": "user", "content": "Explain to me how AI works"}],
"extra_body": {
"google": {
"thinking_config": {
"thinking_level": "low",
"include_thoughts": true
}
}
}
}'
Gemini 3 支援 OpenAI 相容性,適用於對話完成 API 中的想法簽章。如需完整範例,請參閱「思想簽章」頁面。
串流
Gemini API 支援串流回應。
Python
from openai import OpenAI
client = OpenAI(
api_key="GEMINI_API_KEY",
base_url="https://generativelanguage.googleapis.com/v1beta/openai/"
)
response = client.chat.completions.create(
model="gemini-3-flash-preview",
messages=[
{
"role": "system",
"content": "You are a helpful assistant."
},
{ "role": "user",
"content": "Hello!"
}
],
stream=True
)
for chunk in response:
print(chunk.choices[0].delta)
JavaScript
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: "GEMINI_API_KEY",
baseURL: "https://generativelanguage.googleapis.com/v1beta/openai/"
});
async function main() {
const completion = await openai.chat.completions.create({
model: "gemini-3-flash-preview",
messages: [
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "Hello!"
}
],
stream: true,
});
for await (const chunk of completion) {
console.log(chunk.choices[0].delta.content);
}
}
main();
REST
curl "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"messages": [
{"role": "user", "content": "Explain to me how AI works"}
],
"stream": true
}'
函式呼叫
透過函式呼叫,您可以更輕鬆地從生成模型取得結構化資料輸出內容,且 Gemini API 支援這項功能。
Python
from openai import OpenAI
client = OpenAI(
api_key="GEMINI_API_KEY",
base_url="https://generativelanguage.googleapis.com/v1beta/openai/"
)
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="gemini-3-flash-preview",
messages=messages,
tools=tools,
tool_choice="auto"
)
print(response)
JavaScript
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: "GEMINI_API_KEY",
baseURL: "https://generativelanguage.googleapis.com/v1beta/openai/"
});
async function main() {
const messages = [{"role": "user", "content": "What's the weather like in Chicago today?"}];
const 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"],
},
}
}
];
const response = await openai.chat.completions.create({
model: "gemini-3-flash-preview",
messages: messages,
tools: tools,
tool_choice: "auto",
});
console.log(response);
}
main();
REST
curl "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer GEMINI_API_KEY" \
-d '{
"model": "gemini-3-flash-preview",
"messages": [
{
"role": "user",
"content": "What'\''s the weather like in Chicago today?"
}
],
"tools": [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the current 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"]
}
}
}
],
"tool_choice": "auto"
}'
圖像解讀
Gemini 模型原生支援多模態資料,在許多常見的視覺工作中,都能提供同級最佳效能。
Python
import base64
from openai import OpenAI
client = OpenAI(
api_key="GEMINI_API_KEY",
base_url="https://generativelanguage.googleapis.com/v1beta/openai/"
)
# 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/agi/image.jpeg")
response = client.chat.completions.create(
model="gemini-3-flash-preview",
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])
JavaScript
import OpenAI from "openai";
import fs from 'fs/promises';
const openai = new OpenAI({
apiKey: "GEMINI_API_KEY",
baseURL: "https://generativelanguage.googleapis.com/v1beta/openai/"
});
async function encodeImage(imagePath) {
try {
const imageBuffer = await fs.readFile(imagePath);
return imageBuffer.toString('base64');
} catch (error) {
console.error("Error encoding image:", error);
return null;
}
}
async function main() {
const imagePath = "Path/to/agi/image.jpeg";
const base64Image = await encodeImage(imagePath);
const messages = [
{
"role": "user",
"content": [
{
"type": "text",
"text": "What is in this image?",
},
{
"type": "image_url",
"image_url": {
"url": `data:image/jpeg;base64,${base64Image}`
},
},
],
}
];
try {
const response = await openai.chat.completions.create({
model: "gemini-3-flash-preview",
messages: messages,
});
console.log(response.choices[0]);
} catch (error) {
console.error("Error calling Gemini API:", error);
}
}
main();
REST
bash -c '
base64_image=$(base64 -i "Path/to/agi/image.jpeg");
curl "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer GEMINI_API_KEY" \
-d "{
\"model\": \"gemini-3-flash-preview\",
\"messages\": [
{
\"role\": \"user\",
\"content\": [
{ \"type\": \"text\", \"text\": \"What is in this image?\" },
{
\"type\": \"image_url\",
\"image_url\": { \"url\": \"data:image/jpeg;base64,${base64_image}\" }
}
]
}
]
}"
'
生成圖片
使用 gemini-2.5-flash-image 或 gemini-3-pro-image-preview 生成圖片。支援的參數包括 prompt、model、n、size 和 response_format。相容性層會自動忽略此處或 extra_body 部分未列出的任何其他參數。
Python
import base64
from openai import OpenAI
from PIL import Image
from io import BytesIO
client = OpenAI(
api_key="GEMINI_API_KEY",
base_url="https://generativelanguage.googleapis.com/v1beta/openai/",
)
response = client.images.generate(
model="gemini-2.5-flash-image",
prompt="a portrait of a sheepadoodle wearing a cape",
response_format='b64_json',
n=1,
)
for image_data in response.data:
image = Image.open(BytesIO(base64.b64decode(image_data.b64_json)))
image.show()
JavaScript
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: "GEMINI_API_KEY",
baseURL: "https://generativelanguage.googleapis.com/v1beta/openai/",
});
async function main() {
const image = await openai.images.generate(
{
model: "gemini-2.5-flash-image",
prompt: "a portrait of a sheepadoodle wearing a cape",
response_format: "b64_json",
n: 1,
}
);
console.log(image.data);
}
main();
REST
curl "https://generativelanguage.googleapis.com/v1beta/openai/images/generations" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer GEMINI_API_KEY" \
-d '{
"model": "gemini-2.5-flash-image",
"prompt": "a portrait of a sheepadoodle wearing a cape",
"response_format": "b64_json",
"n": 1,
}'
生成影片
透過與 Sora 相容的veo-3.1-generate-preview/v1/videos端點生成影片。支援的頂層參數為 prompt 和 model。duration_seconds、image 和 aspect_ratio 等其他參數必須與 extra_body 一併傳遞。如要查看所有可用參數,請參閱「extra_body」一節。
影片生成作業是長時間執行的作業,會傳回作業 ID,您可以輪詢作業是否完成。
Python
from openai import OpenAI
client = OpenAI(
api_key="GEMINI_API_KEY",
base_url="https://generativelanguage.googleapis.com/v1beta/openai/"
)
# Returns a Long Running Operation (status: processing)
response = client.videos.create(
model="veo-3.1-generate-preview",
prompt="A cinematic drone shot of a waterfall",
)
print(f"Operation ID: {response.id}")
print(f"Status: {response.status}")
JavaScript
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: "GEMINI_API_KEY",
baseURL: "https://generativelanguage.googleapis.com/v1beta/openai/"
});
async function main() {
// Returns a Long Running Operation (status: processing)
const response = await openai.videos.create({
model: "veo-3.1-generate-preview",
prompt: "A cinematic drone shot of a waterfall",
});
console.log(`Operation ID: ${response.id}`);
console.log(`Status: ${response.status}`);
}
main();
REST
curl "https://generativelanguage.googleapis.com/v1beta/openai/videos" \
-H "Authorization: Bearer $GEMINI_API_KEY" \
-F "model=veo-3.1-generate-preview" \
-F "prompt=A cinematic drone shot of a waterfall"
查看影片狀態
影片生成作業為非同步。使用 GET /v1/videos/{id} 輪詢狀態,並在完成時擷取最終影片網址:
Python
import time
from openai import OpenAI
client = OpenAI(
api_key="GEMINI_API_KEY",
base_url="https://generativelanguage.googleapis.com/v1beta/openai/"
)
# Poll until video is ready
video_id = response.id # From the create call
while True:
video = client.videos.retrieve(video_id)
if video.status == "completed":
print(f"Video URL: {video.url}")
break
elif video.status == "failed":
print(f"Generation failed: {video.error}")
break
print(f"Status: {video.status}. Waiting...")
time.sleep(10)
JavaScript
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: "GEMINI_API_KEY",
baseURL: "https://generativelanguage.googleapis.com/v1beta/openai/"
});
async function main() {
// Poll until video is ready
const videoId = response.id; // From the create call
while (true) {
const video = await openai.videos.retrieve(videoId);
if (video.status === "completed") {
console.log(`Video URL: ${video.url}`);
break;
} else if (video.status === "failed") {
console.log(`Generation failed: ${video.error}`);
break;
}
console.log(`Status: ${video.status}. Waiting...`);
await new Promise(resolve => setTimeout(resolve, 10000));
}
}
main();
REST
curl "https://generativelanguage.googleapis.com/v1beta/openai/videos/VIDEO_ID" \
-H "Authorization: Bearer $GEMINI_API_KEY"
音訊理解
分析音訊輸入內容:
Python
import base64
from openai import OpenAI
client = OpenAI(
api_key="GEMINI_API_KEY",
base_url="https://generativelanguage.googleapis.com/v1beta/openai/"
)
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="gemini-3-flash-preview",
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)
JavaScript
import fs from "fs";
import OpenAI from "openai";
const client = new OpenAI({
apiKey: "GEMINI_API_KEY",
baseURL: "https://generativelanguage.googleapis.com/v1beta/openai/",
});
const audioFile = fs.readFileSync("/path/to/your/audio/file.wav");
const base64Audio = Buffer.from(audioFile).toString("base64");
async function main() {
const response = await client.chat.completions.create({
model: "gemini-3-flash-preview",
messages: [
{
role: "user",
content: [
{
type: "text",
text: "Transcribe this audio",
},
{
type: "input_audio",
input_audio: {
data: base64Audio,
format: "wav",
},
},
],
},
],
});
console.log(response.choices[0].message.content);
}
main();
REST
bash -c '
base64_audio=$(base64 -i "/path/to/your/audio/file.wav");
curl "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer GEMINI_API_KEY" \
-d "{
\"model\": \"gemini-3-flash-preview\",
\"messages\": [
{
\"role\": \"user\",
\"content\": [
{ \"type\": \"text\", \"text\": \"Transcribe this audio file.\" },
{
\"type\": \"input_audio\",
\"input_audio\": {
\"data\": \"${base64_audio}\",
\"format\": \"wav\"
}
}
]
}
]
}"
'
結構化輸出內容
Gemini 模型可以輸出您定義的任何結構的 JSON 物件。
Python
from pydantic import BaseModel
from openai import OpenAI
client = OpenAI(
api_key="GEMINI_API_KEY",
base_url="https://generativelanguage.googleapis.com/v1beta/openai/"
)
class CalendarEvent(BaseModel):
name: str
date: str
participants: list[str]
completion = client.beta.chat.completions.parse(
model="gemini-3-flash-preview",
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)
JavaScript
import OpenAI from "openai";
import { zodResponseFormat } from "openai/helpers/zod";
import { z } from "zod";
const openai = new OpenAI({
apiKey: "GEMINI_API_KEY",
baseURL: "https://generativelanguage.googleapis.com/v1beta/openai"
});
const CalendarEvent = z.object({
name: z.string(),
date: z.string(),
participants: z.array(z.string()),
});
const completion = await openai.chat.completions.parse({
model: "gemini-3-flash-preview",
messages: [
{ role: "system", content: "Extract the event information." },
{ role: "user", content: "John and Susan are going to an AI conference on Friday" },
],
response_format: zodResponseFormat(CalendarEvent, "event"),
});
const event = completion.choices[0].message.parsed;
console.log(event);
嵌入
文字嵌入可衡量字串的關聯性,並使用 Gemini API 生成。您可以使用 gemini-embedding-2-preview 取得多模態嵌入,或使用 gemini-embedding-001 取得純文字嵌入。
Python
from openai import OpenAI
client = OpenAI(
api_key="GEMINI_API_KEY",
base_url="https://generativelanguage.googleapis.com/v1beta/openai/"
)
response = client.embeddings.create(
input="Your text string goes here",
model="gemini-embedding-2-preview"
)
print(response.data[0].embedding)
JavaScript
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: "GEMINI_API_KEY",
baseURL: "https://generativelanguage.googleapis.com/v1beta/openai/"
});
async function main() {
const embedding = await openai.embeddings.create({
model: "gemini-embedding-2-preview",
input: "Your text string goes here",
});
console.log(embedding);
}
main();
REST
curl "https://generativelanguage.googleapis.com/v1beta/openai/embeddings" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer GEMINI_API_KEY" \
-d '{
"input": "Your text string goes here",
"model": "gemini-embedding-2-preview"
}'
Batch API
您可以使用 OpenAI 程式庫建立批次工作、提交工作,並查看工作狀態。
您需要準備 OpenAI 輸入格式的 JSONL 檔案。例如:
{"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gemini-3-flash-preview", "messages": [{"role": "user", "content": "Tell me a one-sentence joke."}]}}
{"custom_id": "request-2", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gemini-3-flash-preview", "messages": [{"role": "user", "content": "Why is the sky blue?"}]}}
Batch 的 OpenAI 相容性支援建立批次、監控工作狀態,以及查看批次結果。
目前不支援上傳及下載相容性。不過,下列範例會使用 genai 用戶端上傳及下載檔案,與使用 Gemini Batch API 時相同。
Python
from openai import OpenAI
# Regular genai client for uploads & downloads
from google import genai
client = genai.Client()
openai_client = OpenAI(
api_key="GEMINI_API_KEY",
base_url="https://generativelanguage.googleapis.com/v1beta/openai/"
)
# Upload the JSONL file in OpenAI input format, using regular genai SDK
uploaded_file = client.files.upload(
file='my-batch-requests.jsonl',
config=types.UploadFileConfig(display_name='my-batch-requests', mime_type='jsonl')
)
# Create batch
batch = openai_client.batches.create(
input_file_id=batch_input_file_id,
endpoint="/v1/chat/completions",
completion_window="24h"
)
# Wait for batch to finish (up to 24h)
while True:
batch = client.batches.retrieve(batch.id)
if batch.status in ('completed', 'failed', 'cancelled', 'expired'):
break
print(f"Batch not finished. Current state: {batch.status}. Waiting 30 seconds...")
time.sleep(30)
print(f"Batch finished: {batch}")
# Download results in OpenAI output format, using regular genai SDK
file_content = genai_client.files.download(file=batch.output_file_id).decode('utf-8')
# See batch_output JSONL in OpenAI output format
for line in file_content.splitlines():
print(line)
OpenAI SDK 也支援使用 Batch API 生成嵌入內容。如要這麼做,請將 create 方法的 endpoint 欄位換成嵌入端點,並將 JSONL 檔案中的 url 和 model 鍵換成:
# JSONL file using embeddings model and endpoint
# {"custom_id": "request-1", "method": "POST", "url": "/v1/embeddings", "body": {"model": "ggemini-embedding-001", "messages": [{"role": "user", "content": "Tell me a one-sentence joke."}]}}
# {"custom_id": "request-2", "method": "POST", "url": "/v1/embeddings", "body": {"model": "gemini-embedding-001", "messages": [{"role": "user", "content": "Why is the sky blue?"}]}}
# ...
# Create batch step with embeddings endpoint
batch = openai_client.batches.create(
input_file_id=batch_input_file_id,
endpoint="/v1/embeddings",
completion_window="24h"
)
如需完整範例,請參閱 OpenAI 相容性食譜的「批次產生嵌入內容」一節。
使用 extra_body 啟用 Gemini 功能
Gemini 支援多項功能,但 OpenAI 模型不支援,不過可以使用 extra_body 欄位啟用。
| 參數 | 類型 | 端點 | 說明 |
|---|---|---|---|
cached_content |
文字 | 即時通訊 | 對應至 Gemini 的一般內容快取。 |
thinking_config |
物件 | 即時通訊 | 對應於 Gemini 的 ThinkingConfig。 |
aspect_ratio |
文字 | 圖片 | 輸出長寬比 (例如 "16:9"、"1:1"、"9:16")。 |
generation_config |
物件 | 圖片 | Gemini 生成設定物件 (例如 {"responseModalities": ["IMAGE"], "candidateCount": 2})。 |
safety_settings |
清單 | 圖片 | 自訂安全門檻篩選器 (例如 [{"category": "HARM_CATEGORY_HATE_SPEECH", "threshold": "BLOCK_NONE"}])。 |
tools |
清單 | 圖片 | 啟用依據功能 (例如 [{"google_search": {}}])。僅適用於 gemini-3-pro-image-preview。 |
aspect_ratio |
文字 | 影片 | 輸出影片的尺寸 (橫向為 16:9,直向為 9:16)。如果未指定,則會從 size對應。 |
resolution |
文字 | 影片 | 輸出解析度 (720p、1080p、4K)。注意:1080p 和 4K 會觸發升頻管道。 |
duration_seconds |
整數 | 影片 | 生成長度 (值:4、6、8)。使用 reference_images、插補或擴充功能時,必須為 8。 |
frame_rate |
文字 | 影片 | 輸出影片的畫面更新率 (例如 "24")。 |
input_reference |
文字 | 影片 | 用來生成影片的參考輸入內容。 |
extend_video_id |
文字 | 影片 | 要延長的現有影片 ID。 |
negative_prompt |
文字 | 影片 | 要排除的項目 (例如 "shaky camera")。 |
seed |
整數 | 影片 | 用於決定性生成的整數。 |
style |
文字 | 影片 | 視覺樣式 (cinematic 預設,creative 適用於社群媒體)。 |
person_generation |
文字 | 影片 | 控制人物生成 (allow_adult、allow_all、dont_allow)。 |
reference_images |
清單 | 影片 | 最多 3 張風格/角色參考圖片 (base64 素材資源)。 |
image |
文字 | 影片 | Base64 編碼的初始輸入圖片,用於設定影片生成條件。 |
last_frame |
物件 | 影片 | 用於插補的最終圖片 (需要 image 做為第一個影格)。 |
使用 extra_body 的範例
以下範例說明如何使用 extra_body 設定 cached_content:
Python
from openai import OpenAI
client = OpenAI(
api_key=MY_API_KEY,
base_url="https://generativelanguage.googleapis.com/v1beta/"
)
stream = client.chat.completions.create(
model="gemini-3-flash-preview",
n=1,
messages=[
{
"role": "user",
"content": "Summarize the video"
}
],
stream=True,
stream_options={'include_usage': True},
extra_body={
'extra_body':
{
'google': {
'cached_content': "cachedContents/0000aaaa1111bbbb2222cccc3333dddd4444eeee"
}
}
}
)
for chunk in stream:
print(chunk)
print(chunk.usage.to_dict())
列出模型
取得可用 Gemini 模型清單:
Python
from openai import OpenAI
client = OpenAI(
api_key="GEMINI_API_KEY",
base_url="https://generativelanguage.googleapis.com/v1beta/openai/"
)
models = client.models.list()
for model in models:
print(model.id)
JavaScript
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: "GEMINI_API_KEY",
baseURL: "https://generativelanguage.googleapis.com/v1beta/openai/",
});
async function main() {
const list = await openai.models.list();
for await (const model of list) {
console.log(model);
}
}
main();
REST
curl https://generativelanguage.googleapis.com/v1beta/openai/models \
-H "Authorization: Bearer GEMINI_API_KEY"
擷取模型
擷取 Gemini 模型:
Python
from openai import OpenAI
client = OpenAI(
api_key="GEMINI_API_KEY",
base_url="https://generativelanguage.googleapis.com/v1beta/openai/"
)
model = client.models.retrieve("gemini-3-flash-preview")
print(model.id)
JavaScript
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: "GEMINI_API_KEY",
baseURL: "https://generativelanguage.googleapis.com/v1beta/openai/",
});
async function main() {
const model = await openai.models.retrieve("gemini-3-flash-preview");
console.log(model.id);
}
main();
REST
curl https://generativelanguage.googleapis.com/v1beta/openai/models/gemini-3-flash-preview \
-H "Authorization: Bearer GEMINI_API_KEY"
目前限制
我們正在擴大功能支援範圍,因此 OpenAI 程式庫仍處於 Beta 版。
如果您對支援的參數、即將推出的功能有任何疑問,或是在開始使用 Gemini 時遇到任何問題,請加入我們的開發人員論壇。
後續步驟
如需更詳細的範例,請試用 OpenAI 相容性 Colab。