พรอมป์ตสำหรับการดึงเอนทิตีที่มีชื่อ
ดึงชื่อ วันที่ สถานที่ และเอนทิตีแบบกำหนดเองจากข้อความที่ไม่มีโครงสร้าง
พรอมป์ตสำหรับการดึงเอนทิตีที่มีชื่อ เป็นบทเรียน AI Prompt Engineering ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน AI Prompt Engineering และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส AI Prompt Engineering มีบทเรียนทั้งหมด 4 บทเรียน
การสกัดเอนทิตีที่มีชื่อคืออะไร
การสกัดเอนทิตีที่มีชื่อ (NER) คือภารกิจในการระบุและจัดหมวดหมู่เอนทิตีเฉพาะในโลกจริงที่กล่าวถึงในข้อความ การประมวลผลภาษาธรรมชาติแบบดั้งเดิมใช้โมเดลทางสถิติสำหรับ NER ส่วน LLM สามารถทำงานนี้ได้ด้วยพรอมต์ที่ออกแบบมาอย่างดี
ประเภทเอนทิตีที่พบบ่อย:
- PERSON: ชื่อบุคคล (Elon Musk, Dr. Jane Smith)
- ORG: บริษัทและองค์กร (Apple, WHO)
- DATE: วันที่และนิพจน์บอกเวลา (15 มกราคม, วันอังคารที่แล้ว, ไตรมาส 3 ปี 2024)
- LOCATION: สถานที่ (New York, แม่น้ำอะเมซอน)
- MONEY: ตัวเลขทางการเงิน (4.2 พันล้านดอลลาร์)
พรอมต์ 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 โดยเทียบกับชุดการทดสอบที่มีการกำกับป้ายกำกับ
- สำหรับการประมวลผลเป็นชุด ให้ประมวลผลเอกสารหลายฉบับในการเรียกใช้ครั้งเดียว พร้อมผลลัพธ์ที่มีโครงสร้างแยกตามเอกสาร
คำถามที่พบบ่อย
บทเรียน “พรอมป์ตสำหรับการดึงเอนทิตีที่มีชื่อ” ฟรีหรือไม่
ใช่ — ข้อความเต็มของ “พรอมป์ตสำหรับการดึงเอนทิตีที่มีชื่อ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส AI Prompt Engineering ให้อัปเกรดเป็น CoddyKit PRO คอร์ส AI Prompt Engineering มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “พรอมป์ตสำหรับการดึงเอนทิตีที่มีชื่อ”
ดึงชื่อ วันที่ สถานที่ และเอนทิตีแบบกำหนดเองจากข้อความที่ไม่มีโครงสร้าง คุณปฏิบัติ AI Prompt Engineering ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน AI Prompt Engineering หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน AI Prompt Engineering บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน
บทเรียน “พรอมป์ตสำหรับการดึงเอนทิตีที่มีชื่อ” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน AI Prompt Engineering นี้ได้ไหม
ได้ บทเรียน AI Prompt Engineering ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- พรอมป์ตสำหรับการดึงเอนทิตีที่มีชื่อ
- การดึงข้อมูลโดยขับเคลื่อนด้วยสคีมา
- LLM ในฐานะตัวจำแนกข้อความ
- ความมั่นใจและความไม่แน่นอนในการจำแนก