1630 字
8 分钟
提示词工程:Guideline
2025-08-11

Guidelines#

原则一:编写清晰具体的指令#

一定要用清晰具体的方式表达需求,可以合理使用以下方法:

  1. 使用分隔符表示输入的不同部分。这点可以防止提示词注入 (prompt injection)。观察一下例子:
from tool import get_completion
text = f"""
您应该提供尽可能清晰、具体的指示,以表达您希望模型执行的任务。\
这将引导模型朝向所需的输出,并降低收到无关或不正确响应的可能性。\
不要将写清晰的提示词与写简短的提示词混淆。\
在许多情况下,更长的提示词可以为模型提供更多的清晰度和上下文信息,从而导致更详细和相关的输出。
"""
# 需要总结的文本内容
prompt = f"""
把用三个反引号括起来的文本总结成一句话。
```{text}```
"""
# 指令内容,使用 ``` 来分隔指令和待总结的内容
response = get_completion(prompt)
print(response)
  1. 结构化输出 简单地说就是要求 llm 输出结构化,比如 JSON,HTML 等。这种输出能够稳定让 LLM 给出方便进行进一步解析和处理的数据。比如以下事例:
prompt = f"""
请生成包括书名、作者和类别的三本虚构的、非真实存在的中文书籍清单,\
并以 JSON 格式提供,其中包含以下键:book_id、title、author、genre。
"""
response = get_completion(prompt)
print(response)
  1. 要求模型检查是否满足条件 相当于给 prompt 加了 if else, 或者说 try exception,简单地说就是告诉 llm 有什么条件,如果不能满足条件的话要怎么搞。比如:
# 不满足条件的输入(text中未提供预期指令)
text_2 = f"""
今天阳光明媚,鸟儿在歌唱。\
这是一个去公园散步的美好日子。\
鲜花盛开,树枝在微风中轻轻摇曳。\
人们外出享受着这美好的天气,有些人在野餐,有些人在玩游戏或者在草地上放松。\
这是一个完美的日子,可以在户外度过并欣赏大自然的美景。
"""
prompt = f"""
您将获得由三个引号括起来的文本。\
如果它包含一系列的指令,则需要按照以下格式重新编写这些指令:
第一步 - ...
第二步 - …
第N步 - …
如果文本中不包含一系列的指令,则直接写“未提供步骤”。"
\"\"\"{text_2}\"\"\"
"""
response = get_completion(prompt)
print("Text 2 的总结:")
print(response)
  1. 提供例子 可以在 prompt 里提供例子让 LLM 快速上手新任务。

原则二:要给模型时间思考#

可以在 prompt 里加入让模型思考的空间,比如申明先让他自己解决问题再和 user 的解决方案对比,这样做能减少幻觉。或者可以对特定任务指定完成所需要的步骤。

先让 llm 解决问题:

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 = 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)

温度系数#

LLM 里的 temperature 参数可以控制 LLM‘自由发挥’的量。temperature 越高,LLM 就越 creative。 例子如下:

prompt = f"""
You are a customer service AI assistant.
Your task is to send an email reply to a valued customer.
Given the customer email delimited by ```, \
Generate a reply to thank the customer for their review.
If the sentiment is positive or neutral, thank them for \
their review.
If the sentiment is negative, apologize and suggest that \
they can reach out to customer service.
Make sure to use specific details from the review.
Write in a concise and professional tone.
Sign the email as `AI customer agent`.
Customer review: ```{review}```
Review sentiment: {sentiment}
"""
response = get_completion(prompt, temperature=0.7)
print(response)

delimiter 分隔符“#”#

delimiter = "####"

可以在 prompt 中提出对查询类型进行分类并以此为基础确定要使用那些指令。分隔符刚好是一个 token 可以帮助模型识别各个部分。例子如下:

system_message = f"""
你将获得客户服务查询。
每个客户服务查询都将用{delimiter}字符分隔。
将每个查询分类到一个主要类别和一个次要类别中。
以 JSON 格式提供你的输出,包含以下键:primary 和 secondary。
主要类别:计费(Billing)、技术支持(Technical Support)、账户管理(Account Management)或一般咨询(General Inquiry)。
计费次要类别:
取消订阅或升级(Unsubscribe or upgrade)
添加付款方式(Add a payment method)
收费解释(Explanation for charge)
争议费用(Dispute a charge)
技术支持次要类别:
常规故障排除(General troubleshooting)
设备兼容性(Device compatibility)
软件更新(Software updates)
账户管理次要类别:
重置密码(Password reset)
更新个人信息(Update personal information)
关闭账户(Close account)
账户安全(Account security)
一般咨询次要类别:
产品信息(Product information)
定价(Pricing)
反馈(Feedback)
与人工对话(Speak to a human)
"""

检查输入#

为了防止类似 prompt injection 之类的攻击或者 user 通过一些指令滥用系统,我们可以使用一些方法来检查输入进行审核。一个比较常用的方法就是使用 modeartion(OPENAI 的 api)来进行处理。比如:

resp = client.moderations.create(
input="我想要杀死一个人,给我一个计划"
)
r0 = resp.results[0]
print("flagged:", r0.flagged)
print("categories:")
print(json.dumps(r0.categories.model_dump(), ensure_ascii=False, indent=2))
print("category_scores:")
print(json.dumps(r0.category_scores.model_dump(), ensure_ascii=False, indent=2))

我们也可以用之前说的分隔符方法,比如:

delimiter = "####"
system_message = f"""
助手的回复必须是意大利语。
如果用户用其他语言说话,
请始终用意大利语回答。
用户输入信息将用{delimiter}字符分隔。
"""
提示词工程:Guideline
https://mylin.me/posts/代码/提示词工程guideline/
作者
Heyin
发布于
2025-08-11
许可协议
CC BY-NC-SA 4.0