1. Home
  2. Blog
  3. Artificial Intelligence

Artificial Intelligence

What Is Prompt Engineering? Techniques, Examples and Common Mistakes

Better prompts are less about magic phrases and more about clear instructions. Learn the core techniques with before-and-after examples, then see how to test a prompt instead of guessing whether it works.

9 min read
What is prompt engineering? Techniques, examples and common mistakes

Key takeaways

  • Prompt engineering is the practice of writing instructions that get useful, reliable results from AI models.
  • Most improvements come from being clear about the task, context, output format and limits.
  • Examples (few-shot prompting) and prompt chaining are the techniques worth learning first.
  • Test prompts against a set of real cases, because one good answer proves very little.

Two people can ask the same AI model for the same thing and get answers of very different quality. The difference is often the prompt. Prompt engineering is the skill of closing that gap, and you do not need a machine learning background to learn it.

This guide explains the techniques that matter most, with prompts you can adapt. The examples work as patterns with most large language models (LLMs), though each model behaves differently, so try them on the one you use. Output described here is illustrative and not a guarantee of what a model will produce.

What is prompt engineering?

A prompt is the input you give to a generative AI model. Prompt engineering is the process of designing and refining that input so the output is accurate, relevant and in a form you can use. It covers the wording of your request, the background you supply, the examples you include and the way you break work into steps.

A helpful way to think about it: imagine briefing a very capable new colleague who knows a great deal in general but nothing about your project, your audience or your standards. If you say “write something about our release”, you will get something generic. If you give them the audience, the facts and the length, you will get something much closer to what you need.

Why prompts matter

An LLM generates text by predicting what is likely to come next, based on patterns learned from training data and whatever you provide. It does not read your mind, and it will usually fill any gap in your request with a plausible assumption. Vague prompts therefore do not fail loudly. They produce something that looks fine but may be wrong for your situation.

This matters more when AI is built into a product. In a chat, you can simply ask again. In an application, a prompt runs thousands of times without anyone watching, so small weaknesses become repeated errors.

Anatomy of a good prompt

Most strong prompts contain some combination of these parts. You rarely need all of them, but it helps to check for each.

Part Question it answers Example
Role Who should the model act as? You are a senior QA engineer.
Task What exactly should it do? Write test cases for this login form.
Context What does it need to know? Accounts lock after five failed tries.
Input What data should it work on? The requirement text, clearly marked.
Format How should the answer look? A table with ID, steps and expected result.
Constraints What are the limits? At most ten cases. Do not invent features.

Before and after

Here is a weak prompt:

Write test cases for login.

It leaves everything open: which login, what rules, how many cases and what format. Here is the same request with those gaps filled:

You are a senior QA engineer.

Write test cases for the login form described below.

Requirements:
- Email and password are both required.
- The account locks after 5 failed attempts within 15 minutes.
- "Forgot password" sends a reset link.

Output a table with the columns: ID, Scenario, Steps, Expected result.
Cover positive, negative and boundary cases, with at most 10 rows.
If a requirement is unclear, list your question below the table
instead of guessing.

The second version is longer, but it needs fewer retries. Asking the model to raise questions rather than guess is especially useful, since it surfaces missing information. If you want to judge the result, our guide on how to write test cases explains what good ones look like.

Core prompt engineering techniques

Zero-shot prompting

You give an instruction with no examples. This is the simplest method and is fine for common tasks such as summarising or translating. Start here, and add more only if the results fall short.

Few-shot prompting

You show a few examples of the input and output you want, and the model follows the pattern. This is often the quickest way to get a consistent format or tone, because showing is clearer than describing.

Classify the sentiment of each review as positive, negative or mixed.

Review: "Fast delivery and great quality."
Sentiment: positive

Review: "It broke after two days."
Sentiment: negative

Review: "Lovely design, but the battery is poor."
Sentiment: mixed

Review: "Setup was painful, though support fixed it quickly."
Sentiment:

Choose examples that cover tricky cases rather than only easy ones, and vary them so that the model does not copy an accidental pattern.

Asking for step-by-step reasoning

Known as chain-of-thought prompting, this asks the model to work through a problem before giving its final answer. It tends to help with maths, logic and multi-step decisions.

A plan costs 800 per month, or 8,000 per year paid upfront.
A customer expects to stay for 11 months. Which is cheaper?
Work through the calculation first, then give the answer
on a final line starting with "Answer:".

The reasoning also gives you something to check, but do not treat it as a perfect record of how the model reached its answer. Verify important results independently.

Role prompting

Assigning a role, such as “You are a technical editor”, can shift tone, vocabulary and focus. It does not give the model knowledge it lacks, so a role is no substitute for supplying the facts.

Providing context

If an answer depends on your documents or data, paste them in and tell the model to rely on them. Systems that do this automatically, by retrieving relevant documents before each request, are known as retrieval-augmented generation (RAG). A good instruction is: “Answer using only the text below. If the answer is not there, say you do not know.” This reduces made-up answers, although it does not remove the risk.

Specifying the format

State exactly what structure you want. If your code will read the result, ask for JSON and show the shape:

Extract the details from this email. Return only JSON:
{"name": string, "order_id": string, "issue": string}
Use null for anything that is missing.

Email: """
{email_text}
"""

Using delimiters such as triple quotes separates your instructions from the data. Many APIs also offer structured output modes that enforce a schema, and these are more reliable than asking in words alone. Always validate the output in your code anyway.

Prompt chaining

Instead of one giant prompt, break the work into steps, feeding each output into the next. For example, to answer a long customer complaint: first extract the facts, then classify the issue, then draft a reply using those results. Each step is simpler, easier to test and easier to fix when something goes wrong.

Iteration

Your first prompt is a draft. Read the output, work out what is wrong and change one thing at a time. If the answer is too long, set a limit. If it misses a case, add an example. Changing one thing at a time tells you what actually helped.

Prompts for developers

Coding assistants respond well to the same principles. Share the error, the relevant code, your language and version, and what you have already tried.

This Python 3.13 function should return orders from the last 7 days,
but it also returns older ones.

[paste function and one failing example]

First explain the cause in two sentences.
Then show the smallest fix. Do not refactor anything else.

Review generated code just as you would a colleague’s. Run it, read it and add tests. Our guide to unit vs integration testing is a good reference, and a clear description of the problem, as in a good bug report, improves AI answers as much as human ones.

How to test a prompt

One impressive answer does not mean a prompt works. Models can vary between runs, and a prompt tuned on one input can fail on the next. Treat prompts more like code: collect real examples, define what a correct answer is, and measure.

Here is a minimal evaluation script. You supply call_model, a function that sends text to whichever model you use and returns its reply.

PROMPT = """Classify this support ticket as billing, technical or other.
Reply with one word only.

Ticket: {ticket}"""

CASES = [
    ("I was charged twice this month", "billing"),
    ("The app crashes when I log in", "technical"),
    ("Do you have an office in Pune?", "other"),
]

def evaluate(call_model):
    passed = 0
    for ticket, expected in CASES:
        answer = call_model(PROMPT.format(ticket=ticket)).strip().lower()
        ok = answer == expected
        passed += ok
        print("PASS" if ok else "FAIL", "|", ticket, "->", answer)
    print(f"{passed}/{len(CASES)} passed")

We checked this script with a fake model that always gets the third case wrong, and it reported 2/3 passed, so failures show up clearly. In real use, add many more cases, including awkward ones, and run the set several times. Rerun it whenever you change the prompt or upgrade the model. For free-form answers where exact matching is impossible, score with a checklist or human review.

Tip: Keep production prompts in version control alongside your code. Then you can review changes, roll back a bad one and see which prompt produced which results.

Prompt injection and limits

If your application passes user text or web content to a model, that text may contain instructions such as “ignore your previous rules”. This is called prompt injection, and no prompt wording fully prevents it. Treat model output as untrusted, give the model only the permissions it needs, and require human approval for sensitive actions such as sending money or deleting data.

Also keep in mind that models can state false information with confidence, and their knowledge may be out of date. Check facts, figures and citations, and do not paste confidential data into a tool unless your organisation has approved it.

Common mistakes

  • Being vague. “Make it better” gives the model nothing to aim for. Say what better means.
  • Overloading one prompt. Five tasks at once lead to uneven results. Chain them instead.
  • Trusting without checking. The more an answer matters, the more you need to verify it.
  • Never measuring. Without test cases, you cannot tell if a change helped or just looked better once.

Final thoughts

Prompt engineering is mostly clear communication plus a habit of testing. Take one task you repeat every week and write a proper prompt for it, covering the task, context, format and constraints. Add two or three examples, try it on several real inputs and keep what works. A small library of tested prompts will serve you better than any list of tricks.

Frequently asked questions

What is prompt engineering in simple words?

It is writing clear instructions for an AI model and improving them until you get the results you need, reliably and in a useful format.

Do I need to code to learn prompt engineering?

No. Anyone can practise with a chat tool. Coding becomes useful when you build prompts into applications or test them at scale.

What is the difference between zero-shot and few-shot prompting?

Zero-shot prompting gives only an instruction. Few-shot prompting includes a few input and output examples, so the model can follow the pattern you show.

Is prompt engineering still a useful skill?

Yes. Models keep improving and need fewer tricks, but they still cannot guess your goals. Clear instructions, good context and testing remain valuable.

Why does the same prompt give different answers?

Most models use some randomness when generating text. Lower temperature settings, where available, reduce variation but may not remove it, so test prompts more than once.

Keep learning

Work with Stack Quora

Need help with testing, WordPress or SEO?

We help teams ship better software and grow their sites. Tell us what you are working on and we will suggest a clear next step.

Keep reading

More guides on testing, AI & modern development

Enjoyed this article? Pick a topic and jump straight into our newest tutorials.

Artificial Intelligence

LLM Structured Output Explained: Getting Reliable JSON From AI Models

LLM structured output explained with validation we ran in Pydantic: JSON mode and schemas, constrained decoding, the ways model output…

Read article →
DevOps

SSH Keys Explained: How They Work, ssh-keygen, Ed25519 and Safe Habits

SSH keys explained with keys we generated: public vs private keys, ssh-keygen, Ed25519 vs RSA, fingerprints, passphrases, ssh-agent, authorized_keys, config…

Read article →
DevOps

HTTP Caching Explained: Cache-Control, ETag and 304 Responses, With a Live Test

HTTP caching explained with a small server we ran: Cache-Control directives, max-age, no-cache vs no-store, ETag revalidation and 304 responses,…

Read article →
Test Automation

API Contract Testing Explained: Catch Breaking Changes Before They Ship

API contract testing explained with a schema check we ran: what a contract is, consumer-driven contracts, Pact, OpenAPI, which changes…

Read article →
Software Testing

Risk-Based Testing Explained: Score Risks, Build a Matrix and Test What Matters

Risk-based testing explained step by step: identifying risks, scoring likelihood and impact, building a risk matrix, mapping risk to test…

Read article →
Databases & SQL

SQL Constraints Explained: NOT NULL, UNIQUE, CHECK and FOREIGN KEY, Tested

SQL constraints explained with tests we ran: NOT NULL, UNIQUE, CHECK, DEFAULT, PRIMARY and FOREIGN KEY, the NULL loopholes, SQLite's…

Read article →
Databases & SQL

SQL Date Functions Explained: Adding, Comparing and Grouping Dates Without Bugs

SQL date functions explained with queries we ran: adding intervals, month-end surprises, date differences, the BETWEEN trap, grouping by day,…

Read article →
Software Development

Python asyncio Explained: async, await, gather and TaskGroup With Real Timings

Python asyncio explained with code we timed: coroutines, await, gather, TaskGroup, error handling, timeouts, limiting concurrency and the blocking-call mistake…

Read article →
Software Development

Debounce vs Throttle in JavaScript: How They Work, When to Use Each, Tested

Debounce vs throttle in JavaScript explained with timings we measured in Node.js: how each works, simple implementations, leading and trailing…

Read article →
Software Development

Python Context Managers Explained: The with Statement, contextlib and Real Uses

Python context managers explained with code we ran: how with works, __enter__ and __exit__, contextlib.contextmanager, suppress, ExitStack, database transactions and…

Read article →
Artificial Intelligence

LLM Temperature and Top-p Explained: How AI Models Choose Their Next Word

LLM temperature and top-p explained with a simulation we ran: how probabilities are reshaped, what top-p keeps, recommended settings by…

Read article →
DevOps

YAML Explained: Syntax, the Norway Problem and Other Traps We Tested

YAML explained with a parser test: basic syntax, lists and maps, the Norway problem, versions turning into floats, octal zip…

Read article →
DevOps

Cron Jobs Explained: Syntax, Real Schedules and the Mistakes That Break Them

Cron jobs explained with schedules we verified: the five fields, operators, real examples, the day-of-month OR day-of-week trap, environment problems,…

Read article →
Software Testing

Bug Life Cycle in Software Testing: Every Status, Who Owns It and Common Mistakes

The bug life cycle explained: every defect status from New to Closed, who owns each step, rejected, deferred and reopened…

Read article →
Test Automation

Property-Based Testing in Python: Hypothesis Finds the Bugs Your Examples Miss

Property-based testing explained with Hypothesis tests we ran: properties vs examples, strategies, shrinking, the real bugs it found in our…

Read article →
Databases & SQL

SQL Pagination Explained: OFFSET vs Keyset, With a Million-Row Test

SQL pagination explained with a million-row test we ran: LIMIT and OFFSET, why deep pages get slow, keyset (cursor) pagination,…

Read article →
Databases & SQL

SQL EXISTS vs IN: Differences, the NOT IN NULL Trap and Performance

SQL EXISTS vs IN explained with queries we ran: how each works, why NOT IN returns no rows when a…

Read article →
Software Development

Python Logging Explained: Levels, Handlers, Formatters and Mistakes to Avoid

Python logging explained with code we ran: levels, basicConfig quirks, named loggers, handlers and formatters, logger.exception, lazy formatting, duplicate logs…

Read article →
Software Development

JavaScript Map vs Object: Key Differences, Pitfalls and a Benchmark

JavaScript Map vs Object explained with code we ran in Node.js: key types, ordering, the prototype trap, JSON, size, WeakMap…

Read article →
Software Development

Python Type Hints Explained: Annotations, mypy and the Errors It Catches

Python type hints explained with a real mypy run: basic annotations, Optional and unions, TypedDict, Literal, Protocol, generics, Callable, strict…

Read article →
Artificial Intelligence

LLM Tokens Explained: How AI Models Read Text, Count Costs and Fill Context Windows

LLM tokens explained with a tokenizer we ran: how text is split, why counts differ by language and tokenizer, context…

Read article →
DevOps

Semantic Versioning Explained: MAJOR.MINOR.PATCH, Ranges and Release Rules

Semantic versioning explained with code we ran: MAJOR.MINOR.PATCH rules, pre-releases, correct version sorting, caret and tilde ranges, 0.x versions, lockfiles…

Read article →
DevOps

Git Reset vs Revert: How to Undo Commits Safely, With a Tested Example

Git reset vs revert explained with a repository we built: soft, mixed and hard reset, revert commits, reverting merges, recovering…

Read article →
Software Testing

The Test Pyramid Explained: Layers, Ratios and When to Break the Shape

The test pyramid explained: unit, integration and end-to-end layers, sensible ratios, the ice cream cone anti-pattern, the testing trophy and…

Read article →
Test Automation

pytest Fixtures Explained: Scope, yield Teardown, conftest.py and Factories

pytest fixtures explained with a suite we ran: how fixtures work, scopes, yield teardown, conftest.py, factory fixtures, parametrized fixtures, built-ins…

Read article →
Databases & SQL

SQL Upsert Explained: INSERT ON CONFLICT, MERGE and the REPLACE Trap

SQL upsert explained with queries we ran: INSERT ON CONFLICT DO UPDATE and DO NOTHING, the excluded row, conditional updates,…

Read article →
Databases & SQL

SQL LIKE Operator Explained: Wildcards, Case Sensitivity and Performance

The SQL LIKE operator explained with queries we ran: % and _ wildcards, escaping, NOT LIKE and NULL, case sensitivity…

Read article →
Artificial Intelligence

AI Hallucinations Explained: Why Language Models Make Things Up and How to Reduce It

AI hallucinations explained: what they are, why language models produce them, common types, how to reduce them with grounding and…

Read article →
Test Automation

Mocking in Python: unittest.mock, patch and the Mistakes That Make Tests Lie

Mocking in Python with unittest.mock, tested: Mock and return_value, side_effect, patching where a name is used, spec and autospec, mocking…

Read article →
Software Testing

Code Coverage Explained: Line vs Branch Coverage and What 100% Really Means

Code coverage explained with a real coverage.py run: line, branch and condition coverage, reading a report, why 100% coverage can…

Read article →
Artificial Intelligence

What Are AI Agents? How They Work, With a Simple Agent Loop You Can Run

What are AI agents? A plain guide to the agent loop, tools, memory and guardrails, with a small Python loop…

Read article →
Test Automation

TDD vs BDD: Key Differences, One Feature Built Both Ways and When to Use Each

TDD vs BDD explained with one discount feature built both ways: red-green-refactor with code we ran, Given-When-Then scenarios, tools, trade-offs…

Read article →
Software Testing

User Acceptance Testing (UAT): Process, Checklist and Real Examples

User acceptance testing explained: who runs it, how it differs from QA, a seven-step process, a UAT test case template,…

Read article →
Artificial Intelligence

What Are Embeddings? Vectors and Cosine Similarity Explained Simply

What are embeddings? A plain-language guide to vectors, cosine similarity and semantic search, with a small example we ran, common…

Read article →
Test Automation

Flaky Tests: What Causes Them and How to Fix Them for Good

Flaky tests explained with demos we ran: the main causes, how to confirm and diagnose one, proper fixes for timing,…

Read article →
Software Testing

Load Testing vs Stress Testing: Differences, Metrics and k6 Examples

Load testing vs stress testing explained: what each proves, spike and soak tests, the metrics that matter, why averages mislead,…

Read article →