AI Prompt Engineering · Lezione

Prompt per l'estrazione di entità nominate

Estragga nomi, date, luoghi ed entità personalizzate da testo non strutturato

Lezione 1 di 413 passaggi

Prompt per l'estrazione di entità nominate è una lezione AI Prompt Engineering gratuita su CoddyKit. Questa è la lezione 1 di 4. Puoi leggere la lezione completa qui gratuitamente — poi esercitati direttamente nel browser con un editor di codice integrato e un tutor IA disponibile 24/7. Fa parte del percorso di apprendimento AI Prompt Engineering, e i tuoi progressi si sincronizzano tra il web e l'app CoddyKit. Il corso AI Prompt Engineering include 4 lezioni in totale.

Che cos'è l'estrazione di entità denominate?

L'estrazione di entità denominate (NER) è il processo di identificazione e categorizzazione di entità specifiche del mondo reale menzionate nel testo. L'NLP tradizionale utilizza modelli statistici per la NER; gli LLM possono eseguire questo compito con un prompt ben progettato.

Tipi comuni di entità:

  • PERSON: Nomi di persona (Elon Musk, Dr. Jane Smith)
  • ORG: Aziende e organizzazioni (Apple, WHO)
  • DATE: Date ed espressioni temporali (15 gennaio, martedì scorso, T3 2024)
  • LOCATION: Luoghi (New York, il fiume Amazon)
  • MONEY: Importi finanziari ($4,2 miliardi)

Prompt NER di base

Il prompt NER più semplice richiede tutte le entità in un formato specifico:

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))

Aggiunta di vincoli sui tipi all'estrazione

L'estrazione di base restituisce le stringhe delle entità. I vincoli sui tipi aggiungono la validazione, assicurando che le date siano in un formato specifico e che le organizzazioni escludano le parole comuni:

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.')

Estrazione basata su schema

Per l'utilizzo in produzione, definisca in anticipo lo schema delle entità e lo riporti nel prompt. In questo modo il contratto dell'output diventa esplicito:

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])

Gestione delle entità ambigue

Alcune stringhe di entità sono ambigue: Apple potrebbe indicare l'azienda o il frutto, mentre Jordan potrebbe indicare una persona o un Paese. Guida il modello a risolvere l'ambiguità usando il contesto:

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)

Estrazione con definizioni dei campi

Per i tipi di entità personalizzati specifici del proprio dominio, fornisca nel prompt le definizioni dei campi, così il modello saprà esattamente cosa deve includere:

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)

Estrazione in batch delle entità

Per elaborare più documenti, l'estrazione in batch è più efficiente. Progetti il prompt in modo che gestisca più input e restituisca un risultato strutturato per ogni documento:

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 delle entità estratte

Le entità estratte spesso richiedono un post-processing prima di poter essere utilizzate:

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))

Valutazione della qualità dell'estrazione

La qualità della NER viene misurata con precisione, richiamo e punteggio F1 rispetto a un set di test annotato:

  • Precisione: di tutte le entità estratte, quale frazione è corretta?
  • Richiamo: di tutte le entità reali, quale frazione è stata estratta?
  • F1: media armonica di precisione e richiamo
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))

Riduzione delle entità allucinate

A volte i modelli estraggono entità che non esistono nel testo sorgente: si tratta di allucinazioni. Strategie di mitigazione:

  • Specifichi: Estragga solo le entità menzionate esplicitamente nel testo. Non deduca né aggiunga entità non presenti.
  • Specifichi: Per ogni entità, includa la citazione esatta del testo in cui compare.
  • Esegua il post-processing: verifichi che ogni stringa di entità estratta compaia effettivamente nel testo originale
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)

Coreferenze e collegamento delle entità

Dopo aver estratto le stringhe grezze delle entità, due attività aggiuntive migliorano l'utilità per le elaborazioni successive:

  • Risoluzione delle coreferenze: collega lui, l'azienda ed esso all'entità denominata a cui si riferiscono
  • Collegamento delle entità: associa i nomi estratti a identificatori canonici (ad esempio, "Apple" → apple_inc in una knowledge base)

Entrambe le attività possono essere gestite con un ulteriore passaggio del prompt dopo l'estrazione iniziale.

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)

Verifica rapida

Qual è il modo più efficace per impedire a un modello di estrarre entità non presenti nel testo sorgente?

Estrazione di entità denominate: concetti fondamentali

L'estrazione di entità denominate basata su LLM è flessibile e potente quando il prompt è ben progettato:

  • Definisca esplicitamente i tipi di entità: PERSON, ORG, DATE, LOCATION, MONEY e i tipi specifici del dominio
  • Utilizzi uno schema JSON nel prompt per imporre una struttura coerente dell'output
  • Aggiunga definizioni dei campi per i tipi di entità personalizzati, così il modello saprà esattamente cosa è idoneo
  • Richieda citazioni dal testo sorgente per evitare allucinazioni delle entità
  • Esegua il post-processing per normalizzare i formati delle entità (date in formato ISO, nomi con maiuscole iniziali)
  • Valuti la qualità con precisione, richiamo e F1 rispetto a un set di test annotato
  • Per i batch, elabori più documenti in un'unica chiamata con un output strutturato per ogni documento
Gratis per iniziare

Impara AI Prompt Engineering con un tutor IA — gratis

Scrivi ed esegui vero codice nel tuo browser, ricevi aiuto istantaneo da un tutor IA disponibile 24/7, e riprendi da dove hai lasciato sul web o nell'app.

Corsi
53
Lezioni
199

Domande Frequenti

La lezione «Prompt per l'estrazione di entità nominate» è gratuita?

Sì — il testo completo di «Prompt per l'estrazione di entità nominate» è gratuito qui sul web. Per esercitarvi in modo interattivo (un editor di codice integrato e un tutor IA 24/7) e sbloccare il resto del corso AI Prompt Engineering, passa a CoddyKit PRO. Il corso AI Prompt Engineering include 4 lezioni in totale.

Cosa imparerò in «Prompt per l'estrazione di entità nominate»?

Estragga nomi, date, luoghi ed entità personalizzate da testo non strutturato Eserciti AI Prompt Engineering con codice pratico che esegui direttamente nel browser, e un tutor IA 24/7 risponde alle tue domande mentre lavori sulla lezione.

Ho bisogno di esperienza per iniziare AI Prompt Engineering?

Non è richiesta alcuna esperienza precedente. AI Prompt Engineering su CoddyKit è strutturato per principianti e studenti avanzati, quindi puoi iniziare da qui o dall'inizio e procedere al tuo ritmo. Questa è la lezione 1 di 4.

Quanto tempo richiede la lezione «Prompt per l'estrazione di entità nominate»?

La maggior parte delle lezioni CoddyKit richiede circa 5–10 minuti. Ogni lezione è breve e interattiva, quindi fai progressi costanti e riprendi esattamente da dove hai lasciato su web e app.

Posso scrivere ed eseguire codice in questa lezione AI Prompt Engineering?

Sì. Ogni lezione AI Prompt Engineering include un editor di codice integrato, quindi scrivi ed esegui codice reale direttamente nel tuo browser e ricevi feedback istantaneo dall'IA — nessuna configurazione locale necessaria.

Tutte le lezioni di questo corso

  1. Prompt per l'estrazione di entità nominate
  2. Estrazione dei dati guidata dallo schema
  3. LLM come classificatore di testo
  4. Affidabilità e incertezza nella classificazione
← Torna a AI Prompt Engineering