Skip to content

Prompt Optimization for LLM: Methods, Metrics, and Automation

Cover: Prompt Optimization for LLM: Methods, Metrics, and Automation Prompt optimization is the process of improving the quality of LLM responses through changes in formulation, structure, and context. Unlike one-time prompt writing, optimization involves an iterative cycle: measurement, analysis, change, and re-measurement. In this article, I will explain how to set up this process in practice: which metrics to use, which methods yield the most impact, and how to automate optimization.

Why Prompt Optimization is Needed

A prompt is an interface to the model. Even small changes in formulation can significantly affect the quality of the response. Optimization allows: - Increase accuracy and relevance of responses; - Reduce errors and hallucinations; - Decrease token usage through shorter prompts; - Improve consistency of responses for the same queries. Without a systematic approach, prompts often remain 'as they are'—they work on test examples but break on real data. More on the basic principles in the guide on system prompts and the review of prompting techniques.

Metrics for Evaluating Prompts

Before optimizing, you need to learn how to measure. I use the following metrics: | Metric | What it measures | How to calculate | |--------|-----------------|------------------| | Accuracy | Proportion of correct answers | Comparison to a benchmark | | F1-score | Balance of precision and recall | For classification | | BLEU / ROUGE | Lexical similarity | For text generation | | Answer Relevancy | Relevance of the answer | LLM-as-a-Judge | | Faithfulness | Alignment with facts | LLM-as-a-Judge | | Token Efficiency | Token usage | Average number of tokens per request | For most tasks, I use a combination: automatic metrics for quick checks and an LLM judge for semantic evaluation. It's important that the test set is representative and does not contain leaks. More on metrics in the article on LLM evaluation metrics.

Optimization Methods

I distinguish several levels of optimization: 1. Changing formulations. Replacing ambiguous words, adding context, clarifying instructions. 2. Structuring the prompt. Dividing into sections, using markdown, explicitly indicating the response format. 3. Adding examples. Few-shot examples often improve quality. More on few-shot. 4. Changing generation parameters. Temperature, top-p, max tokens. See temperature and top-p. 5. Using prompt chains. Breaking down complex tasks into simpler ones. See prompt chaining. In practice, the greatest effect comes from a combination of structuring and adding examples. Changing temperature usually affects diversity but not accuracy.

Automating Optimization

Manual optimization is a labor-intensive process. I automate it with scripts that: - Generate prompt variants (e.g., using the LLM itself); - Run each variant on a test set; - Calculate metrics; - Select the best variant. Example of a simple Python script:

import openai

def evaluate_prompt(prompt, test_cases):
    correct = 0
    for case in test_cases:
        response = openai.ChatCompletion.create(
            model="gpt-4",
            messages=[{"role": "system", "content": prompt}, {"role": "user", "content": case["input"]}]
        )
        if response.choices[0].message.content == case["expected"]:
            correct += 1
    return correct / len(test_cases)

# Generation of variants, evaluation, selection of the best
For versioning prompts, I use the approach described in the guide on prompt versioning practices.

Common Mistakes

During optimization, I often encounter mistakes: 1. Overfitting to the test set. A prompt that works perfectly on test data may fail on real data. I always keep a separate validation set. 2. Ignoring cost. Complicating the prompt increases token usage. I calculate cost per request. 3. Too frequent changes. If you change the prompt every day, it's hard to understand what exactly influenced the result. I document changes and conduct A/B tests. 4. Lack of baseline. You need to compare with the original prompt, not just between variants.

Conclusion

Prompt optimization is an iterative process based on measurements. Start with defining metrics and a test set, then try different methods, document results, and gradually improve. Automation helps speed up the process but does not replace analysis. Useful materials: system prompt, context engineering, prompt caching.