Colab 魔術

這個筆記本介紹了適用於 PaLM 的 Colab 魔術指令。您可以運用 Magics 輕鬆在 Colab 筆記本中開發、測試、比較和評估提示。

前往 ai.google.dev 查看 在 Google Colab 中執行 前往 GitHub 查看原始碼

設定

請按照下列步驟安裝並測試魔術效果。

安裝 PaLM 魔術

如要在 Colab 或其他 IPython 環境中使用 PaLM 魔法指令,請先下載並安裝 google-generativeai Python 套件。

%pip install -q google-generativeai

載入 PaLM 的魔法

接著,使用 %load_ext 神奇指令載入 %%palm 魔術:

%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 金鑰

執行下列儲存格來設定 API 金鑰。

%env GOOGLE_API_KEY=YOUR PALM KEY

PaLM 魔術指令:runcompilecompareevaluate

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 資料欄則顯示結果。本指南將在您瀏覽本指南時加入其他資料欄。

提示範本

提示不必是固定字串。您可以使用 {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 欄會追蹤清單中的輸入字詞索引。於 這些範例,0Input Num'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 試算表讀取資料

PaLM 的神奇指令也能讀取及寫入 Google 試算表。你需要登入才能存取試算表資料。本節著重說明如何讀取試算表中的資料。下一節說明如何將輸出內容寫入 Google 試算表。

登入並授權存取試算表

設定試算表格式以搭配 PaLM 魔術使用

將 Google 試算表的 ID 或網址傳遞至 --sheets_input_names 旗標,即可載入試算表做為範本資料。

在試算表中使用下列格式,在提示範本中使用這些資料:

  1. 將變數名稱 (提示範本) 的名稱置於工作表的第一列。
  2. 將資料替換成以下資料列中每個變數的資料。

舉例來說,如果提示範本有兩個要替換的變數 (nametemperament),請編寫如下所示的試算表:

名稱 性情
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.

你自己試試看!

如要試用自己的資料,請建立新試算表,並將 ID 傳遞至 --sheets_input_names。除了 ID 和網址之外,您也可以使用標題來搜尋工作表,例如:%%palm --sheets_input_names "Animal adjectives"

結合 Google 試算表輸入與 Python 輸入內容

試算表輸入內容也可以與 --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 指令,將含有預留位置的提示轉換為可在 Python 中呼叫的函式。

所有標記和後續處理作業皆「編譯」中,並會在叫用時使用。

在這個範例中,系統會使用 beforeextract_and_normalize 後處理函式,建立名稱為 translate_en_to_fr 的函式。

%%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 的形式顯示。不過,您可以分別使用 .as_dict().as_dataframe() 將結果物件轉換為 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() 方法,瞭解如何擷取支援的模型。任何支援 generateText 方法的模型都能使用 PaLM 魔術。

%%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 模型

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 DataFrame。您可呼叫 as_dict()as_pandas_dataframe(),明確將這些變數強制轉換為 Python 字典或 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_output_names 將輸出內容儲存回 Google 試算表。您必須登入,且須有適當權限才能存取不公開的試算表。

如要試用這項功能,請建立新試算表,並命名為 Translation results。與輸入旗標一樣,--sheets_output_names 旗標也接受工作表網址或 ID 來取代文字名稱。

%%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 是最後一欄,供 evalcompare 指令使用決定最終輸出結果。

以下是一些後續處理適用的函式範例。其中一個會新增資料欄,另一個則使用 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 時,系統會使用原始模型輸出內容計算字詞數。如果您替換這些條件,則字詞計數會取代擷取的第一個句子中的字詞數。

延伸閱讀