ย้ายข้อมูลไปยัง Google GenAI SDK

เราได้เปิดตัวชุดไลบรารีใหม่ที่เรียกว่า Google GenAI SDK ตั้งแต่การเปิดตัว Gemini 2.0 ในช่วงปลายปี 2024 ซึ่งมีประสบการณ์การใช้งานที่ดียิ่งขึ้นสำหรับนักพัฒนาแอปผ่าน สถาปัตยกรรมไคลเอ็นต์ที่อัปเดต และ ช่วยลดความซับซ้อนในการเปลี่ยนผ่านระหว่างเวิร์กโฟลว์ของนักพัฒนาแอป และองค์กร

ตอนนี้ 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 สร้างไคลเอ็นต์ แต่โดยทั่วไปแล้วการดำเนินการกับโมเดล Generative จะเรียกใช้ในอินสแตนซ์ 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 SDK ใหม่จะดึงคีย์ API จากตัวแปรสภาพแวดล้อม GEMINI_API_KEY หากคุณไม่ได้ส่งคีย์ไปยังไคลเอ็นต์

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

ก่อนหน้านี้ไม่มีออบเจ็กต์ไคลเอ็นต์ คุณเข้าถึง API ผ่านออบเจ็กต์ GenerativeModel โดยตรง

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 ใหม่ให้สิทธิ์เข้าถึงเมธอด API ทั้งหมดผ่านออบเจ็กต์ Client ยกเว้นกรณีพิเศษที่เก็บสถานะ (chat และ session ของ Live API) ฟังก์ชันเหล่านี้ทั้งหมดเป็นฟังก์ชันที่ไม่เก็บสถานะ ออบเจ็กต์ที่แสดงผลจะเป็นคลาส 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 ใหม่มีฟีเจอร์อำนวยความสะดวกมากมายเช่นเดียวกับ 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 = "";
for await (const chunk of response) {
  console.log(chunk.text);
  text += chunk.text;
}

Go

ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
    log.Fatal(err)
}

for result, err := range client.Models.GenerateContentStream(
    ctx,
    "gemini-3.5-flash",
    genai.Text("Write a story about a magic backpack."),
    nil,
) {
    if err != nil {
        log.Fatal(err)
    }
    fmt.Print(result.Candidates[0].Content.Parts[0].Text)
}

การกำหนดค่า

ก่อน

Python

import google.generativeai as genai

model = genai.GenerativeModel(
  'gemini-3.5-flash',
    system_instruction='you are a story teller for kids under 5 years old',
    generation_config=genai.GenerationConfig(
      max_output_tokens=400,
      top_k=2,
      top_p=0.5,
      temperature=0.5,
      response_mime_type='application/json',
      stop_sequences=['\n'],
    )
)
response = model.generate_content('tell me a story in 100 words')

JavaScript

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

const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");
const model = genAI.getGenerativeModel({
  model: "gemini-3.5-flash",
  generationConfig: {
    candidateCount: 1,
    stopSequences: ["x"],
    maxOutputTokens: 20,
    temperature: 1.0,
  },
});

const result = await model.generateContent(
  "Tell me a story about a magic backpack.",
);
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")
model.SetTemperature(0.5)
model.SetTopP(0.5)
model.SetTopK(2.0)
model.SetMaxOutputTokens(100)
model.ResponseMIMEType = "application/json"
resp, err := model.GenerateContent(ctx, genai.Text("Tell me about New York"))
if err != nil {
    log.Fatal(err)
}
printResponse(resp) // utility for printing response

หลัง

Python

สำหรับเมธอดทั้งหมดใน SDK ใหม่ ระบบจะระบุอาร์กิวเมนต์ที่จำเป็นเป็นอาร์กิวเมนต์คีย์เวิร์ด และระบุอินพุตที่ไม่บังคับทั้งหมดในอาร์กิวเมนต์ config คุณระบุอาร์กิวเมนต์การกำหนดค่าเป็นพจนานุกรม Python หรือคลาส Config ในเนมสเปซ google.genai.types ก็ได้ คำจำกัดความทั้งหมดในโมดูล types จะเป็นคลาส pydantic เพื่อความสะดวกและสม่ำเสมอ

from google import genai
from google.genai import types

client = genai.Client()

response = client.models.generate_content(
  model='gemini-3.5-flash',
  contents='Tell me a story in 100 words.',
  config=types.GenerateContentConfig(
      system_instruction='you are a story teller for kids under 5 years old',
      max_output_tokens= 400,
      top_k= 2,
      top_p= 0.5,
      temperature= 0.5,
      response_mime_type= 'application/json',
      stop_sequences= ['\n'],
      seed=42,
  ),
)

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 about a magic backpack.",
  config: {
    candidateCount: 1,
    stopSequences: ["x"],
    maxOutputTokens: 20,
    temperature: 1.0,
  },
});

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 about New York"),
    &genai.GenerateContentConfig{
        Temperature:      genai.Ptr[float32](0.5),
        TopP:             genai.Ptr[float32](0.5),
        TopK:             genai.Ptr[float32](2.0),
        ResponseMIMEType: "application/json",
        StopSequences:    []string{"Yankees"},
        CandidateCount:   2,
        Seed:             genai.Ptr[int32](42),
        MaxOutputTokens:  128,
        PresencePenalty:  genai.Ptr[float32](0.5),
        FrequencyPenalty: genai.Ptr[float32](0.5),
    },
)
if err != nil {
    log.Fatal(err)
}
debugPrint(result) // utility for printing response

การตั้งค่าความปลอดภัย

สร้างการตอบกลับด้วยการตั้งค่าความปลอดภัยดังนี้

ก่อน

Python

import google.generativeai as genai

model = genai.GenerativeModel('gemini-3.5-flash')
response = model.generate_content(
    'say something bad',
    safety_settings={
        'HATE': 'BLOCK_ONLY_HIGH',
        'HARASSMENT': 'BLOCK_ONLY_HIGH',
  }
)

JavaScript

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

const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");
const model = genAI.getGenerativeModel({
  model: "gemini-3.5-flash",
  safetySettings: [
    {
      category: HarmCategory.HARM_CATEGORY_HARASSMENT,
      threshold: HarmBlockThreshold.BLOCK_LOW_AND_ABOVE,
    },
  ],
});

const unsafePrompt =
  "I support Martians Soccer Club and I think " +
  "Jupiterians Football Club sucks! Write an ironic phrase telling "