https://pin.it/3vfy0Dt

Mastering the Art of Prompting in Generative AI: A Comprehensive Guide

Naveed Ul Mustafa
7 min readJul 3, 2023

Navigating the intricate landscape of generative AI prompts can often feel akin to learning a new language. Like any language, it is riddled with nuances that, when mastered, can help us communicate our desires to the model with unparalleled precision and clarity. This guide is your comprehensive playbook to understanding and applying the core principles of effective prompting, enhancing your generative AI endeavors.

Crafting Clear and Specific Instructions

Your AI model is like an extremely literal genie. It does precisely what it’s instructed to do and nothing more. Hence, it’s pivotal that we’re as explicit and unambiguous in our prompts as possible. However, clear instructions don’t necessarily translate to short prompts. Quite the contrary, a longer, more elaborate prompt can often paint a comprehensive picture for the AI, resulting in richer, more relevant outputs.

Here are some powerful strategies to hone your instruction-crafting skills:

Embrace Delimiters: Delimiters are your allies in creating order within your prompts. They serve as signposts, distinguishing separate parts of your input, and guiding the AI. You can use triple quotes ("""), triple backticks ('''), triple dash (---), angle brackets (<>), or XML tags to structure your prompt. Let's see it in action:

prompt = f"""
Identify the main characters in the novel 'To Kill a Mockingbird'"""

Call for Structured Output: Calling for your outputs to be structured in formats like JSON or HTML can drastically improve the clarity and utility of the output. Have a look:

prompt_1 = f"""
Describe the novel 'Pride and Prejudice' in a JSON format"""

prompt_2 = 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.
"""

Condition Checks: If your task is based on certain assumptions, ask the model to confirm these before progressing. Here are examples:

prompt_1 = f"""
if 'The Catcher in the Rye' is a novel,
then provide a brief summary of it
"""

prompt_2 = f"""
if the novel 'To Kill a Mockingbird' is a classic,
then write a summary of the novel
"""

prompt_3 = 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_1}\"\"\"
"""

Utilize Few-Shot Prompts: A few-shot prompt is akin to showing the model a roadmap to the desired output, or in other words, a model is tasked to answer in a consistent style. By providing examples of what you’re seeking, the model can better understand and mimic the pattern. Like this:


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.
"""
# Example: Deeplearning.ai short course

<grandparent>: Resilience is like a mighty oak tree that withstands the strongest storms, bending but never breaking. It is the unwavering determination to rise again after every fall, and the ability to find strength in the face of adversity. Just as a diamond is formed under immense pressure, resilience is forged through challenges and hardships, making us stronger and more resilient in the process.

Example: deeplearning.ai short course

Allowing Ample Time for Task Completion

Even the brightest minds need time to process and articulate their thoughts, and our AI model is no different. Ensuring that the model is afforded sufficient time to understand and complete the task is paramount. If rushed or overloaded with complex tasks, the model may provide an off-the-mark or oversimplified answer.

How can we achieve this? Here’s how:

Break It Down: Split your task into manageable steps. This makes it easier for the model to process the task and arrive at a more accurate answer.

prompt = f"""
Step 1: Understand the novel 'The Great Gatsby'.
Step 2: Identify the key themes.
Step 3: Write a summary incorporating these themes.
"""
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.
"""
# example 1
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}```
"""

# Same text but with different instructions
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 Italian summary>
Output JSON: <json with summary and num_names>

Text: <{text}>
"""

Example: deeplearning.ai short course

Promote Thoughtful Processing: Encourage the model to take its time, think through the question, do a calculation itself and breaking down the task into steps to give the model more time to think and then articulate a detailed answer.

prompt = f"""
Take a moment to understand and analyze the concept of 'quantum physics'
before providing a simplified explanation.
"""
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:
"""

Example: deeplearning.ai short course

Understanding Model Limitations

AI model, albeit high sophistication, still has its limitations. It doesn’t perfectly memorize the entirety of the information it’s seen, and often struggles to recognize the boundaries of its knowledge. This can result in the model offering responses about obscure topics that sound plausible but are not factually accurate — a phenomenon we refer to as ‘hallucinations’. As practitioners, we must be cognizant of these limitations and craft our prompts accordingly.

Working Example:

I briefly applied the skills learned to the practice and followed the steps, go generate near accurate text from reference.

import openai
openai.api_key = "sk-.." # the key can be accessed by the OpenAPI
# Helper Function
def get_completion(prompt, model="gpt-3.5-turbo"):
messages = [{"role": "user", "content": prompt}]
response = openai.ChatCompletion.create(
model=model,
messages=messages,
temperature=0, # degree of randomness of the model's output
)
return response.choices[0].message["content"]
prompt = f"""
Find any relevent text for Hajmola.\
Give me the source of it.\

Generate a 100 words summary for presentation about cheap and relevent\
solutions of gastric issues.
"""
response = get_completion(prompt)
print(response)

Hajmola is a popular digestive tablet in India that is known for its tangy taste and digestive properties. It is made from a blend of traditional Indian herbs and spices, including black salt, cumin, and ginger. Hajmola is commonly used to relieve indigestion, bloating, and acidity. It is also believed to stimulate the digestive system and improve appetite. The source of this information is the official website of Hajmola, available here.

Summary:

Gastric issues can be a common problem for many individuals, but there are affordable and effective solutions available. One such solution is Hajmola, a digestive tablet made from natural herbs and spices. Hajmola is known for its tangy taste and ability to relieve indigestion, bloating, and acidity. It stimulates the digestive system and improves appetite. This affordable and relevant solution can provide relief from gastric issues without breaking the bank. Consider incorporating Hajmola into your daily routine for a cost-effective and natural way to address digestive problems.

In conclusion, the art of effective prompting lies in a harmonious blend of crafting precise instructions, allowing the model sufficient time, and staying aware of its limitations. Like any art form, it requires practice and patience. But with this comprehensive guide as your roadmap, you’re well on your way to mastering the art of prompting. Happy prompting, and may your AI journey be enriching and enlightening!

Kindly follow my Github and Twitter.

--

--

Naveed Ul Mustafa

Student, interested in Machine Learning & Gen AI, Computational Neuroscience & Computer Vision