This prompt is built for platform engineers and AI infrastructure teams who need to detect the language of short text inputs before routing them to language-specific models, translation layers, or locale-aware workflows. It targets search queries, chatbot messages, and API requests under 20 words where standard language detection libraries often fail due to insufficient signal. The prompt produces an ISO 639-1 language code with a calibrated confidence score and an explicit low-confidence flag for inputs that are too short, ambiguous, or dominated by proper nouns and cross-lingual homographs. Use this when wrong-language routing would degrade downstream output quality, break retrieval pipelines, or create user trust issues in multilingual products.
Prompt
Short Text Language Detection Prompt for Queries

When to Use This Prompt
Defines the ideal use case, user, and boundaries for the short-text language detection prompt before you integrate it into a production routing pipeline.
Do not use this prompt when inputs are reliably longer than a full sentence, as statistical libraries like fasttext or langdetect will be faster, cheaper, and equally accurate at that length. Do not use it for detecting multiple languages within a single input—this prompt is designed for primary language detection only; for mixed-language inputs, use a dedicated mixed-language detection prompt from the same playbook series. Avoid relying on this prompt for real-time streaming applications with sub-100ms latency budgets unless you've benchmarked your model endpoint and confirmed it meets your p95 latency target. The prompt is also inappropriate for detecting regional locale variants (e.g., en-US vs. en-GB) where spelling and formatting differences are the only signal—use the locale identification prompt instead.
Before wiring this into production, run it against your eval set of single-word queries, proper nouns, and cross-lingual homographs (e.g., 'chat' which is both French and English, or 'bank' which exists in multiple Germanic languages). Measure how often the low-confidence flag fires correctly versus when the model overconfidently misclassifies. If your product has a supported language list, add a post-processing constraint that maps any detected language outside that list to a fallback or clarification flow. The next section provides the copy-ready prompt template you can adapt and test immediately.
Use Case Fit
Where the short-text language detection prompt works and where it breaks. Use these cards to decide if this prompt fits your pipeline before you integrate it.
Good Fit: Single-Language Queries Under 20 Words
Use when: the input is a short search query, chatbot message, or API parameter where one dominant language is expected. Guardrail: the prompt is optimized for brevity and speed, not for literary analysis. If the input is a single word, expect low confidence and plan a fallback.
Bad Fit: Multi-Paragraph Documents
Avoid when: the input exceeds 20 words or contains multiple paragraphs. Risk: the prompt's short-text heuristics break down on longer text, often producing overconfident but incorrect results. Guardrail: route longer inputs to a document-level language detection prompt with n-gram and statistical features instead.
Required Inputs: Raw Text and a Confidence Threshold
What you must provide: a raw text string and a minimum confidence threshold for accepting the result. Guardrail: never use the prompt without a configurable threshold. If the model returns confidence below your threshold, route to a human reviewer or a more expensive disambiguation model.
Operational Risk: Proper Nouns as False Signals
What to watch: names like 'Paris', 'Tokyo', or 'Volkswagen' can mislead the detector into guessing the wrong language. Guardrail: implement a post-detection check that flags inputs where proper nouns dominate the token count. If flagged, request clarification or use a named-entity-aware detection path.
Operational Risk: Cross-Lingual Homographs
What to watch: words spelled identically across languages (e.g., 'chat' in English and French) cause ambiguity on very short inputs. Guardrail: log all single-word detections for review. If your product frequently sees single-word queries, build a disambiguation prompt that asks for additional context instead of guessing.
Operational Risk: Silent Misclassification in Production
What to watch: the prompt returns a language code even when confidence is low, and downstream systems trust it blindly. Guardrail: always pair this prompt with a confidence score validator. If confidence is below 0.8, either reject the classification, escalate for human review, or route to a clarification workflow before any irreversible action.
Copy-Ready Prompt Template
A production-ready system instruction for detecting the language of short text queries with explicit low-confidence handling.
This prompt template is designed to be pasted directly into your system instructions for a language detection node. It forces the model to return a structured JSON object containing a language code and a confidence flag, rather than a conversational guess. The template is purpose-built for short text under 20 words—search queries, chatbot messages, and API requests—where disambiguation is hardest. Before deploying, replace every square-bracket placeholder with your application's specific values, such as your supported language list and minimum confidence threshold.
textYou are a language detection classifier for short text queries. Your only job is to identify the language of the input and return a structured JSON object. Do not answer the query, translate it, or provide any explanation. ## INPUT [INPUT] ## SUPPORTED LANGUAGES You may only return language codes from this list: [SUPPORTED_LANGUAGE_CODES] ## OUTPUT SCHEMA Return exactly this JSON structure with no additional text, markdown fences, or commentary: { "language_code": "ISO 639-1 code or 'unknown'", "confidence": "high" | "low", "detection_notes": "Brief reason for low confidence, or null if high" } ## CONFIDENCE RULES - Return "high" only when the language is unambiguous given the available text. - Return "low" when: - The text is a single word that exists in multiple languages (e.g., 'no', 'die', 'chat'). - The text is a proper noun, brand name, or URL with no language-specific words. - The text contains only numbers, emoji, or punctuation. - The text is a cross-lingual homograph where multiple languages are plausible. - The text is shorter than [MIN_CHARACTERS_FOR_HIGH_CONFIDENCE] characters. - When confidence is "low", set "language_code" to "unknown" unless a dominant language is still clearly identifiable. ## CONSTRAINTS - Do not guess. If the language is not clearly identifiable, return "unknown" with "low" confidence. - Do not use the query topic or domain to infer language. Only use linguistic features. - Ignore named entities, URLs, and code snippets when they are the only content. - For mixed-language input, return the primary language only if it represents more than [MIXED_LANGUAGE_THRESHOLD]% of the content. Otherwise return "unknown". ## EXAMPLES Input: "weather tomorrow" Output: {"language_code": "en", "confidence": "high", "detection_notes": null} Input: "banco" Output: {"language_code": "unknown", "confidence": "low", "detection_notes": "Single word exists in Spanish, Portuguese, and Italian. Insufficient context to disambiguate."} Input: "https://example.com" Output: {"language_code": "unknown", "confidence": "low", "detection_notes": "URL only. No linguistic content to classify."} Input: "café con leche por favor" Output: {"language_code": "es", "confidence": "high", "detection_notes": null}
After copying this template, you must adapt the placeholders to match your production environment. Set [SUPPORTED_LANGUAGE_CODES] to the exact list of ISO 639-1 codes your downstream pipelines can handle—typically a JSON array like ["en", "es", "fr", "de", "ja"]. Set [MIN_CHARACTERS_FOR_HIGH_CONFIDENCE] based on your eval results; start with 5 and adjust after testing on your query distribution. Set [MIXED_LANGUAGE_THRESHOLD] to the percentage cutoff for declaring a primary language in mixed input; 70% is a reasonable default. The [INPUT] placeholder should be replaced at runtime by your application with the raw user query, stripped of any prompt injection delimiters. Do not modify the output schema without updating all downstream parsers, validators, and monitoring dashboards that consume this JSON structure.
Prompt Variables
Inputs the prompt needs to work reliably. Replace each placeholder before sending to the model.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[INPUT_TEXT] | The short text query to classify. Typically under 20 words from search, chatbot, or API payloads. | "cómo estás" | Required. Must be a non-empty string. If null or empty, return error before model invocation. |
[SUPPORTED_LANGUAGES] | Comma-separated list of ISO 639-1 codes the system can route to. Constrains the model's output space. | "en,es,fr,de,ja,ko,zh" | Required. Must be a valid comma-separated list of ISO 639-1 codes. Parse and validate against known language codes. |
[CONFIDENCE_THRESHOLD] | Minimum confidence score (0.0-1.0) for auto-routing. Below this, the output should flag for human review or clarification. | 0.7 | Required. Must be a float between 0.0 and 1.0. Use for post-processing gating, not embedded in the prompt. |
[UNKNOWN_LANGUAGE_LABEL] | The label to return when no supported language meets the confidence threshold. | "und" | Required. Must be a string. Use ISO 639-3 'und' for undetermined or a custom label like 'unknown'. Validate output contains this label on low-confidence inputs. |
[MAX_INPUT_LENGTH] | Character limit for the input text. Truncate or reject inputs exceeding this before prompt assembly. | 500 | Required. Must be a positive integer. Enforce in application layer. Inputs over this limit should use a different prompt designed for longer text. |
[OUTPUT_FORMAT] | Expected output structure. Use a JSON schema or type description the model must follow. | "{"language_code": string, "confidence": float, "needs_review": boolean}" | Required. Must be a valid JSON schema string. Validate model output against this schema. Retry on parse failure. |
[FEW_SHOT_EXAMPLES] | Optional array of input-output pairs demonstrating correct behavior on ambiguous short texts. | "[{"input": "bank", "output": {"language_code": "und", "confidence": 0.1, "needs_review": true}}]" | Optional. If provided, must be a valid JSON array. Each example must match [OUTPUT_FORMAT]. Use to calibrate ambiguity handling. |
Implementation Harness Notes
A practical guide to wiring the Short Text Language Detection prompt into a production application with validation, retries, logging, and human-review integration.
Integrating a language detection prompt into a production system requires more than just calling an LLM. The harness must handle the prompt's inherent uncertainty, especially with short text. The core loop involves: receiving the input query, injecting it into the [INPUT] placeholder, calling a fast, cost-effective model (like GPT-4o-mini or Claude Haiku), and then strictly validating the output before the routing decision is made. The primary risk is a low-confidence or incorrect language code causing a cascading failure downstream, such as routing a query to the wrong translation model or a language-specific knowledge base that cannot process it.
The validation layer is the most critical component. You must parse the model's response and check that the language_code field is a valid ISO 639-1 code from your supported list. If the confidence_score is below a defined threshold (e.g., 0.85), or if the ambiguity_flag is set to true, the system should not proceed automatically. Instead, implement a fallback strategy: route to a default 'multilingual' or 'unknown' queue, use a higher-capability model for a second opinion, or, in high-stakes customer support scenarios, flag the item for a human reviewer. A simple retry loop with a slightly modified prompt (e.g., adding
If uncertain
respond with 'un' for unknown") can resolve transient failures but will not fix fundamentally ambiguous inputs like single-word proper nouns."
For observability, log every detection event: the raw input, the model's full response, the validated language code, the confidence score, and the final routing decision. This data is essential for calibrating your confidence threshold and identifying patterns of misclassification, such as a specific set of cross-lingual homographs that consistently fool the model. Wire these logs into your eval framework to run regression tests. A golden dataset of 100 short, ambiguous queries (e.g., 'chat', 'main', 'bank') with their correct, human-verified language labels should be run against the prompt weekly to detect drift. When a failure mode is identified, do not just add a one-off rule in application code; update the prompt's [EXAMPLES] or [CONSTRAINTS] to teach the model the correct behavior directly, keeping the logic centralized and maintainable.
Expected Output Contract
Defines the exact JSON fields, types, and validation rules for the language detection response. Use this contract to parse, validate, and route the model output in your application harness.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
language_code | ISO 639-1 string | Must match /^[a-z]{2}$/. Reject if not a valid ISO 639-1 code. | |
language_name | string | Must be the English name of the detected language. Non-empty string. | |
confidence_score | float (0.0-1.0) | Must be a number between 0.0 and 1.0 inclusive. Parse as float; reject if out of range. | |
is_ambiguous | boolean | Must be true if confidence_score is below the configured threshold (default 0.85) or if multiple languages are plausible. Strict boolean type required. | |
alternative_languages | array of objects | If present, each object must contain language_code (ISO 639-1) and confidence_score (float). Array can be empty if is_ambiguous is false. | |
input_length_category | enum: [short, very_short, adequate] | Must be one of the three allowed values. Use short for 3-20 words, very_short for 1-2 words, adequate for 21+ words. | |
detection_notes | string or null | If present, must be a string explaining ambiguity or detection rationale. Null allowed. Max 200 characters. | |
script_code | ISO 15924 string or null | If detectable, must be a valid ISO 15924 four-letter script code (e.g., Latn, Cyrl, Arab). Null if script is ambiguous or irrelevant. |
Common Failure Modes
Short-text language detection fails in predictable ways. These are the most common production failure modes and the specific guardrails that catch them before they affect downstream routing.
Single-Word Ambiguity
What to watch: Single-word queries like 'chat' or 'pain' exist in multiple languages. The model guesses the most statistically likely language rather than the user's actual intent, causing silent misrouting. Guardrail: Enforce a minimum character or token threshold. For inputs below 20 characters, return a low-confidence flag and route to a clarification prompt or a multi-language fallback index.
Proper Noun False Positives
What to watch: Named entities like 'Paris', 'Toyota', or 'Samsung' trigger incorrect language classification because the model treats the entity's origin language as the input language. A query like 'Paris hotel' in English gets classified as French. Guardrail: Add a pre-processing step that masks or tags recognized named entities before language detection. Use a secondary check that compares the function-word language against the content-word language.
Cross-Lingual Homograph Confusion
What to watch: Words spelled identically across languages but with different meanings ('gift' in English vs. German, 'once' in English vs. Spanish) cause the model to latch onto a single token and misclassify the entire input. Guardrail: Require the prompt to output a per-token language distribution when confidence is below 0.85. If the distribution is bimodal, flag for human review or route to a disambiguation prompt.
Overconfident Short-Text Predictions
What to watch: The model returns a 0.98 confidence score for a three-word input that is genuinely ambiguous between Spanish and Portuguese. The score reflects model calibration on long texts, not actual certainty on short inputs. Guardrail: Calibrate confidence thresholds specifically on a short-text evaluation set. Apply a length-based confidence penalty that reduces the raw score for inputs under 50 characters before making routing decisions.
Script-Only Detection Without Language Disambiguation
What to watch: The model detects Cyrillic script and returns 'ru' when the input is actually Bulgarian, Serbian, or Mongolian. Script detection is not language detection, but the prompt conflates them on short inputs lacking distinctive vocabulary. Guardrail: Add an explicit instruction in the prompt to distinguish script identification from language identification. When only script-level evidence is available, output the script code alongside a language code of 'und' (undetermined) with a note.
Mixed-Language Input Misclassification
What to watch: A query like 'How do I say gracias in English' gets classified as Spanish because the model weights content words over function words. The primary language is English, but the detection fails. Guardrail: Prompt the model to estimate language proportions and return the dominant language only when it exceeds a 60% threshold. If no language exceeds the threshold, flag as mixed and route to a multi-language handler or clarification step.
Evaluation Rubric
Test cases to validate the Short Text Language Detection Prompt before production deployment. Run these against your configured prompt, model, and confidence thresholds. Each case targets a known failure mode for queries under 20 words.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Single-word query detection | Returns language code with confidence below [LOW_CONFIDENCE_THRESHOLD] and ambiguity flag set to true | Returns high-confidence code for ambiguous word (e.g., 'chat' detected as English when French is equally plausible) | Run 20 single-word queries from [AMBIGUOUS_WORD_LIST] and verify confidence < [LOW_CONFIDENCE_THRESHOLD] for at least 80% |
Proper noun handling | Returns language code matching the query's surrounding language context, not the noun's origin | Classifies 'Paris hotel recommendations' as French or 'Tokyo sushi menu' as Japanese | Run 15 queries mixing proper nouns from [PROPER_NOUN_LIST] with function words from [TARGET_LANGUAGE] and verify correct classification |
Cross-lingual homograph disambiguation | Returns language code consistent with the majority of non-homograph tokens in the query | Misclassifies 'die' (German article) as English verb or 'pain' (French bread) as English discomfort | Run 10 homograph queries from [HOMOGRAPH_TEST_SET] and verify accuracy > 90% |
Very short query with noise | Returns language code with confidence below [LOW_CONFIDENCE_THRESHOLD] or correctly identifies dominant language despite typos | Returns high-confidence wrong language for 3-word query with one typo | Run 25 noisy short queries from [NOISY_SHORT_QUERY_SET] and verify either correct classification or low-confidence flag |
Empty or whitespace-only input | Returns null language code with confidence 0 and ambiguity flag set to true | Returns any language code or non-zero confidence | Send 5 empty/whitespace inputs and verify null output with zero confidence |
Numeric-only or symbol-only input | Returns null language code with confidence 0 and ambiguity flag set to true | Returns a language code for '12345' or '!!!' | Send 5 numeric/symbol inputs and verify null output with zero confidence |
Mixed-language short query | Returns primary language code with confidence below [LOW_CONFIDENCE_THRESHOLD] and secondary language list populated | Returns high-confidence single language for 'hola my friend' or 'merci thank you' | Run 15 mixed-language queries from [MIXED_LANGUAGE_TEST_SET] and verify secondary languages detected and confidence < [LOW_CONFIDENCE_THRESHOLD] |
Script-only detection without language | Returns script code in [SCRIPT_FIELD] and language code with confidence below [LOW_CONFIDENCE_THRESHOLD] when script maps to multiple languages | Returns high-confidence language for Cyrillic text that could be Russian, Ukrainian, or Serbian | Run 10 script-ambiguous queries from [SCRIPT_AMBIGUITY_SET] and verify low confidence with script field populated |
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
Start with the base prompt and a single model. Use a simple string match or regex to extract the language code from the model response. Skip formal schema validation—just log outputs and spot-check manually. Accept the default temperature and don't add retries yet.
code[SYSTEM]: Detect the language of the following query. Return ONLY the ISO 639-1 code. If uncertain, return 'und'. [USER]: [QUERY]
Watch for
- Model returning prose instead of a bare code (e.g., 'The language is French' instead of 'fr')
- Overconfidence on single-word queries like 'chat' (French for 'cat' vs. English 'chat')
- Proper nouns being misclassified as a different language
- No handling of mixed-language or code-switched inputs

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