大模型时代的prompt学习(持续更新)

为什么要学prompt

OpenAI 的 CEO Sam Altman 认为 prompt 是个非常高杠杆的技能。学习 prompt 可以让你更好地使用 ChatGPT 等产品, 当然prompt可能 会是个短期过度形态,未来肯定会有更友好的交互形式,或者理解能力更强的 AI 产品。
prompt高杠杆
前特斯拉 AI 负责人 Andrej Karpathy(最近二进宫回OpenAI ) 今年 1 月底也说:最热门的新编程语言是英语。

基本原则

  • 完整简约
    不精确的信息生成的答案可能就会很宽泛,而更好的方式是增加更多的信息。
  • 精确无歧义
    减少歧义,少用模棱两可的词语。
  • 语法规范
    使用正确的语法、拼写,以及标点

prompt撰写框架

Base Prompt Framework

Elavis Saravia 总结的框架,他认为一个 prompt 里需包含以下几个元素:

Instruction(必须): 指令,即你希望模型执行的具体任务。
Context(选填): 背景信息,或者说是上下文信息,这可以引导模型做出更好的反应。
Input Data(选填): 输入数据,告知模型需要处理的数据。
Output Indicator(选填): 输出指示器,告知模型我们要输出的类型或格式。
只要你按照这个框架写 prompt ,模型返回的结果都不会差。

当然,你在写 prompt 的时候,并不一定要包含所有4个元素,而是可以根据自己的需求排列组合。比如拿前面的几个场景作为例子:

推理:Instruction + Context + Input Data
信息提取:Instruction + Context + Input Data + Output Indicator

CRISPE Prompt Framework

Matt Nigh 的 CRISPE Framework,这个 framework 更加复杂,但完备性会比较高,比较适合用于编写 prompt 模板。CRISPE 分别代表以下含义:

CR: Capacity and Role(能力与角色)。你希望 ChatGPT 扮演怎样的角色。
I: Insight(洞察力),背景信息和上下文(坦率说来我觉得用 Context 更好)。
S: Statement(指令),你希望 ChatGPT 做什么。
P: Personality(个性),你希望 ChatGPT 以什么风格或方式回答你。
E: Experiment(尝试),要求 ChatGPT 为你提供多个答案。
以下是这几个参数的例子:

StepExample
Capacity and RoleAct as an expert on software development on the topic of machine learning frameworks, and an expert blog writer.把你想象成机器学习框架主题的软件开发专家,以及专业博客作者。
InsightThe audience for this blog is technical professionals who are interested in learning about the latest advancements in machine learning.这个博客的读者主要是有兴趣了解机器学习最新进展技术的专业人士。
StatementProvide a comprehensive overview of the most popular machine learning frameworks, including their strengths and weaknesses. Include real-life examples and case studies to illustrate how these frameworks have been successfully used in various industries.提供最流行的机器学习框架的全面概述,包括它们的优点和缺点。包括现实生活中的例子,和研究案例,以说明这些框架如何在各个行业中成功地被使用。
PersonalityWhen responding, use a mix of the writing styles of Andrej Karpathy, Francois Chollet, Jeremy Howard, and Yann LeCun. 在回应时,混合使用 Andrej Karpathy、Francois Chollet、Jeremy Howard 和 Yann LeCun 的写作风格。
ExperimentGive me multiple different examples.给我多个不同的例子。

场景

撰写文案文档

参考公式(base framework prompt)
【背景:产品/项目介绍】+【指令:撰写/修改 + 文案/文档类型】+【输入数据:模仿对象内容/修改内容(可选)】+【输出指示:关于主题/产品的要点 + 结构/字数等】

例:

产品说明文档,假设要做一个在线教育平台
我要做一个在线教育平台(背景),请写一篇产品说明文档(指令),核心功能包括在线课程、实时答疑、学习社群,按照介绍、功能、优势三个部分组织内容,不超过1000字(输出指示)。

竞品分析

参考公式(base framework prompt)
【背景:竞品领域/行业】+【指令:进行竞品分析/提供竞品列表/分析报告】+【输入数据:提供参考大纲结构/产品内容(可选)】+【输出指示:分析类型/关注点 + 格式要求(表格/列表/段落)等】

例:

1. 快速获取竞品列表
我们准备进入知识付费行业(背景),列出目前市场上的知识付费产品(指令),提供产品名称和简要介绍的列表(输出指示)
2. 明确分析思路,深入研究竞品
我正在研究在线教育行业中的竞争对手(背景),(指令)请对(输入数据)得到APP、极客时间、樊登读书、喜马拉雅进行竞品分析,分析各竞品的竞品定位与核心价值、产品特点与功能、用户评价与反馈(输出指示)

产品设计

参考公式(base framework prompt)
【背景:产品类型/现状】+【指令:获取设计建议/优化方案】+【输入数据:参考案例辅助说明等(可选)】+【输出指示:设计元素/参考案例 + 格式要求(图文/列表/段落)等】

例:

假设要做一个在线教育平台的用户积分体系
我们在做一个在线教育平台(背景),希望增加用户参与度和活跃度,(指令)请为在线教育平台提供用户积分体系的设计建议,列出积分体系的关键要素和激励措施(输出指示)

数据分析

参考公式(base framework prompt)
【背景:数据类型/业务场景】+【指令:发现原因/趋势/优化建议】+【输入数据:要分析的数据】+【输出指示:问题/现象描述 + 格式要求(图表/列表/段落)等】

例:

1.产品日活数据下跌,让它帮忙分析
我正在做一款知识付费产品(背景),近期发现产品的日活数据下降,(指令)请帮我分析下这些数据,看是否正常,有没有问题?(输出指示)列出数据特点,如有问题,分析可能的原因,并提供优化建议;(输入数据)以下是具体的日活数据:日期 日活
2.补发渠道的日活数据,获取更具体的分析与建议
下面我再补充一下各个渠道的日活跃用户情况,请你进一步分析

chain of thought

zero shot

这个技巧使用起来非常简单,只需要在问题的结尾里放一句 Let‘s think step by step (让我们一步步地思考),模型输出的答案会更加准确。

这个技巧来自于 Kojima 等人 2022 年的论文 Large Language Models are Zero-Shot Reasoners。在论文里提到,当我们向模型提一个逻辑推理问题时,模型返回了一个错误的答案,但如果我们在问题最后加入 Let‘s think step by step 这句话之后,模型就生成了正确的答案:

ZeroShotChainOfThought001

论文里有讲到原因,大致如下:

  1. 像 ChatGPT 这类产品,它是一个统计语言模型,本质上是基于过去看到过的所有数据,用统计学意义上的预测结果进行下一步的输出(答案是一个字一个字算出来的)。当它拿到的数据里有逻辑,它就会通过统计学的方法将这些逻辑找出来,并将这些逻辑呈现给你,让你感觉到它的回答很有逻辑。
  2. 在计算的过程中,模型会进行很多假设运算(具体不详)。比如解决某个问题是从 A 到 B 再到 C,中间有很多假设。
  3. 它第一次算出来的答案错误的原因,只是因为它在中间跳过了一些步骤(B)。而让模型一步步地思考,则有助于其按照完整的逻辑链(A > B > C)去运算,而不会跳过某些假设,最后算出正确的答案。

按照论文里的解释,零样本思维链涉及两个补全结果,左侧气泡表示基于提示输出的第一次的结果,右侧气泡表示其收到了第一次结果后,将最开始的提示一起拿去运算,最后得出了正确的答案:
ZeroShotChainOfThought002

这个技巧,除了用于解决复杂问题外,还适合生成一些连贯主题的内容,比如写长篇文章、电影剧本等。

但需要注意其缺点,连贯不代表,它就一定不会算错,如果其中某一步骤算错了,错误会因为逻辑链,逐步将错误积累,导致生成的文本可能出现与预期不符的内容。

另外,根据 Wei 等人在 2022 年的论文表明,它仅在大于等于 100B 参数的模型中使用才会有效。如果你使用的是小样本模型,这个方法不会生效。

根据 Yongchao Zhou 等人的最新论文,更好的 prompt 是:

Let's work this out in a step by step way to be sure we have the right answer.

在吴恩达的 ChatGPT Prompt Engineering 课程中,有提到一个这个技巧的另一种用法,不仅仅只是让 AI 按步骤行事,还会告知 AI 每一步要做什么。比如这个案例(注意这个是 python 代码):

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}>
"""

简单解释下这个代码:

  1. 开头是让 AI 按照 1 ~ 4 步运行
  2. 然后再让 AI 根据特定格式输出内容

最后 AI 的输出是这样的:

Summary: Jack and Jill go on a quest to fetch water, but misfortune strikes and they tumble down the hill, returning home slightly battered but with their adventurous spirits undimmed.
Translation: Jack et Jill partent en quête d'eau, mais la malchance frappe et ils dégringolent la colline, rentrant chez eux légèrement meurtris mais avec leurs esprits aventureux intacts.
Names: Jack, Jill
Output JSON: {"french_summary": "Jack et Jill partent en quête d'eau, mais la malchance frappe et ils dégringolent la colline, rentrant chez eux légèrement meurtris mais avec leurs esprits aventureux intacts.", "num_names": 2}

上述的案例只是将任务拆解,能让 AI 生成的结果更加符合要求,而这个方法同样能提升 AI 的回答准确性,比如这个案例:

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:

Land cost: 100x

Solar panel cost: 250x

Maintenance cost: 100,000 + 100x
Total cost: 100x + 250x + 100,000 + 100x = 450x + 100,000

AI 的回答是「The student’s solution is correct」。但其实学生的答案是错误的,应该 360x + 100,000,我们将 prompt 调整成这样:

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:
"""

本质上,也是将任务分拆成多步,这次 AI 输出的结果是这样的(结果就是正确的了):

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 + 10x

Total cost: 100x + 250x + 100,000 + 10x = 360x + 100,000

Is the student's solution the same as actual solution just calculated:
No

Student grade:
Incorrect

in context learning(few shot)

Brown 等人在 2020 年发现的,论文里有一个这样的例子,非常有意思,通过这个例子你应该更能体会,像 ChatGPT 这类统计语言模型,其实并不懂意思,只是懂概率

Brown 输入的内容是这样的(whatpu 和 farduddle 其实根本不存在):

A "whatpu" is a small, furry animal native to Tanzania. An example of a sentence that uses
the word whatpu is:
We were traveling in Africa and we saw these very cute whatpus.
To do a "farduddle" means to jump up and down really fast. An example of a sentence that uses
the word farduddle is:

Output 是这样的:

When we won the game, we all started to farduddle in celebration.

不过这并不代表,Few-Shot 就没有缺陷,我们试试下面这个例子:

Prompt:

The odd numbers in this group add up to an even number: 4, 8, 9, 15, 12, 2, 1.
A: The answer is False.

The odd numbers in this group add up to an even number: 17,  10, 19, 4, 8, 12, 24.
A: The answer is True.

The odd numbers in this group add up to an even number: 16,  11, 14, 4, 8, 13, 24.
A: The answer is True.

The odd numbers in this group add up to an even number: 17,  9, 10, 12, 13, 4, 2.
A: The answer is False.

The odd numbers in this group add up to an even number: 15, 32, 5, 13, 82, 7, 1. 
A:

Output 是这样的:

The answer is True.

输出的答案其实是错误的,实际上的答案应该是:

Adding all the odd numbers (15, 5, 13, 7, 1) gives 41. The answer is False.

那我们有没有什么方法解决?

根据 Wei 他们团队在 2022 年的研究表明:

通过向大语言模型展示一些少量的样例,并在样例中解释推理过程,大语言模型在回答提示时也会显示推理过程。这种推理的解释往往会引导出更准确的结果。

从下面这个案例里,你可以看到加入解释后,输出的结果就正确了。

FewShotChainOfThought001

那本章开头提的例子就应该是这样的(注:本例子同样来自 Wei 团队论文):

The odd numbers in this group add up to an even number: 4, 8, 9, 15, 12, 2, 1.
A: Adding all the odd numbers (9, 15, 1) gives 25. The answer is False.

The odd numbers in this group add up to an even number: 17,  10, 19, 4, 8, 12, 24.
A: Adding all the odd numbers (17, 19) gives 36. The answer is True.

The odd numbers in this group add up to an even number: 16,  11, 14, 4, 8, 13, 24.
A: Adding all the odd numbers (11, 13) gives 24. The answer is True.

The odd numbers in this group add up to an even number: 17,  9, 10, 12, 13, 4, 2.
A: Adding all the odd numbers (17, 9, 13) gives 39. The answer is False.

The odd numbers in this group add up to an even number: 15, 32, 5, 13, 82, 7, 1. 
A:

聊完技巧,我们再结合前面的 Zero-Shot ,来聊聊 Chain of Thought 的关键知识。根据 Sewon Min 等人在 2022 年的研究 表明,思维链有以下特点:

  1. “the label space and the distribution of the input text specified by the demonstrations are both key (regardless of whether the labels are correct for individual inputs)” 标签空间和输入文本的分布都是关键因素(无论这些标签是否正确)。
  2. the format you use also plays a key role in performance, even if you just use random labels, this is much better than no labels at all. 即使只是使用随机标签,使用适当的格式也能提高性能。

例如给 ChatGPT 一些不一定准确的例子:

I loved the new Batman movie!  // Negative
This is bad // Positive
This is good // Negative
What a good show! //

Output 是这样的:

Positive

在上述的案例里,每一行,都写了一句话和一个情感词,并用 // 分开,但我给这些句子都标记了错误的答案,比如第一句其实应该是 Positive 才对。但:

  1. 即使我给内容打的标签是错误的(比如第一句话,其实应该是 Positive),对于模型来说,它仍然会知道需要输出什么东西。 换句话说,模型知道 // 划线后要输出一个衡量该句子表达何种感情的词(Positive or Negative)。这就是前面论文里 #1 提到的,即使我给的标签是错误的,或者换句话说,是否基于事实,并不重要。标签和输入的文本,以及格式才是关键因素。
  2. 只要给了示例,即使随机的标签,对于模型生成结果来说,都是有帮助的。这就是前面论文里 #2 提到的内容。

最后,需要记住,思维链仅在使用大于等于 100B 参数的模型时,才会生效。

BTW,更多信息见斯坦福大学的讲义:Natural Language Processing with Deep Learning

Self-Consistency

Self-Consistency 自洽是对 Chain of Thought 的一个补充,它能让模型生成多个思维链,然后取最多数答案的作为最终结果。

按照 Xuezhi Wang 等人在 2022 年发表的论文 表明。当我们只用一个逻辑链进行优化时,模型依然有可能会算错,所以 XueZhi Wang 等人提出了一种新的方法,让模型进行多次运算,然后选取最多的答案作为最终结果:

SelfConsistency001

就我目前使用下来,在 ChatGPT 上,其自洽性非常高,暂时没有遇到过出现多种答案的情况。查阅多份资料,我发现这个自洽性可能更多的用于评估模型的优劣,好的模型一般自洽性会比较高。

在此案例中,考虑如下多步推理问题:

Consider a multi-step reasoning problem like the following:

Question: If a store has 10 apples and 8 oranges, and it sells 6 apples and 4 oranges, how many fruits are left in the store?

Instead of directly answering the question, the chain-of-thought prompting would require the language model to produce a series of short sentences that mimic a human's reasoning process:

The store has 10 apples.
The store has 8 oranges.
6 apples are sold.
4 oranges are sold.
There are 10 - 6 = 4 apples left.
There are 8 - 4 = 4 oranges left.
The store now has 4 apples + 4 oranges = 8 fruits.

Using self-consistency, the language model generates multiple reasoning paths:

Reasoning Path A:

The store has 10 apples.
The store has 8 oranges.
6 apples are sold.
4 oranges are sold.
There are 10 - 6 = 4 apples left.
There are 8 - 4 = 4 oranges left.
The store now has 4 apples + 4 oranges = 8 fruits.
Reasoning Path B:

The store initially has 10 apples and 8 oranges.
It sells 6 apples, so there are 10 - 6 = 4 apples left.
It sells 4 oranges, so there are 8 - 4 = 4 oranges left.
The store now has 4 apples + 4 oranges = 8 fruits.

翻译过来则为:

问题:如果一家商店有 10 个苹果和 8 个橙子,此时店里卖出了 6 个苹果和 4 个橙子,那么店里还剩下多少水果?

思维链提示(chain-of-thought prompting)不是直接回答问题,而是要求语言模型生成一系列模仿人类推理过程的短句:

商店有 10 个苹果。
店里有 8 个橙子。
卖了 6 个苹果。
卖了 4 个橙子。
还剩下 10 - 6 = 4 个苹果。
剩下 8 - 4 = 4 个橙子。
商店现在有 4 个苹果 + 4 个橙子 = 8 个水果。

使用 Self-consistency,语言模型生成多个推理路径:

推理路径A:

商店有 10 个苹果。
店里有 8 个橙子。
卖了 6 个苹果。
卖了 4 个橙子。
还剩下 10 - 6 = 4 个苹果。
剩下 8 - 4 = 4 个橙子。
商店现在有 4 个苹果 + 4 个橙子 = 8 个水果。

推理路径 B:

商店最初有 10 个苹果和 8 个橙子。
商店卖了 6 个苹果,所以还剩下 10 - 6 = 4 个苹果。
商店卖了 4 个橙子,所以还剩下 8 - 4 = 4 个橙子。
商店现在有 4 个苹果 + 4 个橙子 = 8 个水果。

Self-consistency 从生成的多个推理路径中选择最一致的答案。在这个例子中,推理路径 A 和 B 都得出相同的答案(8 个水果)。可以看到这种做法增加了模型对最终答案正确的信心。

Program-Aided

2022 年,根据Luyu Gao 等人的研究,在 LLM 模型中,即使使用了 Chain of Thought 的方法,也未必能拿到答案。Luyu Gao 的解决方法是在 prompt 里引入代码,并引导模型使用代码来运算和思考,最后答案就是正确的:
PAL001

prompt tips

To Do and Not To Do

在问答场景里,为了让 AI 回答更加准确,一般会在问题里加条件。比如让 AI 推荐一部电影给你 Recommend a movie to me 。但这个 prompt 太空泛了,AI 无法直接回答,接着它会问你想要什么类型的电影,但这样你就需要跟 AI 聊很多轮,效率比较低。

所以,为了提高效率,一般会在 prompt 里看到类似这样的话(意思是不要询问我对什么感兴趣,或者问我的个人信息):

DO NOT ASK FOR INTERESTS. DO NOT ASK FOR PERSONAL INFORMATION.

如果你在 ChatGPT 里这样提问,或者使用 ChatGPT 最新的 API ,它就不会问你问题,而是直接推荐一部电影给你,它的 Output 是这样的:

Certainly! If you're in the mood for an action-packed movie, you might enjoy "John Wick" (2014), directed by Chad Stahelski and starring Keanu Reeves. The movie follows a retired hitman named John Wick who seeks vengeance against the people who wronged him. It's a fast-paced and stylish film with lots of thrilling action sequences and an engaging story. If you're looking for something that will keep you on the edge of your seat, "John Wick" is definitely worth a watch!

但如果你使用的是如 Davinci-003 这样的模型,它的 Output 很可能是这样的,它还会问你的兴趣爱好:

Sure, I can recommend a movie based on your interests. What kind of movie would you like to watch? Do you prefer action, comedy, romance, or something else?

所以 OpenAI 的 API 最佳实践文档里,提到了一个这样的最佳实践:

Instead of just saying what not to do, say what to do instead. 与其告知模型不能干什么,不妨告诉模型能干什么。

我自己的实践是,虽然现在最新的模型已经理解什么是 Not Todo ,但如果你想要的是明确的答案,加入更多限定词,告知模型能干什么,回答的效率会更高,且预期会更明确。还是电影推荐这个案例,你可以加入一个限定词:

Recommend a movie from the top global trending movies to me.

当然并不是 Not Todo 就不能用,如果:

  • 你已经告知模型很明确的点,然后你想缩小范围,那增加一些 Not Todo 会提高不少效率。
  • 你是在做一些探索,比如你不知道如何做精准限定,你只知道不要什么。那可以先加入 Not Todo ,让 AI 先发散给你答案,当探索完成后,再去优化 prompt。

以下是一些场景案例,我整理了两个 Less Effective(不太有效的) 和 Better(更好的) prompt,你可以自己尝试下这些案例:

场景Less EffectiveBetter原因
推荐雅思必背英文单词Please suggest me some essential words for IELTSPlease suggest me 10 essential words for IELTS后者 prompt 会更加明确,前者会给大概 20 个单词。这个仍然有提升的空间,比如增加更多的限定词语,像字母 A 开头的词语。
推荐香港值得游玩的地方Please recommend me some places to visit in Hong Kong. Do not recommend museums.Please recommend me some places to visit in Hong Kong including amusement parks.后者的推荐会更准确高效一些,但如果你想进行一些探索,那前者也能用。

add examples

直接告知 AI 什么能做,什么不能做外。在某些场景下,我们能比较简单地向 AI 描述出什么能做,什么不能做。但有些场景,有些需求很难通过文字指令传递给 AI,即使描述出来了,AI 也不能很好地理解。

比如给宠物起英文名,里面会夹杂着一些所谓的名字风格。此时你就可以在 prompt里增加一些例子,我们看看这个例子:

Suggest three names for a horse that is a superhero.

Output 是这样的,第一个感觉还行,第二个 Captain 有 hero 的感觉,但 Canter 就像是说这匹马跑得很慢,而且三个都比较一般,不够酷。

Thunder Hooves, Captain Canter, Mighty Gallop

此时你就可以在 prompt 里增加一些案例:

Suggest three names for an animal that is a superhero.

Animal: Cat
Names: Captain Sharpclaw, Agent Fluffball, The Incredible Feline
Animal: Dog
Names: Ruff the Protector, Wonder Canine, Sir Barks-a-Lot
Animal: Horse
Names:

增加例子后,输出的结果就更酷一些,或者说是我想要的那种风格的名字。

Gallop Guardian, Equine Avenger, The Mighty Stallion

以下是一些场景案例,我整理了两个 Less Effective(不太有效的) 和 Better(更好的) prompt,你可以自己尝试下这些案例:

场景Less EffectiveBetter原因
起英文名Suggest three English names for a boy.Suggest three English names for a boy.
Here are some examples: Jimmy、Jason、James
可以在下方运行这个案例,在不给示例的情况下 AI 会给你什么答案。
将电影名称转为 emojiConvert Star Wars into emoji.Convert movie titles into emoji.
Back to the Future: 👨👴🚗🕒
Batman: 🤵🦇
Transformers: 🚗🤖
Star Wars:
可以在下方运行这个案例,在不给示例的情况下 AI 会给你什么答案。

引导词引导模型输出特定内容

例如,在 prompt 的最后增加 SELECT 可以很好地提示 AI 可以写 SQL 代码了。

Create a MySQL query for all students in the Computer Science Department:
Table departments, columns = [DepartmentId, DepartmentName]
Table students, columns = [DepartmentId, StudentId, StudentName]
SELECT

同样的道理,如果你想让 AI 写 Python 代码,那 import 会是比较好的提示。但需要注意,这个只是告知 AI 可以写代码了,并不能告知 AI 写何种代码,你仍然需要在 prompt 里增加提示,告知 AI 要生成何种语言的代码。

在吴恩达的 ChatGPT Prompt Engineering 课程中,也提到这个技巧,只是在课程中,引导词并不是放在最后,而是在 prompt 里直接说明,让 AI 生成一个 JSON 格式的内容。课程中的例子是这样的(注意这个是 python 代码):

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.
"""

关键是在 prompt 里跟 AI 说明,需要 AI 按照 JSON 格式输出内容。

add role

介绍一个有效的技巧,就是在 prompt 里增加一些 role(角色)相关的内容,让 AI 生成的内容更符合你的需求。

比如如果上一个回答比较复杂,希望重新回答,可以加入这样的一段话,让 AI 假设自己是一个小学老师,并且很擅长将复杂的内容转变成 7、8岁小朋友也能听懂的话,然后再改写这段话:

You are a primary school teacher who can explain complex content to a level that a 7 or 8 year old child can understand. Please rewrite the following sentences to make them easier to understand:

Output 就变成了下面这样。不管是用词,还是语法,看起来都更容易懂了。

OpenAI is a place where people work on making computers really smart. It's like a lab where they do research to make computers do amazing things! They want the computers to be really friendly and helpful to people. They use one of the most powerful computers in the world to do this research. A bunch of really rich and smart people gave money to start this lab. One of them is Elon Musk, but he left in 2018. Another really big company, Microsoft, gave them a lot of money too.

另外除了增加角色外,还能让 AI 模拟某个人,比如让 AI 以 David Foster Wallace 的风格改写上述那段话:

Imagine you are the famous writer David Foster Wallace, please rewrite this sentences.

Output 是这样的:

As David Foster Wallace, I might rewrite these sentences to sound more like this:

OpenAI is a lab that studies something called artificial intelligence, which is like when computers can do things that normally only humans can do. They have a big computer that's one of the most powerful in the world, and they're trying to make sure the AI they create is friendly and helpful. The lab was started in 2015 in a city called San Francisco, and a bunch of important people gave them a lot of money to do their research. One of those people was Elon Musk, who stopped working there but still gives them money, and Microsoft also gave them a lot of money recently.

关于这个技巧的应用,以及如何更好地使用 AI 提升写作能力,建议各位阅读 Nat Eliason 的 Using ChatGPT as a Writing Coach,他使用 ChatGPT 辅助其写作,就用到了上述的技巧。

特殊符号分割待处理文本和指令

不管是信息总结,还是信息提取,你一定会输入大段文字,甚至多段文字,此时有个小技巧。

可以用“”“将指令和文本分开。根据我的测试,如果你的文本有多段,增加”“”会提升 AI 反馈的准确性(这个技巧来自于 OpenAI 的 API 最佳实践文档

当然也能用 ### 符号区隔,不过#常 作为格式示例,太多 # 的话 prompt 会比较乱。

比如下面的 prompt 就属于 Less effective prompt。为什么呢?据我的测试,主要还是 AI 不知道什么是指令,什么是待处理的内容,用符号分隔开来会更利于 AI 区分。

Please summarize the following sentences to make them easier to understand.
OpenAI is an American artificial intelligence (AI) research laboratory consisting of the non-profit OpenAI Incorporated (OpenAI Inc.) and its for-profit subsidiary corporation OpenAI Limited Partnership (OpenAI LP). OpenAI conducts AI research with the declared intention of promoting and developing a friendly AI. OpenAI systems run on the fifth most powerful supercomputer in the world.[5][6][7] The organization was founded in San Francisco in 2015 by Sam Altman, Reid Hoffman, Jessica Livingston, Elon Musk, Ilya Sutskever, Peter Thiel and others,[8][1][9] who collectively pledged US$1 billion. Musk resigned from the board in 2018 but remained a donor. Microsoft provided OpenAI LP with a $1 billion investment in 2019 and a second multi-year investment in January 2023, reported to be $10 billion.[10]

Better prompt:

Please summarize the following sentences to make them easier to understand.

Text: """
OpenAI is an American artificial intelligence (AI) research laboratory consisting of the non-profit OpenAI Incorporated (OpenAI Inc.) and its for-profit subsidiary corporation OpenAI Limited Partnership (OpenAI LP). OpenAI conducts AI research with the declared intention of promoting and developing a friendly AI. OpenAI systems run on the fifth most powerful supercomputer in the world.[5][6][7] The organization was founded in San Francisco in 2015 by Sam Altman, Reid Hoffman, Jessica Livingston, Elon Musk, Ilya Sutskever, Peter Thiel and others,[8][1][9] who collectively pledged US$1 billion. Musk resigned from the board in 2018 but remained a donor. Microsoft provided OpenAI LP with a $1 billion investment in 2019 and a second multi-year investment in January 2023, reported to be $10 billion.[10]
"""

另外,在吴恩达的 ChatGPT Prompt Engineering 课程中,还提到,你可以使用其他特殊符号来分割文本和 prompt,比如<><tag></tag> 等,课程中的案例是这样的(注意这个是 python 代码,需要关注的是 prompt 里的 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}`
"""

如果你是在开发一款允许用户输入内容,并对内容进行总结的 AI 产品,那你就可以使用到这个技巧。

通过格式词阐述需要输出的格式

假设你想让 AI 总结一篇非常非常长的文章,并且按照特定格式给你总结,那你可以在文章前面明确输出的格式(完整案例)。它的意思其实是让 ChatGPT 按 Topic 总结,每个 Topic 里按照无序列表(就是里面那个 -)将每个 Topic 的主要观点罗列出来。

Summarize the main points of the following speech
Use the following format:
Topic 1: <topic_name_1>
- <point_1>
..
Topic 2: <topic_name_2>
- <point_1>
..
Topic 10: ..

Text: """
Thank you so much, Fred, for that lovely introduction. And thanks to the Atlantic Council for hosting me today.

The course of the global economy over the past two years has been shaped by COVID-19 and our efforts to fight the pandemic. It’s now evident, though, that the war between Russia and Ukraine has redrawn the contours of the world economic outlook. Vladimir Putin’s unprovoked attack on Ukraine and its people is taking a devastating human toll, with lives tragically lost, families internally displaced or becoming refugees, and communities and cities destroyed.
...

"""

Output 是这样的:

Topic 1: The war in Ukraine
- The war is taking a human toll with lives lost, families displaced, and communities destroyed
- The Biden administration is committed to holding Russia accountable
- The war has violated international law and is a challenge to the international order

Topic 2: The global economy
- The war is having negative impacts on the global economy, including higher commodity prices and inflation
- The IMF and World Bank will be focused on helping developing countries weather the impacts of the war
- The ultimate outcome for the global economy depends on the path of the war

关于这个场景和技巧,我想再解释一下为什么潜力很大。

根据我使用各种 Summary 或者信息提取的产品,我发现 AI 并不知道什么是重点,所以在总结的过程中,会丢失很多内容。如何引导 AI 进行总结,就变得非常重要,且具有一定的可玩性。

使用此技巧可以使输出更结构化。比如针对一篇文章进行问答,你不仅想要得到一个答案,也希望 ChatGPT 的答案符合特定的格式,方便你下一步进行自动化。

比如问 “这里的债券 duration 是多少?”. 正常 GPT 模型的答案可能是 “债券 duration 是 4 年” 或 “duration 4 年”。
ChatGPT 的回答不稳定,且不方便继续处理。

解法:
我们可以通过这个技巧,让模型理解我们预期的格式。并在此基础上,为了方便自动化,让模型输出特定的结构化答案 (比如 JSON/Markdown 等)。
也可以方便集成更多的额外要求,比如增加一个"confidence level", 并通过 prompt 的形式指定这些数值的格式。

比如:

{context}
Question: What is bond duration mentioned here.
Answer template (Valid JSON format):
{{
"duration": $duration_numeric_value_in_year,
"confidence_level": $answer_confidence_level_high_modrate_or_low,
}}
Answer:

在吴恩达的 ChatGPT Prompt Engineering 课程中,有提到一个这个技巧的高级用法,在让 AI 按照特定格式输出内容的同时,还让 AI 根据内容是否满足特定条件,来判断应该输出什么结果,下面课程中的案例的 prompt( python 代码有一些转义字符,可以忽略):

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}\"\"\"

简单解释下,这个 prompt 分成两步:

让 AI 将输入的 text 转为步骤(就是 prompt 里的 Step 1、2)

然后还增加了一个判断,如果输入的 text 里没有 step 的内容,那么就输出 No Step

假如输入的 text 是一个泡茶的步骤介绍:

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.

那么 AI 输出的内容是这样的(因为内容中包含了步骤式的内容):

Step 1 - Get some water boiling.
Step 2 - Grab a cup and put a tea bag in it.
Step 3 - Once the water is hot enough, pour it over the tea bag.
Step 4 - Let it sit for a bit so the tea can steep.
Step 5 - After a few minutes, take out the tea bag.
Step 6 - Add some sugar or milk to taste.
Step 7 - Enjoy your delicious cup of tea!

但如果我们输入的是这样的 text:

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.

从内容上看,这段话,没有任何步骤式的内容,所以 AI 的输出是这样的:

No steps provided.

加入特定符号,让模型知道如何处理特殊情况

这个解释起来有点复杂,以下是 OpenAI 的官方 prompt,在一些奇怪的问题上比如 What is Devz9 的回答,你可以用 ? 代替答案,让模型知道当遇到超出回答范围时,需要如何处理(注意:此方法在 playground 上有效,但在 ChatGPT 上无效)。

Q: Who is Batman?
A: Batman is a fictional comic book character.

Q: What is torsalplexity?
A: ?

Q: What is Devz9?
A: ?

Q: Who is George Lucas?
A: George Lucas is American film director and producer famous for creating Star Wars.

Q: What is the capital of California?
A: Sacramento.

Q: What is Kozar-09?
A: 

它的 Output 是这样的:

?

中文prompt tips

中文prompt模版

在这里插入图片描述
示例:
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

提升稳定性

在这里插入图片描述

文献

  1. Prompt-Engineering-Guide
  2. Learn Prompting
  3. ChatGPT3-Free-Prompt-List
  4. Natural Language Processing with Deep Learning
  5. edx ChatGPT101
  6. OpenAI Examples
  7. 1个Prompt框架+4个公式,讲清产品经理如何用ChatGPT让工作效率翻倍
  8. Learning Prompt
  • 7
    点赞
  • 32
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值