Production-grade guide to llm ab testing covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.
Llm Ab Testing
Llm Ab Testing is the discipline of routing user-facing LLM requests through two or more configured variants—different prompts, model selections, temperature or top-p values, or system instructions—and recording the resulting outputs to determine which variant best serves the intended purpose. It matters whenever a team has more than one reasonable way to configure an LLM call and needs a data-driven basis for choosing between them rather than relying on intuition or ad hoc observation.
The reader’s goals naturally partition the workflow. Below are the concrete steps for designing, running, and closing an LLM AB test, organized by what you’re trying to accomplish.
Before traffic splits, every variant must be identifiable and reproducible. Prompt text, model IDs, and generation parameters should be tracked in version control, not hard-coded into deployment scripts.
Prompt versioning with git
mkdir -p prompts/ab_test
cat > prompts/ab_test/v1.txt <<'EOF'
You are a senior DevOps engineer. Explain the difference between Docker and Podman in exactly three sentences.
EOF
cat > prompts/ab_test/v2.txt <<'EOF'
Act as a senior cloud architect. Compare Docker and Podman in a single, concise paragraph. Focus on security boundaries.
EOF
git add prompts/ab_test/
git commit -m "add AB-test prompt variants v1 and v2"
Model and generation-parameter flag pattern Most HTTP-based LLM services accept a small, well-known set of request parameters. The two most commonly AB-ed flags are model (which underlying engine processes the request) and temperature (which controls output randomness). A minimal curl representation of a single request looks like this:
curl -s POST https://<your-gateway>/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <your-token>" \
-d '{
"model": "<model-id>",
"temperature": 0.2,
"messages": [{"role": "user", "content": "Explain X."}]
}'
In an AB test, the same payload is emitted with a different model value or a different temperature flag. No vendor-specific config key is assumed; the pattern holds for any service that conforms to the chat-completions request shape.
Traffic splitting can be as simple as a deterministic hash-based router or as sophisticated as a feature-flag middleware. The goal is that, for any given user request, the same variant is selected consistently within a session, and the aggregate distribution matches the intended percentages.
Deterministic hash router (bash)
#!/usr/bin/env bash
# routes a request to v1 or v2 based on a hash of the user/session id
USER_ID="${1:-anonymous}"
HASH=$(echo -n "$USER_ID" | sha256sum | cut -c1-8)
PROB=$((16#$HASH % 100))
if (( PROB < 50 )); then
echo "v1"
else
echo "v2"
fi
Pass the output of this script as a variant header or query parameter downstream. Because the hash function is deterministic, the same user always sees the same variant, which is essential for reliable outcome collection.
Feature-flag middleware (prose pattern) If your platform already ships with a flag evaluator (e.g., a LaunchDarkly-compatible API, an internal Consul KV lookup, or a simple environment-variable check), drop a variant key into the flag payload:
{
"variant": "v2",
"default": "v1"
}
The middleware reads the key before the request hits the LLM gateway and injects the appropriate model or temperature value into the outgoing JSON. This keeps the routing logic out of the application code and into the config layer.
An AB test is only as good as the data it records. For each request, you need a persistent log that captures: the variant identifier, the full prompt, the model used, the generation parameters, the raw model response, and a machine-readable outcome signal.
Log a single request to PostgreSQL
CREATE TABLE llm_ab_runs (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
variant TEXT NOT NULL,
model TEXT NOT NULL,
temperature FLOAT NOT NULL,
prompt TEXT NOT NULL,
response TEXT NOT NULL,
outcome JSONB, -- free-form key-value from your success criteria
received_at TIMESTAMP WITH TIME ZONE DEFAULT now()
);
A lightweight script can post-run this after every curl invocation:
#!/usr/bin/env bash
set -euo pipefail
VARIANT="$1" # "v1" or "v2", from the router
MODEL="$2" # from the curl --data payload
TEMP="$3" # from the curl --data payload
PROMPT="$4" # raw user prompt
RESPONSE="$5" # raw model return body
OUTCOME=$(cat <<EOF
{"success": true, "length": $(echo -n "$RESPONSE" | wc -c)}
EOF
)
psql -d ai_experiments -c \
"INSERT INTO llm_ab_runs (variant, model, temperature, prompt, response, outcome) \
VALUES ('$VARIANT', '$MODEL', $TEMP, '\''$(echo "$PROMPT" | sed "s/'/''/g")'\'', '\''$(echo "$RESPONSE" | sed "s/'/''/g")'\'', '$OUTCOME'::jsonb);"
Post-run curl wrapper that logs automatically
#!/usr/bin/env bash
set -euo pipefail
VARIANT="${1:-v1}"
MODEL="${2:-gpt-4}"
TEMP="${3:-0.2}"
PROMPT="${4:-}"
# Store the raw curl body into a temp file so we can inspect it later
RESPONSE=$(mktemp)
curl -s POST https://<your-gateway>/v1/chat/completions \
-H "Content-Type: application/json" \
-H "Authorization: Bearer <your-token>" \
-d "{\"model\":\"$MODEL\",\"temperature\":$TEMP,\"messages\":[{\"role\":\"user\",\"content\":\"$PROMPT\"}]}" \
-o "$RESPONSE"
# Derive a one-line outcome metric (e.g., response length, presence of a keyword)
LEN=$(wc -c < "$RESPONSE")
OUTCOME=$(jq -n --argjson len "$LEN" '{success: ($len > 0), length: $len}')
# Push to the DB (the function from the snippet above)
./log_to_llm_ab.sh "$VARIANT" "$MODEL" "$TEMP" "$PROMPT" "$(cat "$RESPONSE")" "$OUTCOME"
# Clean up
rm -f "$RESPONSE"
Once you have a sufficient volume of rows in llm_ab_runs, the comparison step is a matter of aggregating the outcome column per variant and looking for consistent differences. The pattern is generic SQL; no p-values or percentages are prescribed.
Aggregate outcome per variant
SELECT
variant,
COUNT(*) AS total,
avg((outcome->>'length')::float) AS avg_length,
bool_and((outcome->>'success')::bool) AS all_successful
FROM llm_ab_runs
GROUP BY variant
ORDER BY variant;
If a variant consistently yields higher avg_length while keeping all_successful true, that’s a data-backed signal. If the rows overlap heavily (same avg_length, same all_successful distribution), the test is inconclusive and should be extended or redesigned.
Export for external analysis
psql -d ai_experiments -c \
"\copy (SELECT * FROM llm_ab_runs) TO '/tmp/ab_results.csv' WITH (FORMAT csv, HEADER true)"
The CSV can then be opened in a spreadsheet or fed into a BI tool of your choosing. The database export is the only artifact you control; everything after that uses tools you already run.
Tie the entire flow into your CI/CD pipeline so that a new prompt version or model flag triggers a test run, records results, and blocks a release if the new variant underperforms on a pre‑defined criterion.
GitHub Actions example (prose)
name: LLM AB Test
on:
push:
paths:
- 'prompts/ab_test/**'
jobs:
run-test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Install deps
run: pip install psycopg2-binary jq
- name: Run AB test iteration
env:
DB_URL: ${{ secrets.DB_URL }}
GATEWAY_TOKEN: ${{ secrets.GATEWAY_TOKEN }}
run: python scripts/run_ab_iteration.py
- name: Fail if new variant loses
run: |
# script exits non-zero if the new variant's avg_length
# is more than 10% worse than the control's
./scripts/check_ab_threshold.py
The check_ab_threshold.py script reads the latest CSV export, computes the per-variant averages, and exits with status 1 if the hypothesis “variant 2 improves response length without sacrificing success” is not met. This keeps the AB test in the merge gate, where rollback is free and the next iteration can start immediately.
temperature differently: a value of 0.7 may produce near‑deterministic output on one engine and highly creative output on another. Always pair a model change with a re‑calibrated temperature range, or lock temperature across variants if you’re comparing models.psql insert or the jq post‑processing can fail with malformed input or invalid escape errors. Sanitize both prompt and response strings (e.g., sed "s/\n/\\n/g" before insertion) before they hit the database.outcome column is flexible but makes cross‑run comparison brittle. Define a minimal schema for outcome (e.g., always include success: boolean and at least one numeric metric) and enforce it in the insert script. Without that, you’ll spend downstream time guessing which keys exist.An LLM AB test is a loop: define variants → split traffic → capture structured outcomes → compare → iterate. The concrete tools—git for prompt versioning, curl for request emission, psql for logging, jq for lightweight parsing, and a CI step for gatekeeping—are all off‑the‑shelf and vendor‑agnostic. Drop them into your existing workflow, define your success criteria as a tiny JSON shape, and you’ll have a repeatable experiment framework without needing to invent new CLI flags or vendor‑specific config keys.
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.
We use cookies for analytics (Google Analytics) and advertising (Google AdSense) to improve your experience and support free content. Privacy Policy