Openai+Coursera: ChatGPT Prompt Engineering (4)

I want to share with you the recently learned Coursera and openai jointly created the ChatGPT Prompt Engineering online course. The following are the first two blogs I wrote about the course:

  1. ChatGPT Prompt Engineering (1)
  2. ChatGPT Prompt Engineering (2)
  3. ChatGPT Prompt Engineering (3)

Today we come to study the third part: transformation (Transforming).

Transforming

Today we’ll explore how to use large language models for text transformation tasks such as language translation, spelling and grammar checking, tone adjustment, and formatting.

First of all, we need to set the main code to access ChatGPT through API:

import openai
 
openai.api_key='YOUR_OPENAI_API_KEY'

To prevent the Rate limits problem, we need to install a library backoff that provides function decorators for backoff and retry

# pip install backoff
import backoff

@backoff.on_exception(backoff.expo, openai.error.RateLimitError)
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"]

Translate

ChatGPT is a large-scale language model trained using resources in multiple languages. This enables the model to do multilingual translation work. Here are some examples of how to use this feature.

Here’s an example of translating from English to Spanish:

#Translate English to Spanish

prompt = f"""
Translate the following English text to Spanish: \
```Hi, I would like to order a blender```
"""
response = get_completion(prompt)
print(response)

Here’s how to let ChatGP identify which language the text belongs to:

prompt = f"""
Tell me which language this is:
```Combien co?te le lampadaire?```
"""
response = get_completion(prompt)
print(response)

Translate text into French, Spanish and English:

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)

Translate text into formal and informal Spanish:

prompt = f"""
Translate the following text to Spanish in both the \
formal and informal forms:
'Would you like to order a pillow?'
"""
response = get_completion(prompt)
print(response)

Universal Translator

Imagine if you were the head of the IT department of a large multinational e-commerce company. Customers are sending you messages about IT issues in their respective native languages. Your employees come from all over the world, and they only speak their native language. At this point you need a universal translator!

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" # My screen is flashing
]

Next, we will translate the above customer questions in different languages into English and Chinese:

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"""
    Translate the following text to English \
    and Chinese: ```{issue}```
    """
    response = get_completion(prompt)
    print(response, "\
")

Intonation shift

ChatGPT can output content with different tones according to different audiences. Below is a dialogue in English slang that we asked ChatGPT to convert into a business letter intonation.

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)

Format conversion

ChatGPT can convert between different formats. The prompt should describe the input and output format. Next we will convert a python dictionary from JSON format to HTML format:

data_json = { "resturant employees" :[
    {"name":"Shyam", "email":"[email protected]"},
    {"name":"Bob", "email":"[email protected]"},
    {"name":"Jai", "email":"[email protected]"}
]}

prompt = f"""
Translate the following python dictionary from JSON to HTML \
table with column headers and title: {data_json}
"""
response = get_completion(prompt)
print(response)

Next we want to display this HTML page:

from IPython.display import display, Markdown, Latex, HTML, JSON
display(HTML(response))

Spell Check/Grammar Check

Here we have some examples of common grammar and spelling problems and large language model (LLM) responses.

To signal to the LLM that you want it to proofread your text, you can instruct the model to “proofread” or “proofread and correct”. There are grammatical errors or spelling mistakes in the following paragraphs of text. We need ChatGPT to check and correct errors in the text.

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"""Proof read 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)

Let’s try to let ChatGPT correct Chinese sentences to see if it can find the error:

text = [
  "Our company is a professional computer repair company with good service attitude and reasonable price",
  "They learn a lot about history, math and science in school.",
  "We went to a new restaurant and it was delicious and the waiters were friendly.",
  "You have to finish your homework first and go out to play!",
  "The sound of forest waves fluctuating with the wind in the green mountains and green mountains is like a symphony played by nature.",
  "Qixi is just a festival for the Cowherd and the Weaver Girl, and has nothing to do with mere mortals.",
  "There are two very lucky things in my life, one is that I met you, and the other is that I will spend the rest of my life with you."
]
for t in text:
    prompt = f"""Check the following article for typos or grammatical errors, and rewrite the sentence if there are errors.
    You have to output 2 sentences when replying, one is the original text and the other is the modified text, if no errors are found, say "no errors found".

    Please output in the following format:
    Original Text: Here is the original text
    Modified text: here is the modified text
    
    Original text:{t}"""
    response = get_completion(prompt)
    print(response)
    print()

In general, ChatGPT is quite familiar with Chinese typos, and the success rate of correcting some obvious typos can reach 100%, but for the last sentence, we found that sometimes ChatGPT’s reply to the last sentence is: no Find the bug. You can try to see how much the recognition rate of ChatGPT is for Chinese typos.

Next, we provide ChatGPT with an English essay and let it correct the essay:

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)

Since the content of the short article is relatively long, we use a proofreading tool to see what modifications ChatGPT has made:

from redlines import Redlines

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

Here we can clearly find the modifications made by ChatGPT to the original text.

Next, let ChatGPT modify the above original text into an APA-style article (APA style is the writing style and format of academic documents such as academic journal articles and books)

prompt = f"""
proof read 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))

Summary

Tonight we learned how to make ChatGPT realize multilingual translation function, language recognition, typo/grammar check, tone conversion and other functions. I hope today’s content can be helpful to everyone!

If you think my article is helpful to you, please buy me a cup of coffee!