0Pricing
AI Prompt Engineering · บทเรียน

การดึงข้อมูลโดยขับเคลื่อนด้วยสคีมา

ใส่สคีมา JSON ในพรอมป์ตเพื่อรับประกันรูปแบบผลลัพธ์ที่มีโครงสร้าง

การดึงข้อมูลโดยขับเคลื่อนด้วยสคีมา เป็นบทเรียน AI Prompt Engineering ฟรีบน CoddyKit นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน AI Prompt Engineering และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส AI Prompt Engineering มีบทเรียนทั้งหมด 4 บทเรียน

เหตุใดจึงต้องใช้การสกัดข้อมูลโดยใช้สคีมา

เมื่อคุณบอกโมเดลว่า สกัดข้อมูลสำคัญ คุณจะได้ผลลัพธ์ที่ไม่สม่ำเสมอและคาดเดาไม่ได้ แต่เมื่อคุณระบุสคีมา JSON และบอกว่า สกัดข้อมูลให้ตรงตามสคีมานี้ทุกประการ คุณจะได้ผลลัพธ์ที่เครื่องอ่านได้ สม่ำเสมอ และปลอดภัยด้านชนิดข้อมูลทุกครั้ง

การสกัดข้อมูลโดยใช้สคีมาเป็นรูปแบบที่ใช้ในระบบใช้งานจริงซึ่งประมวลผลใบแจ้งหนี้ สัญญา เวชระเบียน บันทึกการประชุม และเอกสารทุกประเภทที่ต้องสกัดข้อมูลที่มีโครงสร้างจากข้อความที่ไม่มีโครงสร้างอย่างน่าเชื่อถือ

การระบุสคีมาในพรอมต์

สคีมาจะอยู่โดยตรงในพรอมต์ โมเดลใช้สคีมานั้นเป็นข้อกำหนดของผลลัพธ์:

import anthropic, json

client = anthropic.Anthropic(api_key='YOUR_API_KEY')

INVOICE_SCHEMA = '''
{
  "invoice_number": "string",
  "vendor_name": "string",
  "vendor_address": "string or null",
  "invoice_date": "YYYY-MM-DD",
  "due_date": "YYYY-MM-DD or null",
  "line_items": [
    {
      "description": "string",
      "quantity": "number",
      "unit_price": "number",
      "total": "number"
    }
  ],
  "subtotal": "number",
  "tax": "number or null",
  "total_amount": "number",
  "currency": "3-letter ISO code e.g. USD"
}
'''

def extract_invoice(invoice_text):
    prompt = f'Extract structured data from this invoice.\nReturn JSON matching this schema exactly:\n{INVOICE_SCHEMA}\n\nInvoice:\n{invoice_text}'
    r = client.messages.create(model='claude-opus-4-5', max_tokens=500, messages=[{'role': 'user', 'content': prompt}])
    return json.loads(r.content[0].text)

print('Invoice schema defined.')

ตัวอย่างการสกัดข้อมูลจากใบแจ้งหนี้

การใช้สคีมาเพื่อสกัดข้อมูลที่มีโครงสร้างจากข้อความใบแจ้งหนี้จริง:

invoice_text = '''
INVOICE #INV-2025-0342
From: Acme Software Ltd.
123 Tech Street, San Francisco, CA 94105

Date: March 15, 2025
Due: April 14, 2025

Items:
- Annual Pro License (5 seats) x1 @ $2,400.00 = $2,400.00
- Setup & Onboarding x2 @ $300.00 = $600.00

Subtotal: $3,000.00
Tax (8.5%): $255.00
TOTAL DUE: $3,255.00 USD
'''

result = extract_invoice(invoice_text)
print(f'Invoice: {result["invoice_number"]}')
print(f'Vendor: {result["vendor_name"]}')
print(f'Total: {result["currency"]} {result["total_amount"]}')
print(f'Line items: {len(result["line_items"])}')

การสกัดข้อมูลจากบันทึกการประชุม

การสกัดข้อมูลโดยใช้สคีมาที่นำไปใช้กับบันทึกการประชุม ซึ่งเป็นเอกสารประเภทที่มีโครงสร้างน้อยกว่า:

MEETING_SCHEMA = '''
{
  "meeting_title": "string",
  "date": "YYYY-MM-DD",
  "attendees": ["string"],
  "decisions": ["string"],
  "action_items": [
    {
      "task": "string",
      "owner": "string or null",
      "due_date": "YYYY-MM-DD or null"
    }
  ],
  "next_meeting": "string or null"
}
'''

meeting_notes = '''
Product Sync - March 20, 2025
Attendees: Sarah (PM), Jake (Engineering), Priya (Design)

Decided to push the v2.0 launch to April 15.
Will not include the analytics dashboard in v2.0.

Actions:
- Jake to fix the login bug by March 25
- Priya to finalize mockups by March 22
- Sarah to send updated roadmap to stakeholders (no date set)

Next sync: March 27, same time.
'''

print(f'Meeting schema: {len(MEETING_SCHEMA)} chars')
print(f'Notes length: {len(meeting_notes)} chars')

การสกัดข้อมูลจำเพาะของผลิตภัณฑ์

การสกัดข้อมูลจำเพาะของผลิตภัณฑ์ที่มีโครงสร้างจากคำอธิบายในแค็ตตาล็อก:

PRODUCT_SCHEMA = '''
{
  "product_name": "string",
  "sku": "string or null",
  "category": "string",
  "price": {"amount": "number", "currency": "string"},
  "dimensions": {
    "length_cm": "number or null",
    "width_cm": "number or null",
    "height_cm": "number or null",
    "weight_kg": "number or null"
  },
  "colors": ["string"],
  "materials": ["string"],
  "features": ["string"],
  "in_stock": true | false
}
'''

product_text = 'AlphaDesk Pro standing desk. SKU: AD-PRO-001. $899. Available in white and black. 120x60x75cm, 35kg. Steel frame, bamboo top. Features: memory height, anti-collision, app control. In stock.'

prompt = f'Extract product specs. Return JSON:\n{PRODUCT_SCHEMA}\n\nProduct: {product_text}'
r = client.messages.create(model='claude-opus-4-5', max_tokens=400, messages=[{'role': 'user', 'content': prompt}])
print(json.loads(r.content[0].text))

การจัดการฟิลด์ที่ไม่จำเป็น

สคีมาต้องจัดการกับฟิลด์ที่ไม่จำเป็นได้อย่างเหมาะสม ใช้ null เป็นค่าเริ่มต้นสำหรับข้อมูลที่ขาดหาย แทนการละเว้นฟิลด์นั้น เพราะวิธีนี้ช่วยให้โครงสร้างผลลัพธ์สม่ำเสมอ:

prompt_optional = '''
Extract the data. For fields not present in the source text,
use null — do NOT omit the field.
Every field in the schema must appear in the output.

Schema:
{
  "company": "string",
  "ceo": "string or null",
  "founded": "YYYY or null",
  "revenue": "string or null",
  "employees": "number or null"
}

Text: Vertex AI Solutions is a B2B SaaS company.
'''

# Expected output: ceo, founded, revenue, employees all set to null
# NOT omitted — null fields are still present in the JSON
print(prompt_optional)

การสกัดข้อมูลจากเอกสารหลายฉบับด้วยสคีมาเดียวกัน

สามารถใช้สคีมาเดียวกันกับเอกสารจำนวนมากได้อย่างสม่ำเสมอ นี่คือวิธีสร้างฐานข้อมูลที่มีโครงสร้างจากเอกสารที่ไม่มีโครงสร้างในระดับใหญ่:

def extract_many(documents, schema):
    results = []
    for i, doc in enumerate(documents):
        try:
            r = client.messages.create(
                model='claude-opus-4-5', max_tokens=400,
                messages=[{'role': 'user', 'content': f'Extract data. Return JSON matching schema:\n{schema}\n\nDocument:\n{doc}'}]
            )
            parsed = json.loads(r.content[0].text)
            parsed['_source_doc'] = i
            parsed['_extraction_ok'] = True
            results.append(parsed)
        except (json.JSONDecodeError, Exception) as e:
            results.append({'_source_doc': i, '_extraction_ok': False, '_error': str(e)})
    return results

invoices = ['Invoice from Acme, March 2025, $500', 'Invoice from Beta Corp, April 2025, $1200']
results = extract_many(invoices, INVOICE_SCHEMA)
print(f'Processed: {len([r for r in results if r["_extraction_ok"]])} success, {len([r for r in results if not r["_extraction_ok"]])} failed')

การตรวจสอบสคีมาหลังการสกัดข้อมูล

ตรวจสอบข้อมูลที่สกัดได้กับสคีมาที่คาดไว้โดยใช้ไลบรารี jsonschema ของ Python หรือเครื่องมือตรวจสอบแบบกำหนดเอง:

def validate_extracted(data, required_fields, type_checks):
    errors = []

    # Check required fields
    for field in required_fields:
        if field not in data or data[field] is None:
            errors.append(f'Required field missing or null: {field}')

    # Check types
    for field, expected_type in type_checks.items():
        if field in data and data[field] is not None:
            if not isinstance(data[field], expected_type):
                errors.append(f'{field}: expected {expected_type.__name__}, got {type(data[field]).__name__}')

    return errors

extracted = {'invoice_number': 'INV-001', 'total_amount': 3255.0, 'vendor_name': 'Acme', 'invoice_date': '2025-03-15'}
required = ['invoice_number', 'total_amount', 'vendor_name']
types = {'total_amount': float, 'invoice_number': str, 'line_items': list}
errors = validate_extracted(extracted, required, types)
print('Validation errors:', errors)

การปรับปรุงสคีมาเป็นรอบ ๆ

สคีมาพัฒนาผ่านการทดสอบเป็นรอบ ๆ กระบวนการมีดังนี้:

  1. กำหนดสคีมาเบื้องต้นโดยอาศัยความรู้ในโดเมน
  2. เรียกใช้การสกัดข้อมูลกับเอกสารตัวอย่าง 20 ฉบับ
  3. ตรวจสอบผลลัพธ์ ว่าฟิลด์ใดผิดหรือขาดหายอย่างต่อเนื่อง
  4. ปรับปรุงคำอธิบายสคีมาและเพิ่มคำจำกัดความของฟิลด์
  5. เรียกใช้กับเอกสาร 20 ฉบับเดิมอีกครั้ง
  6. ทำซ้ำจนกว่าคุณภาพจะถึงเกณฑ์

การเพิ่มคำอธิบายฟิลด์ลงในสคีมา

เมื่อฟิลด์มีความกำกวม ให้เพิ่มความคิดเห็นอธิบายเพื่อชี้นำโมเดล:

ANNOTATED_SCHEMA = '''
{
  "invoice_number": "string // The unique identifier for this invoice, e.g., INV-2025-001",
  "invoice_date": "YYYY-MM-DD // Date the invoice was issued",
  "due_date": "YYYY-MM-DD or null // Payment due date; null if not specified",
  "subtotal": "number // Amount before tax, as a decimal number",
  "tax": "number or null // Tax amount as a decimal; null if tax is not listed",
  "total_amount": "number // Final amount to pay, including tax",
  "payment_terms": "string or null // e.g., Net 30, Due on receipt; null if not mentioned"
}
'''

print('Annotated schema adds context per field.')
print(f'Schema length: {len(ANNOTATED_SCHEMA)} chars')

คะแนนความมั่นใจของฟิลด์ที่สกัดได้

สำหรับระบบใช้งานจริง ให้ใส่คะแนนความมั่นใจสำหรับแต่ละฟิลด์ การสกัดข้อมูลที่มีความมั่นใจต่ำสามารถส่งต่อให้มนุษย์ตรวจสอบได้:

SCHEMA_WITH_CONFIDENCE = '''
{
  "fields": {
    "invoice_number": {"value": "string", "confidence": "high|medium|low"},
    "total_amount": {"value": "number", "confidence": "high|medium|low"},
    "due_date": {"value": "YYYY-MM-DD or null", "confidence": "high|medium|low"}
  },
  "overall_confidence": "high|medium|low",
  "extraction_notes": "string or null // Any ambiguities encountered"
}
'''

prompt = f'Extract invoice data with confidence scores.\nReturn JSON:\n{SCHEMA_WITH_CONFIDENCE}\n\nInvoice: Payment due within 30 days. Total is approximately $500.'
r = client.messages.create(model='claude-opus-4-5', max_tokens=300, messages=[{'role': 'user', 'content': prompt}])
result = json.loads(r.content[0].text)
print('Overall confidence:', result.get('overall_confidence'))
print('Notes:', result.get('extraction_notes'))

ตรวจสอบความเข้าใจ

เมื่อไม่มีฟิลด์ที่จำเป็นอยู่ในเอกสารต้นฉบับ พรอมต์การสกัดข้อมูลโดยใช้สคีมาควรกำชับให้โมเดลส่งคืนค่าใดสำหรับฟิลด์นั้น

การสกัดข้อมูลโดยใช้สคีมา — ประเด็นสำคัญ

การสกัดข้อมูลโดยใช้สคีมาเป็นมาตรฐานสำหรับการประมวลผลเอกสารที่เชื่อถือได้ในระบบใช้งานจริง:

  • ระบุสคีมา JSON ที่แน่นอนในพรอมต์ เพราะโมเดลจะใช้สคีมานั้นเป็นข้อกำหนดของผลลัพธ์
  • เพิ่มคำอธิบายฟิลด์สำหรับฟิลด์ที่กำกวมเพื่อชี้นำการตีความของโมเดล
  • กำชับเสมอว่า ฟิลด์ที่ขาดหายให้ส่งคืนค่า null และห้ามละเว้นฟิลด์นั้น
  • ใช้สคีมาเดียวกันกับเอกสารจำนวนมากเพื่อให้ได้ผลลัพธ์ที่สม่ำเสมอและพร้อมนำไปใช้สร้างฐานข้อมูล
  • ใส่คะแนนความมั่นใจสำหรับแต่ละฟิลด์เพื่อรองรับการส่งต่อให้มนุษย์ตรวจสอบ
  • ตรวจสอบข้อมูลที่สกัดได้ด้วยโปรแกรมหลังการสกัดข้อมูลทุกครั้ง
  • ปรับปรุงสคีมาเป็นรอบ ๆ โดยสกัดข้อมูลจากตัวอย่าง 20 รายการ ตรวจสอบ ปรับปรุง และทำซ้ำ

คำถามที่พบบ่อย

บทเรียน “การดึงข้อมูลโดยขับเคลื่อนด้วยสคีมา” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การดึงข้อมูลโดยขับเคลื่อนด้วยสคีมา” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Prompt Engineering ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Prompt Engineering มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การดึงข้อมูลโดยขับเคลื่อนด้วยสคีมา”

ใส่สคีมา JSON ในพรอมป์ตเพื่อรับประกันรูปแบบผลลัพธ์ที่มีโครงสร้าง คุณปฏิบัติ AI Prompt Engineering ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Prompt Engineering หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Prompt Engineering บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 2 จากทั้งหมด 4 บทเรียน

บทเรียน “การดึงข้อมูลโดยขับเคลื่อนด้วยสคีมา” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน AI Prompt Engineering นี้ได้ไหม

ได้ บทเรียน AI Prompt Engineering ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. พรอมป์ตสำหรับการดึงเอนทิตีที่มีชื่อ
  2. การดึงข้อมูลโดยขับเคลื่อนด้วยสคีมา
  3. LLM ในฐานะตัวจำแนกข้อความ
  4. ความมั่นใจและความไม่แน่นอนในการจำแนก
← กลับไปที่ AI Prompt Engineering