Prompt Chaining
Prompt Engineering
AI
Automation
Advanced

Prompt Chaining: เชื่อม Prompt หลายขั้นตอนให้ทรงพลัง

เรียนรู้เทคนิค Prompt Chaining การเชื่อมหลาย Prompts เข้าด้วยกันเพื่อทำงานซับซ้อน พร้อมตัวอย่างและ patterns ที่ใช้ได้จริง

AI Unlocked Team
21/01/2568
Prompt Chaining: เชื่อม Prompt หลายขั้นตอนให้ทรงพลัง

Prompt Chaining: เชื่อม Prompt หลายขั้นตอนให้ทรงพลัง

บางงานซับซ้อนเกินกว่าจะทำสำเร็จด้วย Prompt เดียว Prompt Chaining คือเทคนิคการแบ่งงานใหญ่ออกเป็นขั้นตอนย่อยๆ แล้วส่งต่อผลลัพธ์จากขั้นตอนหนึ่งไปยังอีกขั้นตอน

Prompt Chaining คืออะไร?

Prompt Chaining คือการเชื่อมหลาย Prompts เข้าด้วยกัน โดยผลลัพธ์ของ Prompt แรกจะกลายเป็น input ของ Prompt ถัดไป

เปรียบเทียบ

Single Prompt (ไม่ chain):
┌─────────────────────────────┐
│ "วิเคราะห์ข้อมูล สร้าง     │
│  กราฟ สรุป และแนะนำ"       │
└─────────────────────────────┘
         ↓
    (ผลลัพธ์ปนกัน)

Prompt Chaining:
┌─────────┐    ┌─────────┐    ┌─────────┐    ┌─────────┐
│วิเคราะห์│ → │สร้างกราฟ│ → │  สรุป   │ → │ แนะนำ   │
└─────────┘    └─────────┘    └─────────┘    └─────────┘
    ↓              ↓              ↓              ↓
  data         visual         summary      recommendations

ทำไมต้องใช้ Prompt Chaining?

1. ควบคุมคุณภาพแต่ละขั้นตอน

แต่ละขั้นตอนตรวจสอบได้:
- ขั้นตอน 1 ผิด → แก้ไขก่อนไปต่อ
- ไม่ต้องเริ่มใหม่ทั้งหมด

2. ลดความซับซ้อน

งานยาก 1 งาน → งานง่าย 5 งาน
AI ทำได้ดีกว่าเมื่องานชัดเจน

3. Debugging ง่าย

ถ้าผลลัพธ์ไม่ดี:
- รู้ว่าขั้นตอนไหนมีปัญหา
- แก้ไขเฉพาะจุด

4. Reusable Components

ขั้นตอนที่ออกแบบดี:
- นำไปใช้กับงานอื่นได้
- สร้าง library ของ prompts

Patterns ของ Prompt Chaining

1. Sequential Chain (ลำดับต่อเนื่อง)

A → B → C → D

ตัวอย่าง: การเขียนบทความ
1. Research: หาข้อมูลหัวข้อ
2. Outline: สร้างโครงร่าง
3. Draft: เขียนร่างแรก
4. Edit: แก้ไขปรับปรุง
5. Polish: ขัดเกลาภาษา

2. Parallel Chain (ขนาน)

    ┌→ B ─┐
A ──┼→ C ─┼→ E
    └→ D ─┘

ตัวอย่าง: วิเคราะห์หลายมุม
1. Input: รายงานการเงิน
2. ขนาน:
   - วิเคราะห์รายได้
   - วิเคราะห์ต้นทุน
   - วิเคราะห์กระแสเงินสด
3. รวมผล: สรุปภาพรวม

3. Conditional Chain (เงื่อนไข)

     ┌→ B (ถ้า X)
A ───┤
     └→ C (ถ้า Y)

ตัวอย่าง: Customer Support
1. จำแนกประเภทคำถาม
2. ถ้าเรื่องสินค้า → Chain สินค้า
   ถ้าเรื่องคำสั่งซื้อ → Chain คำสั่งซื้อ
   ถ้าเรื่องอื่น → Chain ทั่วไป

4. Loop Chain (วนซ้ำ)

A → B → Check
      ↓
    ไม่ผ่าน → กลับไป B
      ↓
    ผ่าน → C

ตัวอย่าง: การเขียนโค้ด
1. เขียนโค้ด
2. ตรวจสอบ
3. ถ้ามี error → แก้ไข → กลับข้อ 2
4. ถ้าผ่าน → เสร็จสิ้น

ตัวอย่างการใช้งาน

ตัวอย่าง 1: Content Creation Pipeline

# Step 1: Research
prompt1 = """
วิจัยข้อมูลเกี่ยวกับ "Prompt Engineering"
ให้ข้อมูลสำคัญ 5 ประเด็น
"""
research = call_ai(prompt1)

# Step 2: Outline
prompt2 = f"""
จากข้อมูลต่อไปนี้:
{research}

สร้างโครงร่างบทความ:
- หัวข้อหลัก
- หัวข้อย่อย 5 ข้อ
- ประเด็นสำคัญในแต่ละหัวข้อ
"""
outline = call_ai(prompt2)

# Step 3: Draft
prompt3 = f"""
จากโครงร่างนี้:
{outline}

เขียนบทความ 1,000 คำ
ภาษาเข้าใจง่าย มีตัวอย่าง
"""
draft = call_ai(prompt3)

# Step 4: Edit
prompt4 = f"""
บทความต่อไปนี้:
{draft}

ตรวจแก้:
1. ไวยากรณ์และการสะกด
2. ความลื่นไหล
3. ความชัดเจน
4. SEO keywords
"""
final = call_ai(prompt4)

ตัวอย่าง 2: Data Analysis Pipeline

# Step 1: Clean Data
prompt1 = f"""
ข้อมูลดิบ:
{raw_data}

ทำความสะอาด:
- หาค่าผิดปกติ
- จัดการ missing values
- แปลงรูปแบบให้ถูกต้อง

Output: JSON ที่ clean แล้ว
"""
clean_data = call_ai(prompt1)

# Step 2: Analyze
prompt2 = f"""
ข้อมูลที่ clean แล้ว:
{clean_data}

วิเคราะห์:
- แนวโน้ม (Trends)
- ความสัมพันธ์ (Correlations)
- ค่าผิดปกติ (Outliers)
- สถิติพื้นฐาน
"""
analysis = call_ai(prompt2)

# Step 3: Visualize (describe)
prompt3 = f"""
จากการวิเคราะห์:
{analysis}

แนะนำ visualization:
- กราฟอะไรเหมาะสม
- แกน X, Y
- สีและ labels
- Code สำหรับ matplotlib
"""
visualization = call_ai(prompt3)

# Step 4: Recommend
prompt4 = f"""
จากการวิเคราะห์:
{analysis}

ให้คำแนะนำ:
- 3 insights สำคัญ
- 3 actions ที่ควรทำ
- ความเสี่ยงที่ต้องระวัง
"""
recommendations = call_ai(prompt4)

ตัวอย่าง 3: Customer Support Chain

# Step 1: Classify
prompt1 = f"""
ข้อความจากลูกค้า:
"{customer_message}"

จำแนกประเภท:
- product_inquiry
- order_status
- complaint
- technical_support
- other

ตอบแค่ประเภทเดียว
"""
category = call_ai(prompt1)

# Step 2: Route to appropriate chain
if category == "product_inquiry":
    prompt2 = f"""
    คำถามเรื่องสินค้า:
    "{customer_message}"

    ข้อมูลสินค้าของเรา:
    {product_catalog}

    ตอบคำถามลูกค้า อ้างอิงจากข้อมูลจริง
    """
elif category == "complaint":
    prompt2 = f"""
    ข้อร้องเรียน:
    "{customer_message}"

    ตอบ:
    1. แสดงความเสียใจ
    2. รับทราบปัญหา
    3. เสนอวิธีแก้ไข
    4. ให้ช่องทางติดต่อเพิ่มเติม
    """
# ... other categories

response = call_ai(prompt2)

# Step 3: Quality Check
prompt3 = f"""
คำตอบที่จะส่งลูกค้า:
{response}

ตรวจสอบ:
1. ตอบตรงคำถามหรือไม่
2. น้ำเสียงเหมาะสมหรือไม่
3. มีข้อมูลครบถ้วนหรือไม่

ถ้ามีปัญหา ปรับปรุงให้
"""
final_response = call_ai(prompt3)

ตัวอย่าง 4: Code Review Chain

# Step 1: Understand
prompt1 = f"""
โค้ดต่อไปนี้:

{user_code}

อธิบาย:
1. โค้ดนี้ทำอะไร
2. มี functions อะไรบ้าง
3. Dependencies ที่ใช้
"""
understanding = call_ai(prompt1)

# Step 2: Find Issues
prompt2 = f"""
โค้ด:

{user_code}

หาปัญหา:
1. Bugs ที่เห็นได้ชัด
2. Security vulnerabilities
3. Performance issues
4. Code style issues
"""
issues = call_ai(prompt2)

# Step 3: Suggest Fixes
prompt3 = f"""
ปัญหาที่พบ:
{issues}

โค้ดเดิม:

{user_code}

แนะนำวิธีแก้ไขแต่ละปัญหา
พร้อมตัวอย่างโค้ด
"""
fixes = call_ai(prompt3)

# Step 4: Improve
prompt4 = f"""
โค้ดเดิม:

{user_code}

ปรับปรุง:
1. Refactor ให้ clean ขึ้น
2. เพิ่ม error handling
3. เพิ่ม comments
4. ปรับตาม best practices
"""
improved_code = call_ai(prompt4)

Implementation Tips

1. ใช้ Structured Output

# กำหนด format ชัดเจน
prompt = """
วิเคราะห์ข้อความนี้

Output format (JSON):
{
  "sentiment": "positive/negative/neutral",
  "topics": ["topic1", "topic2"],
  "summary": "..."
}
"""

2. Error Handling

def chain_with_retry(prompts, max_retries=3):
    results = []
    for i, prompt in enumerate(prompts):
        for attempt in range(max_retries):
            try:
                result = call_ai(prompt.format(prev=results[-1] if results else ""))
                validate(result)  # ตรวจสอบผลลัพธ์
                results.append(result)
                break
            except Exception as e:
                if attempt == max_retries - 1:
                    raise
                continue
    return results

3. Caching

import hashlib

def cached_call(prompt):
    cache_key = hashlib.md5(prompt.encode()).hexdigest()
    if cache_key in cache:
        return cache[cache_key]

    result = call_ai(prompt)
    cache[cache_key] = result
    return result

4. Parallel Execution

import asyncio

async def parallel_chain(prompts):
    tasks = [call_ai_async(p) for p in prompts]
    return await asyncio.gather(*tasks)

# ใช้เมื่อ prompts ไม่ขึ้นต่อกัน
results = asyncio.run(parallel_chain([
    "วิเคราะห์มุม A",
    "วิเคราะห์มุม B",
    "วิเคราะห์มุม C"
]))

Best Practices

1. แต่ละ Chain ทำหน้าที่เดียว

❌ ไม่ดี:
"วิเคราะห์ สรุป และแนะนำ"

✅ ดี:
Chain 1: "วิเคราะห์ข้อมูล"
Chain 2: "สรุปผลการวิเคราะห์"
Chain 3: "ให้คำแนะนำ"

2. กำหนด Output Format ชัดเจน

ตอบในรูปแบบ:
## Summary
[สรุป 2-3 ประโยค]

## Key Points
- Point 1
- Point 2
- Point 3

## Next Steps
1. ...
2. ...

3. ตรวจสอบระหว่าง Chains

def validate_step(result, step_name):
    if not result:
        raise ValueError(f"{step_name} returned empty")
    if len(result) < 50:
        raise ValueError(f"{step_name} too short")
    return True

4. Log ทุกขั้นตอน

import logging

def logged_chain(prompt, step_name):
    logging.info(f"Starting {step_name}")
    result = call_ai(prompt)
    logging.info(f"Completed {step_name}: {len(result)} chars")
    return result

สรุป

Prompt Chaining คือการเชื่อมหลาย Prompts:

Patterns หลัก:

  • Sequential: A → B → C
  • Parallel: A → [B, C, D] → E
  • Conditional: A → (B หรือ C)
  • Loop: A → B → Check → (ซ้ำ หรือ C)

ข้อดี:

  • ควบคุมคุณภาพได้
  • Debug ง่าย
  • Reusable

Best Practices:

  • แต่ละ chain ทำหน้าที่เดียว
  • กำหนด output format ชัด
  • ตรวจสอบระหว่าง chains
  • Log ทุกขั้นตอน

อ่านเพิ่มเติม:


เขียนโดย

AI Unlocked Team