OpenAI官方《提示词工程课》超详细中文笔记 开发人员的ChatGPT提示工程对初学者友爱。只需求对Python有根本的了解。但它也适用于期望挨近快速工程的前沿并运用LLM的高级机器学习工程师。

该课程与OpenAI合作,旨在协助开发人员有用利用LLM,反映了对运用最新LLM模型提示的最佳实践的最新理解。

吴恩达作为AI届的泰斗,我十分认可吴恩达对末来的判别,可参阅:吴恩达来信:LLMs的夸姣末来

不要想偷闲,请不断学习!

请不要为在前期的苹果上花了1.99美元买了个手电筒运用就无比兴奋喜悦。作为人的价值,你要专心在运用 ChatGPT构建范畴内更杂乱的运用上。不管你来自什么范畴或行业。

面向人群:

  • 略微懂点python的小白。

  • 不理解python也能够通过ChatGPT快速自学。

  • 想要拿来开箱就用的小白,劝退!

你将在这门课程中学到什么

这是吴恩达和OpenAI提示词工程师官方出品的《ChatGPT Prompt Engineering for Developers》课程。

在ChatGPT Prompt Engineering for Developers中,您将学习怎么运用大型言语模型(LLM)快速构建新的强壮运用程序。运用OpenAI API,您将能够快速构建才干,学习以成本昂扬、高度技能性或曾经根本不或许的办法进行创新和发明价值。

这门课的内容包含

  1. 学习怎么运用大型言语模型 (LLM) 快速构建新的强壮运用程序。运用OpenAI API,您将能够快速构建学习创新 和发明价值的才干。这些才干在曾经由于成本昂扬、技能含量高根本不或许。
  2. 这门由Isa Fulford (OpenAI) 和Andrew Ng (DeepLearning.AI) 教授的短期课程将描绘 LLM 的作业原理,供给 快速工程的最佳实践,并展现 LLM API 怎么在运用程序中用于各种使命,包含:
  • 总结(例如,为了简练起见总结用户谈论)
  • 揣度(例如,心情分类、主题提取)
  • 转化文本(例如翻译、拼写和语法更正)
  • 扩展(例如,主动写电子邮件)

此外,您将学习编写有用提示的两个要害准则,怎么体系地设计好的提示,并学习构建自界说谈天机器人。

将学习编写有用提示的两个要害准则,怎么体系地设计好的提示,以及学习构建自界说谈天机器人。一切概念都用许多示例进行了阐明,您能够直接在咱们的Jupyter笔记本环境中玩这些示例,以取得即时工程的实践经历。

关于作者

Isa Fulford

Open AI技能人员Isa Fulford 是 ChatGPT Retrieval Plugin 的主要奉献者。该插件能够让用户以问答的办法轻松查找和查找个人或作业文档,在 GitHub 上 star 量现已过万。此外,Isa Fulford 在教授怎么将 LLM 用于产品方面也做了许多作业,是 OpenAI Cookbook(OpenAI API 的运用示例和攻略)的主要奉献者之一。

项目链接:github.com/openai/chat…

项目链接:github.com/openai/chat…

吴恩达

吴恩达是斯坦福大学核算机科学系和电气工程系的客座教授,曾任斯坦福人工智能试验室主任。此外,他仍是 DeepLearning.AI 的创始人、Landing AI 的创始人兼首席履行官、AI Fund 的普通合伙人、Coursera 的主席和联合创始人。

简介/Introduction

OpenAI官方《提示词工程课》超详细中文笔记

教育目标

本课程是面向ChatGPT提示工程的开发者课程。

吴恩达将与Isa Fulford一同教授这门课程。

关于Isa Fulford她是OpenAI技能人员,从前建立过受欢迎的ChatGPT检索揷件,而且一向在教导人们怎么在产品中 运用LLM或大型言语模型技能。她还为OpenAI CookBook 做出了奉献,教授人们提示技能。

在这门课程中,咱们将与您共享一些或许性,以及怎么完结这些或许性的最佳实践。

  1. 首要,您将学习一些用提示词做一个app开发的最佳实践。
  2. 然后咱们将介绍一些常见用例,例如总结、揣度、转化、扩展。
  3. 最终并带您运用LLM构建谈天机器人。

咱们期望这能激起您构建新运用程序的幻想力。

指令LLM

在构建大型言语模型或LLM的开发进程中,一般有两品种型的LLM,即根底LLM和指令调整LLM。

  • 根底LLM是依据文本练习数据进行练习的,一般是依据互联网和其他来历的许多数据进行练习,以猜测下一个单 词。
  • 而指令调整LLM是依据指令进行练习的。咱们一般会从一个现已过练习的根底LLM开端,然后进一步用输入和输 出来调整它,使其能够遵从指令,并通过人类反响来进一步优化。

因而,本课程即将点介绍指令调整LLM的最佳实践。

当您运用指令调整LLM时,请考虑将指令发送给一个聪明但不了解您使命细节的人。假如LLM不能正常作业,有时 是由于指令不行明晰。因而,鄙人一个视频中,您将学习怎么明晰明晰地表达指令以及给LLM时刻考虑的准则。

攻略/Guidelines

OpenAI官方《提示词工程课》超详细中文笔记

在这个视频中,Isa将介绍一些提示准则,以协助您取得想要的成果。具体而言,她将谈论两个要害准则,以有用地 编写提示工程师。稍后,当她讲解Jupyter笔记本示例时,我鼓舞您随时暂停视频以自行运转代码,以便您能够看到 输出成果,并测验更改切当的提示并玩一些不同的改动,以获取提示输入和输出的经历。

所以我将概述一些准则和战略,在运用ChatGPT等言语模型时会有所协助。我首要会在高层次上概述这些内容,然 后再通过实例运用具体的战略。咱们将在整个课程中运用这些相同的战略。

第一个准则:编写明晰和具体的指令。

第二个准则:给模型满意的时刻考虑。

环境预备

在咱们开端之前,咱们需求进行一些设置。

在整个课程中,咱们将运用OpenAI Python库来访问OpenAI API。

假如您还没有装置此Python库,您能够运用PIP进行装置,如下所示:

pip install openai

我现已装置了此包,因而不会履行此操作。然后,您需求导入OpenAI并设置您的OpenAI API密钥,它是一个隐秘 密钥。您能够从OpenAI网站获取其间一个API密钥。然后您只需像这样设置您的API密钥,并替换为您自己的API密 钥。假如您想要,也能够将其设置为环境变量。

import openai
import os
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())
openai.api_key = os.getenv('OPENAI_API_KEY')

在本课程中,您不需求履行任何此操作。您只需运转此代码,由于咱们现已在环境中设置了API密钥。我会将其复 制。不要忧虑这是怎么作业的。

在整个课程中,咱们将运用OpenAI的ChatGPT模型,GPT-3.5-Turbo。

协助函数

现在,咱们将界说此协助函数,以便更轻松地运用提示并查看生成的输出。函数getCompletion接收提示并回来该提示的完结成果。

def get_completion(prompt, model="gpt-3.5-turbo"):
    messages = [{"role": "user", "content": prompt}]
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=0, # this is the degree of randomness of the model's output
    )
    return response.choices[0].message["content"]

现在让咱们深化了解咱们的第一个准则,即编写明晰和具体的指令。您应该通过供给尽或许明晰和具体的指令来表达您想要模型履行的使命。这将引导模型朝着所需的输出方向,并削减获取无关或不正确呼应的时机。

明晰 ≠ 简略

不要混淆明晰的提示与简略的提示,由于在许多状况下,更长的提示实践上供给了更多的明晰度和上下文,这实践上能够导致更具体和相关的输出。协助您编写明晰和具体指令的第一个战略是运用分隔符明晰地指示输入的不同部分。

准则一:明晰具体的指令

技巧1:运用区分符

这段视频中,Isa向咱们介绍了两个提示编写准则,以协助咱们取得所需的成果。首要,咱们应该写出明晰和具体的指令,以引导模型生成咱们需求的输出,削减获取无关或过错呼应的或许性。与此相关的一个战略是运用分隔符,明晰指示输入的不同部分。这些分隔符能够是任何明晰的标点符号,例如三个反引号,引号,XML标记,部分标题等,让模型清楚地知道哪些是独立的部分,以防止提示注入。

️提示注入(Prompt Injection)是指用户增加输入到提示中,或许会与咱们的指令相对立,导致模型遵从用户的指令而不是咱们的指令。

示例中,咱们要求模型将由三个反引号括起来的文本总结成一个语句,以明晰地指示模型需求处理哪些文本部分。假如没有分隔符,用户或许会增加不相关的输入,导致模型输出过错的成果。因而,运用分隔符能够进步模型的精确性和稳定性。

  • 区分符能够是任何符号,比方“`, “””, < >, , :
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)
"""
To guide a model towards the desired output and reduce the chances of irrelevant or incorrect responses, it is important to provide clear and specific instructions, which may require longer prompts for more clarity and context.
"""

技巧2:结构化输出

下一个战略是要求结构化输出。为了更简略解析模型输出,要求模型以HTML或JSON等结构化格局供给输出或许是有协助的。在示例中,咱们要求模型生成三本虚拟图书的书名、作者和类型,并运用JSON格局以特定键的办法供给输出。咱们能够看到,咱们得到了三个格局杰出的虚拟图书的标题,并以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.
"""
response = get_completion(prompt)
print(response)
"""
[
  {
    "book_id": 1,
    "title": "The Lost City of Zorath",
    "author": "Aria Blackwood",
    "genre": "Fantasy"
  },
  {
    "book_id": 2,
    "title": "The Last Survivors",
    "author": "Ethan Stone",
    "genre": "Science Fiction"
  },
  {
    "book_id": 3,
    "title": "The Secret Life of Bees",
    "author": "Lila Rose",
    "genre": "Romance"
  }
]
"""

技巧3:条件是否满意

下一个战略是让模型查看条件是否被满意。假如使命有一些假定并不一定满意,咱们能够告知模型先查看这些假定,假如不满意,则指出并停止使命完结的测验。你也能够考虑潜在的鸿沟状况以及模型应该怎么处理它们,以防止意外过错或成果。在这个比方中,咱们给出了一段描绘泡茶进程的阶段,然后咱们用一个 prompt 让模型提取这些指令。假如它在文本中找不到任何指令,咱们让它输出“no steps provided”。在第二个阶段中,模型判别没有找到任何指令。

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)
Completion for Text 1:
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_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)
"""
Completion for Text 2:
No steps provided.
"""

技巧4:少样本提示

这个准则的最终一个战略是 few-shot prompting。这种办法是在让模型履行实践使命之前,供给现已成功履行所需使命的示例。在提示中,咱们告知模型其使命是以共同的风格答复问题,然后供给了一个孩子和祖父母之间的对话作为示例。孩子说,“教我怎么耐心等待”,祖父母用类比来答复。由于咱们告知模型要以共同的风格答复问题,所以当咱们下一个要求“教我关于韧性”的时分,由于模型现已有了这个 few-shot 的示例,它会以类似的办法答复这个问题,比方“韧性就像一棵能够跟着风摇曳却从不折断的树”,等等。

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)
"""
<grandparent>: Resilience is like a tree that bends with the wind but never breaks. It's the ability to bounce back from adversity and keep moving forward, even when things get tough. Just like a tree needs strong roots to withstand the storm, we need to cultivate inner strength and perseverance to overcome life's challenges.
"""

准则二:给模型考虑时刻

第二个准则是要给模型考虑的时刻。

假如模型在匆忙地做出过错的揣度,你应该测验重构查询,要求在模型供给最终答案之前进行一系列相关的推理。另一个考虑这个问题的办法是,假如你给模型一个太杂乱的使命,在短时刻内或用少数的字数内完结,它或许会猜测成果,这很或许是不正确的。这也会发生在人类身上。假如你要求一个人在没有时刻先核算答案的状况下完结一个杂乱的数学问题,他们也很或许会犯过错。因而,在这些状况下,你能够要求模型花更多的时刻考虑问题,这意味着它在使命上花费更多的核算功夫。

技巧1:给定进程来补全

首要,咱们能够运用明晰的进程来完结一个使命。在这个比方中,咱们给模型供给了一个包含Jack and Jill故事概述的阶段,而且运用明晰的进程指示模型完结四个使命:

  1. 首要,用一句话来概括文本
  2. 其次将概述翻译成法语
  3. 然后列出法语概述中的每个称号
  4. 而且输出一个JSON目标包含”French summary”和”num names”两个key。

最终咱们增加了这个阶段的文本。运转这个模型后,咱们能够看到模型别离完结了这四个使命,并按照咱们要求的格局输出了成果。

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)
"""
Completion for prompt 1:
Two siblings, Jack and Jill, go on a quest to fetch water from a well on a hilltop, but misfortune strikes and they both tumble down the hill, returning home slightly battered but with their adventurous spirits undimmed.
Deux frres et surs, Jack et Jill, partent en qute d'eau d'un puits sur une colline, mais un malheur frappe et ils tombent tous les deux de la colline, rentrant chez eux lgrement meurtris mais avec leurs esprits aventureux intacts. 
Noms: Jack, Jill.
{
  "french_summary": "Deux frres et surs, Jack et Jill, partent en qute d'eau d'un puits sur une colline, mais un malheur frappe et ils tombent tous les deux de la colline, rentrant chez eux lgrement meurtris mais avec leurs esprits aventureux intacts.",
  "num_names": 2
}
"""

现在我将向您展现另一个提示,以完结相同的使命。在这个提示中,我运用了一个我很喜爱运用的格局,来指定模型的输出结构。

由于正如您在这个示例中留意到的那样,这个称号的标题是法语的,这或许不是咱们想要的。假如咱们要传递这个输出,或许会有一些困难和不可猜测性。因而,在这个提示中,咱们要求类似的内容,即开端时要求相同的进程,然后要求模型运用以下格局:文本、摘要、翻译、称号和输出JSON。

接着,咱们只需输入要摘要的文本,或许只需说“text”。然后,咱们开端运转代码。能够看到,这是完结的成果。模型运用了咱们要求的格局。因而,有时这很好,由于它将更简略传递代码,由于它具有愈加标准化的格局,能够更好地猜测。

一同请留意,在这种状况下,咱们运用了尖括号作为分隔符,而不是三个反引号。你能够挑选任何对你来说有意义或对模型有意义的分隔符。

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)
"""
Completion for prompt 2:
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 qute d'eau, mais un malheur frappe et ils tombent de la colline, rentrant chez eux lgrement meurtris mais avec leurs esprits aventureux intacts.
Names: Jack, Jill
Output JSON: {"french_summary": "Jack et Jill partent en qute d'eau, mais un malheur frappe et ils tombent de la colline, rentrant chez eux lgrement meurtris mais avec leurs esprits aventureux intacts.", "num_names": 2}
"""

技巧2:让模型先梳理再给定论

咱们的下一个战略是指示模型在匆忙做出定论之前自行处理问题。有时,当咱们明晰指示模型在得出定论之前先理清作业的顺序时,咱们会取得更好的成果。这与咱们之前谈论的给模型时刻来处理问题的主见是相同的,就像人相同,咱们让它自己考虑处理方案,而不是立刻判别答案是否正确。

在这个问题中,咱们要求模型判别学生的答复是否正确。首要,咱们有这个数学问题,然后是学生的答复。

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:
Land cost: 100x
Solar panel cost: 250x
Maintenance cost: 100,000 + 100x
Total cost: 100x + 250x + 100,000 + 100x = 450x + 100,000
"""
response = get_completion(prompt)
print(response)
"""
The student's solution is correct.
"""

现实上,学生的答复是过错的,由于他们核算了维护费用为100,000加100x,但实践上应该是10x,由于每平方英尺只要10美元,其间x是装置面积的大小(以平方英尺为单位)。因而,应该是360x加100,000,而不是450x。

假如咱们运转这个单元格代码,模型会说学生的答复是正确的。

假如您仔细阅览学生的答复,您会发现这实践上是过错的,由于模型仅仅粗略地阅览了它,就像我方才所做的那样。

因而,咱们能够通过指示模型先核算自己的答复,然后再将其与学生的答复进行比较来处理这个问题。咱们能够通过一个更长的提示来完结这一点。咱们告知模型如下:

您的使命是确认学生的答复是否正确。要处理这个问题,请履行以下进程。

  1. 首要,核算出您自己的答复。
  2. 然后将您的答复与学生的答复进行比较,并点评学生的答复是否正确。

在你自己解题之前,不要决议学生的答复是否正确。保证您自己处理了这个问题。

因而,咱们运用了相同的格局,即问题、学生答复、实践答复,以及答复是否共同(是或否)和学生的成果(正确或过错)。因而,咱们有与上面相同的问题和答复。

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:
Land cost: 100x
Solar panel cost: 250x
Maintenance cost: 100,000 + 100x
Total cost: 100x + 250x + 100,000 + 100x = 450x + 100,000
```
Actual solution:
"""
response = get_completion(prompt)
print(response)
"""
Let x be the size of the installation in square feet.
Costs:
Land cost: 100x
Solar panel cost: 250x
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
"""

那么现在,假如咱们运转这个单元格……正如你看到的,这个模型实践上首要进行了自己的核算。然后,它找到了正确的答案,即360x加上100,000,而不是450x加上100,000。然后,当被要求将其与学生的处理方案进行比较时,它意识到它们不共同。因而,学生实践上是不正确的。这是一个比方,展现了学生的处理方案是正确的,但学生的处理方案实践上是过错的。这是一个比方,展现了让模型自己进行核算,并将使命分解为进程,以便给模型更多的时刻考虑,能够协助您取得更精确的呼应。

束缚:模型错觉

接下来,咱们将谈论一些模型的束缚,由于我以为在运用大型言语模型开发运用程序时,紧记这些束缚十分重要。假如模型在练习进程中接触到许多的常识,它并不是完美地记住了它看到的信息,因而它并不很好地知道它的常识鸿沟。这意味着它或许会测验答复关于晦涩话题的问题,而且或许会假造听起来合理但实践上不正确的内容。咱们将这些假造的主见称为错觉。

我将给您展现一个比方,其间模型会发生错觉。这是一个比方,其间模型从一个实在的牙刷公司发明了一个虚拟的产品姓名。因而,提示是“告知我关于Boy的AeroGlide Ultra Slim Smart Toothbrush。”假如咱们运转这个提示,模型将为咱们供给一个适当逼真的虚拟产品的描绘。这种状况或许比较危险,由于这听起来十分实在。

因而,请保证在构建自己的运用程序时运用咱们在这个笔记本中介绍的一些技巧,尽量防止这种状况。这是模型已知的弱点,咱们正在活跃努力处理。在文本中寻觅相关引证,并要求模型运用这些引证来答复问题,而且有一种追溯答案到源文档的办法,一般能够削减这些错觉。

prompt = f"""
Tell me about AeroGlide UltraSlim Smart Toothbrush by Boie
"""
response = get_completion(prompt)
print(response)
"""
The AeroGlide UltraSlim Smart Toothbrush by Boie is a high-tech toothbrush that uses advanced sonic technology to provide a deep and thorough clean. It features a slim and sleek design that makes it easy to hold and maneuver, and it comes with a range of smart features that help you optimize your brushing routine.
One of the key features of the AeroGlide UltraSlim Smart Toothbrush is its advanced sonic technology, which uses high-frequency vibrations to break up plaque and bacteria on your teeth and gums. This technology is highly effective at removing even the toughest stains and buildup, leaving your teeth feeling clean and fresh.
In addition to its sonic technology, the AeroGlide UltraSlim Smart Toothbrush also comes with a range of smart features that help you optimize your brushing routine. These include a built-in timer that ensures you brush for the recommended two minutes, as well as a pressure sensor that alerts you if you're brushing too hard.
Overall, the AeroGlide UltraSlim Smart Toothbrush by Boie is a highly advanced and effective toothbrush that is perfect for anyone looking to take their oral hygiene to the next level. With its advanced sonic technology and smart features, it provides a deep and thorough clean that leaves your teeth feeling fresh and healthy.
"""

这便是提示攻略的全部内容,接下来您将转到下一个视频,该视频将介绍迭代提示开发进程。

关于反斜杠的阐明:

在本课程中,咱们运用反斜杠\来使文本习惯屏幕而不刺进换行符’\n’字符。

GPT-3实践上不受您是否刺进换行符的影响。可是在运用LLM时,您或许需求考虑您的提示中的换行符是否会影响模型的性能。

迭代/Iterative

暂时无法在飞书文档外展现此内容

当我运用大型言语模型构建运用程序时,我从来没有在第一次测验中得到最终运用程序中运用的提示。但这并不重要。只要您有一个杰出的迭代进程,使您的提示不断改善,那么您就能得到适宜您想要完结的使命的提示。

你或许听我说过,当我练习一个机器学习模型时,它简直从来没有在第一次测验时成功。现实上,假如我练习的第一个模型成功了,我会感到十分惊奇。

在提示方面,它第一次成功的概率或许略微高一些,但正如他所说的,第一个提示是否成功并不重要。最重要的是得到适用于您的运用程序的提示的进程。因而,让咱们进入代码并展现一些框架,以考虑怎么迭代地开发提示。

假如您之前参加过我的机器学习课程,您或许会看到我运用一个图表,说在机器学习开发中,您常常有一个主见,然后完结它。编写代码,获取数据,练习模型,这就给您一个试验成果。然后您能够查看该输出,进行过错剖析,找出哪些地方作业或不作业,然后乃至能够改动您要处理的问题或怎么处理它的切当主见,并更改完结并运转另一个试验等,一遍又一遍地迭代,以取得有用的机器学习模型。

假如您对机器学习不熟悉,而且曾经没有看过这个图表,请不要忧虑,关于本次演示的其余部分来说,这并不重要。可是,当您编写提示以运用OOM开发运用程序时,该进程或许十分类似,您能够有一个关于您想要完结的使命的主见,然后测验编写第一个提示,期望它明晰具体,并或许在恰当的状况下给体系一些时刻来考虑,然后运转它并查看成果。

假如第一次不能很好地作业,那么迭代进程就开端了,找出指令不行明晰或没有给算法满意的时刻考虑的原因,使您能够不断完善主见、完善提示等等,直到您得到适宜您运用程序的提示。这也是为什么我个人没有太重视互联网上那些说30个完美提示的文章,由于我以为或许并不存在一个适用于一切状况的完美提示。更重要的是,您要有一个针对特定运用程序开发杰出提示的流程。让咱们一同看一个示例代码。这是之前视频中看到的初始代码,它现已移植了OpenAI和Port OS。

环境预备

这儿咱们获取了Open AI API密钥,这是上一次您看到的同一辅佐函数。

import openai
import os
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # read local .env file
openai.api_key  = os.getenv('OPENAI_API_KEY')
def get_completion(prompt, model="gpt-3.5-turbo"):
    messages = [{"role": "user", "content": prompt}]
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=0, # this is the degree of randomness of the model's output
    )
    return response.choices[0].message["content"]

事例1:生成产品描绘

在这个视频中,我将运用一个生成产品描绘的使命作为运转示例。让我把它张贴在这儿。假如需求,能够随时暂停视频,然后在左侧的笔记本中仔细阅览。

这是一个椅子的现实表,其间描绘了它是一个美丽的中世纪灵感宗族的一部分,讲述了结构,尺度,椅子选项,资料等。它来自意大利。所以,假定您想要将这个现实表供给给营销团队,以协助他们为在线零售网站编撰描绘。

我将这样阐明我的使命,然后张贴到代码中。

fact_sheet_chair = """
OVERVIEW
- Part of a beautiful family of mid-century inspired office furniture, 
including filing cabinets, desks, bookcases, meeting tables, and more.
- Several options of shell color and base finishes.
- Available with plastic back and front upholstery (SWC-100) 
or full upholstery (SWC-110) in 10 fabric and 6 leather options.
- Base finish options are: stainless steel, matte black, 
gloss white, or chrome.
- Chair is available with or without armrests.
- Suitable for home or business settings.
- Qualified for contract use.
CONSTRUCTION
- 5-wheel plastic coated aluminum base.
- Pneumatic chair adjust for easy raise/lower action.
DIMENSIONS
- WIDTH 53 CM | 20.87”
- DEPTH 51 CM | 20.08”
- HEIGHT 80 CM | 31.50”
- SEAT HEIGHT 44 CM | 17.32”
- SEAT DEPTH 41 CM | 16.14”
OPTIONS
- Soft or hard-floor caster options.
- Two choices of seat foam densities: 
 medium (1.8 lb/ft3) or high (2.8 lb/ft3)
- Armless or 8 position PU armrests 
MATERIALS
SHELL BASE GLIDER
- Cast Aluminum with modified nylon PA6/PA66 coating.
- Shell thickness: 10 mm.
SEAT
- HD36 foam
COUNTRY OF ORIGIN
- Italy
"""

所以我的提示是:您的使命是协助营销团队依据技能现实表为零售网站或产品创立描绘,编写产品描绘等。

这是我向大型言语模型解说使命的第一次测验。让我按Shift + Enter,这需求几秒钟运转,咱们得到了成果。


Python
prompt = f"""
Your task is to help a marketing team create a 
description for a retail website of a product based 
on a technical fact sheet.
Write a product description based on the information 
provided in the technical specifications delimited by 
triple backticks.
Technical specifications: ```{fact_sheet_chair}```
"""
response = get_completion(prompt)
print(response)
"""
Introducing our stunning mid-century inspired office chair, the perfect addition to any home or business setting. Part of a beautiful family of office furniture, including filing cabinets, desks, bookcases, meeting tables, and more, this chair is available in several options of shell color and base finishes to suit your style. Choose from plastic back and front upholstery (SWC-100) or full upholstery (SWC-110) in 10 fabric and 6 leather options.
The chair is constructed with a 5-wheel plastic coated aluminum base and features a pneumatic chair adjust for easy raise/lower action. It is available with or without armrests and is qualified for contract use. The base finish options are stainless steel, matte black, gloss white, or chrome.
Measuring at a width of 53 cm, depth of 51 cm, and height of 80 cm, with a seat height of 44 cm and seat depth of 41 cm, this chair is designed for ultimate comfort. You can also choose between soft or hard-floor caster options and two choices of seat foam densities: medium (1.8 lb/ft3) or high (2.8 lb/ft3). The armrests are available in either an armless or 8 position PU option.
The materials used in the construction of this chair are of the highest quality. The shell base glider is made of cast aluminum with modified nylon PA6/PA66 coating and has a shell thickness of 10 mm. The seat is made of HD36 foam, ensuring maximum comfort and durability.
This chair is made in Italy and is the perfect combination of style and functionality. Upgrade your workspace with our mid-century inspired office chair today!
"""

看起来它现已很好地写了一个描绘,介绍了一款令人惊叹的中世纪灵感办公椅,完美的版型等等。

问题1:生成的内容太长

可是当我看到这个成果时,我觉得,哇,这太长了。它确实做到了我要求它做的作业,也便是从技能现实表开端写产品描绘。可是当我看到这个成果时,我觉得这有点长。或许咱们期望它再短一点。

所以我想到了一个主见,我编写了一个提示并得到了成果。我对它不是很满意,由于它太长了,所以我会弄清我的提示,说运用最多50个单词来更好地辅导所需长度,然后再次运转它。看起来这是一个更好的产品简略描绘,介绍了一个中世纪灵感的办公椅,一同又时髦又有用。不错。

prompt = f"""
Your task is to help a marketing team create a 
description for a retail website of a product based 
on a technical fact sheet.
Write a product description based on the information 
provided in the technical specifications delimited by 
triple backticks.
Use at most 50 words.
Technical specifications: ``{fact_sheet_chair}``
"""
response = get_completion(prompt)
print(response)
```
Introducing our mid-century inspired office chair, part of a beautiful furniture family. Available in various shell colors and base finishes, with plastic or full upholstery options in fabric or leather. Suitable for home or business use, with a 5-wheel base and pneumatic chair adjust. Made in Italy.
```

让我再承认一下这个长度。我将获取呼应,依据空格进行切割,然后你将打印出长度。所以有52个单词。其实还不错。大型言语模型在遵从十分精确的单词计数指令方面体现还能够,但并不是特别超卓。但这个成果实践上还不错。有时会输出60或65个单词,但这还算是合理范围内的。有些作业你能够这样做。让我再次运转一下。但这些都是告知大型言语模型您想要的输出长度的不同办法。所以这是一个、两个、三个。我数了这些语句。看起来我做得不错。我也看到有些人有时会像这样做,我不知道,运用至多280个字符。由于大型言语模型解说文本的办法,运用一种称为分词器的东西,因而它们在核算字符数方面体现一般。可是,281个字符。它实践上十分挨近。一般,大型言语模型无法抵达这种程度。但这些都是能够测验的不同办法,以控制输出的长度。但接着,咱们只需将其切换回最多运用50个单词即可。这便是咱们方才得到的成果。

问题2:面向受众不对

当咱们持续为咱们的网站批改这段文本时,咱们或许会决议,哇,这个网站不是直接出售给消费者,而是旨在向家具零售商出售家具,他们更感兴趣的是椅子的技能细节和资料。在这种状况下,您能够采用这个提示,并说,我要批改这个提示,使其更精确地描绘技能细节。

因而,让我持续批改这个提示。我要说,这个描绘是为家具零售商而设计的,因而应该是技能性的,要点放在资料、产品和结构方面。好的,让咱们运转它。

prompt = f"""
Your task is to help a marketing team create a 
description for a retail website of a product based 
on a technical fact sheet.
Write a product description based on the information 
provided in the technical specifications delimited by 
triple backticks.
The description is intended for furniture retailers, 
so should be technical in nature and focus on the 
materials the product is constructed from.
Use at most 50 words.
Technical specifications: ``{fact_sheet_chair}``
"""
response = get_completion(prompt)
print(response)
"""
Introducing our mid-century inspired office chair, perfect for both home and business settings. With a range of shell colors and base finishes, including stainless steel and matte black, this chair is available with or without armrests. The 5-wheel plastic coated aluminum base and pneumatic chair adjust make it easy to move and adjust to your desired height. Made with high-quality materials, including a cast aluminum shell and HD36 foam seat, this chair is built to last.
"""

看起来不错。它说,镀铝底座和气动椅子。高质量资料。通过批改提示,您能够让它更专心于您想要的特定特征。当我看到这个时,我或许会决议,在描绘的结尾处,我还想包含产品ID。因而,我能够进一步改善这个提示。为了让它给我产品ID,我能够在描绘的结尾处增加这个指令,在技能标准中包含每个7个字符的产品ID。让咱们运转它,看看会发生什么。

prompt = f"""
Your task is to help a marketing team create a 
description for a retail website of a product based 
on a technical fact sheet.
Write a product description based on the information 
provided in the technical specifications delimited by 
triple backticks.
The description is intended for furniture retailers, 
so should be technical in nature and focus on the 
materials the product is constructed from.
At the end of the description, include every 7-character 
Product ID in the technical specification.
Use at most 50 words.
Technical specifications: ``{fact_sheet_chair}``
"""
response = get_completion(prompt)
print(response)
"""
chair, perfect for home or business settings. With a range of shell colors and base finishes, and the option of plastic or full upholstery, this chair is both stylish and comfortable. Constructed with a 5-wheel plastic coated aluminum base and pneumatic chair adjust, it's also practical. Available with or without armrests and suitable for contract use. Product ID: SWC-100, SWC-110.
"""

于是它说,介绍咱们的中世纪办公椅,壳颜色,讲述塑料涂层铝底座,有用,一些选项,讲述了两个产品ID。看起来不错。

您方才所看到的是许多开发者即将阅历的迭代提示开发的简略示例。我以为一个攻略是,在上一个视频中,您看到Yisa共享了许多最佳实践。因而,我一般会紧记这些最佳实践,明晰明晰地表达指令,假如需求,给模型一些时刻去考虑。有了这些主见,一般值得测验首次编写提示,查询发生了什么,然后从那里开端迭代优化提示,以逐渐挨近所需的成果。因而,许多成功的提示,您或许会在各种程序中看到,都是通过这样的迭代进程取得的。

问题3:用表格描绘

让咱们来玩一下,我想给你展现一个更杂乱的提示示例,让你感受一下ChatGPT的才干。我在这儿增加了一些额定的指令。在描绘之后,包含一个给出产品尺度的表格,然后将一切内容格局化为HTML。那么让咱们运转它。

prompt = f"""
Your task is to help a marketing team create a 
description for a retail website of a product based 
on a technical fact sheet.
Write a product description based on the information 
provided in the technical specifications delimited by 
triple backticks.
The description is intended for furniture retailers, 
so should be technical in nature and focus on the 
materials the product is constructed from.
At the end of the description, include every 7-character 
Product ID in the technical specification.
Use at most 50 words.
Technical specifications: ``{fact_sheet_chair}``
"""
response = get_completion(prompt)
print(response)
"""
<div>
<h2>Mid-Century Inspired Office Chair</h2>
<p>Introducing our mid-century inspired office chair, part of a beautiful family of office furniture that includes filing cabinets, desks, bookcases, meeting tables, and more. This chair is available in several options of shell color and base finishes, allowing you to customize it to your liking. You can choose between plastic back and front upholstery or full upholstery in 10 fabric and 6 leather options. The base finish options are stainless steel, matte black, gloss white, or chrome. The chair is also available with or without armrests, making it suitable for both home and business settings. Plus, it's qualified for contract use, ensuring its durability and longevity.</p>
<p>The chair's construction features a 5-wheel plastic coated aluminum base and a pneumatic chair adjust for easy raise/lower action. You can also choose between soft or hard-floor caster options and two choices of seat foam densities: medium (1.8 lb/ft3) or high (2.8 lb/ft3). The armrests are also customizable, with the option of armless or 8 position PU armrests.</p>
<p>The materials used in the chair's construction are of the highest quality. The shell base glider is made of cast aluminum with modified nylon PA6/PA66 coating, with a shell thickness of 10 mm. The seat is made of HD36 foam, ensuring maximum comfort and support.</p>
<p>Made in Italy, this mid-century inspired office chair is the perfect addition to any office space. Order yours today!</p>
<h3>Product IDs:</h3>
<ul>
<li>SWC-100</li>
<li>SWC-110</li>
</ul>
</div>
<table>
  <caption>Product Dimensions</caption>
  <tr>
    <th>Dimension</th>
    <th>Measurement (inches)</th>
  </tr>
  <tr>
    <td>Width</td>
    <td>20.87"</td>
  </tr>
  <tr>
    <td>Depth</td>
    <td>20.08"</td>
  </tr>
  <tr>
    <td>Height</td>
    <td>31.50"</td>
  </tr>
  <tr>
    <td>Seat Height</td>
    <td>17.32"</td>
  </tr>
  <tr>
    <td>Seat Depth</td>
    <td>16.14"</td>
  </tr>
</table>
"""

在实践中,你最终会得到像这样的提示,这一般需求多次迭代才干完结。我不以为有人在测验让体系处理一份现实表格时会一开端就写出这个切当的提示。因而,这实践上输出了一堆HTML代码。让咱们显现HTML,看看它是否是有用的HTML,看看它是否可行。我并不确认它是否可行,但让咱们看看。

OpenAI官方《提示词工程课》超详细中文笔记

哦,很帅。好的,看起来像是一个烘托图。它有一个十分美丽的椅子描绘,包含结构、资料和产品尺度。

哦,看起来我忘记了最多运用50个单词的指令,所以这有点长,可是假如您需求的话,能够随时暂停视频,让它变得更简练,并重新生成,看看成果怎么。

因而,我期望您从本视频中了解到,提示开发是一个迭代的进程。测验一些东西,看看它还不能彻底满意您的要求,然后考虑怎么弄清您的指令,或许在某些状况下,考虑给它更多的考虑空间,以使其更挨近于发生您想要的成果。

我以为成为有用的提示工程师的要害不是知道完美的提示,而是具有一个杰出的进程来开发对您的运用程序有用的提示。

在本视频中,我只举了一个比方来阐明怎么开发提示。关于更杂乱的运用程序,有时您会有多个比方,比方10个、50个或100个现实表,并逐步开发和对许多事例进行点评。

可是关于大多数运用程序的前期开发,我看到许多人会像我相同只运用一个示例进行开发,可是关于更老练的运用程序,有时对多个示例进行提示点评或许是有用的,比方在多个现实表上测验不同的提示,以查看均匀或最差状况的性能怎么。

但一般只要当运用程序更老练时,您才需求这些指标来驱动提示改善的最终几个增量进程。因而,请测验运用Jupyter代码笔记本示例,并测验不同的变体,看看您得到的成果怎么。完结后,请持续下一个视频,咱们将谈论大型言语模型在软件运用程序中十分常见的一种用处,即对文本进行摘要。

摘要/ Summarizing

暂时无法在飞书文档外展现此内容

当今世界上有太多的文字,简直没有人有满意的时刻去阅览咱们期望有时刻阅览的一切内容。因而,我看到的最令人兴奋的大型言语模型的运用之一是运用它来概括文本。

我看到多个团队将其集成到多个软件运用程序中。您能够在Chat GPT Web界面上完结这项作业。我常常运用它来概括文章,这样我就能够阅览比曾经更多的文章内容。

假如您想以编程办法进行此操作,您将在本课程中了解到怎么操作。因而,让咱们深化了解代码,看看怎么运用它来概括文本。

环境预备

因而,让咱们从导入OpenAI、加载API密钥以及这个getCompletion辅佐函数的相同的开端代码开端。

import openai
import os
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # read local .env file
openai.api_key  = os.getenv('OPENAI_API_KEY')
def get_completion(prompt, model="gpt-3.5-turbo"): # Andrew mentioned that the prompt/ completion paradigm is preferable for this class
    messages = [{"role": "user", "content": prompt}]
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=0, # this is the degree of randomness of the model's output
    )
    return response.choices[0].message["content"]

字数束缚

我将运用“总结此产品谈论”的示例来运转代码。我从女儿的生日上得到了这个熊猫毛绒玩具,她很喜爱,到处带着等等。假如您正在构建电子商务网站,而且有许多的谈论,那么概括冗长的谈论的东西或许会让您快速地阅览更多谈论,以更好地了解您一切客户的主见。

prod_review = """
Got this panda plush toy for my daughter's birthday, \
who loves it and takes it everywhere. It's soft and \ 
super cute, and its face has a friendly look. It's \ 
a bit small for what I paid though. I think there \ 
might be other options that are bigger for the \ 
same price. It arrived a day earlier than expected, \ 
so I got to play with it myself before I gave it \ 
to her.
"""

这儿有一个用于生成摘要的提示。您的使命是从电商网站的产品谈论中生成一个简略的摘要,在最多30个单词内概括以下谈论等。因而,这是一个软软的、心爱的熊猫毛绒玩具,遭到女儿的喜爱,但价格有点小,提早到货。还不错,这是一个适当好的摘要。正如您在前一个视频中所看到的,您还能够通过控制字符计数或语句数等来影响这个摘要的长度。有时,在创立摘要时,假如您对摘要有一个十分具体的意图,例如,假如您想向物流部分供给反响,您还能够批改提示以反映这一点,以便它能够生成一个更适用于您事务中的一个特定组的摘要。

prompt = f"""
Your task is to generate a short summary of a product \
review from an ecommerce site. 
Summarize the review below, delimited by triple 
backticks, in at most 30 words. 
Review: ``{prod_review}``
"""
response = get_completion(prompt)
print(response)
"""
Soft and cute panda plush toy loved by daughter, but a bit small for the price. Arrived early.
"""

专心物流

例如,假如我想向物流部分供给反响,我能够将这个提示批改为要点重视说到了哪些方面与产品的物流和交付相关。假如我运转这个提示,那么它将生成一个摘要,但不是从“软软的、心爱的熊猫毛绒玩具”开端,而是侧重于它提早了一天到货的现实,然后仍然有其他的细节。

prompt = f"""
Your task is to generate a short summary of a product \
review from an ecommerce site to give feedback to the \
Shipping deparmtment. 
Summarize the review below, delimited by triple 
backticks, in at most 30 words, and focusing on any aspects \
that mention shipping and delivery of the product. 
Review: ``{prod_review}``
"""
response = get_completion(prompt)
print(response)
"""
The panda plush toy arrived a day earlier than expected, but the customer felt it was a bit small for the price paid.
"""

专心价格

或许举个比方,假如咱们不是企图向物流部分供给反响,而是想向定价部分供给反响,那么定价部分担任确认产品的价格。我会让它重视与价格和感知价值相关的任何方面。然后这将生成一个不同的摘要,说或许价格对其尺度来说太高了。在我为物流部分或定价部分生成的摘要中,它愈加侧重于与这些具体部分相关的信息。现实上,随时随地能够暂停视频,然后让它为担任产品客户体验的产品部分生成信息。或许为您以为或许与电商网站有关的其他内容生成信息。但在这些摘要中,即使它生成了与物流相关的信息,它也有其他的信息,您能够决议是否有协助。

prompt = f"""
Your task is to generate a short summary of a product \
review from an ecommerce site to give feedback to the \
pricing deparmtment, responsible for determining the \
price of the product.  
Summarize the review below, delimited by triple 
backticks, in at most 30 words, and focusing on any aspects \
that are relevant to the price and perceived value. 
Review: ``{prod_review}``
"""
response = get_completion(prompt)
print(response)
"""
The panda plush toy is soft, cute, and loved by the recipient, but the price may be too high for its size.
"""

因而,依据您想要总结的办法,您还能够要求它提取信息,而不是总结它。

下面是一个提示,表示您的使命是提取相关信息,以便向运输部分供给反响。现在它只说产品提早了一天抵达,没有其他信息,虽然在一般的摘要中也有期望的内容,但假如运输部分只想知道发生了什么,那么这些内容与其不太相关。

prompt = f"""
Your task is to extract relevant information from \ 
a product review from an ecommerce site to give \
feedback to the Shipping department. 
From the review below, delimited by triple quotes \
extract the information relevant to shipping and \ 
delivery. Limit to 30 words. 
Review: ``{prod_review}``
"""
response = get_completion(prompt)
print(response)
"""
The product arrived a day earlier than expected.
"""

最终,让我与您共享一个具体的示例,阐明怎么在作业流程中运用它来协助总结多个谈论,以使它们更易于阅览。所以,这儿有几篇谈论。这有点长,可是这是第二篇关于一个站立灯的谈论,它能够用于卧室。这是第三篇关于电动牙刷的谈论。我的牙医推荐了它。这是关于搅拌机的谈论,当他们说那个季节性出售的17件套装等等。实践上,这是许多文本。假如您想要,能够随时暂停视频并具体阅览一切这些内容。可是,假如您想要知道这些谈论者写了什么,而不必停下来具体阅览一切内容,该怎么办呢?所以我将谈论1设置为咱们之前所看到的产品谈论。并将一切这些谈论放入列表中。

review_1 = prod_review
review for a standing lamp
review_2 = """
Needed a nice lamp for my bedroom, and this one \
had additional storage and not too high of a price \
point. Got it fast - arrived in 2 days. The string \
to the lamp broke during the transit and the company \
happily sent over a new one. Came within a few days \
as well. It was easy to put together. Then I had a \
missing part, so I contacted their support and they \
very quickly got me the missing piece! Seems to me \
to be a great company that cares about their customers \
and products. 
"""
review for an electric toothbrush
review_3 = """
My dental hygienist recommended an electric toothbrush, \
which is why I got this. The battery life seems to be \
pretty impressive so far. After initial charging and \
leaving the charger plugged in for the first week to \
condition the battery, I've unplugged the charger and \
been using it for twice daily brushing for the last \
3 weeks all on the same charge. But the toothbrush head \
is too small. I’ve seen baby toothbrushes bigger than \
this one. I wish the head was bigger with different \
length bristles to get between teeth better because \
this one doesn’t.  Overall if you can get this one \
around the $50 mark, it's a good deal. The manufactuer's \
replacements heads are pretty expensive, but you can \
get generic ones that're more reasonably priced. This \
toothbrush makes me feel like I've been to the dentist \
every day. My teeth feel sparkly clean! 
"""
review for a blender
review_4 = """
So, they still had the 17 piece system on seasonal \
sale for around $49 in the month of November, about \
half off, but for some reason (call it price gouging) \
around the second week of December the prices all went \
up to about anywhere from between $70-$89 for the same \
system. And the 11 piece system went up around $10 or \
so in price also from the earlier sale price of $29. \
So it looks okay, but if you look at the base, the part \
where the blade locks into place doesn’t look as good \
as in previous editions from a few years ago, but I \
plan to be very gentle with it (example, I crush \
very hard items like beans, ice, rice, etc. in the \ 
blender first then pulverize them in the serving size \
I want in the blender then switch to the whipping \
blade for a finer flour, and use the cross cutting blade \
first when making smoothies, then use the flat blade \
if I need them finer/less pulpy). Special tip when making \
smoothies, finely cut and freeze the fruits and \
vegetables (if using spinach-lightly stew soften the \ 
spinach then freeze until ready for use-and if making \
sorbet, use a small to medium sized food processor) \ 
that you plan to use that way you can avoid adding so \
much ice if at all-when making your smoothie. \
After about a year, the motor was making a funny noise. \
I called customer service but the warranty expired \
already, so I had to buy another one. FYI: The overall \
quality has gone done in these types of products, so \
they are kind of counting on brand recognition and \
consumer loyalty to maintain sales. Got it in about \
two days.
"""
reviews = [review_1, review_2, review_3, review_4]
for i in range(len(reviews)):
    prompt = f"""
    Your task is to generate a short summary of a product \ 
    review from an ecommerce site. 
    Summarize the review below, delimited by triple \
    backticks in at most 20 words. 
    Review: ``{reviews[i]}``
    """
    response = get_completion(prompt)
    print(i, response, "\n")
"""
0 Soft and cute panda plush toy loved by daughter, but a bit small for the price. Arrived early. 
1 Affordable lamp with storage, fast shipping, and excellent customer service. Easy to assemble and missing parts were quickly replaced. 
2 Good battery life, small toothbrush head, but effective cleaning. Good deal if bought around $50. 
3 The product was on sale for $49 in November, but the price increased to $70-$89 in December. The base doesn't look as good as previous editions, but the reviewer plans to be gentle with it. A special tip for making smoothies is to freeze the fruits and vegetables beforehand. The motor made a funny noise after a year, and the warranty had expired. Overall quality has decreased. 
"""

现在,假如我在谈论上完结一个for循环。这是我的提示,我要求它在最多20个单词中进行总结。然后让它获取呼应并将其打印出来。让咱们运转它。

它打印出第一个谈论是Pantatoi谈论,灯的谈论总结,牙刷的谈论总结,然后是搅拌机。因而,假如您有一个具有数百条谈论的网站,您能够幻想怎么运用这个功能构建一个仪表板,以获取许多谈论的简略摘要,以便您或其他人能够更快地阅览谈论。然后,假如他们愿意,能够单击以查看原始的长谈论。这能够协助您有用地了解一切客户的主见。

这便是关于总结的全部内容。我期望您能够幻想假如您有任何包含许多文本的运用程序,怎么运用这些提示来对它们进行总结,以协助人们快速了解文本中的内容,以及或许挑选更深化地发掘。

鄙人一个视频中,咱们将看看大型言语模型的另一个才干,即运用文本进行揣度。例如,假如您有产品谈论并想要快速了解哪些产品谈论具有正面或负面心情,该怎么做呢?让咱们鄙人一个视频中看看怎么做到这一点。

推理/Inferring

暂时无法在飞书文档外展现此内容

下一个视频是关于揣度的。我以为这些使命是指模型将文本作为输入并履行某种剖析的使命。因而,这能够是提取标签、提取称号、理解文本的情感等使命。例如,假如您想从一段文本中提取活跃或消沉的情感,在传统的机器学习作业流程中,您需求搜集标签数据集、练习模型、确认怎么在云中布置模型并进行揣度。这或许十分有用,可是需求阅历许多的作业流程。而关于每个使命,例如情感、提取称号等,您都需求练习和布置单独的模型。

大型言语模型的一个很好的长处是,关于许多这样的使命,您只需求编写一个提示,就能够当即开端生成成果。这在运用程序开发方面具有巨大的速度优势。而且,您能够只运用一个模型、一个API来履行许多不同的使命,而不需求找出怎么练习和布置许多不同的模型。因而,让咱们跳进代码中,看看您怎么利用这一点。下面是一个惯例的开端代码,我将运转它。

环境预备

import openai
import os
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # read local .env file
openai.api_key  = os.getenv('OPENAI_API_KEY')
def get_completion(prompt, model="gpt-3.5-turbo"):
    messages = [{"role": "user", "content": prompt}]
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=0, # this is the degree of randomness of the model's output
    )
    return response.choices[0].message["content"]

情感剖析

我要运用的最重要的比方是一个台灯的点评。所以我需求一款适宜卧室的美观台灯,而且带有额定的储物空间等等。

lamp_review = """
Needed a nice lamp for my bedroom, and this one had \
additional storage and not too high of a price point. \
Got it fast.  The string to our lamp broke during the \
transit and the company happily sent over a new one. \
Came within a few days as well. It was easy to put \
together.  I had a missing part, so I contacted their \
support and they very quickly got me the missing piece! \
Lumina seems to me to be a great company that cares \
about their customers and products!!
"""

现在让我写一个提示来分类这个点评的情感。假如我想让体系告知我这个点评的情感,我只需求写下“以下产品点评的情感是什么”,然后加上一般的分隔符和点评文本等等。然后运转它。

prompt = f"""
What is the sentiment of the following product review, 
which is delimited with triple backticks?
Review text: '''{lamp_review}'''
"""
response = get_completion(prompt)
print(response)
"""
The sentiment of the product review is positive.
"""

输出成果是这个产品点评的情感是活跃的,这好像适当正确。这个灯不是完美的,可是这位顾客好像很满意。这好像是一个关怀客户和产品的好公司。我以为活跃情感好像是正确的答案。

现在这个程序打印了整个语句,“这个产品点评的情感是活跃的”。假如你想要一个更简练的答复,以便更简略进行后处理,我能够增加另一个指令,让它只答复一个单词,活跃或消沉。

prompt = f"""
What is the sentiment of the following product review, 
which is delimited with triple backticks?
Give your answer as a single word, either "positive" \
or "negative".
Review text: '''{lamp_review}'''
"""
response = get_completion(prompt)
print(response)
"""
positive
"""

这样它就会像这样输出“活跃”,这样一个文本处理程序就更简略获取这个输出并进行处理。

接下来让咱们看另一个提示,仍然是运用这个灯的点评。在这儿,我让它辨认出以下点评作者表达的心情列表,包含不超越五个项目。

prompt = f"""
Identify a list of emotions that the writer of the \
following review is expressing. Include no more than \
five items in the list. Format your answer as a list of \
lower-case words separated by commas.
Review text: '''{lamp_review}'''
"""
response = get_completion(prompt)
print(response)
"""
happy, satisfied, grateful, impressed, content
"""

大型言语模型十分擅长从一段文本中提取特定内容。在这种状况下,咱们正在表达情感。这关于了解客户对特定产品的主见或许十分有用。关于许多客户支撑组织来说,了解特定用户是否十分懊丧十分重要。因而,您或许有一个不同的分类问题,例如“以下谈论的作者是否表达了愤恨?”

prompt = f"""
Is the writer of the following review expressing anger?\
The review is delimited with triple backticks. \
Give your answer as either yes or no.
Review text: '''{lamp_review}'''
"""
response = get_completion(prompt)
print(response)
"""
No
"""

由于假如有人真的很气愤,那么或许需求特别留意客户的谈论,以便客户支撑或客户成功联络客户并弄清楚状况,并为客户处理问题。

在这种状况下,客户并没有气愤。请留意,运用监督学习,假如我想构建一切这些分类器,那么我无法在短短几分钟内完结这项作业,但您能够暂停此视频并测验更改某些提示,以获取对此灯谈论进行不同揣度的提示。

接下来,我将展现您能够运用该体系履行的其他使命,特别是从客户谈论中提取更丰厚的信息。信息提取是NLP(自然言语处理)的一部分,它涉及从文本中提取您想要了解的特定信息。

信息抽取

在这个提示中,我要求它辨认以下内容:产品购买项和制造产品的公司称号。假如您企图总结来自在线购物电子商务网站的许多谈论,确认物品、制造商、确认活跃和消沉心情,跟踪特定物品或特定制造商的活跃或消沉心情趋势或许会对您的许多谈论很有用。在这个比方中,我即将求它将呼应格局化为具有项目和品牌键的JSON目标。

prompt = f"""
Identify the following items from the review text: 
Item purchased by reviewer
Company that made the item
The review is delimited with triple backticks. \
Format your response as a JSON object with \
"Item" and "Brand" as the keys. 
If the information isn't present, use "unknown" \
as the value.
Make your response as short as possible.
Review text: '''{lamp_review}'''
"""
response = get_completion(prompt)
print(response)
"""
{
  "Item": "lamp",
  "Brand": "Lumina"
}
"""

因而,假如我这样做,它会说项目是灯,品牌是Luminar,您能够轻松地将其加载到Python字典中,然后对此输出进行进一步处理。

多使命抽取

在咱们阅历的比方中,您能够看到怎么编写提示来辨认心情,确认或人是否气愤,然后提取物品和品牌。提取一切这些信息的一种办法是运用3或4个提示并调用getCompletion,您能够一次一个地提取这些不同的字段,但现实证明,您实践上能够编写单个提示以一同提取一切这些信息。

prompt = f"""
Identify the following items from the review text: 
Sentiment (positive or negative)
Is the reviewer expressing anger? (true or false)
Item purchased by reviewer
Company that made the item
The review is delimited with triple backticks. \
Format your response as a JSON object with \
"Sentiment", "Anger", "Item" and "Brand" as the keys.
If the information isn't present, use "unknown" \
as the value.
Make your response as short as possible.
Format the Anger value as a boolean.
Review text: '''{lamp_review}'''
"""
response = get_completion(prompt)
print(response)
"""
{
  "Sentiment": "positive",
  "Anger": false,
  "Item": "lamp with additional storage",
  "Brand": "Lumina"
}
"""

让咱们来举一个比方,比方辨认精密项目,提取情感,作为谈论者表达愤恨,购买产品,彻底做到了。在这儿,我还要告知它将愤恨值格局化为布尔值,然后让我运转一下,这将输出一个JSON,其间情感是活跃的,愤恨,而且false周围没有引号,由于我要求它将其作为布尔值输出。

它将项目提取为一个带有额定存储空间的台灯,而不是仅仅的台灯,这看起来还不错。这样,您能够运用一个单独的提示从文本中提取多个字段。假如有需求,您能够暂停视频并自己测验不同的变体,乃至测验输入彻底不同的谈论,以查看是否仍然能够精确提取这些内容。

主题分类

我看到大型言语模型的一个很帅的运用是揣度主题。给定一篇长文,你知道,这篇文章是关于什么的?有哪些话题?这是一篇虚拟的关于政府工人对他们作业的机构感受的报纸文章。所以,最近政府进行了一项查询,你知道,等等,NASA的成果是一个受欢迎的部分,具有很高的满意度评分。我是NASA的粉丝,我喜爱他们所做的作业,但这是一篇虚拟的文章。因而,鉴于这样的一篇文章,咱们能够问它,在这个提示下,确认以下文本中正在谈论的五个主题。让咱们把每个项目格局化成一个或两个单词长,将您的呼应格局化为逗号分隔的列表,假如咱们运转它,你知道,咱们会得到这篇文章是关于政府查询的,它是关于作业满意度的,它是关于NASA的等等。总的来说,我以为它适当不错,它提取了一个主题列表。

暂时无法在飞书文档外展现此内容

story = """
In a recent survey conducted by the government, 
public sector employees were asked to rate their level 
of satisfaction with the department they work at. 
The results revealed that NASA was the most popular 
department with a satisfaction rating of 95%.
One NASA employee, John Smith, commented on the findings, 
stating, "I'm not surprised that NASA came out on top. 
It's a great place to work with amazing people and 
incredible opportunities. I'm proud to be a part of 
such an innovative organization."
The results were also welcomed by NASA's management team, 
with Director Tom Johnson stating, "We are thrilled to 
hear that our employees are satisfied with their work at NASA. 
We have a talented and dedicated team who work tirelessly 
to achieve our goals, and it's fantastic to see that their 
hard work is paying off."
The survey also revealed that the 
Social Security Administration had the lowest satisfaction 
rating, with only 45% of employees indicating they were 
satisfied with their job. The government has pledged to 
address the concerns raised by employees in the survey and 
work towards improving job satisfaction across all departments.
"""
prompt = f"""
Determine five topics that are being discussed in the \
following text, which is delimited by triple backticks.
Make each item one or two words long. 
Format your response as a list of items separated by commas.
Text sample: '''{story}'''
"""
response = get_completion(prompt)
print(response.split(sep=','))
"""
['government survey',
 ' job satisfaction',
 ' NASA',
 ' Social Security Administration',
 ' employee concerns']
"""

当然,您也能够将其拆分,以获取这篇文章谈论的五个主题的清单。

prompt = f"""
Determine whether each item in the following list of \
topics is a topic in the text below, which
is delimited with triple backticks.
Give your answer as list with 0 or 1 for each topic.\
List of topics: {", ".join(topic_list)}
Text sample: '''{story}'''
"""
response = get_completion(prompt)
print(response)
"""
nasa: 1
local government: 0
engineering: 0
employee satisfaction: 1
federal government: 1
"""
topic_dict = {i.split(': ')[0]: int(i.split(': ')[1]) for i in response.split(sep='\n')}
if topic_dict['nasa'] == 1:
    print("ALERT: New NASA story!")

假如你有一组文章并提取出主题,那么你也能够运用大型言语模型来协助你索引不同的主题。假定咱们是一个新闻网站,这是咱们追踪的主题:NASA,当地政府,工程,员工满意度和联邦政府。假定你想弄清楚给定一篇新闻文章,其间包含哪些主题。运用以下提示:确认以下主题列表中的每个项目是否是文本下的主题。为每个主题供给0或1的答案列表。只需运用一个提示,就能够确认新闻文章涉及的主题,并能够将此信息放入字典中,以便快速处理任何文章,确认其主题,并在主题包含NASA时打印出新NASA故事的警报。值得留意的是,上述提示并不是十分强健的。

假如我去生产体系,我或许会让它以JSON格局输出答案,而不是作为列表,由于大型言语模型的输出或许有些不共同。因而,这实践上是一段适当脆弱的代码。可是假如您想,在看完本视频后,能够测验批改此提示,使其输出JSON而不是像这样的列表,然后有一个更强健的办法来确认更大的文章是否是关于NASA的故事。

这便是揣度的内容,只需求几分钟的时刻,您就能够构建多个用于对文本进行揣度的体系,而曾经这或许需求一个熟练的机器学习开发人员几天乃至几周的时刻。因而,我以为这十分令人兴奋,无论是关于熟练的机器学习开发人员仍是关于新手来说,您现在都能够运用提示来快速构建并开端揣度这些适当杂乱的自然言语处理使命。鄙人一个视频中,咱们将持续谈论能够运用大型言语模型完结的一些令人兴奋的作业,并持续介绍转化。您怎么将一段文本转化为另一段文本,例如将其翻译成另一种言语?让咱们进入下一个视频。

转化 / Transforming

暂时无法在飞书文档外展现此内容

大型言语模型十分擅长将其输入转化为不同的格局,例如输入一段文本,将其转化或翻译为另一种言语,或协助拼写和语法纠正,即输入或许不彻底契合语法的文本,协助您略微修复一下,乃至能够转化格局,例如输入HTML并输出JSON。因而,我从前写过一些运用程序,用了许多惯例表达式,现在运用大型言语模型和几个提示能够更简略地完结这些运用程序。

我现在简直用Chat GPT来校正我写的一切东西,所以我很高兴现在在笔记本上向您展现更多的示例。因而,首要咱们将导入OpenAI并运用在视频中一向运用的getCompletion协助函数。

环境预备

import openai
import os
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # read local .env file
openai.api_key  = os.getenv('OPENAI_API_KEY')
def get_completion(prompt, model="gpt-3.5-turbo", temperature=0):
    messages = [{"role": "user", "content": prompt}]
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=temperature, 
    )
    return response.choices[0].message["content"]

翻译

咱们将首要做一个翻译使命。大型言语模型一般在许多来历的许多文本上进行练习,其间许多文本都是来自互联网,而这些文本又是不同的言语。因而,这使得模型具有进行翻译的才干。这些模型掌握了数百种言语,但掌握程度各不相同。接下来,咱们将介绍怎么运用这种才干的一些示例。

让咱们从一些简略的内容开端。在第一个比方中,提示是将以下英文文本翻译为西班牙文。 Hi, I would like to order a blender. 的呼应是Hola,me gustara ordenar una licuadora。在这儿,我十分抱歉一切的西班牙语听众,我不会西班牙语,这一点您肯定能够看出来。

prompt = f"""
Translate the following English text to Spanish: \ 
I would like to order a blender```
"""
response = get_completion(prompt)
print(response)
"""
Hola, me gustara ordenar una licuadora.
"""

现在让咱们试试另一个比方。在这个比方中,提示是告知我这是哪种言语。然后这段文本是法语,Combien cote la lampe d’air。模型辨认出这是法语。

prompt = f"""
Tell me which language this is: 
cote le lampadaire?```
"""
response = get_completion(prompt)
print(response)
"""
This is French.
"""

模型还能够一同进行多种翻译。在这个比方中,让咱们假定将以下文本翻译为法语和西班牙语。而且,让咱们再加上一个英语海盗。文本是 I want to order a basketball。所以在这儿,咱们有法语、西班牙语和英语海盗。

prompt = f"""
Translate the following  text to French and Spanish
and English pirate: \
want to order a basketball```
"""
response = get_completion(prompt)
print(response)
"""
French pirate: ``Je veux commander un ballon de basket``
Spanish pirate: ``Quiero ordenar una pelota de baloncesto``
English pirate: ``I want to order a basketball``
"""

在某些言语中,翻译或许会因说话者与听众的关系而改动。您还能够向言语模型解说这一点。因而,它将能够相应地进行翻译。在这个比方中,咱们说,将以下文本翻译为西班牙语的正式和非正式办法。Would you like to order a pillow? 还要留意,这儿咱们运用的是。只要有一定的明晰分隔就能够了。所以,这儿咱们有正式和非正式之分。正式场合是指当你和一个比你资历高的人说话或许在一个工作场合时,你需求运用正式口气;而非正式则是当你和朋友集体交流时运用。

我实践上不会说西班牙语,可是我父亲会说,他说这是正确的。

prompt = f"""
Translate the following text to Spanish in both the \
formal and informal forms: 
'Would you like to order a pillow?'
"""
response = get_completion(prompt)
print(response)
"""
Formal: Le gustara ordenar una almohada?
Informal: Te gustara ordenar una almohada?
"""

通用翻译

接下来的比方中,咱们假定咱们是一个跨国电子商务公司的担任人,用户的音讯将运用各种不同的言语,而且用户将运用多种言语向咱们反映其 IT 问题,因而咱们需求一种通用的翻译器。首要,咱们将张贴一些不同言语的用户音讯列表,然后咱们将循环遍历每一个用户音讯。因而,在用户音讯中循环遍历问题,然后我将复制这个略微长一点的代码块。首要,咱们将问询模型告知咱们问题是用什么言语书写的。然后,咱们将打印出原始音讯的言语和问题,并要求模型将其翻译成英文和韩文。让咱们运转它。

user_messages = [
  "La performance du systme est plus lente que d'habitude.",  # System performance is slower than normal         
  "Mi monitor tiene pxeles que no se iluminan.",              # My monitor has pixels that are not lighting
  "Il mio mouse non funziona",                                 # My mouse is not working
  "Mj klawisz Ctrl jest zepsuty",                             # My keyboard has a broken control key
  "我的屏幕在闪耀"                                               # My screen is flashing
] 
for issue in user_messages:
    prompt = f"Tell me what language this is: ``{issue}``"
    lang = get_completion(prompt)
    print(f"Original message ({lang}): {issue}")
    prompt = f"""
    Translate the following  text to English \
    and Korean: ``{issue}``
    """
    response = get_completion(prompt)
    print(response, "\n")
"""
Original message (This is French.): La performance du systme est plus lente que d'habitude.
English: The system performance is slower than usual.
Korean: 시스템 성능이 평소보다 느립니다. 
Original message (This is Spanish.): Mi monitor tiene pxeles que no se iluminan.
English: My monitor has pixels that don't light up.
Korean: 내 모니터에는 불이 켜지지 않는 픽셀이 있습니다. 
Original message (This is Italian.): Il mio mouse non funziona
English: My mouse is not working.
Korean: 내 마우스가 작동하지 않습니다. 
Original message (This is Polish.): Mj klawisz Ctrl jest zepsuty
English: My Ctrl key is broken.
Korean: 제 Ctrl 키가 고장 났어요. 
Original message (This is Chinese (Simplified).): 我的屏幕在闪耀
English: My screen is flickering.
Korean: 내 화면이 깜빡입니다. 
"""

风格转化

在这儿,咱们有一个更正式的商业信函,其间包含一份落地灯标准的主张书。接下来咱们要做的作业是在不同的格局之间进行转化。

prompt = f"""
Translate the following from slang to a business letter: 
'Dude, This is Joe, check out this spec on this standing lamp.'
"""
response = get_completion(prompt)
print(response)
"""
Dear Sir/Madam,
I am writing to bring to your attention a standing lamp that I believe may be of interest to you. Please find attached the specifications for your review.
Thank you for your time and consideration.
Sincerely,
Joe
"""

ChatGPT十分擅长在不同格局之间进行翻译,例如JSON到HTML、XML等各种格局。在提示中,咱们将描绘输入和输出格局。以下是一个示例:咱们有一个包含餐厅员工姓名和电子邮件的JSON列表。在提示中,咱们即将求模型将其从JSON转化为HTML表格。然后咱们将得到模型的呼应并打印出来,以便查看通过格局化后的HTML表格。

data_json = { "resturant employees" :[     {"name":"Shyam", "email":"shyamjaiswal@gmail.com"},    {"name":"Bob", "email":"bob32@gmail.com"},    {"name":"Jai", "email":"jai87@gmail.com"}]}
prompt = f"""
Translate the following python dictionary from JSON to an HTML \
table with column headers and title: {data_json}
"""
response = get_completion(prompt)
print(response)
"""
<table>
  <caption>Restaurant Employees</caption>
  <thead>
    <tr>
      <th>Name</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Shyam</td>
      <td>shyamjaiswal@gmail.com</td>
    </tr>
    <tr>
      <td>Bob</td>
      <td>bob32@gmail.com</td>
    </tr>
    <tr>
      <td>Jai</td>
      <td>jai87@gmail.com</td>
    </tr>
  </tbody>
</table>
"""

OpenAI官方《提示词工程课》超详细中文笔记

拼写语法查看

接下来的转化使命是拼写查看和语法查看。这是ChatGPT的一个十分受欢迎的运用。咱们主张您常常运用它,特别是在运用非母言语语时十分有用。以下是一些常见的语法和拼写问题以及怎么运用言语模型来处理它们的示例。咱们将列举一些语句,这些语句中存在某些语法或拼写过错。然后咱们将循环遍历每个语句,恳求模型进行校正和批改。然后咱们会得到呼应并像平常相同将其打印出来。模型能够纠正一切这些语法过错。咱们能够运用之前谈论过的一些技巧来改善提示。为了改善提示,咱们能够说“校正并更正以下文本。假如你没有找到任何过错,请说没有过错。”通过迭代的提示开发,您能够找到一个更牢靠的提示。

text = [
  "The girl with the black and white puppies have a ball.",  # The girl has a ball.
  "Yolanda has her notebook.", # ok
  "Its going to be a long day. Does the car need it’s oil changed?",  # Homonyms
  "Their goes my freedom. There going to bring they’re suitcases.",  # Homonyms
  "Your going to need you’re notebook.",  # Homonyms
  "That medicine effects my ability to sleep. Have you heard of the butterfly affect?", # Homonyms
  "This phrase is to cherck chatGPT for speling abilitty"  # spelling
]
for t in text:
    prompt = f"""Proofread and correct the following text
    and rewrite the corrected version. If you don't find
    and errors, just say "No errors found". Don't use 
    any punctuation around the text:
    ``{t}``"""
    response = get_completion(prompt)
    print(response)
 """
 The girl with the black and white puppies has a ball.
No errors found.
It's going to be a long day. Does the car need its oil changed?
Their goes my freedom. There going to bring they're suitcases.
Corrected version: 
There goes my freedom. They're going to bring their suitcases.
You're going to need your notebook.
That medicine affects my ability to sleep. Have you heard of the butterfly effect?
This phrase is to check ChatGPT for spelling ability.
 """

另一个比方是查看您在公共论坛上发布文本之前进行拼写和语法查看的示例。咱们将运用一份有关填充熊猫的谈论的示例,然后要求模型对谈论进行校正和更正。最终,咱们将得到更正后的版别。

text = f"""
Got this for my daughter for her birthday cuz she keeps taking \
mine from my room.  Yes, adults also like pandas too.  She takes \
it everywhere with her, and it's super soft and cute.  One of the \
ears is a bit lower than the other, and I don't think that was \
designed to be asymmetrical. It's a bit small for what I paid for it \
though. I think there might be other options that are bigger for \
the same price.  It arrived a day earlier than expected, so I got \
to play with it myself before I gave it to my daughter.
"""
prompt = f"proofread and correct this review: ``{text}``"
response = get_completion(prompt)
print(response)
"""
I got this for my daughter's birthday because she keeps taking mine from my room. Yes, adults also like pandas too. She takes it everywhere with her, and it's super soft and cute. However, one of the ears is a bit lower than the other, and I don't think that was designed to be asymmetrical. Additionally, it's a bit small for what I paid for it. I think there might be other options that are bigger for the same price. On the positive side, it arrived a day earlier than expected, so I got to play with it myself before I gave it to my daughter.
"""

咱们能够做的一件很帅的作业是找到原始谈论和模型输出之间的差异。因而,咱们将运用这个RedLines Python包来做这件作业。咱们将取得咱们谈论的原始文本和模型输出之间的差异,然后将其显现出来。在这儿,您能够看到原始谈论和模型输出之间的差异以及现已更正的内容。

from redlines import Redlines
diff = Redlines(text,response)
display(Markdown(diff.output_markdown))

OpenAI官方《提示词工程课》超详细中文笔记

因而,咱们运用的提示是“校正并更正此谈论”,但您还能够进行更明显的更改,例如改动口气等。让咱们再试试其他东西。在这个提示中,咱们即将求模型校正和更正同一篇谈论,一同使其更有吸引力,保证它遵从APA风格,并面向高级读者。咱们还即将求以markdown格局输出。因而,咱们在上面运用的是来自原始谈论的相同文本。让咱们履行一下。在这儿,咱们有一篇扩展的APA风格谈论《软性熊猫》。

prompt = f"""
proofread and correct this review. Make it more compelling. 
Ensure it follows APA style guide and targets an advanced reader. 
Output in markdown format.
Text: ``{text}``
"""
response = get_completion(prompt)
display(Markdown(response))
"""
Title: A Soft and Cute Panda Plushie for All Ages
As an adult, I can attest that pandas are not just for kids. That's why I got this adorable panda plushie for my daughter's birthday, after she kept taking mine from my room. And let me tell you, it was a hit!
The plushie is super soft and cuddly, making it the perfect companion for my daughter. She takes it everywhere with her, and it has quickly become her favorite toy. However, I did notice that one of the ears is a bit lower than the other, which I don't think was designed to be asymmetrical. But that doesn't take away from its cuteness.
The only downside is that it's a bit small for the price I paid. I think there might be other options that are bigger for the same price. But overall, I'm happy with my purchase.
One thing that surprised me was that it arrived a day earlier than expected. This gave me the chance to play with it myself before giving it to my daughter. And I have to say, I was impressed with the quality and attention to detail.
In conclusion, if you're looking for a soft and cute panda plushie for yourself or a loved one, this is definitely a great option. Just be aware that it might be a bit smaller than expected.
"""

这便是转化视频的全部内容。接下来,咱们将进行扩展,从言语模型中生成更长、更自在的呼应。

扩写 / Expanding

暂时无法在飞书文档外展现此内容

扩展是将短的文本片段,比方一组阐明或一系列主题,并让大型言语模型生成更长的文本,比方关于某个主题的电子邮件或论文的使命。这样做很有用,比方假如你把大型言语模型作为头脑风暴的合作伙伴。但我也想指出,这样做有一些问题,比方假如有人用它生成许多的垃圾邮件。因而,当你运用大型言语模型的这些功能时,请担任任地运用,并以有助于人们的办法运用。在这个视频中,咱们将演示怎么运用言语模型依据某些信息生成个性化的电子邮件。这封电子邮件有点自称为来自 AI 机器人,这一点十分重要,如安德鲁所说到的。咱们还将运用另一个模型输入参数,称为温度,这使您能够改动模型呼应中的探究和多样性程度。让咱们开端吧。

环境预备

所以在咱们开端之前,咱们要做一些一般的设置。所以设置OpenAI Python包,然后界说咱们的协助函数get完结。

import openai
import os
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # read local .env file
openai.api_key  = os.getenv('OPENAI_API_KEY')
def get_completion(prompt, model="gpt-3.5-turbo",temperature=0): # Andrew mentioned that the prompt/ completion paradigm is preferable for this class
    messages = [{"role": "user", "content": prompt}]
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=temperature, # this is the degree of randomness of the model's output
    )
    return response.choices[0].message["content"]

主动回复邮件

现在咱们要为客户谈论编写一个自界说的电子邮件回复,因而给定客户谈论和心情,咱们将生成一个自界说的回复。现在咱们将运用言语模型依据客户谈论和谈论的心情为客户生成一个自界说的电子邮件。所以咱们现已运用咱们在揣度视频中看到的那种提示提取了心情,然后这是搅拌器的客户谈论,现在咱们将依据心情定制回复。

given the sentiment from the lesson on "inferring",
and the original customer message, customize the email
sentiment = "negative"
review for a blender
review = f"""
So, they still had the 17 piece system on seasonal \
sale for around $49 in the month of November, about \
half off, but for some reason (call it price gouging) \
around the second week of December the prices all went \
up to about anywhere from between $70-$89 for the same \
system. And the 11 piece system went up around $10 or \
so in price also from the earlier sale price of $29. \
So it looks okay, but if you look at the base, the part \
where the blade locks into place doesn’t look as good \
as in previous editions from a few years ago, but I \
plan to be very gentle with it (example, I crush \
very hard items like beans, ice, rice, etc. in the \ 
blender first then pulverize them in the serving size \
I want in the blender then switch to the whipping \
blade for a finer flour, and use the cross cutting blade \
first when making smoothies, then use the flat blade \
if I need them finer/less pulpy). Special tip when making \
smoothies, finely cut and freeze the fruits and \
vegetables (if using spinach-lightly stew soften the \ 
spinach then freeze until ready for use-and if making \
sorbet, use a small to medium sized food processor) \ 
that you plan to use that way you can avoid adding so \
much ice if at all-when making your smoothie. \
After about a year, the motor was making a funny noise. \
I called customer service but the warranty expired \
already, so I had to buy another one. FYI: The overall \
quality has gone done in these types of products, so \
they are kind of counting on brand recognition and \
consumer loyalty to maintain sales. Got it in about \
two days.
"""

因而,这儿的阐明是您是一名客户服务AI助理,您的使命是发送一封关于您的客户的电子邮件回复,给定由三个反引号分隔的客户电子邮件,生成回复以感谢客户的谈论。假如心情是活跃或中立的,感谢他们的谈论。假如心情是消沉的,抱歉并主张他们能够联络客户服务。保证运用谈论中的具体细节,以简练和专业的口气书写,并以客户署理AI身份签署电子邮件。

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)
print(response)
"""
Dear Valued Customer,
Thank you for taking the time to leave a review about our product. We are sorry to hear that you experienced an increase in price and that the quality of the product did not meet your expectations. We apologize for any inconvenience this may have caused you.
We would like to assure you that we take all feedback seriously and we will be sure to pass your comments along to our team. If you have any further concerns, please do not hesitate to reach out to our customer service team for assistance.
Thank you again for your review and for choosing our product. We hope to have the opportunity to serve you better in the future.
Best regards,
AI customer agent
"""

当您运用言语模型生成文本时,您将向用户展现这种透明度十分重要,让用户知道他们看到的文本是由AI生成的。然后咱们将输入客户谈论和谈论心情。还要留意,这部分不一定重要,由于咱们实践上能够运用此提示来提取谈论心情,然后在后续进程中编写电子邮件。但为了示例,咱们现已从谈论中提取了心情。因而,这儿咱们有对客户的回复。它处理了客户在谈论中说到的细节。就像咱们指示的那样,主张他们联络客户服务,由于这仅仅一个AI的客户服务署理。

接下来,咱们将运用言语模型中的一个参数,称为温度,它将允许咱们改动模型呼应的品种。所以你能够将温度视为模型的探究程度或随机性。因而,关于这个特定的短语,我最喜爱的食物是模型猜测的最有或许的下一个单词是披萨,其次是寿司和玉米卷。所以,在零的温度下,模型总是会挑选最有或许的下一个词,在这种状况下是披萨,在更高的温度下,它也会挑选一个不太或许的词,在更高的温度下,它乃至或许挑选玉米卷,它只要5%的时机被选中。

你能够幻想那种状况,当模型持续这个最终的反响时,我最喜爱的食物是披萨,它持续发生更多的单词,这个反响会与反响有所不同,第一个反响,我最喜爱的食物是玉米卷。因而,跟着这种模型的持续,这两种呼应将变得越来越不同。

一般来说,在构建想要一种可猜测呼应的运用程序时,我主张运用温度零。在一切这些视频中,咱们一向在运用温度零,我以为假如你企图构建一个牢靠和可猜测的体系,你应该这样做。假如你企图以一种更有创意的办法运用模型,你或许想要一种更广泛的不同输出,你或许想要运用更高的温度。所以,现在让咱们运用咱们刚刚运用的提示,让咱们测验生成一封电子邮件,但让咱们运用更高的温度。所以,在咱们在整个视频中运用的get完结函数中,咱们现已指定了一个模型,然后也是一个温度,但咱们现已将它们设置为默认值。所以,现在让咱们测验改动温度。所以,咱们将运用提示,然后让咱们测验温度0.7。因而,当温度为0时,每次履行相同的提示时,您应该期望相同的完结。而当温度为0.7时,您每次都会得到不同的输出。

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)
"""
Dear valued customer,
Thank you for taking the time to leave a review about our product. We are sorry to hear that you experienced an increase in price for the system you were interested in, and that you also experienced an issue with the motor after a year of use. We apologize for any inconvenience this may have caused you.
Please know that our company strives to provide excellent customer service and we would like to assist you with this matter. Please feel free to reach out to our customer service team at any time for assistance.
Thank you again for your feedback and for choosing our product. 
Best regards,
AI customer agent
"""

这是咱们的电子邮件,正如你所看到的,它与咱们之前收到的电子邮件不同。

让咱们再履行一次,以标明咱们将再次收到不同的电子邮件。这儿咱们有另一封不同的电子邮件。所以,我主张你自己玩玩温度。或许你现在能够暂停视频,在各种不同的温度下测验这个提示,看看输出是怎么改动的。总结一下,在更高的温度下,模型的输出更随机。你简直能够以为在更高的温度下,帮手更简略分神,但或许更有发明力。

"""
Dear Valued Customer,
Thank you for taking the time to leave a review. We sincerely apologize for the inconvenience you experienced with the price increase and the quality of the product. We understand your frustration and would like to offer our deepest apologies. If there is anything we can do to assist you, please do not hesitate to reach out to our customer service team.
We appreciate your feedback and hope to have the opportunity to serve you better in the future. 
Kind Regards,
AI customer agent
"""

鄙人一个视频中,咱们将具体谈论Chat Completions Endpoint格局,以及怎么运用此格局创立自界说谈天机器人。

谈天机器人 / ChatBot

暂时无法在飞书文档外展现此内容

关于大型言语模型的一个令人兴奋的作业是你能够用它来构建一个自界说谈天机器人,只需少数的努力。ChatGPT,网络界面,是你具有对话界面的一种办法,通过大型言语模型进行对话。但很帅的作业之一是你也能够运用大型言语模型来构建你的自界说谈天机器人,或许能够扮演AI客户服务署理或餐馆AI接单员的人物。

在本视频中,你将学习怎么为自己做这件事。我将更具体地描绘OpenAI ChatCompletions格局的组件,然后你将自己构建一个谈天机器人。让咱们开端吧。

环境预备

首要,咱们将像平常相同设置OpenAI Python包。

import os
import openai
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # read local .env file
openai.api_key  = os.getenv('OPENAI_API_KEY')

像ChatGPT这样的谈天模型实践上被练习为将一系列音讯作为输入并回来模型生成的音讯作为输出。因而,尽管谈天格局旨在使这样的多轮对话变得简略,但咱们现现已过之前的视频看到,它关于没有任何对话的单轮使命也相同有用。所以接下来,咱们将界说两个辅佐函数。这是咱们在一切视频中一向运用的函数,它是getWorks函数。

可是假如你看一下,咱们给出了一个提示,然后在函数内部,咱们实践上在做的是将这个提示放入看起来像某种用户音讯中。这是由于ChatGPT模型是一个谈天模型,这意味着它被练习成将一系列音讯作为输入,然后回来模型生成的音讯作为输出。所以用户音讯是一种输入,然后帮手音讯是输出。所以,在这个视频中,咱们将运用一个不同的协助函数,而不是把一个提示作为输入并得到一个完结,咱们将传入一个音讯列表。这些音讯能够来自各种不同的人物,所以我将描绘这些。

def get_completion(prompt, model="gpt-3.5-turbo"):
    messages = [{"role": "user", "content": prompt}]
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=0, # this is the degree of randomness of the model's output
    )
    return response.choices[0].message["content"]
def get_completion_from_messages(messages, model="gpt-3.5-turbo", temperature=0):
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=temperature, # this is the degree of randomness of the model's output
    )
#     print(str(response.choices[0].message))
    return response.choices[0].message["content"]

所以这是一个音讯列表的示例。所以,第一条音讯是一个体系音讯,它给出了一个整体指令,然后在这条音讯之后,咱们在用户和帮手之间进行了某种转化。这将持续下去。假如你从前运用过ChatGPT,网络界面,那么你的音讯便是用户音讯,然后ChatGPT的音讯便是帮手音讯。所以体系音讯有助于设置帮手的行为和人物,它在某种程度上是对话的高级指令。所以你能够把它幻想成在帮手耳边窃窃私语,引导帮手的反响,而用户却没有意识到体系音讯。

所以,作为用户,假如你从前运用过ChatGPT,你或许不知道ChatGPT的体系音讯中有什么,这便是意图。体系音讯的长处是,它为开发人员供给了一种构建对话的办法,而无需将恳求自身作为对话的一部分。因而,您能够引导帮手,在其耳边低语并引导其呼应,而无需让用户意识到。

messages =  [
{'role':'system', 'content':'You are an assistant that speaks like Shakespeare.'},    
{'role':'user', 'content':'tell me a joke'},   
{'role':'assistant', 'content':'Why did the chicken cross the road'},   
{'role':'user', 'content':'I don't know'}  ]

所以,现在让咱们测验在对话中运用这些音讯。因而,咱们将运用咱们的新帮手函数从音讯中取得完结。咱们还运用更高的温度。所以体系音讯说,你是一个说话像莎士比亚的帮手。所以这是咱们向帮手描绘它应该怎么体现。然后第一个用户信息是,给我讲个笑话。接下来是,为什么鸡要过马路?最终一个用户信息是,我不知道。所以假如咱们运转这个,呼应是抵达另一边。让咱们再试一次。

response = get_completion_from_messages(messages, temperature=1)
print(response)
"""
To get to the other side, sire! 'Tis a classic jest, known by many a bard.
"""

为了抵达另一边,公平地说,夫人,这是一个古老的经典,永远不会失利。这是咱们的莎士比亚呼应。

让咱们再试一件事,由于我想更清楚地阐明这是帮手音讯。所以在这儿,让咱们去打印整个音讯呼应。所以,为了让这更清楚,嗯,这个呼应是一个帮手音讯。所以,人物是帮手,然后内容是音讯自身。

所以,这便是这个帮手函数中发生的作业。咱们仅仅传递音讯的内容。现在让咱们做另一个比方。

messages =  [
{'role':'system', 'content':'You are friendly chatbot.'},    
{'role':'user', 'content':'Hi, my name is Isa'}  ]
response = get_completion_from_messages(messages, temperature=1)
print(response)
"""
Hello Isa! Nice to meet you. How are you doing today?
"""

所以,这儿咱们的音讯是,嗯,帮手音讯是,你是一个友爱的谈天机器人,第一条用户音讯是,嗨,我的姓名是Isa。咱们想,嗯,获取第一条用户音讯。所以,让咱们履行这个。第一条帮手音讯。所以,第一条音讯是,你好Isa,很高兴见到你。我今日能够怎么协助你?

messages =  [
{'role':'system', 'content':'You are friendly chatbot.'},    
{'role':'user', 'content':'Yes,  can you remind me, What is my name?'}  ]
response = get_completion_from_messages(messages, temperature=1)
print(response)
"""
I'm sorry, but as a chatbot, I do not have access to information about your personal details such as your name. However, you can tell me your name and we can continue our conversation.
"""

现在,让咱们测验另一个比方。所以,这儿咱们的音讯是,嗯,体系音讯,你是一个友爱的谈天机器人,第一条用户音讯是,是的,你能提示我我的姓名是什么吗?让咱们得到呼应。正如你所看到的,模型实践上并不知道我的姓名。所以,与言语模型的每个对话都是一个独立的交互,这意味着你必须为模型供给一切相关的音讯,以便在当时对话中提取。

假如你想让模型从对话中提取,或许引证,记住对话的前期部分,你必须在模型的输入中供给前期的交流。所以,咱们将此称为上下文。所以,让咱们试试这个。

messages =  [
{'role':'system', 'content':'You are friendly chatbot.'},
{'role':'user', 'content':'Hi, my name is Isa'},
{'role':'assistant', 'content': "Hi Isa! It's nice to meet you. \
Is there anything I can help you with today?"},
{'role':'user', 'content':'Yes, you can remind me, What is my name?'}  ]
response = get_completion_from_messages(messages, temperature=1)
print(response)
"""
Of course, your name is Isa.
"""

所以,现在咱们现已给出了模型需求的上下文,嗯,这是我在前面的音讯中的姓名,咱们会问相同的问题,所以咱们会问我的姓名是什么。模型能够呼应,由于它具有它需求的一切上下文,嗯,在咱们输入给它的这种音讯列表中。

订单机器人

所以现在你要构建你自己的谈天机器人。这个谈天机器人将被称为orderbot,咱们将主动搜集用户提示和帮手呼应,以构建这个orderbot。它将接受披萨店的订单,所以首要咱们要界说这个协助函数,它要做的是搜集咱们的用户音讯,这样咱们就能够防止像上面那样手动输入它们,这将从下面构建的用户交互界面搜集提示,然后将其附加到一个名为上下文的列表中,然后它将每次都运用该上下文调用模型。然后模型呼应也被增加到上下文中,所以模型音讯被增加到上下文中,用户音讯被增加到上下文中,依此类推,所以它越来越长。

def collect_messages(_):
    prompt = inp.value_input
    inp.value = ''
    context.append({'role':'user', 'content':f"{prompt}"})
    response = get_completion_from_messages(context) 
    context.append({'role':'assistant', 'content':f"{response}"})
    panels.append(
        pn.Row('User:', pn.pane.Markdown(prompt, width=600)))
    panels.append(
        pn.Row('Assistant:', pn.pane.Markdown(response, width=600, style={'background-color': '#F6F6F6'})))
    return pn.Column(*panels)

这样模型就有了它需求的信息来决议下一步做什么。现在咱们将设置并运转这种UI来显现订单机器人,这是上下文,它包含包含菜单的体系音讯,留意,每次咱们调用言语模型时,咱们都将运用相同的上下文,上下文跟着时刻的推移而积累。然后让咱们履行这个。好的,我要说,嗨,我想订一个比萨饼。助理说,太好了,你想订什么比萨饼?咱们有腊肠、奶酪和茄子比萨饼。它们多少钱?太好了,好的,咱们有价格。我想我觉得一个中等的茄子比萨饼。所以你能够幻想,咱们能够持续这个对话,让咱们看看咱们在体系音讯中放了什么。

你是订单机器人,一个为比萨饼餐厅搜集订单的主动化服务。你首要问好顾客,然后搜集订单,然后问询是提货仍是送货。你等待搜集整个订单,然后总结一下,最终一次查看客户是否想要增加任何其他东西。假如是送货,你能够要求一个地址。最终,你收取付款。保证弄清一切选项、额定费用和尺度,以唯一地辨认菜单中的项目。你以简略、十分对话、友爱的办法回应。菜单包含,然后咱们有菜单。

所以让咱们回到咱们的谈话,让咱们看看助理是否一向在遵从指示。

import panel as pn  # GUI
pn.extension()
panels = [] # collect display 
context = [ {'role':'system', 'content':"""
You are OrderBot, an automated service to collect orders for a pizza restaurant. \
You first greet the customer, then collects the order, \
and then asks if it's a pickup or delivery. \
You wait to collect the entire order, then summarize it and check for a final \
time if the customer wants to add anything else. \
If it's a delivery, you ask for an address. \
Finally you collect the payment.\
Make sure to clarify all options, extras and sizes to uniquely \
identify the item from the menu.\
You respond in a short, very conversational friendly style. \
The menu includes \
pepperoni pizza  12.95, 10.00, 7.00 \
cheese pizza   10.95, 9.25, 6.50 \
eggplant pizza   11.95, 9.75, 6.75 \
fries 4.50, 3.50 \
greek salad 7.25 \
Toppings: \
extra cheese 2.00, \
mushrooms 1.50 \
sausage 3.00 \
canadian bacon 3.50 \
AI sauce 1.50 \
peppers 1.00 \
Drinks: \
coke 3.00, 2.00, 1.00 \
sprite 3.00, 2.00, 1.00 \
bottled water 5.00 \
"""} ]  # accumulate messages
inp = pn.widgets.TextInput(value="Hi", placeholder='Enter text here…')
button_conversation = pn.widgets.Button(name="Chat!")
interactive_conversation = pn.bind(collect_messages, button_conversation)
dashboard = pn.Column(
    inp,
    pn.Row(button_conversation),
    pn.panel(interactive_conversation, loading_indicator=True, height=300),
)
dashboard
"""
[呈现一个人机交互界面]
"""

实践运用示例效果如下

OpenAI官方《提示词工程课》超详细中文笔记

好的,太好了,助理问咱们是否想要任何咱们指定了助理信息的配料。所以我想咱们不需求额定的配料。作业…当然能够。咱们还想点什么吗?嗯,让咱们喝点水。实践上,薯条。小仍是大?这很棒,由于咱们在体系音讯中要求帮手弄清额定的东西和附加内容。

所以你理解了,请随意自己玩这个。你能够暂停视频,持续在左面你自己的笔记本上运转它。

所以现在咱们能够要求模型创立一个JSON摘要,咱们能够依据对话发送到订单体系。所以咱们现在附加另一个体系音讯,这是一个指令,咱们说创立一个JSON的前一个食物订单的摘要,逐项列出每个项意图价格,字段应该是一个比萨饼,包含旁边面,两个配料列表,三个饮料列表和四个旁边面列表,最终是总价。

messages =  context.copy()
messages.append(
{'role':'system', 'content':'create a json summary of the previous food order. Itemize the price for each item\
 The fields should be 1) pizza, include size 2) list of toppings 3) list of drinks, include size   4) list of sides include size  5)total price '},    
)
 #The fields should be 1) pizza, price 2) list of toppings 3) list of drinks, include size include price  4) list of sides include size include price, 5)total price '},    
response = get_completion_from_messages(messages, temperature=0)
print(response)
"""
Sure, here's a JSON summary of your order:
```
{
  "pizza": {
    "type": "意大利辣腊肠披萨",
    "size": "中号",
    "price": 12.95
  },
  "toppings": [
    {
      "type": "加拿大培根",
      "price": 3.50
    },
    {
      "type": "蘑菇",
      "price": 1.50
    },
    {
      "type": "彩椒",
      "price": 1.00
    }
  ],
  "drinks": [
    {
      "type": "可乐",
      "size": "中杯",
      "price": 3.00
    }
  ],
  "sides": [],
  "total_price": 18.95
}
```
"""

你也能够在这儿运用用户音讯,这不一定是体系音讯。所以让咱们履行这个。留意在这种状况下,咱们运用较低的温度,由于关于这些使命,咱们期望输出是适当可猜测的。关于会话署理,您或许期望运用更高的温度,可是在这种状况下,我或许也会运用更低的温度,由于关于客户的帮手谈天机器人,您或许期望输出也更可猜测。

因而,这儿咱们有咱们的订单摘要,因而假如咱们愿意,咱们能够将其提交给订单体系。现在咱们有了它,您现已构建了自己的订单谈天机器人。请随意自界说它,并运用体系音讯来改动谈天机器人的行为,并让它充当具有不同常识的不同人物。

收尾 / Conclusion

暂时无法在飞书文档外展现此内容

祝贺你完结了这个简略的课程。

总之,在这个简略的课程中,你现已学习了

  • 提示的两个要害准则。
  1. 写清楚具体的阐明,
  2. 在适宜的时分,给模型时刻考虑。
  • 你还学习了迭代提示开发,以及怎么具有一个适宜你的运用程序的提示进程是要害。
  1. 咱们学习了一些对许多运用程序有用的大型言语模型的功能,特别是总结、揣度、转化和扩展。

  2. 你还看到了怎么构建一个自界说谈天机器人。

这是你在一个简略的课程中学到的许多东西,我期望你喜爱阅览这些资料。咱们期望你能想出一些你现在能够自己构建的运用程序的主见。请去试试这个,让咱们知道你想出了什么。没有运用程序太小,从一个十分小的项目开端是很好的,或许有点有用,或许它根本没有用,仅仅一些有趣的东西。是的,我发现玩这些模型真的很有趣,所以去玩吧!我赞同,这是一个很好的周末活动,从经历来看。

嗯,仅仅,你知道,请利用你第一个项意图经历来构建一个更好的第二个项目,你知道,乃至或许是一个更好的第三个项目,等等。这便是我自己运用这些模型跟着时刻的推移而生长的办法。或许假如你现已有了一个更大项意图主见,就去做吧。你知道,作为提示,这些大型言语模型是一项十分强壮的技能,所以不言而喻,咱们要求你担任任地运用它们,请只构建会发生活跃影响的东西。

是的,我彻底赞同。我以为在这个年代,构建AI体系的人能够对其他人发生巨大的影响。所以咱们一切人都担任任地运用这些东西比以往任何时分都愈加重要。嗯,我以为构建依据大型言语模型的运用程序现在仅仅一个十分令人兴奋和不断发展的范畴。现在你现已完结了这门课程,我以为你现在具有丰厚的常识,能够让你构建今日很少有人知道怎么去做的东西。所以,我期望你也能协助咱们传达这个,并鼓舞其他人也参加这门课程。最终,我期望你在学习这门课程时玩得开心,我要感谢你完结了这门课程。以斯拉和我都等待听到你制作的惊人的东西。