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 マジックには、次の 4 つのコマンドがあります。

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

コマンド: palm run

run コマンドは、セルの内容をモデルに送信します。

プロンプトの実行は非常に一般的であるため、コマンドが指定されていない場合、PaLM マジックはデフォルトで run コマンドを実行します。たとえば、次の 2 つのセルは同じです。

%%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 スプレッドシートに書き込む方法については、後のセクションで説明します。

ログインしてスプレッドシートへのアクセスを承認

<ph type="x-smartling-placeholder">

PaLM のマジックで使用するためにスプレッドシートをフォーマットする

Google スプレッドシートの ID または URL を --sheets_input_names フラグに渡して、テンプレート データとして読み込みます。

プロンプト テンプレートでデータを使用するには、スプレッドシートで次の形式を使用します。

  1. シートの最初の行に(プロンプト テンプレートの)変数名を入力します。
  2. 各変数に代入するデータを各行に入力します。

たとえば、プロンプト テンプレートに nametemperament という 2 つの変数を置き換える場合、スプレッドシートを次のように記述します。

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.

実際に試してみましょう。

自分のデータを使ってこれを試すには、新しいスプレッドシートを作成し、ID を --sheets_input_names に渡します。ID と URL だけでなく、タイトルでシートを検索することもできます(例:%%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})

出力形式

デフォルトでは、「compiled」関数は、その出力を 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 フラグを使用して 1 つ以上のカスタム関数を指定できます。

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 DataFrame として表示されるカスタム オブジェクトです。as_dict() または as_pandas_dataframe() を呼び出すことで、明示的に Python 辞書またはデータフレームに強制変換できます。

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 フラグもテキスト名の代わりにシートの URL または ID を受け入れます。

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

結果は新しいタブに保存され、ここに Colab で表示されるものと同じデータが含まれます。

保存したシートの例

複数の候補の生成

1 つのプロンプトに対して複数の出力を生成するには、--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 コマンドで最終出力を決定するために使用されます。

後処理で使用するサンプル関数の例を次に示します。1 つは新しい列を追加し、もう 1 つは 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 が呼び出されると、元のモデル出力を使用して単語数が計算されます。これらを入れ替えると、単語カウントは抽出された最初の文の単語数になります。

関連情報