0Pricing
AI Prompt Engineering · 강의

명명된 개체 추출 프롬프트

비정형 텍스트에서 이름, 날짜, 위치 및 사용자 지정 개체를 추출합니다.

명명된 개체 추출 프롬프트은(는) CoddyKit의 무료 AI Prompt Engineering 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 AI Prompt Engineering 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. AI Prompt Engineering 강의에는 총 4개의 강의가 포함되어 있습니다.

개체명 추출이란 무엇입니까?

개체명 추출(NER)은 텍스트에 언급된 특정 실제 개체를 식별하고 분류하는 작업입니다. 기존 NLP에서는 통계 모델을 사용해 NER을 수행하지만, LLM은 잘 설계된 프롬프트만으로도 이를 수행할 수 있습니다.

일반적인 개체 유형은 다음과 같습니다:

  • PERSON: 사람의 이름(Elon Musk, Dr. Jane Smith)
  • ORG: 회사와 조직(Apple, WHO)
  • DATE: 날짜와 시간 표현(January 15, last Tuesday, Q3 2024)
  • LOCATION: 장소(New York, the Amazon River)
  • MONEY: 금액($4.2 billion)

기본 NER 프롬프트

가장 간단한 NER 프롬프트는 모든 개체를 특정 형식으로 요청합니다:

import anthropic, json

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

text = 'Apple CEO Tim Cook met with European Commission President Ursula von der Leyen in Brussels on March 15, 2025 to discuss the Digital Markets Act.'

prompt = f'''
Extract all named entities from the text below.
Return ONLY a JSON object with no other text:
{{
  "people": ["string"],
  "organizations": ["string"],
  "locations": ["string"],
  "dates": ["string"]
}}

Text: {text}
'''

r = client.messages.create(
    model='claude-opus-4-5', max_tokens=300,
    messages=[{'role': 'user', 'content': prompt}]
)
print(json.loads(r.content[0].text))

추출에 유형 제약 조건 추가

기본 추출은 개체 문자열을 반환합니다. 유형 제약 조건을 추가하면 유효성 검사가 적용되어 날짜가 특정 형식인지, 조직에서 일반적인 단어가 제외되었는지를 확인할 수 있습니다:

prompt_typed = '''
Extract named entities from the text below with type constraints.
Return JSON:
{
  "people": ["Full name as written in text"],
  "organizations": ["Official organization name only, no articles (the, a)"],
  "dates": ["ISO 8601 format if possible: YYYY-MM-DD, else exact text as written"],
  "money": ["Include currency symbol and amount: $4.2B, EUR 500K"],
  "locations": ["City, Country format if applicable"]
}
If a category has no entities, use an empty array [].

Text: {text}
'''

print(prompt_typed[:200])
print('\nConstraints enforce consistent output format per entity type.')

스키마 기반 추출

실제 운영 환경에서는 개체 스키마를 미리 정의하고 프롬프트에서 참조하십시오. 이렇게 하면 출력 계약이 명확해집니다:

ENTITY_SCHEMA = '''
{
  "entities": [
    {
      "text": "exact text as it appears in the document",
      "type": "PERSON | ORG | DATE | LOCATION | MONEY | PRODUCT | EVENT",
      "normalized": "canonical form (e.g., full name, ISO date)",
      "start_char": "integer, character offset in source text",
      "confidence": "high | medium | low"
    }
  ]
}
'''

def extract_entities(text):
    prompt = f'Extract all named entities. Return JSON matching this schema exactly:\n{ENTITY_SCHEMA}\n\nText: {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)

result = extract_entities('Tesla stock rose 5% after Elon Musk announced the Cybertruck delivery on December 1.')
print(result['entities'][0])

모호한 개체 처리

일부 개체 문자열은 모호합니다. Apple은 회사일 수도 있고 과일일 수도 있으며, Jordan은 사람일 수도 있고 국가일 수도 있습니다. 모델이 문맥을 사용해 모호성을 해결하도록 안내하십시오:

prompt_disambiguation = '''
Extract named entities from the text. For ambiguous entities, use the surrounding
context to determine the correct type. Include your reasoning in an "evidence" field.

Return JSON:
{
  "entities": [
    {
      "text": "string",
      "type": "PERSON | ORG | LOCATION | OTHER",
      "evidence": "brief reason for type assignment"
    }
  ]
}

Text: Jordan and Apple signed a distribution deal for the new Air Jordan shoes.
'''

# Expected output: Jordan = PERSON (context: Air Jordan), Apple = ORG (context: signed a deal)
print(prompt_disambiguation)

필드 정의를 사용한 추출

사용자 도메인에 특화된 사용자 지정 개체 유형의 경우, 모델이 무엇을 해당 유형으로 판단해야 하는지 정확히 알 수 있도록 프롬프트에 필드 정의를 제공하십시오:

prompt_custom = '''
Extract entities from the medical text below using these custom entity types:

Entity Types:
- MEDICATION: Any drug name, trade name, or generic name
- DOSAGE: Amounts and frequencies (mg, mcg, units/day)
- CONDITION: Diagnoses, symptoms, or medical conditions
- PROCEDURE: Medical tests, surgeries, or treatments
- PROVIDER: Doctor names and medical professionals

Return JSON: {"entities": [{"text": str, "type": str}]}

Text: Dr. Patel prescribed Metformin 500mg twice daily for Type 2 Diabetes.
A follow-up HbA1c test is scheduled for next month.
'''

print(prompt_custom)

일괄 개체 추출

여러 문서를 처리할 때는 일괄 추출이 더 효율적입니다. 여러 입력을 처리하고 문서마다 구조화된 결과를 반환하도록 프롬프트를 설계하십시오:

def batch_extract(documents):
    docs_formatted = '\n'.join(
        f'<document id="{i+1}">\n{doc}\n</document>'
        for i, doc in enumerate(documents)
    )

    prompt = f'''
Extract named entities from each document below.
Return JSON: {{
  "results": [
    {{"doc_id": int, "entities": {{"people": [], "organizations": [], "dates": []}}}}
  ]
}}

{docs_formatted}
'''

    r = client.messages.create(
        model='claude-opus-4-5', max_tokens=1000,
        messages=[{'role': 'user', 'content': prompt}]
    )
    return json.loads(r.content[0].text)

docs = [
    'Satya Nadella presented at Microsoft Build 2025.',
    'The WHO released guidelines on May 10.'
]
print(batch_extract(docs))

추출된 개체 후처리

추출된 개체는 사용하기 전에 후처리가 필요한 경우가 많습니다:

from datetime import datetime

def normalize_entities(raw_entities):
    normalized = {'people': [], 'organizations': [], 'dates': [], 'money': []}

    for person in raw_entities.get('people', []):
        normalized['people'].append(person.strip().title())

    for org in raw_entities.get('organizations', []):
        normalized['organizations'].append(org.strip())

    for date_str in raw_entities.get('dates', []):
        # Try to parse to ISO format
        for fmt in ['%B %d, %Y', '%Y-%m-%d', '%b %d, %Y']:
            try:
                parsed = datetime.strptime(date_str.strip(), fmt)
                normalized['dates'].append(parsed.strftime('%Y-%m-%d'))
                break
            except ValueError:
                pass
        else:
            normalized['dates'].append(date_str.strip())

    return normalized

raw = {'people': ['tim cook', 'URSULA VON DER LEYEN'], 'dates': ['March 15, 2025']}
print(normalize_entities(raw))

추출 품질 평가

NER 품질은 레이블이 지정된 테스트 집합을 기준으로 정밀도, 재현율, F1 점수를 사용해 측정합니다:

  • 정밀도: 추출된 모든 개체 중 올바른 개체의 비율은 얼마입니까?
  • 재현율: 실제 개체 전체 중 추출된 개체의 비율은 얼마입니까?
  • F1: 정밀도와 재현율의 조화 평균
def evaluate_extraction(predicted, ground_truth):
    pred_set = set(predicted)
    true_set = set(ground_truth)

    true_positives = len(pred_set & true_set)
    false_positives = len(pred_set - true_set)
    false_negatives = len(true_set - pred_set)

    precision = true_positives / (true_positives + false_positives) if pred_set else 0
    recall = true_positives / (true_positives + false_negatives) if true_set else 0
    f1 = 2 * precision * recall / (precision + recall) if (precision + recall) else 0

    return {'precision': round(precision, 3), 'recall': round(recall, 3), 'f1': round(f1, 3)}

predicted = ['Tim Cook', 'Apple', 'Brussels', 'March 15 2025']
ground_truth = ['Tim Cook', 'Apple', 'Ursula von der Leyen', 'Brussels', 'March 15, 2025', 'European Commission']
print(evaluate_extraction(predicted, ground_truth))

환각으로 생성된 개체 줄이기

모델이 원문에 존재하지 않는 개체를 추출하는 경우가 있습니다. 이를 환각이라고 합니다. 완화 전략은 다음과 같습니다:

  • 다음과 같이 지시합니다: 텍스트에 명시적으로 언급된 개체만 추출하십시오. 존재하지 않는 개체를 추론하거나 추가하지 마십시오.
  • 다음과 같이 지시합니다: 각 개체에 대해 텍스트에서 해당 개체가 나타나는 정확한 인용문을 포함하십시오.
  • 후처리에서 추출된 각 개체 문자열이 실제로 원문에 나타나는지 확인합니다
def anti_hallucination_extract(text):
    prompt = f'''
Extract ONLY entities that are explicitly present in the text below.
Do NOT infer, add, or supplement with external knowledge.
For each entity, include the exact quote from the text.

Return JSON: {{"entities": [{{"text": str, "type": str, "quote": str}}]}}

Text: {text}
'''
    r = client.messages.create(model='claude-opus-4-5', max_tokens=400, messages=[{'role': 'user', 'content': prompt}])
    extracted = json.loads(r.content[0].text)

    # Post-process: verify each entity appears in original text
    verified = [e for e in extracted['entities'] if e['text'].lower() in text.lower()]
    return {'entities': verified}

result = anti_hallucination_extract('Google announced a $5B investment in AI infrastructure.')
print(result)

상호참조 해결과 개체 연결

원시 개체 문자열을 추출한 후 다음 두 가지 추가 작업을 수행하면 후속 처리의 유용성이 향상됩니다:

  • 상호참조 해결: 그, 그 회사, 그것을 해당 대상인 개체명과 연결합니다
  • 개체 연결: 추출된 이름을 표준 식별자에 매핑합니다(예: "Apple" → apple_inc를 지식 기반에서 사용)

두 작업 모두 초기 추출 후 추가 프롬프트 단계에서 처리할 수 있습니다.

coref_prompt = '''
Resolve coreferences in the text below.
For each pronoun or definite reference (he, she, it, the company, the CEO),
identify which named entity it refers to.

Return JSON: {"coreferences": [{"text": str, "refers_to": str, "position": int}]}

Text: Apple released its new chip. The company said it would ship in Q4.
Tim Cook announced that he would present it at the fall event.
'''

print(coref_prompt)

빠른 확인

원문에 없는 개체를 모델이 추출하지 못하게 하는 가장 효과적인 방법은 무엇입니까?

개체명 추출 — 핵심 요약

프롬프트를 잘 설계하면 LLM 기반 개체명 추출은 유연하고 강력합니다:

  • 개체 유형을 명시적으로 정의합니다. PERSON, ORG, DATE, LOCATION, MONEY 및 도메인별 유형을 포함합니다
  • 프롬프트에 JSON 스키마를 사용하여 일관된 출력 구조를 강제합니다
  • 사용자 지정 개체 유형에 필드 정의를 추가하여 모델이 정확히 어떤 항목이 해당하는지 알 수 있도록 합니다
  • 개체 환각을 방지하기 위해 원문 인용을 요구합니다
  • 후처리에서 개체 형식을 정규화합니다(날짜는 ISO 형식으로, 이름은 제목 형식으로 변환)
  • 레이블이 지정된 테스트 집합을 기준으로 정밀도, 재현율, F1을 사용해 품질을 평가합니다
  • 일괄 처리에서는 한 번의 호출로 여러 문서를 처리하고 문서별로 구조화된 출력을 반환합니다

자주 묻는 질문

“명명된 개체 추출 프롬프트” 강의는 무료인가요?

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

“명명된 개체 추출 프롬프트”에서 뭘 배우나요?

비정형 텍스트에서 이름, 날짜, 위치 및 사용자 지정 개체를 추출합니다. 브라우저에서 직접 실행하는 실습 코드로 AI Prompt Engineering을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

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

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

“명명된 개체 추출 프롬프트” 강의는 얼마나 걸리나요?

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

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

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

이 강의의 모든 강의

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