Inferensys

Prompt

Language Detection for RAG Pipeline Routing Prompt

A practical prompt playbook for detecting query language and routing to the correct vector index, embedding model, and response generation locale in multilingual RAG systems.
Developer building agentic RAG system, retrieval pipeline diagram on laptop, technical workspace with notes.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for the Language Detection for RAG Pipeline Routing Prompt.

This prompt is designed for AI platform engineers and MLOps teams who need to route user queries to language-specific vector indexes within a Retrieval-Augmented Generation (RAG) system. The core job-to-be-done is deterministic language identification at the ingress layer of a multilingual RAG pipeline, where sending a query to the wrong index—for example, routing a German question to an English knowledge base—directly degrades answer quality, breaks citation grounding, and erodes user trust. The ideal user is an engineer building a production retrieval system who needs a structured, testable language detection step that outputs a standardized language code, a confidence score, and an explicit index routing decision before the retrieval call is made.

Use this prompt when your RAG pipeline serves multiple language-specific knowledge bases or embedding collections and you need a reliable, auditable routing decision. It is appropriate for queries of moderate length—typically 10 to 500 words—where sufficient lexical and syntactic signal exists for disambiguation. The prompt expects a raw user query string as input and produces a JSON object containing the detected language, a confidence score between 0 and 1, and a target index identifier. It includes explicit handling for ambiguous or low-confidence cases by returning a fallback index and an ambiguity flag, preventing silent misrouting. The prompt is designed to be wired into a pre-retrieval middleware layer, where its output can be logged, validated, and used to select the correct vector store and embedding model before any search is executed.

Do not use this prompt for real-time streaming audio transcription, for inputs under 5 words where language signal is insufficient, or for documents containing multiple languages in equal proportion. It is not a translation prompt—it detects and routes, but does not transform the query. For code-switched inputs where two languages are interleaved within a single sentence, use the Mixed-Language Input Detection Prompt instead. For CJK disambiguation where character overlap between Chinese, Japanese, and Korean creates ambiguity, pair this prompt with the CJK Language Disambiguation Prompt. If your pipeline handles regulated content where language implies jurisdictional data residency requirements, combine this prompt with the Language Detection for Sensitive Data Handling Policy Prompt to ensure compliance-aware routing. Always validate the output against a golden dataset of known-language queries before deployment, and monitor production confidence score distributions to detect drift in your user population's language mix.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works, where it fails, and the operational risks to manage before routing RAG queries by language.

01

Good Fit: Monolingual Queries

Use when: user queries are predominantly in a single language and map cleanly to a dedicated vector index. Guardrail: still run a confidence check; a single loanword or named entity should not flip the routing decision.

02

Bad Fit: Code-Switched Inputs

Avoid when: users frequently mix languages in a single query. A primary-language vote will route to the wrong index for the secondary language. Guardrail: pair with a code-switching segment identifier and route segments separately, or fall back to a multilingual index.

03

Required Inputs

Must provide: raw user query text, a list of supported language codes mapped to available indexes, and a confidence threshold below which the system should fall back to a multilingual index or ask for clarification. Guardrail: never route without a defined fallback index for low-confidence or unsupported languages.

04

Operational Risk: Index Mismatch

Risk: a misclassified query retrieves chunks from the wrong language index, producing a fluent but factually irrelevant answer. Guardrail: log the detected language and confidence alongside every retrieval call; set an alert if low-confidence routings exceed 5% of traffic.

05

Operational Risk: Embedding Drift

Risk: routing to a language-specific index that uses a different embedding model than the query encoder. Guardrail: validate at startup that the selected embedding model matches the target index; if mismatched, route to a cross-lingual index or re-encode with the correct model.

06

Operational Risk: Named Entity Interference

Risk: foreign-language named entities (brand names, technical terms, person names) skew the language detector toward the wrong language. Guardrail: strip or mask known entities before detection, or use a detector trained to be robust to entity noise, and log cases where entity removal changes the routing decision.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for detecting query language and mapping it to the correct RAG pipeline index, embedding model, and response locale.

This prompt template is designed to sit at the ingress point of a multilingual retrieval-augmented generation (RAG) system. Its job is to accept a user query, detect the primary language, and produce a structured routing decision that downstream orchestration code can act on. The template uses square-bracket placeholders for all variable inputs, constraints, and configuration so you can adapt it to your specific language indexes, supported locales, and routing logic without rewriting the core instruction.

text
You are a language detection router for a multilingual RAG system. Your task is to analyze the user's query, determine its primary language, and output a structured routing decision.

[INPUT]
User Query: "[USER_QUERY]"

[CONTEXT]
Supported Languages and Index Mappings:
[LANGUAGE_INDEX_MAPPINGS]

Default Fallback Language: [DEFAULT_FALLBACK_LANGUAGE]
Default Fallback Index: [DEFAULT_FALLBACK_INDEX]

[CONSTRAINTS]
1. Detect the primary language of the query. If the query contains multiple languages, identify the dominant one.
2. If the query contains foreign-language named entities (e.g., a French company name in an English query), do not let them override the primary language detection.
3. If the query contains technical terms borrowed from another language, treat them as part of the primary language's lexicon.
4. If the detected language is not in the Supported Languages list, route to the Default Fallback.
5. If the query is too short to disambiguate (fewer than [MINIMUM_CONFIDENCE_LENGTH] words), set confidence to "low" and flag for clarification.
6. Do not translate the query. Preserve the original text for downstream retrieval.

[OUTPUT_SCHEMA]
Return a single JSON object with the following fields:
{
  "detected_language": "ISO 639-1 code or 'unknown'",
  "confidence": "high | medium | low",
  "routing_target": "index identifier from the mapping or fallback",
  "requires_clarification": true | false,
  "clarification_reason": "explanation if clarification is needed, otherwise null",
  "original_query": "the exact user query, unmodified"
}

[EXAMPLES]
Example 1:
User Query: "What is the capital of France?"
Output: {"detected_language": "en", "confidence": "high", "routing_target": "en-index-v2", "requires_clarification": false, "clarification_reason": null, "original_query": "What is the capital of France?"}

Example 2:
User Query: "Was ist die Hauptstadt von Frankreich?"
Output: {"detected_language": "de", "confidence": "high", "routing_target": "de-index-v1", "requires_clarification": false, "clarification_reason": null, "original_query": "Was ist die Hauptstadt von Frankreich?"}

Example 3:
User Query: "Tell me about the restaurant 'La Maison d'Or' in Paris"
Output: {"detected_language": "en", "confidence": "high", "routing_target": "en-index-v2", "requires_clarification": false, "clarification_reason": null, "original_query": "Tell me about the restaurant 'La Maison d'Or' in Paris"}

Example 4:
User Query: "config"
Output: {"detected_language": "unknown", "confidence": "low", "routing_target": "en-index-v2", "requires_clarification": true, "clarification_reason": "Query too short to disambiguate language. Only 1 word provided.", "original_query": "config"}

[RISK_LEVEL]
This routing decision controls which knowledge base and embedding model are used. Incorrect routing may return irrelevant or untranslated results. If confidence is "low" and the query is short, prefer clarification over silent misrouting.

To adapt this template, replace the placeholders with your production values. [LANGUAGE_INDEX_MAPPINGS] should be a structured list mapping each supported ISO 639-1 code to its corresponding vector index identifier and embedding model name. [MINIMUM_CONFIDENCE_LENGTH] is a tunable threshold—start with 3 words and adjust based on your query patterns. The examples section is critical for teaching the model how to handle named entities and short queries; replace them with examples drawn from your actual query logs. Before deploying, run this prompt against a golden dataset of at least 200 queries covering all supported languages, mixed-language inputs, short queries, and edge cases with foreign named entities. Measure routing accuracy, clarification rate, and latency. If your system cannot tolerate any misrouting, add a human review step for all confidence: "low" outputs before the query reaches retrieval.

IMPLEMENTATION TABLE

Prompt Variables

Inputs required by the Language Detection for RAG Pipeline Routing Prompt. Each placeholder must be populated before the prompt is sent to the model. Validation notes describe how to verify the input is well-formed before execution.

PlaceholderPurposeExampleValidation Notes

[USER_QUERY]

The raw text input that needs language detection before RAG index routing

¿Cuál es la política de devoluciones para pedidos internacionales?

Non-empty string required. Reject null or whitespace-only inputs. Length check: warn if under 10 characters for short-text ambiguity handling.

[SUPPORTED_LANGUAGES]

JSON array of ISO 639-1 language codes the RAG pipeline can route to

["en", "es", "fr", "de", "ja", "zh"]

Must be a valid JSON array of 2-letter codes. Parse check: every element must match ^[a-z]{2}$. Empty array not allowed. At least one language required.

[INDEX_MAPPING]

JSON object mapping each supported language to its vector index ID and embedding model name

{"en": {"index": "kb-en-v3", "model": "text-embedding-3-large"}, "es": {"index": "kb-es-v2", "model": "multilingual-e5-large"}}

Schema check: every key must exist in [SUPPORTED_LANGUAGES]. Each value must have non-null 'index' and 'model' string fields. Missing mapping for any supported language is a hard failure.

[FALLBACK_LANGUAGE]

Default language code when detection confidence is below threshold or language is unsupported

"en"

Must be a valid ISO 639-1 code present in [SUPPORTED_LANGUAGES]. Null not allowed. This is the safety net for unclassifiable inputs.

[CONFIDENCE_THRESHOLD]

Minimum confidence score (0.0-1.0) required to accept a language detection result without falling back

0.85

Must be a float between 0.0 and 1.0. Values below 0.7 produce excessive fallback; values above 0.95 produce risky routing on ambiguous inputs. Recommend 0.80-0.90 range.

[AMBIGUITY_FLAG]

Boolean controlling whether the prompt returns an ambiguity warning when multiple languages are plausible

Must be true or false. When true, output schema must include an 'ambiguous' field. When false, the model picks the highest-confidence language without signaling uncertainty.

[NAMED_ENTITY_HANDLING]

Instruction for how to treat foreign-language named entities, technical terms, and code within the query

"Treat foreign proper nouns and technical terms as non-indicative of overall language. Prioritize grammatical structure over isolated tokens."

String required. Must be non-empty. This instruction directly affects false-positive rates on queries containing brand names, person names, or API identifiers in other languages.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the language detection prompt into a production RAG pipeline with validation, retries, and fallback routing.

The language detection prompt is not a standalone utility; it is a critical routing component in a retrieval-augmented generation pipeline. When a user query arrives, the prompt must execute before any embedding lookup or document retrieval occurs. The detected language code determines which vector index to query, which embedding model to use, and which response generation locale to activate. A misclassification here silently breaks downstream retrieval quality—the system retrieves documents in the wrong language, generates responses the user cannot read, or wastes compute on indexes that contain no relevant content. Wire this prompt as a synchronous pre-retrieval step with a strict latency budget: 200–500ms is a reasonable target for most production systems, given that the prompt processes only the raw query text and returns a structured language label.

The implementation should follow a validate-then-route pattern. After the model returns a JSON payload containing the language code and confidence score, run a server-side validator that checks: (1) the language code exists in your supported language list, (2) the confidence score exceeds your configured threshold (start at 0.85 and calibrate downward based on eval results), and (3) the output schema matches the expected fields exactly. If validation fails, retry once with the same prompt—transient model failures or malformed JSON are the most common causes. If the retry also fails or returns confidence below threshold, route the query to a multilingual fallback index that contains documents across all supported languages. This fallback path prevents dropped queries and gives you a safety net while you tune the detection prompt. Log every routing decision—detected language, confidence score, retry count, and final index selected—so you can measure misrouting rates and identify language pairs where detection accuracy degrades.

For model selection, prefer a fast, cost-efficient model for this classification task. A lightweight model like GPT-4o-mini, Claude Haiku, or a fine-tuned open-weight classifier will handle language detection reliably without adding significant latency or cost to every query. Avoid routing this prompt to a large reasoning model—language detection is a pattern-matching task that does not benefit from chain-of-thought or extended context windows. If you are processing high query volumes, consider batching language detection requests where your architecture permits, or deploy a dedicated classification endpoint with connection pooling to reduce per-request overhead. For RAG systems that support code-switched or mixed-language queries, extend the validator to handle multi-language outputs and route to multiple indexes when the prompt returns more than one language above the confidence threshold.

The most dangerous failure mode in production is silent misrouting: the prompt returns a plausible but incorrect language code with high confidence, and the query flows to the wrong index without any alert. To catch this, implement an eval harness that runs alongside your production pipeline. Sample a percentage of routed queries (start with 5%), run them through a human-reviewed language verification step or a secondary detection model, and compare the results against the primary prompt's output. Set an alert threshold—if the disagreement rate exceeds 2% for any language pair, trigger a review of that pair's detection performance. For high-risk deployments where retrieval quality directly impacts user trust or regulatory compliance, add a human-in-the-loop confirmation step for queries where the confidence score falls between 0.70 and 0.85, or where the detected language is a known difficult case (e.g., short queries, CJK disambiguation, transliterated text). This adds latency but prevents the worst-class misrouting errors from reaching users.

IMPLEMENTATION TABLE

Expected Output Contract

The structured contract the Language Detection prompt must fulfill. Use this table to validate the model's response before routing the query to a language-specific RAG index.

Field or ElementType or FormatRequiredValidation Rule

detected_language

ISO 639-1 code (string)

Must be a valid two-letter code from a predefined allowlist of supported languages. Reject any response not in the allowlist.

confidence_score

float (0.0 to 1.0)

Must be a number between 0 and 1 inclusive. If below the [CONFIDENCE_THRESHOLD], the routing harness must trigger a fallback or clarification path.

is_ambiguous

boolean

Must be true if confidence_score is below [CONFIDENCE_THRESHOLD] or if multiple languages are detected with significant probability. Used to gate automatic routing.

alternative_languages

array of objects

If present, each object must contain a 'language' (ISO 639-1 string) and a 'score' (float). The array must be sorted by score descending. Null is allowed if is_ambiguous is false.

target_index

string

Must exactly match a valid index name from the [INDEX_MAP] configuration. If no match is found, the routing harness must reject the output and log the mismatch.

requires_translation

boolean

Must be true if the detected language does not match the native language of the target index's embedding model. Used to decide whether to invoke a translation layer before retrieval.

rationale

string

Must be a non-empty string summarizing the key linguistic evidence for the decision. The harness should log this for debugging but not use it for routing logic.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when routing queries by language in RAG pipelines, and how to guard against silent misrouting.

01

Short Query Ambiguity

What to watch: Queries under 10 words (e.g., 'bank', 'chat', 'order status') lack sufficient signal for reliable language detection. The model may default to English or the training-dominant language, routing a Spanish query to the English index. Guardrail: Implement a minimum character threshold (e.g., 50 characters) before trusting the language label. Below threshold, return language=und with confidence=0 and route to a multilingual fallback index or ask the user to clarify.

02

Foreign-Language Named Entities

What to watch: A query in English containing German entity names (e.g., 'What is the policy at Münchener Rück?') can trigger a false German classification. The model latches onto the entity's script or orthography rather than the surrounding query language. Guardrail: Add a few-shot example explicitly demonstrating that named entities do not determine the query language. In eval, include a test suite of queries with cross-lingual proper nouns, brand names, and technical terms to measure misrouting rate.

03

Code-Switched Input Misclassification

What to watch: Users mixing languages in a single query (e.g., '¿Cómo configuro the Kubernetes cluster?') cause the model to pick one language arbitrarily, often the first detected. The query routes to a monolingual index missing half the relevant context. Guardrail: Extend the prompt to output a primary language plus a secondary language list with proportion estimates. Route to the primary index but log the secondary languages. If the secondary proportion exceeds 30%, consider a multi-index retrieval or flag for review.

04

CJK Script Overlap

What to watch: Chinese, Japanese, and Korean queries sharing Han characters (e.g., 大学 appears in both Chinese and Japanese) cause disambiguation failures. The model may default to Chinese due to training data imbalance, routing Japanese queries to the wrong embedding model and index. Guardrail: Add explicit CJK disambiguation logic in the prompt using kana detection (Japanese), hangul detection (Korean), and character frequency heuristics (Chinese). Include a dedicated eval set of 100+ short CJK queries with known ground-truth labels.

05

Overconfident Low-Resource Language Detection

What to watch: The model assigns high confidence to a wrong language label for low-resource languages (e.g., Swahili misclassified as Arabic, Tagalog as Spanish) because training data for those languages is sparse. The query routes to an index with no relevant documents, producing empty or irrelevant retrieval. Guardrail: Require the prompt to output a calibrated confidence score and an ambiguity_flag. Route low-confidence predictions to a multilingual embedding model instead of a language-specific one. Log all low-confidence routes for weekly review and model threshold tuning.

06

Technical Terminology as Language Signal

What to watch: Queries heavy with English technical terms (e.g., 'API', 'dataframe', 'latency') but written in another language can be misclassified as English. The model weights loanwords and domain terms as language signal, ignoring the grammatical structure of the surrounding text. Guardrail: Instruct the prompt to prioritize function words, morphology, and syntax over technical vocabulary when determining language. Include eval examples where >40% of tokens are English loanwords but the query language is not English.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the Language Detection for RAG Pipeline Routing Prompt before deployment. Each criterion targets a known failure mode in production language routing.

CriterionPass StandardFailure SignalTest Method

Primary Language Accuracy

Correct ISO 639-1 code for inputs >= 15 words

Wrong language code returned for unambiguous monolingual text

Run against a golden dataset of 200+ monolingual samples across all supported languages

Short-Text Ambiguity Handling

Returns [LANGUAGE_CODE] with confidence < 0.8 AND ambiguity_flag: true for inputs < 5 words

High-confidence classification on single-word queries or proper nouns

Test with 50 short queries: 'Paris', 'bank', 'chat', 'data' and verify low confidence

Mixed-Language Input Detection

Returns primary_language AND secondary_languages array with proportion estimates

Only one language reported when input contains >= 20% secondary language tokens

Inject code-switched sentences: 'I need ayuda with my cuenta' and verify both 'en' and 'es' detected

Named Entity Resilience

Correct language despite foreign-language named entities in text

Language misclassified because of person names, brand names, or place names in another language

Test: 'I visited München last summer and loved the Biergarten' must return 'en' not 'de'

CJK Disambiguation

Correctly distinguishes zh, ja, ko on inputs >= 10 characters

zh returned for Japanese text containing kanji without kana

Test with 30 samples each of Chinese, Japanese, Korean; require 95% accuracy on strings >= 10 chars

Confidence Score Calibration

Confidence >= 0.9 correlates with >= 95% accuracy; confidence < 0.6 correlates with < 70% accuracy

High confidence on misclassified inputs or low confidence on trivially easy inputs

Plot calibration curve using 500 labeled samples; compute ECE (Expected Calibration Error) < 0.1

Unsupported Language Fallback

Returns 'unsupported' or configured fallback code when language not in [SUPPORTED_LANGUAGES]

Closest-match language returned for unsupported language without flagging

Test with Amharic, Basque, Welsh inputs; verify fallback behavior matches [FALLBACK_POLICY]

Latency Budget Compliance

Classification completes in < [LATENCY_BUDGET_MS] for 95th percentile

Timeout or > 2x budget on long inputs or mixed-script text

Load test with 1000 requests at varying lengths; measure p50, p95, p99 latency

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a simple function that calls the model with raw text. Use a lightweight wrapper that returns { language_code, confidence } without strict schema enforcement. Hardcode the list of supported language codes and index mappings in application config rather than the prompt. Log every classification result alongside the input for manual spot-checking.

code
SYSTEM: Detect the language of the following query. Return JSON with language_code (ISO 639-1) and confidence (0-1).

USER QUERY: [INPUT_TEXT]

Watch for

  • Missing schema checks letting malformed JSON through to downstream routing
  • Overly broad instructions causing the model to explain its reasoning instead of returning clean JSON
  • No handling for inputs under 10 characters where confidence should be low
  • Hardcoded language lists drifting out of sync with actual vector index coverage
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.