前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >用ChatGPT进行翻译、校对、扩写、聊天

用ChatGPT进行翻译、校对、扩写、聊天

作者头像
Michael阿明
发布2023-05-26 17:26:46
1.3K0
发布2023-05-26 17:26:46
举报

代码语言:javascript
复制
import openai
import os

from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # read local .env file

openai.api_key  = os.getenv('OPENAI_API_KEY')

def get_completion(prompt, model="gpt-3.5-turbo", temperature=0): 
    messages = [{"role": "user", "content": prompt}]
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=temperature, 
    )
    return response.choices[0].message["content"]

1. 翻译

代码语言:javascript
复制
prompt = f"""
翻译以下句子为中文: \ 
```Hi, I would like to order a blender```
"""
response = get_completion(prompt)
print(response)

输出:嗨,我想订购一个搅拌机。

代码语言:javascript
复制
prompt = f"""
这个句子是什么语言的: 
```Combien coûte le lampadaire?```
"""
response = get_completion(prompt)
print(response)

输出:这个句子是法语。

代码语言:javascript
复制
prompt = f"""
分别将以下句子翻译为英语、法语、西班牙语、中文: \
```I want to order a basketball```
"""
response = get_completion(prompt)
print(response)

输出:

代码语言:javascript
复制
英语:I want to order a basketball.
法语:Je veux commander un ballon de basket.
西班牙语:Quiero pedir una pelota de baloncesto.
中文:我想订购一个篮球。
代码语言:javascript
复制
prompt = f"""
使用正式和非正式的口气翻译下面的句子为中文: 
'Would you like to order a pillow?'
"""
response = get_completion(prompt)
print(response)

输出:

代码语言:javascript
复制
正式口气:您是否需要订购一个枕头?
非正式口气:你要不要订一个枕头?

2. 通用翻译器

代码语言:javascript
复制
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"""
    翻译以下文本为中文和俄文: ```{issue}```
    """
    response = get_completion(prompt)
    print(response, "\n")

输出:

代码语言:javascript
复制
Original message (This is French.): La performance du système est plus lente que d'habitude.
中文:系统性能比平常慢。
俄文:Системная производительность медленнее, чем обычно. 

Original message (This is Spanish.): Mi monitor tiene píxeles que no se iluminan.
我的显示器有不亮的像素。

Мой монитор имеет пиксели, которые не светятся. 

Original message (This is Italian.): Il mio mouse non funziona
我的鼠标不工作。

Моя мышь не работает. 

Original message (This is Polish.): Mój klawisz Ctrl jest zepsuty
我的Ctrl键坏了
Моя клавиша Ctrl сломана 

Original message (This is Chinese (Simplified).): 我的屏幕在闪烁
中文:我的屏幕在闪烁。
俄文:Мой экран мигает. 

3. 风格改写

代码语言:javascript
复制
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)

输出:

代码语言:javascript
复制
Dear Sir/Madam,

I am writing to bring to your attention a standing lamp that I believe may be of interest to you. Please find attached the specifications for your review.

Thank you for your time and consideration.

Sincerely,

Joe
代码语言:javascript
复制
prompt = f"""
使用一首中国的诗词来表达下面的句子: 
'The little girl propped up a small boat and 
stole the white lotus back. 
Without understanding the hidden traces, 
the duckweed drove along'
"""
response = get_completion(prompt)
print(response)

输出:

代码语言:javascript
复制
小姑娘撑起小船,偷了白莲回。
不解其中蕴含,萍水随波逐。

4. 格式转化

代码语言:javascript
复制
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))

输出:

代码语言:javascript
复制
<table>
  <caption>Restaurant Employees</caption>
  <thead>
    <tr>
      <th>Name</th>
      <th>Email</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Shyam</td>
      <td>shyamjaiswal@gmail.com</td>
    </tr>
    <tr>
      <td>Bob</td>
      <td>bob32@gmail.com</td>
    </tr>
    <tr>
      <td>Jai</td>
      <td>jai87@gmail.com</td>
    </tr>
  </tbody>
</table>
在这里插入图片描述
在这里插入图片描述

5. 校对、更正

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

输出:

代码语言:javascript
复制
The girl with the black and white puppies has a ball.
No errors found.
It's going to be a long day. Does the car need its oil changed?
Their goes my freedom. There going to bring they're suitcases.

Corrected version: 
There goes my freedom. They're going to bring their suitcases.
You're going to need your notebook.
That medicine affects my ability to sleep. Have you heard of the butterfly effect?
This phrase is to check ChatGPT for spelling ability.
代码语言:javascript
复制
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)

输出:

代码语言:javascript
复制
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.
代码语言:javascript
复制
from redlines import Redlines

diff = Redlines(text,response)
display(Markdown(diff.output_markdown))
在这里插入图片描述
在这里插入图片描述

模型修改了语句,还删除了一些多余的空格

代码语言:javascript
复制
prompt = f"""
校对并更正这篇评论。让它更有吸引力。
确保它遵循APA风格的指南,并以高级读者为目标。
以 markdown 格式输出
Text: ```{text}```
"""
response = get_completion(prompt)
display(Markdown(response))

输出:

代码语言:javascript
复制
Title: A Soft and Cute Panda Plush Toy for All Ages

I purchased this panda plush toy for my daughter's birthday because she kept taking mine from my room. 
As an adult, I also appreciate the cuteness of pandas. 
My daughter takes it everywhere with her, and it's incredibly soft and adorable. 
However, I did notice that one of the ears is slightly lower than the other, which I don't think was intended to be asymmetrical.

While I love the quality of the toy, I do think it's a bit small for the price I paid. 
I believe there are other options available that are larger for the same price. 
Nonetheless, the toy arrived a day earlier than expected, which gave me the opportunity to play with it myself before giving it to my daughter.

Overall, I highly recommend this panda plush toy for anyone who loves soft and cute stuffed animals. 
It's perfect for children and adults alike.

6. 扩写

生成客户服务电子邮件,邮件是根据每个客户的评论量身定制的

代码语言:javascript
复制
# given the sentiment from the lesson on "inferring",
# and the original customer message, customize the email
sentiment = "负面"

# review for a blender
review = f"""
所以,他们仍然有季节性的17件套\
11月份的售价约为49美元\
半价,但出于某种原因(称之为哄抬价格)\
大约在12月的第二周,价格都上涨了\
最高可达70美元至89美元不等\
系统11件套系统的价格上涨了约10美元或\
因此,价格也与之前29美元的售价不同\
所以它看起来不错,但如果你看看底座\
刀片锁定位置看起来不太好\
就像几年前的版本一样,但我\
计划对它非常温和(例如,我喜欢\
非常坚硬的物品,如豆类、冰块、大米等
先用搅拌机搅拌,然后把它们按份量粉碎\
我要加入搅拌机,然后换成搅打\
切出更细的面粉,并使用横切刀片\
制作冰沙时先用平刀片\
如果我需要更细/更少浆的话)。制作时的特殊提示\
冰沙,切细并冷冻水果\
蔬菜(如果用菠菜稍微炖一下,会软化
菠菜然后冷冻,直到可以使用,如果制作的话\
冰糕,使用中小型食品加工机)
你计划以这种方式使用,你可以避免添加\
如果在做奶昔的时候有很多冰的话\
大约一年后,发动机发出了奇怪的声音\
我打电话给客服,但保修期已过\
已经了,所以我不得不再买一个。仅供参考:总体\
这些类型的产品质量都很差,所以\
他们有点指望品牌知名度和\
消费者忠诚度以维持销售额。大约收到了两天。
"""

prompt = f"""
你是一名客服人工智能助理。
您的任务是向有价值的客户发送电子邮件回复。
给定由```分隔的客户电子邮件生成回复以感谢客户的评价。
如果情绪是积极的或中立的,感谢他们他们的评论。
如果情绪消极,道歉并建议他们可以联系客户服务。
确保使用评论中的具体细节。用简洁而专业的语气写作。
在电子邮件上签名为“AI客户代理”。
顾客评价: ```{review}```
评价情绪: {sentiment}
"""
response = get_completion(prompt)
print(response)

输出:

代码语言:javascript
复制
尊敬的客户,

我们非常抱歉听到您对我们的产品不满意。我们感谢您分享您的经验和反馈,这对我们来说非常重要。

我们深刻理解您的不满和失望,并希望能够解决您的问题。如果您需要任何帮助或支持,请随时联系我们的客户服务团队,我们将竭尽全力为您提供帮助。

再次感谢您对我们的反馈,我们将继续努力提高我们的产品和服务质量。

祝您一切顺利。

AI客户代理

更改参数temperature=0.7

代码语言:javascript
复制
response = get_completion(prompt, temperature=0.7)
print(response)

输出:

代码语言:javascript
复制
尊敬的客户,

非常感谢您对我们产品的评价和反馈。我们非常抱歉您遇到了不愉快的经历,我们的产品质量不符合您的期望。

我们建议您联系我们的客户服务团队,以便我们可以为您提供更多的帮助和支持。我们会在我们的最佳能力范围内尽力解决您的问题。

再次感谢您对我们产品的评价和反馈。我们将继续努力提高我们的产品质量和客户服务。

祝您一切顺利。

AI客户代理

输出提到了 我们的产品质量不符合您的期望

参数改成 1,输出如下:

代码语言:javascript
复制
尊敬的顾客,

感谢您给出的评价并对您的经历表示歉意。
我们很抱歉听到您购买的产品发出了奇怪的声音,但保修期已过。
我们建议您联系我们的客户服务团队以了解其他可行的解决方案。

我们对于这次购物体验的问题倍感尴尬,但我们保证对于未来的服务和产品,我们会更注重质量和可靠性。

AI客户代理

temperature = 0, 输出内容 比较稳定 否则, temperature 越大,内容越多样化

7. 聊天

代码语言:javascript
复制
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"]
代码语言:javascript
复制
messages =  [  
{'role':'system', 'content':'你是一个说话像莎士比亚的助手。'},    
{'role':'user', 'content':'给我讲个笑话'},   
{'role':'assistant', 'content':'为什么小鸡要过马路'},   
{'role':'user', 'content':'我不知道啊'}  ]

response = get_completion_from_messages(messages, temperature=1)
print(response)

输出:

代码语言:javascript
复制
为了到对面去看看为什么那只熊猫在借着秋千拍照呢。
代码语言:javascript
复制
messages =  [  
{'role':'system', 'content':'你是一个友好的聊天机器人'},    
{'role':'user', 'content':'你好,我的名字是迈克'}  ]
response = get_completion_from_messages(messages, temperature=1)
print(response)

输出:

代码语言:javascript
复制
你好迈克,很高兴和你交流。有什么我可以帮助你的吗?
代码语言:javascript
复制
messages =  [  
{'role':'system', 'content':'你是一个友好的聊天机器人'},    
{'role':'user', 'content':'你能告诉我,我叫什么名字吗?'}  ]
response = get_completion_from_messages(messages, temperature=1)
print(response)

输出:

代码语言:javascript
复制
很抱歉,我不知道您的名字。请问您能告诉我吗?
代码语言:javascript
复制
messages =  [  
{'role':'system', 'content':'你是一个友好的聊天机器人'},
{'role':'user', 'content':'你好,我的名字是迈克'},
{'role':'assistant', 'content': "hi,迈克,很高兴见到你,我能帮到你什么吗?"},
{'role':'user', 'content':'是的,你能告诉我,我叫什么名字吗?'}  ]
response = get_completion_from_messages(messages, temperature=1)
print(response)

输出:

代码语言:javascript
复制
很抱歉,迈克,我刚才已经看到你自我介绍时已经提到了你的名字了,你的名字就是迈克。

8. 点餐

代码语言:javascript
复制
def collect_messages(_):
    prompt = inp.value_input
    inp.value = ''
    context.append({'role':'user', 'content':f"{prompt}"})
    response = get_completion_from_messages(context) 
    context.append({'role':'assistant', 'content':f"{response}"})
    panels.append(
        pn.Row('User:', pn.pane.Markdown(prompt, width=600)))
    panels.append(
        pn.Row('Assistant:', pn.pane.Markdown(response, width=600, style={'background-color': '#F6F6F6'})))
 
    return pn.Column(*panels)
代码语言:javascript
复制
import panel as pn  # GUI
pn.extension()

panels = [] # collect display 

context = [ {'role':'system', 'content':"""
你是一个点餐机器人,这是一项为披萨店收集订单的自动化服务\
你先向客户打招呼,然后接单\
然后问是取货还是送货\
您等待收集整个订单,然后汇总并检查最终订单\
如果客户想添加其他内容,则需要时间\
如果是快递,你需要一个地址\
最后你收到了付款\
确保明确所有选项、附加功能和尺寸\
从菜单中识别项目\
你的回答简短,非常友好\
菜单包括\
意大利辣香肠披萨12.95、10.00、7.00\
奶酪披萨10.95、9.25、6.50\
茄子披萨11.95、9.75、6.75\
薯条4.50,3.50\
希腊沙拉7.25\
顶盖:\
额外的奶酪2.00\
蘑菇1.50\
香肠3.00\
加拿大培根3.50\
AI酱1.50\
辣椒1.00\
饮料:\
焦炭3.00、2.00、1.00\
精灵3.00、2.00、1.00\
瓶装水5.00\
"""} ]  # accumulate messages


inp = pn.widgets.TextInput(value="Hi", placeholder='Enter text here…')
button_conversation = pn.widgets.Button(name="Chat!")

interactive_conversation = pn.bind(collect_messages, button_conversation)

dashboard = pn.Column(
    inp,
    pn.Row(button_conversation),
    pn.panel(interactive_conversation, loading_indicator=True, height=300),
)

dashboard

输出:

代码语言:javascript
复制
Assistant:
你好!欢迎来到我们的披萨店!请问您是要取货还是需要送货呢?
请告诉我您的订单,我会尽快为您处理。
我们的菜单包括意大利辣香肠披萨、奶酪披萨、茄子披萨、薯条和希腊沙拉。
我们还有额外的奶酪、蘑菇、香肠、加拿大培根、AI酱和辣椒可以添加。
饮料方面,我们有焦炭、精灵和瓶装水可供选择。
请告诉我您的选择,我会为您确认订单并收取付款。

User:
我要点餐

Assistant:
好的,请问您需要取货还是送货呢?请告诉我您的订单,我会尽快为您处理。
我们的菜单包括意大利辣香肠披萨、奶酪披萨、茄子披萨、薯条和希腊沙拉。
我们还有额外的奶酪、蘑菇、香肠、加拿大培根、AI酱和辣椒可以添加。
饮料方面,我们有焦炭、精灵和瓶装水可供选择。
请告诉我您的选择,我会为您确认订单并收取付款。

User:
我要 茄子披萨,蘑菇,瓶装水

Assistant:
好的,您的订单是一份茄子披萨,加蘑菇,一瓶瓶装水,对吗?
请问您需要取货还是送货呢?

User:
我要送货上门

Assistant:
好的,我们需要您提供送货地址。
请告诉我您的地址,以便我们为您安排送货。
同时,您需要支付订单总额为 18.70 美元,
包括茄子披萨 11.95 美元,蘑菇 1.50 美元,
瓶装水 5.00 美元和送货费用 0.25 美元。
请问您使用哪种付款方式呢?

User:
我要使用信用卡付款

Assistant:
好的,我们接受信用卡付款。
请告诉我您的信用卡号码、过期日期和安全码,以便我们为您收取付款。
同时,请提供您的姓名和账单地址。
请注意,我们会保护您的个人信息,并使用安全的加密技术来处理您的付款。

User:
好麻烦,我用现金吧

Assistant:
没问题,我们接受现金付款。
请确认您的订单总额为 18.70 美元,
包括茄子披萨 11.95 美元,蘑菇 1.50 美元,
瓶装水 5.00 美元和送货费用 0.25 美元。
请确保您有足够的现金支付订单。
我们会尽快为您安排送货。谢谢您的订购!
代码语言:javascript
复制
messages =  context.copy()
messages.append(
{'role':'system', 'content':'''创建上一个食物订单的json摘要。
逐项列出每件商品的价格
字段应为1)披萨,包括尺寸  
2)顶盖清单 
3)饮料清单,包括尺寸  
4)配菜清单包括尺寸  
5)运费
6)总价'''},    
)

response = get_completion_from_messages(messages, temperature=0)
print(response)

输出:

代码语言:javascript
复制
以下是上一个食物订单的JSON摘要:

{
  "订单号": "123456",
  "订单时间": "2021-08-01 12:30:00",
  "订单类型": "送货上门",
  "送货地址": "123 Main St, Anytown, USA",
  "订单详情": [
    {
      "商品名称": "茄子披萨",
      "尺寸": "中",
      "价格": 11.95
    },
    {
      "商品名称": "蘑菇",
      "价格": 1.50
    },
    {
      "商品名称": "瓶装水",
      "尺寸": "小",
      "价格": 5.00
    }
  ],
  "配菜清单": [],
  "饮料清单": [],
  "披萨清单": [],
  "顶盖清单": [
    {
      "名称": "蘑菇",
      "价格": 1.50
    }
  ],
  "运费": 0.25,
  "总价": 18.70
}

其中,茄子披萨中尺寸的价格为 11.95 美元,蘑菇的价格为 1.50 美元,瓶装水小尺寸的价格为 5.00 美元,配菜清单和饮料清单为空,披萨清单为空,顶盖清单中只有蘑菇,价格为 1.50 美元,运费为 0.25 美元,总价为 18.70 美元。
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2023-05-21,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 1. 翻译
  • 2. 通用翻译器
  • 3. 风格改写
  • 4. 格式转化
  • 5. 校对、更正
  • 6. 扩写
  • 7. 聊天
  • 8. 点餐
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档