This prompt is designed for telecom integrators and data engineers who receive partial phone numbers from model outputs—numbers missing country codes, containing ambiguous local formats, or stripped of international prefixes during extraction. The job-to-be-done is inferring the most likely E.164 country code from available context clues (other fields in the record, user locale, language signals, or explicit hints in surrounding text) and producing a complete, dialable number with a confidence flag. The ideal user is building an identity resolution pipeline, a CRM ingestion workflow, or a customer data platform where incomplete numbers block deduplication and downstream routing.
Prompt
Country Code Inference for Partial Phone Numbers Prompt Template

When to Use This Prompt
Understand the job, the required inputs, and the boundaries before wiring country code inference into a production pipeline.
Use this prompt when you have a partial number and at least one contextual signal—a billing country, a user-provided locale, a language preference, or a known region from a related record. The prompt is not a general-purpose phone validator; it assumes the number itself is syntactically plausible but missing the country prefix. Do not use this prompt when you have zero context (the model will guess, and the confidence flag will be low, but the output may still be misleading), when the number is already in full E.164 format (use a canonicalization prompt instead), or when the number is so malformed that digit-level repair is required before country code inference can begin. For high-volume pipelines, pair this prompt with a pre-filter that separates already-complete numbers from partial ones to avoid unnecessary inference calls.
The prompt produces a structured output containing the inferred country code, the completed E.164 number, a confidence score, and a reasoning trace. Ambiguous cases are the primary failure mode: numbers like 2025550142 could be Washington, DC (+1) or a subset of other North American numbering plan digits. The prompt is designed to flag these ambiguities rather than silently pick a winner. Before wiring this into production, you must decide your threshold for auto-acceptance versus human review, and you should test against a golden set of ambiguous cases where multiple countries share overlapping number patterns. The next section provides the copy-ready template with placeholders for your specific inputs, constraints, and risk tolerance.
Use Case Fit
Where the Country Code Inference prompt template works, where it fails, and the operational risks to manage before integrating it into a telecom or CRM pipeline.
Good Fit: Context-Rich Partial Numbers
Use when: the model output includes a partial number alongside strong contextual clues such as a full address, region code, or explicit country mention. The prompt reliably infers the correct E.164 country code when disambiguation is low. Guardrail: always pass the surrounding context, not just the raw number string.
Bad Fit: Ambiguous Multi-Country Patterns
Avoid when: the number pattern is shared across multiple countries (e.g., North American Numbering Plan) and no other context is available. The model will guess, often incorrectly. Guardrail: require a confidence flag in the output schema and route low-confidence inferences to a human review queue.
Required Inputs: More Than Just Digits
Risk: passing only a bare number string forces the model to hallucinate a country code based on statistical priors. Guardrail: the prompt template requires a [CONTEXT] field containing the original model output, user metadata, or transaction locale. Without it, the inference is unreliable.
Operational Risk: Silent Misrouting
Risk: an incorrectly inferred country code can route calls or messages to the wrong destination, causing compliance violations or customer experience failures. Guardrail: implement a post-inference validator that checks the resulting E.164 number against known valid ranges for the inferred country before the number enters any downstream system.
Operational Risk: Over-Confidence on Short Numbers
Risk: the model may assign high confidence to inferences on very short or truncated numbers where no reliable disambiguation is possible. Guardrail: add a minimum digit-length threshold in the application harness. Numbers below 7 digits should always be flagged for human review, regardless of model confidence.
Pipeline Fit: Post-Extraction Repair Step
Use when: this prompt is a repair step after an initial extraction model has produced a partial or ambiguous phone number. It is not a standalone extraction tool. Guardrail: chain this prompt after a validation step that detects missing country codes, and only invoke it for records that fail E.164 validation.
Copy-Ready Prompt Template
A reusable prompt template with square-bracket placeholders for inferring missing country codes from partial phone numbers in model outputs.
This prompt template is designed to take a partial phone number—one that may be missing its country code—along with available context clues, and return a complete E.164-formatted number with an inferred country code and a confidence flag. The template uses square-bracket placeholders that you replace with actual values in your application code before sending the request to the model. The core job is disambiguation: when a number like 555-0123 could belong to multiple countries, the model must weigh contextual signals such as user locale, address fields, or surrounding text to make the best inference.
textYou are a phone number normalization specialist. Your task is to infer the missing country code for a partial phone number and return a complete E.164-formatted number. INPUT NUMBER: [PARTIAL_NUMBER] CONTEXT CLUES (may be empty): [CONTEXT] USER LOCALE (ISO 3166-1 alpha-2, may be empty): [LOCALE] RULES: 1. If the input number already includes a valid country code, return it as-is in E.164 format. 2. If the country code is missing, infer the most likely country code using the context clues and user locale. 3. If multiple countries share the number pattern, use context to disambiguate. If context is insufficient, default to the user locale's country code. 4. If no inference is possible, set the country code to null and flag the output. 5. Strip any leading zeros, trunk prefixes, or non-numeric characters before formatting. 6. Return ONLY valid JSON matching the output schema. No explanatory text. OUTPUT SCHEMA: { "original_input": "string (the input as received)", "e164_number": "string (complete E.164 number with + and country code, or null if impossible)", "inferred_country_code": "string (ISO 3166-1 alpha-2, or null)", "confidence": "high | medium | low | none", "reasoning": "string (brief explanation of inference logic)", "requires_human_review": true | false } CONSTRAINTS: - Do not invent area codes or subscriber numbers not present in the input. - If the input appears to be a local number without enough context, flag for human review. - For numbers in the North American Numbering Plan (NXX-NXX-XXXX patterns), default to US (+1) unless context strongly indicates Canada or another NANP country. - For UK numbers starting with 07, infer +44. - For numbers matching mobile patterns in multiple EU countries, use locale as tiebreaker.
To adapt this template, replace each bracketed placeholder with real data from your pipeline. [PARTIAL_NUMBER] should be the raw number string from the model output. [CONTEXT] should include any surrounding text, address fields, or user-provided location hints. [LOCALE] should be a two-letter country code from your application's user session or request metadata. In production, always validate the returned JSON against the output schema before accepting the inference. For high-risk telecom or compliance workflows, route any output with confidence: "low" or requires_human_review: true to a review queue rather than writing it directly to your system of record.
Prompt Variables
Required inputs for the country code inference prompt. Each placeholder must be populated before the prompt is sent. Validation notes describe how to check the input quality before inference.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[PARTIAL_PHONE_NUMBER] | The incomplete phone number string that may be missing a country code | +1 (555) 123-4567 or 07700 900123 | Must be a non-empty string. Strip whitespace and non-numeric characters before validation. Reject if fewer than 7 digits remain. |
[CONTEXT_CLUES] | Additional text or metadata that may hint at the country of origin | User profile locale: de-DE, Shipping address: Berlin, Germany | Optional but strongly recommended. If null, set to empty string. When provided, check for ISO country codes, city names, or locale strings to improve inference accuracy. |
[DEFAULT_COUNTRY_CODE] | Fallback country code to use when inference confidence is below threshold | 1 | Must be a valid ITU-T country calling code as a string. Validate against a reference list of active country codes. Reject if code is reserved, unassigned, or longer than 3 digits. |
[CONFIDENCE_THRESHOLD] | Minimum confidence score required to accept an inferred country code without flagging for review | 0.85 | Must be a float between 0.0 and 1.0. Values below 0.7 produce excessive false positives; values above 0.95 may cause unnecessary human review. Default to 0.85 if not specified. |
[OUTPUT_SCHEMA] | Expected JSON structure for the normalized phone number and metadata | {"e164": "string", "country_code": "string", "confidence": "float", "needs_review": "boolean"} | Must be a valid JSON Schema object or a plain object example. Validate that required fields e164, country_code, and confidence are present. Reject schemas missing needs_review flag. |
[AMBIGUOUS_PATTERN_LIST] | Known number patterns shared by multiple countries to test disambiguation | ["1-xxx-xxx-xxxx", "44-7xxx-xxxxxx"] | Optional array of regex or glob patterns. When provided, the prompt should explicitly reason about these patterns. Validate each entry is a valid regex string. Empty array is acceptable. |
[MAX_RETRIES] | Number of repair attempts allowed if the output fails schema validation | 3 | Must be a positive integer. Values above 5 risk cost overruns without meaningful improvement. Default to 3. Track retry count in logs and abort if exceeded. |
Implementation Harness Notes
How to wire the country code inference prompt into a production application with validation, retries, and confidence gating.
This prompt is designed to be called as a post-processing step after a model has extracted or generated a partial phone number. It should not be the primary extraction prompt. Wire it into your pipeline immediately after phone number extraction and before the number is written to your canonical data store or passed to a downstream telephony API. The harness must treat the model's output as a structured repair suggestion, not as an authoritative result—every inferred country code must pass through validation and confidence checks before acceptance.
Input assembly: Collect the partial phone number string, any available locale hints (user language, shipping country, IP geolocation), and the original context where the number appeared. Pack these into the [PARTIAL_NUMBER], [LOCALE_HINTS], and [SOURCE_CONTEXT] placeholders. If no locale hints exist, pass an explicit null or empty object—do not omit the field, as the prompt's instructions depend on knowing when hints are absent. For batch processing, send one record per call; batching multiple numbers in a single prompt increases the risk of cross-record contamination and makes per-record confidence scoring unreliable.
Model choice and configuration: Use a model with strong instruction-following and low hallucination rates on structured tasks—GPT-4o, Claude 3.5 Sonnet, or equivalent. Set temperature=0 to maximize deterministic behavior. Enable structured output mode (JSON mode or tool calling with a defined schema) to enforce the [OUTPUT_SCHEMA] contract. The output must include inferred_country_code, complete_e164, confidence (a float 0.0–1.0), alternative_codes (array of other plausible codes), and reasoning (a brief string explaining the inference). If the model cannot produce valid JSON, fail closed—do not attempt to parse a free-text response.
Validation layer: Before accepting the output, run these checks: (1) The complete_e164 string must match the E.164 regex pattern ^\+[1-9]\d{1,14}$. (2) The inferred_country_code must appear in a hardcoded allowlist of valid ITU country calling codes. (3) If confidence < 0.85, route the record to a human review queue with the original partial number, the model's reasoning, and the alternative codes. (4) If alternative_codes contains a code with a confidence delta of less than 0.15 from the primary, flag the record as ambiguous—this often happens with North American numbers (+1 shared by US, Canada, and several Caribbean nations) or numbers in the +7 shared region. (5) Verify that the national significant number portion of the E.164 output is consistent with the input partial number; the model should not invent or drop digits.
Retry and fallback strategy: If validation fails due to malformed JSON or schema violations, retry once with the same input and an explicit error message appended to the prompt (e.g., 'Previous output failed validation: [ERROR_DETAIL]. Please correct and return valid JSON only.'). If the second attempt fails or if confidence remains below threshold after retry, do not retry further—escalate to human review. For high-throughput pipelines, implement a dead-letter queue for records that fail after max retries, and monitor the failure rate to detect prompt drift or model behavior changes.
Logging and observability: Log every inference with: input partial number (hashed if PII-sensitive), locale hints, model version, prompt version, raw output, validation result, confidence score, and final disposition (accepted, reviewed, rejected). This trace is essential for debugging ambiguous cases—especially shared country code regions—and for calibrating the confidence threshold over time. If your application operates in regulated telecom or financial contexts, these logs are also your audit evidence that inference decisions were reviewed and not applied blindly.
Expected Output Contract
Validate every field in the model response before it enters your telecom pipeline. Each row defines a required or optional element, its expected type, and the exact validation rule to apply.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
inferred_country_code | string (ISO 3166-1 alpha-2) | Must match /^[A-Z]{2}$/. Reject if not in allowed country list from [ALLOWED_COUNTRIES]. | |
e164_number | string | Must match /^+[1-9]\d{1,14}$/. Reject if country code prefix does not match inferred_country_code. | |
original_input | string | Must exactly match the [PARTIAL_NUMBER] input. Reject if any character is altered, added, or removed. | |
confidence | string | Must be one of: high, medium, low. Reject any other value. Map to downstream routing rules. | |
reasoning | array of strings | Must be a non-empty array. Each element must be a non-empty string. Reject if empty array or contains empty strings. | |
alternative_country_codes | array of strings | If present, each element must match /^[A-Z]{2}$/. Reject if any element is not in [ALLOWED_COUNTRIES]. Null allowed. | |
ambiguous_match | boolean | Must be true or false. Reject any other value. If true, confidence must be low or medium. | |
context_clues_used | array of strings | If present, must be a non-empty array of non-empty strings. Reject if empty array. Null allowed when no context clues were used. |
Common Failure Modes
Country code inference from partial phone numbers fails in predictable ways. These cards cover the most common production failure modes and how to guard against them before they reach downstream systems.
Ambiguous Numbering Plan Overlap
What to watch: The model cannot distinguish between countries that share the same national number length and leading digits (e.g., US/Canada +1, or several NANP Caribbean nations). The prompt confidently infers the wrong country code because the local number pattern is valid in multiple jurisdictions. Guardrail: Require the model to output a confidence field and a ranked list of alternative_countries when ambiguity exceeds a threshold. Route low-confidence inferences to a human review queue or cross-reference with a separate locale hint (language, address, or IP geolocation) before accepting the result.
Over-Inference from Weak Context Clues
What to watch: The model latches onto incidental context—such as a mention of a city name in the surrounding text or a user's display language—and infers a country code that is incorrect for the actual phone number. A number from London, Ontario gets +44 instead of +1. Guardrail: Add a strict instruction that context clues are secondary to number structure analysis. Require the model to separate structural_evidence (digit patterns) from contextual_evidence (surrounding text) in its reasoning, and never override structural evidence with weak context alone.
Silent Default to Home Country
What to watch: When no country code is present and context is sparse, the model defaults to a single country (often US +1 or the training-data-dominant locale) without flagging the assumption. This produces plausible-looking E.164 numbers that are silently wrong for international users. Guardrail: Never allow a hard default. Require the prompt to output inferred_country: null and confidence: 0 when structural evidence is insufficient. The application layer should then either prompt the user for clarification or block the record from downstream ingestion until resolved.
Mobile vs. Geographic Number Confusion
What to watch: The model misclassifies a mobile number as a geographic landline (or vice versa) and applies a country code inference rule that is only valid for one type. Some countries have distinct numbering ranges for mobile and fixed lines, and the model conflates them. Guardrail: Include a number_type field in the output schema (mobile, fixed, toll-free, premium) and instruct the model to use type-specific inference rules. Validate that the inferred country code is compatible with the detected number type before accepting the result.
Truncated Number Misinterpretation
What to watch: A partial or truncated phone number (e.g., missing the last few digits due to token limits or extraction errors) still passes structural validation because the remaining digits match a valid national pattern. The model infers a country code for a number that is too short to be reliable. Guardrail: Add a minimum digit count check in the prompt instructions. If the national number (after stripping any existing country code) falls below the minimum length for the inferred country, flag the output with truncation_risk: true and suppress the inference or mark it for human review.
Leading Zero and Trunk Prefix Mishandling
What to watch: The model treats a leading zero (common in national dialing formats across Europe and Asia) as part of the subscriber number rather than stripping it before applying E.164 formatting. This produces invalid E.164 numbers with an extra zero after the country code. Guardrail: Add explicit trunk prefix stripping rules per country in the prompt. Instruct the model to detect and remove national trunk prefixes (0, 0xx) before prepending the country code. Include test cases for countries with variable-length trunk prefixes in the eval harness.
Evaluation Rubric
Use this rubric to test the quality of inferred country codes before shipping the prompt. Each criterion targets a specific failure mode observed in production telecom pipelines.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
E.164 Format Compliance | All output numbers match ^+[1-9]\d{1,14}$ | Missing plus sign, leading zero after country code, or length > 15 digits | Regex validation on 100 generated outputs |
Country Code Accuracy | ≥ 95% of inferred codes match ground truth for unambiguous inputs | US number inferred as +91; UK mobile inferred as +353 | Labeled test set of 200 partial numbers with known country codes |
Confidence Flag Calibration | Low-confidence flag set when multiple valid countries share the number pattern | High confidence assigned to +1 number shared by US, Canada, and Jamaica without disambiguation | Check confidence field against known ambiguous number ranges (NANP overlap, +7 shared region) |
Context Clue Utilization | Provided context (language, address, currency) shifts inference correctly when number pattern is ambiguous | Ignoring [CONTEXT] field and defaulting to most populous country for the pattern | A/B test: same number with different context clues; verify output changes appropriately |
No Hallucinated Local Numbers | Local number portion preserved exactly as input; no digit invention or truncation | Input '555-1234' becomes '555-1235' or '555-12' in output | Character-level diff between input local number and output local number across 100 cases |
Multiple Country Listing Completeness | When ambiguous, all plausible countries listed in [POSSIBLE_COUNTRIES] with calling codes | Only one country returned for +1 number without context | Assert array length > 1 for known ambiguous prefixes; check calling code correctness |
Graceful Handling of Unparseable Input | Returns error object with reason when input cannot be parsed as a phone number | Model invents a country code for 'call me maybe' or 'N/A' | Test with 20 non-phone inputs; expect structured error with null confidence |
Output Schema Adherence | JSON matches exact [OUTPUT_SCHEMA] with all required fields present and correctly typed | Missing [INFERRED_COUNTRY_CODE] field; confidence returned as string instead of float | JSON Schema validation against expected schema; type check on confidence field |
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 small set of ambiguous test cases. Use a frontier model with default temperature (0.0–0.2). Skip strict schema enforcement initially—focus on whether the model returns plausible country codes and confidence flags. Add a simple post-processing step that maps the model's output to a flat JSON object with inferred_country_code, confidence, and reasoning fields.
Watch for
- The model returning country names instead of ISO codes—add explicit output format instructions if this occurs.
- Overconfidence on ambiguous numbers shared across countries (e.g., +1 for US/Canada).
- Missing
confidencefield when the model is unsure—add a fallback default of"low"in post-processing.

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