קסם של Colab

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

לצפייה ב-ai.google.dev הפעלה ב-Google Colab הצגת המקור ב-GitHub

הגדרה

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

התקנת הקסם של PaLM

כדי להשתמש בפקודות הקסם של PaLM ב-Colab או בסביבת IPython אחרת, קודם צריך להוריד ולהתקין את google-generativeai חבילת Python.

%pip install -q google-generativeai

טעינת הקסם של PaLM

בשלב הבא, טוען את הקסם של %%palm באמצעות הקסם %load_ext:

%load_ext google.generativeai.notebook

בדיקת ההתקנה

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

%%palm --help
usage: palm [-h] {run,compile,compare,eval} ...

A system for interacting with LLMs.

positional arguments:
  {run,compile,compare,eval}

options:
  -h, --help            show this help message and exit

קבלת מפתח PaLM API

כדי להשתמש ב-PaLM API, תצטרכו ליצור מפתח API. (צריך לבצע את השלב הזה רק פעם אחת).

הגדרה של מפתח ה-API ב-notebook

כדי להגדיר את מפתח ה-API, מריצים את התא שלמטה.

%env GOOGLE_API_KEY=YOUR PALM KEY

פקודות הקסם של PaLM: run, compile, compare ו-evaluate

הקסמים של PaLM מספקים ארבע פקודות שונות:

  1. run
  2. compile
  3. compare
  4. evaluate

פקודה: palm run

הפקודה run שולחת את תוכן התא למודל.

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

%%palm run
The opposite of hot is
%%palm
The opposite of hot is

הבנת הפלט

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

תבניות של הצעות לפעולות

הנחיות לא חייבות להיות מחרוזות קבועות. אפשר להחדיר ערכים להנחיה באמצעות placeholders של תבניות באמצעות {curly braces}.

english_words = {
    # Each value here (hot, cold) will be substituted in for {word} in the prompt
    'word': ['hot', 'cold']
}
%%palm --inputs english_words
The opposite of {word} is

הבנת הפלט

העמודה Input Num עוקבת אחר האינדקס של מילת הקלט ברשימות. בדוגמאות האלה, הערך Input Num של 0 הוא 'hot' ו-1 הוא 'cold'.

ציון קבוצות מרובות של ערכי קלט

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

extreme_temperatures = {
    'word': ['hot', 'cold']
}
minor_temperatures = {
    'word': ['warm', 'chilly']
}
%%palm --inputs extreme_temperatures minor_temperatures
The opposite of {word} is

קריאת נתונים מ-Google Sheets

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

נכנסים ל-Sheets ומאשרים גישה

עיצוב גיליון אלקטרוני לשימוש עם הקסם של PaLM

מעבירים את המזהה או כתובת ה-URL של גיליון אלקטרוני ב-Google Sheets אל הדגל --sheets_input_names כדי לטעון אותו כנתוני תבנית.

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

  1. מזינים את שמות המשתנים (של תבנית ההנחיות) בשורה הראשונה בגיליון.
  2. בשורות הבאות, מזינים את הנתונים כתחליף לכל משתנה.

לדוגמה, אם בתבנית ההנחיות יש שני משתנים להחלפה, name ו-temperament, הגיליון האלקטרוני צריך להיכתב כך:

name מזג
Milo שובב
גדול מאוד רגוע
סוברה ביישן
%%palm --sheets_input_names https://docs.google.com/spreadsheets/d/1UHfpkmBqIX5RjeJcGXOevIEhMmEoKlf5f9teqwQyHqc/edit
Create a single sentence description of a monkey's personality. The monkey's name is {name} and it has a {temperament} temperament.

רוצה לנסות?

כדי לנסות את התכונה באמצעות נתונים משלכם, צריך ליצור גיליון חדש ולהעביר את המזהה אל --sheets_input_names. בנוסף למזהה ולכתובת ה-URL, אפשר גם לחפש בגיליונות לפי כותרת, למשל %%palm --sheets_input_names "Animal adjectives".

שילוב קלט ב-Sheets עם קלט Python

אפשר לשלב גם ערכי קלט ב-Sheets עם --inputs:

new_monkeys = {
    'name': ['Hackerella'],
    'temperament': ['clever'],
}
%%palm --inputs new_monkeys --sheets_input_names 1UHfpkmBqIX5RjeJcGXOevIEhMmEoKlf5f9teqwQyHqc 1UHfpkmBqIX5RjeJcGXOevIEhMmEoKlf5f9teqwQyHqc
Create a single sentence description of a monkey's personality. The monkey's name is {name} and it has a {temperament} temperament.

פקודה: palm eval

אפשר להשתמש ב-%%palm eval כדי להשוות בין הפלט של הנחיה לבין נתוני קרקע ידועים.

test_data = {
    "word": ["dog", "cat", "house"]
}
ground_truth = ["chien", "chat", "maison"]
%%palm eval --inputs test_data --ground_truth ground_truth
English: Hello
French: Bonjour
English: {word}
French:

הפלט של המודל לאחר עיבוד

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

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

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

from google.generativeai.notebook import magics

# Define a function to extract only the first response.
@magics.post_process_replace_fn
def extract_and_normalize(input):
  first_line, *unused = input.split('English:')
  return first_line.strip().lower()

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

%%palm eval --inputs test_data --ground_truth ground_truth | extract_and_normalize
English: Hello
French: Bonjour
English: {word}
French:

פקודה: palm compile

משתמשים בפקודה %%palm compile כדי להמיר הנחיה עם placeholders לפונקציה שניתן לקרוא מתוך Python.

כל הסימונים והעיבוד אחרי העיבוד עוברים הידור (compile) בפונקציה וייעשה בהם שימוש כשמפעילים אותם.

בדוגמה הזו, נוצרת פונקציה שנקראת translate_en_to_fr באמצעות הפונקציה extract_and_normalize שאחרי העיבוד, שמתוארת before.

%%palm compile translate_en_to_fr | extract_and_normalize
English: Hello
French: Bonjour
English: {word}
French:
'Saved function to Python variable: translate_en_to_fr'
en_words = ['cat', 'dog']
translate_en_to_fr({'word': en_words})

פורמטים של פלט

כברירת מחדל, פונקציית 'הידור' מחזירה את הפלט שלה כאובייקט שיוצג כ-Pandas DataFrame. עם זאת, ניתן להמיר את אובייקט התוצאות ל-DataFrame או למילון באמצעות .as_dict() או .as_dataframe(), בהתאמה.

למידע נוסף, ניתן לעיין בדגל --outputs.

results = translate_en_to_fr({'word': en_words}).as_dict()

fr_words = results['text_result']

for en, fr in zip(en_words, fr_words):
  print(f'{fr} is French for {en}')
chat is French for cat
chien is French for dog

פקודה: palm compare

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

%%palm compile few_shot_prompt
English: Hello
French: Bonjour
English: {word}
French:
'Saved function to Python variable: few_shot_prompt'
%%palm compile zero_shot_prompt
{word} translated to French is:
'Saved function to Python variable: zero_shot_prompt'
words = {
    "word": ["dog", "cat", "house"]
}
%%palm compare few_shot_prompt zero_shot_prompt --inputs words

פונקציות השוואה בהתאמה אישית

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

def average_word_length(lhs, rhs):
  """Count the average number of words used across prompts."""
  return (len(lhs.split(' ')) + len(rhs.split(' '))) / 2

def shortest_answer(lhs, rhs):
  """Label the prompt that generated the shortest output."""
  if len(lhs) < len(rhs):
    return 'first'
  elif len(lhs) > len(rhs):
    return 'second'
  else:
    return 'same'
%%palm compare few_shot_prompt zero_shot_prompt --inputs words --compare_fn average_word_length shortest_answer

פקודות אחרות

עזרה

הדגל --help מציג את הפקודות הנתמכות שאפשר להעביר ישירות אל %%palm

אפשר להוסיף את --help כדי לראות את התיעוד המפורט של כל פקודה. לדוגמה,

%%palm run --help
usage: palm run [-h] [--model_type {echo,text}] [--temperature TEMPERATURE]
                [--model MODEL] [--candidate_count CANDIDATE_COUNT] [--unique]
                [--inputs INPUTS [INPUTS ...]]
                [--sheets_input_names SHEETS_INPUT_NAMES [SHEETS_INPUT_NAMES ...]]
                [--outputs OUTPUTS [OUTPUTS ...]]
                [--sheets_output_names SHEETS_OUTPUT_NAMES [SHEETS_OUTPUT_NAMES ...]]

options:
  -h, --help            show this help message and exit
  --model_type {echo,text}, -mt {echo,text}
                        The type of model to use.
  --temperature TEMPERATURE, -t TEMPERATURE
                        Controls the randomness of the output. Must be
                        positive. Typical values are in the range: [0.0, 1.0].
                        Higher values produce a more random and varied
                        response. A temperature of zero will be deterministic.
  --model MODEL, -m MODEL
                        The name of the model to use. If not provided, a
                        default model will be used.
  --candidate_count CANDIDATE_COUNT, -cc CANDIDATE_COUNT
                        The number of candidates to produce.
  --unique              Whether to dedupe candidates returned by the model.
  --inputs INPUTS [INPUTS ...], -i INPUTS [INPUTS ...]
                        Optional names of Python variables containing inputs
                        to use to instantiate a prompt. The variable must be
                        either: a dictionary {'key1': ['val1', 'val2'] ...},
                        or an instance of LLMFnInputsSource such as
                        SheetsInput.
  --sheets_input_names SHEETS_INPUT_NAMES [SHEETS_INPUT_NAMES ...], -si SHEETS_INPUT_NAMES [SHEETS_INPUT_NAMES ...]
                        Optional names of Google Sheets to read inputs from.
                        This is equivalent to using --inputs with the names of
                        variables that are instances of SheetsInputs, just
                        more convenient to use.
  --outputs OUTPUTS [OUTPUTS ...], -o OUTPUTS [OUTPUTS ...]
                        Optional names of Python variables to output to. If
                        the Python variable has not already been defined, it
                        will be created. If the variable is defined and is an
                        instance of LLMFnOutputsSink, the outputs will be
                        written through the sink's write_outputs() method.
  --sheets_output_names SHEETS_OUTPUT_NAMES [SHEETS_OUTPUT_NAMES ...], -so SHEETS_OUTPUT_NAMES [SHEETS_OUTPUT_NAMES ...]
                        Optional names of Google Sheets to write inputs to.
                        This is equivalent to using --outputs with the names
                        of variables that are instances of SheetsOutputs, just
                        more convenient to use.

דגמים

צריך להשתמש בדגל --model כדי לציין את וריאנט מודל PaLM שבו רוצים להשתמש.

אפשר לעיין בשיטה list_models() כדי לאחזר את המודלים הנתמכים. אפשר להשתמש בקסם של PaLM עם כל מודל שתומך בשיטת generateText.

%%palm run --model models/text-bison-001
My favourite color is

פרמטרים של מודל

אפשר גם להגדיר פרמטרים של מודל, כמו --candidate_count ו---temperature.

%%palm run --model models/text-bison-001 --temperature 0.5
My favourite color is

ניפוי באגים: מודל ההד

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

%%palm --model_type echo
A duck's quack does not echo.

ייצוא פלט ל-Python

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

בדוגמה הזו, הפלט נשמר במשתנה Python: fave_colors

%%palm --outputs fave_colors
The best colors to wear in spring-time are

משתני פלט הם אובייקטים מותאמים אישית שיוצגו כברירת מחדל כסימן DataFrames מסוג Pandas. אפשר להפוך אותם למילון Python או למסגרת נתונים מפורשת על ידי קריאה ל-as_dict() או as_pandas_dataframe().

from pprint import pprint

pprint(fave_colors.as_dict())
{'Input Num': [0],
 'Prompt': ['The best colors to wear in spring-time are'],
 'Prompt Num': [0],
 'Result Num': [0],
 'text_result': ['* Pastels: These soft, muted colors are perfect for the '
                 'springtime, as they are fresh and airy. Some popular pastel '
                 'colors include baby blue, mint green, and pale pink.\n'
                 '* Brights: If you want to make a statement, bright colors '
                 'are a great option for spring. Some popular bright colors '
                 'include fuchsia, cobalt blue, and yellow.\n'
                 '* Neutrals: Neutral colors are always a good choice, as they '
                 'can be easily dressed up or down. Some popular neutrals '
                 'include beige, gray, and white.\n'
                 '\n'
                 'When choosing colors to wear in the spring, it is important '
                 'to consider the occasion and your personal style. For '
                 'example, if you are attending a formal event, you may want '
                 'to choose a more muted color palette, such as pastels or '
                 'neutrals. If you are going for a more casual look, you may '
                 'want to choose brighter colors, such as brights or pastels.']}

כתיבה ב-Google Sheets

אפשר לשמור פלט בחזרה ב-Google Sheets באמצעות --sheets_output_names. אתם צריכים להיות מחוברים לחשבון וצריכה להיות לכם ההרשאות המתאימות כדי לגשת לגיליונות פרטיים.

כדי לנסות את זה, צריך ליצור גיליון חדש ולתת לו את השם Translation results. בדומה לדגל הקלט, הדגל --sheets_output_names מקבל גם את כתובת ה-URL או המזהה של הגיליון במקום שם הטקסט.

%%palm --inputs english_words --sheets_output_names "Translation results"
English: Hello
French: Bonjour
English: {word}
French:

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

דוגמה לגיליון שמור

יצירת מועמדים מרובים

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

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

%%palm run --temperature 1.0 --candidate_count 8 --unique
In a single word, my favourite color is

בעמודה Result Num יש הבחנה בין כמה מועמדים שנבחרו מאותה הנחיה.

הפלט של המודל לאחר עיבוד

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

פונקציות לאחר עיבוד יכולות להוסיף עמודה חדשה לפלט, או לשנות את העמודה text_result. העמודה text_result היא העמודה האחרונה, והיא משמשת את הפקודות eval ו-compare כדי לקבוע את הפלט הסופי.

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

import re
from google.generativeai.notebook import magics

# Add a new column.
def word_count(result):
  return len(result.split(' '))

# Modify the text_result column
@magics.post_process_replace_fn
def extract_first_sentence(result):
  """Extracts the first word from the raw result."""
  first, *_ = re.split(r'\.\s*', result)
  return first

כדי להשתמש בפונקציות האלה, צריך לצרף אותן לפקודה %%palm באמצעות האופרטור Pipe (|), כך.

%%palm run | word_count | extract_first_sentence
The happiest thing I can imagine is

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

קריאה נוספת