Google 会使用 AI 技术将内容翻译成您偏好的语言。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(在 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)
|
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="")
|
后续步骤
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
最后更新时间 (UTC):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"]],["最后更新时间 (UTC):2026-10-15。"],[],[]]