Inferensys

Prompt

URL Standardization and Repair Prompt Template

A practical prompt playbook for using the URL Standardization and Repair Prompt Template in production AI workflows to clean and normalize URLs from model outputs.
ML engineer managing model versions on laptop, version history visible, technical Git-like workflow.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the job-to-be-done, ideal user, required context, and limitations for the URL Standardization and Repair prompt.

This prompt is for data pipeline operators, integration engineers, and platform teams who need to clean, standardize, and repair URLs extracted from model-generated text. Model outputs often contain URLs with missing schemes, inconsistent trailing slashes, broken encoding, or domain-only fragments. This prompt normalizes these into a consistent, validatable format suitable for downstream ingestion into databases, analytics systems, or link checkers. Use this when you have a batch of URLs from an LLM and need them to conform to a predictable structure before storage or further processing. This is a post-generation repair step, not a URL extraction prompt.

The ideal user has a list of URL strings that passed an initial extraction step but failed a structural validation check. For example, a model might output example.com/page when your database expects https://example.com/page. Or it might produce https://example.com/page/ and https://example.com/page as two separate entries when they represent the same resource. This prompt handles scheme addition, trailing slash consistency, encoding fixes (e.g., decoding %20 to spaces or re-encoding malformed characters), and basic repair of broken URL structures. It does not verify whether a URL is reachable or whether the domain exists—that is a separate link-checking concern.

Do not use this prompt when you need to extract URLs from raw text. That is an extraction task requiring a different prompt design with different evaluation criteria. Do not use it when you need to resolve redirects, check HTTP status codes, or validate that a URL points to real content—those are runtime operations that belong in application code, not in a normalization prompt. Also avoid this prompt when your URLs contain authentication tokens, session parameters, or other sensitive query strings that should be stripped or redacted before sending to an external model. For high-volume pipelines, batch the URLs and add a post-processing validation step that rejects any output that does not parse as a valid URL according to your application's URL parser. This ensures the model's output is a repair, not a new source of corruption.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works and where it does not. Understand the operational boundaries before wiring it into a production pipeline.

01

Good Fit: Post-Generation Cleanup

Use when: You have a stream of URLs from an LLM that are semantically correct but structurally malformed (missing schemes, inconsistent trailing slashes, encoding artifacts). Guardrail: Always run a structural validator before repair to avoid normalizing already-valid URLs.

02

Bad Fit: Real-Time User Input

Avoid when: Users are typing URLs directly into a form field. Use deterministic client-side or server-side libraries instead. Guardrail: Reserve LLM-based repair for URLs extracted from unstructured text where heuristic parsers fail on edge cases like embedded punctuation or line breaks.

03

Required Input: Raw URL String

What to watch: The prompt needs the raw, unmodified URL string exactly as the model output it. Pre-processing can mask the failure pattern you're trying to repair. Guardrail: Pass the URL as a single string field with surrounding context stripped to avoid confusing the repair model with adjacent text.

04

Operational Risk: Over-Aggressive Path Stripping

What to watch: The repair model may incorrectly strip query parameters, fragments, or path segments it deems 'unnecessary,' breaking deep links. Guardrail: Add a constraint in the prompt to preserve all path components, query strings, and fragments unless they contain obvious encoding errors. Test against a golden set of parameterized URLs.

05

Operational Risk: Domain-Only Normalization

What to watch: The model may return only the base domain (e.g., example.com) when the input was a full URL, losing the specific page reference. Guardrail: Include an explicit instruction to preserve the full path unless the input itself is domain-only. Add an eval check comparing input path length to output path length.

06

Scale Consideration: Batch vs. Single Repair

What to watch: Repairing URLs one-at-a-time with an LLM is expensive and slow at scale. Guardrail: Batch multiple URLs into a single prompt with a JSON array output schema. Set a batch size limit (e.g., 20 URLs) and implement a fallback to a deterministic library if the LLM call fails or times out.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A copy-ready system prompt for normalizing and repairing URLs from model-generated text, with placeholders for your normalization policy and input data.

This prompt template is designed to be dropped directly into a single-turn repair task. It takes a list of URLs extracted from model outputs—often containing missing schemes, encoding artifacts, inconsistent trailing slashes, or domain-only fragments—and applies a configurable normalization policy to produce clean, consistent, and deduplicatable URL strings. The template separates the normalization rules from the input data so you can version your policy independently of the repair calls.

text
You are a URL standardization engine. Your task is to normalize and repair a list of URLs extracted from model-generated text. Apply the normalization policy below to each input URL. Return only the normalized URLs in the specified output format. Do not add commentary, explanations, or markdown formatting.

## NORMALIZATION POLICY
[POLICY]

## INPUT URLS
[INPUT_URLS]

## OUTPUT FORMAT
[OUTPUT_FORMAT]

## CONSTRAINTS
- If a URL is irreparably malformed or missing a recoverable domain, output [INVALID_PLACEHOLDER] instead of guessing.
- Do not invent paths, query parameters, or fragments that are not present in the input.
- Preserve the original URL's intent; only repair structural defects.
- Apply the normalization policy consistently across all inputs.

How to adapt this template: Replace [POLICY] with your organization's URL normalization rules—for example, enforcing HTTPS, lowercasing the hostname, removing default ports, sorting query parameters, stripping tracking parameters, and deciding whether trailing slashes should be added or removed. Replace [INPUT_URLS] with the list of URLs to repair, one per line or as a JSON array depending on your [OUTPUT_FORMAT] specification. Replace [OUTPUT_FORMAT] with a precise schema description, such as a JSON array of strings or one normalized URL per line. Replace [INVALID_PLACEHOLDER] with a sentinel value like null, "INVALID", or an empty string that your downstream parser can detect. For high-risk pipelines where URL integrity affects billing, security, or user safety, add a human review step before the normalized URLs are written to your system of record.

What to do next: Copy this template into your prompt management system or version-controlled prompt library. Define your normalization policy as a separate, testable artifact so you can evaluate policy changes without altering the repair prompt structure. Before deploying, run the prompt against a golden dataset of known-bad URLs and verify that the output format is parseable, the sentinel value appears for truly unrecoverable inputs, and the normalization rules are applied without over-aggressive stripping of legitimate path or query components.

IMPLEMENTATION TABLE

Prompt Variables

Validate these inputs before sending the prompt. Missing or malformed variables are the most common cause of silent normalization failures.

PlaceholderPurposeExampleValidation Notes

[RAW_URL]

The unnormalized URL string from model output or user input

Must be a non-empty string. Null or empty input should abort before prompt assembly. Check for leading/trailing whitespace and strip before validation.

[DEFAULT_SCHEME]

Fallback scheme when the URL has no protocol

https

Must be one of: http, https. Default to https. Reject ftp, file, or other schemes unless explicitly allowed by downstream system.

[TRAILING_SLASH_POLICY]

Whether to add, remove, or preserve trailing slashes on path-only URLs

remove

Must be one of: add, remove, preserve. Null defaults to preserve. Incorrect policy causes duplicate records in downstream systems.

[LOWERCASE_HOST]

Whether to force the hostname to lowercase

Must be true or false. Default true per RFC 3986. Set false only if downstream system is case-sensitive (rare).

[ENCODING_FIX_MODE]

How aggressively to repair percent-encoding errors

conservative

Must be one of: conservative, aggressive, none. Conservative fixes double-encoding only. Aggressive re-encodes all non-ASCII characters. None skips encoding repair.

[MAX_URL_LENGTH]

Maximum allowed URL length in characters before truncation is flagged

2048

Must be a positive integer. Default 2048. URLs exceeding this should be flagged rather than silently truncated. Set to null to disable length check.

[ALLOWED_TLDS]

List of valid top-level domains for domain plausibility checks

["com", "org", "net", "io", "gov"]

Must be an array of strings or null. Null skips TLD validation. Use for catching model-hallucinated domains with fake TLDs like .example or .test in production data.

[REPAIR_CONFIDENCE_THRESHOLD]

Minimum confidence score for automatic repair vs. flagging for human review

0.85

Must be a float between 0.0 and 1.0. Repairs below this threshold are flagged but still returned. Set to 1.0 to require human review for all repairs.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the URL standardization prompt into a production data pipeline with validation, retries, and observability.

The URL standardization prompt is designed to run as a post-generation repair step inside a data pipeline, not as a standalone interactive tool. The typical integration pattern places this prompt after a model generates text containing URLs and before those URLs enter a database, analytics system, or downstream API. The harness should accept a batch of candidate URL strings, invoke the prompt for each, validate the normalized output, and route failures to a dead-letter queue for manual review or secondary repair attempts.

Validation is the critical boundary. After the model returns a normalized URL, the harness must verify that the output is a syntactically valid URL (RFC 3986), that the scheme is present and matches an allowlist (e.g., https, http, mailto), and that the domain contains at least one dot. If the model returns a domain-only string without a scheme, the harness should prepend https:// as a safe default rather than rejecting the record. For high-risk pipelines where URLs drive financial transactions or authentication flows, add a human review gate for any URL where the model changed the domain, path, or query string beyond case normalization and trailing slash consistency.

Retry logic should be bounded. If the model returns malformed output (unparseable string, missing domain, or a refusal), retry once with the same prompt and a stronger constraint instruction appended: [CONSTRAINTS]: Return ONLY the normalized URL string. No explanation, no markdown, no surrounding text. If the second attempt also fails, log the original input, both outputs, the model version, and the timestamp to an observability store, then route the record to manual review. Do not retry more than twice—the cost of repeated failures outweighs the recovery rate for URL repair.

Model choice matters for this task. URL normalization is a deterministic, rule-heavy operation that does not benefit from creative reasoning. Use a fast, inexpensive model (e.g., GPT-4o-mini, Claude Haiku, or a fine-tuned small model) rather than a large frontier model. If processing high-volume streams, consider batching up to 20 URLs per request with a numbered list format and a strict output schema that maps input indices to normalized URLs. This reduces API overhead while keeping each URL's repair context independent.

Observability and drift detection should be built into the harness from day one. Log the input URL, the normalized output, the model version, and a boolean flag indicating whether the output differs from the input. Track the repair rate (percentage of URLs modified) and the rejection rate (percentage sent to manual review). A sudden spike in repair rate may indicate a change in the upstream model generating the URLs, while a spike in rejection rate may signal prompt drift or a model version regression. Wire these metrics into your existing monitoring dashboards alongside eval pass/fail rates from your regression test suite.

IMPLEMENTATION TABLE

Expected Output Contract

The JSON schema, field descriptions, and pass/fail conditions for the URL Standardization and Repair prompt. Use this table to validate the model's response before it enters downstream systems.

Field or ElementType or FormatRequiredValidation Rule

normalized_url

string (valid URL)

Must pass new URL() constructor. Scheme must be https unless input explicitly uses http. Trailing slash must be consistent with input path structure.

original_url

string

Must match the [INPUT_URL] exactly. Used for audit trail and diff comparison.

repairs_applied

array of strings

Each string must match an enum value: scheme_addition, www_removal, www_addition, trailing_slash_added, trailing_slash_removed, encoding_fix, domain_typo_correction, path_cleanup, fragment_removal, query_sorting, none.

confidence

number (0.0-1.0)

Must be between 0.0 and 1.0 inclusive. Values below 0.7 should trigger human review if [REQUIRE_HUMAN_REVIEW_ON_LOW_CONFIDENCE] is true.

is_reachable

boolean | null

If [PERFORM_REACHABILITY_CHECK] is true, must be true or false. If false or null, must be null. Do not hallucinate reachability.

warnings

array of strings

Each string must describe a specific risk: domain_typo_possible, encoding_ambiguous, path_truncation_risk, scheme_guess, ip_address_detected, localhost_detected. Empty array if no warnings.

canonical_domain

string

Must be lowercase, punycode-encoded if non-ASCII. Must not include scheme, path, query, or fragment. Must match the domain portion of normalized_url.

repair_log

array of objects

Each object must have fields: field (string, the URL component changed), from (string, original value), to (string, repaired value), reason (string, enum: encoding, convention, typo_correction, security, consistency).

PRACTICAL GUARDRAILS

Common Failure Modes

URL standardization prompts break in predictable ways. Here are the most common production failure modes and how to guard against them before they corrupt your data pipeline.

01

Over-Aggressive Path Stripping

What to watch: The model normalizes /blog/posts/123 to example.com by stripping the entire path, treating it as redundant. This destroys resource identifiers, API endpoints, and deep links. Guardrail: Add an explicit constraint in the prompt template: 'Preserve the full URL path unless it is a known index page (e.g., /index.html, /default.aspx).' Validate output URLs retain path segments when the input contained non-root paths.

02

Scheme Guessing on Protocol-Relative URLs

What to watch: The model receives //cdn.example.com/lib.js and guesses http:// instead of https://, or vice versa. This breaks secure contexts and creates mixed-content warnings. Guardrail: Instruct the model to default to https:// for protocol-relative URLs unless the domain is explicitly known to require http://. Add a post-processing rule that flags http:// outputs for review when the input was protocol-relative.

03

Encoding Double-Fix Corruption

What to watch: An already-encoded URL like https://example.com/search?q=hello%20world gets re-encoded to https://example.com/search?q=hello%2520world, breaking the query. The model treats %20 as literal text rather than an encoded space. Guardrail: Add a pre-check step that detects already-encoded URLs and passes them through unchanged. In the prompt, instruct: 'Do not re-encode already percent-encoded characters. Only encode raw special characters.'

04

Trailing Slash Inconsistency Across Domains

What to watch: The model applies a blanket trailing-slash policy (always add or always strip) without respecting domain-specific conventions. Some APIs require trailing slashes; some CDNs break with them. Guardrail: Include a domain-specific trailing-slash rule table in the prompt context. When the domain is unknown, preserve the input's trailing slash behavior rather than normalizing it. Log trailing-slash changes for audit.

05

Query Parameter Reordering That Breaks Caching

What to watch: The model alphabetizes query parameters for consistency, but the target system relies on parameter order for cache keys or signature validation. Reordering invalidates signed URLs or creates cache misses. Guardrail: Add a constraint: 'Preserve the original query parameter order unless the output schema explicitly requires canonical ordering.' For signed URLs, flag any parameter modification for human review.

06

Domain-Only Normalization Without Path Validation

What to watch: The model correctly normalizes the domain (lowercase, punycode) but silently drops or corrupts the path, fragment, or query string. The output is a valid URL but points to the wrong resource. Guardrail: Add a structural validation step that compares input and output URL components: scheme, host, port, path, query, fragment. Require exact path preservation unless the prompt explicitly authorizes path rewriting rules.

IMPLEMENTATION TABLE

Evaluation Rubric

Run these checks on a golden dataset of 50-100 malformed URLs to validate the URL Standardization and Repair prompt before shipping. Each criterion targets a known failure mode in production URL normalization pipelines.

CriterionPass StandardFailure SignalTest Method

Scheme Addition Accuracy

Missing scheme added as https:// for 100% of hostname-bearing URLs; no scheme added to non-URL strings

http:// added to URLs that should be https://; scheme prepended to email addresses or plain text

Compare output scheme against labeled ground truth for 50 scheme-missing inputs

Trailing Slash Consistency

Trailing slash present on root-path URLs (example.com/) and absent on path-bearing URLs (example.com/page) per configurable [TRAILING_SLASH_POLICY]

Inconsistent slash application within same batch; slash appended to query-string URLs; double slashes introduced

Regex check against expected slash pattern for 30 root-path and 30 path-bearing test cases

Encoding Repair Correctness

Percent-encoded characters decoded to readable form; double-encoding resolved; reserved characters in query strings preserved as encoded

Over-decoding breaks URL structure; under-decoding leaves %20 artifacts; query parameter delimiters decoded when they should remain encoded

Parse output with URL parser, compare decoded components against expected normalized form for 40 encoding-corrupted inputs

Domain Typos and TLD Correction

Common domain typos corrected (goggle.com to google.com, .cmo to .com); unknown domains left unchanged with confidence flag

False-positive correction of valid but uncommon domains; correction of intentional typosquatting domains used as test inputs

Check corrected domains against a reference allowlist of known-good corrections; count false positives on 20 typo and 20 valid-unusual domain pairs

Broken URL Repair Rate

At least 90% of recoverably broken URLs (missing dots, extra slashes, space-injected) produce a valid, parseable URL

Output is null or unparseable for a recoverable input; repair introduces a different broken URL; valid URL returned but points to wrong resource

Parse output with WHATWG URL parser; compare resolved hostname+path against expected repair target for 50 broken-URL test cases

Over-Aggressive Path Stripping

Paths retained when present in input; only truly empty or whitespace-only paths normalized to root

Valid path segments stripped from URLs with non-empty paths; query strings removed during normalization; fragment identifiers dropped without [PRESERVE_FRAGMENTS] flag

Compare output path+query+fragment against input for 30 path-bearing URLs; flag any case where non-empty path becomes empty

Domain-Only Normalization Restraint

Domain-only inputs (example.com) normalized to https://example.com/ without hallucinated paths, subdomains, or www prefix unless specified by [WWW_POLICY]

www. prepended to domains that don't use it; /index.html or other paths hallucinated; subdomains invented for bare domains

Check 25 domain-only inputs for added subdomains, hallucinated paths, or spurious www insertion

Batch Consistency

Same input URL produces identical output across multiple invocations within the same batch; no non-deterministic variation

Same malformed URL repaired differently across two runs; trailing slash policy applied inconsistently; encoding fixes vary between invocations

Run the same 20-input batch twice with temperature=0; diff outputs line-by-line; flag any non-identical pairs

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Add a strict output schema (JSON array with original_url, normalized_url, repair_actions[], warnings[]). Wrap the prompt in a retry loop: if output fails schema validation, send the validation error back as [REPAIR_CONTEXT]. Add structured logging with pipeline_run_id, batch_id, and per-URL timestamps. Use a lower temperature (0.1–0.2) for consistency.

code
For each URL in [URL_LIST], produce a JSON object:
{
  "original_url": string,
  "normalized_url": string | null,
  "repair_actions": ["scheme_added" | "trailing_slash_normalized" | "encoding_fixed" | "punycode_applied" | "www_normalized" | "fragment_removed" | "default_port_removed" | "unrepairable"],
  "warnings": [string],
  "confidence": 0.0-1.0
}

Rules:
- Add `https://` when scheme is missing unless evidence suggests `http://` or `ftp://`
- Normalize trailing slashes per [TRAILING_SLASH_POLICY]
- Decode safe characters, re-encode unsafe ones per RFC 3986
- Apply Punycode to non-ASCII domains
- Strip default ports (443 for https, 80 for http)
- Flag unrepairable URLs with confidence < 0.3

Watch for

  • Silent format drift across model version upgrades
  • Missing human review for unrepairable URLs that still get normalized
  • Encoding double-fix (model re-encodes already-encoded sequences)
  • Trailing slash policy inconsistency between runs
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.