Experiment with Prompt Engineering

openai
Prompt Engineering
Published

July 15, 2023

This notebook contains study notes of the short course ChatGPT Prompt Engineering for Developers of DeepLearning.AI.

Import libs and functions (click to toggle the content)
import json
import openai

from openai_utils import chat_completion, run_and_print
Enter OpenAI API Key (click to toggle the content)
from getpass import getpass

openai.api_key = getpass()
 ········

How to write clear and specific instructions

Use delimiters

Code
text = f"""\
You should express what you want a model to do by providing instructions that are as clear and specific as you can possibly make them. This will guide the model towards the desired output, and reduce the chances of receiving irrelevant or incorrect responses. Don't confuse writing a clear prompt with writing a short prompt. In many cases, longer prompts provide more clarity and context for the model, which can lead to more detailed and relevant outputs."""
prompt = f"""\
Summarize the text delimited by triple backticks into a single sentence.
```{text}```
"""
messages = [
    {'role': 'user', 'content': prompt}
]
response, _ = chat_completion(messages)
print(response)
To guide a model towards the desired output and minimize irrelevant or incorrect responses, it is important to provide clear and specific instructions, even if they are longer and more detailed.

Ask for structured outputs

Code
prompt = f"""\
Generate a list of three made-up book titles along with their authors and genres. 
Provide them in JSON format with the following keys: 
book_id, title, author, genre.
"""
messages = [
    {'role': 'user', 'content': prompt}
]
response, _ = chat_completion(messages)
print(response)
{
  "books": [
    {
      "book_id": 1,
      "title": "The Enigma of Elysium",
      "author": "Evelyn Sinclair",
      "genre": "Mystery"
    },
    {
      "book_id": 2,
      "title": "Whispers in the Wind",
      "author": "Lucas Montgomery",
      "genre": "Fantasy"
    },
    {
      "book_id": 3,
      "title": "Shadows of Serendipity",
      "author": "Amelia Hart",
      "genre": "Romance"
    }
  ]
}

Specify conditions in prompts

Code
user_input = f"""\
Making a cup of tea is easy! First, you need to get some water boiling. While that's happening, grab a cup and put a tea bag in it. Once the water is hot enough, just pour it over the tea bag. Let it sit for a bit so the tea can steep. After a few minutes, take out the tea bag. If you like, you can add some sugar or milk to taste. And that's it! You've got yourself a delicious cup of tea to enjoy."""

prompt = f"""\
You will be provided with text delimited by triple backticks.
If it contains a sequence of instructions, re-write those instructions in the following format:

Step 1 - ...
Step 2 - ...

Step N - ...

If the text does not contain a sequence of instructions, then simply write "No steps provided."

```{user_input}```
"""
messages = [
    {'role': 'user', 'content': prompt}
]
response, _ = chat_completion(messages)
print("Completion for Text 1:")
print(response)
Completion for Text 1:
Step 1 - Get some water boiling.
Step 2 - Grab a cup and put a tea bag in it.
Step 3 - Pour the hot water over the tea bag.
Step 4 - Let the tea steep for a few minutes.
Step 5 - Take out the tea bag.
Step 6 - Add sugar or milk to taste.
Step 7 - Enjoy your cup of tea.
Code
user_input = f"""\
The sun is shining brightly today, and the birds are singing. It's a beautiful day to go for a walk in the park. The flowers are blooming, and the trees are swaying gently in the breeze. People are out and about, enjoying the lovely weather. Some are having picnics, while others are playing games or simply relaxing on the grass. It's a perfect day to spend time outdoors and appreciate the beauty of nature."""

prompt = f"""
You will be provided with text delimited by triple quotes. 
If it contains a sequence of instructions, re-write those instructions in the following format:

Step 1 - ...
Step 2 - ...
...
Step N - ...

If the text does not contain a sequence of instructions, then simply write "No steps provided."

\"\"\"{user_input}\"\"\"
"""
messages = [
    {'role': 'user', 'content': prompt}
]
response, _ = chat_completion(messages)
print("Completion for Text 2:")
print(response)
Completion for Text 2:
No steps provided.

Few-shot prompting

Code
prompt = f"""\
Your task is to answer in a consistent style.

<child>: Teach me about patience.

<grandparent>: The river that carves the deepest valley flows from a modest spring; the grandest symphony originates from a single note; the most intricate tapestry begins with a solitary thread.

<child>: Teach me about resilience.
"""
messages = [
    {'role': 'user', 'content': prompt}
]
response, _ = chat_completion(messages)
print(response)
<grandparent>: Resilience is like a mighty oak tree that withstands the strongest storms, bending but never breaking. It is the unwavering spirit that rises from the ashes, stronger and more determined than before.

Let the model “think”

Specify steps for completing a task

Code
text = f"""\
In a charming village, siblings Jack and Jill set out on a quest to fetch water from a hilltop well. As they climbed, singing joyfully, misfortune struck—Jack tripped on a stone and tumbled down the hill, with Jill following suit. Though slightly battered, the pair returned home to comforting embraces. Despite the mishap, their adventurous spirits remained undimmed, and they continued exploring with delight."""

prompt_1 = f"""\
Perform the following actions: 
1 - Summarize the following text delimited by triple backticks with 1 sentence.
2 - Translate the summary into French.
3 - List each name in the French summary.
4 - Output a json object that contains the following keys: french_summary, num_names.

Separate your answers with line breaks.

Text:
```{text}```
"""
messages = [
    {'role': 'user', 'content': prompt_1}
]
response, _ = chat_completion(messages)
print("Completion for prompt 1:")
print(response)
Completion for prompt 1:
1 - Jack and Jill, siblings, go on a quest to fetch water from a well on a hill, but they both fall down the hill after Jack trips on a stone, yet they return home and remain adventurous.
2 - Jack et Jill, frère et sœur, partent en quête d'eau d'un puits situé au sommet d'une colline, mais ils tombent tous les deux après que Jack trébuche sur une pierre, cependant ils rentrent chez eux et restent aventureux.
3 - Jack, Jill
4 - {"french_summary": "Jack et Jill, frère et sœur, partent en quête d'eau d'un puits situé au sommet d'une colline, mais ils tombent tous les deux après que Jack trébuche sur une pierre, cependant ils rentrent chez eux et restent aventureux.", "num_names": 2}

specify output format

Code
prompt_2 = f"""\
Your task is to perform the following actions:
1 - Summarize the following text delimited by <> with 1 sentence.
2 - Translate the summary into French.
3 - List each name in the French summary.
4 - Output a json object that contains the following keys: french_summary, num_names.

Use the following format:
Text: <text to summarize>
Summary: <summary>
Translation: <summary translation>
Names: <list of names in French summary>
Output JSON: <json with summary and num_names>

Text: <{text}>
"""
messages = [
    {'role': 'user', 'content': prompt_2}
]
response, _ = chat_completion(messages)
print("\nCompletion for prompt 2:")
print(response)
Completion for prompt 2:
Summary: Jack and Jill, siblings from a charming village, go on a quest to fetch water from a hilltop well but encounter misfortune along the way. 
Translation: Jack et Jill, frère et sœur d'un charmant village, partent en quête d'eau d'un puits au sommet d'une colline mais rencontrent des malheurs en chemin.
Names: Jack, Jill
Output JSON: {"french_summary": "Jack et Jill, frère et sœur d'un charmant village, partent en quête d'eau d'un puits au sommet d'une colline mais rencontrent des malheurs en chemin.", "num_names": 2}

Ask the model to work out its own solution before reaching a conclusion

Code
prompt = f"""
Determine if the student's solution is correct or not.

Question:
I'm building a solar power installation and I need help working out the financials.
- Land costs $100 / square foot
- I can buy solar panels for $250 / square foot
- I negotiated a contract for maintenance that will cost me a flat $100k per year, and an additional $10 / square foot

What is the total cost for the first year of operations as a function of the number of square feet.

Student's Solution:
Let x be the size of the installation in square feet.
Costs:
1. Land cost: 100x
2. Solar panel cost: 250x
3. Maintenance cost: 100,000 + 100x
Total cost: 100x + 250x + 100,000 + 100x = 450x + 100,000
"""
messages = [
    {'role': 'user', 'content': prompt}
]
response, _ = chat_completion(messages)
print(response)
The student's solution is correct. The total cost for the first year of operations is indeed 450x + 100,000.

The model’s response is wrong because the student’s solution is not correct. To fix it, ask the model to figure out its own solution.

Code
prompt = f"""
Your task is to determine if the student's solution is correct or not.
To solve the problem do the following:
- First, work out your own solution to the problem. 
- Then compare your solution to the student's solution and evaluate if the student's solution is correct or not. 
Don't decide if the student's solution is correct until you have done the problem yourself.

Use the following format:
Question:
```
question here
```
Student's solution:
```
student's solution here
```
Actual solution:
```
steps to work out the solution and your solution here
```
Is the student's solution the same as actual solution just calculated:
```
yes or no
```
Student grade:
```
correct or incorrect
```

Question:
```
I'm building a solar power installation and I need help working out the financials. 
- Land costs $100 / square foot
- I can buy solar panels for $250 / square foot
- I negotiated a contract for maintenance that will cost me a flat $100k per year, and an additional $10 / square foot

What is the total cost for the first year of operations as a function of the number of square feet.
``` 
Student's solution:
```
Let x be the size of the installation in square feet.
Costs:
1. Land cost: 100x
2. Solar panel cost: 250x
3. Maintenance cost: 100,000 + 100x
Total cost: 100x + 250x + 100,000 + 100x = 450x + 100,000
```
Actual solution:
"""

messages = [
    {'role': 'user', 'content': prompt}
]
response, _ = chat_completion(messages)
print(response)
To calculate the total cost for the first year of operations, we need to add up the costs of land, solar panels, and maintenance.

1. Land cost: $100 / square foot
The cost of land is $100 multiplied by the number of square feet.

2. Solar panel cost: $250 / square foot
The cost of solar panels is $250 multiplied by the number of square feet.

3. Maintenance cost: $100,000 + $10 / square foot
The maintenance cost is a flat fee of $100,000 per year, plus $10 multiplied by the number of square feet.

Total cost = Land cost + Solar panel cost + Maintenance cost

Total cost = ($100 / square foot) * x + ($250 / square foot) * x + ($100,000 + $10 / square foot) * x

Simplifying the expression:

Total cost = $100x + $250x + ($100,000 + $10x)

Total cost = $350x + $100,000

Is the student's solution the same as the actual solution just calculated:
No

An example of iterative prompt development

product fact sheet (click to toggle the content)
fact_sheet_chair = """
OVERVIEW
- Part of a beautiful family of mid-century inspired office furniture, 
including filing cabinets, desks, bookcases, meeting tables, and more.
- Several options of shell color and base finishes.
- Available with plastic back and front upholstery (SWC-100) 
or full upholstery (SWC-110) in 10 fabric and 6 leather options.
- Base finish options are: stainless steel, matte black, 
gloss white, or chrome.
- Chair is available with or without armrests.
- Suitable for home or business settings.
- Qualified for contract use.

CONSTRUCTION
- 5-wheel plastic coated aluminum base.
- Pneumatic chair adjust for easy raise/lower action.

DIMENSIONS
- WIDTH 53 CM | 20.87”
- DEPTH 51 CM | 20.08”
- HEIGHT 80 CM | 31.50”
- SEAT HEIGHT 44 CM | 17.32”
- SEAT DEPTH 41 CM | 16.14”

OPTIONS
- Soft or hard-floor caster options.
- Two choices of seat foam densities: 
 medium (1.8 lb/ft3) or high (2.8 lb/ft3)
- Armless or 8 position PU armrests 

MATERIALS
SHELL BASE GLIDER
- Cast Aluminum with modified nylon PA6/PA66 coating.
- Shell thickness: 10 mm.
SEAT
- HD36 foam

COUNTRY OF ORIGIN
- Italy
"""
Code
prompt = f"""
Your task is to help a marketing team create a 
description for a retail website of a product based 
on a technical fact sheet.

Write a product description based on the information 
provided in the technical specifications delimited by 
triple backticks.

Technical specifications: ```{fact_sheet_chair}```
"""

run_and_print(prompt)
Introducing our stunning mid-century inspired office chair, the perfect addition to any home or business setting. This chair is part of a beautiful family of office furniture, including filing cabinets, desks, bookcases, meeting tables, and more, all designed with a timeless mid-century aesthetic.

One of the standout features of this chair is the variety of customization options available. You can choose from several shell colors and base finishes to perfectly match your existing decor. The chair is available with either plastic back and front upholstery or full upholstery in a range of 10 fabric and 6 leather options, allowing you to create a look that is uniquely yours.

The chair is also available with or without armrests, giving you the flexibility to choose the option that best suits your needs. The base finish options include stainless steel, matte black, gloss white, or chrome, ensuring that you can find the perfect match for your space.

In terms of construction, this chair is built to last. It features a 5-wheel plastic coated aluminum base, providing stability and mobility. The pneumatic chair adjust allows for easy raise and lower action, ensuring optimal comfort throughout the day.

When it comes to dimensions, this chair is designed with both style and comfort in mind. With a width of 53 cm (20.87"), depth of 51 cm (20.08"), and height of 80 cm (31.50"), it offers ample space without overwhelming your space. The seat height is 44 cm (17.32") and the seat depth is 41 cm (16.14"), providing a comfortable seating experience for users of all heights.

We understand that every space is unique, which is why we offer a range of options to further customize your chair. You can choose between soft or hard-floor caster options, ensuring that your chair glides smoothly across any surface. Additionally, you have the choice between two seat foam densities: medium (1.8 lb/ft3) or high (2.8 lb/ft3), allowing you to select the level of support that suits your preferences. The chair is also available with armless design or 8 position PU armrests, providing additional comfort and versatility.

When it comes to materials, this chair is crafted with the utmost attention to quality. The shell base glider is made from cast aluminum with a modified nylon PA6/PA66 coating, ensuring durability and longevity. The shell thickness is 10 mm, providing a sturdy and reliable structure. The seat is made from HD36 foam, offering a comfortable and

The text is too long, limit the length of response

Code
prompt = f"""
Your task is to help a marketing team create a 
description for a retail website of a product based 
on a technical fact sheet.

Write a product description based on the information 
provided in the technical specifications delimited by 
triple backticks.

Use at most 50 words.

Technical specifications: ```{fact_sheet_chair}```
"""

run_and_print(prompt)
Introducing our mid-century inspired office chair, part of a stunning furniture collection. With various color and finish options, choose between plastic or full upholstery in fabric or leather. The chair features a durable aluminum base with 5 wheels and pneumatic height adjustment. Perfect for home or business use. Made in Italy.

Try to ask the model to focus on aspects for intended audience

Code
prompt = f"""
Your task is to help a marketing team create a 
description for a retail website of a product based 
on a technical fact sheet.

Write a product description based on the information 
provided in the technical specifications delimited by 
triple backticks.

The description is intended for furniture retailers, 
so should be technical in nature and focus on the 
materials the product is constructed from.

Use at most 50 words.

Technical specifications: ```{fact_sheet_chair}```
"""

run_and_print(prompt)
Introducing our mid-century inspired office chair, part of a beautiful furniture collection. With various shell colors and base finishes, it offers versatility for any setting. Choose between plastic or full upholstery in a range of fabric and leather options. The chair features a durable aluminum base with 5-wheel design and pneumatic chair adjustment. Made in Italy.
Code
prompt = f"""
Your task is to help a marketing team create a 
description for a retail website of a product based 
on a technical fact sheet.

Write a product description based on the information 
provided in the technical specifications delimited by 
triple backticks.

The description is intended for furniture retailers, 
so should be technical in nature and focus on the 
materials the product is constructed from.

At the end of the description, include every 7-character 
Product ID in the technical specification.

Use at most 50 words.

Technical specifications: ```{fact_sheet_chair}```
"""

run_and_print(prompt)
Introducing our mid-century inspired office chair, part of a beautiful family of furniture. With various shell colors and base finishes, this chair offers versatility and style. Choose between plastic or full upholstery in a range of fabric and leather options. The chair features a 5-wheel plastic coated aluminum base and a pneumatic chair adjust for easy height adjustment. Available with or without armrests, this chair is suitable for both home and business settings. Made with high-quality materials, including a cast aluminum shell and HD36 foam seat, this chair is built to last. Product ID: SWC-100, SWC-110.

Ask the model to respond using HTML format with a table

Code
prompt = f"""
Your task is to help a marketing team create a 
description for a retail website of a product based 
on a technical fact sheet.

Write a product description based on the information 
provided in the technical specifications delimited by 
triple backticks.

The description is intended for furniture retailers, 
so should be technical in nature and focus on the 
materials the product is constructed from.

After the description, include a table that gives the 
product's dimensions. The table should have two columns. 
In the first column include the name of the dimension. 
In the second column include the measurements in inches only.
Give the table the title "Product Dimensions".

After the table, list all 7-character Product IDs from the technical specification.

Technical specifications: ```{fact_sheet_chair}```

Format everything as HTML that can be used in a website. 
Place the table after the description.
"""

messages = [
    {'role': 'user', 'content': prompt}
]
response, _ = chat_completion(messages, max_tokens=800)
print(response)
<!DOCTYPE html>
<html>
<head>
  <title>Product Description</title>
</head>
<body>
  <h1>Product Description</h1>
  <p>Introducing our latest addition to the mid-century inspired office furniture collection - the SWC Chair. This beautifully designed chair is perfect for both home and business settings, offering comfort and style in one package. With its sleek and modern look, it is sure to enhance any workspace.</p>
  <p>The SWC Chair is constructed with high-quality materials to ensure durability and longevity. The shell is made of cast aluminum with a modified nylon PA6/PA66 coating, providing strength and stability. The seat is filled with HD36 foam, offering exceptional comfort for extended periods of sitting.</p>
  <p>With a 5-wheel plastic coated aluminum base, the SWC Chair provides smooth mobility and stability. The pneumatic chair adjustment allows for easy raise and lower action, ensuring the perfect height for any user.</p>
  
  <h2>Product Dimensions</h2>
  <table>
    <tr>
      <th>Dimension</th>
      <th>Measurement (inches)</th>
    </tr>
    <tr>
      <td>Width</td>
      <td>20.87"</td>
    </tr>
    <tr>
      <td>Depth</td>
      <td>20.08"</td>
    </tr>
    <tr>
      <td>Height</td>
      <td>31.50"</td>
    </tr>
    <tr>
      <td>Seat Height</td>
      <td>17.32"</td>
    </tr>
    <tr>
      <td>Seat Depth</td>
      <td>16.14"</td>
    </tr>
  </table>
  
  <h2>Product IDs</h2>
  <ul>
    <li>SWC-100</li>
    <li>SWC-110</li>
  </ul>
</body>
</html>
Code
from IPython.display import display, HTML

display(HTML(response))
Product Description

Product Description

Introducing our latest addition to the mid-century inspired office furniture collection - the SWC Chair. This beautifully designed chair is perfect for both home and business settings, offering comfort and style in one package. With its sleek and modern look, it is sure to enhance any workspace.

The SWC Chair is constructed with high-quality materials to ensure durability and longevity. The shell is made of cast aluminum with a modified nylon PA6/PA66 coating, providing strength and stability. The seat is filled with HD36 foam, offering exceptional comfort for extended periods of sitting.

With a 5-wheel plastic coated aluminum base, the SWC Chair provides smooth mobility and stability. The pneumatic chair adjustment allows for easy raise and lower action, ensuring the perfect height for any user.

Product Dimensions

Dimension Measurement (inches)
Width 20.87"
Depth 20.08"
Height 31.50"
Seat Height 17.32"
Seat Depth 16.14"

Product IDs

  • SWC-100
  • SWC-110

Summarizing texts

text to be summarized (click to toggle the content)
prod_review = "Got this panda plush toy for my daughter's birthday, who loves it and takes it everywhere. It's soft and super cute, and its face has a friendly look. 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 her."

specify limit of generated response

Code
prompt = f"""
Your task is to generate a short summary of a product review from an ecommerce site. 

Summarize the review below, delimited by triple backticks, in at most 30 words. 

Review: ```{prod_review}```
"""
messages = [
    {'role': 'user', 'content': prompt}
]
response, usages = chat_completion(messages)
print(response)
This panda plush toy is loved by the reviewer's daughter, who takes it everywhere. It is soft, cute, and has a friendly face. However, it is considered small for the price.
Code
len(response.split())
31
Code
usages
{'prompt_tokens': 135, 'completion_tokens': 39, 'total_tokens': 174}

specify a focus for the model to summarize with

focusing on shipping and delivery

Code
prompt = f"""
Your task is to generate a short summary of a product review from an ecommerce site to give feedback to the Shipping deparmtment.

Summarize the review below, delimited by triple backticks, in at most 30 words, and focusing on any aspects that mention shipping and delivery of the product. 

Review: ```{prod_review}```
"""

run_and_print(prompt)
The customer loves the panda plush toy but feels it is small for the price. They mention that it arrived a day earlier than expected.

focusing on price and value

Code
prompt = f"""
Your task is to generate a short summary of a product review from an ecommerce site to give feedback to the pricing deparmtment, responsible for determining the price of the product.

Summarize the review below, delimited by triple backticks, in at most 30 words, and focusing on any aspects that are relevant to the price and perceived value.

Review: ```{prod_review}```
"""

run_and_print(prompt)
The panda plush toy is loved by the daughter, but the reviewer feels it is overpriced as there might be larger options available for the same price.

extract information

Code
prompt = f"""
Your task is to extract relevant information from a product review from an ecommerce site to give feedback to the Shipping department.

From the review below, delimited by triple quotes extract the information relevant to shipping and delivery.

Your answer should only include words from the original review.

Review: ```{prod_review}```
"""

response = get_completion(prompt)
print(response)
The relevant information about shipping and delivery from the review is: "It arrived a day earlier than expected."

Inferring from texts

Code
text = """Needed a nice lamp for my bedroom, and this one had additional storage and not too high of a price point. Got it fast.  The string to our lamp broke during the transit and the company happily sent over a new one. Came within a few days as well. It was easy to put together.  I had a missing part, so I contacted their support and they very quickly got me the missing piece! Lumina seems to me to be a great company that cares about their customers and products!!"""

prompt = f"""
Identify the following items from the review text: 
- Sentiment (positive or negative)
- Identify up to five emotions. List them using low-case words.
- Is the reviewer expressing anger? (true or false)
- Item purchased by reviewer
- Company that made the item

The review is delimited with triple backticks.
Format your response as a JSON object with:
"Sentiment", "Emotions", "Anger", "Item" and "Brand" as the keys.
If the information isn't present, use "unknown" as the value.
Make your response as short as possible.
Format the Anger value as a boolean.

Review text: '''{text}'''
"""

run_and_print(prompt)
{
  "Sentiment": "positive",
  "Emotions": ["happy", "satisfied", "grateful", "impressed", "content"],
  "Anger": false,
  "Item": "lamp",
  "Brand": "Lumina"
}

Inferring topics

story text (click to toggle the content)
story = """
In a recent survey conducted by the government, 
public sector employees were asked to rate their level 
of satisfaction with the department they work at. 
The results revealed that NASA was the most popular 
department with a satisfaction rating of 95%.

One NASA employee, John Smith, commented on the findings, 
stating, "I'm not surprised that NASA came out on top. 
It's a great place to work with amazing people and 
incredible opportunities. I'm proud to be a part of 
such an innovative organization."

The results were also welcomed by NASA's management team, 
with Director Tom Johnson stating, "We are thrilled to 
hear that our employees are satisfied with their work at NASA. 
We have a talented and dedicated team who work tirelessly 
to achieve our goals, and it's fantastic to see that their 
hard work is paying off."

The survey also revealed that the 
Social Security Administration had the lowest satisfaction 
rating, with only 45% of employees indicating they were 
satisfied with their job. The government has pledged to 
address the concerns raised by employees in the survey and 
work towards improving job satisfaction across all departments.
"""
Code
prompt = f"""
Determine five topics that are being discussed in the following text, which is delimited by triple backticks.

Make each item one or two words long. 

Format your response as a list of items separated by commas.

Text sample: '''{story}'''
"""

messages = [
    {'role': 'user', 'content': prompt}
]
response, _ = chat_completion(messages)
print(response)
1. Government survey
2. Department satisfaction rating
3. NASA
4. Social Security Administration
5. Job satisfaction improvement
Code
response = response.split(sep='\n')
response
['1. Government survey',
 '2. Department satisfaction rating',
 '3. NASA',
 '4. Social Security Administration',
 '5. Job satisfaction improvement']
Code
topic_list = ["nasa", "local government", "engineering",
              "employee satisfaction", "federal government"]
prompt = f"""
Determine whether each item in the following list of topics is a topic in the text below, which is delimited with triple backticks.

Give your answer as list with 0 or 1 for each topic.

List of topics: {", ".join(topic_list)}

Text sample: '''{story}'''
"""

run_and_print(prompt)
[1, 0, 0, 1, 1]

Tone transformation

Code
prompt = """
Translate the following from slang to a business letter: 
'Dude, This is Joe, check out this spec on this standing lamp.'
"""

run_and_print(prompt)
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 contains important details about the standing lamp in question. 

Thank you for your time and consideration. I look forward to hearing from you soon.

Sincerely,
Joe

Format conversion

Describe the input and output formats in the prompt.

Code
employees = {
    "Employees" : [
        {"name":"Jane", "email":"janedoe@gmail.com", "cell phone": "(416)123-3456"},
        {"name":"Bob", "email":"bob1111@gmail.com", "cell phone": "(416)987-4321"},
        {"name":"John", "email":"john222@gmail.com", "cell phone": "(416)555-6666"}
    ]
}
prompt = f"""
Translate the following python dictionary from JSON to an HTML table with column headers and title:
{employees}
"""
messages = [
    {'role': 'user', 'content': prompt}
]
response, _ = chat_completion(messages)
Code
from IPython.display import display, HTML

display(HTML(response))

Employees

Name Email Cell Phone
Jane janedoe@gmail.com (416)123-3456
Bob bob1111@gmail.com (416)987-4321
John john222@gmail.com (416)555-6666

Spell check and grammar check

For proofreading, instruct the model to “proofread” or “proofread and correct”

Code
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"""Proofread 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}```"""
    run_and_print(prompt)
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
Code
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}```"
messages = [
    {'role': 'user', 'content': prompt}
]
response, _ = chat_completion(messages)
Code
from redlines import Redlines
from IPython.display import display, Markdown

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

Got this for my daughter for her 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 Additionally, it’s a bit small for what I paid for it though. it. I think believe there might be other options that are bigger for the same price. It 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.

Code
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}```
"""

messages = [
    {'role': 'user', 'content': prompt}
]
response, _ = chat_completion(messages)

display(Markdown(response))

Review of a Panda Plush Toy: A Perfect Gift for All Ages

I purchased this adorable panda plush toy as a birthday gift for my daughter, who has a penchant for sneaking into my room and “borrowing” my belongings. However, let me assure you that pandas are not just for kids; even adults like me can’t resist their charm.

From the moment my daughter unwrapped this gift, she has been inseparable from her new companion. The plush toy’s irresistibly soft and cuddly texture makes it the perfect companion for any adventure. Its cuteness factor is off the charts, and it never fails to bring a smile to my daughter’s face.

However, I must mention that there is a slight flaw in the design. One of the panda’s ears is positioned slightly lower than the other, which appears to be unintentional. While this asymmetry does not detract from the overall appeal, it is worth noting for those seeking perfection.

In terms of size, I must admit that I expected a slightly larger plush toy considering its price. It would be beneficial for potential buyers to explore alternative options that offer a larger size for the same price. Nevertheless, the quality and craftsmanship of this panda plush toy are undeniable.

To my surprise, the delivery of this product exceeded my expectations. It arrived a day earlier than the estimated delivery date, allowing me to indulge in some playtime with the panda before presenting it to my daughter. This unexpected bonus added to the overall excitement and anticipation surrounding the gift.

In conclusion, this panda plush toy is a delightful gift that transcends age boundaries. Its softness, cuteness, and undeniable charm make it a perfect companion for anyone. While there may be other options available in terms of size, the quality and timely delivery of this product make it a worthwhile purchase. So, whether you’re a child or a child at heart, this panda plush toy is sure to bring joy and warmth to your life.