Inferensys

Prompt

Spelling Error Detection and Correction Prompt Template

A practical prompt playbook for using Spelling Error Detection and Correction Prompt Template in production AI workflows.
Operations team reviewing AI workflow automation on laptop, workflow builder visible, casual office setup.
PROMPT PLAYBOOK

When to Use This Prompt

A practical guide for RAG operators and search engineers on where to deploy spelling correction as a pre-retrieval gate, and when to avoid it.

This prompt is designed for the specific job of cleaning noisy user input before it reaches your retrieval system. It is ideal for RAG operators and search engineers who observe that typos, misspellings, and keyboard errors in user queries are causing poor recall or irrelevant results from vector and keyword search backends. The core workflow is a pre-retrieval gate: a raw user query enters, and a corrected query with per-token confidence scores exits. This allows your application to make a programmatic decision—use the corrected query, fall back to the original, or ask the user for clarification—before spending compute on a doomed retrieval round.

You should use this prompt when user input is short-form and noisy, such as in a search bar or a chatbot interface, and your downstream retrieval system lacks native fuzzy matching or robust spelling tolerance. It is particularly valuable in domains with a mix of common words and highly specific jargon, where a generic spellchecker would 'fix' a technical term into a common word. The prompt's explicit instruction to preserve intentional technical terms and flag low-confidence corrections is the key differentiator from a simple library call. For example, a query like 'k8s pod err' should be corrected to 'Kubernetes pod error' with high confidence, while 'k8s' itself should be flagged as a deliberate term, not a misspelling of 'kids'. The confidence score is not just a number; it is a signal for your application logic. A low-confidence correction on a domain term should trigger a lookup against your internal glossary, not a blind replacement.

Do not use this prompt as a general-purpose text polisher or for correcting grammar in long-form documents. It is tuned for short, retrieval-critical strings. Avoid it when your retrieval system already performs robust spelling correction natively, or when the latency of an additional LLM call is unacceptable for your real-time requirements. If the user's query is fundamentally ambiguous or nonsensical, this prompt is not a solution; pair it with a separate query disambiguation or gibberish detection prompt. The next step after understanding this use case is to copy the prompt template, plug in your domain glossary as part of the [CONTEXT], and run it against a golden dataset of 50-100 real user queries to calibrate your confidence score thresholds before production deployment.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not.

01

Good Fit: Pre-Retrieval Query Cleaning

Use when: user queries contain common typos, misspellings, or character transpositions that degrade vector or keyword search recall. Guardrail: Run this prompt before embedding generation to prevent wasted retrieval compute on corrupted terms.

02

Bad Fit: Domain-Specific Jargon Correction

Avoid when: the query contains intentional technical terms, product codes, or domain shorthand that a general-purpose spell checker would incorrectly 'fix'. Guardrail: Pair this prompt with a domain glossary and an over-correction detection eval to preserve known terms.

03

Required Inputs: Query String and Context

What you need: a raw user query string and, optionally, a list of protected terms or a domain vocabulary to prevent false corrections. Guardrail: Without a protected-term list, the model may 'correct' valid technical identifiers, breaking retrieval for power users.

04

Operational Risk: Semantic Drift

What to watch: a spelling correction can accidentally change the meaning of a query, especially for short queries or ambiguous terms. Guardrail: Implement a semantic similarity check between the original and corrected query embeddings. Flag corrections that exceed a drift threshold for human review or clarification.

05

Operational Risk: Latency Budget

What to watch: adding an LLM call for spelling correction introduces latency to every retrieval request. Guardrail: Cache corrections for common misspellings and set a strict timeout. Fall back to the original query if the correction call exceeds the latency budget.

06

Bad Fit: Multilingual or Code-Switched Queries

Avoid when: users mix languages in a single query or write in a language the spell-check prompt is not calibrated for. Guardrail: Use a language detection step first. Route non-English or mixed-language queries to a specialized normalization prompt or skip correction to avoid introducing errors.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A production-ready prompt for detecting and correcting spelling errors in user queries before retrieval, preserving domain terminology and proper nouns.

This prompt template is designed to sit in front of your retrieval pipeline and clean user queries before they hit your vector database or search index. It corrects genuine spelling mistakes while preserving technical terms, product names, and proper nouns that might otherwise be flagged as errors by generic spellcheckers. The template outputs a corrected query string, a confidence score, and a list of changes made, giving you the audit trail needed for debugging retrieval failures.

text
You are a spelling correction system for search queries in a [DOMAIN] application. Your job is to fix genuine spelling errors while preserving intentional technical terms, product names, acronyms, and proper nouns.

INPUT QUERY:
[USER_QUERY]

DOMAIN GLOSSARY (DO NOT CORRECT THESE TERMS):
[DOMAIN_TERMS]

INSTRUCTIONS:
1. Identify tokens that appear to be misspelled based on standard [LANGUAGE] spelling.
2. For each candidate correction, check whether the token matches a known domain term, product name, acronym, or proper noun from the glossary. If it matches, do NOT correct it.
3. For tokens not in the glossary, apply minimal-edit correction that preserves the likely intended word.
4. Do not change word order, add words, remove words, or alter punctuation unless it is part of a spelling fix.
5. If the query contains multiple plausible corrections for the same token, select the one with highest likelihood given the surrounding context.
6. If no corrections are needed, return the original query unchanged with confidence 1.0.

OUTPUT SCHEMA:
Return valid JSON matching this structure:
{
  "original_query": "string",
  "corrected_query": "string",
  "confidence": number (0.0 to 1.0),
  "corrections": [
    {
      "original_token": "string",
      "corrected_token": "string",
      "position": number (0-indexed token position),
      "rationale": "string (brief explanation)"
    }
  ],
  "uncorrected_domain_terms": ["string"]
}

CONSTRAINTS:
- Never correct terms listed in the domain glossary.
- Never alter casing of proper nouns or acronyms.
- If confidence is below [MIN_CONFIDENCE_THRESHOLD], set corrected_query to original_query and flag for human review.
- Return ONLY the JSON object, no markdown fences or additional text.

To adapt this template, replace [DOMAIN] with a short description of your application domain, [LANGUAGE] with the expected input language, and [MIN_CONFIDENCE_THRESHOLD] with your acceptable confidence floor. The [DOMAIN_TERMS] placeholder should be populated at runtime with your controlled vocabulary, product catalog, or entity list. The [USER_QUERY] placeholder receives the raw user input. Wire the output JSON into a validator that checks schema compliance before forwarding the corrected_query to your retrieval backend. For high-stakes domains, route corrections with confidence below your threshold to a human review queue rather than silently executing them.

IMPLEMENTATION TABLE

Prompt Variables

Required and optional inputs for the spelling error detection and correction prompt. Validate each before sending to the model to prevent downstream retrieval failures.

PlaceholderPurposeExampleValidation Notes

[USER_QUERY]

The raw user input string containing potential spelling errors

How do I impliment a RAG pipline?

Required. Must be a non-empty string. Reject null or whitespace-only input before prompt assembly.

[DOMAIN_GLOSSARY]

A list of domain-specific terms, acronyms, and proper nouns that must not be corrected

['RAG', 'LLM', 'vectorstore', 'LangChain']

Optional but strongly recommended. Provide as a JSON array of strings. If null, the model may over-correct technical jargon.

[CORRECTION_SENSITIVITY]

Controls how aggressively the model corrects ambiguous tokens

low | medium | high

Optional. Defaults to medium. Use low for user-facing chat where preserving voice matters. Use high for backend retrieval where precision is critical.

[OUTPUT_SCHEMA]

The expected JSON structure for the corrected output

{ corrected_query: string, corrections: [{original: string, corrected: string, position: number, confidence: float}], unchanged_terms: string[] }

Required. Enforce this schema in the prompt and validate with a JSON schema validator post-response. Reject responses missing required fields.

[CONFIDENCE_THRESHOLD]

Minimum confidence score for a correction to be applied automatically

0.85

Optional. Float between 0.0 and 1.0. Corrections below this threshold should be flagged for human review or logged for audit. Default to 0.8 if not provided.

[MAX_CORRECTIONS]

Upper bound on the number of spelling corrections the model can propose

5

Optional. Integer. Prevents runaway correction on severely malformed input. If exceeded, the query should be rejected or escalated rather than over-corrected.

[LANGUAGE_CODE]

ISO 639-1 language code for the query language

en | de | fr | es

Optional. Defaults to en. Critical for multilingual deployments to prevent false-positive corrections on valid non-English words.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the spelling correction prompt into a production RAG pipeline with validation, retries, and safety checks.

This prompt is designed to sit as a pre-retrieval gate in your RAG pipeline. It receives the raw user query string and returns a corrected version before any embedding computation or vector search occurs. The primary integration point is a lightweight API endpoint or middleware function that intercepts the query, calls the LLM with this prompt template, validates the response, and then passes the corrected query downstream. You should never send the raw user query directly to your vector database or keyword index without first running it through this correction step—uncorrected typos produce near-zero cosine similarity to relevant documents and waste compute on irrelevant retrieval rounds.

Wire the prompt into your application with a validation wrapper that checks the LLM response before forwarding it. The expected output schema includes a corrected_query string, a confidence_score float between 0.0 and 1.0, and a corrections_applied array of before/after pairs. Your harness should: (1) parse the JSON response and reject malformed outputs, (2) verify the confidence score is within range, (3) compare the original and corrected strings—if they are identical, skip the correction step entirely to save a retrieval round, and (4) log the correction event with a trace ID for observability. For high-stakes domains like healthcare or legal search, add a confidence threshold gate: if confidence_score falls below 0.7, route the query to a human review queue rather than executing retrieval automatically. This prevents over-correction of domain jargon or proper nouns that the model is uncertain about.

Model choice matters here. Use a fast, inexpensive model for this gate because it runs on every user query before any other processing. GPT-4o-mini, Claude Haiku, or a fine-tuned small open-weight model are appropriate. Avoid large models for this step—the latency cost of a 70B+ parameter model on every keystroke will degrade user experience. Implement a retry strategy with exponential backoff (max 2 retries) for transient failures, but fail closed: if the correction service is unavailable after retries, pass the original query through with a correction_skipped flag rather than blocking the user. Finally, instrument this step with metrics: track correction rate, average confidence, over-correction complaints from users, and latency p95. These metrics will tell you when your prompt needs tuning or when your domain vocabulary has drifted beyond the model's correction capability.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the structured JSON payload returned by the spelling correction prompt. Use this contract to validate the model's response before passing the corrected query to your retrieval backend.

Field or ElementType or FormatRequiredValidation Rule

corrected_query

string

Must not be empty. Must differ from [ORIGINAL_QUERY] only where errors were detected. Length must be within 10% of original length unless major reconstruction was required.

original_query

string

Must exactly match the [ORIGINAL_QUERY] input passed to the prompt. Validate by string equality check.

corrections

array of objects

Array length must be >= 0. If empty, confidence_score should be >= 0.95. Each object must contain 'original_token', 'corrected_token', and 'position' fields.

corrections[].original_token

string

Must be a substring present in original_query. Case-sensitive match required.

corrections[].corrected_token

string

Must not be identical to original_token. Must be a valid word or preserved technical term from [PROTECTED_TERMS] list if provided.

corrections[].position

object

Must contain 'start' and 'end' integer fields representing character offsets in original_query. start must be less than end.

confidence_score

number (float 0.0-1.0)

Must be between 0.0 and 1.0 inclusive. If corrections array is empty, score must be >= 0.95. If corrections exist, score should reflect the lowest per-correction confidence.

preserved_terms

array of strings

If [PROTECTED_TERMS] input was provided, this field must list which protected terms were detected and left unchanged. Validate each entry exists in the input protected terms list.

PRACTICAL GUARDRAILS

Common Failure Modes

Spelling correction prompts fail in predictable ways. Here are the most common production failure modes and how to guard against them before they degrade retrieval quality.

01

Over-Correction of Domain Jargon

What to watch: The model 'fixes' legitimate technical terms, product names, or acronyms into common words. 'Kubernetes' becomes 'Kuber nets', 'PostgreSQL' becomes 'Postgres SQL', breaking retrieval against internal knowledge bases. Guardrail: Provide a domain glossary as a protected term list in the prompt. Instruct the model to preserve any term matching the glossary exactly. Add a post-correction check that flags any changed term found in the protected list.

02

Proper Noun Destruction

What to watch: Person names, company names, and location names get normalized into dictionary words. 'Nguyen' becomes 'Engine', 'Xero' becomes 'Zero', causing entity resolution failures downstream. Guardrail: Include a named entity preservation instruction. Use a separate NER pass before correction to identify and lock entities. Test against a curated list of known proper nouns from your system's entity store.

03

Intent Drift During Correction

What to watch: A typo fix changes the semantic meaning of the query. 'Show me unapproved PRs' corrected to 'Show me approved PRs' inverts the user's intent entirely. Guardrail: Compute embedding similarity between the original and corrected query. Set a minimum cosine similarity threshold. If the score drops below the threshold, flag for human review or fall back to the original query with a clarification prompt.

04

Silent Correction of Intentional Shorthand

What to watch: Users in technical domains use deliberate abbreviations and shorthand that the model expands incorrectly. 'k8s' becomes 'keys', 'db' becomes 'database' when the user meant a specific DB instance name. Guardrail: Maintain a known-shorthand registry. Pass it as a locked token list. If the model proposes a correction for a registered shorthand, reject the change and preserve the original form.

05

Confidence Miscalibration

What to watch: The model reports high confidence on wrong corrections or low confidence on obvious fixes. This breaks any downstream logic that gates retrieval on a confidence threshold, causing either bad queries to pass or good corrections to be blocked. Guardrail: Calibrate confidence scores against a held-out correction dataset. Log every correction with its confidence score and the ground-truth outcome. Use these logs to tune your acceptance threshold and detect drift over time.

06

Multi-Language Token Confusion

What to watch: Queries containing mixed-language terms get monolingual corrections applied. A French product name in an English query gets anglicized, or a code snippet gets grammar-corrected. Guardrail: Add a language detection step before correction. For mixed-language queries, apply correction only to tokens matching the primary language. Preserve tokens detected as code, identifiers, or non-primary languages unchanged.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the quality of spelling correction outputs before deploying the prompt in a production RAG pipeline. Use these checks to prevent over-correction of domain terms and ensure intent preservation.

CriterionPass StandardFailure SignalTest Method

Spelling Error Detection

All genuine spelling errors in [INPUT_QUERY] are identified and corrected

Missed typos remain in [CORRECTED_QUERY] output

Run against a golden dataset of 100 queries with known spelling errors; require >95% recall on error detection

Domain Term Preservation

Technical terms, product names, and domain jargon from [DOMAIN_GLOSSARY] are not altered

A glossary term is changed to a common word (e.g., 'Kubernetes' to 'Kuber nets')

Inject 20 domain-specific terms into test queries; assert zero false corrections on glossary items

Proper Noun Handling

Person names, company names, and branded terms retain original casing and spelling

A proper noun is lowercased or respelled (e.g., 'McDonald' to 'Mac Donald')

Test with a list of 50 known proper nouns embedded in queries; require exact match preservation

Intent Preservation

The corrected query preserves the user's original search intent as measured by embedding similarity

Embedding cosine similarity between [INPUT_QUERY] and [CORRECTED_QUERY] drops below 0.92

Compute embedding similarity on 200 query-correction pairs; flag any pair below threshold for human review

Confidence Score Calibration

[CONFIDENCE_SCORE] values correlate with actual correction accuracy

High-confidence corrections (>0.9) are wrong more than 5% of the time

Bin corrections by confidence decile; measure observed error rate per bin; require monotonic calibration curve

Over-Correction Rate

No valid words are incorrectly flagged as errors and changed

A correctly spelled word is replaced with a different word (false positive correction)

Run against a clean query set with zero spelling errors; require <1% false correction rate

Multi-Language Stability

Queries containing mixed-language terms or non-English words are not corrupted

A non-English word is anglicized or replaced (e.g., 'café' to 'cafe' when diacritic matters)

Test with 30 queries containing code-switched or loanword terms; require zero unintended normalizations

Acronym Conflict Avoidance

Acronyms that overlap with common misspellings are preserved when context supports them

A valid acronym is expanded or corrected (e.g., 'AWS' to 'WAS')

Create a conflict test set of 15 acronyms that resemble typos; require context-aware preservation in >90% of cases

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a small test set of 20-30 misspelled queries. Use a frontier model with default temperature (0). Skip confidence scoring and focus on getting corrected strings. Store corrections in a flat JSON log for manual review.

code
Correct the spelling in this search query. Preserve technical terms, product names, and proper nouns exactly as written.

Query: [USER_QUERY]

Return only the corrected query string.

Watch for

  • Over-correction of domain jargon (e.g., 'Kubernetes' → 'Kuber nets')
  • No mechanism to flag ambiguous corrections
  • Silent failures on mixed-language queries
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.