This prompt is designed for production RAG operators who ingest noisy text from automatic speech recognition (ASR) systems, mobile keyboards, or multilingual users typing in a non-native script. The core job-to-be-done is to correct spelling errors in a source-language query by analyzing phonetic similarity before the query is translated and sent to a retrieval engine. Without this correction layer, a garbled transcription—such as 'shocolat' instead of 'chocolat'—propagates through the translation step and yields nonsense retrieval results, degrading the entire RAG pipeline. The ideal user is an engineer or ML operator who already has a translation step in their retrieval stack and observes error propagation from upstream noise.
Prompt
Multilingual Query Correction with Phonetic Similarity Prompt

When to Use This Prompt
Defines the pre-translation correction job, the ideal user, and the boundaries where this prompt should not be applied.
Use this prompt when your retrieval pipeline includes a translation step and you can provide a source language label, a target retrieval language label, and the raw query string. The prompt expects these three inputs and returns a corrected query in the source language, a confidence score, and an explanation of the changes made. This output is designed to be passed directly to your translation model, not to the retrieval engine. The confidence score acts as a gating mechanism: you can route low-confidence corrections to a human review queue or log them for offline analysis. The explanation field provides an audit trail, which is critical for debugging retrieval failures in production.
Do not use this prompt for grammar correction, query expansion, or translation itself. Those are separate downstream steps with different failure modes and evaluation criteria. If your input is already clean text, this prompt adds latency without benefit. If your retrieval pipeline does not include a translation step, you should use a monolingual spelling correction prompt instead. This prompt is also not a substitute for improving your ASR model or keyboard language detection; it is a tactical fix for error propagation, not a strategic solution to input quality. For high-stakes domains like legal or medical retrieval, always route low-confidence corrections to human review before the query proceeds to translation.
Use Case Fit
Where the Multilingual Query Correction with Phonetic Similarity prompt delivers value and where it introduces risk. Use these cards to decide if this prompt belongs in your retrieval pipeline.
Good Fit: Voice-to-Text Pipelines
Use when: user queries originate from ASR systems that produce phonetically plausible but orthographically incorrect text, especially for named entities or domain terms. Guardrail: always log the original ASR transcript alongside the corrected query for audit and ASR model improvement.
Good Fit: User-Generated Typo Recovery
Use when: search queries come from mobile or fast-typing users where spelling errors follow phonetic patterns (e.g., 'farmacia' for 'pharmacy'). Guardrail: set a confidence threshold on the correction; if the model's confidence is low, retrieve against both the original and corrected query and fuse results.
Bad Fit: Semantic or Conceptual Errors
Avoid when: the user's query is spelled correctly but uses the wrong term conceptually (e.g., 'affect' vs 'effect'). Phonetic correction will not catch these and may introduce incorrect terms. Guardrail: pair this prompt with a separate semantic validation step or intent classifier before retrieval.
Required Input: Language Identification
Risk: phonetic similarity rules differ across languages; applying English phonetic heuristics to a Spanish query produces nonsense corrections. Guardrail: require a language identifier or user locale as a mandatory input field. If language is unknown, run detection first and refuse correction if confidence is below 0.9.
Operational Risk: Over-Correction of Rare Terms
Risk: the model may 'correct' rare but valid domain terms, product names, or surnames into more common words, destroying retrieval precision. Guardrail: maintain a protected terms list for your domain and skip correction for any token matching that list. Log all corrections for periodic review by a search relevance engineer.
Operational Risk: Latency Budget Blowout
Risk: adding a phonetic correction step before translation and retrieval increases end-to-end latency, which is especially damaging for real-time voice interfaces. Guardrail: set a strict timeout on the correction step. If it does not complete within your p95 latency budget, fall back to the original query and flag the interaction for async analysis.
Copy-Ready Prompt Template
A reusable prompt template for correcting spelling errors in multilingual queries using phonetic similarity before translation and retrieval.
This prompt template is designed to be dropped directly into your query preprocessing pipeline. It takes a potentially misspelled or phonetically ambiguous user query in a source language and produces a corrected version by reasoning about how the query would sound to a native speaker. The correction step happens before any translation or retrieval, preventing error propagation into downstream vector or keyword searches. The template uses square-bracket placeholders for all dynamic inputs, making it safe to template in code without accidental variable injection.
textYou are a multilingual query correction engine. Your task is to correct spelling errors in a user query by reasoning about phonetic similarity in the source language. You must produce a corrected query that a native speaker would recognize as the intended input. [INPUT] Source Query: [USER_QUERY] Source Language (ISO 639-1): [SOURCE_LANG] [CONTEXT] Domain: [DOMAIN] Common Misspelling Patterns in [SOURCE_LANG]: [MISSPELLING_PATTERNS] Phonetic Alphabet Reference: [PHONETIC_ALPHABET] [OUTPUT_SCHEMA] Return a valid JSON object with the following fields: - corrected_query: The spelling-corrected query in the source language. - corrections_applied: An array of objects, each with {original_token, corrected_token, confidence (0.0-1.0), reason}. - phonetic_ambiguity_flag: Boolean indicating if multiple plausible corrections exist. - alternative_corrections: An array of alternative corrected queries if phonetic_ambiguity_flag is true. [CONSTRAINTS] - Do not translate the query. Correction must remain in [SOURCE_LANG]. - Do not change the meaning or add information. Only fix spelling. - If the query is already correct, return it unchanged with an empty corrections_applied array. - For names, brands, or domain terms, prefer the canonical spelling from [DOMAIN] context. - If confidence is below 0.7 for any correction, set phonetic_ambiguity_flag to true. [EXAMPLES] Input: "recieve pakage" (English) Output: {"corrected_query": "receive package", "corrections_applied": [{"original_token": "recieve", "corrected_token": "receive", "confidence": 0.95, "reason": "common i-before-e error"}, {"original_token": "pakage", "corrected_token": "package", "confidence": 0.92, "reason": "phonetic substitution of k for ck"}], "phonetic_ambiguity_flag": false, "alternative_corrections": []} Input: "shudule maintanance" (English) Output: {"corrected_query": "schedule maintenance", "corrections_applied": [{"original_token": "shudule", "corrected_token": "schedule", "confidence": 0.88, "reason": "phonetic mapping of sh to sch"}, {"original_token": "maintanance", "corrected_token": "maintenance", "confidence": 0.85, "reason": "vowel sequence error"}], "phonetic_ambiguity_flag": false, "alternative_corrections": []}
To adapt this template, replace the placeholders with your runtime values. [USER_QUERY] and [SOURCE_LANG] are mandatory. [DOMAIN] should be a short string like "e-commerce" or "medical" to ground the correction in your vocabulary. [MISSPELLING_PATTERNS] is optional but highly recommended for non-English languages where you can supply known error patterns (e.g., common diacritic omissions in French or vowel confusions in Arabic transliteration). [PHONETIC_ALPHABET] can be set to "IPA" or a language-specific phonetic system to guide the model's reasoning. The [EXAMPLES] section is static in this template but you should extend it with 2-3 real examples from your production logs to improve few-shot accuracy. The output schema is strict JSON; validate it in your application layer before passing the corrected_query to your translation or retrieval step. If phonetic_ambiguity_flag is true, log the alternatives and consider routing to a human review queue or running parallel retrievals with each candidate.
Prompt Variables
Required and optional inputs for the Multilingual Query Correction with Phonetic Similarity Prompt. Validate each before sending to the model to prevent garbage-in, garbage-out behavior in production retrieval pipelines.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[SOURCE_QUERY] | The raw user input containing potential spelling errors, typos, or voice-to-text artifacts in the source language | Wie komme ich zum Banhof | Must be a non-empty string. Check for null, empty, or whitespace-only input. Reject if length exceeds 500 characters to prevent abuse. |
[SOURCE_LANGUAGE] | ISO 639-1 or BCP-47 language code identifying the language of [SOURCE_QUERY] | de | Must match a supported language code from your configured set. Validate against an allowlist. If null or 'auto', run a language detection step first and inject the detected code. |
[TARGET_LANGUAGE] | ISO 639-1 or BCP-47 language code for the corrected and translated output query | en | Must be a valid language code. Must differ from [SOURCE_LANGUAGE] if translation is intended. Validate against the same allowlist as [SOURCE_LANGUAGE]. |
[PHONETIC_ALPHABET] | The phonetic encoding algorithm to apply for similarity matching | DoubleMetaphone | Must be one of an enumerated set: 'Soundex', 'DoubleMetaphone', 'Caverphone', or 'MatchRating'. Default to 'DoubleMetaphone' if not provided. Reject unknown values. |
[DOMAIN_CONTEXT] | Optional domain or terminology scope to bias correction toward specific vocabulary | transportation | If provided, must be a non-empty string from a predefined domain list. If null, the model uses general vocabulary. Validate against an allowlist of supported domains to prevent prompt injection via this field. |
[MAX_CANDIDATES] | Maximum number of corrected query candidates the model should return for evaluation | 3 | Must be an integer between 1 and 5. Default to 3 if not provided. Reject values outside this range to control latency and cost in the retrieval pipeline. |
[CONFIDENCE_THRESHOLD] | Minimum confidence score required for a correction to be used automatically without human review | 0.85 | Must be a float between 0.0 and 1.0. If the top candidate's score falls below this threshold, route to a human review queue instead of proceeding to retrieval. Default to 0.8 if not provided. |
Implementation Harness Notes
How to wire the multilingual phonetic correction prompt into a production retrieval pipeline with validation, logging, and fallback controls.
This prompt is designed to sit immediately before query translation and retrieval in a RAG pipeline. It accepts a raw user query—often from voice-to-text or mobile input—and returns a corrected version with phonetic similarity annotations. The harness should treat this as a synchronous pre-processing step: the corrected query is passed directly to the next stage (translation, expansion, or retrieval) without persisting intermediate state unless audit logging is required. Because the prompt operates on potentially noisy input, the harness must enforce a strict timeout (2–3 seconds) and a maximum input length (typically 500 characters) to prevent runaway processing on garbled or excessively long voice transcripts.
Wire the prompt into your application as a typed function with a clear contract. The function signature should accept a source_query: str, source_language: str (ISO 639-1 code), and an optional phonetic_alphabet: str (defaulting to 'IPA' but supporting 'Soundex' or 'Metaphone' variants). The return type is a structured object containing corrected_query: str, corrections: list[dict] (each with original_token, corrected_token, phonetic_distance, and confidence), and a correction_applied: bool flag. Validate the output against this schema immediately after the model responds. If the model returns malformed JSON or missing required fields, retry once with a stricter output constraint appended to the prompt. After a second failure, log the raw response and fall back to the original uncorrected query to avoid blocking the retrieval pipeline.
For production observability, instrument the harness with three key metrics: correction rate (percentage of queries where correction_applied is true), average phonetic distance of applied corrections, and schema validation failure rate. Log every correction event with the original query, corrected query, and confidence scores to a structured logging system. This data is essential for tuning the confidence threshold at which corrections are accepted versus discarded. A practical starting threshold is confidence >= 0.7; corrections below this should be logged but not applied, and the original query should proceed unchanged. For high-stakes domains like healthcare or legal retrieval, route all corrections above a phonetic distance of 0.5 to a human review queue before they enter the retrieval step.
Model choice matters here. This prompt works best with models that have strong multilingual phonetic awareness—GPT-4o, Claude 3.5 Sonnet, and Gemini 1.5 Pro all perform well. Smaller or open-weight models may struggle with rare language pairs or produce hallucinated phonetic transcriptions. If using a local model, test extensively on a golden dataset of 200+ real misspellings across your target languages before deploying. The harness should support model routing: use a fast, cheap model for common language pairs (e.g., English-Spanish) and escalate to a more capable model for low-resource language pairs or when the initial correction confidence is below threshold. Avoid chaining this prompt with other LLM calls in sequence without caching the corrected query—re-running phonetic correction on the same input wastes tokens and adds latency.
Expected Output Contract
Defines the exact JSON structure, field types, and validation rules for the multilingual phonetic query correction prompt output. Use this contract to parse, validate, and integrate the model response into your retrieval pipeline.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
corrected_query | string | Must be non-empty. Length must not exceed 3x the character count of [ORIGINAL_QUERY]. Must differ from [ORIGINAL_QUERY] if corrections were made. | |
original_query | string | Must exactly match the [ORIGINAL_QUERY] input string. Used for downstream audit comparison. | |
corrections_applied | array of objects | Each object must contain 'original_token', 'corrected_token', and 'reason' fields. Array must be empty if no corrections were needed. | |
corrections_applied[].original_token | string | The exact substring from [ORIGINAL_QUERY] that was identified as erroneous. | |
corrections_applied[].corrected_token | string | The replacement token. Must not be identical to original_token. | |
corrections_applied[].reason | enum string | Must be one of: 'phonetic_similarity', 'keyboard_proximity', 'common_typo', 'voice_transcription_error', 'language_transfer_error'. | |
target_language | ISO 639-1 code | Must match the [TARGET_LANGUAGE] input exactly. Used to confirm the correction context. | |
confidence_score | float | Must be a number between 0.0 and 1.0. Represents the model's self-assessed confidence in the overall correction. Values below 0.7 should trigger a human review or retry. | |
phonetic_encoding_used | string or null | If a specific algorithm was referenced (e.g., 'Double Metaphone', 'Soundex'), name it here. Null if no explicit encoding was applied. Validate against a known list of algorithms. |
Common Failure Modes
Phonetic correction across languages introduces unique failure modes that compound before retrieval. These are the most common breaks and how to guard against them.
Phonetic Over-Correction on Valid Terms
What to watch: The model 'corrects' a correctly spelled domain term or proper noun because it sounds like a common word in the target language. A drug name or product code gets rewritten into something plausible but wrong. Guardrail: Provide a protected terms list or entity catalog as part of the prompt context. Instruct the model to preserve terms that match known entities exactly, even if they appear phonetically irregular.
Language Boundary Confusion
What to watch: A query contains words from multiple languages, and the model applies the wrong phonetic rules to a borrowed word or code-switched segment. The correction makes the word unrecognizable in its source language. Guardrail: Prepend a language detection step before phonetic correction. For code-switched queries, segment by language first, then apply language-specific phonetic rules per segment rather than treating the whole query as one language.
Error Propagation into Translation
What to watch: A phonetically corrected query looks plausible in the source language but introduces a semantic shift that the downstream translator amplifies. The retrieval step then searches for the wrong concept entirely. Guardrail: Run a back-translation check after correction and translation. Compare the round-tripped query to the original user input. Flag corrections where semantic similarity drops below a threshold for human review or fallback to uncorrected translation.
Silent Failure on Low-Confidence Corrections
What to watch: The model makes a correction with low confidence but does not signal uncertainty. The corrected query enters retrieval, returns irrelevant results, and the RAG system generates a confident but wrong answer with no indication anything failed. Guardrail: Require the prompt to output an explicit confidence score per correction. Route low-confidence corrections to a fallback path that uses the original query or triggers a clarification ask-back to the user.
Homophone Disambiguation Without Context
What to watch: A homophone in the source language maps to multiple valid words, and the model picks the wrong one because it lacks domain or session context. A voice query for 'read' vs. 'reed' in a technical context gets corrected to the wrong form. Guardrail: Pass available session context, user role, or domain tags into the prompt. Instruct the model to use context to disambiguate and to output alternative candidates when multiple valid corrections exist, letting the retrieval layer run parallel searches.
Over-Correction Destroying Intent Signals
What to watch: The model aggressively normalizes phonetic variants that carry intentional meaning, such as regional spellings, brand stylizations, or quoted search terms. The corrected query loses the user's original intent signal. Guardrail: Add a preservation rule in the prompt for quoted strings, all-caps terms, and known stylized forms. Output a diff between the original and corrected query so downstream systems can decide whether to use the correction or fall back to the original.
Evaluation Rubric
Use these criteria to test whether the prompt corrects phonetic errors without introducing semantic drift or breaking the retrieval pipeline. Run each test before shipping a prompt version.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Phonetic correction accuracy | Corrects at least 90% of injected phonetic errors across a 50-sample test set | Corrected query still contains a misspelling or introduces a new, incorrect word | Run against a golden dataset of [SOURCE_QUERY] with known phonetic errors and expected [CORRECTED_QUERY] pairs |
Semantic preservation | Corrected query retains the original meaning; back-translation matches source intent with >= 0.95 cosine similarity | Corrected query changes the topic, entity, or intent of the original query | Embed both [SOURCE_QUERY] and [CORRECTED_QUERY], compute cosine similarity, and flag pairs below threshold |
Language boundary respect | Correction does not alter words that are valid in the source language but phonetically similar to words in another language | A correct word in [SOURCE_LANGUAGE] is replaced with a phonetically similar word from a different language | Include cross-language false-friend pairs in the test set and verify [CORRECTED_QUERY] leaves them unchanged |
Error propagation prevention | Corrected query produces retrieval results with higher relevance than the uncorrected query for >= 95% of test cases | Retrieval precision or recall drops after correction compared to the original noisy query | Run retrieval with both [SOURCE_QUERY] and [CORRECTED_QUERY] against the target index; compare NDCG@10 |
Output schema compliance | Response is valid JSON matching the [OUTPUT_SCHEMA] on 100% of test runs | Missing required fields, extra fields, or type mismatches in the JSON output | Validate output with a JSON schema validator; fail on any schema violation |
Confidence score calibration | [CONFIDENCE] score >= 0.8 correlates with actual correction correctness in >= 90% of cases | High-confidence corrections are frequently wrong or low-confidence corrections are frequently right | Bin outputs by [CONFIDENCE] score decile and compute precision per bin; flag inversions |
Null handling | Returns [CORRECTED_QUERY] equal to [SOURCE_QUERY] and [CONFIDENCE] >= 0.95 when no errors are present | Prompt alters a correct query or returns low confidence for a clean input | Include 20 clean queries in the test set and verify no unnecessary corrections occur |
Latency budget | Correction completes within 500ms for queries under 200 characters | P95 latency exceeds 500ms in production traffic | Measure end-to-end prompt execution time under load; alert if threshold breached |
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 as-is with a frontier model (GPT-4o, Claude 3.5 Sonnet). Accept raw string output and skip structured schema validation. Focus on getting the phonetic correction logic right for 2–3 language pairs before adding production guardrails.
Watch for
- The model returning explanations instead of the corrected query
- Over-correction of rare but valid terms
- No confidence signal when phonetic similarity is ambiguous

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