提示词编写指南
学习目标
通过本课程,你将了解到在大模型的使用中,提示词撰写的原则和相关策略。通过编写有效的提示词内容来提高大模型的使用效率。
相关知识点
- 提示词编写
学习内容
1 提示词编写
提示词是与大模型进行交互的关键部分,编写有效的提示词对于获得准确、有用的结果至关重要。
提示词用于向大模型传达任务要求和相关信息,引导模型生成符合期望的输出。它就像是给模型的 “指令”,告诉模型需要做什么,以及在生成回答时应考虑哪些因素。
以下是常见的类型:
-
问答型提示词:用于向模型提出问题,获取相关答案。例如,“地球的直径是多少?”“什么是量子力学?”。编写这类提示词时,要确保问题表述准确,避免过于宽泛或复杂的问题。
-
生成型提示词:要求模型生成文本内容,如文章、故事、诗歌等。例如,“以‘春天的花园’为主题,写一首五言绝句”。在编写时,要明确生成内容的主题、体裁、风格等要求。
-
分析型提示词:让模型对给定的文本、事件或现象进行分析。比如,“分析一下这部电影的剧情结构和人物塑造”。此类提示词需要明确分析的对象和具体的分析维度。
-
指令型提示词:指示模型执行特定的操作或任务,如 “将这段文字翻译成英文”“对这段代码进行优化”。编写时要清晰说明操作要求和相关细节。
1.1 依赖环境安装
%pip install openai
1.2 加载大模型
通过openai的接口实例化一个deepseek模型的对象。
import os
import httpx
from openai import OpenAI
# 此课程基于DeepSeek-R1运行,学员可自行前往官网进行api申请
client = OpenAI(
base_url=<BASE_URL>,
api_key=<API_KEY>,
http_client=httpx.Client(verify=False),
)
deepseek回复的内容包含了模型的思考步骤,通过建立extract_after_think函数对大模型返回的信息进行预处理,使得返回的信息只包含最终的回复内容。
from openai import ChatCompletion
def extract_after_think(chat_completion: ChatCompletion) -> str:
content = chat_completion.choices[0].message.content
start_index = content.find("</think>")
if start_index != -1:
return content[start_index + len("</think>"):]
else:
return ""
构建get_completion实现调用大模型的封装,输入提示词信息,得到大模型根据提示词信息返回的最终回复。
#请根据实际替换model_name
def get_completion(prompt, temperature=0.6):
messages = [{"role": "user", "content": prompt}]
response = client.chat.completions.create(
model=<model_name>,
messages=messages,
stream=False,
temperature=temperature,
max_tokens=2048,
top_p=0.95
)
return extract_after_think(response)
1.3 提示词原则
原则一:撰写清晰且具体的指令。
原则二:给模型留出 “思考” 的时间。
1.3.1 撰写清晰且具体的指令
策略一:使用分隔符来清晰指示输入内容中不同的部分。
分隔符可以是以下任何一种:```、“”"、<>、< tag> </ tag >
在提示词的构造中,通过不同的分割符来对不同内容进行分割处理。
例如以下:
通过 ```对text文档和提示词进行一个分割。
prompt = f"""
Summarize the text delimited by triple backticks \
into a single sentence.
```{text}```
"""
text = f"""
You should express what you want a model to do by \
providing instructions that are as clear and \
specific as you can possibly make them. \
This will guide the model towards the desired output, \
and reduce the chances of receiving irrelevant \
or incorrect responses. Don't confuse writing a \
clear prompt with writing a short prompt. \
In many cases, longer prompts provide more clarity \
and context for the model, which can lead to \
more detailed and relevant outputs.
"""
prompt = f"""
Summarize the text delimited by triple backticks \
into a single sentence.
```{text}```
"""
response = get_completion(prompt)
print(response)
策略二:对输出的内容进行结构化的要求。
例如使用:
JSON、HTML
大模型根据输入的提示词中规定的输出格式,来对回复的内容进行规定格式的格式化处理。
prompt = f"""
Generate a list of three made-up book titles along \
with their authors and genres.
Provide them in JSON format with the following keys:
book_id, title, author, genre.
"""
response = get_completion(prompt)
print(response)
策略三:要求模型检查条件是否得到满足。
在提示词中设置判断条件,模型根据设定的判断条件进行不同的规定输出。
text_1 = f"""
Making a cup of tea is easy! First, you need to get some \
water boiling. While that's happening, \
grab a cup and put a tea bag in it. Once the water is \
hot enough, just pour it over the tea bag. \
Let it sit for a bit so the tea can steep. After a \
few minutes, take out the tea bag. If you \
like, you can add some sugar or milk to taste. \
And that's it! You've got yourself a delicious \
cup of tea to enjoy.
"""
prompt = f"""
You will be provided with text delimited by triple quotes.
If it contains a sequence of instructions, \
re-write those instructions in the following format:
Step 1 - ...
Step 2 - …
…
Step N - …
If the text does not contain a sequence of instructions, \
then simply write \"No steps provided.\"
\"\"\"{text_1}\"\"\"
"""
response = get_completion(prompt)
print("Completion for Text 1:")
print(response)
text_2 = f"""
The sun is shining brightly today, and the birds are \
singing. It's a beautiful day to go for a \
walk in the park. The flowers are blooming, and the \
trees are swaying gently in the breeze. People \
are out and about, enjoying the lovely weather. \
Some are having picnics, while others are playing \
games or simply relaxing on the grass. It's a \
perfect day to spend time outdoors and appreciate the \
beauty of nature.
"""
prompt = f"""
You will be provided with text delimited by triple quotes.
If it contains a sequence of instructions, \
re-write those instructions in the following format:
Step 1 - ...
Step 2 - …
…
Step N - …
If the text does not contain a sequence of instructions, \
then simply write \"No steps provided.\"
\"\"\"{text_2}\"\"\"
"""
response = get_completion(prompt)
print("Completion for Text 2:")
print(response)
策略四:“少样本” 提示法。
少样本提示法是一种通过提供少量示例(通常为 1-5 个)引导大语言模型(LLM)理解任务要求的提示工程方法,无需大量标注数据且降低对指令复杂度的依赖。
在提示词的编写中,给出少量的提示信息,让大模型学习到其中的回复风格。
例如示例:
通过给出一段对话信息,来让大模型知道应该按照什么样的风格来进行回复。
prompt = f"""
Your task is to answer in a consistent style.
<child>: Teach me about patience.
<grandparent>: The river that carves the deepest \
valley flows from a modest spring; the \
grandest symphony originates from a single note; \
the most intricate tapestry begins with a solitary thread.
<child>: Teach me about resilience.
"""
response = get_completion(prompt)
print(response)
1.3.2 给模型留出 “思考” 的时间
策略一:明确完成一项任务所需的步骤。
在提示词的编写中,给出具体每一步需要完成的工作,让大模型按照步骤一步一步的进行"思考",给出最终的回复。
```python
text = f"""
In a charming village, siblings Jack and Jill set out on \
a quest to fetch water from a hilltop \
well. As they climbed, singing joyfully, misfortune \
struck—Jack tripped on a stone and tumbled \
down the hill, with Jill following suit. \
Though slightly battered, the pair returned home to \
comforting embraces. Despite the mishap, \
their adventurous spirits remained undimmed, and they \
continued exploring with delight.
"""
# example 1
prompt_1 = f"""
Perform the following actions:
1 - Summarize the following text delimited by triple \
backticks with 1 sentence.
2 - Translate the summary into French.
3 - List each name in the French summary.
4 - Output a json object that contains the following \
keys: french_summary, num_names.
Separate your answers with line breaks.
Text:
```{text}```
"""
response = get_completion(prompt_1)
print("Completion for prompt 1:")
print(response)
在提示词中规定步骤中输出信息格式,使得大模型能够按照规定的格式输出每一步中需要输出的信息。
prompt_2 = f"""
Your task is to perform the following actions:
1 - Summarize the following text delimited by
<> with 1 sentence.
2 - Translate the summary into French.
3 - List each name in the French summary.
4 - Output a json object that contains the
following keys: french_summary, num_names.
Use the following format:
Text: <text to summarize>
Summary: <summary>
Translation: <summary translation>
Names: <list of names in Italian summary>
Output JSON: <json with summary and num_names>
Text: <{text}>
"""
response = get_completion(prompt_2)
print("\nCompletion for prompt 2:")
print(response)
策略二:指示模型在得出结论之前先自行找出解决方案。
这种提示词策略被称为 “思维链提示法”,其思想是引导模型显式地展示推理步骤,而非直接生成结论,从而提升复杂任务的解决能力。
prompt = f"""
Determine if the student's solution is correct or not.
Question:
I'm building a solar power installation and I need \
help working out the financials.
- Land costs $100 / square foot
- I can buy solar panels for $250 / square foot
- I negotiated a contract for maintenance that will cost \
me a flat $100k per year, and an additional $10 / square \
foot
What is the total cost for the first year of operations
as a function of the number of square feet.
Student's Solution:
Let x be the size of the installation in square feet.
Costs:
1. Land cost: 100x
2. Solar panel cost: 250x
3. Maintenance cost: 100,000 + 100x
Total cost: 100x + 250x + 100,000 + 100x = 450x + 100,000
"""
response = get_completion(prompt)
print(response)
学生的解决方案实际上是不正确的。
可以通过指示模型先自行得出解决方案来解决这个问题。
prompt = f"“”
Your task is to determine if the student’s solution
is correct or not.
To solve the problem do the following:
- First, work out your own solution to the problem.
- Then compare your solution to the student’s solution \
and evaluate if the student’s solution is correct or not.
Don’t decide if the student’s solution is correct until
you have done the problem yourself.
Use the following format:
Question:
question here
Student’s solution:
student's solution here
Actual solution:
steps to work out the solution and your solution here
Is the student’s solution the same as actual solution
just calculated:
yes or no
Student grade:
correct or incorrect
Question:
I'm building a solar power installation and I need help \
working out the financials.
- Land costs $100 / square foot
- I can buy solar panels for $250 / square foot
- I negotiated a contract for maintenance that will cost \
me a flat $100k per year, and an additional $10 / square \
foot
What is the total cost for the first year of operations \
as a function of the number of square feet.
Student’s solution:
Let x be the size of the installation in square feet.
Costs:
1. Land cost: 100x
2. Solar panel cost: 250x
3. Maintenance cost: 100,000 + 100x
Total cost: 100x + 250x + 100,000 + 100x = 450x + 100,000
Actual solution:
“”"
response = get_completion(prompt)
print(response)
prompt = f"“”
Your task is to determine if the student’s solution
is correct or not.
To solve the problem do the following:
- First, work out your own solution to the problem.
- Then compare your solution to the student’s solution \
and evaluate if the student’s solution is correct or not.
Don’t decide if the student’s solution is correct until
you have done the problem yourself.
Use the following format:
Question:
question here
Student’s solution:
student's solution here
Actual solution:
steps to work out the solution and your solution here
Is the student’s solution the same as actual solution
just calculated:
yes or no
Student grade:
correct or incorrect
Question:
I'm building a solar power installation and I need help \
working out the financials.
- Land costs $100 / square foot
- I can buy solar panels for $250 / square foot
- I negotiated a contract for maintenance that will cost \
me a flat $100k per year, and an additional $10 / square \
foot
What is the total cost for the first year of operations \
as a function of the number of square feet.
Student’s solution:
Let x be the size of the installation in square feet.
Costs:
1. Land cost: 100x
2. Solar panel cost: 250x
3. Maintenance cost: 100,000 + 100x
Total cost: 100x + 250x + 100,000 + 100x = 450x + 100,000
Actual solution:
“”"
response = get_completion(prompt)
print(response)
1.4 模型的局限性:幻觉现象
模型的幻觉是指人工智能模型,尤其是像大型语言模型这类,生成看似合理但实际上与事实不符或完全虚构的内容的现象。
例如,模型可能会 “编造” 出不存在的事件、人物、产品、技术等,或者对已知的事物给出错误的描述、属性及关系等。
博伊(Boie)是一家真实存在的公司,但(AeroGlide UltraSlim Smart Toothbrush)产品名称并不是真实的。
prompt = f"""
Tell me about AeroGlide UltraSlim Smart Toothbrush by Boie
"""
response = get_completion(prompt)
print(response)

被折叠的 条评论
为什么被折叠?



