קסם של Colab

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

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

הגדרה

פועלים לפי השלבים הבאים כדי להתקין ולבדוק את הקסם.

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

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

%pip install -q google-generativeai

מגלים את הקסם של PaLM

עכשיו אפשר לטעון את %%palm בעזרת הקסם של %load_ext:

%load_ext google.generativeai.notebook

בדיקת ההתקנה

כדי לבדוק אם פקודות הקסם מותקנות כראוי, מריצים את %%palm --help. לתשומת ליבכם, אם עדיין אין לכם מפתח PaLM API, תצטרכו להשתמש במפתח 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

קבלת מפתח API של PaLM

כדי להשתמש ב-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, צריך לכתוב את הגיליון האלקטרוני כך:

שם מזג
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:

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

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

פונקציות לאחר עיבוד מאפשרות להגדיר פונקציה שמעבדת את הפלט של המודל. במקרה של הפקודה 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 שהוגדרה למעלה תיקח את הפלט מהמודל ותקצר צמדי שפות חוזרים, ותשאיר רק את התגובה הראשונה. מידע נוסף על עיבוד לאחר עיבוד (post-processing) זמין בקטע עיבוד לאחר עיבוד.

%%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.

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

בדוגמה הזו, נוצרת פונקציה בשם 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

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

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

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

קריאה נוספת