Llm Evaluation Frameworks

Production-grade guide to llm evaluation frameworks covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.

LLM evaluation frameworks are systems that automate the measurement of model performance across a set of tasks, enabling engineers to compare, tune, and validate large language models in production. They matter when a team moves beyond ad hoc prompts and manual review—when models are deployed, scaled, and iterated on continuously. Evaluation is not a one-off task; it is the foundation of model quality, model governance, and feedback-driven development.

Designing an Evaluation Pipeline

Define a standard evaluation pipeline using eval as the entry point. The core workflow is:

  1. Prepare a dataset of input–expected output pairs.
  2. Run the model on each input.
  3. Compute metrics for each prediction.
  4. Aggregate results across the dataset.
  5. Export results for reporting, debugging, and alerting.

The dataset is a JSON file with a rows array, where each row contains input, expected, and optional metadata. The evaluation runs with a config.yaml that specifies the model, inference parameters, and metric definitions.


model:
  name: "gpt-4-turbo"
  temperature: 0.3
  max_tokens: 512

metrics:
  - name: "exact_match"
    type: "string"
    reference: "expected"
    prediction: "output"
    threshold: 1.0

  - name: "f1_score"
    type: "text"
    reference: "expected"
    prediction: "output"
    average: "macro"

  - name: "latency_ms"
    type: "time"
    reference: "start_time"
    prediction: "end_time"

inputs:
  data_path: "data/squad-v2.json"
  split: "test"
  limit: 1000

The evaluation engine expects the input data to be in a standard format. Each row must have input (a string or object), expected (the ground truth), and optional metadata. The model is invoked via an HTTP endpoint using curl or a requests-style call.

curl -X POST https://api.openai.com/v1/chat/completions \
  -H "Authorization: Bearer $OPENAI_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-4-turbo",
    "messages": [
      {"role": "user", "content": "Explain the theory of relativity."}
    ],
    "temperature": 0.3,
    "max_tokens": 512
  }'

The output is parsed and matched to the expected field. Metrics are computed per row and then aggregated.

Running Evaluations at Scale

For batch evaluation, use eval run --config config.yaml --output results.json. The command reads the dataset, invokes the model for each input, collects outputs, computes metrics, and writes a structured result file.

{
  "config": {
    "model": "gpt-4-turbo",
    "temperature": 0.3,
    "max_tokens": 512,
    "metrics": ["exact_match", "f1_score"]
  },
  "results": [
    {
      "input": "What is the capital of France?",
      "expected": "Paris",
      "output": "Paris, the capital of France.",
      "metrics": {
        "exact_match": 1.0,
        "f1_score": 0.94,
        "latency_ms": 287
      },
      "metadata": { "source": "squad-v2", "index": 42 }
    },
    {
      "input": "Who wrote Hamlet?",
      "expected": "William Shakespeare",
      "output": "William Shakespear",
      "metrics": {
        "exact_match": 0.8,
        "f1_score": 0.76,
        "latency_ms": 312
      }
    }
  ],
  "summary": {
    "exact_match": 0.92,
    "f1_score": 0.84,
    "latency_ms": 298,
    "total_rows": 1000
  }
}

When the dataset grows beyond 10,000 rows, evaluation becomes a batch job. Run it via systemctl or kubectl:

# /etc/systemd/system/llm-eval.service
[Unit]
Description=LLM Evaluation Pipeline
After=network.target

[Service]
Type=simple
User=eval
WorkingDirectory=/app
ExecStart=/usr/bin/eval run --config config.yaml --output results.json
Restart=on-failure
RestartSec=10

[Install]
WantedBy=multi-user.target

The service runs daily. On failure, the job logs to /var/log/llm-eval.log, and a systemctl status llm-eval shows:

● llm-eval.service - LLM Evaluation Pipeline
   Loaded: loaded (/etc/systemd/system/llm-eval.service; enabled; vendor preset: enabled)
   Active: active (running) since Wed 2024-04-03 08:00:00 UTC; 1d 2h ago
 Main PID: 12345 (eval)
   Memory: 1.2G
   CGroup: /system.slice/llm-eval.service
           └─12345 /usr/bin/eval run --config config.yaml --output results.json

Apr 04 10:15:32 server eval[12345]: Error: Failed to load data from data/squad-v2.json: No such file or directory
Apr 04 10:15:32 server eval[12345]: Fallback: Using default dataset.
Apr 04 10:15:40 server eval[12345]: Metrics computed: exact_match, f1_score, latency_ms
Apr 04 10:15:40 server eval[12345]: Summary: exact_match=0.92, f1_score=0.84, latency_ms=298

The error No such file or directory indicates a missing data/squad-v2.json. This is silent in production: the evaluation runs, but the summary is biased by a default dataset. The root cause is a missing data/ directory in the container image.

Evaluating New Model Versions

To compare model versions, use eval compare --baseline model-v1 --candidate model-v2 --config config.yaml. This runs both models on the same dataset and computes delta metrics.

eval compare \
  --baseline "gpt-4-turbo-2024-03-01" \
  --candidate "gpt-4-turbo-2024-04-01" \
  --config config.yaml \
  --output diff-results.json

The output includes per-row differences and a summary of improvement.

{
  "baseline": {
    "model": "gpt-4-turbo-2024-03-01",
    "exact_match": 0.91,
    "f1_score": 0.83
  },
  "candidate": {
    "model": "gpt-4-turbo-2024-04-01",
    "exact_match": 0.93,
    "f1_score": 0.86
  },
  "delta": {
    "exact_match": 0.02,
    "f1_score": 0.03
  },
  "per_row": [
    {
      "input": "What is the boiling point of water?",
      "baseline_output": "100 degrees Celsius",
      "candidate_output": "100°C",
      "baseline_metrics": { "exact_match": 0.8, "f1_score": 0.75 },
      "candidate_metrics": { "exact_match": 1.0, "f1_score": 0.92 }
    }
  ]
}

A common failure: the compare command assumes the same dataset path and format, but the candidate model is evaluated on a slightly different dataset due to a misconfigured data_path. The evaluation appears to improve, but the delta is confounded by data drift.

Debugging Failed Evaluations

When evaluation fails, the first step is to examine the output file. A row with metrics missing indicates a model call failure. The output field is null, or the error field contains a structured error.

{
  "input": "Summarize the following text: ...",
  "expected": "A summary of the input text.",
  "output": null,
  "error": {
    "type": "http",
    "status": 500,
    "message": "Internal Server Error",
    "details": {
      "url": "https://api.openai.com/v1/chat/completions",
      "request_id": "req-abc123",
      "retry_after": 30
    }
  },
  "metrics": {
    "exact_match": null,
    "f1_score": null
  }
}

This indicates a model service outage. The evaluation pipeline must handle transient failures. Configure retry logic in config.yaml:

model:
  name: "gpt-4-turbo"
  temperature: 0.3
  max_tokens: 512
  retry:
    max_attempts: 3
    delay_seconds: 1
    backoff_factor: 2
    statuses: [500, 502, 503, 504]
    exceptions: ["timeout", "connection_error"]

If the model service returns 504 Gateway Timeout, the system retries the request with exponential backoff.

Custom Metrics and Advanced Evaluation

Beyond built-in metrics, define custom metrics using Python. The framework supports metric.py files that export a compute function.

# metrics/semantic_similarity.py
import numpy as np
from sklearn.metrics.pairwise import cosine_similarity

def compute(predictions, references):
    # predictions: list of strings
    # references: list of strings
    # return: list of float scores
    embeddings = embed_batch(predictions + references)
    pred_emb = embeddings[:len(predictions)]
    ref_emb = embeddings[len(predictions):]

    similarities = cosine_similarity(pred_emb, ref_emb)
    return [sim.max() for sim in similarities]

def embed_batch(texts):
    # returns list of 768-d vectors
    # uses a pre-loaded sentence-transformers model
    pass

Register the metric in config.yaml:

metrics:
  - name: "semantic_similarity"
    type: "python"
    path: "metrics/semantic_similarity.py"
    kwargs:
      model_name: "all-MiniLM-L6-v2"

The evaluation engine loads the module, calls compute(predictions, references), and includes the result in the output.

A subtle failure: the embed_batch function expects input in a specific format, but the evaluation pipeline passes raw strings. The model outputs are correct, but the metric scores are consistently low. The root cause is a mismatch in embedding preprocessing—no tokenizer.encode step. This is silent: the framework does not validate the input format.

Monitoring and Alerting

The evaluation framework outputs results in a standard format, making it easy to integrate with monitoring tools. Use psql to store results in a database.

CREATE TABLE llm_evaluation (
  id SERIAL PRIMARY KEY,
  config_hash TEXT,
  model_name TEXT,
  dataset_name TEXT,
  timestamp TIMESTAMPTZ DEFAULT NOW(),
  exact_match DOUBLE PRECISION,
  f1_score DOUBLE PRECISION,
  latency_ms DOUBLE PRECISION,
  total_rows INTEGER,
  success BOOLEAN
);

-- Insert results from JSON
COPY llm_evaluation (
  config_hash, model_name, dataset_name, exact_match, f1_score, latency_ms, total_rows, success
) FROM PROGRAM 'cat results.json | jq -r \".summary | [ .exact_match, .f1_score, .latency_ms, .total_rows, true ] | @tsv\"';

Set up alerts using systemctl or a cron job:

# /etc/cron.d/llm-eval-alerts
0 8 * * * /app/alerts.py --threshold 0.90 --metric exact_match

The alerts.py script queries the database and sends emails when metrics drop below threshold.

# alerts.py
import psycopg2
import smtplib
from email.mime.text import MIMEText

conn = psycopg2.connect("dbname=evals user=eval user=eval")
cur = conn.cursor()

cur.execute("""
  SELECT model_name, exact_match, timestamp
  FROM llm_evaluation
  WHERE timestamp > NOW() - INTERVAL '24 hours'
  ORDER BY timestamp DESC
  LIMIT 1
""")

row = cur.fetchone()
model, score, timestamp = row

if score < 0.90:
  msg = MIMEText(f"Model {model} scored {score:.3f} on exact_match, below threshold.")
  msg['Subject'] = f"LLM Evaluation Alert: {model}"
  msg['From'] = '[email protected]'
  msg['To'] = '[email protected]'

  with smtplib.SMTP('localhost') as server:
    server.send_message(msg)

Common Failures and Pitfalls

Evaluation is not a final report. It is a continuous loop of measurement, feedback, and iteration. The framework must be as robust as the model it evaluates.

This page was rewritten on 12 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.