I modelli Gemini sono accessibili utilizzando le librerie OpenAI (Python e TypeScript/JavaScript) insieme all'API REST, aggiornando tre righe di codice e utilizzando la tua chiave API Gemini. Se non utilizzi già le librerie OpenAI, ti consigliamo di chiamare direttamente l'API Gemini.
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-2.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)
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-2.0-flash",
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-2.0-flash",
"messages": [
{"role": "user", "content": "Explain to me how AI works"}
]
}'
Che cosa è cambiato? Solo tre righe.
api_key="GEMINI_API_KEY": sostituisci "GEMINI_API_KEY" con la tua chiave API Gemini effettiva, che puoi ottenere in Google AI Studio.base_url="https://generativelanguage.googleapis.com/v1beta/openai/": questo indica alla libreria OpenAI di inviare richieste all'endpoint dell'API Gemini anziché all'URL predefinito.model="gemini-2.5-flash": scegli un modello Gemini compatibile
Pensiero
I modelli Gemini 3 e 2.5 sono addestrati a risolvere problemi complessi, il che porta a un ragionamento notevolmente migliorato. L'API Gemini è dotata di parametri di pensiero che consentono di controllare con precisione quanto il modello penserà.
Gemini 3 utilizza i livelli di pensiero "low" e "high", mentre i modelli Gemini 2.5 utilizzano
budget di pensiero esatti. Questi corrispondono agli sforzi di ragionamento di OpenAI come segue:
reasoning_effort (OpenAI) |
thinking_level (Gemini 3) |
thinking_budget (Gemini 2.5) |
|---|---|---|
minimal |
low |
1,024 |
low |
low |
1,024 |
medium |
high |
8,192 |
high |
high |
24,576 |
Se non viene specificato alcun reasoning_effort, Gemini utilizza il livello o il budget predefinito del modello.
Se vuoi disattivare il pensiero, puoi impostare reasoning_effort su "none" per i modelli 2.5. Il ragionamento non può essere disattivato per i modelli Gemini 2.5 Pro o 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-2.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)
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-2.5-flash",
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-2.5-flash",
"reasoning_effort": "low",
"messages": [
{"role": "user", "content": "Explain to me how AI works"}
]
}'
I modelli di pensiero Gemini producono anche riepiloghi dei pensieri.
Puoi utilizzare il campo extra_body per includere i campi Gemini
nella tua richiesta.
Tieni presente che le funzionalità di reasoning_effort e thinking_level/thinking_budget si sovrappongono, pertanto non possono essere utilizzate contemporaneamente.
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-2.5-flash",
messages=[{"role": "user", "content": "Explain to me how AI works"}],
extra_body={
'extra_body': {
"google": {
"thinking_config": {
"thinking_budget": "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-2.5-flash",
messages: [{role: "user", content: "Explain to me how AI works",}],
extra_body: {
"google": {
"thinking_config": {
"thinking_budget": "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-2.5-flash",
"messages": [{"role": "user", "content": "Explain to me how AI works"}],
"extra_body": {
"google": {
"thinking_config": {
"include_thoughts": true
}
}
}
}'
Gemini 3 supporta la compatibilità con OpenAI per le firme di pensiero nelle API di completamento della chat. Puoi trovare l'esempio completo nella pagina Firme dei pensieri.
Streaming
L'API Gemini supporta le risposte in streaming.
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-2.0-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)
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-2.0-flash",
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-2.0-flash",
"messages": [
{"role": "user", "content": "Explain to me how AI works"}
],
"stream": true
}'
Chiamata di funzione
La chiamata di funzioni semplifica l'ottenimento di output di dati strutturati da modelli generativi ed è supportata nell'API Gemini.
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-2.0-flash",
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-2.0-flash",
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-2.0-flash",
"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"
}'
Comprensione delle immagini
I modelli Gemini sono nativamente multimodali e offrono prestazioni di prima classe in molte attività di visione comuni.
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-2.0-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])
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-2.0-flash",
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-2.0-flash\",
\"messages\": [
{
\"role\": \"user\",
\"content\": [
{ \"type\": \"text\", \"text\": \"What is in this image?\" },
{
\"type\": \"image_url\",
\"image_url\": { \"url\": \"data:image/jpeg;base64,${base64_image}\" }
}
]
}
]
}"
'
Genera un'immagine
Genera un'immagine:
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="imagen-3.0-generate-002",
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: "imagen-3.0-generate-002",
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": "imagen-3.0-generate-002",
"prompt": "a portrait of a sheepadoodle wearing a cape",
"response_format": "b64_json",
"n": 1,
}'
Comprensione dell'audio
Analizza l'input audio:
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-2.0-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)
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-2.0-flash",
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-2.0-flash\",
\"messages\": [
{
\"role\": \"user\",
\"content\": [
{ \"type\": \"text\", \"text\": \"Transcribe this audio file.\" },
{
\"type\": \"input_audio\",
\"input_audio\": {
\"data\": \"${base64_audio}\",
\"format\": \"wav\"
}
}
]
}
]
}"
'
Output strutturato
I modelli Gemini possono generare oggetti JSON in qualsiasi struttura definita.
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-2.0-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)
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-2.0-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: zodResponseFormat(CalendarEvent, "event"),
});
const event = completion.choices[0].message.parsed;
console.log(event);
Incorporamenti
Gli embedding di testo misurano la correlazione tra stringhe di testo e possono essere generati utilizzando l'API Gemini.
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-001"
)
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-001",
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-001"
}'
API Batch
Puoi creare job batch, inviarli e controllarne lo stato utilizzando la libreria OpenAI.
Dovrai preparare il file JSONL nel formato di input di OpenAI. Ad esempio:
{"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gemini-2.5-flash", "messages": [{"role": "user", "content": "Tell me a one-sentence joke."}]}}
{"custom_id": "request-2", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gemini-2.5-flash", "messages": [{"role": "user", "content": "Why is the sky blue?"}]}}
La compatibilità di OpenAI per Batch supporta la creazione di un batch, il monitoraggio dello stato del job e la visualizzazione dei risultati del batch.
La compatibilità per il caricamento e il download non è attualmente supportata. L'esempio seguente utilizza invece il client genai per caricare e scaricare file, come quando si utilizza l'API Batch di Gemini.
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)
L'SDK OpenAI supporta anche la generazione di incorporamenti con l'API Batch. Per farlo, sostituisci il campo endpoint del metodo create con un endpoint di incorporamento, nonché le chiavi url e model nel file JSONL:
# 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"
)
Per un esempio completo, consulta la sezione Generazione di incorporamenti batch del ricettario di compatibilità di OpenAI.
extra_body
Esistono diverse funzionalità supportate da Gemini che non sono disponibili nei modelli OpenAI, ma che possono essere attivate utilizzando il campo extra_body.
Funzionalità di extra_body
cached_content |
Corrisponde a GenerateContentRequest.cached_content di Gemini. |
thinking_config |
Corrisponde a ThinkingConfig di Gemini. |
cached_content
Ecco un esempio di utilizzo di extra_body per impostare 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-2.5-pro",
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())
Elenco modelli
Per ottenere un elenco dei modelli Gemini disponibili:
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"
Recuperare un modello
Recupera un modello 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-2.0-flash")
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-2.0-flash");
console.log(model.id);
}
main();
REST
curl https://generativelanguage.googleapis.com/v1beta/openai/models/gemini-2.0-flash \
-H "Authorization: Bearer GEMINI_API_KEY"
Limitazioni attuali
Il supporto delle librerie OpenAI è ancora in versione beta mentre estendiamo il supporto delle funzionalità.
Se hai domande sui parametri supportati, sulle funzionalità future o se riscontri problemi durante l'utilizzo di Gemini, partecipa al nostro forum per sviluppatori.
Passaggi successivi
Prova il nostro OpenAI Compatibility Colab per esaminare esempi più dettagliati.