提示工程(5):转换(Transforming)能力

LLM非常擅长将输入转换成不同的格式,例如多语种文本翻译、拼写及语法纠正、语气调整、格式转换等。以前要用正则表达式,或者调用一些转换函数来解决的问题,现在用一个大语言模型和几个提示就可以简单实现了。

import openai
openai.api_key="openai 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"]

一、翻译任务

将一段英语翻译成西班牙语

prompt =f"""
Translate the following English text to Spanish:
'''  Hi, I would like to order a blender. '''
"""

response =get_completion(prompt)
print(response)
Hola, me gustaría ordenar una licuadora.

翻译成法语和海盗英语。

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)
French: "Je veux commander un ballon de basket."
Spanish: "Quiero ordenar una pelota de baloncesto."
English Pirate: "I be wantin' to order a basketball, matey."

翻译成中文,分别为正式和非正式的语气。

prompt = f"""
请将以下文本翻译成中文,分别展示成正式与非正式两种语气: 
'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.",
    "Mi monitor tiene pixeles que no se iluminan.",
    "Il mio mouse non funziona",
    "Mój klawisz Ctrl jest zepsuty",
    "我的屏幕在闪烁"
]
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=========================================\n")
原始消息 (法语): La performance du système est plus lente que d'habitude. 

中文翻译:系统性能比平时慢。
英文翻译:The system performance is slower than usual. 
=========================================

原始消息 (西班牙语): Mi monitor tiene pixeles que no se iluminan. 

中文翻译:我的显示器有一些像素点不亮。
英文翻译:My monitor has pixels that do not 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. 
=========================================

二、语气调整

我想让大模型给我写封正式的邮箱。请见下例。

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)
Dear Sir/Madam,

I hope this letter finds you well. My name is Joe, and I am writing to bring your attention to a specification document regarding a standing lamp. 

I kindly request that you take a moment to review the attached spec, as it provides detailed information about the features and qualities of the aforementioned lamp. 

Thank you for your time and consideration. I look forward to discussing this matter further with you.

Yours sincerely,
Joe

三、格式转换

我想把一JSON转换成HTML的表格。

data_json = { "resturant employees" :[
    {"name": "Shyam", "email": "shyamjaiswalegmail.com"},
    {"name": "Bob" , "email" : "Jaibob32@gmail.com"},
    {"name": "Jai", "email": "jai87@gmail.com"} 
]}

prompt = f"""
Transalte the following python dictionary from JSON to a HTML table with column headers and title: {data_json}
"""

response = get_completion (prompt)
print (response)
<!DOCTYPE html>
<html>
<head>
<style>
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}

tr:nth-child(even) {
  background-color: #dddddd;
}
</style>
</head>
<body>

<h2>Restaurant Employees</h2>

<table>
  <tr>
    <th>Name</th>
    <th>Email</th>
  </tr>
  <tr>
    <td>Shyam</td>
    <td>shyamjaiswalegmail.com</td>
  </tr>
  <tr>
    <td>Bob</td>
    <td>Jaibob32@gmail.com</td>
  </tr>
  <tr>
    <td>Jai</td>
    <td>jai87@gmail.com</td>
  </tr>
</table>

</body>
</html>

展示表格如下:

from IPython.display import display, HTML
display(HTML(response))

table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}

td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}

tr:nth-child(even) {
background-color: #dddddd;
}

Restaurant Employees

Name Email
Shyam shyamjaiswalegmail.com
Bob Jaibob32@gmail.com
Jai jai87@gmail.com

四、语法和拼写检查

下面是对每句英文进行语法检查。如果有错误则直接修正,如果没有则显示“No errors found.”

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"""Proffread and correct the following text
    and rewrite the correct version. If you don't find 
    any errors, just say "No errors found": 
    '''{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?"
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 takir 
mine from my room. Yes, adults also like pandas too. 
She ti it everywhere with her, and it's super soft and cute. One of 
ears is a bit lower than the other, and I don't think that 
we designed to be asymmetrical. It's a bit small for what I pair 
though. I think there might be other options that are bigger 
the same price. It arrived a day earlier than expected, so 
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)
Got this for my daughter for her 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. One of the ears is a bit lower than the other, and I don't think it was designed to be asymmetrical. It's a bit small for what I paid 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.

有哪些地方纠错了,我们希望看到痕迹。请见下面示例。
我们先安装redlines包,并import markdown包。

from redlines import Redlines
from IPython.display import Markdown  # Import Markdown from IPython.display

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

Got this for my daughter for her birthday cuz because she keeps takir ¶ taking mine from my room. Yes, adults also like pandas too. She ti 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 ¶ we it was designed to be asymmetrical. It’s a bit small for what I pair ¶ paid 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.

五、风格变换

上面那段文字,我们希望采用APA(American Psychological Association)风格。同时,也综合应用了语法纠错,改写等方法,最后输出预期的结果。

prompt = f"""
proofread and correct this review. Make it more compelling.
Ensure it follows APA style guide and targets an advanced reader.
Output in markdown format.

Text: '''{text}'''
"""
response = get_completion(prompt)
display(Markdown(response))

Review of a Panda Plush Toy

I purchased this adorable panda plush toy as a birthday gift for my daughter, who has a habit of taking my belongings from my room. However, it turns out that adults can also appreciate the charm of pandas.

My daughter absolutely adores this toy and takes it everywhere with her. The plush is incredibly soft and undeniably cute. However, I did notice a minor flaw in its design – one of the ears is slightly lower than the other, which seems to be unintentional.

While the quality of the plush is exceptional, I found it to be a bit smaller than I anticipated for its price. I believe there might be other options available at the same price point that offer a larger size.

On a positive note, the delivery of the toy was prompt, arriving a day earlier than expected. This allowed me to thoroughly inspect and even play with the toy myself before presenting it to my daughter.

In conclusion, despite the minor design flaw and smaller size, this panda plush toy is undeniably adorable and made of high-quality materials. It would make a delightful gift for any panda enthusiast, regardless of age. However, for those seeking a larger plush toy, it may be worth exploring other options within the same price range.

以上是关于大模型转换(Transforming)的应用。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注