從 OpenAI SDK 遷移至 Gen AI SDK

本頁面說明如何將為 OpenAI SDK 設計的程式碼遷移至 Google Gen AI SDK,以便在 Vertex AI 上使用 Gemini 模型。

遷移總覽

下列筆記本示範如何從 openai 程式庫實際遷移至 google-genai 程式庫:

API 和語法對應

下表比較 OpenAI SDK 與 Gen AI SDK 的核心元件、方法和參數。

功能 OpenAI SDK (openai) 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 程式庫,然後安裝 Gen AI SDK。

pip install google-genai

2. 驗證與初始化

OpenAI 使用 API 金鑰,而 Vertex AI 則使用 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 the Vertex AI platform
client = genai.Client(
    vertexai=True,
    project='your-project-id',
    location='us-central1'
)
        
提示:您也可以設定環境變數來初始化用戶端,不必使用引數,類似於 OpenAI 用戶端從環境讀取 API 金鑰的方式。

設定 GOOGLE_GENAI_USE_VERTEXAIGOOGLE_CLOUD_PROJECTGOOGLE_CLOUD_LOCATION,如下所示:

export GOOGLE_GENAI_USE_VERTEXAI=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 中,temperaturemax_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)
        

Chat (多輪)

下列程式碼範例顯示管理對話記錄的差異。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="")
        

後續步驟