Duke filluar me lëshimin e Gemini 2.0 në fund të vitit 2024, ne prezantuam një set të ri librarish të quajtur Google GenAI SDK . Ai ofron një përvojë të përmirësuar për zhvilluesit përmes një arkitekture të përditësuar të klientit dhe thjeshton kalimin midis rrjedhave të punës së zhvilluesit dhe ndërmarrjes.
SDK-ja Google GenAI tani është në Disponueshmëri të Përgjithshme (GA) në të gjitha platformat e mbështetura. Nëse po përdorni një nga bibliotekat tona të trashëguara , ne ju rekomandojmë fuqimisht të migroni.
Ky udhëzues ofron shembuj para dhe pas të kodit të migruar për t'ju ndihmuar të filloni.
Instalimi
Para
Python
pip install -U -q "google-generativeai"
JavaScript
npm install @google/generative-ai
Shko
go get github.com/google/generative-ai-go
Pas
Python
pip install -U -q "google-genai"
JavaScript
npm install @google/genai
Shko
go get google.golang.org/genai
Qasje në API
SDK-ja e vjetër e trajtonte në mënyrë implicite klientin API prapa skenave duke përdorur një sërë metodash ad hoc. Kjo e bënte të vështirë menaxhimin e klientit dhe kredencialeve. Tani, ju bashkëveproni përmes një objekti qendror Client . Ky objekt Client vepron si një pikë e vetme hyrjeje për shërbime të ndryshme API (p.sh., models , chats , files , tunings ), duke promovuar qëndrueshmëri dhe duke thjeshtuar menaxhimin e kredencialeve dhe konfigurimit nëpër thirrje të ndryshme API.
Më parë (Qasje më pak e centralizuar e API-t)
Python
SDK-ja e vjetër nuk përdorte në mënyrë të qartë një objekt klienti të nivelit të lartë për shumicën e thirrjeve API. Ju do të krijonit dhe bashkëvepronit drejtpërdrejt me objektet GenerativeModel .
import google.generativeai as genai
# Directly create and use model objects
model = genai.GenerativeModel('gemini-3.7-flash')
response = model.generate_content(...)
chat = model.start_chat(...)
JavaScript
Ndërsa GoogleGenerativeAI ishte një pikë qendrore për modelet dhe bisedat, funksionalitete të tjera si menaxhimi i skedarëve dhe i memorjes së përkohshme shpesh kërkonin importimin dhe krijimin e klasave të klientëve krejtësisht të ndara.
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.7-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(...);
Shko
Funksioni genai.NewClient krijoi një klient, por operacionet e modelit gjenerues zakonisht thirreshin në një instancë të veçantë GenerativeModel të marrë nga ky klient. Shërbime të tjera mund të jenë aksesuar nëpërmjet paketave ose modeleve të dallueshme.
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.7-flash")
resp, err := model.GenerateContent(...)
cs := model.StartChat()
// Call methods on separate client objects for other services
uploadedFile, err := fileClient.UploadFile(...)
Pas (Objekt i Klientit të Qendruar)
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(...);
Shko
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(...)
Autentifikimi
Si bibliotekat e vjetra ashtu edhe ato të rejat autentifikohen duke përdorur çelësat API. Mund ta krijoni çelësin tuaj API në Google AI Studio.
Para
Python
SDK-ja e vjetër e trajtonte objektin e klientit API në mënyrë implicite.
import google.generativeai as genai
genai.configure(api_key=...)
JavaScript
import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI("GEMINI_API_KEY");
Shko
Importoni bibliotekat e Google:
import (
"github.com/google/generative-ai-go/genai"
"google.golang.org/api/option"
)
Krijo klientin:
client, err := genai.NewClient(ctx, option.WithAPIKey("GEMINI_API_KEY"))
Pas
Python
Me Google GenAI SDK, së pari krijoni një klient API, i cili përdoret për të thirrur API-në. SDK-ja e re do të marrë çelësin tuaj API nga variablat e mjedisit GEMINI_API_KEY , nëse nuk ia kaloni një të tillë klientit.
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"});
Shko
Importoni bibliotekën GenAI:
import "google.golang.org/genai"
Krijo klientin:
client, err := genai.NewClient(ctx, &genai.ClientConfig{
Backend: genai.BackendGeminiAPI,
})
Gjeneroni përmbajtje
Tekst
Para
Python
Më parë, nuk kishte objekte klientësh, ju qaseshit në API direkt përmes objekteve GenerativeModel .
import google.generativeai as genai
model = genai.GenerativeModel('gemini-3.7-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.7-flash" });
const prompt = "Tell me a story in 300 words";
const result = await model.generateContent(prompt);
console.log(result.response.text());
Shko
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.7-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
Pas
Python
SDK-ja e re e Google GenAI ofron qasje në të gjitha metodat API përmes objektit Client . Me përjashtim të disa rasteve të veçanta me gjendje ( chat dhe session live-API), të gjitha këto janë funksione pa gjendje. Për dobi dhe uniformitet, objektet e kthyera janë klasa pydantic .
from google import genai
client = genai.Client()
response = client.models.generate_content(
model='gemini-3.7-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.7-flash",
contents: "Tell me a story in 300 words.",
});
console.log(response.text);
Shko
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
result, err := client.Models.GenerateContent(ctx, "gemini-3.7-flash", genai.Text("Tell me a story in 300 words."), nil)
if err !=