Google 會運用 AI 技術將內容翻譯成你偏好的語言,但可能會出錯。
從 OpenAI SDK 遷移至 Google Gen AI SDK
本頁面說明如何將為 OpenAI SDK 設計的程式碼遷移至 Google Gen AI SDK,以便在 Gemini Enterprise Agent Platform 上使用 Gemini 模型。
遷移總覽
下列筆記本示範如何從 openai 程式庫實際遷移至 google-genai 程式庫:
API 和語法對應
下表比較 OpenAI SDK 與 Google Gen AI SDK 的核心元件、方法和參數。
| 功能 |
OpenAI SDK (openai) |
Google Gen AI SDK (google-genai) |
| 用戶端初始化 |
client = OpenAI(api_key=...) |
client = genai.Client(vertexai=True, ...) |
| 生成方法 |
client.chat.completions.create |
client.models.generate_content |
| 串流方法 |
stream=True (參數) |
client.models.generate_content_stream (方法) |
| 使用者輸入內容 |
messages=[{"role": "user", "content": "..."}] |
contents="..." (字串) 或 contents=[...] (清單) |
| 系統指令 |
messages=[{"role": "system", "content": "..."}] |
config=types.GenerateContentConfig(system_instruction=...) |
| 回應存取權 |
response.choices[0].message.content |
response.text |
| 即時通訊記錄 |
手動管理清單 (messages.append) |
client.chats.create() (有狀態的物件) |
| 詞元數上限 |
max_tokens |
max_output_tokens (位於 config) |
| 溫度參數 (temperature) |
temperature |
temperature (位於 config) |
| JSON 模式 |
response_format={"type": "json_object"} |
response_mime_type="application/json" (位於 config) |
安裝和設定
解除安裝 OpenAI 程式庫,然後安裝 Google Gen AI SDK。
pip install google-genai
2. 驗證與初始化
OpenAI 使用 API 金鑰,但 Agent Platform 使用 Identity and Access Management (IAM) 憑證 (應用程式預設憑證)。您必須明確定義專案 ID 和位置。
| OpenAI SDK |
Google Gen AI SDK |
from openai import OpenAI
import os
# Relies on OPENAI_API_KEY environment variable
client = OpenAI()
|
from google import genai
# Use vertexai=True to use Agent Platform
client = genai.Client(
vertexai=True,
project='your-project-id',
location='us-central1'
)
|
提示:您也可以設定環境變數來初始化用戶端,不必使用引數,類似於 OpenAI 用戶端從環境讀取 API 金鑰的方式。
設定 GOOGLE_GENAI_USE_ENTERPRISE、GOOGLE_CLOUD_PROJECT 和 GOOGLE_CLOUD_LOCATION,如下所示:
export GOOGLE_GENAI_USE_ENTERPRISE=true
export GOOGLE_CLOUD_PROJECT='your-project-id'
export GOOGLE_CLOUD_LOCATION='global'
設定完成後,您就可以初始化用戶端,不必傳遞參數:
from google import genai
client = genai.Client()
程式碼範例
下列程式碼範例顯示常見工作在 OpenAI SDK 和 Google Gen AI SDK 之間的差異。
單輪文字生成
下列程式碼範例說明如何生成文字。請注意,在 Google Gen AI SDK 中,系統指令會做為設定參數處理,而非輸入清單中的訊息角色。
| OpenAI SDK |
Google Gen AI SDK |
response = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Explain quantum physics."}
]
)
print(response.choices[0].message.content)
|
from google.genai import types
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="Explain quantum physics.",
config=types.GenerateContentConfig(
system_instruction="You are a helpful assistant."
)
)
print(response.text)
|
使用參數生成文字
下列程式碼範例顯示定義設定參數時的差異。在 Google Gen AI SDK 中,temperature、max_output_tokens (先前為 max_tokens) 和 JSON 格式等參數會分組到 GenerateContentConfig 物件中。
| OpenAI SDK |
Google Gen AI SDK |
response = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "user", "content": "List 3 types of apples in JSON."}
],
temperature=0.7,
max_tokens=1000,
response_format={"type": "json_object"}
)
print(response.choices[0].message.content)
|
from google.genai import types
config = types.GenerateContentConfig(
temperature=0.7,
max_output_tokens=1000,
response_mime_type="application/json"
)
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="List 3 types of apples in JSON.",
config=config
)
print(response.text)
|
對話 (多輪)
下列程式碼範例顯示管理對話記錄的差異。Google Gen AI SDK 提供具狀態的 chat 物件,可簡化這項程序,而 OpenAI 則需要手動將訊息附加至清單。
| OpenAI SDK |
Google Gen AI SDK |
# You must manually manage the list state
messages = [{"role": "user", "content": "Hi"}]
response = client.chat.completions.create(
model="gpt-4",
messages=messages
)
# Append the response to history manually
messages.append(response.choices[0].message)
messages.append({"role": "user", "content": "Next question"})
response2 = client.chat.completions.create(
model="gpt-4",
messages=messages
)
print(response2.choices[0].message.content)
|
# The SDK manages history for you
chat = client.chats.create(
model="gemini-2.5-flash",
config=types.GenerateContentConfig(
system_instruction="You are a helpful assistant."
)
)
response1 = chat.send_message("Hi")
print(response1.text)
# History is retained automatically in the chat object
response2 = chat.send_message("Next question")
print(response2.text)
|
串流
下列程式碼範例顯示串流回應的差異。Google Gen AI SDK 使用特定方法 (generate_content_stream),而非布林值旗標。
| OpenAI SDK |
Google Gen AI SDK |
stream = client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": "Write a story."}],
stream=True
)
for chunk in stream:
if chunk.choices[0].delta.content:
print(chunk.choices[0].delta.content, end="")
|
stream = client.models.generate_content_stream(
model="gemini-2.5-flash",
contents="Write a story."
)
for chunk in stream:
print(chunk.text, end="")
|
後續步驟
除非另有註明,否則本頁面中的內容是採用創用 CC 姓名標示 4.0 授權,程式碼範例則為阿帕契 2.0 授權。詳情請參閱《Google Developers 網站政策》。Java 是 Oracle 和/或其關聯企業的註冊商標。
上次更新時間:2026-10-15 (世界標準時間)。
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2026-10-15 (世界標準時間)。"],[],[]]