Bab 10: Prompt Chaining¶
Daripada satu prompt panjang yang nyuruh AI lakukan 5 hal, pecah jadi 5 prompt kecil. Output prompt 1 = input prompt 2. Hasilnya jauh lebih reliable.
Prompt chaining adalah teknik mendekomposisi task kompleks jadi serial step yang lebih kecil dan terkontrol.
Setelah Bab 10, kamu akan bisa:
- Memahami kenapa task panjang sering gagal di single prompt
- Pecah task jadi chain yang reliable
- Build pipeline LLM untuk production use case
10.1. Masalah: Kitchen Sink Prompt¶
Prompt yang minta banyak hal sekaligus:
Tulis email follow-up ke client. Translate ke Bahasa Inggris.
Cek grammar. Bikin versi formal dan casual. Tambahkan subject line.
Format: 3 versi side-by-side dalam tabel.
Output biasanya: setengah-setengah, format kacau, beberapa permintaan ter-skip.
Akar masalah: LLM tidak bisa fokus optimal di banyak task secara simultaneous. Quality menurun seiring kompleksitas prompt.
10.2. Solusi: Chain Multiple Prompts¶
Pecah jadi serial step, output step N jadi input step N+1.
flowchart LR
Input["User input"]
P1["Prompt 1:<br/>Tulis email<br/>casual ID"]
O1["Output 1:<br/>Email casual ID"]
P2["Prompt 2:<br/>Translate<br/>ke EN"]
O2["Output 2:<br/>Email casual EN"]
P3["Prompt 3:<br/>Convert ke<br/>formal version"]
O3["Output 3:<br/>Email formal EN"]
Final["Result"]
Input --> P1 --> O1
O1 --> P2 --> O2
O2 --> P3 --> O3
O3 --> Final
style Input fill:#1a1a1a,stroke:#6366f1,color:#fafafa
style P1 fill:#1a1a1a,stroke:#f59e0b,color:#fafafa
style P2 fill:#1a1a1a,stroke:#f59e0b,color:#fafafa
style P3 fill:#1a1a1a,stroke:#f59e0b,color:#fafafa
style O1 fill:#1a1a1a,stroke:#10b981,color:#fafafa
style O2 fill:#1a1a1a,stroke:#10b981,color:#fafafa
style O3 fill:#1a1a1a,stroke:#10b981,color:#fafafa
style Final fill:#1a1a1a,stroke:#ec4899,color:#fafafa
Cara baca diagram
Diagram ini menunjukkan alur prompt chaining linear.
Step demi step:
- Input dari user
- Prompt 1 — tugas pertama, fokus tunggal (misal: tulis email casual ID)
- Output 1 → Prompt 2 — tugas kedua, fokus tunggal (misal: translate)
- Output 2 → Prompt 3 — tugas ketiga (misal: ubah ke formal)
- Final result
Kunci insight:
Setiap prompt fokus pada 1 task. Quality tiap step tinggi karena tidak ter-distract.
Bandingkan dengan single prompt:
- Single: 1 prompt → 1 output messy yang coba penuhi 5 task
- Chained: 3 prompt → 3 output clean, masing-masing optimal
Trade-off:
- ✓ Quality lebih tinggi
- ✓ Lebih bisa di-debug (kalau gagal, tahu di step mana)
- ✗ Lebih banyak API calls (cost lebih tinggi)
- ✗ Lebih lambat (3 round-trip vs 1)
Untuk production app, hampir selalu pakai chaining.
10.3. Pattern Umum¶
Pattern 1: Sequential Refinement¶
Step demi step refine output:
Step 1: Generate draft
Step 2: Edit grammar
Step 3: Improve tone
Step 4: Add structure (heading, etc)
Pattern 2: Decompose-and-Solve¶
Pecah problem jadi sub-problem, solve masing-masing, gabungkan:
Step 1: Identify sub-problems
Step 2: Solve sub-problem 1
Step 3: Solve sub-problem 2
Step 4: Combine solutions
Pattern 3: Validate-and-Retry¶
Generate output, lalu validasi:
Step 1: Generate solution
Step 2: Critique solution (cari masalah)
Step 3: Kalau ada issue, regenerate dengan feedback
Pattern 4: Map-Reduce¶
Untuk dataset besar:
10.4. Contoh Implementasi (Python)¶
import openai
def chained_email_writer(brief):
# Step 1: Draft email casual
draft = openai_call(
f"Tulis email casual berdasarkan brief: {brief}"
)
# Step 2: Edit grammar
edited = openai_call(
f"Edit grammar dan typo email berikut, tetap casual:\n{draft}"
)
# Step 3: Convert ke formal version
formal = openai_call(
f"Convert email berikut jadi versi formal, simpan inti pesan:\n{edited}"
)
return {"casual": edited, "formal": formal}
def openai_call(prompt):
response = openai.ChatCompletion.create(
model="gpt-4",
messages=[{"role": "user", "content": prompt}],
)
return response.choices[0].message.content
3 prompt terpisah, masing-masing fokus, output di-pipe.
10.5. Validate-and-Retry Pattern (Detail)¶
Pattern ini penting untuk reliability:
def reliable_extract(text):
for attempt in range(3):
# Step 1: Try extract
extracted = openai_call(
f"Extract data dari: {text}\nOutput JSON."
)
# Step 2: Validate
is_valid, errors = validate_json(extracted)
if is_valid:
return extracted
# Step 3: Retry dengan feedback
text = f"{text}\n\nPrevious attempt had errors: {errors}\nFix and retry."
raise Exception("Failed after 3 attempts")
Ini pattern dasar untuk structured output reliability.
10.6. Use Case¶
Content Pipeline¶
Tiap step prompt terpisah, output terkontrol.
Data Processing¶
Research Assistant¶
10.7. Cost-Quality Trade-Off¶
Chaining = lebih banyak API calls = lebih mahal.
Kapan worth it:
- Production app dengan reliability requirement
- Output yang akan di-process programmatik
- Task kompleks dengan multiple sub-task jelas
Kapan skip:
- Quick prototype
- Personal use occasional
- Task yang single prompt handle dengan baik
10.8. Latihan¶
10.1 — Decompose¶
Pilih task complex (misal "research kompetitor + write report"). Pecah jadi 4-5 step. Tulis prompt tiap step.
10.2 — Validate-Retry¶
Build chain yang generate JSON. Tambahkan validation step. Kalau invalid, retry dengan feedback.
10.3 — Tantangan: Real Pipeline¶
Build pipeline production-ready (Python script) untuk task spesifik di kerjaan kamu.
Patterns¶
- Sequential refinement — draft → edit → polish
- Decompose-and-solve — pecah → solve → gabung
- Validate-and-retry — generate → validate → retry kalau gagal
- Map-reduce — process chunks → aggregate
Pseudocode¶
output_1 = llm(prompt_1, input)
output_2 = llm(prompt_2, output_1)
output_3 = llm(prompt_3, output_2)
return output_3
Kapan Pakai¶
✓ Production apps ✓ Task kompleks dengan sub-task jelas ✓ Output untuk programmatic processing
Kapan Skip¶
✗ Quick prototype ✗ Personal one-off ✗ Task single-prompt cukup
Cost Implication¶
- 1 single prompt = 1 API call
- 3-step chain = 3 API calls
- Calculate: worth it kalau quality jump signifikan