4.3 Prompt Chaining and Validation-Retry Loops
Prompt Chaining คืออะไร
Prompt Chaining คือการแบ่ง complex task เป็นหลาย prompts เรียงต่อกัน — output ของ prompt แรกเป็น input ของ prompt ถัดไป ทำให้แต่ละ step ง่ายและ focused แทนที่จะยัดทุกอย่างใน prompt เดียวแล้วหวังว่า Claude จะทำถูกทั้งหมด
Basic Chain Pattern
# Step 1: Extract key information
extraction = client.messages.create(
messages=[{"role": "user", "content": f"Extract all dates, names, and amounts from: {document}"}]
)
# Step 2: Validate extracted data
validation = client.messages.create(
messages=[{"role": "user", "content": f"Validate this data for consistency: {extraction.content[0].text}"}]
)
# Step 3: Transform to final format
output = client.messages.create(
messages=[{"role": "user", "content": f"Convert this validated data to SQL INSERT statements: {validation.content[0].text}"}]
)
Validation-Retry Loop
เพิ่ม validation ระหว่าง steps — ถ้า output ไม่ผ่าน ส่งกลับไปแก้:
def chain_with_validation(prompt, validator_fn, max_retries=3):
messages = [{"role": "user", "content": prompt}]
for attempt in range(max_retries):
response = client.messages.create(messages=messages)
output = response.content[0].text
is_valid, error = validator_fn(output)
if is_valid:
return output
# Add validation feedback and retry
messages.append({"role": "assistant", "content": output})
messages.append({"role": "user", "content": f"This output has an issue: {error}. Please fix it."})
raise ValueError(f"Failed validation after {max_retries} attempts")
Chain Composition Patterns
Gate Pattern
ถ้า step ใด fail → หยุดทั้ง chain:
steps = [extract, validate, transform, format]
for step_fn in steps:
result = step_fn(result)
if not result.success:
return f"Chain failed at step: {step_fn.__name__}: {result.error}"
Branch Pattern
เลือก path ตาม output ของ step ก่อนหน้า:
classification = classify(input)
if classification == "bug_report":
result = bug_analysis_chain(input)
elif classification == "feature_request":
result = feature_analysis_chain(input)
Accumulator Pattern
สะสม results จากทุก steps:
context = {"original_input": input}
context["extracted"] = extract(input)
context["validated"] = validate(context["extracted"])
context["enriched"] = enrich(context) # ใช้ทุก context ที่สะสมมา
Exam Tips
- Prompt chaining ลด complexity ต่อ step — Claude ทำงานดีกว่ากับ focused tasks
- Validation-retry loop ใช้ conversation history (append messages) ไม่ใช่ start fresh
- ข้อสอบอาจถาม trade-off: chaining = more API calls (cost, latency) แต่ accuracy สูงกว่า
- Gate pattern = fail fast — เหมาะเมื่อ downstream steps depend on correctness
- ใส่ validation feedback ที่ specific — “Fix the date format” ดีกว่า “Try again”