20%

4.4 Few-Shot Prompting

Few-Shot Prompting คืออะไร

Few-Shot Prompting คือการให้ตัวอย่าง (examples) ใน prompt เพื่อ “สอน” Claude ว่า output ที่ต้องการหน้าตาเป็นอย่างไร — แทนที่จะอธิบายยาวๆ ให้ 2-3 ตัวอย่างบอก pattern ชัดกว่า Claude เก่งมากในการ infer pattern จาก examples

Format

prompt = """Classify the sentiment of customer reviews.

Examples:
Review: "สินค้าดีมาก ส่งเร็ว ประทับใจ"
Sentiment: positive
Confidence: 0.95

Review: "ของมาช้ามาก รอ 2 อาทิตย์ สภาพไม่ดี"
Sentiment: negative  
Confidence: 0.90

Review: "ก็โอเค ราคาเหมาะสม ไม่มีอะไรพิเศษ"
Sentiment: neutral
Confidence: 0.75

Now classify:
Review: "{user_review}"
Sentiment:"""

When Few-Shot Helps

  • Custom format — ต้องการ output format เฉพาะที่อธิบายยาก
  • Tone matching — ต้องการ writing style เฉพาะ
  • Edge cases — แสดงว่า edge case ควร handle อย่างไร
  • Domain-specific — terminology หรือ conventions ของ domain

When Few-Shot Hurts

  • Simple tasks — Claude ทำได้ดีอยู่แล้วโดยไม่ต้องมีตัวอย่าง (เสีย tokens เปล่า)
  • Biasing — examples อาจ bias Claude ให้ตอบตาม pattern มากเกินไป
  • Token expensive — แต่ละ example กิน tokens ใน context window
  • Inconsistent examples — ถ้า examples ขัดแย้งกัน Claude จะ confused

Example Selection Strategies

Diverse Examples

เลือก examples ที่ cover different cases:

- ตัวอย่าง positive sentiment
- ตัวอย่าง negative sentiment  
- ตัวอย่าง neutral/edge case

Similar Examples

เลือก examples ที่ใกล้เคียงกับ actual input:

def select_examples(input_text, example_bank, k=3):
    # Retrieve most similar examples via embedding similarity
    similarities = compute_similarity(input_text, example_bank)
    return top_k(similarities, k)

Format Consistency

ทุก example ต้อง format เดียวกัน exactly:

# ดี — consistent format
Input: X → Output: Y
Input: A → Output: B

# ไม่ดี — inconsistent
Input: X
Result: Y
---
A → B

Dynamic Few-Shot

เลือก examples ตาม input ที่เข้ามา แทนที่จะ hardcode:

def build_prompt(user_input, example_db):
    relevant_examples = retrieve_similar(user_input, example_db, k=3)
    
    prompt = "Classify these inputs:\n\n"
    for ex in relevant_examples:
        prompt += f"Input: {ex.input}\nOutput: {ex.output}\n\n"
    prompt += f"Input: {user_input}\nOutput:"
    
    return prompt

Exam Tips

  • Few-shot = ให้ examples ใน prompt; Zero-shot = ไม่มี examples
  • Claude ทำ few-shot ได้ดีมาก — 2-3 examples มักพอ
  • ข้อสอบอาจถามว่าเมื่อไหร่ few-shot ดีกว่า zero-shot — ตอบ: custom format, domain-specific, edge cases
  • Examples ต้อง consistent ใน format — inconsistency ทำให้ Claude confused
  • Dynamic example selection (RAG-style) ดีกว่า static examples สำหรับ diverse inputs
  • อย่าใช้ examples มากเกินไป (5+ examples) — diminishing returns + token cost