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

news2024/11/27 16:47:17

目录


前言

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 foam

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

输出
在这里插入图片描述

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

五、转换

转换:大型语言模型非常擅长将其输入转换为不同的格式,例如输入一种语言的一段文本并将其翻译成不同的语言, 或帮助进行拼写和语法方面的更正。或者输入 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_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, 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.coloradmin.cn/o/615605.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

软件外包开发UI管理工具

软件在开发前需要设计UI界面&#xff0c;UI界面是产品经理和开发人员、测试人员之间的交流工具&#xff0c;因此项目中会有多人的工作涉及到的UI界面&#xff0c;这就需要有个好的工具协调相互之间的工作。今天和大家分享一些常用到的工具&#xff0c;希望对大家的工作有所帮助…

插件框架PF4J-从理论到实践

PF4J:Plugin Framework for Java 目录 是什么&#xff1f; 不是什么&#xff1f; 特点 组件 主要类 流程概述 spring-pf4j 思考 功能模块化 我对pf4j的封装和使用demo GitHub - chlInGithub/pf4jDemo: pf4j demo 是什么&#xff1f; 开源轻量级的插件框架。通过插件…

三相三线、三相四线、三相五线制区别

三相三线、三相四线、三相五线制区别 1、三相三线2、三相四线3、三相五线4、三相三线和三相四线的区别5、三相四线和三相五线的区别 1、三相三线 由A、B、C这3根相线俗称火线组成&#xff0c;没有布置零线N和接地线PE&#xff0c;这种布线方式常见于交流380V的上一级10KV的系统…

Maven安装教程

maven环境配置&#xff08;点击此电脑右键属性&#xff09;&#xff1a; 点击高级系统设置&#xff0c;点击环境变量&#xff1a; 开始配置环境变量&#xff08;点击系统变量&#xff0c;新建按钮&#xff09;&#xff1a; 新建系统变量&#xff1a;MAVEN_HOMED:\maven\apac…

vueX学习看这篇就够了

vuex就是为了实现全局状态管理 vuex有哪些东西&#xff1f; state【状态】getter【可以认为是 store 的计算属性&#xff0c;不会修改状态】mutation【唯一修改state的方法&#xff0c;不支持异步】action【不能直接修改state,通过触发mutation修改状态&#xff0c;支持异步】…

GPT聊天功能,逐字返回数据

目录 前言一、前端二、后端1.接收前端请求的api如下是继续向其他接口请求的api如下是直接返回前端数据的api甚至可以返回图片 2.模拟GPT的接口 前言 我们在和GPT交流的时候发现GPT总是逐字的显示&#xff0c;因为GPT是一种基于神经网络的自然语言处理模型&#xff0c;它的训练…

王道考研计算机网络第一章知识点汇总

以上内容为1.1概念与功能的重点知识点 以下为1.2组成与分类&#xff1a; P2P模式下每台主机既可以是客户也可以是服务器&#xff0c;主机越多资源分享速度越快。 1.3标准化工作及相关组织 1.4性能指标 带宽只是指的是从主机内部往传输链路上投送数据的最大能力(从入口端放入数…

棱镜七彩中标浦发银行项目 助力金融行业开源治理

近日&#xff0c;棱镜七彩凭借出色的研发实力和优秀的产品服务能力在众多竞标企业中脱颖而出&#xff0c;成功中标上海浦东发展银行创新实验室“开源治理扫描工具信创改造课题”项目。棱镜七彩将为浦发银行在开源软件治理、软件安全可靠性等方面提供全方位支持。 在数字经济发…

odoo from 表单自定义按钮 执行JS代码 并调用websoket

业务场景&#xff1a; 集成串口读取RFID数据。由于串口是需要在客户端本地电脑执行才可以拿到数据 但是系统 部署在服务器 不能直接调用串口。 解决方案&#xff1a; 利用websoket通信 调用串口 传输 读取到的串口数据&#xff0c;解决服务器与本地之间的通信 本场景是基于odo…

深度解析:2023年软件测试的10个新趋势和挑战

随着技术的飞速发展&#xff0c;软件测试的角色和责任也在经历重大转变。我们在2023年目前所面临的一些新趋势和挑战值得所有从业人员关注。以下是这些主要趋势和挑战的深度分析。 趋势一&#xff1a;人工智能和机器学习在测试中的应用 AI和ML正在越来越多地应用于软件测试&am…

给httprunnermanager接口自动化测试平台演示参数化(五)

文章目录 一、背景1.1、前情回顾 二、参数化实现三、总结 一、背景 参数化&#xff0c;在使用httprunner框架的时候&#xff0c;参数话说实在的不是很实用&#xff0c;因为更多是场景化的用例编写&#xff0c;不用过多的去参数化批量执行&#xff0c;无非也就是登录注册查询啥的…

数据库系统概论 ---知识点大全(期末复习版)

&#xff08;一&#xff09;绪论 数据(Data)&#xff1a;是数据库中存储的基本对象 数据的定义&#xff1a;描述事物的符号记录 数据的种类&#xff1a;文字、图形、图象、声音等 数据的特点&#xff1a;数据与其语义是不可分的 数据库(Database,简称DB)&#xff1a;是长期…

数据结构与算法-跳表详解

我们知道如果一个数组是有序的&#xff0c;查询的时候可以使用二分法进行查询&#xff0c;时间复杂度可以降到 O(logn) &#xff0c;但如果链表是有序的&#xff0c;我们仍然是从前往后一个个查找&#xff0c;这样显然很慢&#xff0c;这个时候我们可以使用跳表&#xff08;Ski…

chatgpt赋能python:Python如何依次取字符——一种简单有效的方法

Python如何依次取字符——一种简单有效的方法 1. 介绍 Python 常常被用于编写文本处理脚本&#xff0c;而文本处理中的一个常见任务就是依次取字符。本文将介绍一种简单高效的方法&#xff0c;让您可以在 Python 中便捷地完成此操作。 2. 如何依次取字符 Python 中的字符串…

黑客入门必备指南

在探讨黑客如何入门之前&#xff0c;首先我们的思想要端正。 作为一名黑客&#xff0c;必须要有正直善良的价值观。 或许你听过这么一句话“能力越大&#xff0c;责任越大”作为一名黑客就是如此&#xff0c;黑客的技术越精湛&#xff0c;能力就越大&#xff0c;就越不能去干…

spark入门 Linux模式 Local模式 (二)

一、下载对应的spark包 https://archive.apache.org/dist/spark/spark-3.0.0/ 我这里下载的是spark-3.0.0-bin-hadoop3.2.tgz 二、解压 tar -zvxf spark-3.0.0-bin-hadoop3.2.tgz三、启动 再解压路径的bin目录执行下 ./spark-shell 四、测试 WordCount代码例子 sc.textFil…

接口测试-使用mock生产随机数据

在做接口测试的时候&#xff0c;有的接口需要进行大量的数据进行测试&#xff0c;还不能是重复的数据&#xff0c;这个时候就需要随机生产数据进行测试了。这里教导大家使用mock.js生成各种随机数据。 一、什么是mock.js mock.js是用于生成随*机数据&#xff0c;拦截 Ajax 请…

uniapp引入uView正确步骤及误区

1.导入uview组件库 2.导入成功后在main.js里引入 import uView from /uni_modules/uview-ui Vue.use(uView)3.在App.vue里引入样式文件 import "/uni_modules/uview-ui/index.scss";4.在pages.json里添加配置 "easycom": {"^u-(.*)": "/…

大聪明教你学Java | parallelStream().forEach() 的踩坑日记

前言 &#x1f34a;作者简介&#xff1a; 不肯过江东丶&#xff0c;一个来自二线城市的程序员&#xff0c;致力于用“猥琐”办法解决繁琐问题&#xff0c;让复杂的问题变得通俗易懂。 &#x1f34a;支持作者&#xff1a; 点赞&#x1f44d;、关注&#x1f496;、留言&#x1f4…

springboot学生管理系统(含源码+数据库)

本次系统开发所用到的Java语言、Spring框架、SpringMVC框架、MyBatis框架、SpringBoot框架以及MySQL。 1.系统分析 &#xff08;1&#xff09;教师管理需求&#xff0c;学校想轻松的查阅指定教师的信息&#xff0c;学校对教师进行一个基本的信息管理&#xff0c;学校可以方便…