המדריך למתחילים של Gemini API

במדריך למתחילים הזה נסביר איך להתקין את הספריות שלנו ולשלוח את הבקשה הראשונה ל-Gemini API.

לפני שמתחילים

צריך מפתח API של Gemini. אם עדיין אין לכם חשבון, תוכלו להירשם בחינם ל-Google AI Studio.

התקנה של Google GenAI SDK

ב-Python 3.9 ואילך, מתקינים את חבילת google-genai באמצעות פקודת pip הבאה:

pip install -q -U google-genai

באמצעות Node.js v18 ואילך, מתקינים את Google Gen AI SDK ל-TypeScript ול-JavaScript באמצעות הפקודה הבאה של npm:

npm install @google/genai

מתקינים את ‎google.golang.org/genai בספריית המודול באמצעות הפקודה go get:

go get google.golang.org/genai
  1. כדי ליצור פרויקט חדש של Apps Script, עוברים אל script.new.
  2. לוחצים על Untitled project.
  3. משנים את השם של פרויקט Apps Script ל-AI Studio ולוחצים על Rename.
  4. מגדירים את מפתח ה-API
    1. בצד ימין, לוחצים על הגדרות הפרויקט הסמל של הגדרות הפרויקט.
    2. בקטע מאפייני סקריפט, לוחצים על הוספת מאפיין סקריפט.
    3. בשדה נכס, מזינים את שם המפתח: GEMINI_API_KEY.
    4. בשדה ערך, מזינים את הערך של מפתח ה-API.
    5. לוחצים על Save script properties.
  5. מחליפים את תוכן הקובץ Code.gs בקוד הבא:

שליחת הבקשה הראשונה

משתמשים ב-method‏ generateContent כדי לשלוח בקשה ל-Gemini API.

from google import genai

client = genai.Client(api_key="YOUR_API_KEY")

response = client.models.generate_content(
    model="gemini-2.0-flash", contents="Explain how AI works in a few words"
)
print(response.text)
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.0-flash",
    contents: "Explain how AI works in a few words",
  });
  console.log(response.text);
}

main();
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.0-flash",
        genai.Text("Explain how AI works in a few words"),
        nil,
    )
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(result.Text())
}
// 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.0-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);
}
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-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"
          }
        ]
      }
    ]
  }'

המאמרים הבאים

עכשיו, אחרי ששלחתם את הבקשה הראשונה ל-API, כדאי לעיין במדריכים הבאים שבהם מוסבר איך משתמשים ב-Gemini: