0Pricing
AI Prompt Engineering · 강의

스키마 기반 데이터 추출

구조화된 출력 형식을 보장하도록 프롬프트에 JSON 스키마를 제공합니다.

스키마 기반 데이터 추출은(는) CoddyKit의 무료 AI Prompt Engineering 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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')

추출 후 스키마 검증

Python의 jsonschema 라이브러리 또는 사용자 지정 검증기를 사용하여 추출된 데이터를 예상 스키마에 맞게 검증하십시오:

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개 샘플을 추출하고, 검토하고, 개선하는 과정을 반복합니다

자주 묻는 질문

“스키마 기반 데이터 추출” 강의는 무료인가요?

네 — “스키마 기반 데이터 추출” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 AI Prompt Engineering 강의 전체를 잠금 해제할 수 있습니다. AI Prompt Engineering 강의에는 총 4개의 강의가 포함되어 있습니다.

“스키마 기반 데이터 추출”에서 뭘 배우나요?

구조화된 출력 형식을 보장하도록 프롬프트에 JSON 스키마를 제공합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Prompt Engineering을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

AI Prompt Engineering을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 AI Prompt Engineering은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“스키마 기반 데이터 추출” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 AI Prompt Engineering 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 AI Prompt Engineering 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 명명된 개체 추출 프롬프트
  2. 스키마 기반 데이터 추출
  3. 텍스트 분류기로서의 LLM
  4. 분류의 확신도와 불확실성
← AI Prompt Engineering(으)로 돌아가기