advanced · 10 menit baca
Prompt Testing & Evaluation
Metode sistematis untuk menguji dan mengukur kualitas prompt
Introduction
Prompt yang terlihat bagus belum tentu menghasilkan output konsisten. Testing dan evaluation adalah proses sistematis untuk memvalidasi bahwa prompt bekerja reliably across different inputs, edge cases, dan use cases.
Tanpa testing, Anda tidak tahu apakah prompt gagal karena instruksi buruk, konteks kurang, atau model limitation. Lesson ini membahas framework untuk menguji prompt secara objektif.
Mengapa Testing Penting?
Masalah Tanpa Testing
Skenario umum:
- Prompt bekerja untuk happy path, gagal untuk edge cases
- Output konsisten untuk input pendek, chaos untuk input panjang
- Format output berubah-ubah tanpa pola jelas
- Biaya token membengkak di production
Benefit Testing Sistematis
- Konsistensi — output predictable untuk berbagai input
- Cost control — deteksi token waste sebelum production
- Quality baseline — ukuran objektif untuk iterasi
- Regression prevention — perubahan prompt tidak break existing behavior
Framework Evaluation
1. Define Success Criteria
Sebelum testing, tentukan metrik sukses yang measurable.
| Technique | When to Use | Token Cost | Quality | Complexity |
|---|---|---|---|---|
| Accuracy | Output harus factually correct | Low | High | Medium |
| Format Compliance | Output harus match struktur spesifik | Low | Medium | Low |
| Completeness | Output harus cover semua requirement | Medium | High | Medium |
| Consistency | Output harus sama untuk input serupa | Medium | High | High |
| Token Efficiency | Cost optimization penting | High | Medium | Low |
2. Build Test Dataset
Test dataset harus representatif dari real-world usage.
Struktur test dataset:
Test Case 1: Happy path (input normal, expected output jelas)
Test Case 2: Edge case (input ekstrem: sangat pendek/panjang)
Test Case 3: Ambiguous input (input yang bisa diinterpretasi berbeda)
Test Case 4: Invalid input (input yang seharusnya ditolak)
Test Case 5: Boundary condition (input di batas constraint)
Before
45 tokensTest dengan 3 contoh: input pendek, input panjang, input dengan typoAfter
78 tokensTest dataset (10 cases):
- 3 happy path (berbagai domain)
- 3 edge cases (empty, 5000 chars, special chars)
- 2 ambiguous (bisa diinterpretasi 2+ cara)
- 2 invalid (missing required field, wrong format)3. Automated Testing
Manual testing tidak scalable. Automate dengan script sederhana.
Contoh test script (pseudocode):
const testCases = [
{ input: "...", expectedFormat: "JSON", expectedFields: ["name", "age"] },
{ input: "...", expectedFormat: "JSON", expectedFields: ["name", "age"] }
];
testCases.forEach(test => {
const output = runPrompt(test.input);
// Check format
assert(isValidJSON(output), "Output must be valid JSON");
// Check fields
const parsed = JSON.parse(output);
test.expectedFields.forEach(field => {
assert(field in parsed, `Missing field: ${field}`);
});
// Check token usage
const tokens = countTokens(output);
assert(tokens < 500, `Token limit exceeded: ${tokens}`);
});
Metode Evaluation
A/B Testing
Bandingkan 2 versi prompt untuk menentukan mana yang lebih baik.
Setup A/B test:
- Variant A: prompt saat ini (baseline)
- Variant B: prompt baru (candidate)
- Metric: pilih 1-2 metrik utama (accuracy, token cost)
- Sample size: minimal 50 test cases per variant
- Statistical significance: gunakan t-test atau chi-square
Before
32 tokensPrompt A terasa lebih baik dari Prompt B berdasarkan 3 contoh yang saya cobaAfter
48 tokensA/B test (n=100):
- Prompt A: 85% accuracy, 450 avg tokens
- Prompt B: 92% accuracy, 380 avg tokens
- Winner: Prompt B (p < 0.05)Human Evaluation
Untuk subjective quality (tone, creativity, readability), butuh human raters.
Human eval protocol:
- Recruit 3-5 raters (internal team atau crowdsource)
- Beri rubric jelas (skala 1-5 untuk setiap dimensi)
- Blind evaluation (rater tidak tahu prompt mana yang generate output)
- Calculate inter-rater agreement (Cohen's kappa)
- Aggregate scores (median atau mean)
LLM-as-Judge
Gunakan LLM lain untuk evaluate output secara otomatis.
Prompt untuk LLM judge:
Evaluate the following output based on these criteria:
1. Accuracy (1-5): Is the information factually correct?
2. Completeness (1-5): Does it address all parts of the request?
3. Clarity (1-5): Is it easy to understand?
Output to evaluate:
{output}
Return JSON: {"accuracy": X, "completeness": Y, "clarity": Z, "reasoning": "..."}
| Technique | When to Use | Token Cost | Quality | Complexity |
|---|---|---|---|---|
| Automated Tests | Format, structure, token checks | Low | Medium | Low |
| A/B Testing | Compare 2 prompt variants | High | High | Medium |
| Human Evaluation | Subjective quality (tone, creativity) | High | High | High |
| LLM-as-Judge | Scale human-like evaluation | High | Medium | Medium |
Metrics Deep Dive
1. Accuracy
Seberapa sering output factually correct?
Cara ukur:
- Manual verification untuk 50-100 samples
- Compare dengan ground truth (jika ada)
- Fact-check dengan external source
Target: 95%+ untuk production use cases
2. Format Compliance
Seberapa sering output match expected format?
Cara ukur:
function checkFormat(output, expectedFormat) {
if (expectedFormat === "JSON") {
try {
JSON.parse(output);
return true;
} catch {
return false;
}
}
// Similar checks for other formats
}
Target: 100% (format compliance harus strict)
3. Token Efficiency
Berapa token rata-rata per request?
Cara ukur:
const avgTokens = totalTokens / numRequests;
const tokenPerDollar = avgTokens * pricePerToken;
Target: Depends on budget, tapi aim for 30-50% reduction dari baseline
4. Latency
Berapa lama AI generate response?
Cara ukur:
const start = Date.now();
const output = await runPrompt(input);
const latency = Date.now() - start;
Target: < 3s untuk interactive use, < 10s untuk batch processing
Regression Testing
Setiap perubahan prompt harus pass regression tests.
Regression test checklist:
- All existing test cases still pass
- Token usage tidak increase > 10%
- Output format tetap konsisten
- Edge cases masih handled correctly
- No new failure patterns introduced
Iterasi Berdasarkan Data
Testing menghasilkan data. Gunakan data untuk iterasi.
Iteration loop:
- Run tests → identify failure patterns
- Analyze failures → categorize (format, accuracy, edge case)
- Hypothesize fix → update prompt
- Re-run tests → validate fix
- Deploy if all tests pass
Before
28 tokensPrompt gagal untuk 3 test cases. Saya tambahkan constraint 'be specific' dan sekarang works.After
52 tokensFailure analysis (n=3):
- All failures: input > 1000 chars
- Root cause: context window overflow
- Fix: add 'summarize if input > 800 chars'
- Re-test: 100% pass rate (n=15)Production Monitoring
Testing tidak berhenti setelah deploy. Monitor production metrics.
Metrics to track:
- Success rate (% requests yang generate valid output)
- Average token usage per request
- P95 latency
- User feedback (thumbs up/down)
- Cost per day
Summary
Framework testing prompt:
- Define success criteria — pilih 2-3 metrik measurable
- Build test dataset — 10-15 cases covering happy path, edge cases, invalid input
- Automate testing — script untuk format, token, consistency checks
- Choose evaluation method — automated (fast), A/B (comparative), human (subjective), LLM-judge (scalable)
- Track metrics — accuracy, format compliance, token efficiency, latency
- Regression testing — setiap perubahan harus pass existing tests
- Iterate with data — analyze failures, hypothesize fix, validate
- Monitor production — track success rate, cost, latency, user feedback
Testing sistematis mengubah prompt engineering dari trial-and-error menjadi data-driven optimization.