目录

  • 前言
  • 一、大语言模型介绍
  • 二、提示指南
    • 2-0、导入API key和相关的python库
    • 2-1、写清楚的、具体的提示
      • 2-1-1、使用分隔符清楚的指示输入的不同部分
      • 2-1-2、要求结构化的输出
      • 2-1-3、按照指定的条件输出
      • 2-1-4、少样本学习
    • 2-2、给模型时间去思考
      • 2-2-1、指定完成任务所需要的具体步骤
      • 2-2-2、要求模型以指定格式输出
      • 2-2-3、指示模型一步步自行找出答案,而不是尽快得出结论
  • 三、迭代式快速开发
    • 3-0、导入API-key 和相关的库
    • 3-1、从产品说明书中生成营销产品描述
    • 3-2、文本太长、聚焦受众
    • 3-3、要求模型提取信息并且组织成表格
    • 3-4、总结
  • 四、推理
    • 4-0、导入API-key 和相关的库
    • 4-1、评论的情感分析指定
    • 4-2、识别出所有情绪
    • 4-3、从客户评论中提取产品和公司名称(信息抽取)
    • 4-4、同时做多项任务(情绪识别、是否表现愤怒、购买的物品、公司名)
  • 五、转换
    • 5-0、导入API-key 和相关的库
    • 5-1、翻译
    • 5-2、语言风格转换
    • 5-3、格式转换
    • 5-4、校对、语法纠正
  • 六、扩展(生成多样化)
    • 6-0、导入API-key 和相关的库
    • 6-1、定制对客户电子邮件的自动回复
    • 6-2、多样化自动回复
  • 七、聊天机器人
    • 7-0、导入API-key 和相关的库
    • 7-1、开始聊天!
    • 7-2、自学习机器人(自动收集用户和助手之间的对话)
  • 总结

前言

Prompt工程师的兴起是因为像OpenAI的ChatGPT这样的聊天机器人已经风靡全球。但是这些工具可能存在偏见、产生错误信息,并且有时会用晦涩难懂的回答干扰用户。这就是Prompt工程师可以提供价值的地方。据《华盛顿邮报》报道,虽然Prompt工程师的角色因公司而异,但其基本任务是探究人工智能的能力以及它为什么会出错。

一、大语言模型介绍

Base LLM(基础大语言模型):预测下一个单词,主要依据的是训练文本
Instruction Tuned LLM(指令微调大语言模型):基于人类反馈的强化学习、有帮助的、真实的、无害的。

二、提示指南

2-0、导入API key和相关的python库

import openai
import os
from dotenv import load_dotenv, find_dotenv_ = load_dotenv(find_dotenv())openai.api_key = "这里填写你的api-key"# 使用模型为gpt-3.5-turbo
def get_completion(prompt, model="gpt-3.5-turbo"):messages = [{"role": "user", "content": prompt}]response = openai.ChatCompletion.create(model=model,messages=messages,temperature=0,)return response.choices[0].message["content"]

2-1、写清楚的、具体的提示

2-1-1、使用分隔符清楚的指示输入的不同部分

使用分隔符清楚的指示输入的不同部分 : 分隔符可以是: “”", ```, <>, < tag >, < /tag >, :

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)

输出
Clear and specific instructions should be provided to guide a model towards the desired output, and longer prompts can provide more clarity and context for the model, leading to more detailed and relevant outputs.

2-1-2、要求结构化的输出

# 生成一个由三个虚假的书名组成的列表,以JSON格式输出它们,并且使用以下键:book_id, title, author, genre。
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)

输出如下

2-1-3、按照指定的条件输出

按照指定的条件输出: 给出泡一杯茶的步骤。使用提示让chatGPT以以下格式输出。

Step 1 - …
Step 2 - …

Step N - …

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)

输出如下所示

2-1-4、少样本学习

少样本学习: 给出案例,按照给定的格式输出

# 你的任务是使用连贯的风格来回答问题。
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 is the ability to bounce back from adversity and keep moving forward, even when things get tough. Just like a tree that grows stronger with each storm it weathers, resilience is a quality that can be developed and strengthened over time.

2-2、给模型时间去思考

2-2-1、指定完成任务所需要的具体步骤

指定完成任务所需要的具体步骤: 详细列出每一步的操作步骤,让chatgpt按照要求去依次执行。

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
# 用一个句子总结以下用三个反引号分隔的文本。
# 把摘要翻译为法语
# 在法语摘要中列出每个名字
# 输出一个json对象包含以下关键词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)

输出如下所示

2-2-2、要求模型以指定格式输出

要求模型以指定格式输出 : 输出格式如下
Text:
Summary:
Translation:
Names:
Output JSON:

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)

输出如下

2-2-3、指示模型一步步自行找出答案,而不是尽快得出结论

错误提示

prompt = f"""
Determine if the student's solution is correct or not.Question:
I'm building a solar power installation and I need \help working out the financials.
- Land costs $100 / square foot
- I can buy solar panels for $250 / square foot
- I negotiated a contract for maintenance that will cost \
me a flat $100k per year, and an additional $10 / square \
foot
What is the total cost for the first year of operations
as a function of the number of square feet.Student's Solution:
Let x be the size of the installation in square feet.
Costs:
1. Land cost: 100x
2. Solar panel cost: 250x
3. Maintenance cost: 100,000 + 100x
Total cost: 100x + 250x + 100,000 + 100x = 450x + 100,000
"""
response = get_completion(prompt)
print(response)

输出
The student’s solution is correct.

这里注意到学生的答案实际是错误的,我们需要修正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:
"""
response = get_completion(prompt)
print(response)

三、迭代式快速开发

目标:迭代地分析和改进提示,以从产品情况说明书生成营销文案。

快速迭代开发图

3-0、导入API-key 和相关的库

import openai
import os
from dotenv import load_dotenv, find_dotenv
from IPython.display import display, HTML_ = load_dotenv(find_dotenv())openai.api_key = "这里填写你的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,)return response.choices[0].message["content"]

3-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 foamCOUNTRY OF ORIGIN
- Italy
"""# 你的任务是帮助营销团队根据技术说明书为产品的零售网站创建描述。
# 请根据技术参数提供的信息(用三个反引号分隔)编写产品描述。
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)

输出如下

3-2、文本太长、聚焦受众

文本太长、聚焦受众: 添加长度限制、让模型专注于与目标受众相关的方面。

# 描述是为家具零售商准备的,所以本质上应该是技术性的,重点是产品的建造材料。
# 在描述的最后,包括每7个字符技术规格书中的产品编号。
# 最多使用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.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)

3-3、要求模型提取信息并且组织成表格

# 在描述之后,包含一个给出产品尺寸的表。这个表应该有两列。在第一列中包括维度的名称。在第二列中只包括以英寸为单位的测量值。
# 给表格命名为产品维度
# 将所有可以在网站中使用的内容格式化为HTML。
将描述放置在<div>元素中。
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.After the description, include a table that gives the product's dimensions. The table should have two columns.In the first column include the name of the dimension. In the second column include the measurements in inches only.Give the table the title 'Product Dimensions'.Format everything as HTML that can be used in a website.
Place the description in a <div> element.Technical specifications: ```{fact_sheet_chair}```
"""response = get_completion(prompt)
print(response)
display(HTML(response))

输出如下所示

3-4、总结

四、推理

4-0、导入API-key 和相关的库

import openai
import os
from dotenv import load_dotenv, find_dotenv
from IPython.display import display, HTML_ = load_dotenv(find_dotenv())openai.api_key = "这里填写你的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,)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!!
"""

4-1、评论的情感分析指定

# 给出产品评论的情感分析,并且要求只使用一个词来回答,使用positive或者negative
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

4-2、识别出所有情绪

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

4-3、从客户评论中提取产品和公司名称(信息抽取)

# 抽取评论,并且以固定的json格式返回
prompt = f"""
Identify the following items from the review text:
- Item purchased by reviewer
- Company that made the itemThe 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)

输出

4-4、同时做多项任务(情绪识别、是否表现愤怒、购买的物品、公司名)

# 并且回复以JSON格式输出,使用Sentiment、Amger、Item、Brand作为key。
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 itemThe 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)

五、转换

转换:大型语言模型非常擅长将其输入转换为不同的格式,例如输入一种语言的一段文本并将其翻译成不同的语言, 或帮助进行拼写和语法方面的更正。或者输入 HTML 并且输出 JSON。

5-0、导入API-key 和相关的库

import openai
import os
from dotenv import load_dotenv, find_dotenv
from IPython.display import display, HTML_ = load_dotenv(find_dotenv())openai.api_key = "这里填写你的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,)return response.choices[0].message["content"]

5-1、翻译

翻译:将一种语言翻译为多种语言

prompt = f"""
Translate the following  text to French and Spanish
and English pirate: \
```I want to order a basketball```
"""
response = get_completion(prompt)
print(response)

输出

输出为规范的输出和俚语

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)

输出

通用翻译器

user_messages = ["La performance du système est plus lente que d'habitude.",  # System performance is slower than normal         "Mi monitor tiene píxeles que no se iluminan.",              # My monitor has pixels that are not lighting"Il mio mouse non funziona",                                 # My mouse is not working"Mój 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 système est plus lente que d’habitude.
English: The system performance is slower than usual.
Korean: 시스템 성능이 평소보다 느립니다.

5-2、语言风格转换

风格转换: 从俚语转变为商务信风格。

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)

输出

5-3、格式转换

格式转换: JSON to an 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)from IPython.display import display, Markdown, Latex, HTML, JSON
display(HTML(response))

输出

5-4、校对、语法纠正

校对、语法纠正:为了向LLM发出你想让它校对你的文本的信号,你需要指示模型“校对”或“校对并纠正”。

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.

六、扩展(生成多样化)

6-0、导入API-key 和相关的库

import openai
import os
from dotenv import load_dotenv, find_dotenv
from IPython.display import display, HTML_ = load_dotenv(find_dotenv())openai.api_key = "这里填写你的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,)return response.choices[0].message["content"]

6-1、定制对客户电子邮件的自动回复

定制对客户电子邮件的自动回复: 让AI扮演客服助理,给客户发邮件,生成回复感谢客户的订阅,如果客户的评价是正面或中性的,那就感谢他们的评价。如果感觉不好,道歉并建议他们联系客服。确保使用到客户评论中的具体细节,用简洁和专业的语气写作。将邮件签名为“AI客户代理”。

# 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.
"""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 a price increase and that the quality of the product did not meet your expectations. We apologize for any inconvenience this may have caused you.
If you have any further concerns or questions, please do not hesitate to reach out to our customer service team. They will be more than happy to assist you in any way they can.
Thank you again for your feedback. We appreciate your business and hope to have the opportunity to serve you better in the future.
Best regards,
AI customer agent

中文输出
尊敬的顾客,
感谢您的评论。我们很抱歉您对我们的产品不满意。我们一直致力于提供高质量的产品和服务,但我们似乎没有达到您的期望。
我们很抱歉您在购买我们的产品时遇到了问题。如果您需要任何帮助或支持,请随时联系我们的客户服务团队。我们将竭尽全力解决您的问题。
再次感谢您的评论,我们将继续努力提高我们的产品和服务质量。
AI客户代理

6-2、多样化自动回复

多样化自动回复:每次回复的答案都不同,这里使用到了一个参数temperature。在openai.ChatCompletion.create()函数里。

Temperature: 参数越高,模型的输出越随机。

具体代码如下

import openai
import os
from dotenv import load_dotenv, find_dotenv
from IPython.display import display, HTML_ = load_dotenv(find_dotenv())openai.api_key = "这里填写你的key"def get_completion(prompt, model="gpt-3.5-turbo", temperature=None):messages = [{"role": "user", "content": prompt}]response = openai.ChatCompletion.create(model=model,messages=messages,temperature=0,)return response.choices[0].message["content"]# 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.
"""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`, give your answer in chinese.
Customer review: ```{review}```
Review sentiment: {sentiment}
"""
response = get_completion(prompt, temperature=0.9)
print(response)

多次输出
尊敬的顾客,
感谢您的评论。我们很抱歉您对我们的产品不满意。我们一直致力于提供高质量的产品和服务,但我们似乎没有达到您的期望。
我们很抱歉您在购买我们的产品时遇到了价格上涨的问题。我们会进一步调查此事,并确保我们的价格政策是公正和透明的。
我们也很遗憾听到您的保修期已过,但我们的客户服务团队随时准备为您提供帮助。如果您需要任何帮助或支持,请随时联系我们的客户服务团队。
再次感谢您的评论和反馈。我们将继续努力提高我们的产品和服务,以满足我们尊贵客户的需求。
AI客户代理

尊敬的顾客,
感谢您的评论。我们很抱歉您对我们的产品不满意。我们一直致力于提供高质量的产品和服务,但很遗憾我们没有达到您的期望。
我们建议您联系我们的客户服务团队,以便我们可以更好地了解您的问题并提供帮助。我们非常重视您的反馈,并将努力改进我们的产品和服务。
再次感谢您的评论,我们期待为您提供更好的服务。
AI客户代理

尊敬的顾客,
感谢您的评论。我们很抱歉您对我们的产品不满意。我们一直致力于提供高质量的产品和服务,但我们似乎没有达到您的期望。
我们很抱歉您在购买我们的产品时遇到了价格上涨的问题。我们会尽力确保我们的价格公正合理,并且我们会进一步研究这个问题,以确保这种情况不再发生。
我们也很遗憾听到您的保修期已过,但我们仍然希望能够帮助您解决任何问题。如果您需要任何帮助或支持,请随时联系我们的客户服务团队,他们将竭尽全力为您提供帮助。
再次感谢您的评论和反馈。我们将继续努力提供更好的产品和服务。
AI客户服务代理

七、聊天机器人

7-0、导入API-key 和相关的库

import openai
import os
from dotenv import load_dotenv, find_dotenv
from IPython.display import display, HTML_ = load_dotenv(find_dotenv())openai.api_key = "这里填写你的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"]# 带有temperature参数的函数。
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"]

7-1、开始聊天!

let`s chat:这里我们并不会传入单一的输入,我们尝试传递消息列表,这些消息来自于不同的角色,我会描述这些角色,第一个消息是系统消息,需要我们给出总体的说明,这里给出的例子是:你是个说话像莎士比亚的助理,之后我们就会在用户和助手这两个角色之间继续下去。

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, verily!

案例二:扮演一个友善的机器人

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)

输出:It’s nice to meet you, Isa! How can I assist you today?

案例三:扮演一个友善的机器人,并给出上下文。(这里我们在前置中给出了名字,所以机器人可以回答。)

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)

输出:Your name is Isa, nice to see you again. Is there any more things I can assist you with?

整个过程的流程图如下所示

7-2、自学习机器人(自动收集用户和助手之间的对话)

自学习机器人: 这里我们自动收集用户和助手之间的对话,这个聊天机器人的工作流程如下:

  • 用户输入消息并按下“Chat”按钮。
  • 用户消息被添加到上下文列表中,并显示在面板上。
  • 聊天机器人使用OpenAI的ChatCompletion API来获取响应。
  • 聊天机器人的响应被添加到上下文列表中,并显示在面板上。
  • 这个过程重复,直到用户选择退出聊天。
import openai
import os
from dotenv import load_dotenv, find_dotenv
from IPython.display import display, HTML_ = load_dotenv(find_dotenv())openai.api_key = "这里添加你的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"]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"]# 绑定于chat按钮上的函数,当点击按钮时,该函数被调用
# 函数的输入参数是一个下划线“_”,这是一个占位符参数,因为Panel库需要一个可调用对象作为回调函数,而这个函数需要一个参数。这个参数不会被使用,所以使用下划线表示。
def collect_messages(_):```inp.value_input:获取用户输入的信息,存入到prompt中去inp.value = ''  将输入框的值设置为空字符串,以便用户输入下一条信息context.append: 将用户输入以及机器人回复添加到上下文context中去。panels.append:  将用户输入以及机器人回复显示到面板上。return: 函数返回一个Column对象,其中包含了所有的面板。这个对象将被绑定到一个名为interactive_conversation的可调用对象上,这个对象将在用户点击“Chat”按钮时被调用,以显示聊天机器人的响应。```prompt = inp.value_inputinp.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, styles={'background-color': '#F6F6F6'})))return pn.Column(*panels)import panel as pn  # GUI
# Panel库需要在Notebook中启用一些JavaScript来提供交互功能。pn.extension()函数会自动插入这些JavaScript代码,以确保Panel库的功能正常运行。
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# 创建一个初始值为“Hi”的文本输入小部件和一个占位符文本,该文本在用户输入内容时消失。
inp = pn.widgets.TextInput(value="Hi", placeholder='Enter text here…')
# 创建一个标签为“Chat!”的按钮
button_conversation = pn.widgets.Button(name="Chat!")# 将按钮和函数绑定在一起
interactive_conversation = pn.bind(collect_messages, button_conversation)
# 创建列布局,加入文本输入小部件、按钮等
dashboard = pn.Column(inp,pn.Row(button_conversation),# loading_indicator=True选项在函数运行时向面板添加一个旋转器,height=300选项将面板的高度设置为300像素。pn.panel(interactive_conversation, loading_indicator=True, height=300),
)dashboard.show()

展示如下(如果是jupyter,直接使用dashboard即可)



小结:


总结

总算写完了!!!

吴恩达联手OpenAI的免费课程笔记—面向开发人员的 ChatGPT 提示工程相关推荐

  1. 新建网站了!Github标星过万的吴恩达机器学习、深度学习课程笔记,《统计学习方法》代码实现,可以在线阅读了!...

    吴恩达机器学习.深度学习,李航老师<统计学习方法>,可以说是机器学习入门的宝典.本文推荐一个网站"机器学习初学者",把以上资源的笔记.代码实现做成了网页版,可以在线阅读 ...

  2. Coursera吴恩达《序列模型》课程笔记(2)-- NLP Word Embeddings

    红色石头的个人网站:redstonewill.com <Recurrent Neural Networks>是Andrw Ng深度学习专项课程中的第五门课,也是最后一门课.这门课主要介绍循 ...

  3. 手机上的机器学习资源!Github标星过万的吴恩达机器学习、深度学习课程笔记,《统计学习方法》代码实现!...

    吴恩达机器学习.深度学习,李航老师<统计学习方法>.CS229数学基础等,可以说是机器学习入门的宝典.本文推荐一个网站"机器学习初学者",把以上资源的笔记.代码实现做成 ...

  4. 吴恩达深度学习笔记_Github标星过万的吴恩达机器学习、深度学习课程笔记,《统计学习方法》代码实现,可以在线阅读了!...

    吴恩达机器学习.深度学习,李航老师<统计学习方法>,可以说是机器学习入门的宝典.本文推荐一个网站"机器学习初学者",把以上资源的笔记.代码实现做成了网页版,可以在线阅读 ...

  5. Coursera吴恩达《序列模型》课程笔记(3)-- Sequence models Attention mechanism

    红色石头的个人网站:redstonewill.com <Recurrent Neural Networks>是Andrw Ng深度学习专项课程中的第五门课,也是最后一门课.这门课主要介绍循 ...

  6. Coursera吴恩达《序列模型》课程笔记(1)-- 循环神经网络(RNN)

    红色石头的个人网站:redstonewill.com <Recurrent Neural Networks>是Andrw Ng深度学习专项课程中的第五门课,也是最后一门课.这门课主要介绍循 ...

  7. Coursera吴恩达《卷积神经网络》课程笔记(2)-- 深度卷积模型:案例研究

    红色石头的个人网站:redstonewill.com <Convolutional Neural Networks>是Andrw Ng深度学习专项课程中的第四门课.这门课主要介绍卷积神经网 ...

  8. AIQ - deeplearning.ai 全套吴恩达老师的深度学习课程笔记及资源在线阅读

    http://www.6aiq.com/deeplearning_ai/html/SUMMARY.html 深度学习笔记目录 第一门课 神经网络和深度学习(Neural Networks and De ...

  9. AIQ - deeplearning.ai 全套吴恩达老师的深度学习课程笔记

    http://www.6aiq.com/deeplearning_ai/html/SUMMARY.html 深度学习笔记目录 第一门课 神经网络和深度学习(Neural Networks and De ...

最新文章

  1. 模型可视化_20210208
  2. JS中怎样获取当前年以及前后几年并构造成对象数组
  3. 【ThinkingInC++】61、非成员运算符
  4. python递归调用详解_Python递归调用自己的函数
  5. Android底部导航栏的实现(RadioGroup和Fragment结合使用)
  6. 对JavaScript解析JSON格式数据的理解
  7. 数据结构和算法9——哈希表
  8. 高级商务办公软件应用【12】
  9. 京东联盟接口——链接取商品sku
  10. <video> 标签快进不生效
  11. mac下编译安卓源码
  12. XiunoBBS ax_date 插件 日期显示不正确 修复
  13. python 爬取携程旅游景点评论
  14. JavaWeb基础(黑马配套)
  15. 二叉排序树基本操作(链表实现)(有错误)
  16. ethz-asl的catkin simple
  17. BUUCTF Misc杂项前十二道题的思路和感悟
  18. Camera ITS当中的部分测试项文档
  19. win10右下角声音符号红叉提示解决未安装任何音频输出设备
  20. linux代码怎么运行gedit,Linux中gedit命令起什么作用呢?

热门文章

  1. JVM系列(二):JDK自带监控命令
  2. 2015年第20本:零秒思考
  3. LIO-Livox(一)简介及框架
  4. Linux中通过v4l2框架获取摄像头的能力的方法
  5. Swift - Alamofire简单GET和POST使用
  6. px、em、rem、vh、pt 分别是什么
  7. 尚医通-预约下单中rabbitmq的使用
  8. 一篇读懂分布式架构下的负载均衡技术:分类、原理、算法、常见方案等
  9. 这几个通信协议的动图不错
  10. 打造智慧流程大脑,炎黄盈动AWS PaaS平台打通流程管理与执行