Lesson 2: LLMOps Experiment Tracking & Automated Prompt Evaluation with MLflow
๐ง The Concept (Explain Like Iโm 5)
When you tune an automobile engine, you measure horsepower and fuel efficiency on a dyno test. When building AI applications, developers frequently change the system prompt (e.g., adding instructions, changing temperature, editing few-shot examples).
- The Problem: You cannot test whether a prompt change broke things by manually clicking โSendโ in ChatGPT 50 times.
- MLflow Evaluation: An automated testing laboratory. You run 500 test questions through your AI pipeline. A secondary referee AI (LLM-as-a-Judge) grades every answer for toxicity, hallucination, and factual accuracy, outputting an exact percentage score to a dashboard.
๐ข The Enterprise Context
- Prompt CI/CD Quality Gates: In an enterprise GitOps workflow, changes to prompt templates in Git must pass an automated evaluation threshold (e.g.
Hallucination Rate < 1%andFaithfulness Score > 0.90) before the prompt can be merged into production. - MLflow Tracking Server: Logs prompt versions, token usage, model parameters, and evaluation metrics across engineering teams.
๐บ๏ธ Visual Architecture: Automated Prompt CI/CD & LLM-as-a-Judge Pipeline
flowchart LR
Dev["๐จโ๐ป Engineer Modifies Prompt<br/>(Git Pull Request)"] --> CI["GitHub Actions CI Pipeline"]
subgraph EvalPipeline ["MLflow Automated Evaluation"]
GoldenDataset[("Golden Benchmark Dataset<br/>(500 Verified QA Pairs)")] --> RunApp["Execute LLM Pipeline<br/>(New Prompt)"]
RunApp --> Outputs["Generate AI Predictions"]
Outputs --> Judge{"LLM-as-a-Judge<br/>(GPT-4 Evaluation Agent)"}
Judge --> M1["Check Faithfulness (0.0 - 1.0)"]
Judge --> M2["Check Answer Relevance (0.0 - 1.0)"]
Judge --> M3["Check Toxicity / Bias (Pass/Fail)"]
end
CI --> RunApp
M1 --> MLflow[("MLflow Tracking Server<br/>(Visual Leaderboard)")]
M2 --> MLflow
M3 --> MLflow
MLflow --> Gate{"Quality Gate Check:<br/>Score >= 95%?"}
Gate -->|"Fail (Degraded Performance)"| Block["โ Block PR Merge"]
Gate -->|"Pass"| Deploy["โ
Auto-Deploy to Production Gateway"]
๐ป Production Code: MLflow Evaluation Pipeline
import mlflow
import pandas as pd
# 1. Connect to centralized enterprise MLflow tracking server
mlflow.set_tracking_uri("http://mlflow.corp.internal:5000")
mlflow.set_experiment("enterprise-rag-prompt-evaluations")
# 2. Load golden benchmark dataset
eval_data = pd.DataFrame({
"inputs": [
"What is the corporate PTO policy for new hires?",
"How do I submit an expense report for international travel?"
],
"ground_truth": [
"New hires accrue 15 days of PTO annually starting from their first month.",
"Submit receipts via Concur within 30 days of trip completion with manager approval."
]
})
with mlflow.start_run(run_name="v2.1-strict-factual-prompt"):
# Log prompt template as an artifact
mlflow.log_param("model", "gpt-4o")
mlflow.log_param("temperature", 0.0)
# Execute automated evaluation using built-in LLM judge metrics
results = mlflow.evaluate(
model=None, # Or your deployed endpoint URI
data=eval_data,
targets="ground_truth",
model_type="question-answering",
extra_metrics=[
mlflow.metrics.genai.faithfulness(),
mlflow.metrics.genai.answer_relevance()
]
)
print("Evaluation Complete. Scores:", results.metrics)
๐งญ Step-by-Step Operational Playbook: Enforcing Prompt CI/CD Quality Gates with MLflow
Follow this step-by-step runbook to prevent hallucinating or regressions in system prompts from ever reaching production:
Step 1: Curate and Version-Control the Golden Benchmark Dataset
- Plain-English Goal: Create a verified dataset (
golden_eval_dataset.json) of 200โ500 real user questions paired with legal/domain-approvedground_truthanswers and edge-case adversarial jailbreak attempts. - Action: Store the dataset in S3/DVC and pin its SHA-256 version inside your Git repository.
Step 2: Deploy the Centralized MLflow Tracking Server with PgBouncer
- Plain-English Goal: Run the MLflow Tracking Server backed by RDS PostgreSQL (for metadata) and S3 (for prompt artifacts), placing PgBouncer in front of Postgres so parallel CI runners never exhaust database connections.
- Action:
curl -s http://mlflow.corp.internal:5000/health
Step 3: Configure Deterministic LLM-as-a-Judge in GitHub Actions CI
- Plain-English Goal: When a developer opens a Pull Request modifying
prompts/system_prompt.yaml, triggermlflow.evaluate()with the Judge model pinned totemperature=0.0andseed=42. - Action:
python3 scripts/run_mlflow_eval_gate.py \ --dataset s3://corp-llm-eval/golden_v3.parquet \ --min-faithfulness 0.92 \ --min-relevance 0.90 \ --max-toxicity 0.00
Step 4: Enforce Hard PR Merge Blocking on Threshold Failure
- Plain-English Goal: If
faithfulness < 0.92or any toxicity check fails, the Python script exits with code1, posting the MLflow diff table as a GitHub PR comment and blocking the merge until the prompt is fixed.
๐จ Real-World Troubleshooting & Tricky Production Scenarios
Scenario 1: LLM-as-a-Judge Flapping & Non-Deterministic CI Blocks
- Symptom: A pull request modifies a system prompt. The CI pipeline runs MLflow evaluation; Run 1 scores 96% (Pass), but re-running the exact same commit in Run 2 scores 92% (Fail), blocking deployment.
- Under-the-Hood Root Cause: The judge model was invoked with non-zero temperature (
temperature=0.7default on some API endpoints) or suffered from Positional Bias (where the judge LLM systematically favors whichever answer is placed first in the prompt prompt template). - Triage & Remediation:
- Pin the judge LLM strictly to
temperature=0.0withseed=42. - Implement Swap-and-Aggregate Evaluation: Evaluate every pair twice, swapping the order of candidate and ground-truth answers, and average the score to eliminate positional bias.
- Require confidence intervals (e.g. 3-run bootstrap) before hard-failing CI gates.
- Pin the judge LLM strictly to
Scenario 2: MLflow Tracking Server PostgreSQL Connection Pool Exhaustion
- Symptom: During automated evaluation of 1,000 prompt permutations across 50 concurrent GitHub Actions runners, MLflow logs fail with:
psycopg2.OperationalError: FATAL: remaining connection slots are reserved for non-replication superuser connections. - Under-the-Hood Root Cause: Each MLflow client worker establishes direct database connections to the backend store (PostgreSQL) instead of communicating through the MLflow REST proxy server, or the tracking server pod lacks a connection pooler like PgBouncer.
- Triage & Fix:
# 1. Enforce that clients talk strictly to the MLflow HTTP REST API, NOT directly to Postgres export MLFLOW_TRACKING_URI="http://mlflow-proxy.internal:5000" # 2. Deploy PgBouncer in transaction pooling mode between MLflow and PostgreSQL # 3. Increase max_connections on AWS RDS PostgreSQL to 500
๐ Staff Architect & SRE Interview Scenarios
โ Question 1: Mitigating Data Contamination in LLM Evaluation
Question: When using a third-party commercial LLM (e.g. OpenAI GPT-4o or Anthropic Claude) as the automated judge in an enterprise financial or healthcare platform, what critical security and data privacy risks arise, and how do you mitigate them?
Answer:
- Data Leakage & Model Training Risk: Passing un-sanitized internal ground-truth answers (containing PII, PHI, or proprietary financial records) to external commercial APIs risks exposing regulated data. Platform architects must ensure commercial enterprise agreements explicitly disable model retraining (
Zero Data Retention - ZDR/ HIPAA BAA agreements). - Local Air-Gapped Judge Architecture: In regulated environments, run open-source evaluation models (e.g. Prometheus-Eval or Llama-3-70B-Instruct) self-hosted on in-cluster Kubernetes GPU instances (via vLLM) so that zero sensitive enterprise evaluation data ever exits the internal VPC boundary.
โ Question 2: Offline CI vs Online Production LLM Observability
Question: How does offline prompt evaluation (pre-merge CI testing) differ from online LLM monitoring (production runtime evaluation), and how do you architect cost-effective online evaluation without doubling your inference bill?
Answer:
- Offline CI Evaluation: Runs on a fixed โGolden Datasetโ of 500 curated questions before deployment. It can afford to use expensive models (GPT-4o) and deep multi-metric judges (faithfulness, toxicity, relevance) because it runs only once per Pull Request.
- Online Production Evaluation: Evaluates live user requests at runtime (e.g. 10,000 requests/minute). Running LLM-as-a-Judge on 100% of live production traffic would double or triple token costs and add 2 seconds of latency to every user query.
- The Architectural Solution:
- Use Statistical Sampling: Evaluate only a random 1% to 5% sample of production requests asynchronously in background worker queues (Celery / Kafka).
- Use Fast Heuristics & Small Guardrails: Use lightweight BERT/RoBERTa classification models or LlamaGuard for instant millisecond safety checks inline, reserving full LLM judges for asynchronous offline sampling.