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 表格访问权限

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

设置电子表格的格式,以便与 PaLM 魔法命令搭配使用

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

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

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

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

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 和网址,您还可以按标题搜索工作表,如%%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 中调用的函数。

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

在此示例中,使用之前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 时,系统将使用原始模型输出来计算字词数。如果您换用这些词汇,则单词数将是提取的第一个句子中的单词数。

深入阅读