【OpenAI官方课程】第五课:ChatGPT文本转换Transforming

欢迎来到ChatGPT 开发人员提示工程课程(ChatGPT Prompt Engineering for Developers)!本课程将教您如何通过OpenAI API有效地利用大型语言模型(LLM)来创建强大的应用程序。

本课程由OpenAI 的Isa Fulford和 DeepLearning.AI 的Andrew Ng主讲,深入了解 LLM 的运作方式,提供即时工程的最佳实践,并演示 LLM API 在各种应用程序中的使用。

在本课程笔记本中,我们将探讨如何使用大型语言模型进行文本转换任务,例如语言翻译、拼写和语法检查、语气调整以及格式转换。

设置

import openai
import os

from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # 读取本地的.env文件

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"]

翻译

ChatGPT是通过许多语言的来源进行训练的。这使得该模型具有翻译能力。以下是如何使用这种能力的一些示例。

prompt = f"""
将以下英文文本翻译成西班牙文:\ 
```Hi, I would like to order a blender```
"""
response = get_completion(prompt)
print(response)

Hola, me gustaría ordenar una licuadora.

prompt = f"""
告诉我这是哪种语言: 
```Combien coûte le lampadaire?```
"""
response = get_completion(prompt)
print(response)

这是法语。

prompt = f"""
将以下文本翻译成法语、西班牙语和英语: \
```I want to order a basketball```
"""
response = get_completion(prompt)
print(response)

法语: Je veux commander un ballon de basket
西班牙语: Quiero pedir una pelota de baloncesto
英语: I want to order a basketball

prompt = f"""
将以下文本翻译成西班牙语的正式和非正式形式: 
'Would you like to order a pillow?'
"""
response = get_completion(prompt)
print(response)

正式: ¿Le gustaría ordenar una almohada?
非正式: ¿Te gustaría ordenar una almohada?

通用翻译器

假设你负责一个大型跨国电子商务公司的IT部门。用户用各自的母语给你发消息,反映他们遇到的IT问题。你的员工来自世界各地,只会说他们的母语。你需要一个通用翻译器!

user_messages = [
  "La performance du système est plus lente que d'habitude.",  # 系统性能比平时慢。
  "Mi monitor tiene píxeles que no se iluminan.",              # 我的显示器有像素点不亮。
  "Il mio mouse non funziona",                                 # 我的鼠标不工作
  "Mój klawisz Ctrl jest zepsuty",                             # 我的Ctrl键坏了
  "我的屏幕在闪烁"                                               # 我的屏幕在闪烁
] 
for issue in user_messages:
    prompt = f"告诉我这是哪种语言: ```{issue}```"
    lang = get_completion(prompt)
    print(f"原始消息 ({lang}): {issue}")

    prompt = f"""
    将以下文本翻译成英文和韩文: ```{issue}```
    """
    response = get_completion(prompt)
    print(response, "\n")

原始消息 (这是法语.): La performance du système est plus lente que d’habitude.
英文: The system performance is slower than usual.
韩文: 시스템 성능이 평소보다 느립니다.
原始消息 (这是西班牙语.): Mi monitor tiene píxeles que no se iluminan.
英文: My monitor has pixels that don’t light up.
韩文: 내 모니터에는 불이 켜지지 않는 픽셀이 있습니다.
原始消息 (这是意大利语.): Il mio mouse non funziona
英文: My mouse is not working.
韩文: 내 마우스가 작동하지 않습니다.
原始消息 (这是波兰语.): Mój klawisz Ctrl jest zepsuty
英文: My Ctrl key is broken.
韩文: 제 Ctrl 키가 고장 났어요.
原始消息 (这是中文(简体).): 我的屏幕在闪烁
英文: My screen is flickering.
韩文: 내 화면이 깜빡입니다.

文本语气转换

写作可以根据预期受众而变化。ChatGPT可以产生不同的语气。

prompt = f"""
将以下俚语转换成商务信函: 
'Dude, This is Joe, check out this spec on this standing lamp.'
"""
response = get_completion(prompt)
print(response)

尊敬的先生/女士,

我写信是想向您介绍一款我认为可能对您有兴趣的落地灯。请查看附件中的规格以供审阅。

谢谢您的时间和考虑。

真诚地,

Joe

格式转换

ChatGPT可以在不同格式之间进行转换。提示应描述输入和输出格式。

data_json = { "resturant employees" :[ 
    {"name":"Shyam", "email":"shyamjaiswal@gmail.com"},
    {"name":"Bob", "email":"bob32@gmail.com"},
    {"name":"Jai", "email":"jai87@gmail.com"}
]}
prompt = f"""
将以下python字典从JSON转换为带有列标题和标题的HTML表格: {data_json}
"""
response = get_completion(prompt)
print(response)

Output:

<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>
from IPython.display import display, Markdown, Latex, HTML, JSON
display(HTML(response))
Restaurant Employees
NameEmail
Shyamshyamjaiswal@gmail.com
Bobbob32@gmail.com
Jaijai87@gmail.com

拼写检查/语法检查。

以下是常见语法和拼写问题以及LLM的响应的一些示例。

要向LLM发出信号,指示它对您的文本进行校对,您可以指示模型“校对”或“校对和纠正”。

text = [ 
  "The girl with the black and white puppies have a ball.",  # 这个女孩有一个球。
  "Yolanda has her notebook.", # 没问题
  "Its going to be a long day. Does the car need it’s oil changed?",  # 同音异形词
  "Their goes my freedom. There going to bring they’re suitcases.",  # 同音异形词
  "Your going to need you’re notebook.",  # 同音异形词
  "That medicine effects my ability to sleep. Have you heard of the butterfly affect?", # 同音异形词
  "This phrase is to cherck chatGPT for speling abilitty"  # 拼写
]
for t in text:
    prompt = f"""校对并纠正以下文本
    并重写已更正的版本。如果您找不到错误,
    只需说“未发现错误”。在文本周围不要使用
    任何标点符号:
    ```{t}```"""
    response = get_completion(prompt)
    print(response)

The girl with the black and white puppies has a ball.
No errors found.
It’s going to be a long day. Does the car need its oil changed?
Their goes my freedom. There going to bring they’re suitcases.
Corrected version:
There goes my freedom. They’re going to bring their suitcases.
You’re going to need your notebook.
That medicine affects my ability to sleep. Have you heard of the butterfly effect?
This phrase is to check ChatGPT for spelling ability.

text = f"""
Got this for my daughter for her birthday cuz she keeps taking \
mine from my room.  Yes, adults also like pandas too.  She takes \
it everywhere with her, and it's super soft and cute.  One of the \
ears is a bit lower than the other, and I don't think that was \
designed to be asymmetrical. It's a bit small for what I paid for it \
though. I think there might be other options that are bigger for \
the same price.  It arrived a day earlier than expected, so I got \
to play with it myself before I gave it to my daughter.
"""
prompt = f"校对并纠正此评论:```{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.

prompt = f"""
校对并纠正此评论。使其更具吸引力。 
确保它遵循APA风格指南并针对高级读者。 
以markdown格式输出。
Text: ```{text}```
"""
response = get_completion(prompt)
display(Markdown(response))

Title: A Soft and Cute Panda Plush Toy for All Ages
Introduction: As a parent, finding the perfect gift for your child’s birthday can be a daunting task. However, I stumbled upon a soft and cute panda plush toy that not only made my daughter happy but also brought joy to me as an adult. In this review, I will share my experience with this product and provide an honest assessment of its features.
Product Description: The panda plush toy is made of high-quality materials that make it super soft and cuddly. Its cute design is perfect for children and adults alike, making it a versatile gift option. The toy is small enough to carry around, making it an ideal companion for your child on their adventures.
Pros: The panda plush toy is incredibly soft and cute, making it an excellent gift for children and adults. Its small size makes it easy to carry around, and its design is perfect for snuggling. The toy arrived a day earlier than expected, which was a pleasant surprise.
Cons: One of the ears is a bit lower than the other, which makes the toy asymmetrical. Additionally, the toy is a bit small for its price, and there might be other options that are bigger for the same price.
Conclusion: Overall, the panda plush toy is an excellent gift option for children and adults who love cute and cuddly toys. Despite its small size and asymmetrical design, the toy’s softness and cuteness make up for its shortcomings. I highly recommend this product to anyone looking for a versatile and adorable gift option.

  • 24
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值