במדריך למתחילים הזה נסביר איך להתקין את הספריות שלנו ולשלוח את הבקשה הראשונה ל-Gemini API.
לפני שמתחילים
אתם צריכים מפתח Gemini API. אם עדיין אין לכם חשבון, תוכלו ליצור אותו בחינם ב-Google AI Studio.
התקנה של Google GenAI SDK
Python
באמצעות Python 3.9 ואילך, מתקינים את החבילה google-genai
באמצעות פקודת pip הבאה:
pip install -q -U google-genai
JavaScript
אם משתמשים ב-Node.js v18+, צריך להתקין את Google Gen AI SDK ל-TypeScript ול-JavaScript באמצעות פקודת npm הבאה:
npm install @google/genai
Go
מתקינים את google.golang.org/genai בספריית המודולים באמצעות הפקודה go get:
go get google.golang.org/genai
Java
אם אתם משתמשים ב-Maven, אתם יכולים להתקין את google-genai על ידי הוספת הקוד הבא ליחסי התלות:
<dependencies>
<dependency>
<groupId>com.google.genai</groupId>
<artifactId>google-genai</artifactId>
<version>1.0.0</version>
</dependency>
</dependencies>
Apps Script
- כדי ליצור פרויקט חדש ב-Apps Script, עוברים אל script.new.
- לוחצים על פרויקט ללא שם.
- משנים את השם של פרויקט Apps Script ל-AI Studio ולוחצים על שינוי שם.
- מגדירים את מפתח ה-API
- בצד ימין, לוחצים על הגדרות הפרויקט
.
- בקטע מאפייני סקריפט לוחצים על הוספת מאפיין סקריפט.
- בשדה Property (מאפיין), מזינים את שם המפתח:
GEMINI_API_KEY
. - בשדה ערך, מזינים את הערך של מפתח ה-API.
- לוחצים על שמירת מאפייני סקריפט.
- בצד ימין, לוחצים על הגדרות הפרויקט
- מחליפים את התוכן של הקובץ
Code.gs
בקוד הבא:
שליחת הבקשה הראשונה
הנה דוגמה לשימוש בשיטה generateContent
כדי לשלוח בקשה ל-Gemini API באמצעות מודל Gemini 2.5 Flash.
אם מגדירים את מפתח ה-API כמשתנה הסביבה GEMINI_API_KEY
, הלקוח יזהה אותו באופן אוטומטי כשמשתמשים בספריות Gemini API.
אחרת, תצטרכו להעביר את מפתח ה-API כארגומנט כשמפעילים את הלקוח.
שימו לב: כל דוגמאות הקוד במסמכי ה-API של Gemini מניחות שהגדרתם את משתנה הסביבה GEMINI_API_KEY
.
Python
from google import genai
# The client gets the API key from the environment variable `GEMINI_API_KEY`.
client = genai.Client()
response = client.models.generate_content(
model="gemini-2.5-flash", contents="Explain how AI works in a few words"
)
print(response.text)
JavaScript
import { GoogleGenAI } from "@google/genai";
// The client gets the API key from the environment variable `GEMINI_API_KEY`.
const ai = new GoogleGenAI({});
async function main() {
const response = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: "Explain how AI works in a few words",
});
console.log(response.text);
}
main();
Go
package main
import (
"context"
"fmt"
"log"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
// The client gets the API key from the environment variable `GEMINI_API_KEY`.
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
result, err := client.Models.GenerateContent(
ctx,
"gemini-2.5-flash",
genai.Text("Explain how AI works in a few words"),
nil,
)
if err != nil {
log.Fatal(err)
}
fmt.Println(result.Text())
}
Java
package com.example;
import com.google.genai.Client;
import com.google.genai.types.GenerateContentResponse;
public class GenerateTextFromTextInput {
public static void main(String[] args) {
// The client gets the API key from the environment variable `GEMINI_API_KEY`.
Client client = new Client();
GenerateContentResponse response =
client.models.generateContent(
"gemini-2.5-flash",
"Explain how AI works in a few words",
null);
System.out.println(response.text());
}
}
Apps Script
// See https://developers.google.com/apps-script/guides/properties
// for instructions on how to set the API key.
const apiKey = PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');
function main() {
const payload = {
contents: [
{
parts: [
{ text: 'Explain how AI works in a few words' },
],
},
],
};
const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent';
const options = {
method: 'POST',
contentType: 'application/json',
headers: {
'x-goog-api-key': apiKey,
},
payload: JSON.stringify(payload)
};
const response = UrlFetchApp.fetch(url, options);
const data = JSON.parse(response);
const content = data['candidates'][0]['content']['parts'][0]['text'];
console.log(content);
}
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [
{
"parts": [
{
"text": "Explain how AI works in a few words"
}
]
}
]
}'
האפשרות 'חשיבה' מופעלת כברירת מחדל בהרבה מדוגמאות הקוד שלנו
הרבה דוגמאות קוד באתר הזה מבוססות על המודל Gemini 2.5 Flash, שבו התכונה 'חשיבה' מופעלת כברירת מחדל כדי לשפר את איכות התשובות. חשוב לדעת: הפעולה הזו עשויה להאריך את זמן התגובה ולהגדיל את השימוש באסימונים. אם אתם רוצים לתת עדיפות למהירות או לצמצם את העלויות, אתם יכולים להשבית את התכונה הזו על ידי הגדרת תקציב החשיבה לאפס, כמו בדוגמאות שבהמשך. מידע נוסף זמין במדריך התכנון.
Python
from google import genai
from google.genai import types
client = genai.Client()
response = client.models.generate_content(
model="gemini-2.5-flash",
contents="Explain how AI works in a few words",
config=types.GenerateContentConfig(
thinking_config=types.ThinkingConfig(thinking_budget=0) # Disables thinking
),
)
print(response.text)
JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({});
async function main() {
const response = await ai.models.generateContent({
model: "gemini-2.5-flash",
contents: "Explain how AI works in a few words",
config: {
thinkingConfig: {
thinkingBudget: 0, // Disables thinking
},
}
});
console.log(response.text);
}
await main();
Go
package main
import (
"context"
"fmt"
"os"
"google.golang.org/genai"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, nil)
if err != nil {
log.Fatal(err)
}
result, _ := client.Models.GenerateContent(
ctx,
"gemini-2.5-flash",
genai.Text("Explain how AI works in a few words"),
&genai.GenerateContentConfig{
ThinkingConfig: &genai.ThinkingConfig{
ThinkingBudget: int32(0), // Disables thinking
},
}
)
fmt.Println(result.Text())
}
REST
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [
{
"parts": [
{
"text": "Explain how AI works in a few words"
}
]
}
]
"generationConfig": {
"thinkingConfig": {
"thinkingBudget": 0
}
}
}'
Apps Script
// See https://developers.google.com/apps-script/guides/properties
// for instructions on how to set the API key.
const apiKey = PropertiesService.getScriptProperties().getProperty('GEMINI_API_KEY');
function main() {
const payload = {
contents: [
{
parts: [
{ text: 'Explain how AI works in a few words' },
],
},
],
};
const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent';
const options = {
method: 'POST',
contentType: 'application/json',
headers: {
'x-goog-api-key': apiKey,
},
payload: JSON.stringify(payload)
};
const response = UrlFetchApp.fetch(url, options);
const data = JSON.parse(response);
const content = data['candidates'][0]['content']['parts'][0]['text'];
console.log(content);
}
המאמרים הבאים
אחרי שביצעתם את בקשת ה-API הראשונה, כדאי לעיין במדריכים הבאים שמציגים את Gemini בפעולה: