Inferensys

Prompt

Entity Extraction with Source Attribution Prompt Template

A practical prompt playbook for extracting entities with traceable source attribution in production AI workflows for audit and compliance teams.
Wide-angle shot of a modern WeWork open floor plan with creative walls covered in AI system architecture diagrams, product team collaborating in standing desk area with industrial lighting.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the specific job-to-be-done, ideal user, and operational boundaries for the entity extraction with source attribution prompt.

This prompt is designed for audit, compliance, and legal review teams who need to extract named entities from unstructured text and anchor every extracted entity to its exact source span, sentence, or document section. Use this when downstream consumers require traceable provenance for every fact, when extraction results must survive external audit, or when you need to distinguish between explicitly stated entities and those merely implied by context. This prompt is not a general-purpose NER tool. It is purpose-built for evidentiary extraction where the source citation is as important as the entity itself.

The ideal workflow involves feeding this prompt a single, self-contained document or a clearly delimited section of text. The model is instructed to return a structured list of entities, each with a mandatory source_span (the exact text from which the entity was derived), a source_location (e.g., 'Paragraph 3, Sentence 2'), and an attribution_confidence (explicit vs. inferred). Do not use this prompt for high-throughput, real-time extraction where latency is critical and source tracing is unnecessary; a standard NER model will be faster and cheaper. Similarly, avoid this prompt for analyzing conversational chat logs where the 'document' boundary is ambiguous—prefer a dedicated transcript extraction playbook instead.

Before integrating this prompt into a production pipeline, you must define the evaluation criteria for attribution accuracy. A successful implementation requires a human-annotated golden dataset where every entity is paired with its correct source span. Run this prompt against that dataset and measure Exact Match (EM) on the source spans, not just entity type accuracy. If the model consistently paraphrases the source span instead of quoting it verbatim, you will need to tighten the constraints in the prompt or add a post-processing validation step that checks if the source_span is a substring of the original document. In high-risk domains like legal or financial compliance, always route extractions with attribution_confidence: inferred to a human review queue before they enter any downstream system of record.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Entity extraction with source attribution is a high-precision workflow for audit and compliance, not a general-purpose extraction tool.

01

Good Fit: Audit and Compliance Workflows

Use when: every extracted entity must be traceable to its source span, sentence, or document section for regulatory review. Guardrail: require exact source offsets or citation keys in the output schema; reject extractions without anchors.

02

Bad Fit: High-Volume, Low-Latency Pipelines

Avoid when: throughput and latency matter more than provenance. Source attribution adds token overhead and validation steps. Guardrail: use a simpler extraction prompt without attribution for real-time ingestion; reserve this prompt for audit samples or compliance batches.

03

Required Inputs

What you need: unstructured source text, a defined entity schema (types, canonical forms), and a citation format (span offsets, sentence index, or section ID). Guardrail: validate that source text is clean enough for span-level attribution; noisy OCR or transcripts may produce broken offsets.

04

Operational Risk: Attribution Drift

What to watch: the model may attribute an entity to the wrong sentence or fabricate a source span when the entity is implied but not explicitly stated. Guardrail: add a validation step that checks each citation against the original text; flag mismatches for human review.

05

Operational Risk: Implied Entity Handling

What to watch: entities that are inferred from context but never explicitly mentioned (e.g., 'the CEO' when the name is absent). Guardrail: require a separate evidence_type field (explicit vs. inferred) and route inferred entities to a review queue before ingestion.

06

Variant: Partial Attribution Mode

Use when: full span-level attribution is too expensive but you still need document-level provenance. Guardrail: modify the prompt to accept document-section or page-level attribution instead of exact spans; clearly label the attribution granularity in the output schema.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt for extracting entities from text and anchoring each to its exact source span, sentence, or section for audit-grade traceability.

This template is the core instruction set for an entity extraction task where every output must be attributable. It is designed to be copied directly into your AI harness, with square-bracket placeholders that you replace with your specific document content, target entity types, and output schema. The prompt enforces a strict contract: no entity should appear in the output without a corresponding source citation, and no source citation should be fabricated.

text
You are an entity extraction system designed for audit and compliance workflows. Your primary directive is to anchor every extracted entity to its exact source span, sentence, or document section. You will be given [INPUT_TEXT] and a list of target entity types defined in [ENTITY_TYPES].

Your task:
1. Identify all mentions of the entity types specified in [ENTITY_TYPES] within [INPUT_TEXT].
2. For each identified entity, extract the exact text span from [INPUT_TEXT] that serves as the primary evidence for the entity.
3. Normalize the entity to its canonical form according to the rules in [NORMALIZATION_RULES]. If no canonical form can be determined, use the mention text.
4. Assign a confidence score between 0.0 and 1.0 for each extraction, following the [CONFIDENCE_RUBRIC].
5. Output the results strictly as a JSON array conforming to [OUTPUT_SCHEMA].

Critical constraints:
- Do not extract an entity if you cannot find an explicit source span in [INPUT_TEXT]. Do not infer entities from context alone.
- For each entity, the `source_span` field must contain a verbatim substring from [INPUT_TEXT]. You must be able to find this exact string in the text.
- If an entity is mentioned multiple times, include a separate entry for each distinct mention, or consolidate them into a single entry with an array of `source_spans` as specified in [OUTPUT_SCHEMA].
- If [INPUT_TEXT] contains no entities of a given type, return an empty array for that type. Do not fabricate entities to fill the schema.
- If the text is ambiguous, set the confidence score accordingly and include a brief `attribution_note` explaining the ambiguity.

[EXAMPLES]

[INPUT_TEXT]: {{document_content}}
[ENTITY_TYPES]: {{entity_types_list}}
[NORMALIZATION_RULES]: {{normalization_instructions}}
[CONFIDENCE_RUBRIC]: {{confidence_criteria}}
[OUTPUT_SCHEMA]: {{json_schema}}

To adapt this template for your own use, replace each placeholder with concrete instructions. The [ENTITY_TYPES] placeholder should contain a clear list like ["PERSON", "ORGANIZATION", "LOCATION", "DATE"]. The [NORMALIZATION_RULES] should specify how to handle variations—for example, "Resolve 'Inc.' and 'Incorporated' to the full legal name if known." The [CONFIDENCE_RUBRIC] is critical for downstream automation; a typical rubric might state: "1.0: Exact match with unambiguous source span. 0.8: Clear match but entity type is slightly ambiguous. 0.5: Multiple possible interpretations exist. Below 0.5: Do not extract." The [OUTPUT_SCHEMA] must be a valid JSON Schema that downstream systems can validate against. The [EXAMPLES] section is optional but strongly recommended for complex entity types or edge cases. After replacing the placeholders, test the prompt against a golden dataset of documents with known entities and source spans to verify that attribution is accurate and no hallucinations occur.

IMPLEMENTATION TABLE

Prompt Variables

Inputs the prompt needs to work reliably. Validate each before sending to the model. Missing or malformed variables are the most common cause of silent extraction failures and broken source attribution.

PlaceholderPurposeExampleValidation Notes

[DOCUMENT_TEXT]

The full unstructured text to extract entities from. Must be plain text with no truncated sentences.

The agreement is entered into by Acme Corp...

Check length > 0 and < model context limit. Reject if null, empty, or only whitespace. Truncation must preserve sentence boundaries.

[ENTITY_TYPES]

A JSON array of entity types to extract. Controls which categories the model searches for.

["PERSON", "ORGANIZATION", "DATE", "LOCATION"]

Must be a valid JSON array. Each element must be a non-empty string. Reject if empty array. Validate against allowed type enum.

[OUTPUT_SCHEMA]

The exact JSON schema the model must conform to. Includes field names, types, and required fields.

{"type": "object", "properties": {"entities": {"type": "array"...

Must be valid JSON Schema. Must include 'entities' array with 'mentionText', 'entityType', 'canonicalForm', 'sourceSpan', 'confidence' fields. Reject if schema is malformed.

[ATTRIBUTION_GRANULARITY]

Specifies the required level of source anchoring: span, sentence, paragraph, or section.

"span"

Must be one of: "span", "sentence", "paragraph", "section". Reject any other value. Span mode requires character offsets; sentence mode requires sentence index.

[CONFIDENCE_THRESHOLD]

Minimum confidence score for automated acceptance. Entities below this threshold must be flagged for human review.

0.75

Must be a float between 0.0 and 1.0. Reject if non-numeric or out of range. Null allowed only if confidence filtering is disabled downstream.

[CANONICALIZATION_RULES]

Rules for normalizing extracted entity text to a standard form. May include case folding, suffix stripping, or KB linking instructions.

"Strip legal suffixes (Inc, Ltd, GmbH). Resolve to Wikidata QID if match confidence > 0.9."

Must be a non-empty string or null. If null, canonicalForm should match mentionText. Reject if rules reference unavailable KB endpoints.

[MAX_ENTITIES]

Hard limit on the number of entities to return. Prevents runaway extraction on long documents.

50

Must be a positive integer. Reject if 0 or negative. Set a reasonable default (e.g., 100) if not provided. Model should prioritize highest-confidence entities if limit is exceeded.

[ABSTENTION_POLICY]

Instruction for when no entities of a requested type are found. Controls whether to return empty array, explicit null, or a flag.

"Return empty array with a top-level 'extractionComplete' flag set to true."

Must be a non-empty string. Reject if null. Policy must be parseable by downstream ingestion. Common options: empty array, null field, or explicit 'noneFound' boolean.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Entity Extraction with Source Attribution prompt into a production application with validation, retry logic, and human review gates.

The Entity Extraction with Source Attribution prompt is designed to be a single step within a larger extraction pipeline, not a standalone chat interaction. In production, you will call this prompt for each document or text segment that requires entity extraction. The application layer is responsible for splitting long documents into manageable chunks that fit within the model's context window while preserving sentence boundaries for accurate source attribution. Each chunk should be processed independently, and the application must maintain a mapping of chunk IDs to their original document positions so that extracted spans can be resolved back to absolute offsets or section references in the source document. The prompt expects a [TEXT] input containing the raw text to analyze and an [ENTITY_TYPES] parameter listing the entity categories to extract (e.g., PERSON, ORGANIZATION, LOCATION, DATE). The output is a JSON array of entity objects, each containing the entity type, mention text, canonical form, confidence score, and a source attribution object with the exact text span, sentence index, and character offsets.

Validation must occur immediately after the model response is received and before any extracted entities are written to downstream systems. Implement a JSON schema validator that checks every entity object for required fields (entity_type, mention_text, source_attribution.span_text, source_attribution.offsets). The validator should also confirm that each source_attribution.span_text is a verbatim substring of the original [TEXT] input at the claimed character offsets. If the span text does not match the source text at those offsets, the entity should be flagged for review rather than silently accepted. Additionally, implement a deduplication check: if two extracted entities share the same mention text and entity type within overlapping source spans, merge them or flag the conflict. For high-stakes use cases such as legal contract review or financial filing extraction, route all entities with a confidence score below a configurable threshold (default 0.85) to a human review queue. The review interface should display the original source text with the extracted span highlighted, the model's proposed entity, and a simple accept/reject/edit form.

Retry logic should be applied selectively. If the model response fails JSON parsing entirely, retry once with the same prompt but append a brief repair instruction: The previous output was not valid JSON. Return ONLY a valid JSON array of entity objects. If the retry also fails, log the failure with the raw response and escalate to a human operator. Do not retry more than twice for the same input, as repeated failures often indicate an input quality problem (e.g., garbled text, encoding issues) rather than a transient model error. For partial failures where most entities validate but a few have attribution mismatches, accept the valid entities and route only the failed ones to review. Log every extraction run with the prompt version, model identifier, input hash, output entity count, validation pass/fail status, and any entities sent to review. This audit trail is essential for compliance teams who need to demonstrate that every extracted fact is traceable to its source.

Model choice matters for attribution accuracy. Models with strong instruction-following and JSON mode support (such as GPT-4o, Claude 3.5 Sonnet, or Gemini 1.5 Pro) produce more reliable span offsets than smaller or older models. If you are using a model that does not support structured output or JSON mode natively, increase the retry budget and consider adding a post-processing step that uses fuzzy string matching to locate the claimed span in the source text when exact offset matching fails. For high-volume pipelines, implement batching where multiple text chunks are processed concurrently, but ensure each chunk's validation and review routing is independent so that one bad chunk does not block the entire batch. Finally, treat the prompt template as versioned code: store it in your repository alongside the validation schema, retry configuration, and review queue routing rules. When you update the prompt, run your eval suite against a golden dataset of annotated documents to confirm that attribution accuracy does not regress before deploying the change to production.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, format, and validation rules that downstream systems depend on for the Entity Extraction with Source Attribution prompt. Every extracted entity must be traceable to its source span.

Field or ElementType or FormatRequiredValidation Rule

entities

array of objects

Must be a JSON array. If no entities are found, return an empty array, not null or a missing key.

entities[].entity_text

string

Must be a non-empty string exactly matching the span in [SOURCE_TEXT]. Leading/trailing whitespace must be trimmed.

entities[].entity_type

enum string

Must be one of the allowed types defined in [ENTITY_TYPES]. Case-sensitive match required. Reject any type not in the schema.

entities[].canonical_form

string or null

If a canonical form is resolved, provide the normalized string. If resolution fails or is not applicable, use null. Do not use an empty string.

entities[].source_attribution

object

Must contain at least one of 'sentence_index', 'char_offset_start', or 'document_section'. All provided fields must be validated for range against [SOURCE_TEXT].

entities[].source_attribution.sentence_index

integer or null

If provided, must be a zero-based index within the sentence array of [SOURCE_TEXT]. Null if attribution uses a different method.

entities[].source_attribution.char_offset_start

integer or null

If provided, must be a valid character index where entity_text begins in [SOURCE_TEXT]. Null if attribution uses a different method. Must be verified with a substring check.

entities[].confidence

number

Must be a float between 0.0 and 1.0 inclusive. Values below [CONFIDENCE_THRESHOLD] should trigger a review flag in the application layer.

PRACTICAL GUARDRAILS

Common Failure Modes

Entity extraction with source attribution breaks in predictable ways. These are the most common failure modes in production and the guardrails that catch them before they corrupt downstream audit trails.

01

Attribution Drift Across Long Documents

What to watch: The model correctly extracts an entity but attributes it to the wrong sentence, paragraph, or section—especially in documents longer than 4K tokens where attention dilutes. The entity is real, but the source pointer is wrong, breaking audit traceability. Guardrail: Chunk the document before extraction, run attribution per chunk, and post-validate that every attributed span actually contains the extracted entity string. Flag mismatches for human review.

02

Implied Entity Hallucination with Fabricated Attribution

What to watch: The model infers an entity that is logically implied but never stated in the text, then fabricates a source span to satisfy the attribution requirement. The output looks grounded but the citation points to text that does not contain the entity. Guardrail: Run a strict string-containment check: the extracted entity mention must appear verbatim in the cited source span. If it does not, either drop the entity or reclassify it as inferred with no source span and flag for review.

03

Partial Attribution When Entities Span Multiple Mentions

What to watch: An entity appears multiple times in a document with different attributes revealed across mentions. The model attributes the canonical entity to only the first mention, losing provenance for attributes drawn from later spans. Guardrail: Require the output schema to support an array of source spans per entity, not a single span. Post-process to verify that every extracted attribute can be traced to at least one cited span. Flag entities where attributes lack source coverage.

04

Co-referent Confusion in Attribution Chains

What to watch: The document refers to an entity with pronouns, aliases, or definite descriptions (

05

Attribution Collapse in Tabular or Structured Text

What to watch: Entities extracted from tables, lists, or key-value pairs lose row, column, or cell-level attribution. The model cites the entire table or section as the source, making it impossible to trace which cell produced which entity. Guardrail: Pre-process structured regions with a table-aware parser before extraction. If using a pure text prompt, require row-level or cell-level attribution in the output schema and validate that source spans are granular enough to isolate individual cells.

06

Confidence Mismatch Between Entity and Attribution

What to watch: The model assigns high confidence to an extracted entity but the attributed source span is ambiguous or contradictory, or vice versa. The confidence score reflects entity correctness but not attribution reliability, misleading downstream trust decisions. Guardrail: Require separate confidence scores for entity correctness and attribution accuracy in the output schema. If attribution confidence is low, route to human review even when entity confidence is high. Never collapse these into a single score.

IMPLEMENTATION TABLE

Evaluation Rubric

Run these checks against a golden dataset of 50-100 annotated documents before shipping. Each criterion targets a specific failure mode in entity extraction with source attribution. Use automated checks where possible; reserve manual review for attribution accuracy and implied entity handling.

CriterionPass StandardFailure SignalTest Method

Entity Recall

≥95% of annotated entities extracted

Missing entities in output; recall below threshold

Automated: compare extracted entity spans against golden annotations using strict span overlap

Entity Precision

≥95% of extracted entities match golden annotations

Hallucinated entities; type confusion; boundary errors

Automated: flag extracted entities with no overlapping golden annotation; measure false-positive rate

Source Attribution Accuracy

≥90% of attributions point to correct source span

Attribution points to wrong sentence or paragraph; citation offset mismatch

Manual review: sample 50 attributions and verify source span contains the entity mention

Attribution Granularity

Each entity has exactly one source reference at sentence or paragraph level

Missing attribution field; multiple conflicting attributions; document-level-only attribution

Automated schema check: verify [SOURCE_SPAN] field is present, non-null, and contains a single reference

Canonical Form Correctness

≥90% of canonical forms match golden canonical annotations

Wrong canonical form; alias used instead of canonical; normalization rule not applied

Automated: compare [CANONICAL_FORM] field against golden canonical value using exact or fuzzy match per entity type

Implied Entity Handling

Implied entities are flagged with [IS_EXPLICIT]=false and confidence ≤0.7

Implied entity marked as explicit; high confidence on inferred entity without evidence

Manual review: identify all entities with [IS_EXPLICIT]=false and verify no explicit span exists in source

Null vs. Missing Discrimination

[NULL_REASON] populated correctly for absent entity types

Entity type missing from output instead of present with null reason; wrong null reason code

Automated: verify output contains all expected entity type keys; check [NULL_REASON] values against document ground truth

Confidence Score Calibration

High-confidence entities (≥0.85) have ≤5% error rate; low-confidence (<0.7) routed correctly

High-confidence entity is wrong; low-confidence entity is correct but not escalated

Automated: bucket entities by confidence band; measure error rate per band; verify escalation threshold triggers

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a simple JSON schema. Focus on getting entity types and source spans correct before adding canonicalization or confidence scoring. Use a lightweight validator that checks for required fields (entity_text, entity_type, source_span) but tolerates missing optional fields.

code
Extract all entities from [INPUT_TEXT]. Return JSON array with:
- entity_text: exact text from source
- entity_type: PERSON | ORG | LOCATION | DATE | PRODUCT
- source_span: {start: char_index, end: char_index}

Watch for

  • Boundary errors where entity spans cut off prefixes or suffixes
  • Type confusion between overlapping categories (e.g., 'Apple' as ORG vs PRODUCT)
  • Missing source offsets when the model paraphrases instead of quoting
  • No confidence signals, so every extraction looks equally certain
Prasad Kumkar

About the author

Prasad Kumkar

CEO & MD, Inference Systems

Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.

His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.