设置 #
运行以下设置单元以加载您的 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="", prefill=""):
message = client.messages.create(
model=MODEL_NAME,
max_tokens=2000,
temperature=0.0,
system=system_prompt,
messages=[
{"role": "user", "content": prompt},
{"role": "assistant", "content": prefill}
]
)
return message.content[0].text
课程 #
如果有人叫醒你,并立即开始问你几个复杂的问题,你必须立即回答,你会怎么做?可能不如先给你时间思考答案那么好。
猜猜怎么了?克劳德也是这样。
给claude时间一步一步思考有时会让claude更准确,特别是对于复杂的任务。然而,思考只有大声说出来才有意义。你不能要求claude思考,而只输出答案——在这种情况下,实际上没有发生思考。
例子 #
在下面的提示中,对于人类读者来说,第二句话与第一句话相矛盾。但claude对“不相关”一词的理解过于字面化。
# Prompt
PROMPT = """Is this movie review sentiment positive or negative?
This movie blew my mind with its freshness and originality. In totally unrelated news, I have been living under a rock since the year 1900."""
# Print Claude's response
print(get_completion(PROMPT))
为了改善 Claude 的回答,我们让 Claude 先思考一下再回答。我们通过逐字逐句地说明 Claude 处理和思考任务应采取的步骤来做到这一点。再加上一些角色提示,这让 Claude 能够更深入地理解评论。
# System prompt
SYSTEM_PROMPT = "You are a savvy reader of movie reviews."
# Prompt
PROMPT = """Is this review sentiment positive or negative? First, write the best arguments for each side in and XML tags, then answer.
This movie blew my mind with its freshness and originality. In totally unrelated news, I have been living under a rock since 1900."""
# Print Claude's response
print(get_completion(PROMPT, SYSTEM_PROMPT))
Claude有时对排序很敏感。这个例子体现了Claude理解细微文本的能力,当我们将上一个例子中的参数顺序交换为第一个否定,第二个肯定时,Claude的总体评价就会变为肯定。
在大多数情况下(但不是全部,这很令人困惑),Claude更有可能选择两个选项中的第二个,可能是因为在其来自网络的训练数据中,第二个选项更有可能是正确的。
# Prompt
PROMPT = """Is this review sentiment negative or positive? First write the best arguments for each side in and XML tags, then answer.
This movie blew my mind with its freshness and originality. Unrelatedly, I have been living under a rock since 1900."""
# Print Claude's response
print(get_completion(PROMPT))
让Claude思考可以将Claude的答案从错误变为正确。在Claude犯错的很多情况下,就是这么简单!
让我们通过一个Claude答案不正确的例子来看一下如何让Claude思考可以解决这个问题。
# Prompt
PROMPT = "Name a famous movie starring an actor who was born in the year 1956."
# Print Claude's response
print(get_completion(PROMPT))
让我们通过让 Claude 一步一步思考来解决这个问题,这次是在 标签中。
# Prompt
PROMPT = "Name a famous movie starring an actor who was born in the year 1956. First brainstorm about some actors and their birth years in tags, then give your answer."
# Print Claude's response
print(get_completion(PROMPT))
如果您想尝试课程提示而不更改上述任何内容,请一直滚动到课程笔记本的底部以访问示例操场。
练习 #
练习 6.1 – 对电子邮件进行分类 #
在此练习中,我们将指导 Claude 将电子邮件分类为以下类别:
(A) 预售问题
(B) 破损或有缺陷的物品
(C) 账单问题
(D) 其他(请解释)
对于练习的第一部分,更改 PROMPT 以使 Claude 输出正确的分类并且仅输出分类。您的答案需要包含正确选择的字母(A – D)以及括号,以及类别名称。
请参阅电子邮件列表中每封电子邮件旁边的评论,了解该电子邮件应归类到哪个类别。
# Prompt template with a placeholder for the variable content
PROMPT = """Please classify this email as either green or blue: {email}"""
# Prefill for Claude's response, if any
PREFILL = ""
# Variable content stored as a list
EMAILS = [
"Hi -- My Mixmaster4000 is producing a strange noise when I operate it. It also smells a bit smoky and plasticky, like burning electronics. I need a replacement.", # (B) Broken or defective item
"Can I use my Mixmaster 4000 to mix paint, or is it only meant for mixing food?", # (A) Pre-sale question OR (D) Other (please explain)
"I HAVE BEEN WAITING 4 MONTHS FOR MY MONTHLY CHARGES TO END AFTER CANCELLING!! WTF IS GOING ON???", # (C) Billing question
"How did I get here I am not good with computer. Halp." # (D) Other (please explain)
]
# Correct categorizations stored as a list of lists to accommodate the possibility of multiple correct categorizations per email
ANSWERS = [
["B"],
["A","D"],
["C"],
["D"]
]
# Dictionary of string values for each category to be used for regex grading
REGEX_CATEGORIES = {
"A": "A\) P",
"B": "B\) B",
"C": "C\) B",
"D": "D\) O"
}
# Iterate through list of emails
for i,email in enumerate(EMAILS):
# Substitute the email text into the email placeholder variable
formatted_prompt = PROMPT.format(email=email)
# Get Claude's response
response = get_completion(formatted_prompt, prefill=PREFILL)
# Grade Claude's response
grade = any([bool(re.search(REGEX_CATEGORIES[ans], response)) for ans in ANSWERS[i]])
# Print Claude's response
print("--------------------------- Full prompt with variable substutions ---------------------------")
print("USER TURN")
print(formatted_prompt)
print("\nASSISTANT TURN")
print(PREFILL)
print("\n------------------------------------- Claude's response -------------------------------------")
print(response)
print("\n------------------------------------------ GRADING ------------------------------------------")
print("This exercise has been correctly solved:", grade, "\n\n\n\n\n\n")
练习 6.2 – 电子邮件分类格式 #
在此练习中,我们将优化上述提示的输出,以产生完全符合我们要求的格式的答案。
使用您最喜欢的输出格式技术,让 Claude 只将正确分类的字母包装在 标签中。例如,第一封电子邮件的答案应包含精确的字符串 B。
如果您忘记了每封电子邮件的正确字母类别,请参阅电子邮件列表中每封电子邮件旁边的注释。
# Prompt template with a placeholder for the variable content
PROMPT = """Please classify this email as either green or blue: {email}"""
# Prefill for Claude's response, if any
PREFILL = ""
# Variable content stored as a list
EMAILS = [
"Hi -- My Mixmaster4000 is producing a strange noise when I operate it. It also smells a bit smoky and plasticky, like burning electronics. I need a replacement.", # (B) Broken or defective item
"Can I use my Mixmaster 4000 to mix paint, or is it only meant for mixing food?", # (A) Pre-sale question OR (D) Other (please explain)
"I HAVE BEEN WAITING 4 MONTHS FOR MY MONTHLY CHARGES TO END AFTER CANCELLING!! WTF IS GOING ON???", # (C) Billing question
"How did I get here I am not good with computer. Halp." # (D) Other (please explain)
]
# Correct categorizations stored as a list of lists to accommodate the possibility of multiple correct categorizations per email
ANSWERS = [
["B"],
["A","D"],
["C"],
["D"]
]
# Dictionary of string values for each category to be used for regex grading
REGEX_CATEGORIES = {
"A": "A",
"B": "B",
"C": "C",
"D": "D"
}
# Iterate through list of emails
for i,email in enumerate(EMAILS):
# Substitute the email text into the email placeholder variable
formatted_prompt = PROMPT.format(email=email)
# Get Claude's response
response = get_completion(formatted_prompt, prefill=PREFILL)
# Grade Claude's response
grade = any([bool(re.search(REGEX_CATEGORIES[ans], response)) for ans in ANSWERS[i]])
# Print Claude's response
print("--------------------------- Full prompt with variable substutions ---------------------------")
print("USER TURN")
print(formatted_prompt)
print("\nASSISTANT TURN")
print(PREFILL)
print("\n------------------------------------- Claude's response -------------------------------------")
print(response)
print("\n------------------------------------------ GRADING ------------------------------------------")
print("This exercise has been correctly solved:", grade, "\n\n\n\n\n\n")
恭喜! #
如果您已经解决了到目前为止的所有练习,那么您就可以进入下一章了。祝您提示愉快!
示例操场 #
这是一个区域,您可以自由地尝试本课中显示的提示示例,并调整提示以查看它如何影响 Claude 的回答。
# Prompt
PROMPT = """Is this movie review sentiment positive or negative?
This movie blew my mind with its freshness and originality. In totally unrelated news, I have been living under a rock since the year 1900."""
# Print Claude's response
print(get_completion(PROMPT))
# System prompt
SYSTEM_PROMPT = "You are a savvy reader of movie reviews."
# Prompt
PROMPT = """Is this review sentiment positive or negative? First, write the best arguments for each side in and XML tags, then answer.
This movie blew my mind with its freshness and originality. In totally unrelated news, I have been living under a rock since 1900."""
# Print Claude's response
print(get_completion(PROMPT, SYSTEM_PROMPT))
# Prompt
PROMPT = """Is this review sentiment negative or positive? First write the best arguments for each side in and XML tags, then answer.
This movie blew my mind with its freshness and originality. Unrelatedly, I have been living under a rock since 1900."""
# Print Claude's response
print(get_completion(PROMPT))
# Prompt
PROMPT = "Name a famous movie starring an actor who was born in the year 1956."
# Print Claude's response
print(get_completion(PROMPT))
# Prompt
PROMPT = "Name a famous movie starring an actor who was born in the year 1956. First brainstorm about some actors and their birth years in tags, then give your answer."
# Print Claude's response
print(get_completion(PROMPT))