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 表格数据。本部分重点介绍如何从 Google 表格读取数据;后面的部分介绍了如何将输出写入 Google 表格。

登录并授予 Google 表格访问权限

设置电子表格的格式以便使用 PaLM 魔法

将 Google 表格的 ID 或网址传递给 --sheets_input_names 标志即可将其加载为模板数据。

在电子表格中使用以下格式,以便在提示模板中使用相应数据:

  1. 将(提示模板)的变量名称放在工作表的第一行。
  2. 在下面的行中输入要替换每个变量的数据。

例如,如果您的提示模板有两个要替换的变量(nametemperament),则应按如下方式编写电子表格:

name 性情
Milo 厚脸皮
Bigsly 放松
苏布拉 害羞
%%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 中调用的函数。

所有标记和后期处理都会“编译”到函数中,并在调用时使用。

在此示例中,使用 before 中的 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。不过,您可以分别使用 .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() 方法。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 模型

您还可以使用 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 时,使用原始模型输出来计算单词数。如果将它们交换,单词数将改为提取的第一个句子中的单词数量。

深入阅读