遷移至 Google GenAI SDK

自 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 服務 (例如 modelschatsfilestunings) 的單一進入點,有助於提升一致性,並簡化不同 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"))
fileClient, err := fileman.NewClient(ctx, option.WithAPIKey("GEMINI_API_KEY"))

// Get a model instance, then call methods on it
model := client.GenerativeModel("gemini-3.6-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.6-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.6-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.6-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 和 live-api session),這些都是無狀態函式。為求實用性和一致性,傳回的物件是 pydantic 類別。

from google import genai
client = genai.Client()

response = client.models.generate_content(
    model='gemini-3.6-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.6-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.6-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.6-flash')
response = model.generate_content([
    'Tell me a story based on this image',
    Image.open(image_path)
])
print(response.text)

JavaScript

import { GoogleGenerativeAI } from "@google/generative-ai";

const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");
const model = genAI.getGenerativeModel({ model: "gemini-3.6-flash" });

function fileToGenerativePart(path, mimeType) {
  return {
    inlineData: {
      data: Buffer.from(fs.readFileSync(path)).toString("base64"),
      mimeType,
    },
  };
}

const prompt = "Tell me a story based on this image";

const imagePart = fileToGenerativePart(
  `path/to/organ.jpg`,
  "image/jpeg",
);

const result = await model.generateContent([prompt, imagePart]);
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.6-flash")

imgData, err := os.ReadFile("path/to/organ.jpg")
if err != nil {
    log.Fatal(err)
}

resp, err := model.GenerateContent(ctx,
    genai.Text("Tell me about this instrument"),
    genai.ImageData("jpeg", imgData))
if err != nil {
    log.Fatal(err)
}

printResponse(resp) // utility for printing response

變更後

Python

新版 SDK 包含許多相同的便利功能。舉例來說,PIL.Image 物件會自動轉換。

from google import genai
from PIL import Image

client = genai.Client()

response = client.models.generate_content(
    model='gemini-3.6-flash',
    contents=[
        'Tell me a story based on this image',
        Image.open(image_path)
    ]
)
print(response.text)

JavaScript

import {GoogleGenAI} from '@google/genai';

const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });

const organ = await ai.files.upload({
  file: "path/to/organ.jpg",
});

const response = await ai.models.generateContent({
  model: "gemini-3.6-flash",
  contents: [
    createUserContent([
      "Tell me a story based on this image",
      createPartFromUri(organ.uri, organ.mimeType)
    ]),
  ],
});
console.log(response.text);

Go