מדריך: תחילת העבודה עם Gemini API


להצגה ב-AI מבית Google הפעלה ב-Google Colab הצגת המקור ב-GitHub

המדריך למתחילים הזה מדגים איך משתמשים ב-Python SDK ב-Gemini API, שנותן גישה למודלים גדולים של שפה (LLM) של Google ב-Gemini. במדריך למתחילים הזה תלמדו איך:

  1. כדי להשתמש ב-Gemini, צריך להגדיר את סביבת הפיתוח ואת הגישה ל-API.
  2. יצירת תשובות טקסט מערכי קלט של טקסט.
  3. ליצור תשובות טקסט מערכי קלט רב-אופניים (טקסט ותמונות).
  4. אפשר להשתמש ב-Gemini לשיחות מרובות תורות (בצ'אט).
  5. להשתמש בהטמעות עבור מודלים גדולים של שפה.

דרישות מוקדמות

אפשר להריץ את המדריך למתחילים הזה ב-Google Colab, שמריץ את ה-notebook הזה ישירות בדפדפן ולא צריך להגדיר בו הגדרות נוספות.

לחלופין, כדי להשלים את המדריך למתחילים הזה באופן מקומי, צריך לוודא שסביבת הפיתוח עומדת בדרישות הבאות:

  • Python 3.9 ואילך
  • התקנה של jupyter כדי להריץ את ה-notebook.

הגדרה

התקנת ה-Python SDK

ה-Python SDK של Gemini API כלול בחבילה google-generativeai. מתקינים את התלות באמצעות PIP:

pip install -q -U google-generativeai

ייבוא חבילות

מייבאים את החבילות הנדרשות.

import pathlib
import textwrap

import google.generativeai as genai

from IPython.display import display
from IPython.display import Markdown


def to_markdown(text):
  text = text.replace('•', '  *')
  return Markdown(textwrap.indent(text, '> ', predicate=lambda _: True))
# Used to securely store your API key
from google.colab import userdata

הגדרה של מפתח API

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

קבלת מפתח API

ב-Colab, מוסיפים את המפתח למנהל הסודות שמופיע מתחת לסמל 🔑 בחלונית השמאלית. נותנים למכשיר את השם GOOGLE_API_KEY.

אחרי שמקבלים את מפתח ה-API, מעבירים אותו ל-SDK. תוכל לעשות זאת בשתי דרכים:

  • מכניסים את המפתח למשתנה הסביבה GOOGLE_API_KEY (ערכת ה-SDK תאסוף אותו משם באופן אוטומטי).
  • צריך להעביר את המפתח אל genai.configure(api_key=...)
# Or use `os.getenv('GOOGLE_API_KEY')` to fetch an environment variable.
GOOGLE_API_KEY=userdata.get('GOOGLE_API_KEY')

genai.configure(api_key=GOOGLE_API_KEY)

הצגת רשימה של מודלים

עכשיו הכול מוכן ואפשר להתחיל לשלוח קריאה ל-Gemini API. בעזרת list_models אפשר לראות את המודלים הזמינים של Gemini:

  • gemini-1.5-flash: המודל מרובה המודלים המהיר ביותר
  • gemini-1.5-pro: המודל הכי משוכלל והכי חכם שלנו בכמה מודלים
for m in genai.list_models():
  if 'generateContent' in m.supported_generation_methods:
    print(m.name)

יצירת טקסט מערכי קלט של טקסט

להנחיות עם טקסט בלבד, צריך להשתמש במודל Gemini 1.5 או מודל Gemini 1.0 Pro:

model = genai.GenerativeModel('gemini-1.5-flash')

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

במקרה הפשוט ביותר, אפשר להעביר מחרוזת הנחיה לשיטה GenerativeModel.generate_content:

%%time
response = model.generate_content("What is the meaning of life?")
CPU times: user 110 ms, sys: 12.3 ms, total: 123 ms
Wall time: 8.25 s

במקרים פשוטים, ה-accessor של response.text הוא כל מה שצריך. כדי להציג טקסט Markdown מעוצב צריך להשתמש בפונקציה to_markdown:

to_markdown(response.text)

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

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

  2. תרומה משמעותית: יש אנשים שמאמינים שמטרת החיים היא תרומה משמעותית לעולם. פעילויות כאלה עשויות לכלול מקצוע שמועיל לאחרים, עיסוק בפעילויות התנדבות או צדקה, יצירת אומנות או ספרות או המצאה.

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

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

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

  6. לחוות את החיים במלואם: יש אנשים שמאמינים שמטרת החיים היא לחוות את כל מה שיש להם להציע. הפעולות האלה יכולות לכלול נסיעה, התנסות בדברים חדשים, נטילת סיכונים ואימוץ מפגשים חדשים.

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

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

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

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

response.prompt_feedback
safety_ratings {
  category: HARM_CATEGORY_SEXUALLY_EXPLICIT
  probability: NEGLIGIBLE
}
safety_ratings {
  category: HARM_CATEGORY_HATE_SPEECH
  probability: NEGLIGIBLE
}
safety_ratings {
  category: HARM_CATEGORY_HARASSMENT
  probability: NEGLIGIBLE
}
safety_ratings {
  category: HARM_CATEGORY_DANGEROUS_CONTENT
  probability: NEGLIGIBLE
}

Gemini יכול ליצור כמה תשובות אפשריות להנחיה אחת. התגובות האפשריות האלה נקראות candidates, ואפשר לבדוק אותן כדי לבחור את התשובה המתאימה ביותר בתור התשובה.

הצגת התשובות האפשריות באמצעות GenerateContentResponse.candidates:

response.candidates
[content {
  parts {
    text: "The query of life\'s purpose has perplexed people across centuries, cultures, and continents. While there is no universally recognized response, many ideas have been put forth, and the response is frequently dependent on individual ideas, beliefs, and life experiences.\n\n1. **Happiness and Well-being:** Many individuals believe that the goal of life is to attain personal happiness and well-being. This might entail locating pursuits that provide joy, establishing significant connections, caring for one\'s physical and mental health, and pursuing personal goals and interests.\n\n2. **Meaningful Contribution:** Some believe that the purpose of life is to make a meaningful contribution to the world. This might entail pursuing a profession that benefits others, engaging in volunteer or charitable activities, generating art or literature, or inventing.\n\n3. **Self-realization and Personal Growth:** The pursuit of self-realization and personal development is another common goal in life. This might entail learning new skills, pushing one\'s boundaries, confronting personal obstacles, and evolving as a person.\n\n4. **Ethical and Moral Behavior:** Some believe that the goal of life is to act ethically and morally. This might entail adhering to one\'s moral principles, doing the right thing even when it is difficult, and attempting to make the world a better place.\n\n5. **Spiritual Fulfillment:** For some, the purpose of life is connected to spiritual or religious beliefs. This might entail seeking a connection with a higher power, practicing religious rituals, or following spiritual teachings.\n\n6. **Experiencing Life to the Fullest:** Some individuals believe that the goal of life is to experience all that it has to offer. This might entail traveling, trying new things, taking risks, and embracing new encounters.\n\n7. **Legacy and Impact:** Others believe that the purpose of life is to leave a lasting legacy and impact on the world. This might entail accomplishing something noteworthy, being remembered for one\'s contributions, or inspiring and motivating others.\n\n8. **Finding Balance and Harmony:** For some, the purpose of life is to find balance and harmony in all aspects of their lives. This might entail juggling personal, professional, and social obligations, seeking inner peace and contentment, and living a life that is in accordance with one\'s values and beliefs.\n\nUltimately, the meaning of life is a personal journey, and different individuals may discover their own unique purpose through their experiences, reflections, and interactions with the world around them."
  }
  role: "model"
}
finish_reason: STOP
index: 0
safety_ratings {
  category: HARM_CATEGORY_SEXUALLY_EXPLICIT
  probability: NEGLIGIBLE
}
safety_ratings {
  category: HARM_CATEGORY_HATE_SPEECH
  probability: NEGLIGIBLE
}
safety_ratings {
  category: HARM_CATEGORY_HARASSMENT
  probability: NEGLIGIBLE
}
safety_ratings {
  category: HARM_CATEGORY_DANGEROUS_CONTENT
  probability: NEGLIGIBLE
}
]

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

כדי להציג את התשובות באופן שוטף, אפשר להשתמש ב-GenerativeModel.generate_content(..., stream=True).

%%time
response = model.generate_content("What is the meaning of life?", stream=True)
CPU times: user 102 ms, sys: 25.1 ms, total: 128 ms
Wall time: 7.94 s
for chunk in response:
  print(chunk.text)
  print("_"*80)
The query of life's purpose has perplexed people across centuries, cultures, and
________________________________________________________________________________
 continents. While there is no universally recognized response, many ideas have been put forth, and the response is frequently dependent on individual ideas, beliefs, and life experiences
________________________________________________________________________________
.

1. **Happiness and Well-being:** Many individuals believe that the goal of life is to attain personal happiness and well-being. This might entail locating pursuits that provide joy, establishing significant connections, caring for one's physical and mental health, and pursuing personal goals and aspirations.

2. **Meaning
________________________________________________________________________________
ful Contribution:** Some believe that the purpose of life is to make a meaningful contribution to the world. This might entail pursuing a profession that benefits others, engaging in volunteer or charitable activities, generating art or literature, or inventing.

3. **Self-realization and Personal Growth:** The pursuit of self-realization and personal development is another common goal in life. This might entail learning new skills, exploring one's interests and abilities, overcoming obstacles, and becoming the best version of oneself.

4. **Connection and Relationships:** For many individuals, the purpose of life is found in their relationships with others. This might entail building
________________________________________________________________________________
 strong bonds with family and friends, fostering a sense of community, and contributing to the well-being of those around them.

5. **Spiritual Fulfillment:** For those with religious or spiritual beliefs, the purpose of life may be centered on seeking spiritual fulfillment or enlightenment. This might entail following religious teachings, engaging in spiritual practices, or seeking a deeper understanding of the divine.

6. **Experiencing the Journey:** Some believe that the purpose of life is simply to experience the journey itself, with all its joys and sorrows. This perspective emphasizes embracing the present moment, appreciating life's experiences, and finding meaning in the act of living itself.

7. **Legacy and Impact:** For others, the goal of life is to leave a lasting legacy or impact on the world. This might entail making a significant contribution to a particular field, leaving a positive mark on future generations, or creating something that will be remembered and cherished long after one's lifetime.

Ultimately, the meaning of life is a personal and subjective question, and there is no single, universally accepted answer. It is about discovering what brings you fulfillment, purpose, and meaning in your own life, and living in accordance with those values.
________________________________________________________________________________

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

response = model.generate_content("What is the meaning of life?", stream=True)

המאפיין prompt_feedback פועל:

response.prompt_feedback
safety_ratings {
  category: HARM_CATEGORY_SEXUALLY_EXPLICIT
  probability: NEGLIGIBLE
}
safety_ratings {
  category: HARM_CATEGORY_HATE_SPEECH
  probability: NEGLIGIBLE
}
safety_ratings {
  category: HARM_CATEGORY_HARASSMENT
  probability: NEGLIGIBLE
}
safety_ratings {
  category: HARM_CATEGORY_DANGEROUS_CONTENT
  probability: NEGLIGIBLE
}

לעומת זאת, מאפיינים כמו text לא:

try:
  response.text
except Exception as e:
  print(f'{type(e).__name__}: {e}')
IncompleteIterationError: Please let the response complete iteration before accessing the final accumulated
attributes (or call `response.resolve()`)

יצירת טקסט מערכי קלט של תמונה וטקסט

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

כשהקלט של ההנחיה כולל גם טקסט וגם תמונות, צריך להשתמש ב-Gemini 1.5 עם השיטה GenerativeModel.generate_content כדי ליצור פלט טקסט:

נוסיף תמונה:

curl -o image.jpg https://t0.gstatic.com/licensed-image?q=tbn:ANd9GcQ_Kevbk21QBRy-PgB4kQpS79brbmmEG7m3VOTShAn4PecDU5H5UxrJxE3Dw1JiaG17V88QIol19-3TM2wCHw
% Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed

  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0
100  405k  100  405k    0     0  6982k      0 --:--:-- --:--:-- --:--:-- 7106k
import PIL.Image

img = PIL.Image.open('image.jpg')
img

png

משתמשים במודל Gemini 1.5 ומעבירים את התמונה למודל באמצעות generate_content.

model = genai.GenerativeModel('gemini-1.5-flash')
response = model.generate_content(img)

to_markdown(response.text)

קערות הכנה לארוחה טריאקי, עם אורז חום, ברוקולי צלוי ופלפלים.

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

response = model.generate_content(["Write a short, engaging blog post based on this picture. It should include a description of the meal in the photo and talk about my journey meal prepping.", img], stream=True)
response.resolve()
to_markdown(response.text)

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

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

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

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

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

שיחות צ'אט

Gemini מאפשר לנהל שיחות במגוון תורות. הכיתה ChatSession מפשטת את התהליך באמצעות ניהול מצב השיחה, כך שבניגוד ל-generate_content, לא צריך לשמור את היסטוריית השיחות כרשימה.

אתחול הצ'אט:

model = genai.GenerativeModel('gemini-1.5-flash')
chat = model.start_chat(history=[])
chat
<google.generativeai.generative_models.ChatSession at 0x7b7b68250100>

השיטה ChatSession.send_message מחזירה את אותו סוג GenerateContentResponse כמו GenerativeModel.generate_content. כמו כן, מצורפת ההודעה והתשובה להיסטוריית הצ'אט:

response = chat.send_message("In one sentence, explain how a computer works to a young child.")
to_markdown(response.text)

מחשב הוא כמו מכונה חכמה מאוד שיכול להבין את ההוראות שלנו ולפעול לפיהן, לעזור לנו בעבודה ואפילו לשחק איתנו במשחקים!

chat.history
[parts {
   text: "In one sentence, explain how a computer works to a young child."
 }
 role: "user",
 parts {
   text: "A computer is like a very smart machine that can understand and follow our instructions, help us with our work, and even play games with us!"
 }
 role: "model"]

תוכלו להמשיך לשלוח הודעות כדי להמשיך את השיחה. צריך להשתמש בארגומנט stream=True כדי לשדר את הצ'אט:

response = chat.send_message("Okay, how about a more detailed explanation to a high schooler?", stream=True)

for chunk in response:
  print(chunk.text)
  print("_"*80)
A computer works by following instructions, called a program, which tells it what to
________________________________________________________________________________
 do. These instructions are written in a special language that the computer can understand, and they are stored in the computer's memory. The computer's processor
________________________________________________________________________________
, or CPU, reads the instructions from memory and carries them out, performing calculations and making decisions based on the program's logic. The results of these calculations and decisions are then displayed on the computer's screen or stored in memory for later use.

To give you a simple analogy, imagine a computer as a
________________________________________________________________________________
 chef following a recipe. The recipe is like the program, and the chef's actions are like the instructions the computer follows. The chef reads the recipe (the program) and performs actions like gathering ingredients (fetching data from memory), mixing them together (performing calculations), and cooking them (processing data). The final dish (the output) is then presented on a plate (the computer screen).

In summary, a computer works by executing a series of instructions, stored in its memory, to perform calculations, make decisions, and display or store the results.
________________________________________________________________________________

glm.Content אובייקטים מכילים רשימה של glm.Part אובייקטים שכל אחד מהם מכיל טקסט (string) או inline_data (glm.Blob), כאשר blob מכיל נתונים בינאריים ו-mime_type. היסטוריית הצ'אט זמינה כרשימה של glm.Content אובייקטים ב-ChatSession.history:

for message in chat.history:
  display(to_markdown(f'**{message.role}**: {message.parts[0].text}'))

user: במשפט אחד, עליכם להסביר איך מחשב פועל לילדים קטנים.

model מחשב הוא כמו מכונה חכמה מאוד שיכולה להבין את ההוראות שלנו ולפעול לפיהן, לעזור לנו בעבודה ואפילו לשחק איתנו במשחקים!

user: אוקיי, אולי תקבלו הסבר מפורט יותר לתלמיד/ה בתיכון?

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

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

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

ספירת אסימונים

למודלים גדולים של שפה יש חלון הקשר, ואורך ההקשר נמדד בדרך כלל מבחינת מספר האסימונים. באמצעות Gemini API אפשר לקבוע את מספר האסימונים לכל אובייקט genai.protos.Content. במקרה הפשוט ביותר, אפשר להעביר מחרוזת שאילתה לשיטה GenerativeModel.count_tokens באופן הבא:

model.count_tokens("What is the meaning of life?")
total_tokens: 7

באופן דומה, אפשר לחפש את ChatSession ב-token_count:

model.count_tokens(chat.history)
total_tokens: 501

שימוש בהטמעות

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

משתמשים בשיטה embed_content כדי ליצור הטמעות. השיטה מטפלת בהטמעה למשימות הבאות (task_type):

סוג המשימה תיאור
RETRIEVAL_QUERY מציינת שהטקסט הנתון הוא שאילתה בהגדרת חיפוש/אחזור.
RETRIEVAL_DOCUMENT מציינת שהטקסט הנתון הוא מסמך בהגדרת חיפוש/אחזור. כדי להשתמש במשימה הזו צריך title.
SEMANTIC_SIMILARITY מציינת שהטקסט הנתון ישמש לדמיון סמנטי (STS).
סיווג מציינת שההטמעות ישמשו לסיווג.
אשכול מציינת שההטמעות ישמשו לקיבוץ לאשכולות.

הפקודה הבאה יוצרת הטמעה למחרוזת יחידה לאחזור מסמכים:

result = genai.embed_content(
    model="models/embedding-001",
    content="What is the meaning of life?",
    task_type="retrieval_document",
    title="Embedding of single string")

# 1 input > 1 vector output
print(str(result['embedding'])[:50], '... TRIMMED]')
[-0.003216741, -0.013358698, -0.017649598, -0.0091 ... TRIMMED]

כדי לטפל בקבוצות של מחרוזות, צריך להעביר רשימת מחרוזות ב-content:

result = genai.embed_content(
    model="models/embedding-001",
    content=[
      'What is the meaning of life?',
      'How much wood would a woodchuck chuck?',
      'How does the brain work?'],
    task_type="retrieval_document",
    title="Embedding of list of strings")

# A list of inputs > A list of vectors output
for v in result['embedding']:
  print(str(v)[:50], '... TRIMMED ...')
[0.0040260437, 0.004124458, -0.014209415, -0.00183 ... TRIMMED ...
[-0.004049845, -0.0075574904, -0.0073463684, -0.03 ... TRIMMED ...
[0.025310587, -0.0080734305, -0.029902633, 0.01160 ... TRIMMED ...

הפונקציה genai.embed_content מקבלת מחרוזות או רשימות של מחרוזות, אבל למעשה היא נבנית סביב הסוג genai.protos.Content (כמו GenerativeModel.generate_content). אובייקטים מסוג glm.Content הם היחידות העיקריות של שיחה ב-API.

האובייקט genai.protos.Content הוא מרובה מצבים, אבל השיטה embed_content תומכת רק בהטמעות טקסט. העיצוב הזה נותן ל-API את האפשרות להתרחב להטמעות מרובות מצבים.

response.candidates[0].content
parts {
  text: "A computer works by following instructions, called a program, which tells it what to do. These instructions are written in a special language that the computer can understand, and they are stored in the computer\'s memory. The computer\'s processor, or CPU, reads the instructions from memory and carries them out, performing calculations and making decisions based on the program\'s logic. The results of these calculations and decisions are then displayed on the computer\'s screen or stored in memory for later use.\n\nTo give you a simple analogy, imagine a computer as a chef following a recipe. The recipe is like the program, and the chef\'s actions are like the instructions the computer follows. The chef reads the recipe (the program) and performs actions like gathering ingredients (fetching data from memory), mixing them together (performing calculations), and cooking them (processing data). The final dish (the output) is then presented on a plate (the computer screen).\n\nIn summary, a computer works by executing a series of instructions, stored in its memory, to perform calculations, make decisions, and display or store the results."
}
role: "model"
result = genai.embed_content(
    model = 'models/embedding-001',
    content = response.candidates[0].content)

# 1 input > 1 vector output
print(str(result['embedding'])[:50], '... TRIMMED ...')
[-0.013921871, -0.03504407, -0.0051786783, 0.03113 ... TRIMMED ...

באופן דומה, היסטוריית הצ'אט מכילה רשימה של genai.protos.Content אובייקטים, שאותה אפשר להעביר ישירות לפונקציה embed_content:

chat.history
[parts {
   text: "In one sentence, explain how a computer works to a young child."
 }
 role: "user",
 parts {
   text: "A computer is like a very smart machine that can understand and follow our instructions, help us with our work, and even play games with us!"
 }
 role: "model",
 parts {
   text: "Okay, how about a more detailed explanation to a high schooler?"
 }
 role: "user",
 parts {
   text: "A computer works by following instructions, called a program, which tells it what to do. These instructions are written in a special language that the computer can understand, and they are stored in the computer\'s memory. The computer\'s processor, or CPU, reads the instructions from memory and carries them out, performing calculations and making decisions based on the program\'s logic. The results of these calculations and decisions are then displayed on the computer\'s screen or stored in memory for later use.\n\nTo give you a simple analogy, imagine a computer as a chef following a recipe. The recipe is like the program, and the chef\'s actions are like the instructions the computer follows. The chef reads the recipe (the program) and performs actions like gathering ingredients (fetching data from memory), mixing them together (performing calculations), and cooking them (processing data). The final dish (the output) is then presented on a plate (the computer screen).\n\nIn summary, a computer works by executing a series of instructions, stored in its memory, to perform calculations, make decisions, and display or store the results."
 }
 role: "model"]
result = genai.embed_content(
    model = 'models/embedding-001',
    content = chat.history)

# 1 input > 1 vector output
for i,v in enumerate(result['embedding']):
  print(str(v)[:50], '... TRIMMED...')
[-0.014632266, -0.042202696, -0.015757175, 0.01548 ... TRIMMED...
[-0.010979066, -0.024494737, 0.0092659835, 0.00803 ... TRIMMED...
[-0.010055617, -0.07208932, -0.00011750793, -0.023 ... TRIMMED...
[-0.013921871, -0.03504407, -0.0051786783, 0.03113 ... TRIMMED...

תרחישים מתקדמים לדוגמה

בקטעים הבאים נדון בתרחישים מתקדמים ובפרטים ברמה נמוכה יותר של Python SDK ל-Gemini API.

הגדרות בטיחות

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

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

response = model.generate_content('[Questionable prompt here]')
response.candidates
[content {
  parts {
    text: "I\'m sorry, but this prompt involves a sensitive topic and I\'m not allowed to generate responses that are potentially harmful or inappropriate."
  }
  role: "model"
}
finish_reason: STOP
index: 0
safety_ratings {
  category: HARM_CATEGORY_SEXUALLY_EXPLICIT
  probability: NEGLIGIBLE
}
safety_ratings {
  category: HARM_CATEGORY_HATE_SPEECH
  probability: NEGLIGIBLE
}
safety_ratings {
  category: HARM_CATEGORY_HARASSMENT
  probability: NEGLIGIBLE
}
safety_ratings {
  category: HARM_CATEGORY_DANGEROUS_CONTENT
  probability: NEGLIGIBLE
}
]

ב-prompt_feedback יצוין איזה מסנן בטיחות חסם את ההצעה לפעולה:

response.prompt_feedback
safety_ratings {
  category: HARM_CATEGORY_SEXUALLY_EXPLICIT
  probability: NEGLIGIBLE
}
safety_ratings {
  category: HARM_CATEGORY_HATE_SPEECH
  probability: NEGLIGIBLE
}
safety_ratings {
  category: HARM_CATEGORY_HARASSMENT
  probability: NEGLIGIBLE
}
safety_ratings {
  category: HARM_CATEGORY_DANGEROUS_CONTENT
  probability: NEGLIGIBLE
}

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

response = model.generate_content('[Questionable prompt here]',
                                  safety_settings={'HARASSMENT':'block_none'})
response.text

חשוב גם שלכל מועמד יש safety_ratings משלו, למקרה שההנחיה עוברת בהצלחה אבל התשובות האישיות נכשלות בבדיקות הבטיחות.

קידוד הודעות

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

ערכת ה-SDK מנסה להמיר את ההודעה לאובייקט genai.protos.Content. האובייקט מכיל רשימה של genai.protos.Part אובייקטים שכל אחד מהם מכיל:

  1. text (מחרוזת)
  2. inline_data (genai.protos.Blob), כאשר blob מכיל data ו-mime_type בינארי.
  3. או סוגים אחרים של נתונים.

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

כך, המקבילה המקבילה בהקלדה המלאה לדוגמה הקודמת היא:

model = genai.GenerativeModel('gemini-1.5-flash')
response = model.generate_content(
    genai.protos.Content(
        parts = [
            genai.protos.Part(text="Write a short, engaging blog post based on this picture."),
            genai.protos.Part(
                inline_data=genai.protos.Blob(
                    mime_type='image/jpeg',
                    data=pathlib.Path('image.jpg').read_bytes()
                )
            ),
        ],
    ),
    stream=True)
response.resolve()

to_markdown(response.text[:100] + "... [TRIMMED] ...")

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

שיחות מרובות תורות

הכיתה genai.ChatSession שהוצגה קודם יכולה לטפל בתרחישים רבים לדוגמה, אבל היא מניחה כמה הנחות. אם התרחיש לדוגמה שלך לא מתאים להטמעה של הצ'אט הזה, כדאי לזכור ש-genai.ChatSession הוא רק wrapper של GenerativeModel.generate_content. בנוסף לבקשות בודדות, האפליקציה יכולה לטפל בשיחות מרובות תורות.

ההודעות הנפרדות הן אובייקטים מסוג genai.protos.Content או מילונים תואמים, כמו שאפשר לראות בקטעים הקודמים. כמילון, להודעה דרושות role ו-parts. role בשיחה יכול להיות user שמספק את ההנחיות, או model שמספק את התשובות.

מעבירים רשימה של genai.protos.Content אובייקטים, והמערכת תתייחס אליה כאל צ'אט עם מספר פניות:

model = genai.GenerativeModel('gemini-1.5-flash')

messages = [
    {'role':'user',
     'parts': ["Briefly explain how a computer works to a young child."]}
]
response = model.generate_content(messages)

to_markdown(response.text)

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

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

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

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

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

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

וכשרוצים להתחבר לאינטרנט כדי לשחק במשחקים עם חברים או לצפות בסרטונים מצחיקים, המחשב משתמש במכשיר שנקרא 'כרטיס רשת' כדי לשלוח ולקבל הודעות באמצעות כבלי האינטרנט או אותות Wi-Fi.

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

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

messages.append({'role':'model',
                 'parts':[response.text]})

messages.append({'role':'user',
                 'parts':["Okay, how about a more detailed explanation to a high school student?"]})

response = model.generate_content(messages)

to_markdown(response.text)

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

‫1. מעבד (CPU): - המוח של המחשב. - מבצע הוראות ומבצע חישובים. - המהירות נמדדת בגיגה-הרץ (GHz). - בדרך כלל, המשמעות של יותר GHz היא עיבוד מהיר יותר.

‫2. זיכרון (RAM): - אחסון זמני לנתונים שנמצאים בעיבוד. - מכיל הוראות ונתונים בזמן שהתוכנית פועלת. - נמדד בג'יגה-בייט (GB). - נפח זיכרון RAM גדול יותר מאפשר הצגת יותר תוכניות בו-זמנית.

‫3. אחסון (HDD/SSD): - אחסון קבוע לנתונים. - אחסון של מערכת ההפעלה, התוכנות וקובצי המשתמש. - נמדד בג'יגה-בייט (GB) או טרה-בייט (TB). - כונני דיסקים קשיחים (HDD) הם מסורתיים, איטיים יותר וזולים יותר. - כונני SSD חדשים, מהירים יותר ויקרים יותר.

4. כרטיס גרפי (GPU): - מעבד ומציג תמונות. - חיוני לגיימינג, לעריכת סרטונים ולמשימות אחרות שצורכות הרבה גרפיקה. - נמדדות ב-RAM של הסרטון (VRAM) ובמהירות השעון.

5. לוח אם: - מחבר את כל הרכיבים. - מספק חשמל ותקשורת.

‫6. מכשירי קלט/פלט (I/O): - המשתמשים יכולים ליצור אינטראקציה עם המחשב. - דוגמאות: מקלדת, עכבר, מסך, מדפסת.

7. מערכת הפעלה (OS): - תוכנה שמנהלת את משאבי המחשב. - מספקת ממשק משתמש ופונקציונליות בסיסית. - דוגמאות: Windows, macOS, Linux.

כאשר מפעילים תוכנה במחשב, הדברים הבאים קורים:

  1. הוראות התוכנית נטענות מהזיכרון לזיכרון.
  2. המעבד קורא את ההוראות מהזיכרון ומבצע אותן אחת אחרי השנייה.
  3. אם ההוראה כוללת חישובים, המעבד מבצע אותם באמצעות היחידה הלוגית האריתמטית (ALU).
  4. אם ההוראה כוללת נתונים, המעבד קורא או כותב בזיכרון.
  5. התוצאות של החישובים או של המניפולציה בנתונים מאוחסנות בזיכרון.
  6. אם התוכנית צריכה להציג משהו על המסך, היא שולחת את הנתונים הדרושים לכרטיס הגרפי.
  7. הכרטיס הגרפי מעבד את הנתונים ושולח אותם לצג, שמציג אותם.

התהליך הזה נמשך עד שהתוכנית מסיימת את המשימה או שהמשתמש מסיים אותה.

הגדרת היצירה

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

model = genai.GenerativeModel('gemini-1.5-flash')
response = model.generate_content(
    'Tell me a story about a magic backpack.',
    generation_config=genai.types.GenerationConfig(
        # Only one candidate for now.
        candidate_count=1,
        stop_sequences=['x'],
        max_output_tokens=20,
        temperature=1.0)
)
text = response.text

if response.candidates[0].finish_reason.name == "MAX_TOKENS":
    text += '...'

to_markdown(text)

פעם, בעיירה קטנה ששוכנת בין גבעות ירוקות מוריקות, חיה נערה צעירה בשם...

מה עושים אחר כך

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