תחילת העבודה עם Gemini API: Python

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

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

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

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

אפשר להריץ את המדריך למתחילים ב-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-pro: בוצעה אופטימיזציה להנחיות טקסט בלבד.
  • gemini-pro-vision: בוצעה אופטימיזציה להנחיות טקסט ותמונות.
for m in genai.list_models():
  if 'generateContent' in m.supported_generation_methods:
    print(m.name)

החבילה של genai תומכת גם במשפחת המודלים של PaLM, אבל רק דגמי Gemini תומכים ביכולות הכלליות וריבוי המודלים של שיטת generateContent.

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

להנחיות טקסט בלבד, משתמשים במודל gemini-pro:

model = genai.GenerativeModel('gemini-pro')

השיטה 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

במקרים פשוטים, כל מה שצריך הוא רכיב הגישה 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-pro-vision) שמקבל גם טקסט וגם תמונות וגם קלט. ה-API 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-pro-vision ולהעביר את התמונה למודל באמצעות generate_content.

model = genai.GenerativeModel('gemini-pro-vision')
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-pro')
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 אובייקטים שכל אחד מהם מכיל טקסט (מחרוזת) או 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}'))

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

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

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

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

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

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

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

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

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

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

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 מקבלת מחרוזות פשוטות או רשימות של מחרוזות, אבל למעשה היא מבוססת על הסוג glm.Content (כמו GenerativeModel.generate_content). אובייקטים מסוג glm.Content הם יחידות השיחה הראשיות ב-API.

אמנם האובייקט glm.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 ...

באופן דומה, היסטוריית הצ'אט מכילה רשימה של אובייקטים של glm.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 מקודד הודעות.

הבסיס ל-Python SDK הוא ספריית הלקוח google.ai.generativelanguage:

import google.ai.generativelanguage as glm

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

  1. a text (מחרוזת)
  2. inline_data (glm.Blob), כאשר blob מכיל data ו-mime_type.

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

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

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

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

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

שיחות עם פניות מרובות

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

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

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

model = genai.GenerativeModel('gemini-pro')

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). - יותר 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-pro')
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.
  • ב-Gemini יש אפשרויות נוספות לשליחת בקשות להגדלה של מגבלת הקצב של יצירת בקשות. מגבלת הקצב של יצירת הבקשות בדגמים של Gemini-Pro היא 60 בקשות לדקה (RPM).