This prompt is for orchestration engineers building the dispatch layer of a multilingual RAG system. Its job is to accept a user query in any language, detect the source language, identify which target index languages are needed for retrieval, and route the query to the appropriate translation and expansion pipeline with a confidence score. Use this prompt when your retrieval indexes span multiple languages and you need a single entry point that decides where to send each query before any translation or expansion happens. This is a classification and routing prompt, not a translation prompt. It does not rewrite the query. It decides which downstream pipeline should handle it.
Prompt
Language Detection and Query Routing Prompt Template

When to Use This Prompt
Understand the job-to-be-done, the ideal user, and the boundaries for a multilingual query routing prompt.
The ideal user is an engineer integrating this prompt into a server-side request path, such as an API endpoint that receives a user query and must dispatch it to language-specific retrieval workers. You should have a known set of available target index languages and a mapping of which downstream pipelines handle each language pair. The prompt expects a raw user query and a list of supported target languages as input. It returns a structured routing decision: the detected source language, one or more target languages, a confidence score, and a recommended pipeline identifier. This output should be validated programmatically before any downstream call is made—check that the target languages exist in your system and that the confidence score meets a minimum threshold before proceeding.
Do not use this prompt when you have only one retrieval language, when the query has already been translated, or when you need the prompt to perform the translation itself. This prompt is also inappropriate for real-time chat where per-message latency must be under 200ms and a lightweight, heuristic-based language detector would suffice. If your system already knows the user's language preference from their profile or session, bypass this prompt and route directly. The primary failure mode is misclassification of low-resource or code-switched queries; always pair this prompt with a fallback routing rule and log routing decisions for offline evaluation. After reading this section, proceed to the prompt template to copy and adapt it for your language coverage.
Use Case Fit
Where this prompt works and where it does not. Use these cards to decide if the Language Detection and Query Routing Prompt Template fits your current architecture before integrating it into your retrieval pipeline.
Good Fit: Multi-Index Architectures
Use when: your retrieval system has separate indexes per language (e.g., English, Japanese, Arabic) and you need to dispatch a user query to the correct one. Guardrail: confirm each target index actually exists and is populated before routing; a correct language detection with a missing index still fails.
Good Fit: Pre-Translation Triage
Use when: you need to decide which translation or expansion pipeline to invoke before retrieval. Guardrail: the prompt should output a confidence score; set a minimum threshold below which the query is routed to a human or a fallback multi-language search.
Bad Fit: Monolingual Corpora
Avoid when: your entire knowledge base is in one language. Language detection adds latency and a potential failure point with no benefit. Guardrail: check your index language distribution before deploying this prompt; if only one language exists, remove the routing step entirely.
Bad Fit: Code-Switching Queries
Avoid when: users routinely mix multiple languages in a single query. This prompt is designed to detect a primary language and route accordingly, not to decompose a mixed-language input. Guardrail: pair this with a code-switching expansion prompt upstream if your user base frequently mixes languages.
Required Input: Language Catalog
Risk: the model guesses languages you don't support or invents index names. Guardrail: always pass an explicit, enumerated list of supported languages and their corresponding index identifiers as part of [CONSTRAINTS]. Never rely on the model's internal knowledge of your infrastructure.
Operational Risk: Silent Misrouting
Risk: the prompt returns a plausible but incorrect language, sending the query to the wrong index and producing empty or irrelevant results without an obvious error. Guardrail: log the detected language, confidence score, and routed index for every query. Set up an alert if the low-confidence routing rate spikes above a defined threshold.
Copy-Ready Prompt Template
A production-ready prompt for detecting query language, identifying required target index languages, and routing to the appropriate translation pipeline with a confidence score.
This prompt template is designed to sit at the entry point of your multilingual retrieval dispatch layer. It accepts a raw user query and returns a structured routing decision: the detected source language, the target index languages needed for retrieval, and a confidence score that your orchestration layer can use to decide whether to proceed, request clarification, or escalate. Replace each square-bracket placeholder with values from your system's configuration before deploying.
textSYSTEM: You are a language detection and query routing dispatcher for a multilingual retrieval system. Your job is to analyze a user query, detect its primary language, determine which target index languages are needed to retrieve relevant documents, and output a structured routing decision with a confidence score. INPUT: User Query: [USER_QUERY] AVAILABLE INDEX LANGUAGES: [AVAILABLE_LANGUAGES_LIST] ROUTING RULES: [ROUTING_RULES] OUTPUT_SCHEMA: { "source_language": "ISO 639-1 code", "source_language_confidence": 0.0-1.0, "target_index_languages": ["ISO 639-1 codes"], "routing_confidence": 0.0-1.0, "requires_clarification": boolean, "clarification_reason": "string or null", "code_switching_detected": boolean, "code_switched_languages": ["ISO 639-1 codes or null"], "routing_strategy": "direct | translate | expand | decompose | clarify" } CONSTRAINTS: - If source_language_confidence is below [MIN_CONFIDENCE_THRESHOLD], set requires_clarification to true. - If the query contains multiple languages (code-switching), set code_switching_detected to true and list all detected languages. - If the query language matches an available index language and no cross-lingual retrieval is needed, set routing_strategy to "direct". - If the query language is not in the available index languages, set routing_strategy to "translate" and include all available index languages as targets. - If the query contains domain-specific terms that may exist in multiple languages, set routing_strategy to "expand" and include the source language plus target languages. - If the query is ambiguous or underspecified, set routing_strategy to "clarify" and provide a clarification_reason. - Never guess a language if confidence is below [MIN_CONFIDENCE_THRESHOLD]. - For queries shorter than [MIN_QUERY_LENGTH] characters, lower the confidence floor by [SHORT_QUERY_PENALTY]. EXAMPLES: [FEW_SHOT_EXAMPLES] Respond ONLY with valid JSON matching the OUTPUT_SCHEMA. No additional text.
To adapt this template for your system, replace [AVAILABLE_LANGUAGES_LIST] with the ISO 639-1 codes your retrieval indexes support, such as ["en", "fr", "de", "ja", "ko"]. Define [ROUTING_RULES] with any business logic specific to your corpus—for example, "legal documents exist only in English and German, so route all legal-domain queries to en and de regardless of source language." Set [MIN_CONFIDENCE_THRESHOLD] to a value like 0.7 for production or 0.5 for a preview environment where you prefer attempted retrieval over clarification. The [MIN_QUERY_LENGTH] and [SHORT_QUERY_PENALTY] parameters prevent overconfident language detection on single-word or two-word queries, which are inherently ambiguous. Provide [FEW_SHOT_EXAMPLES] that reflect your actual query distribution—include at least one code-switching example, one ambiguous short query, and one domain-specific query that should trigger expansion across multiple languages.
Before wiring this into your orchestration layer, validate the output against your schema in a test harness. Confirm that the model returns parseable JSON, that source_language is always a valid ISO 639-1 code from your configured set, and that routing_confidence drops appropriately on short or ambiguous inputs. For high-stakes retrieval where incorrect routing causes user-visible failures, add a human review step when requires_clarification is true or routing_confidence falls below a second, stricter threshold. Log every routing decision with the query, detected language, confidence, and chosen strategy so you can audit routing accuracy over time and feed misrouted queries back into your few-shot examples.
Prompt Variables
Required and optional inputs for the Language Detection and Query Routing prompt. Each variable must be validated before the prompt is assembled to prevent routing failures and language misidentification.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[USER_QUERY] | The raw user input string that needs language detection and routing | ¿Cuánto cuesta el envío a Francia? | Must be a non-empty string. Check for null, empty, or whitespace-only inputs. Reject queries over 2000 characters to prevent prompt stuffing. |
[SUPPORTED_LANGUAGES] | A JSON array of language codes the system can route to | ["en", "es", "fr", "de", "ja"] | Must be a valid JSON array of ISO 639-1 codes. Validate against a known code list. At least one language required. Reject unknown codes. |
[TARGET_INDEX_LANGUAGES] | A JSON array of language codes for which retrieval indexes exist | ["en", "es", "fr"] | Must be a subset of [SUPPORTED_LANGUAGES]. Validate array membership. If empty, routing is impossible and the prompt should not execute. |
[CONFIDENCE_THRESHOLD] | The minimum confidence score required before auto-routing a query | 0.85 | Must be a float between 0.0 and 1.0. If detection confidence is below this threshold, the output must flag for human review or clarification. Default to 0.80 if not provided. |
[FALLBACK_LANGUAGE] | The default language code to use when detection confidence is below threshold | "en" | Must be a valid ISO 639-1 code present in [TARGET_INDEX_LANGUAGES]. If null, the system must escalate to human review instead of guessing. |
[CONTEXT_HISTORY] | Optional array of prior conversation turns for disambiguation | [{"role":"user","content":"Bonjour"}] | If provided, must be a valid JSON array of message objects with role and content fields. Null allowed. Validate structure before inclusion to prevent injection. |
[OUTPUT_SCHEMA] | The expected JSON schema for the routing decision output | {"detected_language":"es","confidence":0.94,"target_languages":["es","en"],"requires_translation":true,"routing_action":"translate_and_expand"} | Must be a valid JSON Schema object. Validate parse before prompt assembly. Reject schemas with circular references or unsupported keywords. |
Implementation Harness Notes
How to wire the language detection and routing prompt into a production multilingual retrieval dispatch layer.
This prompt is designed to be the first step in a multilingual retrieval pipeline. It should be called before any translation, expansion, or retrieval occurs. The application layer must capture the raw user query, inject it into the [USER_QUERY] placeholder, and provide the [AVAILABLE_INDEX_LANGUAGES] list from the system's configuration. The model's response is a structured JSON object that the application parses to decide which downstream translation and retrieval pipelines to invoke. Do not use this prompt as a standalone classifier without wiring its output into actual routing logic.
The application must validate the model's JSON output against a strict schema before acting on it. Check that detected_language is a valid ISO 639-1 code, confidence_score is a float between 0.0 and 1.0, and target_index_languages contains only languages present in the provided [AVAILABLE_INDEX_LANGUAGES] list. If validation fails, log the raw output and the validation error, then fall back to a default routing strategy—typically translating the query into all available index languages with a low-confidence flag. For high-risk domains where retrieval precision is critical, implement a confidence threshold: if confidence_score is below 0.7, route the query to a human review queue or a clarification prompt before proceeding. Model choice matters here; smaller models may produce malformed JSON or hallucinate language codes, so prefer a model with strong structured output capabilities and set the response_format to json_object if the API supports it.
Wire the validated output into a dispatcher that selects the appropriate translation and expansion prompts from the cross-lingual playbook library. For each language in target_index_languages, spawn a parallel retrieval job using the corresponding translation prompt. Log the full routing decision—including the original query, detected language, confidence, and selected target languages—as a structured trace for observability. This trace is essential for debugging retrieval failures and for evaluating whether the language detector is making correct routing decisions over time. Avoid the temptation to skip validation or to treat the model's output as trustworthy without checks; language detection errors at this stage compound into wasted retrieval compute and irrelevant results downstream.
Expected Output Contract
Defines the strict JSON schema for the language detection and routing decision. Use this contract to validate the model's output before dispatching the query to downstream translation or retrieval pipelines.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
detected_language | string (ISO 639-1 code) | Must be a valid 2-letter language code from a predefined allowlist. Reject if code is not in the system's supported language set. | |
confidence_score | float (0.0 to 1.0) | Must be a number between 0.0 and 1.0. If below [MIN_CONFIDENCE_THRESHOLD], route to a human review queue instead of automated dispatch. | |
target_index_languages | array of strings (ISO 639-1) | Array must contain at least one valid language code. Each code must exist in the system's available index list. Reject if the array is empty. | |
routing_strategy | string (enum) | Must be one of: 'translate_then_retrieve', 'multilingual_retrieve', 'code_switch_split', or 'direct_retrieve'. Reject any value not in this enum. | |
requires_translation | boolean | Must be true if detected_language is not in target_index_languages. If false but target_index_languages does not contain detected_language, flag as a logic error. | |
translation_pipeline_id | string or null | Required if requires_translation is true. Must match a valid pipeline ID from the system registry. Null is allowed only when requires_translation is false. | |
disambiguation_candidates | array of objects or null | If confidence_score is below [HIGH_CONFIDENCE_THRESHOLD], this array should contain alternative language guesses with scores. Each object must have 'language' (string) and 'score' (float) fields. Null is allowed if confidence is high. | |
processing_notes | string or null | A brief, human-readable explanation of the routing decision. Must not contain PII from the original query. Null is allowed if no special conditions apply. |
Common Failure Modes
Language detection and routing pipelines break in predictable ways. These cards cover the most common failure modes and the operational guardrails to prevent them.
Short Query Language Ambiguity
What to watch: Queries with fewer than 5 words (e.g., 'router config', 'bank statement') lack sufficient signal for reliable language detection. The model may guess incorrectly, routing the query to the wrong translation pipeline and producing irrelevant results. Guardrail: Implement a minimum character or token threshold. Below the threshold, return a language_detection confidence score and, if below 0.85, prompt the user for clarification or default to the user's profile language.
Code-Switched Query Misrouting
What to watch: Users mixing languages in a single query (e.g., 'Wie debugge ich den Kubernetes pod?') cause the detector to latch onto the dominant language and ignore the embedded terms. The query routes to a German index, missing critical English technical documentation. Guardrail: Add a code_switching_detected boolean to the output schema. When true, route the query to a code-switching expansion prompt that generates separate monolingual queries for each detected language before retrieval.
Confident Misclassification of Similar Languages
What to watch: Closely related languages (e.g., Bosnian/Croatian/Serbian, Danish/Norwegian, Malay/Indonesian) are frequently misclassified with high confidence. A query routed to the wrong index in a related language may return partially relevant results, masking the error. Guardrail: Define language groups in your routing configuration. When the detected language falls into a high-confusion group, route the query to all indexes in that group and merge results, or add a language_group field and log the ambiguity for review.
Proper Noun and Entity Interference
What to watch: Queries containing foreign-language proper nouns, brand names, or technical terms (e.g., 'Samsung Galaxy S24 Preis') can skew language detection toward the entity's language rather than the user's language. The query routes to Korean or English indexes instead of German. Guardrail: Pre-process queries to mask or tag known entities before language detection. Use an entity extraction step to isolate proper nouns, run detection on the remaining text, and re-attach entities after routing.
Script-Based Detection Failure for Shared Scripts
What to watch: Languages sharing the same script (e.g., English, French, and Spanish all use Latin script) cannot be distinguished by character-set heuristics alone. Relying solely on script detection causes routing failures for Latin-script languages. Guardrail: Never use script detection as the sole routing mechanism. Always pair it with a statistical language detection model or an LLM-based classifier. Log cases where script and model predictions disagree for offline evaluation.
Missing Target Index Language Specification
What to watch: The prompt detects the source language correctly but fails to identify which target index languages are needed. A query in Japanese may need retrieval from both Japanese and English indexes, but the router selects only Japanese, missing critical English documentation. Guardrail: Include a target_index_languages array in the output schema with explicit reasoning for each selection. Validate that at least one target language is always returned. For global products, default to including English as a secondary target unless the source is English-only.
Evaluation Rubric
Use this rubric to test the Language Detection and Query Routing prompt before shipping. Each criterion targets a specific failure mode common in multilingual dispatch layers.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Language Detection Accuracy | Detected language matches the ground-truth ISO 639-1 code for the input query | Wrong language code returned, or code-switched query assigned to only one language | Run against a golden set of 50 queries in 5+ languages, including code-switched and ambiguous inputs; require >95% exact match |
Confidence Score Calibration | Confidence score is >=0.85 for unambiguous queries and <=0.70 for genuinely ambiguous or short queries | High confidence (>0.90) on a 2-word ambiguous query, or low confidence (<0.50) on a clear monolingual sentence | Plot confidence distribution against human-labeled ambiguity ratings; check that low-confidence outputs trigger the defined fallback path |
Target Index Language Selection | Output lists all and only the languages where relevant documents exist for this query domain | Missing a required target language, or including a language with no indexed content for the domain | Validate against a known mapping of query-domain-to-index-languages; check that [TARGET_LANGUAGES] is a subset of available indexes |
Routing Decision Correctness | Routing label matches the expected pipeline for the detected language and intent combination | Query routed to a translation-only pipeline when expansion is also needed, or vice versa | Compare routing output to a decision table of expected routes per language-intent pair; require 100% match on 20 curated cases |
Code-Switched Query Handling | Both languages are detected, and separate target queries are generated for each language's index | Only one language detected, or a single blended query produced instead of per-language queries | Test with 10 code-switched queries (e.g., English-Spanish, French-Arabic); verify [DETECTED_LANGUAGES] contains all present languages |
Short or Ambiguous Query Handling | Confidence is low, and the routing decision falls back to a broad multi-index retrieval or clarification request | High-confidence routing on a query like 'bank' or 'run' with no disambiguation attempt | Feed 10 ambiguous single-word queries; verify confidence <0.70 and fallback routing is triggered |
Output Schema Compliance | Response is valid JSON matching the [OUTPUT_SCHEMA] with all required fields present and correctly typed | Missing [CONFIDENCE_SCORE], malformed JSON, or [TARGET_LANGUAGES] as a string instead of array | Schema validation check in CI; parse output with a JSON schema validator and reject on any schema violation |
Latency Budget Adherence | Prompt completes in under 500ms for a single query on target model | Response time exceeds 1 second, causing downstream retrieval timeout | Benchmark with 100 queries; measure p95 latency; flag if p95 exceeds 500ms on production-equivalent hardware |
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. Accept raw text output and parse the language code and confidence manually. Skip strict schema enforcement during early testing.
Watch for
- Missing confidence scores on ambiguous inputs
- Overly broad language categories (e.g., 'zh' vs 'zh-CN')
- No fallback when detection confidence is below threshold

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