יצירת טקסט

Gemini API יכול ליצור פלט טקסט בתגובה לקלטים שונים, כולל טקסט, תמונות, סרטונים וקטעי אודיו. במדריך הזה מוסבר איך ליצור טקסט באמצעות קלט של טקסט ותמונות. הוא כולל גם הנחיות לגבי סטרימינג, צ'אט והמערכת.

קלט טקסט

הדרך הפשוטה ביותר ליצור טקסט באמצעות Gemini API היא לספק למודל קלט יחיד של טקסט בלבד, כפי שמתואר בדוגמה הבאה:

from google import genai

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

response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents=["How does AI work?"]
)
print(response.text)
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.0-flash",
    contents: "How does AI work?",
  });
  console.log(response.text);
}

await main();
// import packages here

func main() {
  ctx := context.Background()
  client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("GEMINI_API_KEY")))
  if err != nil {
    log.Fatal(err)
  }
  defer client.Close()

  model := client.GenerativeModel("gemini-2.0-flash")
  resp, err := model.GenerateContent(ctx, genai.Text("How does AI work?"))
  if err != nil {
    log.Fatal(err)
  }
  printResponse(resp) // helper function for printing content parts
}
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -X POST \
  -d '{
    "contents": [
      {
        "parts": [
          {
            "text": "How does AI work?"
          }
        ]
      }
    ]
  }'

קלט תמונה

ה-API של Gemini תומך בקלט רב-מודלי שמשלב טקסט וקבצי מדיה. הדוגמה הבאה מראה איך ליצור טקסט ממידע קלט של טקסט ותמונה:

from PIL import Image
from google import genai

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

image = Image.open("/path/to/organ.png")
response = client.models.generate_content(
    model="gemini-2.0-flash",
    contents=[image, "Tell me about this instrument"]
)
print(response.text)
import {
  GoogleGenAI,
  createUserContent,
  createPartFromUri,
} from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });

async function main() {
  const image = await ai.files.upload({
    file: "/path/to/organ.png",
  });
  const response = await ai.models.generateContent({
    model: "gemini-2.0-flash",
    contents: [
      createUserContent([
        "Tell me about this instrument",
        createPartFromUri(image.uri, image.mimeType),
      ]),
    ],
  });
  console.log(response.text);
}

await main();
model := client.GenerativeModel("gemini-2.0-flash")

imgData, err := os.ReadFile(filepath.Join(testDataDir, "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)
# Use a temporary file to hold the base64 encoded image data
TEMP_B64=$(mktemp)
trap 'rm -f "$TEMP_B64"' EXIT
base64 $B64FLAGS $IMG_PATH > "$TEMP_B64"

# Use a temporary file to hold the JSON payload
TEMP_JSON=$(mktemp)
trap 'rm -f "$TEMP_JSON"' EXIT

cat > "$TEMP_JSON" << EOF
{
  "contents": [
    {
      "parts": [
        {
          "text": "Tell me about this instrument"
        },
        {
          "inline_data": {
            "mime_type": "image/jpeg",
            "data": "$(cat "$TEMP_B64")"
          }
        }
      ]
    }
  ]
}
EOF

curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -X POST \
  -d "@$TEMP_JSON"

פלט בסטרימינג

כברירת מחדל, המודל מחזיר תשובה אחרי השלמת כל תהליך יצירת הטקסט. כדי לזרז את האינטראקציות, אפשר להשתמש בסטרימינג כדי להחזיר את המופעים של GenerateContentResponse ברגע שהם נוצרים.

from google import genai

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

response = client.models.generate_content_stream(
    model="gemini-2.0-flash",
    contents=["Explain how AI works"]
)
for chunk in response:
    print(chunk.text, end="")
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });

async function main() {
  const response = await ai.models.generateContentStream({
    model: "gemini-2.0-flash",
    contents: "Explain how AI works",
  });

  for await (const chunk of response) {
    console.log(chunk.text);
  }
}

await main();
model := client.GenerativeModel("gemini-1.5-flash")
iter := model.GenerateContentStream(ctx, genai.Text("Write a story about a magic backpack."))
for {
  resp, err := iter.Next()
  if err == iterator.Done {
    break
  }
  if err != nil {
    log.Fatal(err)
  }
  printResponse(resp)
}
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key=${GEMINI_API_KEY}" \
  -H 'Content-Type: application/json' \
  --no-buffer \
  -d '{
    "contents": [
      {
        "parts": [
          {
            "text": "Explain how AI works"
          }
        ]
      }
    ]
  }'

שיחות עם זיכרון

באמצעות Gemini SDK אפשר לאסוף כמה סיבובים של שאלות ותשובות בצ'אט. פורמט הצ'אט מאפשר למשתמשים להתקדם בהדרגה לעבר תשובות ולקבל עזרה בבעיות שמכילות כמה חלקים. הטמעת ה-SDK של הצ'אט מספקת ממשק למעקב אחרי היסטוריית השיחות, אבל מאחורי הקלעים היא משתמשת באותו method‏ generateContent כדי ליצור את התגובה.

בדוגמה הבאה מוצגת הטמעה בסיסית של צ'אט:

from google import genai

client = genai.Client(api_key="GEMINI_API_KEY")
chat = client.chats.create(model="gemini-2.0-flash")

response = chat.send_message("I have 2 dogs in my house.")
print(response.text)

response = chat.send_message("How many paws are in my house?")
print(response.text)

for message in chat.get_history():
    print(f'role - {message.role}',end=": ")
    print(message.parts[0].text)
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });

async function main() {
  const chat = ai.chats.create({
    model: "gemini-2.0-flash",
    history: [
      {
        role: "user",
        parts: [{ text: "Hello" }],
      },
      {
        role: "model",
        parts: [{ text: "Great to meet you. What would you like to know?" }],
      },
    ],
  });

  const response1 = await chat.sendMessage({
    message: "I have 2 dogs in my house.",
  });
  console.log("Chat response 1:", response1.text);

  const response2 = await chat.sendMessage({
    message: "How many paws are in my house?",
  });
  console.log("Chat response 2:", response2.text);
}

await main();
model := client.GenerativeModel("gemini-1.5-flash")
cs := model.StartChat()

cs.History = []*genai.Content{
  {
    Parts: []genai.Part{
      genai.Text("Hello, I have 2 dogs in my house."),
    },
    Role: "user",
  },
  {
    Parts: []genai.Part{
      genai.Text("Great to meet you. What would you like to know?"),
    },
    Role: "model",
  },
}

res, err := cs.SendMessage(ctx, genai.Text("How many paws are in my house?"))
if err != nil {
  log.Fatal(err)
}
printResponse(res)
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY \
  -H 'Content-Type: application/json' \
  -X POST \
  -d '{
    "contents": [
      {
        "role": "user",
        "parts": [
          {
            "text": "Hello"
          }
        ]
      },
      {
        "role": "model",
        "parts": [
          {
            "text": "Great to meet you. What would you like to know?"
          }
        ]
      },
      {
        "role": "user",
        "parts": [
          {
            "text": "I have two dogs in my house. How many paws are in my house?"
          }
        ]
      }
    ]
  }'

אפשר גם להשתמש בשידור חי עם צ'אט, כמו בדוגמה הבאה:

from google import genai

client = genai.Client(api_key="GEMINI_API_KEY")
chat = client.chats.create(model="gemini-2.0-flash")

response = chat.send_message_stream("I have 2 dogs in my house.")
for chunk in response:
    print(chunk.text, end="")

response = chat.send_message_stream("How many paws are in my house?")
for chunk in response:
    print(chunk.text, end="")

for message in chat.get_history():
    print(f'role - {message.role}', end=": ")
    print(message.parts[0].text)
import { GoogleGenAI } from "@google/genai";

const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" });

async function main() {
  const chat = ai.chats.create({
    model: "gemini-2.0-flash",
    history: [
      {
        role: "user",
        parts: [{ text: "Hello" }],
      },
      {
        role: "model",
        parts: [{ text: "Great to meet you. What would you like to know?" }],
      },
    ],
  });

  const stream1 = await chat.sendMessageStream({
    message: "I have 2 dogs in my house.",
  });
  for await (const chunk of stream1) {
    console.log(chunk.text);
    console.log("_".repeat(80));
  }

  const stream2 = await chat.sendMessageStream({
    message: "How many paws are in my house?",
  });
  for await (const chunk of stream2) {
    console.log(chunk.text);
    console.log("_".repeat(80));
  }
}

await main();
model := client.GenerativeModel("gemini-1.5-flash")
cs := model.StartChat()

cs.History = []*genai.Content{
  {
    Parts: []genai.Part{
      genai.Text("Hello, I have 2 dogs in my house."),
    },
    Role: "user",
  },
  {
    Parts: []genai.Part{
      genai.Text("Great to meet you. What would you like to know?"),
    },
    Role: "model",
  },
}

iter := cs.SendMessageStream(ctx, genai.Text("How many paws are in my house?"))
for {
  resp, err := iter.Next()
  if err == iterator.Done {
    break
  }
  if err != nil {
    log.Fatal(err)
  }
  printResponse(resp)
}
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:streamGenerateContent?alt=sse&key=$GEMINI_API_KEY \
  -H 'Content-Type: application/json' \
  -X POST \
  -d '{
    "contents": [
      {
        "role": "user",
        "parts": [
          {
            "text": "Hello"
          }
        ]
      },
      {
        "role": "model",
        "parts": [
          {
            "text": "Great to meet you. What would you like to know?"
          }
        ]
      },
      {
        "role": "user",
        "parts": [
          {
            "text": "I have two dogs in my house. How many paws are in my house?"
          }
        ]
      }
    ]
  }'

פרמטרים של הגדרות

כל הנחיה ששולחים למודל כוללת פרמטרים ששולטים באופן שבו המודל יוצר תשובות. אפשר להגדיר את הפרמטרים האלה או לאפשר למודל להשתמש באפשרויות ברירת המחדל.

הדוגמה הבאה מראה איך להגדיר את הפרמטרים של המודל:

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.0-flash",
    contents=["Explain how AI works"],
    config=types.GenerateContentConfig(
        max_output_tokens=500,
        temperature=0.1
    )
)
print(response.text)
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.0-flash",
    contents: "Explain how AI works",
    config: {
      maxOutputTokens: 500,
      temperature: 0.1,
    },
  });
  console.log(response.text);
}

await main();
model := client.GenerativeModel("gemini-1.5-pro-latest")
model.SetTemperature(0.9)
model.SetTopP(0.5)
model.SetTopK(20)
model.SetMaxOutputTokens(100)
model.SystemInstruction = genai.NewUserContent(genai.Text("You are Yoda from Star Wars."))
model.ResponseMIMEType = "application/json"
resp, err := model.GenerateContent(ctx, genai.Text("What is the average size of a swallow?"))
if err != nil {
  log.Fatal(err)
}
printResponse(resp)
curl https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY \
  -H 'Content-Type: application/json' \
  -X POST \
  -d '{
    "contents": [
      {
        "parts": [
          {
            "text": "Explain how AI works"
          }
        ]
      }
    ],
    "generationConfig": {
      "stopSequences": [
        "Title"
      ],
      "temperature": 1.0,
      "maxOutputTokens": 800,
      "topP": 0.8,
      "topK": 10
    }
  }'

ריכזנו כאן כמה מהפרמטרים של המודל שאפשר להגדיר. (מוסכמות מתן השמות משתנות בהתאם לשפת התכנות).

  • stopSequences: מציין את קבוצת רצפי התווים (עד 5) שיעצור את יצירת הפלט. אם יצוין, ה-API יפסיק להפעיל את הקוד עם הופעתו הראשונה של stop_sequence. רצף העצירות לא ייכלל בתגובה.
  • temperature: קובע את מידת הרנדומיזציה של הפלט. מומלץ להשתמש בערכים גבוהים יותר כדי לקבל תשובות יצירתיות יותר, ובערכים נמוכים יותר כדי לקבל תשובות גורליות יותר. הערכים יכולים לנוע בטווח [0.0, 2.0].
  • maxOutputTokens: מגדיר את המספר המקסימלי של אסימונים שאפשר לכלול באפשרות.
  • topP: שינוי האופן שבו המודל בוחר אסימונים לפלט. האסימונים נבחרים מהסיכוי הגבוה ביותר לנמוך ביותר, עד שסכום ההסתברויות שלהם שווה לערך topP. ערך ברירת המחדל של topP הוא 0.95.
  • topK: שינוי האופן שבו המודל בוחר אסימונים לפלט. כשהערך של topK הוא 1, המשמעות היא שהאסימון שנבחר הוא בעל ההסתברות הגבוהה ביותר מבין כל האסימונים במילון של המודל. לעומת זאת, כשהערך של topK הוא 3, המשמעות היא שהאסימון הבא נבחר מתוך 3 האסימונים עם ההסתברות הגבוהה ביותר באמצעות הטמפרטורה. האסימונים עוברים סינון נוסף על סמך topP, והאסימון הסופי נבחר באמצעות דגימת טמפרטורה.

הוראות למערכת

הוראות המערכת מאפשרות לכם לקבוע את התנהגות המודל על סמך תרחיש לדוגמה ספציפי. כשאתם מספקים הוראות למערכת, אתם מספקים למודל הקשר נוסף שיעזור לו להבין את המשימה וליצור תשובות מותאמות אישית יותר. המודל צריך לפעול בהתאם להוראות המערכת במהלך כל האינטראקציה עם המשתמש, וכך לאפשר לכם לציין התנהגות ברמת המוצר בנפרד מההנחיות שמשתמשי הקצה מספקים.

אפשר להגדיר הוראות מערכת כשמאתחלים את המודל:

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.0-flash",
    config=types.GenerateContentConfig(
        system_instruction="You are a cat. Your name is Neko."),
    contents="Hello there"
)

print(response.text)
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.0-flash",
    contents: "Hello there",
    config: {
      systemInstruction: "You are a cat. Your name is Neko.",
    },
  });
  console.log(response.text);
}

await main();
// import packages here

func main() {
  ctx := context.Background()
  client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("GEMINI_API_KEY")))
  if err != nil {
    log.Fatal(err)
  }
  defer client.Close()

  model := client.GenerativeModel("gemini-2.0-flash")
  model.SystemInstruction = &genai.Content{
    Parts: []genai.Part{genai.Text(`
      You are a cat. Your name is Neko.
    `)},
  }
  resp, err := model.GenerateContent(ctx, genai.Text("Hello there"))
  if err != nil {
    log.Fatal(err)
  }
  printResponse(resp) // helper function for printing content parts
}
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GEMINI_API_KEY" \
  -H 'Content-Type: application/json' \
  -d '{
    "system_instruction": {
      "parts": [
        {
          "text": "You are a cat. Your name is Neko."
        }
      ]
    },
    "contents": [
      {
        "parts": [
          {
            "text": "Hello there"
          }
        ]
      }
    ]
  }'

לאחר מכן תוכלו לשלוח בקשות למודל כרגיל.

מודלים נתמכים

כל משפחת המודלים של Gemini תומכת ביצירת טקסט. מידע נוסף על המודלים ועל היכולות שלהם זמין במאמר מודלים.

טיפים לכתיבת הנחיות

בתרחישי שימוש בסיסיים ליצירת טקסט, יכול להיות שלא תצטרכו לכלול בהנחיה דוגמאות פלט, הוראות מערכת או פרטי עיצוב. זוהי גישה של הנחיה ישירה (zero-shot). בתרחישי שימוש מסוימים, הנחיה חד-פעמית או לכמה משפטים עשויה להניב פלט שמתאים יותר לציפיות של המשתמשים. במקרים מסוימים, כדאי גם לספק הוראות מערכת כדי לעזור למודל להבין את המשימה או לפעול לפי הנחיות ספציפיות.

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