从 2024 年末发布的 Gemini 2.0 开始,我们推出了一组名为 Google GenAI SDK 的新库。它通过更新的客户端架构提供改进的开发者体验,并简化开发者工作流程与企业工作流程之间的过渡。
Google GenAI SDK 现已在所有受支持的平台上正式发布 (GA)。如果您使用的是我们的某个旧版库,我们强烈建议您进行迁移。
本指南提供了迁移前后的代码示例,可帮助您入门。
安装
之前
Python
pip install -U -q "google-generativeai"
JavaScript
npm install @google/generative-ai
Go
go get github.com/google/generative-ai-go
之后
Python
pip install -U -q "google-genai"
JavaScript
npm install @google/genai
Go
go get google.golang.org/genai
API 访问权限
旧版 SDK 使用各种临时方法在后台隐式处理 API 客户端。这使得管理客户端和凭据变得困难。
现在,您可以通过中央 Client 对象进行互动。此 Client 对象充当各种 API 服务(例如 models、chats、files、tunings)的单一入口点,有助于在不同的 API 调用中保持一致性,并简化凭据和配置管理。
之前(API 访问权限不太集中)
Python
旧版 SDK 未明确使用顶级客户端对象来处理大多数 API 调用。您将直接实例化 GenerativeModel 对象并与之交互。
import google.generativeai as genai
# Directly create and use model objects
model = genai.GenerativeModel('gemini-3.5-flash')
response = model.generate_content(...)
chat = model.start_chat(...)
JavaScript
虽然 GoogleGenerativeAI 是模型和聊天功能的中心点,但文件和缓存管理等其他功能通常需要导入和实例化完全独立的客户端类。
import { GoogleGenerativeAI } from "@google/generative-ai";
import { GoogleAIFileManager, GoogleAICacheManager } from "@google/generative-ai/server"; // For files/caching
const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");
const fileManager = new GoogleAIFileManager("GEMINI_API_KEY");
const cacheManager = new GoogleAICacheManager("GEMINI_API_KEY");
// Get a model instance, then call methods on it
const model = genAI.getGenerativeModel({ model: "gemini-3.5-flash" });
const result = await model.generateContent(...);
const chat = model.startChat(...);
// Call methods on separate client objects for other services
const uploadedFile = await fileManager.uploadFile(...);
const cache = await cacheManager.create(...);
Go
genai.NewClient 函数创建了一个客户端,但生成模型操作通常是在从该客户端获取的单独 GenerativeModel 实例上调用的。其他服务可能通过不同的软件包或模式进行访问。
import (
"github.com/google/generative-ai-go/genai"
"github.com/google/generative-ai-go/genai/fileman" // For files
"google.golang.org/api/option"
)
client, err := genai.NewClient(ctx, option.WithAPIKey("GEMINI_API_KEY"))
fileClient, err := fileman.NewClient(ctx, option.WithAPIKey("GEMINI_API_KEY"))
// Get a model instance, then call methods on it
model := client.GenerativeModel("gemini-3.5-flash")
resp, err := model.GenerateContent(...)
cs := model.StartChat()
// Call methods on separate client objects for other services
uploadedFile, err := fileClient.UploadFile(...)
之后(集中式客户端对象)
Python
from google import genai
# Create a single client object
client = genai.Client()
# Access API methods through services on the client object
response = client.models.generate_content(...)
chat = client.chats.create(...)
my_file = client.files.upload(...)
tuning_job = client.tunings.tune(...)
JavaScript
import { GoogleGenAI } from "@google/genai";
// Create a single client object
const ai = new GoogleGenAI({apiKey: "GEMINI_API_KEY"});
// Access API methods through services on the client object
const response = await ai.models.generateContent(...);
const chat = ai.chats.create(...);
const uploadedFile = await ai.files.upload(...);
const cache = await ai.caches.create(...);
Go
import "google.golang.org/genai"
// Create a single client object
client, err := genai.NewClient(ctx, nil)
// Access API methods through services on the client object
result, err := client.Models.GenerateContent(...)
chat, err := client.Chats.Create(...)
uploadedFile, err := client.Files.Upload(...)
tuningJob, err := client.Tunings.Tune(...)
身份验证
旧版库和新版库均使用 API 密钥进行身份验证。您可以在 Google AI Studio 中创建 API 密钥。
之前
Python
旧版 SDK 会隐式处理 API 客户端对象。
import google.generativeai as genai
genai.configure(api_key=...)
JavaScript
import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");
Go
导入 Google 库:
import (
"github.com/google/generative-ai-go/genai"
"google.golang.org/api/option"
)
创建客户端:
client, err := genai.NewClient(ctx, option.WithAPIKey("GEMINI_API_KEY"))
之后
Python
借助 Google GenAI SDK,您可以先创建一个 API 客户端,然后使用该客户端调用 API。
如果您未向客户端传递 API 密钥,新 SDK 将从 GEMINI_API_KEY 环境变量中获取您的 API 密钥。
export GEMINI_API_KEY="YOUR_API_KEY"
from google import genai
client = genai.Client() # Set the API key using the GEMINI_API_KEY env var.
# Alternatively, you could set the API key explicitly:
# client = genai.Client(api_key="YOUR_API_KEY")
JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({apiKey: "GEMINI_API_KEY"});
Go
导入 GenAI 库:
import "google.golang.org/genai"
创建客户端:
client, err := genai.NewClient(ctx, &genai.ClientConfig{
Backend: genai.BackendGeminiAPI,
})
生成内容
文字
之前
Python
之前,没有客户端对象,您可以通过 GenerativeModel 对象直接访问 API。
import google.generativeai as genai
model = genai.GenerativeModel('gemini-3.5-flash')
response = model.generate_content(
'Tell me a story in 300 words'
)
print(response.text)
JavaScript
import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-3.5-flash" });
const prompt = "Tell me a story in 300 words";
const result = await model.generateContent(prompt);
console.log(result.response.text());
Go
ctx := context.Background()
client, err := genai.NewClient(ctx, option.WithAPIKey("GEMINI_API_KEY"))
if err != nil {
log.Fatal(err)
}
defer client.Close()
model := client.GenerativeModel("gemini-3.5-flash")
resp, err := model.GenerateContent(ctx, genai.Text("Tell me a story in 300 words."))
if err != nil {
log.Fatal(err)
}
printResponse(resp) // utility for printing response parts
之后
Python
新的 Google GenAI SDK 通过 Client 对象提供对所有 API 方法的访问权限。除了少数有状态的特殊情况(chat 和实时 API session),这些都是无状态函数。为了实用性和一致性,返回的对象是 pydantic 类。
from google import genai
client = genai.Client()
response = client.models.generate_content(
model='gemini-3.5-flash',
contents='Tell me a story in 300 words.'
)
print(response.text)
print(response.model_dump_json(
exclude_none=True, indent=4))
JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });
const response = await ai.models.generateContent({
model: "gemini-3.5-flash",
contents: "Tell me a story in 300 words.",
});
console.log(response.text);
Go
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
result, err := client.Models.GenerateContent(ctx, "gemini-3.5-flash", genai.Text("Tell me a story in 300 words."), nil)
if err != nil {
log.Fatal(err)
}
debugPrint(result) // utility for printing result
图片
之前
Python
import google.generativeai as genai
model = genai.GenerativeModel('gemini-3.5-flash')
response = model.generate_content([
'Tell me a story based on this image',
Image.open(image_path)
])
print(response.