prompt-eng-interactive-tutorial 第1章:基础提示结构

anthropics/prompt-eng-interactive-tutorial 翻译

第1章:基础提示结构

环境设置

运行以下设置单元以加载你的 API 密钥并建立 get_completion 辅助函数。


!pip install anthropic

# 导入 Python 内置的正则表达式库
import re
import anthropic

# 从 IPython 存储中获取 API_KEY 和 MODEL_NAME 变量
%store -r API_KEY
%store -r MODEL_NAME

client = anthropic.Anthropic(api_key=API_KEY)

def get_completion(prompt: str, system_prompt=""):
    message = client.messages.create(
        model=MODEL_NAME,
        max_tokens=2000,
        temperature=0.0,
        system=system_prompt,
        messages=[
          {"role": "user", "content": prompt}
        ]
    )
    return message.content[0].text

课程

Anthropic 提供了两种 API,分别是传统的 Text Completions API 和当前主推的 Messages API。本教程将只使用 Messages API。

调用 Claude 的 Messages API 至少需要以下参数:

  • model:你要调用的API模型名称
  • max_tokens:生成的最大 token 数。Claude 可能会提前停止,这只是硬性上限,Claude 可能会在单词或句子中间截断。
  • messages:输入消息数组。模型训练时采用 userassistant 轮流对话。创建新消息时,需用 messages 参数指定之前的对话轮次,模型会生成下一条消息。
    • 每条消息必须包含 rolecontent 字段。可以只给一条 user 消息,也可以多轮(必须交替)。第一条必须是 user

还有一些可选参数,如:

  • system:系统提示(system prompt),详见下文。
  • temperature:Claude 回复的多样性。本教程中 temperature 设为 0。

完整参数列表见 API 文档

示例

下面看看 Claude 对格式正确的提示如何响应。运行每个单元(shift+enter),Claude 的回复会显示在下方。

# 提示
PROMPT = "Hi Claude, how are you?"

# 打印 Claude 的回复
print(get_completion(PROMPT))
# 提示
PROMPT = "Can you tell me the color of the ocean?"

# 打印 Claude 的回复
print(get_completion(PROMPT))
# 提示
PROMPT = "What year was Celine Dion born in?"

# 打印 Claude 的回复
print(get_completion(PROMPT))

现在看看格式错误的例子。Messages API 会报错。

第一个例子:messages 数组缺少 rolecontent 字段。

# 获取 Claude 的回复
response = client.messages.create(
        model=MODEL_NAME,
        max_tokens=2000,
        temperature=0.0,
        messages=[
          {"Hi Claude, how are you?"}
        ]
    )

# 打印 Claude 的回复
print(response[0].text)

还有一个例子:没有交替 userassistant 角色。

# 获取 Claude 的回复
response = client.messages.create(
        model=MODEL_NAME,
        max_tokens=2000,
        temperature=0.0,
        messages=[
          {"role": "user", "content": "What year was Celine Dion born in?"},
          {"role": "user", "content": "Also, can you tell me some other facts about her?"}
        ]
    )

# 打印 Claude 的回复
print(response[0].text)

userassistant 消息必须交替,且必须以 user 开头。你可以模拟多轮对话,也可以让 Claude 从最后一条 assistant 消息继续(后续章节详解)。

系统提示(System Prompts)

你还可以使用系统提示。系统提示用于在用户提问前为 Claude 提供上下文、指令和规则

结构上,系统提示与 user/assistant 消息分开,属于单独的 system 参数(见 环境设置 中的 get_completion)。

本教程中,凡是用到系统提示的地方,都会有 system 字段。若不需要,直接设为空字符串。

系统提示示例

# 系统提示
SYSTEM_PROMPT = "Your answer should always be a series of critical thinking questions that further the conversation (do not provide answers to your questions). Do not actually answer the user question."

# 提示
PROMPT = "Why is the sky blue?"

# 打印 Claude 的回复
print(get_completion(PROMPT, SYSTEM_PROMPT))

为什么用系统提示?写得好的系统提示能提升 Claude 遵守规则和指令的能力。详见官方文档

现在进入练习。如果你想试验本课的提示例子,可以滚动到本课底部的示例游乐场


练习

练习1.1 - 数到三

用正确的 user / assistant 格式,编辑下方 PROMPT,让 Claude 数到三。输出会显示你的答案是否正确。

# Prompt - 只需修改此字段
PROMPT = "[请替换为让 Claude 数到三的英文指令]"

# 获取 Claude 的回复
response = get_completion(PROMPT)

# 判分函数
def grade_exercise(text):
    pattern = re.compile(r'^(?=.*1)(?=.*2)(?=.*3).*$', re.DOTALL)
    return bool(pattern.match(text))

# 打印 Claude 的回复和判分结果
print(response)
print("\n--------------------------- GRADING ---------------------------")
print("This exercise has been correctly solved:", grade_exercise(response))

❓ 想要提示?运行下面的单元!

from hints import exercise_1_1_hint; print(exercise_1_1_hint)

练习1.2 - 系统提示

修改 SYSTEM_PROMPT,让 Claude 像 3 岁小孩一样回答。

# System prompt - 只需修改此字段
SYSTEM_PROMPT = "[请替换为让 Claude 像3岁小孩的英文指令]"

# 提示
PROMPT = "How big is the sky?"

# 获取 Claude 的回复
response = get_completion(PROMPT, SYSTEM_PROMPT)

# 判分函数
def grade_exercise(text):
    return bool(re.search(r"giggles", text) or re.search(r"soo", text))

# 打印 Claude 的回复和判分结果
print(response)
print("\n--------------------------- GRADING ---------------------------")
print("This exercise has been correctly solved:", grade_exercise(response))

❓ 想要提示?运行下面的单元!

from hints import exercise_1_2_hint; print(exercise_1_2_hint)

恭喜!

如果你已经完成了所有练习,可以进入下一章。祝你提示愉快!


示例游乐场

你可以在这里自由试验本课的提示例子,调整提示语,观察 Claude 的不同回复。

# 提示
PROMPT = "Hi Claude, how are you?"

# 打印 Claude 的回复
print(get_completion(PROMPT))
# 提示
PROMPT = "Can you tell me the color of the ocean?"

# 打印 Claude 的回复
print(get_completion(PROMPT))
# 提示
PROMPT = "What year was Celine Dion born in?"

# 打印 Claude 的回复
print(get_completion(PROMPT))
# 获取 Claude 的回复
response = client.messages.create(
        model=MODEL_NAME,
        max_tokens=2000,
        temperature=0.0,
        messages=[
          {"Hi Claude, how are you?"}
        ]
    )

# 打印 Claude 的回复
print(response[0].text)
# 获取 Claude 的回复
response = client.messages.create(
        model=MODEL_NAME,
        max_tokens=2000,
        temperature=0.0,
        messages=[
          {"role": "user", "content": "What year was Celine Dion born in?"},
          {"role": "user", "content": "Also, can you tell me some other facts about her?"}
        ]
    )

# 打印 Claude 的回复
print(response[0].text)
# 系统提示
SYSTEM_PROMPT = "Your answer should always be a series of critical thinking questions that further the conversation (do not provide answers to your questions). Do not actually answer the user question."

# 提示
PROMPT = "Why is the sky blue?"

# 打印 Claude 的回复
print(get_completion(PROMPT, SYSTEM_PROMPT))
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容