从 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.6-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.6-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"