首页 > 其他分享 >面向开发者的ChatGPT提示工程-06.转换

面向开发者的ChatGPT提示工程-06.转换

时间:2023-05-07 16:47:47浏览次数:42  
标签:prompt get than 开发者 06 ChatGPT 文本 my response

 

<iframe allowfullscreen="allowfullscreen" frameborder="no" height="500" scrolling="no" src="https://player.bilibili.com/player.html?aid=825579986&bvid=BV1vg4y1L7vR&cid=1113012369&page=1" style="width: 1000px; height: 500px" width="1000"> </iframe>

 

1 引言

   

LLM非常擅长将输入转换成不同的格式,例如多语种文本翻译、拼写及语法纠正、语气调整、格式转换等。

本章节将介绍如何使用编程的方式,调用API接口来实现“文本转换”功能。

   

首先,我们需要OpenAI包,加载API密钥,定义getCompletion函数。

  In [7]:
import openai
import os
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY2")
openai.api_key = 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"]
   

2 文本翻译

   

中文转西班牙语

  In [2]:
prompt = f"""
将以下中文翻译成西班牙语: \ 
```您好,我想订购一个搅拌机。```
"""
response = get_completion(prompt)
print(response)
   
Hola, me gustaría ordenar una batidora.
   

识别语种

  In [3]:
prompt = f"""
请告诉我以下文本是什么语种: 
```Combien coûte le lampadaire?```
"""
response = get_completion(prompt)
print(response)
   
这是法语。
   

多语种翻译

  In [4]:
prompt = f"""
请将以下文本分别翻译成中文、英文、法语和西班牙语: 
```I want to order a basketball.```
"""
response = get_completion(prompt)
print(response)
   
中文:我想订购一个篮球。
英文:I want to order a basketball.
法语:Je veux commander un ballon de basket.
西班牙语:Quiero pedir una pelota de baloncesto.
   

翻译+正式语气

  In [6]:
prompt = f"""
请将以下文本翻译成中文,分别展示成正式与非正式两种语气: 
```Would you like to order a pillow?```
"""
response = get_completion(prompt)
print(response)
   
正式语气:请问您需要订购枕头吗?
非正式语气:你要不要订一个枕头?
   

通用翻译器

   

随着全球化与跨境商务的发展,交流的用户可能来自各个不同的国家,使用不同的语言,因此我们需要一个通用翻译器,识别各个消息的语种,并翻译成目标用户的母语,从而实现更方便的跨国交流。

  In [2]:
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
]
  In [8]:
for issue in user_messages:
    prompt = f"告诉我以下文本是什么语种,直接输出语种,如法语,无需输出标点符号: ```{issue}```"
    lang = get_completion(prompt)
    print(f"原始消息 ({lang}): {issue}\n")

    prompt = f"""
    将以下消息分别翻译成英文和中文,并写成
    中文翻译:xxx
    英文翻译:yyy
    的格式:
    ```{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

中文翻译:我的Ctrl键坏了
英文翻译:My Ctrl key is broken. 
=========================================
原始消息 (中文): 我的屏幕在闪烁

中文翻译:我的屏幕在闪烁。
英文翻译:My screen is flickering. 
=========================================
   

3 语气/风格调整

   

写作的语气往往会根据受众对象而有所调整。例如,对于工作邮件,我们常常需要使用正式语气与书面用词,而对同龄朋友的微信聊天,可能更多地会使用轻松、口语化的语气。

  In [9]:
prompt = f"""
将以下文本翻译成商务信函的格式: 
```小老弟,我小羊,上回你说咱部门要采购的显示器是多少寸来着?```
"""
response = get_completion(prompt)
print(response)
   
尊敬的XXX(收件人姓名):

您好!我是XXX(发件人姓名),在此向您咨询一个问题。上次我们交流时,您提到我们部门需要采购显示器,但我忘记了您所需的尺寸是多少英寸。希望您能够回复我,以便我们能够及时采购所需的设备。

谢谢您的帮助!

此致

敬礼

XXX(发件人姓名)
   

4 格式转换

   

ChatGPT非常擅长不同格式之间的转换,例如JSON到HTML、XML、Markdown等。在下述例子中,我们有一个包含餐厅员工姓名和电子邮件的列表的JSON,我们希望将其从JSON转换为HTML。

  In [9]:
data_json = { "resturant employees" :[ 
    {"name":"Shyam", "email":"[email protected]"},
    {"name":"Bob", "email":"[email protected]"},
    {"name":"Jai", "email":"[email protected]"}
]}
  In [10]:
prompt = f"""
将以下Python字典从JSON转换为HTML表格,保留表格标题和列名:{data_json}
"""
response = get_completion(prompt)
print(response)
   
<table>
  <caption>resturant employees</caption>
  <thead>
    <tr>
      <th>name</th>
      <th>email</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Shyam</td>
      <td>[email protected]</td>
    </tr>
    <tr>
      <td>Bob</td>
      <td>[email protected]</td>
    </tr>
    <tr>
      <td>Jai</td>
      <td>[email protected]</td>
    </tr>
  </tbody>
</table>
  In [11]:
from IPython.display import display, Markdown, Latex, HTML, JSON
display(HTML(response))
    resturant employees
name email
Shyam [email protected]
Bob [email protected]
Jai [email protected]
   

5 拼写及语法纠正

   

拼写及语法的检查与纠正是一个十分常见的需求,特别是使用非母语语言,例如发表英文论文时,这是一件十分重要的事情。

以下给了一个例子,有一个句子列表,其中有些句子存在拼写或语法问题,有些则没有,我们循环遍历每个句子,要求模型校对文本,如果正确则输出“未发现错误”,如果错误则输出纠正后的文本。

  In [14]:
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 spelling abilitty"  # spelling
]
  In [16]:
for i in range(len(text)):
    prompt = f"""请校对并更正以下文本,注意纠正文本保持原始语种,无需输出原始文本。
    如果您没有发现任何错误,请说“未发现错误”。
    
    例如:
    输入:I are happy.
    输出:I am happy.
    ```{text[i]}```"""
    response = get_completion(prompt)
    print(i, response)
   
0 The girl with the black and white puppies has a ball.
1 未发现错误。
2 It's going to be a long day. Does the car need its oil changed?
3 Their goes my freedom. They're going to bring their suitcases.
4 输出:You're going to need your notebook.
5 That medicine affects my ability to sleep. Have you heard of the butterfly effect?
6 This phrase is to check chatGPT for spelling ability.
   

以下是一个简单的类Grammarly纠错示例,输入原始文本,输出纠正后的文本,并基于Redlines输出纠错过程。

  In [18]:
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.
"""
  In [14]:
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. It's also a bit smaller than I expected for the price. I think there might be other options that are bigger for the same price. On the bright side, it arrived a day earlier than expected, so I got to play with it myself before giving it to my daughter.
  In [19]:
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. It's also a bit smaller than I expected for the price. I think there might be other options that are bigger for the same price. On the bright side, it arrived a day earlier than expected, so I got to play with it myself before giving it to my daughter.
"""
  In [ ]:
# 如未安装redlines,需先安装
!pip3.8 install redlines
  In [22]:
from redlines import Redlines
from IPython.display import display, Markdown

diff = Redlines(text,response)
display(Markdown(diff.output_markdown))
   

Got I got this for my daughter for her daughter's birthday cuz because she keeps taking mine from my room. room. Yes, adults also like pandas too. too. She takes it everywhere with her, and it's super soft and cute. One cute. However, one of the ears is a bit lower than the other, and I don't think that was designed to be asymmetrical. It's also a bit small smaller than I expected for what I paid for it though. the price. I think there might be other options that are bigger for the same price. It price. On the bright side, it arrived a day earlier than expected, so I got to play with it myself before I gave giving it to my daughter.

   

6 一个综合样例:文本翻译+拼写纠正+风格调整+格式转换

  In [23]:
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.
"""
  In [24]:
prompt = f"""
针对以下三个反引号之间的英文评论文本,
首先进行拼写及语法纠错,
然后将其转化成中文,
再将其转化成优质淘宝评论的风格,从各种角度出发,分别说明产品的优点与缺点,并进行总结。
润色一下描述,使评论更具有吸引力。
输出结果格式为:
【优点】xxx
【缺点】xxx
【总结】xxx
注意,只需填写xxx部分,并分段输出。
将结果输出成Markdown格式。
```{text}```
"""
response = get_completion(prompt)
display(Markdown(response))
   

【优点】

  • 超级柔软可爱,女儿生日礼物非常受欢迎。
  • 成人也喜欢熊猫,我也很喜欢它。
  • 提前一天到货,让我有时间玩一下。

【缺点】

  • 一只耳朵比另一只低,不对称。
  • 价格有点贵,但尺寸有点小,可能有更大的同价位选择。

【总结】 这只熊猫玩具非常适合作为生日礼物,柔软可爱,深受孩子喜欢。虽然价格有点贵,但尺寸有点小,不对称的设计也有点让人失望。如果你想要更大的同价位选择,可能需要考虑其他选项。总的来说,这是一款不错的熊猫玩具,值得购买。

  In [ ]:
 

标签:prompt,get,than,开发者,06,ChatGPT,文本,my,response
From: https://www.cnblogs.com/botai/p/prompt-engineering-for-developers_6.html

相关文章

  • ChatGPT-Prompts使用指南
    1.StandardPromptsStandardpromptscanbecombinedwithothertechniqueslikerolepromptingandseed-wordpromptingtoenhancetheoutputofChatGPT.......
  • 面向开发者的ChatGPT提示工程-07.扩展
      第七章扩展扩展是将短文本,例如一组说明或主题列表,输入到大型语言模型中,让模型生成更长的文本,例如基于某个主题的电子邮件或论文。这样做有一些很好的用途,例如将大型语言模型用作头脑风暴的伙伴。但这种做法也存在一些问题,例如某人可能会使用它来生成大量垃圾邮件。......
  • 面向开发者的ChatGPT提示工程-08.聊天
      对话聊天使用一个大型语言模型的一个令人兴奋的事情是,我们可以用它来构建一个定制的聊天机器人,只需要很少的工作量。在这一节中,我们将探索如何利用聊天格式(接口)与个性化或专门针对特定任务或行为的聊天机器人进行延伸对话。启动 In [1]:importosim......
  • 面向开发者的ChatGPT提示工程-09.总结
     恭喜你完成了这门短期课程。总的来说,在这门课程中,我们学习了关于prompt的两个关键原则:编写清晰具体的指令;如果适当的话,给模型一些思考时间。你还学习了迭代式prompt开发的方法,并了解了如何找到适合你应用程序的prompt的过程是非常关键的。我们还介绍了许多大型语言模......
  • 面向开发者的ChatGPT提示工程-04.摘要
     文本概括Summarizing1引言 当今世界上有太多的文本信息,几乎没有人能够拥有足够的时间去阅读所有我们想了解的东西。但令人感到欣喜的是,目前LLM在文本概括任务上展现了强大的水准,也已经有不少团队将这项功能插入了自己的软件应用中。本章节将介绍......
  • 面向开发者的ChatGPT提示工程-03. 工程迭代
     迭代式提示开发当使用LLM构建应用程序时,我从来没有在第一次尝试中就成功使用最终应用程序中所需的Prompt。但这并不重要,只要您有一个好的迭代过程来不断改进您的Prompt,那么你就能够得到一个适合任务的Prompt。我认为在提示方面,第一次成功的几率可能会高一些,但正如......
  • 微信公众号对接ChatGPT-实现基于自己知识库的机器人功能-并且可以人工接入进行回复的
    现在很多教程有介绍如何把chatGPT对接到自己的公众号上,利用公众号的自动回复接口功能,实现用户在公众号与chatGPT进行交互。而我实现的功能比上面的要高级很多 首先,用户在公众号端发送咨询消息,可以得到自动回复,并且这个回复是基于我自己的知识库回答的  然后,客服在后台可......
  • 与chatGPT讨论c#的calss 与TypeScript中的calss问题
    与chatGPT讨论c#的calss与TypeScript中的calss问题目前来说chatGPT可以说是一场革命,它为我们提供了另一种选项,当你遇到问题的时候,只能去百度但度出来的结果大多不是我们想要的结果,特别是百度当你想要问度娘时......等到的却是一大堆广告,心中不由升起无明之火,不知百度能不能也搞......
  • spring mvc 报406错误
    我也不知道真正的原因是什么,可能是返回的格式不正确吧,猜测而已,因为之前返回的是Map,这样不行,改为返回字符串String就可以了.原因是缺少jar包,详见http://jadethao.iteye.com/blog/1926525http://macrotea.iteye.com/blog/1179509......
  • 【笔记】跟吴恩达和IsaFulford学提示词工程(初级开发者入门课程)
    标签:#Prompt#LLM创建时间:2023-04-2817:05:45链接:课程(含JupyterNotebook),中文版讲师:AndrewNg,IsaFulford阅读提示这是一篇入门的教程,入门的意思是指大部分内容,可能你都已经知道了,但是知道不等于掌握,Prompt是一门实践经验主义科学,LLM是个黑盒,你只要不断去“实践”才能......