Use this prompt when your ingestion pipeline processes text that may contain multiple writing systems, code-switched content, or visually similar scripts that confuse downstream language detectors. Script detection is a pre-language step that narrows the candidate language set and prevents misrouting of text that shares character sets across unrelated languages. For example, a string written in Cyrillic could be Russian, Ukrainian, Serbian, or Mongolian—detecting the Cyrl script first constrains the language classifier to a manageable subset rather than forcing it to consider all possible languages. This prompt is essential for platforms handling user-generated content from global audiences, multilingual document processing systems, and any pipeline where wrong-language routing degrades output quality or user trust.
Prompt
Script Detection Prompt for Multilingual Input

When to Use This Prompt
Understand when script detection should precede language classification and when it adds unnecessary complexity to your pipeline.
Deploy this prompt when you observe language classifiers failing on short strings, mixed-script documents, or inputs where the writing system itself is the strongest signal. Common failure cases include: Arabic script text misclassified as Persian or Urdu because the classifier overweights vocabulary; Chinese text written in Latin script (Pinyin) routed to English models; and code-switched social media posts where script boundaries mark language boundaries. The prompt produces ISO 15924 script codes (e.g., Latn, Arab, Cyrl, Hans, Hant, Deva) with per-script proportion estimates and a primary script designation, giving your routing middleware structured data to make deterministic decisions. Wire the output into a script-to-language mapping table that feeds your language classifier a constrained candidate list rather than the full set of supported languages.
Do not use this prompt when your input is already known to be monolingual, single-script, or when your language classifier has proven reliable on your specific input distribution. Adding script detection to a pipeline that only processes English-language support tickets adds latency and cost without improving routing accuracy. Similarly, skip this step when you are using a modern multilingual embedding model or LLM that handles script variation natively—many production models now encode script information internally and do not benefit from an explicit pre-classification step. The prompt is most valuable when you control the routing logic between models and need deterministic, auditable decisions rather than relying on a single model's internal representations. Before deploying, run eval checks on visually similar script pairs (Arabic vs. Persian, Chinese Simplified vs. Japanese Kanji, Latin-script languages with heavy diacritic use) and measure whether script detection actually improves downstream classification accuracy for your specific input mix.
Use Case Fit
Where the Script Detection Prompt works reliably and where it introduces risk. Use these cards to decide if this prompt belongs in your pipeline or if you need a different approach.
Good Fit: Pre-Classification Before Language Detection
Use when: you need to identify the writing system (Latin, Cyrillic, Arabic, Han, etc.) before running language-specific classifiers. Script detection narrows the candidate language set and prevents impossible language-script combinations. Guardrail: Always run script detection first in multilingual pipelines; never assume language from script alone.
Bad Fit: Short Strings Under 10 Characters
Avoid when: inputs are very short queries, single words, or proper names. Script detection on strings like 'Paris' or '12345' produces unreliable results because many scripts share character subsets. Guardrail: Set a minimum character threshold (≥10 characters) and route short inputs to a combined script-and-language classifier with explicit low-confidence handling.
Required Input: Raw Text with Unicode Preservation
What to watch: text that has been normalized, lowercased, or stripped of diacritics before reaching the prompt. Script detection depends on character-level features that normalization can destroy. Guardrail: Pass raw, unnormalized text to the script detection prompt. Apply normalization only after script and language are determined.
Operational Risk: Visually Similar Scripts
Risk: scripts like Cyrillic and Latin share visually identical characters (e.g., 'A', 'O', 'T'), causing misclassification on mixed-script or short inputs. Guardrail: Add eval checks specifically for Cyrillic-Latin, Greek-Latin, and Arabic-Persian confusion pairs. Require confidence scores and flag ambiguous results for human review or secondary classification.
Operational Risk: Code-Switched Text with Multiple Scripts
Risk: inputs containing multiple scripts (e.g., Arabic with embedded English URLs, Hindi in Devanagari with Latin brand names) produce ambiguous script labels. A single ISO 15924 code may not capture the full input. Guardrail: Extend the output schema to return an array of detected scripts with character-count proportions. Route multi-script inputs to a segmentation prompt before language classification.
Operational Risk: Emoji-Only or Symbol-Heavy Inputs
Risk: inputs consisting primarily of emoji, punctuation, or mathematical symbols produce spurious script detections or 'Zyyy' (undetermined) codes that downstream systems cannot route. Guardrail: Pre-filter for symbol-only inputs before script detection. If the proportion of alphabetic characters is below 30%, route to a special handling queue rather than forcing a script classification.
Copy-Ready Prompt Template
A production-ready prompt for detecting writing systems in multilingual text and returning ISO 15924 script codes.
This prompt template is designed to be pasted directly into your system instructions for a script detection task. It identifies the writing system(s) present in [INPUT] text, returning standardized ISO 15924 script codes. This is a critical pre-processing step before language classification, as many languages share scripts, and misidentifying the script can cascade into downstream routing errors. The prompt is built to handle single-script, multi-script, and code-switched inputs, and it explicitly instructs the model to reason about visually similar scripts (e.g., Cyrillic vs. Latin) and script mixtures.
textYou are a script detection engine. Your task is to analyze the provided text and identify the writing system(s) used, returning only ISO 15924 script codes. [INPUT] """ [USER_TEXT] """ [OUTPUT_SCHEMA] You must respond with a single, valid JSON object conforming to this schema: { "primary_script": "string (ISO 15924 code for the dominant script)", "detected_scripts": ["string (list of all unique ISO 15924 codes found)"], "script_mixture": "boolean (true if more than one script is detected)", "confidence": "float (0.0 to 1.0, your confidence in the primary script classification)", "rationale": "string (brief explanation of the character analysis, noting any ambiguity)" } [CONSTRAINTS] 1. Use only valid ISO 15924 four-letter codes (e.g., 'Latn', 'Cyrl', 'Arab', 'Hans', 'Hant', 'Jpan', 'Kore'). 2. For CJK characters, distinguish between 'Hans' (Simplified Chinese), 'Hant' (Traditional Chinese), 'Jpan' (Japanese, including Kanji and Kana), and 'Kore' (Korean, including Hangul and Hanja). 3. If the text contains digits, punctuation, or emoji that are script-agnostic, do not include them in the script detection logic unless they are the only characters present. 4. If the input is empty or contains only whitespace, set 'primary_script' to 'Zyyy' (Undetermined) and 'confidence' to 0.0. 5. Prioritize precision on short strings. A single word in a new script should be detected. [EXAMPLES] Input: "Hello, how are you? 你好吗?" Output: {"primary_script": "Latn", "detected_scripts": ["Latn", "Hans"], "script_mixture": true, "confidence": 0.99, "rationale": "Predominantly Latin script with a phrase in Simplified Chinese at the end."} Input: "Москва" Output: {"primary_script": "Cyrl", "detected_scripts": ["Cyrl"], "script_mixture": false, "confidence": 0.99, "rationale": "All characters are Cyrillic."} Input: "data-base" Output: {"primary_script": "Latn", "detected_scripts": ["Latn"], "script_mixture": false, "confidence": 0.95, "rationale": "All letters are Latin script; the hyphen is script-agnostic."}
To adapt this template, replace the [USER_TEXT] placeholder with the input string from your application. You can hardcode the [OUTPUT_SCHEMA] and [CONSTRAINTS] into your system prompt for a fixed use case, or keep them as variables if you are building a more general script-detection microservice. The [EXAMPLES] section is crucial for calibrating the model's behavior on edge cases like CJK disambiguation and mixed-script text. For high-stakes routing, you must pair this prompt with a post-processing validation step that checks the returned codes against a known list of ISO 15924 codes and flags any confidence score below your operational threshold for human review or a fallback model.
Prompt Variables
Required inputs for the script detection prompt. Validate these before sending to the model to prevent silent misclassification of visually similar scripts or code-switched text.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[INPUT_TEXT] | Raw text to analyze for script identification | Привет, how are you? 你好吗? | Required. Must be non-null string. Reject empty strings. Length check: warn if under 10 characters due to insufficient signal for script disambiguation. |
[EXPECTED_SCRIPTS] | Whitelist of ISO 15924 codes the system can handle downstream | ["Latn", "Cyrl", "Hans", "Arab"] | Required. Must be valid JSON array of 4-letter ISO 15924 codes. Validate each code against ISO 15924 registry. Empty array means detect all scripts. |
[CONFIDENCE_THRESHOLD] | Minimum confidence score before routing proceeds automatically | 0.85 | Required. Float between 0.0 and 1.0. Values below 0.7 should trigger human review or clarification request. Default 0.85 for production routing. |
[ALLOW_MULTIPLE_SCRIPTS] | Whether to return multiple scripts for mixed-script input | Required. Boolean. When false, prompt must return only the dominant script. When true, returns all detected scripts with proportion estimates. | |
[OUTPUT_LOCALE] | Language for any explanatory text in the output | en | Optional. ISO 639-1 code. Defaults to "en". Used only for human-readable fields like warnings or notes, not for script codes themselves. |
[MIN_SPAN_LENGTH] | Minimum character span to count as a separate script segment | 3 | Optional. Integer >= 1. Prevents single-character false positives from symbols, emoji, or quoted foreign words. Default 3 for production use. |
[KNOWN_FALSE_POSITIVES] | Character ranges or patterns to ignore during detection | ["U+1F300..U+1F5FF", "U+2600..U+26FF"] | Optional. JSON array of Unicode ranges or regex patterns. Use to exclude emoji, mathematical symbols, and punctuation that share visual similarity with scripts. |
Implementation Harness Notes
How to wire the script detection prompt into an ingestion pipeline with validation, retry logic, and observability.
The script detection prompt is designed to be a lightweight, stateless classifier that sits at the ingress layer of a multilingual ingestion pipeline. It should be called before language identification, as script classification narrows the candidate language set and prevents downstream models from attempting to parse text in unsupported writing systems. In a typical implementation, raw text arrives from an API endpoint, message queue, or batch job, and the prompt is invoked as a synchronous step whose output determines the next processing stage. The prompt expects a single text input and returns an ISO 15924 script code, a confidence score, and a list of any additional scripts detected. This output should be logged alongside the request ID for traceability and later evaluation.
To wire this into an application, wrap the prompt call in a thin service function that handles validation, retries, and fallback. Validate the model's response against a strict schema: the script field must be a valid ISO 15924 four-letter code, confidence must be a float between 0 and 1, and additional_scripts must be an array of valid codes or an empty list. If validation fails, retry once with the same input and a slightly lower temperature (e.g., 0.0 on retry vs. 0.1 on the initial call). If the retry also fails, log the raw response and route the text to a manual review queue rather than guessing. For model choice, a fast, inexpensive model like GPT-4o-mini or Claude Haiku is sufficient for most scripts; reserve larger models for edge cases involving visually similar scripts like Cyrillic vs. Latin or Arabic vs. Persian, where you may want to add a second-pass verification prompt. Do not use this prompt as the sole gate for compliance-critical routing—always pair it with a human review path when script misclassification could cause regulatory exposure.
Observability is critical because script detection failures cascade into language misclassification, wrong embedding model selection, and broken downstream processing. Log the detected script, confidence score, input length, and whether the result passed validation on every call. Set an alert if the validation failure rate exceeds 2% over a rolling window, as this often indicates a model behavior change or a new script pattern in production traffic. For eval, maintain a golden dataset of 200+ samples covering single-script text, multi-script mixtures, code-switched content, and edge cases like emoji-only strings or text composed entirely of punctuation. Run this eval suite on any prompt or model change before deployment. When confidence falls below 0.85, consider routing to a secondary classifier or flagging for human review rather than silently accepting a low-confidence script assignment.
Expected Output Contract
Schema contract for the script detection prompt. Use this to validate model output before routing decisions.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
primary_script | string (ISO 15924 code) | Must match /^[A-Z][a-z]{3}$/; must be a valid ISO 15924 alpha-4 code | |
primary_script_confidence | number (0.0-1.0) | Must be a float between 0 and 1 inclusive; reject if confidence < [MIN_CONFIDENCE_THRESHOLD] | |
detected_scripts | array of strings | Each element must match /^[A-Z][a-z]{3}$/; array must contain at least one entry; must include primary_script | |
script_proportions | object | Keys must be ISO 15924 codes present in detected_scripts; values must be numbers 0.0-1.0 summing to 1.0 ± 0.01 | |
ambiguous_script_pairs | array of objects | Each object must have fields: script_a (string), script_b (string), reason (string); null allowed if no ambiguity detected | |
code_switch_detected | boolean | Must be true if detected_scripts length > 1; must be false if detected_scripts length is 1 | |
input_character_count | integer | Must be a positive integer matching the character length of [INPUT_TEXT]; reject if mismatch > 5 characters | |
detection_timestamp | string (ISO 8601) | If present, must parse as valid ISO 8601 datetime; null allowed for batch processing without timestamps |
Common Failure Modes
Script detection fails silently in production when writing systems look similar, text is too short, or code-switching confuses the classifier. These cards cover the most common breaks and how to guard against them before they reach downstream routing.
CJK Script Confusion
What to watch: Chinese (Hans/Hant), Japanese, and Korean share Han characters (CJK Unified Ideographs). A prompt that only looks for character presence will misclassify Japanese as Chinese or miss Korean when Hangul is sparse. Guardrail: Require multi-signal detection—kana presence for Japanese, Hangul for Korean, and character frequency analysis for Chinese variants. Add a CJK-specific eval set with short strings, mixed-script documents, and Han-only inputs.
Short Text Underdetermination
What to watch: Inputs under 10 characters often lack enough script signal for confident classification. A single word like '東京' could be Japanese or Chinese. The model may guess confidently and route incorrectly. Guardrail: Return an explicit ambiguous: true flag and a confidence score below 0.8 for inputs under 15 characters. Route ambiguous short text to a clarification prompt or a multi-script fallback queue rather than forcing a single script decision.
Visually Similar Scripts
What to watch: Cyrillic and Latin share glyphs (A, B, E, T, O, P, C). Greek and Latin share others. A naive prompt may classify Cyrillic text containing many shared glyphs as Latin, especially in uppercase or sans-serif contexts. Guardrail: Include negative examples in your few-shot prompt showing Cyrillic-only, Greek-only, and mixed-script strings. Add eval cases for uppercase-only inputs and strings composed entirely of shared glyphs. Require the model to identify script-specific characters (Ж, Щ, Ω, Ψ) before deciding.
Code-Switched Script Mixtures
What to watch: Users mix Arabic with French in Latin script, Hindi in Devanagari with English, or Japanese Kanji with Latin URLs. A single-script output fails when the input contains two or more writing systems. Guardrail: Design the output schema to return an array of detected scripts with proportion estimates, not a single script code. Add eval checks for common code-switching patterns in your user base. If the primary script is below 70% of characters, flag for multi-script handling.
Numeric and Symbol-Only Inputs
What to watch: Inputs containing only digits, punctuation, emoji, or mathematical symbols have no script signal. The model may hallucinate a script based on nothing or default to Latin. Guardrail: Add a pre-check that counts alphabetic characters. If fewer than 3 alphabetic characters exist, return script: "Zyyy" (ISO 15924 code for undetermined script) and route to a language-agnostic processing path. Never force a script guess on non-alphabetic input.
Transliterated Text Misclassification
What to watch: Romanized Arabic chat alphabet, Pinyin without tones, or romanized Hindi all use Latin script but represent non-Latin-script languages. The prompt will correctly identify Latin script but miss that the underlying language requires different downstream handling. Guardrail: Add a secondary detection layer for common transliteration patterns (repeated digits for Arabic chat alphabet, tone-number suffixes for Pinyin). When Latin script is detected but transliteration markers are present, flag as script: "Latn" with transliterated: true and route to language-detection rather than script-only routing.
Evaluation Rubric
How to test output quality before shipping. Run these checks against a golden dataset of at least 200 examples covering single-script, multi-script, CJK, and visually similar script pairs.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
ISO 15924 Code Accuracy | Correct 4-letter script code for >= 95% of single-script inputs | Wrong code returned for unambiguous script (e.g., Latn for Cyrillic text) | Exact match against labeled golden dataset; measure per-script precision/recall |
Multi-Script Detection Completeness | All scripts present in input are listed when proportion > 5% | Missing a script that occupies > 10% of characters; script ordering is arbitrary | Tokenize input by Unicode script blocks; verify all blocks above threshold appear in output |
CJK Disambiguation | Correctly distinguishes Hani, Hira, Kana, Hang across >= 90% of CJK test cases | Returns Hani for Japanese text containing kana; returns Hani for Korean Hangul-only text | Curated CJK test set with known script composition; check for kana/hangul presence as disambiguation signals |
Visually Similar Script Separation | Correctly separates Cyrl vs. Latn, Grek vs. Latn, Arab vs. Hebr in >= 85% of ambiguous cases | Returns Latn for Cyrillic text using characters with Latin lookalikes (e.g., а, е, о) | Adversarial test set of homoglyph strings; verify script decision uses character frequency not visual similarity |
Empty or Whitespace-Only Input | Returns empty script list or explicit null with no hallucinated codes | Returns a script code for empty string or whitespace-only input | Unit test with empty string, spaces, newlines, tabs; assert output is empty array or null |
Code-Switched Text Handling | Identifies all scripts present and optionally estimates proportion per script | Reports only the majority script when minority script exceeds 15% of characters | Synthetic code-switched inputs with known script ratios; verify all scripts above threshold appear |
Confidence or Ambiguity Flag | Output includes confidence score or ambiguity flag when multiple scripts are plausible | Returns single script code with no uncertainty indicator for genuinely ambiguous input | Test with short strings where script is underspecified (e.g., 'cat' could be Latn or Cyrl); verify ambiguity signal present |
Non-Text Input Robustness | Returns empty script list or error indicator for numeric-only, emoji-only, or symbol-only input | Returns a script code for input containing no letters (e.g., '12345' or '🔥🔥🔥') | Unit test with numeric strings, emoji sequences, punctuation-only; assert no false script detection |
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 lightweight JSON schema. Use a single model call without retries. Accept the first valid ISO 15924 code returned.
codeSystem: You are a script classifier. Return JSON with script_code (ISO 15924), script_name, and confidence (0-1). User: Classify the writing system: [INPUT_TEXT]
Watch for
- Missing schema validation on the output
- Overly broad instructions that return language codes instead of script codes
- No handling for mixed-script inputs—model may pick the majority script and ignore the rest

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