Colab 魔術

這個筆記本介紹了 PaLM 的 Colab 神奇指令。在 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 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 試算表讀取資料,後續章節將說明如何將輸出內容寫入 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"

結合試算表輸入內容與 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 中呼叫的函式。

所有標記和後續處理都會「編譯」到函式中,並在叫用時使用。

在這個範例中,會使用 之前extract_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。不過,您可以將結果物件分別轉換為 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() 方法,瞭解如何擷取支援的模型。所有支援 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 時,系統會使用原始模型輸出內容計算字詞數。如果替換這些內容,字詞計數會改為擷取的第一句話中的字詞數量。

其他資訊