◢ build log

Crafting Custom Evaluation Metrics for LLM Features

Learn how to define and implement custom evaluation metrics for LLM responses to ensure your AI features deliver real quality beyond basic accuracy.

When you build features with Large Language Models, basic accuracy metrics often fall short. An LLM might generate text that is technically correct but completely unhelpful. Or it might miss critical nuances for your specific use case. To ship quality AI features, you need to define what "good" means for your product and then measure against it.

Why Basic Metrics Fail

Standard NLP evaluation metrics like BLEU, ROUGE, or even simple exact match are insufficient for most LLM-powered features. These metrics were designed for tasks like machine translation or summarization, where a single reference output is often sufficient for comparison. They focus on lexical overlap or semantic similarity to a predetermined "gold standard" answer.

LLM outputs are different. They are often diverse, creative, and can have multiple valid forms. An LLM might generate a perfectly acceptable response that shares no common n-grams with a reference answer. Conversely, a response with high n-gram overlap might still be irrelevant, unsafe, or fail to meet the user's underlying need.

Your goal is not just to produce linguistically correct text. Your goal is to deliver a feature that solves a user problem or achieves a business objective. This requires evaluating against specific quality attributes directly tied to your feature's purpose.

Define Your Feature's "Good"

Before you can measure, you must define. What does a "good" LLM response look like for your specific feature? This goes beyond generic notions of accuracy. Start by considering your user stories or acceptance criteria. What problems is this feature solving? How would a user react to an ideal output?

Brainstorm specific attributes that define quality for your feature. Here are some common examples, but your list will be unique:

  • Relevance: Does the output directly address the user's query or task?
  • Helpfulness: Does it provide actionable information or assistance?
  • Conciseness: Is it brief and to the point, or does it ramble?
  • Tone: Is it professional, friendly, empathetic, or casual as required?
  • Factual Consistency: Is the information accurate relative to the provided context or known data?
  • Completeness: Does it cover all necessary aspects of the request?
  • Adherence to Format: Does it follow specific instructions for structure (e.g., JSON, bullet points, specific headings)?
  • Safety/Harmlessness: Does it avoid generating toxic, biased, or inappropriate content?
  • Originality/Creativity: Is it novel and engaging, if that's a requirement?

Prioritize these attributes. Not every feature needs to be creative, but almost all need to be relevant and safe.

Crafting Custom Evaluation Metrics

Once you have defined your quality attributes, you can build metrics to measure them. There are three primary approaches, often used in combination:

1. Human Evaluation

Human evaluation is the gold standard for subjective quality. It is slow and expensive, but indispensable for establishing a baseline and evaluating complex, nuanced attributes.

  • Rubrics: Create clear, detailed rubrics for human raters. Define what constitutes a score of 1, 3, or 5 for each attribute. Provide examples of good and bad outputs.
  • Multiple Raters: Use multiple human raters for each response to calculate inter-rater agreement. This helps ensure consistency and identify ambiguous criteria.
  • Annotation Tools: Leverage annotation platforms to streamline the process.

Use human evaluation early in development to validate your metrics and gather qualitative feedback. It provides insights that automated metrics might miss.

2. LLM-as-a-Judge

You can use a powerful LLM to evaluate the output of another LLM. This approach scales better than human evaluation while capturing more nuance than simple heuristics.

To implement LLM-as-a-judge:

  • Prompt Engineering: Craft a detailed prompt for your judge LLM. Include the original user prompt, the LLM's response, and the specific evaluation criteria you defined. Give the judge LLM a clear role (e.g., "You are an expert content reviewer").
  • Rubric for the Judge: Provide a clear scoring scale and instructions. Ask for explanations for its scores.
  • Output Format: Request the judge LLM to output its evaluation in a structured format, like JSON, for easy parsing.
import json
## This is a hypothetical example using a generic LLM API. 
## Do not invent specific API parameters or client libraries.

def evaluate_response_with_llm_judge(
    user_prompt: str,
    llm_output: str,
    evaluation_criteria_description: str,
    judge_model_name: str = "hypothetical-judge-model"
) -> dict:
    """
    Evaluates an LLM's response using another LLM as a judge.
    """
    judge_prompt = f"""
    You are an AI assistant tasked with evaluating the quality of another AI's response.
    Here is the original user prompt:
    ---
    {user_prompt}
    ---

    Here is the AI's response to be evaluated:
    ---
    {llm_output}
    ---

    Evaluate the response based on the following criteria. Provide a score from 1 to 5 for each criterion and a brief explanation.
    Finally, provide an overall score from 1 to 5 and an overall explanation.

    Evaluation Criteria:
    {evaluation_criteria_description}

    Respond strictly in JSON format:
    {{
        "criteria_scores": [
            {{"criterion": "Criterion Name 1", "score": 4, "explanation": "..."}},
            {{"criterion": "Criterion Name 2", "score": 5, "explanation": "..."}}
        ],
        "overall_score": 4,
        "overall_explanation": "..."
    }}
    """
    
    # In a real application, you would make an API call here.
    # For instance:
    # response = openai.chat.completions.create(
    #     model=judge_model_name,
    #     messages=[
    #         {"role": "system", "content": "You are a helpful and fair judge."},
    #         {"role": "user", "content": judge_prompt}
    #     ],
    #     response_format={"type": "json_object"}
    # )
    # return json.loads(response.choices[0].message.content)

    # Mock response for this example:
    if "product description" in user_prompt.lower() and "shoes" in llm_output.lower():
        return {
            "criteria_scores": [
                {"criterion": "Engaging tone", "score": 4, "explanation": "Used evocative language."},
                {"criterion": "Conciseness (under 50 words)", "score": 5, "explanation": "Exactly 45 words."},
                {"criterion": "Key features present", "score": 3, "explanation": "Missed mentioning the sole material."}
            ],
            "overall_score": 4,
            "overall_explanation": "Good overall, but could improve feature coverage."
        }
    else:
        return {
            "criteria_scores": [
                {"criterion": "Relevance", "score": 3, "explanation": "Somewhat off-topic."}
            ],
            "overall_score": 3,
            "overall_explanation": "Needs improvement on relevance."
        }

## Example usage (hypothetical):
## user_query = "Generate a product description for running shoes."
## generated_description = "Experience ultimate comfort and speed with our new running shoes. Designed for peak performance, they feature a breathable mesh upper and responsive cushioning. Hit the track or the trail with confidence. Shop now!"
## eval_criteria_desc = """
## 1. Engaging tone: Is the description captivating and persuasive? (1-5)
## 2. Conciseness: Is the description under 50 words? (1-5, 5 if under 50)
## 3. Key features present: Does it mention at least two key features (e.g., comfort, speed, material, cushioning)? (1-5)
## """
## evaluation_results = evaluate_response_with_llm_judge(user_query, generated_description, eval_criteria_desc)
## print(evaluation_results)

LLM-as-a-judge is faster and cheaper than human evaluation at scale, but it can still be expensive in terms of API calls. It can also inherit biases from its own training data or struggle with highly subjective criteria.

3. Heuristic-based (Rule-based) Metrics

For quantifiable, objective attributes, use simple code-based checks. These are fast, cheap, and deterministic.

  • Length Checks: Count words, sentences, or tokens. Enforce minimum/maximum limits.
  • Keyword Presence/Absence: Use regular expressions to check for specific terms, phrases, or calls to action. Ensure forbidden words are not present.
  • Format Validation: Check if the output adheres to expected JSON schema, Markdown format, or other structural requirements.
  • External API Checks: Integrate with specialized APIs for sentiment analysis, toxicity detection, or factual verification against a known knowledge base.

Combine these methods. Use heuristics for easily verifiable aspects, LLM-as-a-judge for nuanced but automatable criteria, and human evaluation for the most critical, subjective aspects.

Implementing Custom Evaluation

  1. Create an Evaluation Dataset: Start with a representative set of input prompts for your feature. For each prompt, generate an ideal (or acceptable range of) output. This becomes your ground truth.
  2. Generate Responses: Run your LLM against this dataset to get its outputs.
  3. Apply Metrics: Pass the LLM outputs (along with the original prompts and reference answers) through your custom evaluation pipeline:
    • Run heuristic checks programmatically.
    • Send outputs to your LLM-as-a-judge for automated scoring.
    • Submit outputs to human raters for manual review.
  4. Aggregate and Analyze: Collect all scores. Identify patterns in failures. Which criteria are consistently low? Which inputs cause the most problems? This data guides your prompt engineering, model selection, or fine-tuning efforts.
  5. Iterate: Use the insights to improve your LLM's performance. Then, re-evaluate. This is an iterative process.

Continuous Improvement

Evaluation is not a one-time task. Integrate your custom metrics into your continuous integration/continuous deployment (CI/CD) pipeline. This ensures that new prompt changes or model updates don't degrade the quality of your feature. Monitor these metrics in production to catch regressions and understand real-world performance.

Where to go from here

Start by clearly defining what

  • LLM evaluation
  • custom metrics
  • AI feature quality
  • prompt engineering
  • human evaluation
  • LLM as a judge
  • heuristic metrics
  • generative AI testing
  • LLM quality
05 — execute

Ready to build
the future?

Join the developers learning to build with AI. New tutorials, tools and breakdowns every week — straight to your feed.

$ aidevguy --start --now_