UNIT -2
BASICS OF PROMPT ENGINEERING
1. What is Prompt Engineering?
Prompt Engineering is the practice of crafting inputs (called prompts) to guide AI models like
ChatGPT, DALL·E, or Codex to generate accurate, useful, and desired outputs.
2. Why is Prompt Engineering Important?
• Enhances response quality
• Ensures clarity and precision
• Enables task automation (summarization, coding, translation, etc.)
• Helps with creative generation (stories, designs, images)
3. Components of a Good Prompt
Component Example
Instruction "Write a summary of..."
Context "Given the following article..."
Input Data "Here is the text: ..."
Output Format "Return it as bullet points"
4. Prompt Types
Type Description Example
Zero-shot No examples provided "Translate to French: Hello"
One-shot One example provided "Translate: 'Hello' → 'Bonjour'. Now try..."
Few-shot Multiple examples provided "Translate these: 'Hi' → 'Salut', etc."
Chain-of-Thought Step-by-step reasoning "Explain your reasoning before answering"
5. Prompt Engineering Techniques
Technique Purpose Example
Be specific and clear Avoid vague wording "List 3 pros and 3 cons of AI in education"
Set constraints Control output "Reply in under 100 words"
Ask for structured output Easier to parse results "Respond in JSON format"
Use delimiters Separate sections "Text: your input Summarize it."
Break down complex tasks Improve reasoning "First list symptoms, then suggest treatment"
6. Prompt Examples
• Summarization:
“Summarize the following article in 5 bullet points.”
• Ideation:
“Generate 5 startup ideas related to eco-friendly packaging.”
• Conversation Style:
“Reply in a friendly and humorous tone.”
• Explain Like I’m 5 (ELI5):
“Explain quantum computing like I’m 5 years old.”
Types of Prompts: Declarative:
Key Characteristics
Feature Description
Direct instruction Tells the model clearly what to do
No examples required Usually zero-shot or minimal context needed
Task-focused Used for summarization, classification, etc.
Easy to understand Great for non-technical users
Examples of Declarative Prompts by Task
Task Prompt Example
Summarization "Summarize this article in bullet points."
Explanation "Explain blockchain technology in simple language."
Comparison "Compare electric cars with petrol cars."
List-making "List 10 interview questions for a data analyst role."
Classification "Label this sentence as positive, neutral, or negative."
Translation "Translate this sentence into Hindi."
Advantages
• Simple to construct
• Efficient for automation
• Easy to understand and modify
• Works well for single-purpose tasks
Limitations
• May lack context or reasoning steps
• Not ideal for multi-step or creative reasoning
• Can return generic answers if the prompt is too broad
•
Interrogative and Instruction Prompt:
Feature Interrogative Prompt Instructional Prompt
Style Question Command
Intent Ask, inquire, explore Direct, instruct, guide
Output Explanation, info, analysis Tasks, generation, steps
Example "Why is Mars red?" "List 3 facts about Mars"
Advanced Prompt Engineering Notes
Definition:
Chain-of-Thought prompting guides the model to reason step-by-step to reach a final answer,
especially useful for complex tasks like math, logic, or reasoning.
Why Use It?
LLMs often give incorrect or shallow answers to reasoning problems if asked directly. CoT
helps the model break down the task into intermediate steps, simulating human thought
processes.
Characteristics:
• Prompts include intermediate reasoning steps.
• Improves accuracy in logical or mathematical tasks.
• Can be manual or auto-generated.
• Example:
Problem:
Q: If a train travels 60 miles in 1.5 hours, what is its average speed?
Zero-shot answer:
60 / 1.5 = 40. The average speed is 40 mph.
Chain-of-Thought prompt:
Let's solve this step by step.
The total distance is 60 miles.
The total time is 1.5 hours.
Speed = Distance / Time = 60 / 1.5 = 40.
So, the average speed is 40 mph.
Use Cases:
• Math word problems
• Logical puzzles
• Multi-step decision making
• Coding explanations
2. Zero-shot Prompting
Definition:
Zero-shot prompting asks the model to perform a task without any examples in the prompt —
only a clear instruction or question is provided.
Why Use It?
• Simple and fast.
• Useful when the task is well-understood by the model or when you want to generalize.
Characteristics:
• No examples given.
• Requires very clear instructions.
• May not perform well on complex or ambiguous tasks.
Example:
Prompt:
Translate the following sentence to French: "I love learning about AI."
Response:
J'adore apprendre sur l'IA.
Use Cases:
• Straightforward tasks (translation, summarization)
• Quick one-off queries
• Tasks with limited prompt space
3. Few-shot Prompting
Definition:
Few-shot prompting provides the model with a few examples of the desired input-output format
before asking it to perform the task.
Why Use It?
This helps the model infer the pattern or logic behind the examples and generate outputs that
match the structure, style, or logic.
Characteristics:
• Uses 2–5 examples.
• Works better than zero-shot for structured or nuanced tasks.
• Helps model learn from contextual demonstration.
Example:
Prompt:
Translate English to French:
English: Hello → French: Bonjour
English: Good night → French: Bonne nuit
English: Thank you → French:
Response:
Merci
Use Cases:
• Classification
• Text transformation
• Language translation
• Writing style imitation
Feature Zero-shot Few-shot Chain-of-Thought
� Examples in Prompt ❌ None ✅ Few ✅ May include reasoning
� Complexity Handling ❌ Limited ✅ Moderate ✅✅ High
� Best For Simple tasks Pattern learning Step-by-step reasoning
� Output Accuracy Low-Medium Medium-High High
Prompt Optimization Techniques
Prompt Optimization is the process of refining your instructions (prompts) to get more
accurate, relevant, and high-quality responses from an AI model.
“The better your prompt, the smarter your model seems.”
Techniques for Prompt Optimization
1. Clarity and Specificity
Description:
Make your instructions clear, concise, and unambiguous. Avoid vague terms.
Example:
Bad Prompt:
Tell me about dogs.
Optimized Prompt:
Give a brief overview of the physical characteristics, temperament, and common health issues of
Labrador Retrievers.
Tip:
• Use precise verbs like summarize, compare, explain, translate, classify.
2. Instruction-Answer Format (Task Framing)
Description:
Clearly separate instructions from the data using labels like "Instruction:", "Input:", "Output:".
� Example:
Instruction: Translate the following sentence from English to Spanish.
Input: How are you?
Output:
3. Use Delimiters
✅ Description:
Enclose the input/output in quotes, code blocks, or other clear delimiters to avoid confusion.
� Example:
Summarize the following text:
"""
Machine learning is a subfield of AI that gives computers the ability to learn without being explicitly
programmed...
"""
4. Few-shot Examples (Demonstration)
✅ Description:
Provide a few input-output examples to help the model learn the task format.
� Example:
Correct grammar:
Incorrect: She don't like apples.
Correct: She doesn't like apples.
Incorrect: He go to school.
Correct:
5. Chain-of-Thought (Step-by-Step Thinking)
✅ Description:
Encourage the model to reason through the answer by including intermediate steps.
� Example:
Q: If a box contains 8 red balls and 12 blue balls, what fraction of the balls are red?
A: Let's think step by step.
Total balls = 8 + 12 = 20
Red balls = 8
Fraction of red balls = 8 / 20 = 2/5
6. Define the Role of the AI (Role Prompting)
✅ Description:
Assign the model a role or persona to shape its tone, knowledge, and style.
� Example:
You are a professional resume editor. Improve the grammar, structure, and tone of the following
resume summary.
7. Constrain Output Format
✅ Description:
Specify the desired structure or format of the output.
� Example:
Give the answer in bullet points, each no more than 10 words.
Or:
Provide the output as a JSON object with fields: name, age, location.
8. Ask for Self-Critique or Verification
✅ Description:
Ask the model to check its own answer or reflect before finalizing.
� Example:
Q: What is 17 * 12?
Answer: 17 * 12 = 204
Verify: Is the above correct? If not, explain and correct it.
✅ Best Practices ⏹ Avoid
Use specific task verbs Being vague or general
Provide examples (few-shot) Giving too many or unrelated ones
Ask for step-by-step reasoning Expecting LLMs to infer complex logic instantly
Define format/output constraints Leaving structure undefined
Assign roles (“You are a...”) Letting model guess your needs
Use delimiters for clarity Mixing input/output in same line
Prompt Engineering for Coding: Use Cases & Practical
Examples
Why Use Prompt Engineering in Coding?
Prompt engineering helps you:
• Write cleaner, faster code.
• Debug more efficiently.
• Understand unfamiliar codebases.
• Generate test cases, documentation, or code explanations.
• Collaborate with AI like a real-time coding assistant.
Common Use Cases in Coding
1. Code Generation
📌📌 Description:
Generate code snippets, functions, or entire modules based on plain-language descriptions.
� Example Prompt:
Write a Python function to check if a number is a palindrome.
2. Debugging Code
📌📌 Description:
Ask the model to analyze faulty code and suggest fixes.
� Example Prompt:
Here is a JavaScript function that's not returning the correct output:
```js
function add(x, y) {
return x + y + 1;
What's wrong? Suggest a fix.
#### 💡💡 Tip:
- Always describe the **bug's symptoms** and expected behavior.
---
3. Code Explanation / Commenting**
Description:
Have the model explain what a code block does, line by line or in summary.
Example Prompt:
Explain this Python code in simple terms for a beginner.
```python
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
4. Converting Code Between Languages
📌📌 Description:
Translate logic/code from one language to another (e.g., Python → Java).
� Example Prompt:
Convert the following Python code to JavaScript:
for i in range(5):
print(i)
5. Finding Algorithm or Library Suggestions
📌📌 Description:
Ask the model to recommend appropriate algorithms or libraries for a task.
� Example Prompt:
I need to sort 10 million integers fast in Python. What libraries or techniques should I use?
6. Test Case Generation
📌📌 Description:
Generate unit tests or edge cases for a given function.
� Example Prompt:
Write 5 unit tests for the following Python function using unittest.
def multiply(a, b):
return a * b
7. Code Refactoring
📌📌 Description:
Improve code readability, performance, or structure.
� Example Prompt:
Refactor this code to make it more Pythonic and efficient:
result = []
for x in range(10):
if x % 2 == 0:
result.append(x)
8. Writing Documentation
📌📌 Description:
Generate docstrings, API references, or README content for a given codebase or function.
� Example Prompt:
Write a Google-style docstring for this function:
def add(a, b):
return a + b