Towards AI Can Help your Team Adopt AI: Corporate Training, Consulting, and Talent Solutions.

Publication

The Art of Prompting: How Accurate Prompts Can Drive Positive Outcomes.
Generative AI   Latest   LLMs   Machine Learning

The Art of Prompting: How Accurate Prompts Can Drive Positive Outcomes.

Last Updated on May 22, 2023 by Editorial Team

Author(s): Rohini Vaidya

Originally published on Towards AI.

Takeaways from the newly available free course offered by DeepLearning.AI and OpenAI regarding Prompt engineering for developers.

Image

Prompt engineering involves designing effective prompts for natural language generation models, such as GPT3, to produce relevant and high-quality responses. Well-designed prompts can significantly improve the accuracy and coherence of generated text, leading to a better user experience and increased effectiveness of the model.

There are two types of Large Language Models(LLMs), i.e. Base LLM and instruction Tuned LLM.

A base language model is a pre-trained language model, it is a large neural network that learns the structure and patterns of natural language through massive data. These models can perform a variety of tasks such as language modeling, sentiment analysis, and question-answering. These models handle multiple tasks and generate text with varying styles and tones.

Instruction language models are fine-tuned on specific tasks or domains by training on smaller datasets & optimizing pre-trained model weights.

The key difference between base and instruction language models is that base models are trained on a diverse range of tasks and data, whereas instruction models are optimized for specific tasks or domains. Instruction models are typically more accurate and effective for their specific task or domain, but may not perform as well on other tasks or in general use.

This course focuses on the best practices for instruction-tuned LLM.

Hey, If you are using the GPT in your local system first time then you can follow the following steps:

Step 1: Open your browser, type openai.com in the browser’s address bar, and press enter.

Step 2: Click on the API button at the top left corner.

Step 3: Click on the sign-up button at the top right.

Step 4: Using your email account sign-up to Openai.

Step 5: Enter your phone number and verify it.

Step 6: Next, click on the personal button at the top right and then click on the view API keys.

Step 7: Here, you will get your API key, just copy it and use it where needed.

Principals used for promoting:

  1. Write clear and specific instructions:

To prevent prompt injection, use delimiters to distinguish different parts of the input. Examples of delimiters include triple quotes """, triple backticks ’’’, triple dashes ___, angle brackets<>, XML tags <tag> </tag>.

import openai
openai.api_key = 'Your API key here'
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"]

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

response = get_completion(prompt)
print(response)

Output:

Clear and specific instructions should be provided to guide a model toward the desired output, and longer prompts can provide more clarity and context for the model, leading to more detailed and relevant outputs.

Ask for a specific format like JSON, HTML

promt1 = f"""
Generate a list of 3 books on health along with the author name, publication and release date in json format with the
following keys : sr.no, book_id, book_name, book_autghor,realese_date, publication,summary

"""

response = get_completion(promt1)
print(response)

Output:

[
{
"sr.no": 1,
"book_id": "ISBN-13: 978-1501167983",
"book_name": "The Plant Paradox: The Hidden Dangers in 'Healthy' Foods That Cause Disease and Weight Gain",
"book_author": "Dr. Steven R. Gundry",
"release_date": "April 25, 2017",
"publication": "Harper Wave",
"summary": "This book reveals the hidden toxins lurking in seemingly healthy foods and provides a step-by-step guide to help readers improve their health by avoiding these harmful substances."
},
{
"sr.no": 2,
"book_id": "ISBN-13: 978-0316322408",
"book_name": "The Whole30: The 30-Day Guide to Total Health and Food Freedom",
"book_author": "Melissa Hartwig Urban and Dallas Hartwig",
"release_date": "April 21, 2015",
"publication": "Houghton Mifflin Harcourt",
"summary": "This book provides a comprehensive 30-day program to help readers reset their eating habits, eliminate unhealthy foods, and improve their overall health and well-being."
},
{
"sr.no": 3,
"book_id": "ISBN-13: 978-0062427137",
"book_name": "The Sleep Revolution: Transforming Your Life, One Night at a Time",
"book_author": "Arianna Huffington",
"release_date": "April 5, 2016",
"publication": "Harmony",
"summary": "This book explores the importance of sleep for overall health and well-being, and provides practical tips and strategies for improving the quality and quantity of sleep."
}
]

You can also check whether the given condition is satisfied or not. Check assumptions required to do a task.

Text1 = """
To make tea, put water in a kettle according to the requirement and
put the kettle on a stove. Let the water boil for some time.
Then put tea leaves into the water. For a cup of tea one teaspoonful tea
leaves is required. Let it boil for a few minutes. Stir the mixture.
It will give a good colour. Pour the mixture into the cup.
Add milk and sugar to your taste. Tea is ready to drink.
"""

Text2 = """
In statistics, the k-nearest neighbors algorithm (k-NN) is a non-parametric supervised learning method
first developed by Evelyn Fix and Joseph Hodges in 1951,[1] and later expanded by Thomas Cover.[2]
It is used for classification and regression.
"""


prompt1=f"""
You will be provided text delimited by the triple quotes.
If the text contains instructions then write it in a following format:
step 1 - ....
step 2 - ...
...
step N -...
If text does not contain instructions then \simply write \'No steps provided for the given text'
'\'\'{Text1}'\'\'
"""


prompt2=f"""
You will be provided text delimited by the triple quotes.
If the text contains instructions then write it in a following format:
step 1 - ....
step 2 - ...
...
step N -...
If text does not contain instructions then \simply write \'No steps provided for the given text'
'\'\'{Text2}'\'\'
"""

response1 = get_completion(prompt1)
print("Completion for Text 1 :")
print(response1)

Output:

Completion for Text 1 :
step 1 - Put water in a kettle according to the requirement and put the kettle on a stove.
step 2 - Let the water boil for some time.
step 3 - Put tea leaves into the water. For a cup of tea one teaspoonful tea leaves is required.
step 4 - Let it boil for a few minutes.
step 5 - Stir the mixture.
step 6 - Pour the mixture into the cup.
step 7 - Add milk and sugar to your taste.
step 8 - Tea is ready to drink.
response2 = get_completion(prompt2)
print("Completion for Text 2:")
print(response1)

Output:

Completion for Text 2:
No steps are provided for the given text.

When giving Text 1 in step format, the model provides steps for preparing tea. In contrast, Text 2 without step format leads to the model outputting “No steps are provided for the given text.” Providing an appropriate prompt enables the model to check conditions from the text.

Few shot prompting: Give successful examples of completing the task and then ask the model to perform a similar task.

prompt="""
Your task is to complete the conversation in a consistent style

Student : Good morning, sir.
Teacher : Good morning.
Student : Sir, my examination is round the corner. Can you give me some instructions as to how I should prepare?
Teacher : Certainly! But at first, get rid of your mobile. That is a major distraction.
Student : Ok, sir.
Student : Madam, I want to go early today.

"""

response = get_completion(prompt)
print(response)

Output:

Teacher : Is there any particular reason why you need to leave early?
Student : Yes, I have an appointment with my dentist.
Teacher : Alright, make sure you catch up on any missed work and let me know if you need any help.
Student : Thank you, madam. I will make sure to do that.

2. Give the model time to think.

Specify the steps and the format of the answer you required to complete the task

Text = f """There once was a king named Midas who did a good deed for a Satyr. And he was then granted a wish by Dionysus, the god of wine.

For his wish, Midas asked that whatever he touched would turn to gold. Despite Dionysus’ efforts to prevent it, Midas pleaded that this was a fantastic wish, and so, it was bestowed.

Excited about his newly-earned powers, Midas started touching all kinds of things, turning each item into pure gold.

But soon, Midas became hungry. As he picked up a piece of food, he found he couldn’t eat it. It had turned to gold in his hand.

Hungry, Midas groaned, “I’ll starve! Perhaps this was not such an excellent wish after all!”

Seeing his dismay, Midas’ beloved daughter threw her arms around him to comfort him, and she, too, turned to gold. “The golden touch is no blessing,” Midas cried."""


prompt = f""" perform the following actions
1 - Summarize the following text delimated by triple backticks.
2 - Translate the summary into hindi.
3 - List each character name in a hindi.

separate your anser with line bracket

Use the following format :
1. Text:<Text to summarize>
2. Summarization: <Summary>
3. Translated summary:<Summary translation>
4. Give the moral of a story:<moral of a story>
Text:
'''{Text}'''

"""

response = get_completion(prompt)

print(response)

Output:

Summarization: King Midas is granted a wish by Dionysus to turn everything he touches into gold. He soon realizes the downside of his wish when he cannot eat or touch his loved ones without turning them into gold. 

Translated summary: राजा मिडास को दियोनिसस द्वारा एक इच्छा पूरी की जाती है कि वह जो कुछ भी छूता है वह सोना बन जाता है। उसे जल्द ही अपनी इच्छा का नुकसान महसूस होता है जब उसे यह पता चलता है कि वह अपने प्रियजनों को छू नहीं सकता।

List of character names in Hindi: राजा मिडास, दियोनिसस, राजकुमारी (King Midas, Dionysus, Princess)

Moral of the story: Be careful what you wish for, as it may have unintended consequences.

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

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

response = get_completion(prompt)
print(response)

Output:

The student's solution is correct.

If you can read the question and the student’s solution carefully, then you will notice that the student’s solution was incorrect.

You can fix this by instructing the model to work out its own solution first and then compare it with the student’s solution.

Below is the correct prompt that one should give:

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:
"""

response = get_completion(prompt)
print(response)

Output:

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 + 10x

Total cost: 100x + 250x + 100,000 + 10x = 360x + 100,000

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

Student grade:
Incorrect

Here, you can see model gives the correct output that is student’s solution was incorrect.

Conclusion: It is most important to provide accurate and precise prompts in order to ensure desired outcomes. The provision of correct prompts plays a pivotal role in achieving success and fulfilling predetermined objectives. Therefore, it is imperative to invest time and effort into crafting prompts that are tailored to meet the intended purpose and produce optimal results.

Next, I’ll cover the remaining topics including text summarizing, transformation, expanding, and chatbots.

Stay tuned !!!

If you found this article insightful, follow me on LinkedIn and Medium.

Thank you !!!

You can read my other blogs:

Unraveling the Complexity of Distributions in Statistics

Navigating the Complex World of Distribution

pub.towardsai.net

A Comprehensive Guide for Handling Outliers

Part: 2

pub.towardsai.net

Basic Concepts of statistics that every Data scientist should know.

It’s easy to lie with statistics, It’s hard to tell the truth without statistics.

pub.towardsai.net

Text extraction for unstructured data using easy OCR.

What is OCR ?

medium.com

Join thousands of data leaders on the AI newsletter. Join over 80,000 subscribers and keep up to date with the latest developments in AI. From research to projects and ideas. If you are building an AI startup, an AI-related product, or a service, we invite you to consider becoming a sponsor.

Published via Towards AI

Feedback ↓