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 キーを使用して認証します。API キーは Google AI Studio で 作成できます。
変更前
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.text)
JavaScript
import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");
const model = genAI.getGenerativeModel({ model: "gemini-3.5-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.5-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.5-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.5-flash",
contents: [
createUserContent([
"Tell me a story based on this image",
createPartFromUri(organ.uri, organ.mimeType)
]),
],
});
console.log(response.text);
Go
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
imgData, err := os.ReadFile("path/to/organ.jpg")
if err != nil {
log.Fatal(err)
}
parts := []*genai.Part{
{Text: "Tell me a story based on this image"},
{InlineData: &genai.Blob{Data: imgData, MIMEType: "image/jpeg"}},
}
contents := []*genai.Content{
{Parts: parts},
}
result, err := client.Models.GenerateContent(ctx, "gemini-3.5-flash", contents, nil)
if err != nil {
log.Fatal(err)
}
debugPrint(result) // utility for printing result
ストリーミング
変更前
Python
import google.generativeai as genai
response = model.generate_content(
"Write a cute story about cats.",
stream=True)
for chunk in response:
print(chunk.text)
JavaScript
import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");
const model = genAI.getGenerativeModel({ model: "gemini-3.5-flash" });
const prompt = "Write a story about a magic backpack.";
const result = await model.generateContentStream(prompt);
// Print text as it comes in.
for await (const chunk of result.stream) {
const chunkText = chunk.text();
process.stdout.write(chunkText);
}
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")
iter := model.GenerateContentStream(ctx, genai.Text("Write a story about a magic backpack."))
for {
resp, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
log.Fatal(err)
}
printResponse(resp) // utility for printing the response
}
変更後
Python
from google import genai
client = genai.Client()
for chunk in client.models.generate_content_stream(
model='gemini-3.5-flash',
contents='Tell me a story in 300 words.'
):
print(chunk.text)
JavaScript
import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });
const response = await ai.models.generateContentStream({
model: "gemini-3.5-flash",
contents: "Write a story about a magic backpack.",
});
let text