Named Entity Extraction Prompts
Extracting names, dates, locations, and custom entities from unstructured text.
Named Entity Extraction Prompts is a free AI Prompt Engineering lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the AI Prompt Engineering learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
What Is Named Entity Extraction?
Named entity extraction (NER) is the task of identifying and categorizing specific real-world entities mentioned in text. Traditional NLP uses statistical models for NER; LLMs can do it with a well-designed prompt.
Common entity types:
- PERSON: People's names (Elon Musk, Dr. Jane Smith)
- ORG: Companies and organizations (Apple, WHO)
- DATE: Dates and time expressions (January 15, last Tuesday, Q3 2024)
- LOCATION: Places (New York, the Amazon River)
- MONEY: Financial figures ($4.2 billion)
Basic NER Prompt
The simplest NER prompt asks for all entities in a specific format:
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))Adding Type Constraints to Extraction
Basic extraction returns entity strings. Type constraints add validation — ensuring that dates are in a specific format, and that organizations exclude common words:
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.')Schema-Driven Extraction
For production use, define the entity schema upfront and reference it in the prompt. This makes the output contract explicit:
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])Handling Ambiguous Entities
Some entity strings are ambiguous — Apple could be the company or the fruit, Jordan could be a person or a country. Guide the model to resolve ambiguity using context:
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)Extraction with Field Definitions
For custom entity types specific to your domain, provide field definitions in the prompt so the model knows exactly what counts:
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)Batch Entity Extraction
For processing multiple documents, batch extraction is more efficient. Design the prompt to handle multiple inputs and return a structured result per document:
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))Post-Processing Extracted Entities
Extracted entities often need post-processing before use:
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))Evaluating Extraction Quality
NER quality is measured with Precision, Recall, and F1 score against a labeled test set:
- Precision: Of all extracted entities, what fraction are correct?
- Recall: Of all true entities, what fraction were extracted?
- F1: Harmonic mean of precision and recall
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))Reducing Hallucinated Entities
Models sometimes extract entities that do not exist in the source text — hallucinations. Mitigation strategies:
- Instruct: Only extract entities explicitly mentioned in the text. Do not infer or add entities not present.
- Instruct: For each entity, include the exact quote from the text where it appears.
- Post-process: verify each extracted entity string actually appears in the original text
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)Coreference and Entity Linking
After extracting raw entity strings, two additional tasks improve downstream usefulness:
- Coreference resolution: Linking he, the company, and it back to the named entity they refer to
- Entity linking: Mapping extracted names to canonical identifiers (e.g., "Apple" → apple_inc in a knowledge base)
Both can be handled with an additional prompt step after initial extraction.
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)Quick Check
What is the most effective way to prevent a model from extracting entities not present in the source text?
Named Entity Extraction — Key Takeaways
LLM-based named entity extraction is flexible and powerful when the prompt is well-designed:
- Define entity types explicitly — PERSON, ORG, DATE, LOCATION, MONEY, and domain-specific types
- Use a JSON schema in the prompt to enforce consistent output structure
- Add field definitions for custom entity types so the model knows exactly what qualifies
- Require source quotes to prevent entity hallucination
- Post-process to normalize entity formats (dates to ISO, names to title case)
- Evaluate quality with precision, recall, and F1 against a labeled test set
- For batches, process multiple documents in one call with structured per-document output
Frequently asked questions
Is the “Named Entity Extraction Prompts” lesson free?
Yes — the full text of “Named Entity Extraction Prompts” is free to read here on the web, and the AI Prompt Engineering course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the AI Prompt Engineering course, upgrade to CoddyKit PRO.
What will I learn in “Named Entity Extraction Prompts”?
Extracting names, dates, locations, and custom entities from unstructured text. You practise AI Prompt Engineering with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start AI Prompt Engineering?
No prior experience is required. AI Prompt Engineering on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Named Entity Extraction Prompts” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this AI Prompt Engineering lesson?
Yes. Every AI Prompt Engineering lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Named Entity Extraction Prompts
- Schema-Driven Data Extraction
- LLM as Text Classifier
- Confidence and Uncertainty in Classification