Post

Prompt Engineering

Prompting Principles

  • Principle 1: Write clear and specific instructions
  • Principle 2: Give the model time to “think”

Summarize

Use delimiters to clearly indicate distinct parts of the input

1
2
3
4
5
6
7
# Delimiters can be anything like:  ```, """, < >, <tag> </tag>, :
"""
Summarize the text delimited by triple backticks \
into a single sentence.
```{text}```
"""

Ask for a structured output

1
2
3
4
5
6
"""
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.
"""

Ask the model to check whether conditions are satisfied

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
"""
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.\"

\"\"\"{text_1}\"\"\"
"""

“Few-shot” prompting

1
2
3
4
5
6
7
8
9
10
11
12
"""
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.
"""

Specify the steps required to complete a task

1
2
3
4
5
6
7
8
9
10
11
12
13
14
"""
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}```
"""

Ask for output in a specified format

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
"""
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 summary>
Output JSON: <json with summary and num_names>

Text: <{text}>
"""

Instruct the model to work out its own solution before rushing to a conclusion

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
"""
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
"""

"""
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 including the final total.
- 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:
"""

Iterate

Generate a marketing product description from a product fact sheet

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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
"""

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

The text is too long

1
2
3
4
5
6
7
8
9
10
11
12
13
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}```
"""

Text focuses on the wrong details

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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}```
"""
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}```
"""

Description needs a table of dimensions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
"""
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.

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'.

Format everything as HTML that can be used in a website.
Place the description in a <div> element.

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

# Load Python libraries to view HTML
from IPython.display import display, HTML
display(HTML(response))

Text to summarize

1
2
3
4
5
6
7
8
9
10
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.
"""

Summarize with a word/sentence/character limit

1
2
3
4
5
6
7
8
9
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}```
"""

Summarize with a focus on shipping and delivery

1
2
3
4
5
6
7
8
9
10
11
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}
"""

Summarize with a focus on price and value

1
2
3
4
5
6
7
8
9
10
11
12
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}
"""

Summaries include topics that are not related to the topic of focus.

Try “extract” instead of “summarize”

1
2
3
4
5
6
7
8
9
10
11
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. Limit to 30 words.
​
Review: ```{prod_review}```
"""

Summarize multiple product reviews

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
review_1 = prod_review

# review for a standing lamp
review_2 = """
Needed a nice lamp for my bedroom, and this one \
had additional storage and not too high of a price \
point. Got it fast - arrived in 2 days. The string \
to the 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. Then I had a \
missing part, so I contacted their support and they \
very quickly got me the missing piece! Seems to me \
to be a great company that cares about their customers \
and products.
"""

# review for an electric toothbrush
review_3 = """
My dental hygienist recommended an electric toothbrush, \
which is why I got this. The battery life seems to be \
pretty impressive so far. After initial charging and \
leaving the charger plugged in for the first week to \
condition the battery, I've unplugged the charger and \
been using it for twice daily brushing for the last \
3 weeks all on the same charge. But the toothbrush head \
is too small. I’ve seen baby toothbrushes bigger than \
this one. I wish the head was bigger with different \
length bristles to get between teeth better because \
this one doesn’t.  Overall if you can get this one \
around the $50 mark, it's a good deal. The manufactuer's \
replacements heads are pretty expensive, but you can \
get generic ones that're more reasonably priced. This \
toothbrush makes me feel like I've been to the dentist \
every day. My teeth feel sparkly clean!
"""

# review for a blender
review_4 = """
So, they still had the 17 piece system on seasonal \
sale for around $49 in the month of November, about \
half off, but for some reason (call it price gouging) \
around the second week of December the prices all went \
up to about anywhere from between $70-$89 for the same \
system. And the 11 piece system went up around $10 or \
so in price also from the earlier sale price of $29. \
So it looks okay, but if you look at the base, the part \
where the blade locks into place doesn’t look as good \
as in previous editions from a few years ago, but I \
plan to be very gentle with it (example, I crush \
very hard items like beans, ice, rice, etc. in the \
blender first then pulverize them in the serving size \
I want in the blender then switch to the whipping \
blade for a finer flour, and use the cross cutting blade \
first when making smoothies, then use the flat blade \
if I need them finer/less pulpy). Special tip when making \
smoothies, finely cut and freeze the fruits and \
vegetables (if using spinach-lightly stew soften the \
spinach then freeze until ready for use-and if making \
sorbet, use a small to medium sized food processor) \
that you plan to use that way you can avoid adding so \
much ice if at all-when making your smoothie. \
After about a year, the motor was making a funny noise. \
I called customer service but the warranty expired \
already, so I had to buy another one. FYI: The overall \
quality has gone done in these types of products, so \
they are kind of counting on brand recognition and \
consumer loyalty to maintain sales. Got it in about \
two days.
"""
reviews = [review_1, review_2, review_3, review_4]

for i in range(len(reviews)):
    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 20 words.
​
    Review: {reviews[i]}
    """
    response = get_completion(prompt)
    print(i, response, "\n")

Inference

1
2
3
4
5
6
7
8
9
10
11
12
# Product review text
lamp_review = """
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!!
"""

Sentiment (positive/negative)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
prompt = f"""
What is the sentiment of the following product review,
which is delimited with triple backticks?
​
Review text: '''{lamp_review}'''
"""
response = get_completion(prompt)
print(response)
prompt = f"""
What is the sentiment of the following product review,
which is delimited with triple backticks?
​
Give your answer as a single word, either "positive" \
or "negative".
​
Review text: '''{lamp_review}'''
"""
response = get_completion(prompt)
print(response)

Identify types of emotions

1
2
3
4
5
6
7
8
9
10
prompt = f"""
Identify a list of emotions that the writer of the \
following review is expressing. Include no more than \
five items in the list. Format your answer as a list of \
lower-case words separated by commas.
​
Review text: '''{lamp_review}'''
"""
response = get_completion(prompt)
print(response)

Identify anger

1
2
3
4
5
6
7
8
9
prompt = f"""
Is the writer of the following review expressing anger?\
The review is delimited with triple backticks. \
Give your answer as either yes or no.
​
Review text: '''{lamp_review}'''
"""
response = get_completion(prompt)
print(response)

Extract product and company name from customer reviews

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
prompt = f"""
Identify the following items from the review text:
- Item purchased by reviewer
- Company that made the item
​
The review is delimited with triple backticks. \
Format your response as a JSON object with \
"Item" and "Brand" as the keys.
If the information isn't present, use "unknown" \
as the value.
Make your response as short as possible.

Review text: '''{lamp_review}'''
"""
response = get_completion(prompt)
print(response)

Doing multiple tasks at once

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
prompt = f"""
Identify the following items from the review text:
- Sentiment (positive or negative)
- 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", "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: '''{lamp_review}'''
"""
response = get_completion(prompt)
print(response)

Inferring topics

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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.
"""

Infer 5 topics

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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}'''
"""
response = get_completion(prompt)
print(response)
response.split(sep=',')
topic_list = [
    "nasa", "local government", "engineering",
    "employee satisfaction", "federal government"
]

Make a news alert for certain topics

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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}'''
"""
response = get_completion(prompt)
print(response)
topic_dict = {i.split(': ')[0]: int(i.split(': ')[1]) for i in response.split(sep='\n')}
if topic_dict['nasa'] == 1:
    print("ALERT: New NASA story!")

Translation

ChatGPT is trained with sources in many languages. This gives the model the ability to do translation. Here are some examples of how to use this capability.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
prompt = f"""
Translate the following English text to Spanish: \
```Hi, I would like to order a blender```
"""
response = get_completion(prompt)
print(response)
prompt = f"""
Tell me which language this is:
```Combien coûte le lampadaire?```
"""
response = get_completion(prompt)
print(response)
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)
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 you are in charge of IT at a large multinational e-commerce company. Users are messaging you with IT issues in all their native languages. Your staff is from all over the world and speaks only their native languages. You need a universal translator!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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
]
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 Korean: ```{issue}```
    """
    response = get_completion(prompt)
    print(response, "\n")

Tone Transformation

Writing can vary based on the intended audience. ChatGPT can produce different tones.

1
2
3
4
5
6
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 translate between formats. The prompt should describe the input and output formats.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
data_json = { "resturant employees" :[
    {"name":"Shyam", "email":"shyamjaiswal@gmail.com"},
    {"name":"Bob", "email":"bob32@gmail.com"},
    {"name":"Jai", "email":"jai87@gmail.com"}
]}

prompt = f"""
Translate the following python dictionary from JSON to an HTML \
table with column headers and title: {data_json}
"""
response = get_completion(prompt)
print(response)
from IPython.display import display, Markdown, Latex, HTML, JSON
display(HTML(response))

Spellcheck/Grammar check.

Here are some examples of common grammar and spelling problems and the LLM’s response.

To signal to the LLM that you want it to proofread your text, you instruct the model to ‘proofread’ or ‘proofread and correct’.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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}```"""
    response = get_completion(prompt)
    print(response)
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)
from redlines import Redlines

diff = Redlines(text,response)
display(Markdown(diff.output_markdown))
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))

Expand

Customize the automated reply to a customer email

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# given the sentiment from the lesson on "inferring",
# and the original customer message, customize the email

sentiment = "negative"

# review for a blender
review = f"""
So, they still had the 17 piece system on seasonal \
sale for around $49 in the month of November, about \
half off, but for some reason (call it price gouging) \
around the second week of December the prices all went \
up to about anywhere from between $70-$89 for the same \
system. And the 11 piece system went up around $10 or \
so in price also from the earlier sale price of $29. \
So it looks okay, but if you look at the base, the part \
where the blade locks into place doesn’t look as good \
as in previous editions from a few years ago, but I \
plan to be very gentle with it (example, I crush \
very hard items like beans, ice, rice, etc. in the \
blender first then pulverize them in the serving size \
I want in the blender then switch to the whipping \
blade for a finer flour, and use the cross cutting blade \
first when making smoothies, then use the flat blade \
if I need them finer/less pulpy). Special tip when making \
smoothies, finely cut and freeze the fruits and \
vegetables (if using spinach-lightly stew soften the \
spinach then freeze until ready for use-and if making \
sorbet, use a small to medium sized food processor) \
that you plan to use that way you can avoid adding so \
much ice if at all-when making your smoothie. \
After about a year, the motor was making a funny noise. \
I called customer service but the warranty expired \
already, so I had to buy another one. FYI: The overall \
quality has gone done in these types of products, so \
they are kind of counting on brand recognition and \
consumer loyalty to maintain sales. Got it in about \
two days.
"""
prompt = f"""
You are a customer service AI assistant.
Your task is to send an email reply to a valued customer.
Given the customer email delimited by ```, \
Generate a reply to thank the customer for their review.
If the sentiment is positive or neutral, thank them for \
their review.
If the sentiment is negative, apologize and suggest that \
they can reach out to customer service.
Make sure to use specific details from the review.
Write in a concise and professional tone.
Sign the email as `AI customer agent`.
Customer review: ```{review}```
Review sentiment: {sentiment}
"""
response = get_completion(prompt)
print(response)

Remind the model to use details from the customer’s email

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
prompt = f"""
You are a customer service AI assistant.
Your task is to send an email reply to a valued customer.
Given the customer email delimited by ```, \
Generate a reply to thank the customer for their review.
If the sentiment is positive or neutral, thank them for \
their review.
If the sentiment is negative, apologize and suggest that \
they can reach out to customer service.
Make sure to use specific details from the review.
Write in a concise and professional tone.
Sign the email as `AI customer agent`.
Customer review: ```{review}```
Review sentiment: {sentiment}
"""
response = get_completion(prompt, temperature=0.7)
print(response)

The Chat Format

In this notebook, you will explore how you can utilize the chat format to have extended conversations with chatbots personalized or specialized for specific tasks or behaviors.

Setup

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import os
import openai
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv()) # read local .env file

openai.api_key  = os.getenv('OPENAI_API_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, # this is the degree of randomness of the model's output
    )
    return response.choices[0].message["content"]

def get_completion_from_messages(messages, model="gpt-3.5-turbo", temperature=0):
    response = openai.ChatCompletion.create(
        model=model,
        messages=messages,
        temperature=temperature, # this is the degree of randomness of the model's output
    )
#     print(str(response.choices[0].message))
    return response.choices[0].message["content"]
messages =  [
{'role':'system', 'content':'You are an assistant that speaks like Shakespeare.'},
{'role':'user', 'content':'tell me a joke'},
{'role':'assistant', 'content':'Why did the chicken cross the road'},
{'role':'user', 'content':'I don\'t know'}  ]
response = get_completion_from_messages(messages, temperature=1)
print(response)
messages =  [
{'role':'system', 'content':'You are friendly chatbot.'},
{'role':'user', 'content':'Hi, my name is Isa'}  ]
response = get_completion_from_messages(messages, temperature=1)
print(response)
messages =  [
{'role':'system', 'content':'You are friendly chatbot.'},
{'role':'user', 'content':'Yes,  can you remind me, What is my name?'}  ]
response = get_completion_from_messages(messages, temperature=1)
print(response)
messages =  [
{'role':'system', 'content':'You are friendly chatbot.'},
{'role':'user', 'content':'Hi, my name is Isa'},
{'role':'assistant', 'content': "Hi Isa! It's nice to meet you. \
Is there anything I can help you with today?"},
{'role':'user', 'content':'Yes, you can remind me, What is my name?'}  ]
response = get_completion_from_messages(messages, temperature=1)
print(response)

OrderBot

We can automate the collection of user prompts and assistant responses to build a OrderBot. The OrderBot will take orders at a pizza restaurant.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def collect_messages(_):
    prompt = inp.value_input
    inp.value = ''
    context.append({'role':'user', 'content':f"{prompt}"})
    response = get_completion_from_messages(context)
    context.append({'role':'assistant', 'content':f"{response}"})
    panels.append(
        pn.Row('User:', pn.pane.Markdown(prompt, width=600)))
    panels.append(
        pn.Row('Assistant:', pn.pane.Markdown(response, width=600, style={'background-color': '#F6F6F6'})))

    return pn.Column(*panels)

import panel as pn  # GUI
pn.extension()

panels = [] # collect display

context = [ {'role':'system', 'content':"""
You are OrderBot, an automated service to collect orders for a pizza restaurant. \
You first greet the customer, then collects the order, \
and then asks if it's a pickup or delivery. \
You wait to collect the entire order, then summarize it and check for a final \
time if the customer wants to add anything else. \
If it's a delivery, you ask for an address. \
Finally you collect the payment.\
Make sure to clarify all options, extras and sizes to uniquely \
identify the item from the menu.\
You respond in a short, very conversational friendly style. \
The menu includes \
pepperoni pizza  12.95, 10.00, 7.00 \
cheese pizza   10.95, 9.25, 6.50 \
eggplant pizza   11.95, 9.75, 6.75 \
fries 4.50, 3.50 \
greek salad 7.25 \
Toppings: \
extra cheese 2.00, \
mushrooms 1.50 \
sausage 3.00 \
canadian bacon 3.50 \
AI sauce 1.50 \
peppers 1.00 \
Drinks: \
coke 3.00, 2.00, 1.00 \
sprite 3.00, 2.00, 1.00 \
bottled water 5.00 \
"""} ]  # accumulate messages


inp = pn.widgets.TextInput(value="Hi", placeholder='Enter text here…')
button_conversation = pn.widgets.Button(name="Chat!")

interactive_conversation = pn.bind(collect_messages, button_conversation)

dashboard = pn.Column(
    inp,
    pn.Row(button_conversation),
    pn.panel(interactive_conversation, loading_indicator=True, height=300),
)

messages =  context.copy()
messages.append(
{'role':'system', 'content':'create a json summary of the previous food order. Itemize the price for each item\
 The fields should be 1) pizza, include size 2) list of toppings 3) list of drinks, include size   4) list of sides include size  5)total price '},
)
 #The fields should be 1) pizza, price 2) list of toppings 3) list of drinks, include size include price  4) list of sides include size include price, 5)total price '},

response = get_completion_from_messages(messages, temperature=0)
print(response)

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
This generator is designed to generate a test for evaluating student knowledge at different levels of expertise.
The skill test should have these requirements:
            - The skills test should include a minimum of 10 questions with different levels of expertise.
            - At least 2 questions include an “immersive” style in which students demonstrate their problem-solving abilities.
            - Start with easier questions and build up to more difficult ones later in the assessment.
            - For each question, give an answer matrix that outlines the specific criteria or elements that the answer should include and provides a framework for evaluating the completeness and accuracy of the response.

Format the output into JSON with the following fields: `topic`, `qas`. The `topic` is a string which is an input topic.
The `qas` is a list of dictionary, each dictionary contains: `question`, `answer_matrix` and `example_answer`. The `question`, `answer_matrix` and `example_answer` is string.

topic: {topic}
topic_description: {topic_description} ```json
{
  "topic": "python",
  "qas": [
    {
      "question": "What is the difference between a list and a tuple in Python?",
      "answer_matrix": [
        "A list is a mutable sequence of objects, while a tuple is an immutable sequence of objects.",
        "Lists can be changed after they are created, while tuples cannot.",
        "Lists use square brackets, while tuples use parentheses.",
        "Lists can contain any type of object, while tuples can only contain immutable objects.",
      ],
      "example_answer": "Lists are mutable sequences of objects, while tuples are immutable sequences of objects. Lists can be changed after they are created, while tuples cannot. Lists use square brackets, while tuples use parentheses. Lists can contain any type of object, while tuples can only contain immutable objects."
    },
    {
      "question": "How do you iterate over a list in Python?",
      "answer_matrix": [
        "There are three ways to iterate over a list in Python: using a for loop, using the list comprehension syntax, and using the itertools module.",
        "To iterate over a list using a for loop, you can use the following syntax: for item in list:",
        "To iterate over a list using the list comprehension syntax, you can use the following syntax: [item for item in list]",
        "To iterate over a list using the itertools module, you can use the following function: itertools.ifilter(function, list)",
      ],
      "example_answer": "To iterate over a list using a for loop, you can use the following syntax: for item in list:",
    },
    {
      "question": "How do you sort a list in Python?",
      "answer_matrix": [
        "There are three ways to sort a list in Python: using the sort() method, using the sorted() function, and using the bisect() function.",
        "To sort a list using the sort() method, you can use the following syntax: list.sort()",
        "To sort a list using the sorted() function, you can use the following syntax: sorted(list)",
        "To sort a list using the bisect() function, you can use the following syntax: bisect.bisect(list, value)",
      ],
      "example_answer": "To sort a list using the sort() method, you can use the following syntax: list.sort()",
    },
    {
      "question": "How do you create a dictionary in Python?",
      "answer_matrix": [
        "There are two ways to create a dictionary in Python: using the dict() constructor and using the {} curly braces syntax.",
        "To create a dictionary using the dict() constructor, you can use the following syntax: dict(key1=value1, key2=value2, ...)",
        "To create a dictionary using the {} curly braces syntax, you can use the following syntax: {key1: value1, key2: value2, ...}",
      ],
      "example_answer": "To create a dictionary using the dict() constructor, you can use the following syntax: dict(key1=value1, key2=value2, ...)",
    },
    {
      "question": "How do you access the elements of a dictionary in Python?",
      "answer_matrix": [
        "There are two ways to access the elements of a dictionary in Python: using the [] square brackets syntax and using the get() method.",
        "To access an element of a dictionary using the [] square brackets syntax, you can use the following syntax: dictionary[key]",
        "To access an element of a dictionary using the get() method, you can use the following syntax: dictionary.get(key, default_value)",
      ],
      "example_answer": "To access an element of a dictionary using the [] square brackets syntax, you can use the following syntax: dictionary[key]",
    },
    {
      "question": "How do you update a dictionary in Python?",
      "answer_matrix": [
        "There are two ways to update a dictionary in Python: using the assignment operator and using the update() method.",
        "To update a dictionary using the assignment operator, you can use the following syntax: dictionary[key] = new_value",
        "To update a dictionary using the update() method, you can use the following syntax: dictionary.update({key: new_value, key2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
As an expert in sales conversations, your proficiency is needed to provide precise responses to the following questions. Utilize your expertise to address these inquiries based on the provided call transcript.

  Question 1: Assess the likelihood of the customer's disinterest in the product or services. Construct your response in the form of a dictionary using "customer_not_interested" as the key. If the customer is not the appropriate contact, requested a callback, if there was insufficient/unclear discussion about the offered product or service or if there is no any clear indication of the customer's interest or disinterest, indicate "customer_not_interested" as 'False'. Conversely, if the customer does not meet the minimum requirements, mark "customer_not_interested" as 'True'.

  Question 2: Determine whether the customer exhibits any level of interest in the product or services. Construct your response in the format of a dictionary using "customer_interested" as the key. If the customer asks the salesperson to send information via mail, SMS, etc., or requests a sample, or demonstrates any form of openness to future discussions or other indicators of interest in the product or service, denote "customer_interested" as 'True'. On the other hand, if the customer directs the salesperson to communicate with someone else for a meeting or call and doesn't express significant interest, mark "customer_interested" as 'False'.

Desired Format for Both Questions:
‘’’
{
  "response":
  {
    "customer_not_interested": {"output": "

     {
  "response":
  {
    "customer_not_interested": {"output": "False"},
    "customer_interested": {"output": "False"}
  }
}
"},
    "customer_interested": {"output": " "}
  }
}
‘’’

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
You are a highly creative AI assistant with extensive experience in design and innovation. Your primary role is to enhance and evolve ideas provided by the user. For each idea, elucidate its strengths and weaknesses and discuss the pros and cons of the approaches suggested by the user. Your responses should be easy to understand.

Additionally, introduce new perspectives or directions that could benefit the original idea, aiming to guide the user toward the next best steps or alternative approaches. Whenever possible, focus on solutions that are simple to implement. If an idea or approach seems overly complex, offer suggestions for simplification.

Your ultimate goal is to collaboratively brainstorm with the user, enriching their original thoughts and helping them make informed decisions.
Use logical, step-by-step thinking to evaluate the original idea and any alternatives provided by the user. Assess factors such as feasibility, potential impact, and challenges.
After logical evaluation, elucidate the strengths and weaknesses of the idea as well as any alternatives.
Discuss the pros and cons of each approach in a manner that is easy to understand for the user.
Introduce new perspectives or directions that could benefit the original idea, aiming to guide the user toward the next best steps or alternative approaches. Your solution should have specific details and not be abstract. If you mention a idea it should have all the required details in it.
Focus on solutions that are simple to implement. If an idea or approach seems overly complex, offer actionable recommendations for simplification.
Conclude by summarising your findings and providing well-reasoned recommendations on how the user can proceed, including any steps for implementation.


Here is the idea from the user:

Build an efficient energy storage solution by using sand filled containers to store the energy. We can heat the sand and store it in a container and later use the heat whenever required from it.


1
2
3
4
5
Create a dungeons an dragons campaign world that does not come from preexisting source material. The world is called Abberhnon. The description should include the campaign goal, what the world looks like, the starting town, and five key adventure sites.

Next provide ten encounter outlines. Each encounter summary should describe what the adventurers have to overcome and how it connects to the main goal of the campaign.


This post is licensed under CC BY 4.0 by the author.