自 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.