אפשר לגשת למודלים של Gemini באמצעות ספריות OpenAI (Python ו-TypeScript / Javascript) וגם באמצעות API בארכיטקטורת REST. רק Google Cloud אימות נתמך באמצעות ספריית OpenAI ב-Gemini Enterprise Agent Platform. אם אתם לא משתמשים כבר בספריות OpenAI, מומלץ לקרוא ל-Gemini API ישירות. אם אתם משתמשים בספריות OpenAI ורוצים לעבור ל-Agent Platform SDKs, תוכלו לעיין במאמר מעבר מ-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)
מה השתנה?
api_key=credentials.token: כדי להשתמש באימות Google Cloud , צריך לקבל אסימון אימותGoogle Cloud באמצעות קוד לדוגמה.
base_url: הפרמטר הזה מציין לספריית OpenAI לשלוח בקשות אל Google Cloudבמקום אל כתובת ה-URL שמוגדרת כברירת מחדל.
model="google/gemini-3.5-flash": בוחרים מודל Gemini תואם מבין המודלים שמארח Vertex.
מעמיק
מודלים של Gemini 2.5 מאומנים לחשוב על פתרון בעיות מורכבות, ולכן הם מסוגלים להסיק מסקנות ברמה גבוהה יותר. ל-Gemini API יש פרמטר של 'תקציב חשיבה' שמאפשר שליטה מדויקת במידת החשיבה של המודל.
בניגוד ל-Gemini API, OpenAI API מציע שלוש רמות של שליטה בתהליך החשיבה: 'נמוכה', 'בינונית' ו'גבוהה'. הרמות האלה ממופות מאחורי הקלעים לתקציבי אסימוני חשיבה של 1K, 8K ו-24K.
אם לא מציינים את מאמץ החשיבה הרציונלית בכלל, זה שווה ערך לאי-ציון של תקציב חשיבה.
כדי לקבל שליטה ישירה יותר בתקציבי החשיבה ובהגדרות אחרות שקשורות לחשיבה מ-API שתואם ל-OpenAI, אפשר להשתמש ב-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: [מזהה הפרויקט](/resource-manager/docs/creating-managing-projects#identifiers). .
כדי לשלוח את הבקשה צריך להרחיב אחת מהאפשרויות הבאות:
אתם אמורים לקבל תגובת 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-2.5-flash-image-preview",
"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)
מגבלות נוכחיות
- משך החיים של אסימוני גישה הוא שעה אחת כברירת מחדל. אחרי שהתוקף שלהם פג, צריך לרענן אותם. מידע נוסף זמין בדוגמת הקוד הזו.
המאמרים הבאים
כדי לממש את הפוטנציאל של Gemini, אפשר להשתמש בספריות של Google Gen AI.
דוגמאות נוספות לשימוש ב-Chat Completions API עם תחביר שתואם ל-OpenAI
אפשר לראות אילו מודלים ופרמטרים של Gemini נתמכים בדף הסקירה הכללית.