设置 #
运行以下设置单元以加载您的 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)
# New argument added for prefill text, with a default value of an empty string
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 可以以多种方式格式化其输出。您只需要求它这样做!
其中一种方法是使用 XML 标记将响应与任何其他多余的文本分开。您已经了解到,您可以使用 XML 标记使您的提示更清晰,更易于 Claude 解析。事实证明,您还可以要求 Claude 使用 XML 标记使其输出更清晰,更易于人类理解。
示例 #
还记得我们在第 2 章中通过要求 Claude 完全跳过序言来解决的“诗歌序言问题”吗?事实证明,我们也可以通过告诉 Claude 将诗歌放在 XML 标记中来实现类似的结果。
# Variable content
ANIMAL = "Rabbit"
# Prompt template with a placeholder for the variable content
PROMPT = f"Please write a haiku about {ANIMAL}. Put it in tags."
# Print Claude's response
print("--------------------------- Full prompt with variable substutions ---------------------------")
print(PROMPT)
print("\n------------------------------------- Claude's response -------------------------------------")
print(get_completion(PROMPT))
为什么我们要这样做呢?因为,将输出放在 XML 标签中,最终用户可以通过编写一个简短的程序来提取 XML 标签之间的内容,从而可靠地获得诗歌,而且只获得诗歌。
此技术的扩展是**将第一个 XML 标签放在助手轮次中。当您将文本放在助手轮次中时,您基本上是在告诉 Claude,Claude 已经说了一些话,应该从那时开始继续。这种技术称为“speaking for Claude”或“预填充 Claude’s response”。
下面,我们使用第一个 XML 标签完成了此操作。请注意 Claude 如何直接从我们离开的地方继续。
# Variable content
ANIMAL = "Cat"
# Prompt template with a placeholder for the variable content
PROMPT = f"Please write a haiku about {ANIMAL}. Put it in tags."
# Prefill for Claude's response
PREFILL = ""
# Print Claude's response
print("--------------------------- Full prompt with variable substutions ---------------------------")
print("USER TURN:")
print(PROMPT)
print("\nASSISTANT TURN:")
print(PREFILL)
print("\n------------------------------------- Claude's response -------------------------------------")
print(get_completion(PROMPT, prefill=PREFILL))
Claude 还擅长使用其他输出格式样式,尤其是 JSON。如果您想要强制 JSON 输出(不是确定性的,但接近确定性的),您还可以使用左括号 {} 预填充 Claude 的响应。
# Variable content
ANIMAL = "Cat"
# Prompt template with a placeholder for the variable content
PROMPT = f"Please write a haiku about {ANIMAL}. Use JSON format with the keys as \"first_line\", \"second_line\", and \"third_line\"."
# Prefill for Claude's response
PREFILL = "{"
# Print Claude's response
print("--------------------------- Full prompt with variable substutions ---------------------------")
print("USER TURN")
print(PROMPT)
print("\nASSISTANT TURN")
print(PREFILL)
print("\n------------------------------------- Claude's response -------------------------------------")
print(get_completion(PROMPT, prefill=PREFILL))
下面是同一提示中的多个输入变量和输出格式规范的示例,全部使用 XML 标签完成。
# First input variable
EMAIL = "Hi Zack, just pinging you for a quick update on that prompt you were supposed to write."
# Second input variable
ADJECTIVE = "olde english"
# Prompt template with a placeholder for the variable content
PROMPT = f"Hey Claude. Here is an email: {EMAIL}. Make this email more {ADJECTIVE}. Write the new version in <{ADJECTIVE}_email> XML tags."
# Prefill for Claude's response (now as an f-string with a variable)
PREFILL = f"<{ADJECTIVE}_email>"
# Print Claude's response
print("--------------------------- Full prompt with variable substutions ---------------------------")
print("USER TURN")
print(PROMPT)
print("\nASSISTANT TURN")
print(PREFILL)
print("\n------------------------------------- Claude's response -------------------------------------")
print(get_completion(PROMPT, prefill=PREFILL))
附加课程 #
如果您通过 API 调用 Claude,则可以将结束 XML 标记传递给 stop_sequences 参数,让 Claude 在发出所需标记后停止采样。这可以节省金钱和最后标记时间,因为 Claude 已经给出了您关心的答案,无需再做最后评论。
如果您想尝试课程提示而不更改上述任何内容,请一直滚动到课程笔记本的底部以访问示例操场。
练习 #
练习 5.1 – 斯蒂芬·库里 GOAT #
被迫做出选择,Claude指定迈克尔·乔丹为有史以来最优秀的篮球运动员。我们能让克劳德选别人吗?
更改 PREFILL 变量,迫使Claude详细论证有史以来最优秀的篮球运动员是斯蒂芬·库里。尽量不要更改除 PREFILL 之外的任何内容,因为这是本练习的重点。
# Prompt template with a placeholder for the variable content
PROMPT = f"Who is the best basketball player of all time? Please choose one specific player."
# Prefill for Claude's response
PREFILL = ""
# Get Claude's response
response = get_completion(PROMPT, prefill=PREFILL)
# Function to grade exercise correctness
def grade_exercise(text):
return bool(re.search("Warrior", text))
# Print Claude's response
print("--------------------------- Full prompt with variable substutions ---------------------------")
print("USER TURN")
print(PROMPT)
print("\nASSISTANT TURN")
print(PREFILL)
print("\n------------------------------------- Claude's response -------------------------------------")
print(response)
print("\n------------------------------------------ GRADING ------------------------------------------")
print("This exercise has been correctly solved:", grade_exercise(response))
#
Exercise 5.2 – Two Haikus #
#
使用 XML 标签修改下面的 PROMPT,以便 Claude 写两首关于该动物的俳句,而不是一首。一首诗的结束和另一首诗的开始应该很清楚。
# Variable content
ANIMAL = "cats"
# Prompt template with a placeholder for the variable content
PROMPT = f"Please write a haiku about {ANIMAL}. Put it in tags."
# Prefill for Claude's response
PREFILL = ""
# Get Claude's response
response = get_completion(PROMPT, prefill=PREFILL)
# Function to grade exercise correctness
def grade_exercise(text):
return bool(
(re.search("cat", text.lower()) and re.search("", text))
and (text.count("\n") + 1) > 5
)
# Print Claude's response
print("--------------------------- Full prompt with variable substutions ---------------------------")
print("USER TURN")
print(PROMPT)
print("\nASSISTANT TURN")
print(PREFILL)
print("\n------------------------------------- Claude's response -------------------------------------")
print(response)
print("\n------------------------------------------ GRADING ------------------------------------------")
print("This exercise has been correctly solved:", grade_exercise(response))
练习 5.3 – 两首俳句,两种动物 #
修改下面的提示,让 Claude 创作两首关于两种不同动物的俳句。使用 {ANIMAL1} 作为第一个替换的替代,使用 {ANIMAL2} 作为第二个替换的替代。
# First input variable
ANIMAL1 = "Cat"
# Second input variable
ANIMAL2 = "Dog"
# Prompt template with a placeholder for the variable content
PROMPT = f"Please write a haiku about {ANIMAL1}. Put it in tags."
# Get Claude's response
response = get_completion(PROMPT)
# Function to grade exercise correctness
def grade_exercise(text):
return bool(re.search("tail", text.lower()) and re.search("cat", text.lower()) and re.search("", text))
# Print Claude's response
print("--------------------------- Full prompt with variable substutions ---------------------------")
print("USER TURN")
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 = "Rabbit"
# Prompt template with a placeholder for the variable content
PROMPT = f"Please write a haiku about {ANIMAL}. Put it in tags."
# Print Claude's response
print("--------------------------- Full prompt with variable substutions ---------------------------")
print(PROMPT)
print("\n------------------------------------- Claude's response -------------------------------------")
print(get_completion(PROMPT))
# Variable content
ANIMAL = "Cat"
# Prompt template with a placeholder for the variable content
PROMPT = f"Please write a haiku about {ANIMAL}. Put it in tags."
# Prefill for Claude's response
PREFILL = ""
# Print Claude's response
print("--------------------------- Full prompt with variable substutions ---------------------------")
print("USER TURN:")
print(PROMPT)
print("\nASSISTANT TURN:")
print(PREFILL)
print("\n------------------------------------- Claude's response -------------------------------------")
print(get_completion(PROMPT, prefill=PREFILL))
# Variable content
ANIMAL = "Cat"
# Prompt template with a placeholder for the variable content
PROMPT = f"Please write a haiku about {ANIMAL}. Use JSON format with the keys as \"first_line\", \"second_line\", and \"third_line\"."
# Prefill for Claude's response
PREFILL = "{"
# Print Claude's response
print("--------------------------- Full prompt with variable substutions ---------------------------")
print("USER TURN")
print(PROMPT)
print("\nASSISTANT TURN")
print(PREFILL)
print("\n------------------------------------- Claude's response -------------------------------------")
print(get_completion(PROMPT, prefill=PREFILL))
# First input variable
EMAIL = "Hi Zack, just pinging you for a quick update on that prompt you were supposed to write."
# Second input variable
ADJECTIVE = "olde english"
# Prompt template with a placeholder for the variable content
PROMPT = f"Hey Claude. Here is an email: {EMAIL}. Make this email more {ADJECTIVE}. Write the new version in <{ADJECTIVE}_email> XML tags."
# Prefill for Claude's response (now as an f-string with a variable)
PREFILL = f"<{ADJECTIVE}_email>"
# Print Claude's response
print("--------------------------- Full prompt with variable substutions ---------------------------")
print("USER TURN")
print(PROMPT)
print("\nASSISTANT TURN")
print(PREFILL)
print("\n------------------------------------- Claude's response -------------------------------------")
print(get_completion(PROMPT, prefill=PREFILL))