LLMs are powerful tools, but they are based on clear instructions to function effectively. Proper prompt engineering helps us discover their full potential by providing specific instruction on what we want them to do. Prompt engineering best practices are important to receive more accurate, relevant, and informative outputs.
LLMs stands for Large Language Models. We also call them AI models or models in short. They are a type of artificial intelligence (AI) tools that can process and generate humanlike text in response to a wide range of prompts and questions.
Prompt engineering is a crucial aspect of working with AI models. It involves writing well-designed prompts or instructions to guide the model’s responses and control its behavior. In this aticle, we will explore the top 10 prompt engineering best practices along with examples to communicate with AI models more efficiently.
Prompt Engineering Best Practices
We can improve the quality and significance of the responses that we receive from an AI model (LLMs) by creating powerful prompts. Being expert on writing poweful prompts requires a solid understanding of how AI interprets and processes natural language inputs. By following Prompt engineering best practices, we can have an excellent understanding in this area.
1. Understand the Model’s Capabilities and Limitations Before Using it
It’s important to understand its capabilities and limitations of a language model before significantly utilizing it for certain tasks. Different models have different strengths. Some may stand out at open-ended text generation, while others can be better at audio, video generation, or analysis or even coding. We should be aware of their weaknesses and potential failure conditions.
For example, GPT-3 has strong general language understanding and generation capabilities, that makes it well-suited for unrestricted writing tasks, question answering, and certain types of analysis. However, its training data ends in 2021, so it may not have the most recent factual knowledge for quickly progressing fields. It also does not handle symbolic mathematics or coding as effectively as models adapted for those tasks. Understanding these pros and cons at the start allows you to plan usage of prompts and model appropriately.
2. Be Specific & Clear as much as possible
While writing prompts, be specific & clear to achieve the correct and relevant results from an AI model. A specific prompt minimizes confusion. It allows the AI to understand the context of request and undertone, that prevents it from providing excessively large or unrelated responses. We should include as many relevant details as possible without overloading the AI with unnecessary information. This practice ensures that the AI has just sufficient advice to produce the specific outcome we are targeting for. For example, instead of asking “Tell me about fast foods,” ask “What are the advantages and disadvantages of having Pizzas?”
While creating the prompts, request for the following specifics:
- Background information: Provide enough background information to understand the context you are questioning about. This primarily covers the topic, scope of the topic, and any related information.
- Format of the Response: We should clearly mention the format in which the response to be presented, such as a list, a table, bullet points, a detailed report, or a summary. Specify any outline or structural priority, such as headings, subheadings, or any paragraph limits.
- Length of Output: Specify the length of output, such as 4 paragraphs or 2000 words.
- Degree of Response: Point out the level of response, such as from high-level details to in-depth analysis, in order to confirm the model’s response matches your requirement.
- Tone and style: Mention the preferable tone and style, such as formal, informal, conversational, or persuasive, to make sure the output matches with your objective or purpose.
- Examples and analogy: Request the AI to include various examples, analogies, or comparative analysis to explain complex concepts in order to make the information easy to connect and understand without difficulty.
♦ Example:
Non-Specific Prompt: “Describe how global warming is influencing extreme weather patterns, such as heatwaves and rainstorm.”
More Specific Prompt:
“Create a comprehensive educational overview of global warming, focusing on the causes, impacts, and solutions. Explain the direct impact of global warming on the frequency, intensity, and geographic distribution of heatwaves and rainstorms worldwide, including scientific data and case studies to illustrate the correlation between rising global temperatures and the occurrence of extreme weather events, highlighting the implications for human health, and propose adaptation and mitigation strategies. Provide a concise but comprehensive analysis of these climate-driven extremes in 2000 words.”
3. Incorporate Examples
Include examples into your prompts whenever possible. It is a strong technique to guide the AI’s responses in the expected direction. It will help AI model to identify the type of information or response you expect. This practice is specifically suitable for complicated tasks where the expected output might be doubtful. This practice can also be useful for innovative tasks where there is possibility of multiple correct answers.
Including examples with AI prompts clarifies our expectations and helps the AI model in providing more accurate and aligned responses.
While creating the prompts, include following example types to produce the best response possible:
- Sample data: Include a portion of text that can reflect the style, tone, and content you expect from the AI to replicate.
- Templates for documents: In order to get output of a specific structure and format, include templates with your prompt.
- Code snippets: If you need support for a programming tasks, provide some code snippet to get correct syntax and logic.
- Visual data representation: If you’re asking the AI to create similar type of graphics, share some example samples of visual data representation.
- Promotional content: If you are creating any content for your marketing needs, include product’s feature or ad copy for the AI to replicate.
♦ Example:
General Prompt: Generate a comparative analysis for different web hosting companies
Better Prompt Including Example:
Generate a comparative analysis for different web hosting companies based on their number of users, prices of the premium plans, and downtime metrics. Provide the output similar to example below:
“Company A: 100,000 users, Premium plan price $20/month, Downtime 2 hours/year”
The response from AI model should be something like:
BlueHost: Users: 100,000 Premium Plan Price: $20/month Downtime: 2 hours/year HostGator: Users: 150,000 Premium Plan Price: $25/month Downtime: 1.5 hours/year SiteGround: Users: 80,000 Premium Plan Price: $18/month with WordPress pre-installed & Free SSL certificate available Downtime: 3 hours/year N6 Cloud: Users: Not specified Premium Plan Price: Starts from INR 180/month Downtime: 99.9% average uptime Please note that some companies do not specify the number of users or exact downtime metrics. For more detailed information, you can explore the company sources directly.
4. Mention your expected output
While prompting with AI model, clearly mention the specific format and structure you need as the output. Point out whether you desire a comprehensive report, a compressed summary, bullet points, or an in-depth approach to help the AI customize its output according to your requirements.
Express any preferences regarding the tone, writing style, and the incorporation of specific elements such as headings or subheadings. By precisely outlining your preferred output, you instruct the AI to provide output that perfectly fits your desired objective.
♦ Example#1:
General Prompt:Write a project status update email template for team communication
Prompt Including Output Structure:
“Write a project status update email template for team communication. The output should be structured as different bullet points, each bullet including sections for project overview, progress updates, challenges faced, action items, and next steps.”
♦ Example#2:
General Prompt: Create a user manual document template for a software application.
Prompt Including Output Structure:
“Create a user manual document for a software application. The output should incorporate subheadings for sections on installation instructions, user interface overview, features guide, and troubleshooting tips.”
5. Apply Persona pattern in your Prompt
A Persona, also known as ‘an AI character’ or ‘role’ is a prompting approach where we instruct the AI model: ‘Act as a environment expert’ or ‘Act as a data science engineer’ or ‘Act as a doctor’. After that we ask our question. We should use this persona at the start of a chat.
AI model can remarkably improve the validity and accuracy of its response if we assign a persona in our prompt. The response will be suitable with a particular context or expertise. It will also ensure that the response generated satisfies the distinct requirements of our question.
This technique becomes very helpful in the contexts where specific domain knowledge is essential, as it instructs the AI model to apply a domain specific terminology that is relevant for the given situation. It will also ensure us that the response provided by the model comes from an expert in the respective domain.
♦ Example:
General Prompt: Explain me about Photo Synthesis process in Plant.
Prompt Using Persona Pattern:
Act as a Science Teacher. Explain me about Photo-synthesis process in plants. Consider that I am a 9-year-old student.
6. Divide complicated tasks into smaller ones
Dividing complicated tasks into smaller ones is a fundamental strategic approach in prompt engineering that helps in achieving better results and managing complexity efficiently. Here’s how it works:
- Clarity and Focus: When we break down a complicated task into smaller parts, we provide clarity and focus to the AI model. Each smaller task becomes more specific and easier for the model to understand and generate a response.
- Sequential Processing: Dividing tasks allows the AI model to process information sequentially. It can deal with one part of the task at a time and make it easier to handle and reduce the chances of information overburden.
- Modularity and Reusability: Dividing tasks into smaller ones promotes modularity and reusability of prompts and outputs. We can use smaller task components in various combinations to generate different outputs and enhance flexibility and efficiency.
- Reduced Complexity: Smaller tasks are often less complex than addressing the entire task at once. This approach reduces intellectual load for both the AI model and the user, which leads to more manageable and effective interactions.
♦ Example:
Without Using the Strategy:
“Create a marketing plan for a new product launch, including market analysis, target audience identification, promotional strategies, and budget allocation.”
Using the Strategy:
“Explain the marketing plan for a new product launch. Break down the plan into four separate tasks:
Task 1: Conduct a market analysis, including competitor research, market trends, and customer preferences.
Task 2: Identify the target audience demographics, psychographics, and buying behavior.
Task 3: Develop promotional strategies, such as advertising campaigns, social media engagement, and influencer partnerships.
Task 4: Allocate the budget for marketing activities, specifying expenses for each strategy and expected ROI.”
In the first prompt without using the strategy, the task is presented as a single comprehensive marketing plan, covering various aspects in one go. This may lead to a less focused or detailed response from the AI model.
In contrast, the second prompt using the strategy breaks down the marketing plan into four specific tasks, each addressing a distinct topic of the plan. This approach provides clarity, helps in generating more targeted responses, and ensures that all key components of the marketing plan are properly addressed.
7. Re-iterate Prompts to Refine the output
It’s essentially a loop of testing, analyzing, and improving our prompts based on the model’s responses. We start with an initial prompt, see the model’s response, and then refine the prompt based on its strengths and weaknesses. This continues until we get the desired output repeatedly. In this approach, we begin with a general prompt and gradually add details based on the model’s responses. Here are some benefits of this kind of Iterative Refinement:
- Improved Accuracy: When we analyze the model’s response, we can identify areas where it went off track and adjust our prompt to achieve greater accuracy.
- Reduced Lack of clarity: The iterative process helps us eliminate ambiguity in our prompts, ensuring the model understands our exact requirements.
- Better Control Over Output Format: Iterative refinement allows us to refine the format of the model’s output, whether it’s a specific style of writing, a structured format like a table, or a particular tone.
Here’s an example to illustrate iterative refinement:
Task: Write a short biography of Marie Curie.
Base Prompt: Write a biography of Marie Curie.
Output: Marie Curie was a scientist.
Analysis: The output is too brief. It lacks details about her achievements and contributions.
Refined Prompt: Write a short biography of Marie Curie, highlighting her pioneering work in radioactivity and her Nobel Prize wins.
Output: Marie Curie was a scientist who made significant contributions to the field of radioactivity. She was the first woman to win a Nobel Prize and the only person to win it in two different scientific fields.
Analysis: This is better, but it could be more specific about her discoveries.
Further Refined Prompt: Write a short biography of Marie Curie, focusing on her discovery of polonium and radium, and her role in developing X-ray technology during World War I.
Output: Marie Curie, a groundbreaking physicist and chemist, is most famous for her discovery of the elements polonium and radium. Her research on radioactivity revolutionized science and medicine. During World War I, she played a crucial role in developing mobile X-ray units, saving countless lives on the battlefield.
Analysis: This is a much more detailed and informative biography that addresses the specific points mentioned in the refined prompt.
Hence, if we iteratively refine our prompts, we can achieve highly specific and accurate results from models. Remember, the key is to analyze each response and identify areas for improvement. This back-and-forth process allows us to “teach” the model what we expect and get the most relevant and useful outputs for our needs.
8. Use Active Voice
Using active voice is an important best practice in prompt engineering. Let’s check why it matters and how it impacts our model’s interactions:
Active vs. Passive Voice:
-
Active Voice: In active voice, the subject performs the action of the verb. It points out who is doing what and makes the sentence clear and direct.
- Example: ” The programmer writes the code.”
-
Passive Voice: In passive voice, the subject receives the action of the verb. It can make the sentence sound more complex and mask the agent performing the action.
- Example: ” The code is written by the programmer.”
Why Active Voice Matters in Prompt Engineering?
Models are trained on massive amounts of text data, and active voice is generally more common in natural language. Here’s why using active voice benefits prompt engineering:
- Clarity: Active voice prompts are clearer and easier for the model to understand. It directly tells the model what action you want it to take.
- Focus: Active voice helps us focus on the subject and the action we desire, leading to more targeted responses.
- Efficiency: Clearer prompts lead to fewer misunderstandings and require less backwards and forwards refinement.
Examples of Active Voice in Prompt Engineering:
-
Instead of: “A blog post about the benefits of solar energy should be written.” (Passive)
-
Try: “Write a blog post explaining the benefits of solar energy for homeowners.” (Active)
-
Instead of: “It would be helpful to summarize the key findings of this research paper.” (Passive)
-
Try: “Summarize the key findings of this research paper on the impact of climate change on biodiversity.” (Active)
-
Instead of: “A creative story inspired by a robot who falls in love with a human should be generated.” (Passive)
-
Try: “Generate a science fiction story about a robot who develops emotions and falls in love with a human.” (Active)
If we use active voice, we provide clear instructions and guide the model towards the desired output. This improves the efficiency and effectiveness of our prompt engineering efforts.
9. Maintain a Neutral Tone
Maintaining a neutral tone is a key aspect of effective prompt engineering. Let’s check the details of why it matters and how to achieve it in our prompts:
Why Neutral Tone Matters?
- Unbiased Outputs: Model are trained on extensive amounts of text data, which can sometimes contain biases. Using a neutral tone in our prompts helps mitigate these biases and promotes the model to generate impartial and unbiased responses.
- Factual Accuracy: Neutral prompts keep the focus on factual information, minimizing the influence of personal opinions or emotional language that might lead to inaccurate outputs.
- Broader Applicability: Neutral prompts are more versatile. They can be used for various tasks without introducing unintended slants or interpretations.
How to Maintain a Neutral Tone?
- Avoid Loaded Language: Loaded words or phrases carry inherent biases or opinions. For example, instead of “corrupt politician,” use “politician accused of corruption.”
- Focus on Facts: Present information realistically. Instead of “the best pizza place in town,” use “a highly-rated pizzeria known for its unique toppings.”
- Use Balanced Language: When presenting opposed viewpoints, ensure both sides are represented fairly and without judgment.
- Focus on “What” Instead of “Why”: Stick to describing events or situations without assuming about motives or assigning blame. (e.g., “The company announced layoffs” instead of “The company made a ruthless decision to lay off employees.”)
Examples of Neutral vs. Non-Neutral Prompts:
Task: Write a news report about the upcoming election.
Non-Neutral Prompt: “Write a news report highlighting the clear flaws in Candidate A’s policies.”
Analysis: This prompt is biased towards Candidate B and encourages a negative description of Candidate A.
Neutral Prompt: “Write a balanced news report about the upcoming election, outlining the key policies of both Candidate A and Candidate B.”
Analysis: This neutral prompt encourages a fair and impartial report that presents both candidates’ positions without judgment.
Another Example:
Task: Describe the impact of social media on society.
Non-Neutral Prompt: “Explain how social media is destroying social interaction and creating a generation of egoists.”
Analysis: This prompt focuses on negative aspects of social media and ignores potential benefits.
Neutral Prompt: “Discuss the positive and negative impacts of social media on various aspects of society, such as communication, mental health, and information access.”
Analysis: This neutral prompt encourages a balanced discussion of both positive and negative effects of social media.
If we maintain a neutral tone in our prompts, we instruct the model towards generating unbiased, impartial, and factually accurate responses. This is crucial for tasks that require a balanced and informative approach.
10. Start Simple and Re-emphasize
“Start Simple and Re-emphasize” is a fundamental principle in effective prompt engineering. It acknowledges that writting the perfect prompt often requires a step-by-step approach, where we begin with a basic ground and gradually refine it based on the model’s response.
Let’s explore this in detail:
Why Start Simple?
- Understanding the Model: Starting simple allows us to assess the model’s capabilities for the specific task at hand. This helps us identify its strengths and weaknesses in addressing our request.
- Clarity of Thought: By starting simple, we force ourself to clearly define what we want the model to do. This clarity translates into a well-structured and focused prompt.
- Building Blocks: Simple prompts serve as building blocks for more complex ones. As we re-emphasize, we can add layers of detail and distinction based on the model’s initial response.
Re-emphasize Process:
- Create a Basic Prompt: This initial prompt should be clear and concise, outlining the desired output in its most basic form.
- Run the Prompt: Supply the prompt to the model and observe the generated output.
- Analyze the Output: This is the decisive step. Carefully evaluate the model’s response. Does it meet your expectations? Are there any issues with accuracy, relevance, or style?
- Refine the Prompt: Based on our evaluation and analysis, we should revise the original prompt. We might need to:
- Add Details or Context: If the response is lacking depth, provide more information to instruct the model.
- Provide Examples: Show the model the kind of output you’re looking for by including relevant examples.
- Adjust Phrasing: Reorganize the prompt or change the wording to improve clarity and focus.
- Specify Desired Format: Indicate if you want a specific format (e.g., bulleted list, poem, code snippet).
- Repeat: Run the revised prompt through the model and analyze the new output. If it’s not what you need, keep refining the prompt until you achieve the desired output.
Example:
Task: Write a news article about a scientific discovery.
Simple Prompt: Write a news article about a scientific discovery.
Output: “Scientists made a discovery.”
Analysis: The output is too unclear. It lacks details about what was discovered and its significance.
Refined Prompt: Write a news article about a recent progress in cancer research. Scientists have discovered a new treatment that shows promise in shrinking tumors. Include quotes from a leading researcher involved in the study.
Output: (This revised prompt might generate a more informative and specific news article about the cancer treatment discovery.)
Analysis: You can further iterate based on this new response, perhaps adding details about the type of cancer or the specific treatment method.
Also read: Quizzes on Creating Effective Prompts.