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

目录


前言

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即可)

在这里插入图片描述
在这里插入图片描述
小结:
在这里插入图片描述


总结

总算写完了!!!🎇🎇🎇

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/16724.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

我用ChatGPT 7分钟生成一个Spring Boot博客项目,有点瑟瑟发抖!

我的《用ChatGPT生成一个SpringBoot应用》保姆级教程上线了。教程的核心是&#xff1a;思路和ChatGPT提示语&#xff0c;已经更新到我的知识星球专栏&#xff0c;目前已经累计实战项目60&#xff0c;目标500 看看ChatGPT生成的项目&#xff0c;Maven结构完整&#xff0c;可正常…

ChatGPT快速搞定前后端开发、测试、运维项目实战,一点代码都不用写!

《面向ChatGPT全栈开发实战》专栏上线了&#xff0c;写这个专栏的过程中&#xff0c;我真有点恐慌&#xff0c;感觉我得失业&#xff0c;因为ChatGPT实在太牛逼了。 注意&#xff1a;由于账号越来难注册&#xff0c;仅限前200名送ChatGPT独立账号&#xff0c;没有的抓紧了。 Ch…

使用机器学习预测股价

股票价格预测有助于确定未来几天或几周内股票的走势&#xff0c;或者至少显示趋势。股票价格取决于多种因素&#xff0c;例如&#xff1a; 基本因素&#xff1a;收入&#xff0c;利润&#xff0c;市场份额&#xff0c;业务的潜在增长前景 外部因素&#xff1a;大流行病&#…

[股票预测]股票历史数据获取

目 录 一、编程环境准备 第一步&#xff1a;安装Anaconda3 第二步&#xff1a;安装工具包Pandas、tushare 第三步&#xff1a;查看Pandas、tushare版本 二、股票历史行情数据提取 2.1获取近3年个股日线交易数据 2.1.1 个股交易接口函数get_hist_data() 2.1.2兴蓉环境(…

股票预测数据与真实数据对比图(八)2021/07/16

重点在于echarts的option 经过查阅文档可以知道&#xff0c;对于echarts的使用&#xff0c;对于图表要绘制的内容是填写在option这一选项&#xff0c;并通过 charts.setOption(option,true); 这条命令来达到刷新图表内容的作用&#xff0c;因此在已经监听了绘制图表类型的基础…

解读:通过挖掘股票内在特征预测股票趋势

写在前面 下面这篇文章的内容主要是来自发表于KDD2019的一篇文章《Investment Behaviors Can Tell What Inside: Exploring Stock Intrinsic Properties for Stock Trend Prediction》。这篇文章发现&#xff0c;职业基金经理们对于股票的共同投资行为可以反应股票的内在属性&a…

使用DeepAR实现股价预测

使用DeepAR实现股价预测 文章目录 使用DeepAR实现股价预测获取股票列表从众多股票中采样100支日期处理函数拉取等长度的股票&#xff0c;并保存 各指标解释预测区间长度及上下文选取给这78支股票所在行业进行归类 目标变量处理协变量处理协变量归一化操作 训练、测试数据划分训…

基于tushare的股票评级与预测

本文内容 股票评级思路&#xff08;一&#xff09; 用百度得到的股票评级六大要素进行股票评分&#xff0c;并用后面的数据对其进行正确性检测。股票评级思路&#xff08;二&#xff09; 在思路一的基础上加入大盘历史的涨跌数据&#xff0c;对评分进行了优化&#xff0c;也进…

python采集往期股票数据进行分析预测

前言 嗨喽~大家好呀&#xff0c;这里是魔王呐 ❤ ~! 准备工作 既然要去赚马内&#xff0c;咱们首先要获取往期的数据来进行分析&#xff0c; 通过往期的规律来对当前进行预测&#xff0c;准不准我不知道&#xff0c;反正比人预测的准&#xff0c; 不准也不要喷我&#xff0…

[ChatGPT最强竞品]爆火,不限量不要钱不用魔法免费注册!

1免责声明 本公众号所发布的文章及工具只限交流学习&#xff0c;本公众号不承担任何责任&#xff01;如有侵权&#xff0c;请告知我们立即删除。 原文地址&#xff1a;[ChatGPT最强竞品]爆火&#xff0c;不限量不要钱不用魔法免费注册&#xff01; 2Claude 介绍 Claude 是下一代…

免费可用!ChatGPT最强竞品来了

&#xff08;永久免费&#xff0c;扫码加入&#xff09; 来源&#xff1a;机器之心 此次&#xff0c;Claude 2 除了一大波能力上的升级&#xff0c;更重要的是大家都可以用了。 今日&#xff0c;那个被很多网友称为「ChatGPT 最强竞品」的人工智能系统 Claude 迎来了版本大更新…

chatgpt-AIGC-从数学开始

向量 向量是由n个实数组成的一个n行1列&#xff08;n*1&#xff09;或一个1行n列&#xff08;1*n&#xff09;的有序数组&#xff1b; 点积 - 向量的点乘,也叫向量的内积、数量积&#xff0c;对两个向量执行点乘运算&#xff0c;就是对这两个向量对应位一一相乘之后求和的操作…

ChatGPT不仅能写代码还能改bug,这届AI全能

工欲善其事必先利其器&#xff0c;我们先来看一下什么是ChatGPT。小试牛刀&#xff0c;让ChatGPT自己来回答一下&#xff1a; 从介绍中可以看出来ChatGPT很擅长处理自然语言&#xff0c;那我们来看看AI处理编程语言的效果如何呢&#xff1f; 第一个挑战&#xff0c;让ChatGP…

如何搭建与使用FTP服务器

文档资料&#xff1a;https://download.csdn.net/download/wangshuxuncom/87845843https://download.csdn.net/download/wangshuxuncom/87845843 视频教程&#xff1a;如何搭建与使用FTP服务器_哔哩哔哩_bilibili如何搭建与使用FTP服务器共计5条视频&#xff0c;包括&#xff…

如何使用Harbor私有镜像仓库

文档资料&#xff1a;https://download.csdn.net/download/wangshuxuncom/87835045https://download.csdn.net/download/wangshuxuncom/87835045 视频教程&#xff1a;服务端_哔哩哔哩_bilibili服务端是如何使用Harbor私有镜像仓库的第1集视频&#xff0c;该合集共计5集&#…

Docker插件一键部署SpringBoot项目

视频&#xff1a; Docker插件一键部署SpringBoot项目_哔哩哔哩_bilibiliDocker插件一键部署SpringBoot项目共计4条视频&#xff0c;包括&#xff1a;环境搭建、集成Docker、创建项目等&#xff0c;UP主更多精彩视频&#xff0c;请关注UP账号。https://www.bilibili.com/video/…

如何在Linux中安装GitLab

文档资料&#xff1a;https://download.csdn.net/download/wangshuxuncom/87840407https://download.csdn.net/download/wangshuxuncom/87840407 视频教程&#xff1a;如何在Linux中安装GitLab_哔哩哔哩_bilibili如何在Linux中安装GitLab共计5条视频&#xff0c;包括&#xff…

老高的 IT 漫谈 - 20200501

新形式 作为一个从上个世纪到现在的 IT 行业老年人&#xff0c;这个公众号开通的初衷其实是想写 IT 圈的事情&#xff0c;甚至是吐槽。但是随着那时候开始折腾海外数据的原因&#xff0c;工作越来越忙&#xff0c;微博都没时间上了&#xff0c;哪有时间写不正经的内容&#xff…

老高的 IT 漫谈 - 20200512

前言&#xff1a; 月初写了第一篇漫谈&#xff0c;反馈还好&#xff0c;所以继续努力写吧&#xff0c;也许以后不做 IP 库了&#xff0c;可以转型做 IT 评论养家糊口了。。。 闲言碎语不再讲&#xff0c;下面开始正题。 腾讯视频超前点播案 内容链接&#xff1a;腾讯“超前点播…

当杠精型AI丈夫遇上阴阳怪气AI老婆,你的代码玩得转吗?

玩趣味活动 赢千元奖金 DataFountain社区首个趣味活动来啦&#xff01;&#xff01;&#xff01; 活动已发车&#xff0c;来不及解释了&#xff0c;先上车&#xff1a;https://www.datafountain.cn/information/activity/3 人工智能问答爆火&#xff0c;你的算法技能储备跟上…