Top 20 ChatGPT prompts that every prompt engineers should know
Vishnu Sivan
Posted on May 27, 2023
In recent years, OpenAI’s ChatGPT has revolutionized the landscape of AI language models with its remarkable capabilities. Powered by the groundbreaking GPT-3 and GPT-4 architectures, ChatGPT has emerged as one of the most versatile and powerful tools available. With its ability to generate human-like text responses, answer questions, create content, and engage in conversation, it has become an invaluable asset in the realm of artificial intelligence. However, to fully harness the potential of this AI marvel, it is crucial to understand the art of effective communication through the use of well-crafted prompts.
Prompts play a vital role in guiding ChatGPT’s responses. The level of detail and specificity within the prompts directly influences the model’s understanding and ability to generate the desired output. By providing explicit instructions, users can prompt the chatbot to extend and embellish sentences, simulate a specific AI tool as a prompt generator, or even refine answers as additional information is provided.
Whether you are an experienced AI enthusiast or a curious newcomer to the world of AI language models, mastering the skill of prompt creation will empower you to unlock the full potential of ChatGPT. In this article, we will dive into the details of crafting effective prompts for ChatGPT.
Getting Started
Table of contents
- What is ChatGPT
- How does ChatGPT works
- What is a prompt
- Importance of crafting effective prompts
- What is prompt engineering
- Top 20 ChatGPT prompts
- Prompt 1: Use delimiters to clearly indicate distinct parts of the input
- Prompt 2: Ask for a structured output
- Prompt 3: Ask the model to check whether conditions are satisfied
- Prompt 4: Ask for a structured output with shot prompts
- Prompt 5: Specify the steps required to complete a task
- Prompt 6: Specify the steps and ask for output in a specified format
- Prompt 7: Instruct the model to work out its own solution before rushing to a conclusion
- Prompt 8: Generate a product description from a product fact sheet
- Prompt 9: Summarize text with a word/sentence/character limit
- Prompt 10: Try extract instead of summarize
- Prompt 11: Summarize multiple product reviews
- Prompt 12: Infer sentiment and topics from product reviews
- Prompt 13: Doing multiple tasks at once
- Prompt 14: Inferring topics
- Prompt 15: Text language detection and translation
- Prompt 16: Writing can vary based on the audience and tone
- Prompt 17: Proofreading the content
- Prompt 18: Customize the automated reply to a customer email
- Prompt 19: chatbots personalized for specific tasks
- Prompt 20: OrderBot
What is ChatGPT
ChatGPT is an artificial intelligence language model developed by OpenAI. It is built on top of the GPT (Generative Pre-trained Transformer) architecture, which is a type of deep learning model widely used for natural language processing tasks. ChatGPT is specifically designed to facilitate conversational interactions with users, allowing them to engage in dialogue and receive responses generated by the model.
ChatGPT leverages its extensive training on a diverse range of internet text to understand and generate human-like responses. It can comprehend prompts or questions provided by users and generate contextually relevant and coherent replies. The model has the ability to grasp the overall meaning and context of the conversation, allowing for interactive and dynamic interactions.
OpenAI has released several iterations of the GPT model, with GPT-3 being the predecessor to ChatGPT. The development of ChatGPT aims to enhance the conversational capabilities of the model and enable more engaging and interactive experiences with users.
How does ChatGPT works
ChatGPT is an AI model that employs deep learning techniques to generate text that resembles human language. It achieves this by predicting the most likely next word in a given sequence of text, drawing upon patterns it has learned from an extensive training process using large amounts of data.
During training, OpenAI exposes ChatGPT to massive volumes of text data. The model then uses this data to make predictions about what the subsequent word should be, based on the patterns it has observed. OpenAI evaluates these predictions and refines the model accordingly. This iterative process is repeated numerous times to improve the model’s performance.
Over time, ChatGPT reaches a stage where its predictions closely resemble human-like responses. However, it’s crucial to note that ChatGPT does not undergo continuous training and is not aware of real-time events or up-to-date information. Its knowledge is based on the data it was trained on and has a knowledge cutoff date, beyond which it does not possess direct information.
What is a prompt
A prompt refers to the text input provided by the user to initiate the response generation process in ChatGPT. It serves as the starting point for the AI to understand the context and meet the user’s expectations by generating a suitable and meaningful output. It acts as a conversation initiator or an information request, guiding ChatGPT in formulating its response. Providing a clear and specific prompt helps AI to better comprehend their intentions and generate the desired output.
Image source: Mastering ChatGPT: How to Craft Effective Prompts
Importance of crafting effective prompts
The process of creating well-designed prompts is essential when utilizing ChatGPT since it has a direct influence on the quality of the generated output. Prompts serve as a guide, establishing the context and desired response for a fruitful interaction. By crafting prompts thoughtfully, one can elicit insightful, accurate, and imaginative responses from ChatGPT that align with their specific requirements and expectations.
Effective prompts help in several ways:
- Clear communication: Well-structured and specific prompts increase the likelihood of receiving relevant and helpful responses.
- Time and effort savings: Thoughtfully crafted prompts can reduce the need for extensive iterations and back-and-forth interactions.
- Error minimization: Providing context and guidelines in prompts helps minimize the chances of the AI generating irrelevant, incorrect, or unhelpful responses.
- Expectation definition: Prompts help users define their expectations, guiding ChatGPT regarding the purpose, level of detail, and any specific constraints of the task.
- Channeling creativity: Well-crafted prompts inspire creative solutions and unique perspectives from ChatGPT, maximizing its knowledge and language capabilities.
- Ambiguity reduction: Effective prompts minimize ambiguity, clearly conveying the user’s intent and desired outcome to avoid miscommunication.
What is prompt engineering
ChatGPT Prompt Engineering is an innovative method in the field of artificial intelligence that revolves around developing natural language processing models capable of generating human-like responses to specific prompts or questions. This approach emphasizes the creation of engaging, informative, and contextually relevant prompts tailored to meet the user’s requirements. By carefully designing prompts, users are encouraged to provide the necessary information to enable the Chatbot to effectively assist them. A key reason for the importance of prompt engineering in ChatGPT lies in optimizing the quality of the generated responses. Without proper prompt engineering, the AI-generated output may fail to accurately address the user’s question or provide relevant information.
Top 20 ChatGPT prompts
In this section, we will discuss on 25 ChatGPT prompts that are useful for the prompt engineers to interact with the AI tool.
Installing dependencies
- Create and activate a virtual environment by executing the following command.
python -m venv venv
source venv/bin/activate #for ubuntu
venv/Scripts/activate #for windows
- Install
openai
,python-dotenv
library using pip.
pip install openai python-dotenv
- Create a file named
.env
and add the openai key as follows.
OPENAI_API_KEY=<your_openai_key>
Before moving into the prompts, access openai api key and create a get_completion()
method. This method takes prompt and model as arguments and provides the results from ChatGPT.
- Create a file
main.py
and the following code to it.
import openai
import os
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())
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,
)
return response.choices[0].message["content"]
Prompt 1: Use delimiters to clearly indicate distinct parts of the input
Delimiters can be anything like:
```, “””, < >,
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.
"""
prompt = f"""
Summarize the text delimited by triple backticks \
into a single sentence.
```{text}```
"""
response = get_completion(prompt)
print(response)
Prompt 2: Ask for a structured output
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.
"""
response = get_completion(prompt)
print(response)
Prompt 3: Ask the model to check whether conditions are satisfied
text = 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 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}\"\"\"
"""
response = get_completion(prompt)
print(response)
Prompt 4: Ask for a structured output with shot prompts
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.
"""
response = get_completion(prompt)
print(response)
Prompt 5: Specify the steps required to complete a task
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 = f"""
Perform the following actions:
1 - Summarize the following text delimited by triple \
backticks with 1 sentence.
2 - Translate the summary into German.
3 - List each name in the German summary.
4 - Output a json object that contains the following \
keys: german_summary, num_names.
Separate your answers with line breaks.
Text:
```{text}```
"""
response = get_completion(prompt)
print(response)
Prompt 6: Specify the steps and ask for output in a specified format
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 = f"""
Your task is to perform the following actions:
1 - Summarize the following text delimited by <> with 1 sentence.
2 - Translate the summary into German.
3 - List each name in the German summary.
4 - Output a json object that contains the
following keys: german_summary, num_names.
Use the following format:
Text: <text to summarize>
Summary: <summary>
Translation: <summary translation>
Names: <list of names in Italian summary>
Output JSON: <json with summary and num_names>
Text: <{text}>
"""
response = get_completion(prompt)
print(response)
Prompt 7: Instruct the model to work out its own solution before rushing to a conclusion
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 wind power installation and I need help \
working out the financials.
- Land costs $100 / square foot
- I can buy windmills for $200 / square foot
- I negotiated a contract for maintenance that will cost \
me a flat $75k per year, and an additional $15 / 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. Windmill cost: 200x
3. Maintenance cost: 75,000 + 100x
Total cost: 100x + 200x + 75,000 + 100x = 315x + 75,000
Actual solution:
"""
response = get_completion(prompt)
print(response)
Prompt 8: Generate a product description from a product fact sheet
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
- 4-wheel plastic coated aluminum base.
- Pneumatic chair adjust for easy raise/lower action.
DIMENSIONS
- WIDTH 50 CM | 20”
- DEPTH 51 CM | 20.08”
- HEIGHT 85 CM | 40”
- 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)
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.
Use at most 50 words.
Technical specifications:
```{fact_sheet_chair}```
"""
response = get_completion(prompt)
print(response)
len(response)
Prompt 9: Summarize text with a word/sentence/character limit
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.
"""
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}```
"""
response = get_completion(prompt)
print(response)
Prompt 10: Try extract instead of summarize
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.
"""
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:
```{review}```
"""
response = get_completion(prompt)
print(response)
Prompt 11: Summarize multiple product reviews
review_1 = """
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.
"""
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_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 $40 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!
"""
reviews = [review_1, review_2, review_3]
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 25 words.
Review:
```{reviews[i]}```
"""
response = get_completion(prompt)
print(i, response, "\n")
Prompt 12: Infer sentiment and topics from product reviews
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! \
VSoft seems to me to be a great company that cares \
about their customers and products!!
"""
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: '''{review}'''
"""
response = get_completion(prompt)
print(response)
Prompt 13: Doing multiple tasks at once
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! \
VSoft 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)
- 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: '''{review}'''
"""
response = get_completion(prompt)
print(response)
Prompt 14: Inferring topics
topics = """
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."
"""
prompt = f"""
Determine four 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: '''{topics}'''
"""
response = get_completion(prompt)
print(response)
Prompt 15: Text language detection and translation
text = f"Hi, I would like to order a pizza"
prompt = f"Tell me what language this is:
```{text}```
"
lang = get_completion(prompt)
print(f"Original message ({lang}): {text}")
prompt = f"""
Translate the following text to German: \
```{text}```
"""
response = get_completion(prompt)
print(response)
Prompt 16: Writing can vary based on the audience and tone
prompt = f"""
Translate the following from slang to a business letter:
'Dude, This is Vishnu, check out this spec on this standing lamp.'
"""
response = get_completion(prompt)
print(response)
Prompt 17: Proofreading the content
text = f"""
Got this for my sister 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 sister.
"""
prompt = f"proofread and correct this review:
```{text}```
"
response = get_completion(prompt)
print(response)
Prompt 18: Customize the automated reply to a customer email
sentiment = "negative"
review = f"""
So, they still had the 17 piece system on seasonal \
sale for around $50 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 $25. \
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 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)
Prompt 19: chatbots personalized for specific tasks
import os
import openai
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())
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
)
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 Vishnu'} ]
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 Vishnu'},
{'role':'assistant', 'content': "Hi Vishnu! 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)
Prompt 20: OrderBot
import os
import openai
from dotenv import load_dotenv, find_dotenv
_ = load_dotenv(find_dotenv())
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
)
return response.choices[0].message["content"]
# We can automate the collection of user prompts and assistant responses to build a OrderBot.
# The OrderBot will take orders at a pizza restaurant.
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 '},
)
response = get_completion_from_messages(messages, temperature=0)
print(response)
Thanks for reading this article.
Thanks Gowri M Bhatt for reviewing the content.
If you enjoyed this article, please click on the heart button ♥ and share to help others find it!
The prompt contents are referred from ChatGPT Prompt Engineering for Developers course provided by deeplearning.ai. I would highly recommend you take the course to understand more about prompt engineering.
ChatGPT Prompt Engineering for Developers | www.deeplearning.ai
The full source code for this tutorial can be found here,
GitHub - codemaker2015/top-20-chatgpt-prompts | github.com
The article is also available on Medium.
Here are some useful links,
Posted on May 27, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.