歡迎來到ChatGPT 開發人員提示工程課程(ChatGPT Prompt Engineering for Developers)!本課程將教您如何通過OpenAI API有效地利用大型語言模型(LLM)來創建強大的應用程序。
本課程由OpenAI 的Isa Fulford和 DeepLearning.AI 的Andrew Ng主講,深入了解 LLM 的運作方式,提供即時工程的最佳實踐,并演示 LLM API 在各種應用程序中的使用。
在本課程筆記本中,我們將探討如何使用大型語言模型進行文本轉換任務,例如語言翻譯、拼寫和語法檢查、語氣調整以及格式轉換。
設置
import openai
import osfrom 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))
Name | |
---|---|
Shyam | shyamjaiswal@gmail.com |
Bob | bob32@gmail.com |
Jai | jai87@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.