This prompt is designed for logistics, data quality, and ETL teams who need to convert raw, unstructured, or partially structured address strings into a canonical postal format. The primary job-to-be-done is to create a consistent, machine-readable address record that downstream systems can consume without manual intervention. Use it when your pipeline requires standardized fields for geocoding, shipping label generation, master data management, or duplicate detection. The prompt is built to handle country-specific formatting rules, PO boxes, rural routes, apartment and suite designators, and missing address components, making it suitable for global address corpora where a one-size-fits-all regex approach fails.
Prompt
Entity Canonicalization Prompt for Address Data

When to Use This Prompt
A practical guide for logistics and data quality teams to canonicalize raw address strings into a structured, confidence-scored postal format.
The ideal user is a data engineer or integration developer who is building an automated ETL pipeline and needs a reliable normalization step before data lands in a system of record. You should use this prompt when you have already extracted an address string from a source document (e.g., a PDF, email, or web form) and now need to parse and standardize it. The prompt requires you to provide the raw address string and, optionally, a target country code or formatting standard (like USPS, Royal Mail, or UPU) as context. It returns a structured JSON object with canonicalized fields (street number, street name, unit, city, state, postal code, country) and a confidence score for each field, enabling your pipeline to make an automated commit-or-review decision.
Do not use this prompt as a geocoding service; it normalizes text, it does not return coordinates. It is also not a substitute for a real-time address validation API when you need to verify deliverability against an official postal database. The prompt is best applied in batch processing or data cleaning workflows where you have a backlog of messy addresses. For high-risk applications like shipping label generation, always route records with low confidence scores to a human review queue. The next step after reading this section is to copy the prompt template, adapt the output schema to match your downstream database contract, and wire it into a validation harness that checks for schema compliance and confidence thresholds before committing any record.
Use Case Fit
Where the Entity Canonicalization Prompt for Address Data works well, where it breaks, and the operational preconditions required before putting it into a production pipeline.
Strong Fit: High-Volume Logistics Ingestion
Use when: You are processing thousands of shipment, return, or facility records per day and need a consistent postal format for label printing, rate calculation, or route optimization. Guardrail: Pair the prompt with a downstream address validation API (e.g., USPS, DHL, local postal authority) to catch canonicalization errors before they become shipping failures.
Poor Fit: Real-Time Point-of-Capture Correction
Avoid when: The user is typing an address into a web form and expects instant, interactive suggestions. This prompt is designed for batch or asynchronous normalization of already-extracted text, not for sub-100ms typeahead. Guardrail: Use a dedicated address autocomplete service for capture; reserve this prompt for cleaning the data after it lands in your database.
Required Inputs: Pre-Extracted Address Components
Risk: Feeding raw, unstructured text (e.g., a full email body) into the canonicalization prompt will produce hallucinated or merged addresses. Guardrail: This prompt expects a structured input object with street, city, state, postal_code, and country fields. Run an extraction prompt first, then pass the extracted object here for normalization.
Operational Risk: Country-Specific Rule Drift
Risk: A single prompt covering all countries will fail on edge cases like Japanese address order, Brazilian neighborhood designations, or UK dependent localities. Guardrail: Implement a country field router that selects a country-specific canonicalization sub-prompt or configuration. Test each country template independently with at least 50 local addresses before merging.
Operational Risk: Silent Data Corruption on Partial Addresses
Risk: The model may confidently fill in missing postal codes or street suffixes with plausible but incorrect values, corrupting your master data. Guardrail: Require the output to include a completeness_score and a modified_fields array. If a critical field like postal_code was missing from the input and the model generated it, flag the record for human review instead of direct ingestion.
Poor Fit: Geocoding Replacement
Avoid when: You need latitude/longitude coordinates or spatial validation (e.g., "does this address exist?"). Canonicalization reformats text; it does not verify real-world existence. Guardrail: Use a dedicated geocoder after canonicalization. If the geocoder returns a low-confidence match, route the original and canonicalized address to a review queue.
Copy-Ready Prompt Template
A reusable prompt with square-bracket placeholders for normalizing extracted addresses to a standard postal format with confidence scoring.
This template is designed to be copied directly into your prompt management system, IDE, or orchestration layer. It accepts a raw address string and a target country code, then returns a structured, canonical address record. Every variable is enclosed in square brackets—replace them with your application's values at runtime. The prompt enforces a strict JSON output schema, handles partial addresses, and requires the model to score its confidence in each component rather than silently guessing.
textYou are an address canonicalization engine. Your task is to normalize the provided address into a standard postal format for the specified country. You must handle partial addresses, PO boxes, rural routes, and ambiguous components. Do not invent missing information. For every address component you return, provide a confidence score between 0.0 and 1.0. INPUT ADDRESS: [RAW_ADDRESS] TARGET COUNTRY (ISO 3166-1 alpha-2): [COUNTRY_CODE] OUTPUT SCHEMA (strict JSON): { "canonical_address": { "recipient_line": string | null, "building_number": string | null, "street_name": string | null, "unit_type": string | null, "unit_number": string | null, "po_box": string | null, "rural_route": string | null, "locality": string | null, "administrative_area": string | null, "postal_code": string | null, "country_code": string }, "component_confidence": { "recipient_line": number, "building_number": number, "street_name": number, "unit_type": number, "unit_number": number, "po_box": number, "rural_route": number, "locality": number, "administrative_area": number, "postal_code": number }, "normalization_notes": [string], "is_complete_address": boolean } CONSTRAINTS: [CONSTRAINTS] EXAMPLES: [EXAMPLES]
Adaptation guidance: Replace [RAW_ADDRESS] with the extracted or user-provided address string. [COUNTRY_CODE] should be a two-letter ISO code (e.g., US, DE, JP) to trigger country-specific formatting rules. Use [CONSTRAINTS] to inject business rules such as 'If the postal code is missing, set is_complete_address to false and add a normalization note.' The [EXAMPLES] placeholder should be populated with 2–4 few-shot examples showing correct handling of PO boxes, rural routes, and partial addresses for your target countries. If your application requires a different output schema (e.g., a single address_line_1 field), modify the JSON structure before deploying, but keep the component-level confidence scores to enable downstream routing decisions.
Next step: After copying this template, wire it into your application harness with a JSON validator that rejects malformed responses. Define a confidence threshold for each component—addresses with postal_code confidence below 0.8 should route to a human review queue rather than being ingested directly into your shipping or billing system. Test the prompt against a golden dataset of 50–100 addresses that includes edge cases like rural routes, multi-unit buildings, and addresses with missing locality fields before promoting to production.
Prompt Variables
Inputs required by the Entity Canonicalization Prompt for Address Data. Each placeholder must be populated before the prompt is sent to the model. Validation notes describe how to check the input before execution.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[RAW_ADDRESS] | The unprocessed address string extracted from the source document | 123 main st. apt 4b springfield il 62701 | Required. Must be a non-empty string. Check for null or whitespace-only values before calling the prompt. |
[COUNTRY_CODE] | ISO 3166-1 alpha-2 country code to apply country-specific formatting rules | US | Required. Must match /^[A-Z]{2}$/. Reject if country is not in the supported country list for this prompt version. |
[OUTPUT_SCHEMA] | The target JSON schema describing the canonical address fields | {"street_number": "string", "street_name": "string", ...} | Required. Must be a valid JSON Schema object. Validate with a schema parser before injection. Do not pass a bare string. |
[CONFIDENCE_THRESHOLD] | Minimum confidence score (0.0-1.0) required to accept a canonical component without flagging it for review | 0.85 | Required. Must be a float between 0.0 and 1.0. Values below 0.7 are not recommended for automated ingestion without human review. |
[ADDRESS_TYPE_HINT] | Optional hint about the expected address category to help disambiguation | residential | Optional. Allowed values: 'residential', 'commercial', 'po_box', 'rural_route', 'military', null. If null, the model infers the type. |
[PARTIAL_ADDRESS_POLICY] | Instruction for how to handle incomplete addresses: fill with null, infer missing parts, or reject | fill_with_null_and_flag | Required. Must be one of: 'fill_with_null_and_flag', 'infer_and_flag', 'reject'. Controls downstream ingestion behavior. |
[ABBREVIATION_EXPANSION_MAP] | A dictionary of allowed abbreviation expansions to override default postal standards | {"mtn": "mountain", "bldg": "building"} | Optional. Must be a valid JSON object with string keys and values. If null, the model uses default USPS or country-specific abbreviation tables. |
Implementation Harness Notes
How to wire the entity canonicalization prompt into a production application with validation, retries, logging, and human review.
The address canonicalization prompt is rarely a standalone call. In production, it sits inside a pipeline that feeds raw address strings from source systems—CRM records, shipping labels, OCR output, or user-submitted forms—and expects normalized, validated payloads that downstream systems can consume without crashing. The harness wraps the model call in pre-processing, post-processing, validation, and escalation logic. The goal is not just a well-formatted address but a trustworthy one: every field that enters your master data store should have a known confidence level and a clear provenance trail.
Start by defining a strict output schema and validating it before any record reaches a database. Use a JSON Schema validator or a library like Pydantic to enforce that canonical_address contains required fields (street_number, street_name, city, state_province, postal_code, country_code), that confidence_scores is present for each component, and that normalization_notes is a non-empty array when the model changed the input. If validation fails, do not silently drop the record. Log the raw input, the malformed output, and the validation error, then route to a repair queue. A common failure mode is the model returning a well-structured address that violates the postal format for the claimed country—for example, a US ZIP+4 pattern applied to a UK postcode. Add a country-specific format validator as a second pass: regex checks for postal codes, state/province abbreviation lookups, and city-postal code consistency checks against a reference dataset.
Confidence thresholds should drive routing, not just annotation. When the model's overall_confidence falls below a configurable threshold (start with 0.85 and tune based on your error tolerance), route the record to a human review queue rather than inserting it directly. For partial addresses—missing street numbers, ambiguous city names, or PO Box-only inputs—the model should still produce its best guess, but the harness must flag these for review. Implement a retry strategy for transient failures: if the model call times out or returns unparseable output, retry once with the same prompt. If the retry also fails, log the failure and escalate. Do not retry more than twice; at that point, the input is likely adversarial or fundamentally uncanonicalizable, and repeated retries waste tokens and latency budget.
Model choice matters for this workload. Address canonicalization requires geographic knowledge and pattern recognition more than creative reasoning. Smaller, faster models (Claude Haiku, GPT-4o-mini, or fine-tuned open-weight models) often perform well here and reduce cost per record. If you are processing high volumes—millions of addresses—consider batching multiple addresses into a single prompt with a JSON array output to amortize prompt overhead, but keep batches small (5–10 addresses) to avoid the model confusing records. Log every call: input address, output canonical form, confidence scores, model version, prompt version, timestamp, and latency. This audit trail is essential for debugging normalization drift when the model provider updates their serving infrastructure or when your prompt changes.
Finally, treat the canonicalization prompt as one step in a larger data quality workflow. After canonicalization, run deduplication against your existing address master to merge near-duplicates. Use the canonical_address fields as matching keys, but also fuzzy-match on the original input to catch cases where the model normalized two variants of the same address differently. If your downstream system is a shipping API, validate the canonicalized address against the carrier's address verification endpoint before accepting it as ground truth. The prompt is the engine; the harness is the steering, brakes, and dashboard. Ship neither without the other.
Expected Output Contract
Defines the exact shape of the canonicalized address record. Use this contract to validate the model's output before ingestion into downstream logistics or master data systems.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
canonical_address | string | Must be a single-line formatted string following the country-specific postal template defined in [COUNTRY_RULES]. Must not contain raw input fragments. | |
address_components | object | Must contain sub-keys for street_number, street_name, unit, city, state_province, postal_code, and country. Each sub-key must be a string or null. | |
address_components.street_number | string | null | Must be a numeric or alphanumeric identifier. If missing in [RAW_ADDRESS], value must be null, not an empty string or 'N/A'. | |
address_components.postal_code | string | null | Must match the regex pattern defined in [COUNTRY_RULES]. If missing or unparseable, set to null and increment missing_required_fields count. | |
confidence_score | number | Must be a float between 0.0 and 1.0. Score must reflect the proportion of expected components successfully parsed and validated. | |
normalization_notes | array of strings | If present, each string must describe a specific transformation applied (e.g., 'Expanded ST to STREET'). Must be an empty array if no transformations were needed. | |
missing_required_fields | array of strings | Must list the keys of any address_components that are required by [COUNTRY_RULES] but resolved to null. Must be an empty array if all required fields are present. | |
input_validation_passed | boolean | Must be true if the [RAW_ADDRESS] was parseable; false if the input was empty, nonsensical, or not an address. If false, canonical_address must be null. |
Common Failure Modes
Address canonicalization fails in predictable ways. These are the most common production failure modes and how to guard against them before they corrupt your downstream systems.
Partial Address Hallucination
What to watch: The model fills in missing components (postal code, city, street suffix) with plausible but incorrect values when the input is incomplete. A partial address like '123 Main, Springfield' gets an invented ZIP code that passes format validation but is geographically wrong. Guardrail: Require explicit null for missing components and add a completeness_score field. Run extracted postal codes against a reference lookup. Flag any record where the model filled more than one missing field for human review.
Country Rule Confusion
What to watch: The model applies one country's address format rules to another country's data—treating a UK postcode as a US ZIP, misplacing the postal code position in Japanese addresses, or forcing state/province fields where they don't exist. This is most common when the country is not explicitly stated in the input. Guardrail: Always pass an explicit [TARGET_COUNTRY] parameter. Include country-specific format examples in the prompt. Validate output structure against a country-specific schema before ingestion, not after.
PO Box and Rural Route Misclassification
What to watch: PO Boxes, rural routes, highway contract routes, and military APO/FPO addresses get parsed as standard street addresses. 'PO Box 1234' becomes a street number '1234' on 'PO Box Street.' Rural route identifiers get dropped entirely. Guardrail: Add explicit detection rules for PO Box, RR, HC, and APO/FPO patterns in the prompt. Output a dedicated address_type enum field. Run a post-extraction classifier that flags any record where the address type doesn't match the parsed structure.
Component-Level Confidence Collapse
What to watch: The model returns a single high confidence score for the entire address when one component (like the street number or postal code) is actually low-confidence or guessed. Downstream systems trust the whole record. Guardrail: Require per-component confidence scores in the output schema. Set component-level thresholds: if postal_code_confidence < 0.8, route the record to a verification queue even if the overall address confidence is high.
Abbreviation Expansion Drift
What to watch: The model inconsistently expands or contracts address abbreviations—sometimes 'St' becomes 'Street,' sometimes it stays 'St,' sometimes 'Saint' gets abbreviated to 'St' when it shouldn't. This breaks deduplication and matching downstream. Guardrail: Specify an explicit abbreviation policy in the prompt: either always expand to full form or always use a defined abbreviation standard like USPS Publication 28. Add a post-processing normalization step that enforces the chosen policy regardless of what the model returned.
Multi-Language Address Corruption
What to watch: When the input address contains mixed scripts or non-Latin characters, the model transliterates inconsistently, drops diacritics, or reorders components to fit an assumed Western format. Japanese addresses get reversed, German umlauts get stripped, and Arabic script gets garbled. Guardrail: Pass a [SCRIPT_HANDLING] parameter specifying whether to preserve original script, transliterate, or return both. Include a script_warnings field in the output. Test with addresses in at least three non-Latin scripts before shipping.
Evaluation Rubric
Use this rubric to test the quality of the canonicalized address output before integrating it into a production pipeline. Each criterion targets a specific failure mode common in address normalization.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Component Completeness | All non-null input components are mapped to a corresponding canonical field in the output. | An input component (e.g., street name) is present in [RAW_ADDRESS] but missing from the canonical output without a null reason. | Parse the output JSON and assert that for every populated field in the input extraction schema, the corresponding canonical field is not null. |
Country-Specific Format Adherence | The canonical address structure strictly follows the postal format rules for the resolved [COUNTRY_CODE]. | A US address is formatted with the postal code before the city, or a UK address is missing the post town. | Validate the output against a regex or structural template for the detected country. Use a library like |
PO Box and Rural Route Handling | PO Boxes and rural route identifiers are placed in the | A PO Box number is placed in a | Assert that if |
Abbreviation Normalization | Common abbreviations (e.g., 'St', 'Ave', 'FL') are expanded to their full canonical form as defined in the [ABBREVIATION_MAP]. | The output contains 'St' instead of 'Street' or 'NY' instead of 'New York' when the map requires full names. | Run a direct string match check on the output fields against a list of forbidden abbreviations. Flag any matches as failures. |
Confidence Score Integrity | A | The confidence score is 1.0 despite a missing house number, or the score is a string instead of a float. | Assert that |
Partial Address Null Handling | Missing components are explicitly set to | A missing | Iterate through all nullable fields in the output schema and assert that their value is either a valid string or the literal JSON |
Input Pass-Through Fidelity | The canonical output does not alter or 'correct' a correctly spelled street name or city that was already valid in the [RAW_ADDRESS]. | The street name 'Main Street' is changed to 'Maine Street' in the canonical output. | Compute the Levenshtein distance between the input and output for the |
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 canonicalization prompt but relax the strict schema enforcement. Use a simple list of address components instead of a nested JSON schema. Focus on getting the normalization logic right for a single country before expanding.
codeNormalize the following address to USPS standard format: [RAW_ADDRESS] Return as: - Full address line - City - State (2-letter code) - ZIP (5-digit) - Country
Watch for
- PO Box and rural route formats being flattened incorrectly
- ZIP+4 truncation without noting the loss
- Missing confidence indicators for ambiguous components
- No handling for non-US addresses slipping through

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