بدءًا من إصدار Gemini 2.0 في أواخر عام 2024، طرحنا مجموعة جديدة من المكتبات تُعرف باسم Google GenAI SDK. وتوفّر هذه المكتبة تجربة محسّنة للمطوّرين من خلال بنية أساسية محدَّثة للعميل، و تسهّل عملية الانتقال بين سير عمل المطوّرين والمؤسسات.
أصبحت Google GenAI SDK متوفّرة الآن للجمهور العام على جميع المنصات المتوافقة. إذا كنت تستخدم إحدى مكتباتنا القديمة، ننصحك بشدة بنقل بياناتك.
يقدّم هذا الدليل أمثلة على الرموز البرمجية قبل وبعد نقل البيانات لمساعدتك في البدء.
تثبيت
قبل
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
الدخول إلى واجهة برمجة التطبيقات
كانت حزمة SDK القديمة تعالج عميل واجهة برمجة التطبيقات ضمنيًا في الخلفية باستخدام مجموعة متنوّعة من الطرق المخصّصة. وقد صعّب ذلك إدارة العميل وبيانات الاعتماد.
يمكنك الآن التفاعل من خلال عنصر Client مركزي. يعمل عنصر Client هذا كنقطة دخول واحدة لمختلف خدمات واجهة برمجة التطبيقات (مثل models وchats وfiles وtunings)، ما يعزّز الاتساق ويسهّل إدارة بيانات الاعتماد والإعدادات على مستوى طلبات واجهة برمجة التطبيقات المختلفة.
قبل (الوصول إلى واجهة برمجة التطبيقات بشكل أقل مركزية)
Python
لم تكن حزمة SDK القديمة تستخدم بشكل صريح عنصر عميل على المستوى الأعلى لمعظم طلبات واجهة برمجة التطبيقات. وكان عليك إنشاء مثيل لعناصر 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(...)
المصادقة
تتم المصادقة في كلٍّ من المكتبات القديمة والجديدة باستخدام مفاتيح واجهة برمجة التطبيقات. يمكنك إنشاء مفتاح واجهة برمجة التطبيقات في Google AI Studio.
قبل
Python
كانت حزمة SDK القديمة تعالج عنصر عميل واجهة برمجة التطبيقات ضمنيًا.
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، يمكنك إنشاء عميل لواجهة برمجة التطبيقات أولاً، ويُستخدم هذا العميل لاستدعاء واجهة برمجة التطبيقات.
ستحصل حزمة SDK الجديدة على مفتاح واجهة برمجة التطبيقات من متغيرات البيئة 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
في السابق، لم تكن هناك عناصر عميل، وكان بإمكانك الوصول إلى واجهات برمجة التطبيقات مباشرةً من خلال عناصر 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 الجديدة الوصول إلى جميع طرق واجهة برمجة التطبيقات من خلال عنصر Client. باستثناء بعض الحالات الخاصة التي تحتفظ بالحالة (chat وsessions لواجهة برمجة التطبيقات المباشرة)، تكون جميع هذه الدوال غير محتفظة بالحالة. لتحقيق الفائدة والاتساق، تكون العناصر التي يتم عرضها فئات 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 :=