Prompt Best Practices
Earn 25 points (50 with Pro) in two steps
- ① Read through the lesson — each section gets a ✓ as you scroll through it.
- ② When every section has a ✓, tap Complete lesson.
0 of 11 read · keep scrolling
✦ See fewer ads and earn double points — 50 a lesson instead of 25 — with Pro
Lesson: Prompt Best Practices
Introduction: The Art of Communicating with AI
In the evolving landscape of technology, prompt engineering has emerged as a fundamental skill for anyone interacting with Large Language Models (LLMs). At its core, a prompt is simply the instruction, question, or context you provide to an AI model to elicit a specific response. While it might seem intuitive to treat these models like human assistants, they operate based on probabilistic patterns, mathematical weights, and massive datasets. Understanding how to craft effective prompts is the difference between receiving a generic, unhelpful answer and obtaining a precise, actionable output that solves a complex problem.
Why does this matter so much? Because AI models are "force multipliers" for human cognition. When you provide a vague, poorly constructed prompt, you force the model to guess your intent, which often leads to "hallucinations"—confidently stated but factually incorrect information—or overly broad responses that require significant cleanup. Conversely, when you master prompt best practices, you minimize wasted time, reduce the need for iterative corrections, and unlock the full potential of these tools to perform tasks ranging from coding and data analysis to creative writing and strategic planning.
This lesson is designed to move you beyond basic trial-and-error. We will explore the structural elements of a high-quality prompt, examine the psychological and technical frameworks that make prompts work, and discuss how to refine your interactions to achieve consistent, high-quality results. By the end of this module, you will have a toolkit of techniques to guide AI models with precision, clarity, and intent.
Not read yet
The Anatomy of a Perfect Prompt
A prompt is not just a sentence; it is a container for information. If you think of a prompt as a request for a service, you need to provide the AI with the same level of detail you would provide a junior analyst or a new team member. The most effective prompts generally contain four core components: the Role, the Task, the Context, and the Constraint.
1. The Role (Persona)
Assigning a persona to an AI model helps anchor its response in a specific domain. When you tell an AI to act as a "Senior Python Developer," it adjusts its internal probability weights to favor technical terminology, clean code structures, and common industry practices.
2. The Task
The task is the explicit instruction of what you want the model to do. It should be a clear, imperative statement. Avoid ambiguous verbs like "help with" or "look at." Instead, use "write," "summarize," "analyze," "refactor," or "generate."
3. The Context
Context provides the "why" and the "how." This includes background information, the target audience, the desired tone, and any reference material the model should use to formulate its answer. Without context, the model defaults to a generic median of the internet, which is rarely what you need for specific professional work.
4. The Constraint
Constraints define the boundaries of the output. This could involve word counts, specific formatting (like JSON or Markdown), language requirements, or specific things to avoid (e.g., "do not use jargon"). Constraints are your primary tool for quality control.
Callout: The "Instructional Gap" The instructional gap is the distance between what you think you asked for and what you actually communicated to the model. Most poor AI outputs are not the result of a "dumb" model, but rather an instructional gap where the user assumed the model possessed context that was never provided. By explicitly stating your constraints and background, you bridge this gap and drastically increase the likelihood of success.
Not read yet
Iterative Refinement: The Prompt Lifecycle
Rarely is the first prompt the best prompt. Professional prompt engineering is an iterative process. You should view your interaction with an AI as a dialogue where you refine the output based on the feedback the model provides.
Step-by-Step Refinement Process
- Draft the Initial Request: Start with your core question or task. Keep it direct but be prepared for a generic response.
- Analyze the Output: Evaluate the response critically. Did it miss a specific point? Is the tone wrong? Is the format unusable for your needs?
- Identify the Missing Element: Determine which part of the prompt was deficient. Did the model lack enough context? Did it ignore a constraint? Was the role not clearly defined?
- Update and Re-prompt: Modify the prompt by adding the missing information or clarifying the instructions. You can often do this by saying, "That was good, but please rewrite it focusing more on [X] and keep the tone more [Y]."
- Standardize: Once you reach an ideal output, save that prompt structure as a template for future use.
Note: When refining, it is often better to start a new chat thread if the context has drifted significantly. AI models have a "context window," and while they can remember previous turns, long, messy threads can sometimes confuse the model or cause it to prioritize earlier, less relevant instructions over new ones.
Not read yet
Practical Examples and Code Snippets
To understand these concepts, let’s look at how to transform a weak prompt into a strong, effective one.
Example 1: Writing Code
Weak Prompt: "Write a script to scrape a website." This is too vague. The model doesn't know which website, what data to extract, or what language to use.
Strong Prompt: "Act as a Senior Web Scraper Developer. I need a Python script using the BeautifulSoup library to extract the product titles and prices from a sample e-commerce site.
- Input: The URL is https://example-store.com/products.
- Output: Save the data into a CSV file named 'products.csv'.
- Constraint: Include error handling for connection timeouts and ensure the script respects the robots.txt file by adding a delay between requests."
Code Implementation:
import requests
from bs4 import BeautifulSoup
import csv
import time
def scrape_products(url):
# Adding a delay to be polite to the server
time.sleep(2)
try:
response = requests.get(url)
response.raise_for_status()
soup = BeautifulSoup(response.text, 'html.parser')
# Logic for extraction
products = []
# Assume specific classes based on the site structure
for item in soup.select('.product-card'):
name = item.select_one('.title').text.strip()
price = item.select_one('.price').text.strip()
products.append({'name': name, 'price': price})
return products
except Exception as e:
print(f"Error occurred: {e}")
return []
# Execution
data = scrape_products("https://example-store.com/products")
# ... (Code to write to CSV)
Example 2: Summarization
Weak Prompt: "Summarize this document." The model might provide a summary that is too long, too short, or misses the key business implications.
Strong Prompt: "Act as a Business Consultant. Summarize the provided meeting transcript in three bullet points.
- Focus: Highlight the key decisions made and the action items assigned to the engineering team.
- Tone: Professional and concise.
- Format: Use a Markdown table for the action items, including columns for 'Task', 'Assignee', and 'Deadline'.
- Transcript: [Paste text here]"
Not read yet
Common Pitfalls and How to Avoid Them
Even with the best intentions, users often fall into traps that degrade AI performance. Being aware of these will save you hours of frustration.
1. The "Leading Question" Trap
When you ask a question in a way that implies a specific answer, the AI is likely to agree with you, even if you are wrong. This is known as "sycophancy."
- Avoid: "Why is [X] the best way to solve this problem?"
- Prefer: "What are the pros and cons of using [X] to solve this problem, and are there better alternatives?"
2. Overloading the Prompt
While context is good, dumping 50 pages of irrelevant information into a prompt can lead to "lost in the middle" phenomena, where the model ignores the information in the middle of your prompt.
- Tip: Be concise. If you have a large document, use RAG (Retrieval-Augmented Generation) techniques or summarize the document first before asking the model to perform a task on it.
3. Neglecting Output Format
If you need the data for a database or an application, do not just ask for "a list."
- Avoid: "Give me a list of users."
- Prefer: "Return the user data in JSON format with the keys: 'id', 'name', 'email', and 'role'."
4. Ignoring Negative Constraints
Models are notoriously bad at "not" doing things. Simply saying "Don't mention X" often results in the model mentioning X because it is thinking about it.
- Strategy: Instead of telling the model what not to do, tell it what to do. Instead of "Don't be verbose," use "Be concise and limit the response to 100 words."
Not read yet
Comparison: Prompting Strategies
Depending on the complexity of your task, you should choose the right prompting strategy. Here is a breakdown of common approaches:
| Strategy | When to Use | Example |
|---|---|---|
| Zero-Shot | Simple, well-defined tasks. | "Translate this text to Spanish." |
| Few-Shot | When you need a specific style or format. | Provide 3 examples of a style, then ask for the 4th. |
| Chain-of-Thought | Complex logic or math problems. | "Think step-by-step to solve this equation." |
| Delimiters | When providing large blocks of text. | Use """ or --- to separate instructions from source text. |
Callout: The Power of Few-Shot Prompting Few-shot prompting is one of the most underutilized techniques. By providing the model with a few examples of "Input: A, Output: B," you essentially "program" the model's behavior. This is far more effective than trying to describe a complex tone or format in abstract terms. If you want a specific output style, just show the model what you want.
Not read yet
Best Practices Checklist for Professionals
To maintain high standards, keep this checklist available when crafting your prompts:
- Be Explicit: Never assume the model knows your intent. Define the role, task, and constraints clearly.
- Use Delimiters: Use punctuation or headers to separate different parts of your prompt (e.g., "Use the text delimited by triple backticks below to answer the question").
- Ask for Reasoning: If the task involves logic, ask the model to "explain your reasoning before providing the final answer." This reduces errors significantly.
- Iterate: Treat the first result as a draft. Use follow-up prompts to refine the output.
- Verify: Always fact-check the output. AI models can hallucinate, especially with dates, names, and technical citations.
- Keep it Modular: If you have a massive task, break it into smaller sub-tasks. Ask the AI to draft an outline, then fill in each section one by one.
Not read yet
Advanced Technique: Chain-of-Thought Prompting
When you ask an AI to solve a complex problem immediately, it tries to predict the final answer based on the statistical likelihood of the next token. This often leads to errors in logic. Chain-of-Thought (CoT) prompting forces the model to articulate its internal process before reaching a conclusion.
Example of CoT: User: "If I have 10 apples, give 2 to my neighbor, buy 5 more, and then eat half of what I have, how many apples are left?"
Weak Response (Direct): "You have 6.5 apples." (The model might miscalculate the sequence.)
Strong Response (CoT): "Let's think step-by-step.
- Starting amount: 10.
- Give 2 to neighbor: 10 - 2 = 8.
- Buy 5 more: 8 + 5 = 13.
- Eat half: 13 / 2 = 6.5. The final result is 6.5."
By forcing the model to show its work, you allow yourself to spot where the logic might have failed, and you significantly increase the accuracy of the final output.
Not read yet
Handling Ambiguity and Edge Cases
There will be times when a prompt is inherently ambiguous. As an expert user, you should anticipate these moments. If a prompt could be interpreted in two ways, the model will pick the most statistically likely one, which might not be yours.
How to handle it:
- Provide Options: "If the document contains [X], do [A]. If it contains [Y], do [B]."
- Ask for Clarification: If you are building an automated system, include a instruction like: "If you are unsure about any part of this request, ask me a clarifying question before proceeding."
- Define Default Behavior: "If you cannot find the requested information in the source text, state clearly that the information is missing rather than guessing."
The Role of System Prompts
If you are using an API or a custom GPT, you will encounter the "System Prompt." This is the highest-level instruction that governs the model's behavior across the entire conversation. Unlike standard user prompts, the system prompt acts as the "constitution" for the AI.
Best Practices for System Prompts:
- Define Personality: "You are a helpful, objective financial advisor."
- Define Boundaries: "Never provide legal or medical advice."
- Define Formatting Defaults: "Always provide responses in Markdown format with headers."
- Define Style: "Use plain, accessible language and avoid corporate jargon."
When you set these rules at the system level, you don't have to repeat them in every individual message, allowing your user prompts to remain focused entirely on the specific task.
Not read yet
Common Questions and Troubleshooting
Q: Why is the AI ignoring my instructions?
A: Often, the model is paying more attention to its internal training data than to your prompt. Try moving your most important instructions to the very beginning or the very end of the prompt. Models tend to prioritize the "recency" of information.
Q: How do I get the AI to stop being so repetitive?
A: You can explicitly tell it: "Avoid repeating information. If you have already stated a point, do not rephrase it later in the response."
Q: Why does the AI sound so robotic?
A: You can adjust the tone by adding a style guide to your prompt. Example: "Write in a conversational, human-like tone. Use short sentences, avoid passive voice, and use analogies to explain complex concepts."
Q: Is there a limit to how long a prompt can be?
A: Yes, every model has a "context window." If your prompt is too long, the model will "forget" the beginning. If you have a massive amount of data, summarize it first or use a model with a larger context window.
Not read yet
Best Practices for Data Privacy and Security
While this lesson focuses on prompt engineering, we must address the professional reality of data security.
- Sanitize Input: Never input sensitive, proprietary, or personally identifiable information (PII) into a public-facing AI model. If you need to analyze sensitive data, ensure you are using an enterprise-grade version of the model that guarantees your data is not used for training.
- Anonymize Data: If you must use a public model, replace real names, addresses, or specific financial figures with placeholders (e.g., "[CLIENT_NAME]", "[DOLLAR_AMOUNT]").
- Verify Compliance: Always check your organization’s AI usage policy before interacting with LLMs regarding company-specific projects.
Summary and Key Takeaways
Prompt engineering is not about "tricking" the model; it is about clear, precise communication. By treating the AI as a highly capable but literal-minded assistant, you can move from basic interactions to sophisticated workflows.
Key Takeaways:
- Structure Matters: Always include a Role, Task, Context, and Constraints to minimize the instructional gap.
- Iterate for Excellence: View your prompt as a draft. Use the AI's output to refine your instructions until you reach the desired result.
- Show, Don't Just Tell: Use "Few-Shot" prompting by providing examples to guide the model toward the specific style, format, or logic you require.
- Force Reasoning: Use Chain-of-Thought prompting for complex tasks to ensure the model follows a logical path rather than just guessing the output.
- Use Delimiters: Use clear separators like triple quotes or headers to help the model distinguish between instructions and the data it needs to process.
- Prioritize Constraints: Be specific about what you want to achieve, and avoid negative instructions (e.g., "don't do X") in favor of positive ones (e.g., "do Y instead").
- Maintain Security: Never share sensitive or proprietary information with public models. Always sanitize your inputs to protect organizational and personal data.
By internalizing these practices, you will significantly improve your efficiency and the quality of the work you produce with AI. Remember that the goal is not to replace your own expertise, but to use these tools to augment your capabilities, allowing you to focus on the high-level strategy and creative decision-making that only humans can provide. Start applying these techniques to your daily tasks, and you will quickly see how much more capable these models become when they are guided by a skilled prompt engineer.
Not read yet
Each section gets a ✓ as you scroll through it. Tap the button to jump to the next one.
- Agent Mode and Edit Mode
- Agent Mode and Edit Mode Quiz5q
- MCP Integration
- MCP Integration Quiz5q
- Code Review with Copilot
- Code Review with Copilot Quiz5q
- Spaces and Spark Features
- Spaces and Spark Features Quiz5q
- Pull Request Summaries
- Pull Request Summaries Quiz5q
- Custom Instructions Files
- Custom Instructions Files Quiz5q
Spend your points to unlock exam-style practice questions
Spend points to unlock GH-300 exam-style practice questions.
Practice for GH-300