This prompt is designed for document pipeline engineers who need to repair OCR-extracted text from scanned documents before it flows into downstream systems like RAG indexes, structured extraction pipelines, or archival databases. The core job-to-be-done is turning error-prone raw OCR output into clean, faithful text that preserves the original document's meaning, structure, and domain-specific terminology. The ideal user is someone building a production ingestion pipeline where OCR errors—split words, misread characters, garbled tables, or corrupted proper nouns—will break entity extraction, search relevance, or compliance audits if left uncorrected.
Prompt
Scanned Document OCR Correction Prompt Template

When to Use This Prompt
Define the job, the ideal user, and the operational boundaries for the scanned document OCR correction prompt.
Use this prompt when you have raw text output from an OCR engine (Tesseract, AWS Textract, Azure Document Intelligence, or similar) and you need a corrected version that is safe for machine consumption. The prompt is most effective when you can supply domain-specific dictionaries (e.g., a list of valid product codes, legal terms, or medical vocabulary) and format-aware correction rules (e.g., 'invoice numbers match pattern INV-\d{6}'). It expects you to provide the raw OCR text, an optional context snippet describing the document type, and a set of constraints that define what a valid correction looks like. The output includes corrected text, a confidence score per correction, and explicit flags for spans where the model is uncertain—giving your pipeline the signals it needs to decide whether to auto-accept, queue for human review, or escalate.
Do not use this prompt when the OCR quality is so degraded that the source text is effectively unrecoverable without visual re-inspection of the original scan. This prompt corrects text, not images; it cannot see the original document. If the raw OCR output is missing entire paragraphs, has swapped page order, or contains unreadable glyphs with no linguistic signal, the correction will be speculative at best. In those cases, re-scanning or using a layout-aware OCR model with visual features is the right first step. Similarly, do not use this prompt as a substitute for structured field extraction—it produces corrected running text, not typed JSON records. For extraction, pair this prompt upstream of a schema extraction prompt that consumes the cleaned output.
Before deploying, build a validation harness that compares corrected output against a golden dataset of manually verified document pairs. Measure character error rate (CER) and word error rate (WER) reduction, but also track the rate of uncertain flags—if more than 15% of corrections are flagged as low confidence, your pipeline likely needs better upstream OCR or a narrower domain dictionary. Always log the raw input, corrected output, confidence scores, and flag counts per document for auditability. In regulated domains like healthcare or legal, route all flagged corrections to a human review queue and never auto-accept corrections on documents where errors could cause harm.
Use Case Fit
Where the Scanned Document OCR Correction Prompt Template delivers value and where it introduces unacceptable risk. Use these cards to decide if this prompt fits your pipeline before investing engineering time.
Good Fit: Downstream Structured Extraction
Use when: You need to feed scanned documents into a strict-schema extraction pipeline (invoices, contracts, forms) and OCR errors cause field-level failures. Guardrail: Run correction before extraction, not after. Measure improvement by comparing extraction completeness rates with and without the correction step.
Good Fit: Domain-Specific Dictionaries Available
Use when: You maintain a controlled vocabulary of domain terms, product names, client names, or regulatory phrases that the base OCR engine frequently mangles. Guardrail: Supply the dictionary as part of [CONTEXT]. Track correction-override rates to detect when the dictionary is stale or missing new terms.
Bad Fit: Real-Time or Low-Latency Pipelines
Avoid when: You need sub-second correction latency on high-throughput document streams. LLM-based correction adds cost and latency. Guardrail: Use this prompt for batch or async processing. For real-time needs, consider a smaller, fine-tuned model or a deterministic spell-correction layer first, reserving LLM correction for low-confidence cases only.
Bad Fit: Handwriting or Severely Degraded Scans
Avoid when: The source document is primarily handwritten or the scan quality is so poor that the base OCR produces near-gibberish. Guardrail: Implement a pre-check that estimates OCR quality (character confidence scores from the OCR engine). Route documents below a threshold to a human review queue instead of attempting automated correction that may introduce plausible but incorrect text.
Required Inputs: OCR Text with Confidence Metadata
What to watch: Sending raw text without per-word or per-character confidence scores forces the model to guess. Guardrail: Always include OCR confidence metadata in [INPUT] when available. The prompt should instruct the model to preserve high-confidence tokens and only rewrite low-confidence spans, reducing the risk of correcting what was already correct.
Operational Risk: Silent Semantic Corruption
Risk: The model corrects a low-confidence OCR error with a contextually plausible but factually wrong term (e.g., correcting a misread drug name or financial figure). Guardrail: Flag all corrections with a confidence score in [OUTPUT_SCHEMA]. Route corrections below a configurable threshold to a human review queue. Never auto-commit corrected text into a system of record without audit trail support.
Copy-Ready Prompt Template
A reusable prompt template for correcting OCR errors in scanned documents with confidence scoring and domain-specific dictionaries.
This prompt template is designed to be dropped into your document processing pipeline immediately after the OCR engine and before any downstream extraction or classification steps. It expects raw OCR output—complete with its typical artifacts: split words, misrecognized characters, merged columns, and garbled headers—and returns a structured correction payload that your application can validate and route. The template uses square-bracket placeholders so you can swap in your own domain dictionaries, output schemas, and risk thresholds without rewriting the core instruction logic.
textYou are a document correction engine. Your task is to repair OCR errors in the provided text while preserving the original meaning, structure, and formatting intent. [CONTEXT] Document type: [DOCUMENT_TYPE] Domain: [DOMAIN] Expected sections: [EXPECTED_SECTIONS] [DOMAIN_DICTIONARY] Correct terms, proper nouns, and expected vocabulary for this domain: [DICTIONARY_ENTRIES] [INPUT] Raw OCR text: [OCR_TEXT] [OUTPUT_SCHEMA] Return a valid JSON object with this exact structure: { "corrected_text": "the full corrected document text", "corrections": [ { "original_span": "the OCR text that was corrected", "corrected_span": "the replacement text", "position": {"start": 0, "end": 0}, "confidence": 0.0, "correction_type": "spelling|word_split|word_merge|number_fix|punctuation|layout_recovery|domain_term|case_fix" } ], "uncertain_spans": [ { "span": "text the model is unsure about", "position": {"start": 0, "end": 0}, "reason": "why confidence is low", "suggested_action": "human_review|dictionary_check|context_clarify" } ], "layout_notes": ["description of recovered columns, tables, or section breaks"], "overall_confidence": 0.0 } [CONSTRAINTS] 1. Never change numbers, dates, monetary amounts, or legal references unless you are certain of the correction. Flag uncertain numeric corrections in uncertain_spans. 2. Use the domain dictionary to resolve ambiguous words. If a word matches a dictionary entry with high confidence, prefer that correction. 3. Preserve paragraph breaks, list structures, and table layouts. Note any layout recovery in layout_notes. 4. For words split across line breaks (common in OCR), merge them and record the correction with type "word_merge". 5. Flag any span where confidence is below [CONFIDENCE_THRESHOLD] in uncertain_spans with a suggested action. 6. Do not rewrite, summarize, or improve the text. Only correct OCR errors. 7. If the entire document appears to be garbled or unreadable, set overall_confidence below 0.3 and include a note in layout_notes. [EXAMPLES] Input: "The agr eement shall term inate on Decem ber 31 , 2025" Output correction: "agr eement" -> "agreement" (word_merge, confidence 0.98), "term inate" -> "terminate" (word_merge, confidence 0.98), "Decem ber" -> "December" (word_merge, confidence 0.97) Input: "Pursuant to Section l.2(a) of the Agr eement" Output correction: "l.2(a)" -> "1.2(a)" (number_fix, confidence 0.85, flag if legal document) Now correct the provided OCR text following these rules.
Adaptation notes: Replace [DOCUMENT_TYPE] with the specific format (invoice, contract, report, form) to activate format-aware correction rules. Populate [DOMAIN_DICTIONARY] with a list of expected proper nouns, technical terms, product names, and common abbreviations for your domain—this is the single highest-leverage field for improving correction accuracy. Set [CONFIDENCE_THRESHOLD] based on your risk tolerance; 0.7 is a reasonable starting point for most pipelines, but lower it to 0.5 for high-recall use cases or raise it to 0.9 when downstream actions are irreversible. The [EXPECTED_SECTIONS] field helps the model recognize when layout recovery is needed—list the section headers that should appear in a well-formed document of this type.
What to do next: After copying this template, run it against a golden dataset of 20–30 documents where you have both the raw OCR output and the ground-truth corrected text. Measure precision and recall on the corrections array, not just the corrected_text string—this lets you tune the confidence threshold and identify which correction types (word_merge, number_fix, etc.) cause the most errors. If overall_confidence consistently falls below your threshold for a document type, consider upgrading your OCR engine or adding pre-processing steps before routing to this prompt. For high-risk domains like legal or financial documents, always route uncertain_spans to a human review queue before the corrected text enters any downstream system.
Prompt Variables
Required inputs for the scanned document OCR correction prompt. Each placeholder must be populated before the prompt is assembled and sent to the model. Missing or malformed inputs are the most common cause of silent correction failures in production.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[OCR_TEXT] | Raw OCR output from the document scanning pipeline that requires correction | Th1s 1s a sc4nned d0cument w1th err0rs. | Must be a non-empty string. Reject null or zero-length input before prompt assembly. Check for control characters and encoding issues that indicate upstream OCR failure. |
[DOCUMENT_TYPE] | Expected document category to activate format-aware correction rules and domain dictionaries | invoice | Must match one of the allowed enum values: invoice, contract, report, form, letter, receipt, statement, or unknown. Invalid values should trigger a routing error before the prompt is sent. |
[DOMAIN_DICTIONARY] | JSON array of domain-specific terms, product names, or entity values that the OCR engine frequently misrecognizes | ["Amoxicillin", "Metformin", "HbA1c"] | Must be a valid JSON array of strings. Empty array is allowed. Each term should be checked for length under 100 characters. Terms exceeding this limit are likely data errors and should be truncated or rejected. |
[LANGUAGE_CODE] | ISO 639-1 language code for the primary document language to select the correct character set and spelling model | en | Must be a valid two-letter ISO 639-1 code. Reject codes not in the allowed set: en, es, fr, de, ja, zh, ar, pt, ru, it, nl, ko. Unknown codes should default to en with a warning log entry. |
[CONFIDENCE_THRESHOLD] | Minimum confidence score for automatic correction acceptance; corrections below this threshold are flagged for human review | 0.85 | Must be a float between 0.0 and 1.0. Values outside this range should be clamped. A threshold of 0.0 disables human review flags. A threshold of 1.0 forces all corrections to review. Log the effective threshold in trace metadata. |
[OUTPUT_SCHEMA] | JSON Schema definition for the expected output structure including corrected text, confidence scores, and review flags | {"type": "object", "properties": {"corrected_text": {"type": "string"}, "corrections": {"type": "array"}, "review_required": {"type": "boolean"}}} | Must be a valid JSON Schema object. Validate with a schema parser before prompt assembly. Reject schemas that are missing required fields: corrected_text, corrections, and review_required. Schema drift between versions must be logged. |
[MAX_CORRECTION_DISTANCE] | Maximum edit distance allowed for a single correction to prevent over-aggressive rewriting of heavily degraded text | 3 | Must be a positive integer. Values above 10 should trigger a warning as they risk introducing hallucinated content. A value of 0 disables all corrections. Default to 3 if not provided. |
Implementation Harness Notes
How to wire the OCR correction prompt into a production document pipeline with validation, retries, and human review.
The OCR correction prompt is not a standalone utility—it is a processing stage inside a larger document ingestion pipeline. The typical harness receives raw OCR text from an upstream extraction service (Tesseract, Azure Document Intelligence, Amazon Textract), enriches it with domain-specific dictionaries and format rules, calls the LLM, validates the corrected output, and routes low-confidence results to a human review queue before passing clean text to downstream systems like search indexes, databases, or NLP classifiers.
Validation is the most critical harness component. After the model returns corrected text and confidence scores, run a post-processing validator that checks: (1) the output text length is within a reasonable delta of the input length—large deviations suggest hallucinated insertions or deletions; (2) any [DOMAIN_DICTIONARY] terms appear in their canonical form; (3) format-specific rules are enforced, such as date patterns matching [DATE_FORMAT] or currency values conforming to [CURRENCY_FORMAT]; (4) the confidence array has an entry for every correction the model claims to have made. If validation fails, retry once with the validation errors appended to the prompt as additional [CONSTRAINTS]. If the retry also fails, route the document to a human review queue with the original OCR text, the failed corrected output, and the specific validation errors.
For model choice, prefer models with strong instruction-following and structured output support—GPT-4o, Claude 3.5 Sonnet, or Gemini 1.5 Pro all work well. Use the model's native structured output or JSON mode to enforce the {corrected_text, corrections: [{original, corrected, confidence, reason}]} schema rather than relying on prompt instructions alone. Set temperature to 0 or very low (0.1) to minimize creative rewrites. For high-throughput pipelines, batch multiple pages or documents into a single request where context windows allow, but keep batches small enough that a single failure does not block a large queue. Log every request and response pair, including the raw OCR input, the domain dictionary version used, the model and its configuration, the corrected output, validation results, and the final routing decision (auto-accepted, retried, or escalated). This audit trail is essential for debugging correction drift and for compliance in regulated industries.
When wiring this into a production system, avoid treating the LLM correction as the final step. Always run a diff between the original OCR and the corrected text to detect silent changes—corrections the model made but did not report in the corrections array. Flag any unreported change above a character-count threshold for human review. Also implement a circuit breaker: if the correction failure rate exceeds a configured threshold (e.g., 20% of documents require human review), pause automated processing and investigate whether the OCR engine, domain dictionary, or model behavior has changed. This prompt is a high-precision tool, not a fire-and-forget service.
Expected Output Contract
Defines the exact structure, types, and validation rules for the corrected OCR output. Use this contract to build downstream parsers, validation checks, and ingestion adapters before deploying the prompt.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
corrected_text | string | Must not be empty. Length must be within 5% of original [RAW_OCR_TEXT] character count to prevent truncation or hallucinated expansion. | |
corrections | array of objects | Each object must contain original, corrected, and confidence keys. Array length must be >= 0. If empty, confidence_summary.overall_confidence must be >= 0.95. | |
corrections[].original | string | Must be a verbatim substring found in [RAW_OCR_TEXT]. If not found, flag as hallucinated_span in validation logs. | |
corrections[].corrected | string | Must differ from original by at least one character. Null or empty string indicates the correction was attempted but failed; set confidence to 0.0 in that case. | |
corrections[].confidence | number | Float between 0.0 and 1.0 inclusive. Values below [MIN_CONFIDENCE_THRESHOLD] must trigger a human review flag in the calling application. | |
confidence_summary | object | Must contain overall_confidence and low_confidence_count. overall_confidence is the mean of all correction confidences, or 1.0 if corrections array is empty. | |
uncertain_spans | array of strings | Each entry must be a substring from [RAW_OCR_TEXT] that the model considered ambiguous but did not correct. Used for audit trails. Null allowed if no uncertain spans exist. | |
domain_terms_applied | array of strings | Each entry must match a term from [DOMAIN_DICTIONARY]. Used to verify that domain-specific corrections were considered. Null allowed if no dictionary was provided. |
Common Failure Modes
What breaks first when correcting OCR output from scanned documents and how to prevent downstream data corruption.
Hallucinated Corrections on Low-Confidence Text
Risk: The model confidently 'corrects' illegible or ambiguous text into plausible but wrong values, especially for proper nouns, numbers, and financial figures. This is the most dangerous failure mode because the output looks correct. Guardrail: Require the prompt to output a confidence score (0-1) for every corrected token. Route any token below a threshold (e.g., 0.85) to a human review queue. Never auto-commit low-confidence corrections to a system of record.
Domain Dictionary Over-Correction
Risk: A supplied domain dictionary (e.g., product names, legal terms) forces the model to map every similar-looking string to a known term, erasing legitimate novel entries or rare variants. Guardrail: Include explicit instructions to prefer the raw OCR text when the edit distance is high. Add a correction_source field to the output schema (dictionary, context, model_inference) so reviewers can audit whether a correction was forced by the dictionary or inferred from context.
Format-Aware Rule Violations
Risk: The model applies generic spelling corrections that break format-specific rules, such as 'correcting' a valid part number AB-1234 to AB-1234 (no change) or incorrectly normalizing a date format that was already correct for the target locale. Guardrail: Provide explicit format preservation rules in the prompt (e.g., 'Do not change the structure of identifiers matching regex [A-Z]{2}-\d{4}'). Add a post-processing validation step that flags any field where the corrected value violates the expected format pattern.
Layout-Induced Context Collapse
Risk: Multi-column layouts, sidebars, and headers/footers cause the OCR engine to interleave text from different sections. The model then attempts to correct this garbled stream, producing nonsensical but grammatically fluent output. Guardrail: Pre-process the document with a layout parser to segment text blocks before sending them to the correction prompt. Instruct the model to flag segments where the semantic coherence drops suddenly, indicating a likely layout boundary error.
Silent Dropping of Uncertain Spans
Risk: Instead of flagging an unreadable word, the model omits it entirely from the corrected output, producing a shorter, cleaner text that is missing critical information. Guardrail: Require the output to preserve the original token count or include a placeholder like [UNREADABLE] for any span the model cannot confidently correct. Implement a length ratio check in the validation layer—if the corrected text is significantly shorter than the input, flag it for review.
Numerical Value Corruption
Risk: Digits are notoriously difficult for OCR, and the model may transpose numbers, drop decimal points, or misread currency symbols, leading to catastrophic errors in financial or scientific documents. Guardrail: Apply a dedicated numerical validation pass after correction. Check that all numbers in the output are arithmetically consistent (e.g., line items sum to totals). Flag any corrected number that differs from the raw OCR value for mandatory human approval before ingestion.
Evaluation Rubric
Use this rubric to test the quality of corrected OCR output before integrating it into a downstream document pipeline. Each criterion targets a specific failure mode common in scanned document correction.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Domain Dictionary Adherence | All corrections for terms in [DOMAIN_DICTIONARY] match the canonical form exactly. | A known domain term is 'corrected' to a non-canonical spelling or a different term entirely. | Parse the corrected text, extract all tokens, and cross-reference against the provided [DOMAIN_DICTIONARY] list. Flag any mismatch. |
Confidence Score Calibration | At least 90% of tokens with a confidence score below [LOW_CONFIDENCE_THRESHOLD] are genuinely ambiguous or illegible in the source. | A clearly legible word in the source image is assigned a low confidence score, or a completely illegible word is assigned a high score. | Sample 20 low-confidence and 20 high-confidence tokens. Manually review the source image to verify the assigned score is appropriate. |
Format Preservation | The output preserves the original document's paragraph breaks, list structures, and table layouts as specified in [OUTPUT_FORMAT]. | A bulleted list is output as a single paragraph, or a multi-column table is flattened into an unreadable text block. | Run a structural diff between the raw OCR output and the corrected output. The number of structural elements (paragraphs, list items) should not decrease unless explicitly requested. |
Uncertainty Flagging | Every correction that is not a direct character-level fix is wrapped in an [UNCERTAINTY_FLAG] and included in the | A word is completely changed based on context (e.g., 'test' to 'text') but no flag is present in the output. | Parse the |
No Hallucinated Content | The corrected text contains no words, numbers, or punctuation marks that cannot be traced to a character or word in the raw OCR input. | A date, name, or figure appears in the corrected output that is completely absent from the raw OCR text. | Use a text diffing tool to compare the raw OCR input and the corrected output. All additions must be character-level substitutions or deletions, not new semantic content. |
Downstream Schema Compatibility | The | The output JSON fails to parse, a required field like | Validate the entire model response against the [OUTPUT_SCHEMA] using a JSON schema validator. The test must pass with zero errors. |
Legibility Threshold Handling | Sections of the raw OCR marked as illegible (e.g., '...', '???') are replaced with a placeholder defined in [ILLEGIBLE_PLACEHOLDER] and flagged for human review. | An illegible section is either silently deleted or the model hallucinates a plausible replacement without a review flag. | Search the corrected output for the [ILLEGIBLE_PLACEHOLDER] token. Verify that each instance corresponds to a gap or garbled text in the raw OCR input. |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Use the base prompt with a frontier model and minimal validation. Focus on getting the correction logic right before adding infrastructure. Replace [DOMAIN_DICTIONARY] with a short inline list of 10-20 domain terms. Skip confidence scoring and output only corrected text.
Watch for
- Over-correction of technical terms not in the dictionary
- Model guessing at illegible characters instead of flagging them
- No way to measure improvement over raw OCR output

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.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us