设置 #
运行以下设置单元以加载您的 API 密钥并建立 get_completion 辅助函数。
!pip install anthropic
# Import python's built-in regular expression library
import re
import anthropic
# Retrieve the API_KEY & MODEL_NAME variables from the IPython store
%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
课程 #
通常,我们不想编写完整的提示,而是想要提示模板,这些模板可以在提交给 Claude 之前使用其他输入数据进行修改。如果您希望 Claude 每次都做同样的事情,这可能会派上用场,但 Claude 用于其任务的数据每次可能都不同。
幸运的是,我们可以很容易地做到这一点,方法是将提示的固定框架与可变的用户输入分开,然后在将完整提示发送给 Claude 之前将用户输入替换到提示中。
下面,我们将逐步介绍如何编写可替换的提示模板,以及如何替换用户输入。
示例 #
在第一个示例中,我们要求 Claude 充当动物噪音生成器。请注意,提交给 Claude 的完整提示只是用输入(在本例中为“Cow”)替换的 PROMPT_TEMPLATE。请注意,当我们打印出完整提示时,单词“Cow”通过 f 字符串替换了 ANIMAL 占位符。
注意:在实践中,您不必为占位符变量指定任何特定名称。我们在此示例中将其命名为 ANIMAL,但同样,我们可以将其命名为 CREATURE 或 A(尽管通常最好让变量名称具体且相关,以便即使没有替换,提示模板也易于理解,这只是为了用户可解析性)。只需确保您命名变量的名称与提示模板 f 字符串所使用的名称相同即可。
# Variable content
ANIMAL = "Cow"
# Prompt template with a placeholder for the variable content
PROMPT = f"I will tell you the name of an animal. Please respond with the noise that animal makes. {ANIMAL}"
# Print Claude's response
print("--------------------------- Full prompt with variable substutions ---------------------------")
print(PROMPT)
print("\n------------------------------------- Claude's response -------------------------------------")
print(get_completion(PROMPT))
为什么我们要像这样分离和替换输入?提示模板简化了重复性任务。假设您构建了一个提示结构,邀请第三方用户向提示提交内容(在本例中是他们想要生成声音的动物)。这些第三方用户不必编写甚至查看完整的提示。他们所要做的就是填写变量。
我们在这里使用变量和 f 字符串进行替换,但您也可以使用 format() 方法进行替换。
注意:提示模板可以有任意数量的变量!
在引入这样的替换变量时,确保 Claude 知道变量的开始和结束位置非常重要(与说明或任务描述相对)。让我们看一个说明和替换变量之间没有分离的例子。
在我们人类看来,变量在下面的提示模板中的开始和结束位置非常清楚。然而,在完全替换的提示中,这种划分变得不清楚。
# Variable content
EMAIL = "Show up at 6am tomorrow because I'm the CEO and I say so."
# Prompt template with a placeholder for the variable content
PROMPT = f"Yo Claude. {EMAIL} <----- Make this email more polite but don't change anything else about it."
# Print Claude's response
print("--------------------------- Full prompt with variable substutions ---------------------------")
print(PROMPT)
print("\n------------------------------------- Claude's response -------------------------------------")
print(get_completion(PROMPT))
在这里,Claude 认为“Yo Claude”是它应该重写的电子邮件的一部分!您可以看出来,因为它以“亲爱的 Claude”开始重写。对于人眼来说,这很清楚,特别是在提示模板中电子邮件的开始和结束位置,但在替换后的提示中变得不那么清晰了。
我们如何解决这个问题?用 XML 标签包装输入!我们在下面这样做了,正如您所见,输出中不再有“亲爱的 Claude”。
XML 标签是尖括号标签,如 。它们成对出现,由一个开始标签(例如 )和一个以 / 标记的结束标签(例如 )组成。 XML 标签用于包装内容,如下所示:content。
注意:虽然 Claude 可以识别并使用各种分隔符和定界符,但我们建议您使用特定的 XML 标签作为 Claude 的分隔符,因为 Claude 经过专门训练,可以将 XML 标签识别为提示组织机制。除了函数调用之外,Claude 并没有经过专门训练的 XML 标签,您可以使用它们来最大限度地提高性能。我们特意以这种方式让 Claude 非常灵活且可定制。
# Variable content
EMAIL = "Show up at 6am tomorrow because I'm the CEO and I say so."
# Prompt template with a placeholder for the variable content
PROMPT = f"Yo Claude. {EMAIL} <----- Make this email more polite but don't change anything else about it."
# Print Claude's response
print("--------------------------- Full prompt with variable substutions ---------------------------")
print(PROMPT)
print("\n------------------------------------- Claude's response -------------------------------------")
print(get_completion(PROMPT))
让我们再看一个 XML 标签如何帮助我们的例子。
在下面的提示中,Claude 错误地解释了提示的哪一部分是指令,哪一部分是输入。它错误地认为“每个都是关于一种动物的,比如兔子”是列表的一部分,这是因为格式问题,而用户(填写 SENTENCES 变量的人)可能并不想要这样。
# Variable content
SENTENCES = """- I like how cows sound
- This sentence is about spiders
- This sentence may appear to be about dogs but it's actually about pigs"""
# Prompt template with a placeholder for the variable content
PROMPT = f"""Below is a list of sentences. Tell me the second item on the list.
- Each is about an animal, like rabbits.
{SENTENCES}"""
# Print Claude's response
print("--------------------------- Full prompt with variable substutions ---------------------------")
print(PROMPT)
print("\n------------------------------------- Claude's response -------------------------------------")
print(get_completion(PROMPT))
为了解决这个问题,我们只需要用 XML 标签将用户输入的句子括起来。这样 Claude 就能看到输入数据的开始和结束位置,尽管 Each 前面的连字符容易让人误解,但它指的是一种动物,比如兔子。
# Variable content
SENTENCES = """- I like how cows sound
- This sentence is about spiders
- This sentence may appear to be about dogs but it's actually about pigs"""
# Prompt template with a placeholder for the variable content
PROMPT = f""" Below is a list of sentences. Tell me the second item on the list.
- Each is about an animal, like rabbits.
{SENTENCES}
"""
# Print Claude's response
print("--------------------------- Full prompt with variable substutions ---------------------------")
print(PROMPT)
print("\n------------------------------------- Claude's response -------------------------------------")
print(get_completion(PROMPT))
注意:在“Each is about an animal”提示的错误版本中,我们必须包含连字符,才能让 Claude 以我们想要的方式做出错误的回应。这是关于提示的重要一课:小细节很重要!清理提示中的拼写错误和语法错误总是值得的。Claude 对模式很敏感(在早期,在微调之前,它是一个原始的文本预测工具),当你犯错时它更容易犯错,当你听起来很聪明时它更聪明,当你听起来很傻时它更傻,等等。
如果您想在不更改上述任何内容的情况下尝试课程提示,请一直滚动到课程笔记本的底部以访问示例游乐场。
练习 #
练习 4.1 – 俳句主题 #
修改 PROMPT,使其成为一个模板,该模板将接受名为 TOPIC 的变量并输出关于该主题的俳句。此练习仅用于测试您对使用 f 字符串的变量模板结构的理解。
# Variable content
TOPIC = "Pigs"
# Prompt template with a placeholder for the variable content
PROMPT = f""
# Get Claude's response
response = get_completion(PROMPT)
# Function to grade exercise correctness
def grade_exercise(text):
return bool(re.search("pigs", text.lower()) and re.search("haiku", text.lower()))
# Print Claude's response
print("--------------------------- Full prompt with variable substutions ---------------------------")
print(PROMPT)
print("\n------------------------------------- Claude's response -------------------------------------")
print(response)
print("\n------------------------------------------ GRADING ------------------------------------------")
print("This exercise has been correctly solved:", grade_exercise(response))
练习 4.2 – 有错别字的狗问题 #
通过添加 XML 标签修复提示,以便 Claude 给出正确答案。
尽量不要更改提示中的任何其他内容。混乱且错误百出的书写是故意的,因此您可以看到 Claude 对此类错误的反应。
# Variable content
QUESTION = "ar cn brown?"
# Prompt template with a placeholder for the variable content
PROMPT = f"Hia its me i have a q about dogs jkaerjv {QUESTION} jklmvca tx it help me muhch much atx fst fst answer short short tx"
# Get Claude's response
response = get_completion(PROMPT)
# Function to grade exercise correctness
def grade_exercise(text):
return bool(re.search("brown", text.lower()))
# Print Claude's response
print("--------------------------- Full prompt with variable substutions ---------------------------")
print(PROMPT)
print("\n------------------------------------- Claude's response -------------------------------------")
print(response)
print("\n------------------------------------------ GRADING ------------------------------------------")
print("This exercise has been correctly solved:", grade_exercise(response))
练习 4.3 – 狗问题第 2 部分 #
修复提示,无需添加 XML 标签。相反,只需从提示中删除一个或两个单词。
与上述练习一样,尽量不要更改提示中的任何其他内容。这将向您展示 Claude 可以解析和理解哪种语言。
# Variable content
QUESTION = "ar cn brown?"
# Prompt template with a placeholder for the variable content
PROMPT = f"Hia its me i have a q about dogs jkaerjv {QUESTION} jklmvca tx it help me muhch much atx fst fst answer short short tx"
# Get Claude's response
response = get_completion(PROMPT)
# Function to grade exercise correctness
def grade_exercise(text):
return bool(re.search("brown", text.lower()))
# Print Claude's response
print("--------------------------- Full prompt with variable substutions ---------------------------")
print(PROMPT)
print("\n------------------------------------- Claude's response -------------------------------------")
print(response)
print("\n------------------------------------------ GRADING ------------------------------------------")
print("This exercise has been correctly solved:", grade_exercise(response))
总结 #
如果您已经解决了到目前为止的所有练习,那么您就可以进入下一章了。祝您提示愉快!
示例操场 #
这是一个区域,您可以自由地尝试本课中显示的提示示例,并调整提示以查看它如何影响 Claude 的回答。
# Variable content
ANIMAL = "Cow"
# Prompt template with a placeholder for the variable content
PROMPT = f"I will tell you the name of an animal. Please respond with the noise that animal makes. {ANIMAL}"
# Print Claude's response
print("--------------------------- Full prompt with variable substutions ---------------------------")
print(PROMPT)
print("\n------------------------------------- Claude's response -------------------------------------")
print(get_completion(PROMPT))
# Variable content
EMAIL = "Show up at 6am tomorrow because I'm the CEO and I say so."
# Prompt template with a placeholder for the variable content
PROMPT = f"Yo Claude. {EMAIL} <----- Make this email more polite but don't change anything else about it."
# Print Claude's response
print("--------------------------- Full prompt with variable substutions ---------------------------")
print(PROMPT)
print("\n------------------------------------- Claude's response -------------------------------------")
print(get_completion(PROMPT))
# Variable content
EMAIL = "Show up at 6am tomorrow because I'm the CEO and I say so."
# Prompt template with a placeholder for the variable content
PROMPT = f"Yo Claude. {EMAIL} <----- Make this email more polite but don't change anything else about it."
# Print Claude's response
print("--------------------------- Full prompt with variable substutions ---------------------------")
print(PROMPT)
print("\n------------------------------------- Claude's response -------------------------------------")
print(get_completion(PROMPT))
# Variable content
SENTENCES = """- I like how cows sound
- This sentence is about spiders
- This sentence may appear to be about dogs but it's actually about pigs"""
# Prompt template with a placeholder for the variable content
PROMPT = f"""Below is a list of sentences. Tell me the second item on the list.
- Each is about an animal, like rabbits.
{SENTENCES}"""
# Print Claude's response
print("--------------------------- Full prompt with variable substutions ---------------------------")
print(PROMPT)
print("\n------------------------------------- Claude's response -------------------------------------")
print(get_completion(PROMPT))
# Variable content
SENTENCES = """- I like how cows sound
- This sentence is about spiders
- This sentence may appear to be about dogs but it's actually about pigs"""
# Prompt template with a placeholder for the variable content
PROMPT = f""" Below is a list of sentences. Tell me the second item on the list.
- Each is about an animal, like rabbits.
{SENTENCES}
"""
# Print Claude's response
print("--------------------------- Full prompt with variable substutions ---------------------------")
print(PROMPT)
print("\n------------------------------------- Claude's response -------------------------------------")
print(get_completion(PROMPT))