במדריך למתחילים הזה נסביר איך להתקין את הספריות שלנו ולשלוח את הבקשה הראשונה ל-Gemini API.
לפני שמתחילים
צריך מפתח API של Gemini. אם עדיין אין לכם חשבון, תוכלו להירשם בחינם ל-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.
- לוחצים על Untitled project.
- משנים את שם הפרויקט ב-Apps Script ל-AI Studio ולוחצים על Rename.
- מגדירים את מפתח ה-API
- בצד ימין, לוחצים על הגדרות הפרויקט
.
- בקטע מאפייני סקריפט, לוחצים על הוספת מאפיין סקריפט.
- בשדה נכס, מזינים את שם המפתח:
GEMINI_API_KEY
. - בשדה ערך, מזינים את הערך של מפתח ה-API.
- לוחצים על Save script properties.
- בצד ימין, לוחצים על הגדרות הפרויקט
- מחליפים את תוכן הקובץ
Code.gs
בקוד הבא:
שליחת הבקשה הראשונה
הנה דוגמה לשימוש בשיטה generateContent
כדי לשלוח בקשה ל-Gemini API באמצעות מודל Gemini 2.5 Flash.
Python
from google import genai
client = genai.Client(api_key="YOUR_API_KEY")
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";
const ai = new GoogleGenAI({ apiKey: "YOUR_API_KEY" });
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()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
APIKey: "YOUR_API_KEY",
Backend: genai.BackendGeminiAPI,
})
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 `GOOGLE_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?key=${apiKey}`;
const options = {
method: 'POST',
contentType: 'application/json',
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?key=$YOUR_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(api_key="GEMINI_API_KEY")
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({ apiKey: "GEMINI_API_KEY" });
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, _ := genai.NewClient(ctx, &genai.ClientConfig{
APIKey: os.Getenv("GEMINI_API_KEY"),
Backend: genai.BackendGeminiAPI,
})
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?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?key=${apiKey}`;
const options = {
method: 'POST',
contentType: 'application/json',
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: