LESSON 25 Β· PROMPT ENGINEERING

Prompt Optimization

Learn how to improve prompts systematically instead of changing words randomly. Define a target, test a prompt, measure the result, and keep the changes that actually improve quality, consistency, cost, or latency.

30 min read β€’ Intermediate β€’ Generative AI

By the end of this lesson, you will be able to:

  • Explain what prompt optimization means in an AI application.
  • Define measurable criteria for prompt quality.
  • Build a small evaluation dataset for prompt experiments.
  • Improve prompts using controlled iterations with Python.
  • Balance answer quality against tokens, latency, and complexity.
1

What Is Prompt Optimization?

Prompt optimization is the process of improving a prompt so that an AI application performs better on the task it is designed to solve.

β€œBetter” needs to be defined. Depending on the application, you may care about correctness, consistency, format compliance, helpfulness, safety, cost, or response time.

RANDOM EDITING

Change words until it feels better

Try a longer instruction.
Try a different adjective.
Try another example.
Looks better β†’ ship it.

This does not tell you whether the change actually improved the application.

OPTIMIZATION

Change β†’ test β†’ measure

Baseline prompt
      ↓
Test dataset
      ↓
Measure results
      ↓
Change one thing
      ↓
Compare again

This creates evidence for deciding which prompt version to keep.

Core idea: A prompt is an engineering artifact. Treat improvements as experiments, not guesses.
2

Start With a Clear Optimization Goal

Before changing a prompt, decide what you are trying to improve. A prompt cannot be β€œbetter” in the abstract.

AccuracyMore correct answers or classifications.
ConsistencySimilar inputs follow the same rules.
FormatResponses follow the required structure.
CostFewer unnecessary input or output tokens.
LatencyLess work and faster responses.
SafetyFewer unwanted or unsafe behaviors.
Example: If your support classifier is already 96% accurate but frequently returns invalid labels, optimize for output compliance firstβ€”not for a longer explanation.
3

Create a Baseline Prompt

Your first tested version is the baseline. Every later version should be compared against it using the same evaluation conditions.

Prompt v1 Baseline
Classify the customer message.

Categories:
- billing
- shipping
- technical
- account

Return the category.

Message:
{message}

Save the prompt text, model settings, test inputs, outputs, and evaluation results. Without a baseline, you cannot confidently say that a change helped.

4

Build an Evaluation Dataset

A small evaluation dataset is a collection of inputs with expected outcomes. It lets you compare prompt versions fairly.

InputExpectedReason
β€œI was charged twice.”billingDuplicate payment
β€œTracking has not changed.”shippingDelivery status
β€œThe app crashes on login.”technicalSoftware problem
β€œI cannot reset my password.”accountAccount access
Keep test inputs unseen: If every evaluation example appears inside the prompt, you may be measuring imitation of the demonstrations rather than general performance.
5

Measure More Than β€œLooks Good”

Choose metrics that match your task. For classification, accuracy and invalid-output rate may be useful. For extraction, field-level correctness matters. For generation, a human or model-based rubric may be needed.

Correctness9 / 10Expected answer achieved
Format10 / 10Required shape followed
Consistency9 / 10Stable across inputs
CostLowPrompt remains efficient
Prompt quality
88%
6

Change One Important Thing at a Time

If you replace the instruction, add five examples, change the output format, and change the model at the same time, you will not know which change caused the result.

V1BaselineInstruction only
β†’
V2Add constraintReturn one label only
β†’
V3Add examplesThree representative cases

Controlled changes make prompt optimization easier to debug and explain to other developers.

7

Improve the Prompt in Layers

A useful optimization sequence is to remove ambiguity before adding complexity.

01Clarify the taskWhat exactly should the model do?
02Add useful contextWhat information does it need?
03Add constraintsWhat boundaries matter?
04Define outputWhat should the response look like?
05Add examplesOnly when examples solve a real ambiguity.
8

Before and After: Optimize a Classifier

V1 Β· BEFORE
Classify this message.

Message:
"I need to change my email."

Category boundaries and output format are not explicit.

V2 Β· AFTER
TASK:
Classify the message.

CATEGORIES:
billing, shipping, technical, account

RULES:
- Choose exactly one category.
- Use only the supplied message.
- Return the category in lowercase.
- Do not add extra text.

MESSAGE:
"I need to change my email."

OUTPUT:

The optimized version reduces ambiguity and makes the output contract explicit.

9

Python Example: Compare Prompt Versions

A simple evaluation loop can compare two prompt versions on the same test inputs.

</> Python Prompt experiment
from openai import OpenAI

client = OpenAI()

test_cases = [
    ("I was charged twice.", "billing"),
    ("My tracking has not changed.", "shipping"),
    ("The app crashes.", "technical"),
    ("I cannot reset my password.", "account"),
]

prompt_v1 = """
Classify the message as billing, shipping, technical, or account.
Return the category.

Message:
{message}
"""

prompt_v2 = """
TASK:
Classify the message.

CATEGORIES:
billing, shipping, technical, account

RULES:
- Choose exactly one category.
- Return only the lowercase category.
- Do not add an explanation.

MESSAGE:
{message}

OUTPUT:
"""

def classify(template, message):
    response = client.responses.create(
        model="YOUR_MODEL",
        input=template.format(message=message),
    )
    return response.output_text.strip().lower()

for name, template in [("v1", prompt_v1), ("v2", prompt_v2)]:
    correct = 0

    for message, expected in test_cases:
        prediction = classify(template, message)

        if prediction == expected:
            correct += 1

    accuracy = correct / len(test_cases)
    print(name, accuracy)
Experiment: Keep the test cases identical between V1 and V2. Then compare accuracy, invalid outputs, prompt length, and latency.
10

Optimize Few-shot Examples Too

Prompt optimization also applies to demonstrations. More examples can improve coverage, but they consume context and may add latency and cost.

SET A

5 examples

Accuracy: 92%

Prompt: 480 tokens

SET B

3 examples

Accuracy: 92%

Prompt: 310 tokens

SET C

1 example

Accuracy: 84%

Prompt: 180 tokens

Optimization decision: If Set B reaches the same accuracy as Set A with fewer tokens, Set B may be the better production prompt.
11

Watch for Prompt Regressions

An optimization can fix one case while breaking another. This is a prompt regression.

BEFORE 96% overall Shipping edge cases: 90%
β†’
AFTER 97% overall Shipping edge cases: 72%

The overall score improved, but an important subgroup became worse. Keep separate checks for critical categories and edge cases rather than relying only on one aggregate number.

12

Optimize for Quality, Cost, and Latency

Production prompt optimization is usually a trade-off. A longer prompt may improve quality but increase token usage. A shorter prompt may be cheaper but less reliable.

Quality ↑More context or examples can help.
Tokens ↓Remove repetition and unnecessary text.
Latency ↓Reduce unnecessary input and output.
Reliability ↑Use explicit rules and validation.
Production goal Best useful result β€” not the longest prompt
13

Prompt Optimization in Production

Once a prompt is used by real users, optimization becomes an ongoing engineering process.

Version promptsKeep V1, V2, V3 so changes are traceable.
Log outcomesTrack useful quality signals and failures.
Maintain testsRun regression cases after prompt changes.
Review failuresTurn recurring failures into new evaluation cases.
Roll back safelyDo not make an untested prompt change irreversible.
PRACTICE

Optimize a Support Prompt

Start with this prompt:

Classify the customer message as billing, shipping, technical, or account.
Return the category.

Message:
{message}
β‘  Define the task β‘‘ Add category rules β‘’ Control the output β‘£ Create 8 test cases β‘€ Compare V1 and V2 β‘₯ Check cost and consistency
Challenge: Improve the prompt without adding unnecessary paragraphs. Your goal is a measurable improvement, not simply a longer prompt.
QUICK QUIZ

Test yourself

1. What should you define before optimizing a prompt?

The goal and the metric you want to improve, such as correctness, consistency, format, cost, or latency.

2. Why keep a baseline prompt?

It gives you a fixed version against which later prompt changes can be compared.

3. Why should evaluation inputs stay the same when comparing versions?

Changing the test set makes it difficult to tell whether the prompt change caused the difference.

4. Can a prompt optimization improve one metric while hurting another?

Yes. For example, a longer prompt may improve accuracy while increasing token usage and latency.

30-Second Recap

  • Prompt optimization is systematic improvement, not random rewriting.
  • Define what β€œbetter” means before changing the prompt.
  • Use a baseline and an evaluation dataset.
  • Change important variables in a controlled way.
  • Watch for regressions in edge cases.
  • Optimize the complete trade-off between quality, cost, latency, and reliability.

Key Takeaways

  • A good prompt should solve a measurable application problem.
  • Evaluation turns prompt engineering into an engineering workflow.
  • Shorter is not always better, and longer is not always better.
  • Examples, constraints, context, and output rules should each earn their place.
  • Production prompts need versioning, regression tests, and ongoing review.