This prompt is designed for identity resolution pipelines, social CRM integrators, and data engineering teams that need to extract social media handles from unstructured or semi-structured model outputs. The primary job is to take a messy text block—such as a bio, a scraped profile, or a free-text notes field—and return a clean, normalized list of platform-attributed handles. The prompt handles common normalization tasks: stripping @ prefixes, converting profile URLs to bare handles (e.g., https://twitter.com/username → username), and detecting the platform when it is implied but not explicitly stated. Use this when downstream systems require deduplicatable, platform-tagged identifiers for matching, enrichment, or analytics.
Prompt
Social Handle Extraction and Normalization Prompt Template

When to Use This Prompt
Define the extraction job, the expected input conditions, and the boundaries where this prompt should not be used.
The ideal input is a short-to-medium length text field (under 2,000 tokens) that contains one or more social media references. The prompt works best when the platform is either explicitly named, implied by domain (e.g., linkedin.com/in/...), or inferable from handle conventions. Do not use this prompt for bulk extraction from large document corpora without chunking; it is not designed for long-context retrieval. Do not use it as a real-time entity linker that must resolve handles against a live identity graph—this prompt normalizes what is present, it does not verify that a handle exists or belongs to a specific person. For verification, pair the output with a separate API lookup step. If the input contains deliberately obfuscated handles (e.g., user [at] domain), expect degraded performance and consider a pre-processing regex layer.
Before wiring this into a production pipeline, define your ambiguity tolerance. The prompt includes a platform disambiguation step, but when a handle could belong to multiple platforms (e.g., a common username without a domain hint), the model must either guess with a confidence flag or return the handle as platform: unknown. Decide which behavior your downstream system can tolerate. For high-stakes identity resolution where a wrong platform attribution causes a broken match, route ambiguous outputs to a human review queue. The eval harness described later in this playbook includes test cases for exactly these ambiguous scenarios. Start by running the prompt against a labeled dataset of 50–100 real-world examples from your own data before integrating it into an automated pipeline.
Use Case Fit
Where this prompt works and where it does not. Use these cards to decide if the Social Handle Extraction and Normalization Prompt Template is the right tool for your pipeline.
Good Fit: Unstructured Text Ingestion
Use when: You are processing free-text model outputs, chat transcripts, or scraped bios that contain social handles in inconsistent formats (e.g., @handle, https://x.com/handle, linkedin.com/in/name). Guardrail: The prompt expects a single block of text. If you have structured data, use a deterministic parser instead.
Bad Fit: Deterministic Extraction
Avoid when: You have a known, fixed set of URL patterns or a small, predictable input format. Guardrail: Regex and URL parsing libraries are cheaper, faster, and more reliable for simple @ stripping or domain extraction. Reserve this prompt for messy, ambiguous, or highly variable text.
Required Inputs
What you must provide: A raw text string containing potential social handles. Guardrail: The prompt cannot infer handles from names alone. If the input is just a person's name, the model will likely hallucinate a handle. Always provide text that explicitly contains the handle.
Operational Risk: Platform Ambiguity
What to watch: A handle like @johndoe could belong to X, Instagram, or TikTok. The model may guess the platform based on context, but this guess can be wrong. Guardrail: Always flag ambiguous platform attributions with a confidence score and route low-confidence results for human review or additional context gathering.
Operational Risk: URL-to-Handle Conversion Errors
What to watch: The model might strip too much from a URL (e.g., removing a required subdirectory) or too little (e.g., leaving query parameters). Guardrail: Implement a post-processing validation step that checks the normalized handle against a regex for each platform's allowed character set and length limits.
Operational Risk: Hallucinated Handles
What to watch: If the input text mentions a person but does not include their handle, the model may invent a plausible handle to satisfy the extraction request. Guardrail: Add a strict instruction to return a null or empty value for the handle field if no explicit handle is found in the source text. Validate this behavior in your eval harness.
Copy-Ready Prompt Template
A reusable prompt template for extracting and normalizing social media handles from unstructured text, with square-bracket placeholders for easy adaptation.
This prompt template is designed to extract social media handles from model-generated text, user-submitted content, or scraped data and normalize them into a consistent, application-ready format. It handles platform detection, @ prefix stripping, URL-to-handle conversion, and ambiguous platform attribution. Use this template as the core instruction block in your extraction pipeline, then wrap it with the validation, retry, and evaluation harness described in the implementation section.
textYou are a social handle extraction and normalization engine. Your job is to extract social media handles from the provided text and return them in a clean, structured format. ## INPUT [INPUT] ## PLATFORM CONTEXT (OPTIONAL) [CONTEXT] ## OUTPUT SCHEMA Return a JSON object with the following structure: { "handles": [ { "platform": "string (twitter, linkedin, github, instagram, youtube, tiktok, facebook, other)", "handle": "string (normalized, no @ prefix, no URL)", "original_text": "string (the exact text span the handle was extracted from)", "confidence": "high|medium|low", "is_ambiguous_platform": true|false, "alternative_platforms": ["string"] } ], "extraction_notes": ["string"] } ## NORMALIZATION RULES 1. Strip @ prefixes from all handles. 2. If the input contains a URL (e.g., https://twitter.com/username, https://linkedin.com/in/username), extract only the handle portion. 3. Convert handles to lowercase for case-insensitive platforms (Twitter, Instagram). Preserve case for case-sensitive platforms (GitHub). 4. Remove trailing slashes, query parameters, and fragments from URL-derived handles. 5. If a handle appears multiple times in the input, return it once with the highest-confidence extraction. 6. Do not invent handles. Only extract handles explicitly present in the input text. ## PLATFORM DETECTION RULES - If the input contains a platform-specific URL (twitter.com, linkedin.com/in, github.com, etc.), assign that platform. - If the handle appears with a platform label (e.g., "Twitter: @user", "GitHub: user"), use that label. - If platform is ambiguous, set is_ambiguous_platform to true and list alternative_platforms. - Use [CONTEXT] as a hint for platform disambiguation when provided. ## CONFIDENCE RULES - high: Platform is explicit from URL or label, and handle format matches platform conventions. - medium: Platform is inferred from handle format or context, but not explicit. - low: Handle extracted but platform is ambiguous with no strong signal. ## CONSTRAINTS [CONSTRAINTS] ## EXAMPLES [EXAMPLES] ## RISK LEVEL [RISK_LEVEL] Return ONLY the JSON object. No markdown fences, no commentary.
To adapt this template, replace the square-bracket placeholders with your specific requirements. [INPUT] should contain the raw text you want to extract handles from. [CONTEXT] is optional but valuable when you have prior knowledge about which platforms are likely (e.g., "this is a developer portfolio page, expect GitHub and LinkedIn"). [CONSTRAINTS] can include platform allowlists or blocklists (e.g., "only extract Twitter and LinkedIn handles"), maximum handle count, or domain-specific rules. [EXAMPLES] should include few-shot demonstrations covering edge cases like URL-embedded handles, handles with special characters, and ambiguous platform signals. [RISK_LEVEL] should be set to low, medium, or high to control whether the extraction pipeline requires human review for low-confidence results. For high-risk identity resolution workflows, always set RISK_LEVEL to high and route low-confidence extractions to a human review queue before they enter your CRM or CDP.
Before deploying this prompt, test it against a golden dataset that includes: handles embedded in narrative text, handles inside markdown links, handles with non-standard characters, multiple handles from different platforms in one input, and inputs with no handles at all. The most common failure mode is over-extraction—the model inventing handles from names or email addresses. Mitigate this by including negative examples in your few-shot demonstrations and by running the output through the hallucination detection harness described in the implementation section. If you are processing user-generated content at scale, also test for prompt injection attempts where malicious input tries to override the normalization rules.
Prompt Variables
Required and optional inputs for the Social Handle Extraction and Normalization prompt. Each placeholder must be populated before the prompt is sent to the model. Validation notes describe how to check that the input is fit for purpose.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[RAW_TEXT] | Unstructured text containing one or more social media handles, profile URLs, or @mentions to extract and normalize. | Follow us on Twitter @InferenceSys and LinkedIn: linkedin.com/company/inference-systems | Must be a non-empty string. Null or whitespace-only input should be rejected before prompt assembly. Maximum length should be enforced at the application layer to avoid token budget overruns. |
[PLATFORM_HINTS] | Optional list of platform names or domains the caller expects to find. Used to disambiguate handles when the platform is not explicit in the text. | ['Twitter', 'LinkedIn', 'GitHub'] | Must be a valid JSON array of strings or null. Each string should match a known platform key from the output schema enum. Unknown platform names should be logged and ignored rather than causing prompt failure. |
[OUTPUT_SCHEMA] | JSON Schema describing the expected output shape. The prompt uses this to enforce field presence, types, and enum values for platform attribution. | {"type": "object", "properties": {"handles": {"type": "array", "items": {"type": "object", "properties": {"raw": {"type": "string"}, "normalized": {"type": "string"}, "platform": {"type": "string", "enum": ["twitter", "linkedin", "github", "instagram", "youtube", "tiktok", "unknown"]}, "confidence": {"type": "number", "minimum": 0, "maximum": 1}}, "required": ["raw", "normalized", "platform", "confidence"]}}}} | Must be valid JSON Schema. Validate with a schema parser before injection. The enum list in platform must match the downstream system's accepted values. Schema version should be tracked for prompt compatibility. |
[CONFIDENCE_THRESHOLD] | Minimum confidence score for including an extracted handle in the output. Handles below this threshold are either dropped or flagged for human review. | 0.7 | Must be a float between 0.0 and 1.0. Values outside this range should be clamped or rejected. A threshold of 0.0 returns all extractions; 1.0 returns only certain matches. Default to 0.5 if not provided. |
[STRIP_AT_PREFIX] | Boolean flag controlling whether the @ symbol is stripped from normalized handles. Some downstream systems require the @, others reject it. | Must be a boolean. Default to true if not provided. Inconsistent stripping across pipeline stages causes duplicate records. Document the convention for your system of record. | |
[RESOLVE_URLS] | Boolean flag controlling whether profile URLs are resolved to their underlying handle. When true, 'twitter.com/InferenceSys' becomes '@InferenceSys'. When false, URLs are extracted as-is. | Must be a boolean. Default to true. When false, URL extraction should still parse the domain for platform attribution. URL resolution failures should be logged with the raw URL preserved. | |
[MAX_HANDLES] | Upper limit on the number of handles to extract from the input. Prevents unbounded output when processing large documents with many mentions. | 10 | Must be a positive integer. Default to 20 if not provided. The application layer should truncate or paginate results rather than silently dropping handles. Exceeding the limit should trigger a warning in the response metadata. |
Implementation Harness Notes
How to wire the social handle extraction prompt into a production application with validation, retries, and platform disambiguation.
This prompt is designed to sit inside a post-generation repair or normalization pipeline, not as a standalone user-facing feature. The typical integration point is after a model has produced unstructured or semi-structured text containing social handles—such as a contact enrichment step, a CRM import, or an identity resolution workflow. The harness receives the raw model output, injects it into the prompt template as [RAW_TEXT], and expects a structured JSON response with normalized handles, platform classifications, and confidence flags. Because the prompt handles both @-style mentions and URL-to-handle conversion, the harness should not pre-process or strip the input before sending it; let the prompt own the extraction logic.
Validation and retry logic is critical here. The harness must validate the returned JSON against a schema that enforces: handles as an array of objects with required fields handle (string, no @ prefix), platform (enum of supported platforms), confidence (0-1 float), and optional original_text and normalization_notes. If validation fails, implement a single retry with the validation error message appended to [CONSTRAINTS] as 'Previous output failed validation: [error]. Correct the output.' Do not retry more than once for the same input—escalate to a human review queue instead. For ambiguous platform attribution where confidence is below 0.7, the harness should route the record to a review queue rather than silently accepting the model's best guess. This is especially important for handles that could belong to multiple platforms (e.g., a short alphanumeric string that exists on both Twitter and GitHub).
Model choice and latency considerations matter for batch versus real-time use. For batch normalization of CRM records, a slower but more accurate model (GPT-4o, Claude 3.5 Sonnet) is appropriate, and you can process records in chunks of 50-100 with a 30-second timeout per chunk. For real-time identity resolution where latency must stay under 2 seconds, use a faster model (GPT-4o-mini, Claude 3.5 Haiku) and process handles one at a time. Logging should capture: the raw input, the normalized output, validation pass/fail, retry count, platform confidence distribution, and any records routed to human review. This log becomes your eval dataset for measuring extraction accuracy over time. Tool use is not required for this prompt—the extraction and normalization logic is self-contained. However, if you have an internal platform validation API (e.g., checking whether a handle actually exists on a platform), wire it as a post-processing step after the prompt returns, not as a tool the model calls during extraction.
What to avoid: Do not use this prompt for real-time user-facing features where a hallucinated handle could cause a bad user experience (e.g., auto-populating a profile field). Always add a human review step for high-confidence actions like sending messages or merging contact records. Do not skip the confidence threshold check—ambiguous platform attribution is the most common failure mode, and silently misattributing a handle to the wrong platform creates data quality debt that compounds across downstream systems. If you're processing handles from user-generated content where the model might extract non-handle text as handles (e.g., email addresses, hashtags), add a post-extraction filter that rejects extracted strings matching known non-handle patterns before they enter your canonicalization pipeline.
Expected Output Contract
Defines the normalized social handle object returned by the prompt. Use this contract to validate outputs before ingestion into identity resolution pipelines or CRM systems.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
handle | string | Must match pattern ^[A-Za-z0-9._]{1,30}$. Must not contain @, URL schemes, or path segments. Leading/trailing whitespace stripped. | |
platform | string | Must be one of the allowed enum values: twitter, linkedin, github, instagram, facebook, youtube, tiktok, other. Case-sensitive lowercase. | |
original_input | string | Must be the exact substring extracted from [INPUT_TEXT] that was interpreted as a social handle. Used for audit trail. | |
confidence | number | Float between 0.0 and 1.0 inclusive. Values below [CONFIDENCE_THRESHOLD] should trigger human review. Null not allowed. | |
normalization_applied | array | Array of strings from fixed set: url_stripped, at_prefix_removed, case_normalized, whitespace_trimmed, trailing_path_removed, query_params_removed. Empty array if no normalization was needed. | |
is_ambiguous_platform | boolean | True when the same handle pattern exists on multiple platforms and platform attribution relied on context clues rather than explicit URL domain. False otherwise. | |
disambiguated_from | string | If is_ambiguous_platform is true, this field must contain the alternative platform considered. Use null when is_ambiguous_platform is false. | |
extraction_span | object | Contains start_char and end_char integers indicating position in [INPUT_TEXT]. Use null when input was a raw handle string without surrounding context. |
Common Failure Modes
Social handle extraction is deceptively brittle. Models confuse platform attribution, mishandle edge-case username formats, and hallucinate handles from display names. These are the most common production failures and how to prevent them.
Platform Misattribution
What to watch: The model extracts a valid handle but assigns it to the wrong platform (e.g., labeling a Twitter handle as LinkedIn). This breaks downstream routing and enrichment. Guardrail: Provide a closed list of supported platforms in the prompt. Require the model to output platform_confidence and flag any handle that matches patterns for multiple platforms for review.
Display Name Treated as Handle
What to watch: The model extracts a person's display name (e.g., 'John Doe') and formats it as a handle (@JohnDoe) without evidence the handle exists. This is the most common hallucination pattern. Guardrail: Add an explicit instruction: 'Only extract handles that appear verbatim in the text. Never infer a handle from a display name.' Validate output handles against the source text with string-matching.
URL-to-Handle Conversion Errors
What to watch: The model misparses profile URLs, extracting subdirectories as handles (e.g., linkedin.com/in/jane-doe-123 becomes jane-doe-123 instead of janedoe). Guardrail: Provide platform-specific URL parsing rules in the prompt. Add a post-processing validator that checks extracted handles against known URL patterns and flags mismatches.
Inconsistent @ Prefix Handling
What to watch: The model sometimes strips the @ prefix and sometimes preserves it, producing duplicate records in downstream systems. Guardrail: Explicitly specify the output format: 'Always output the handle without the @ prefix in the handle field. Include a separate display_handle field with the @ if needed.' Validate output consistency before ingestion.
Multi-Platform Handle Confusion
What to watch: When a text mentions multiple platforms, the model conflates handles across them or assigns the same handle to every platform. Guardrail: Require the model to extract handles per-platform independently. Add a deduplication check: if the same handle appears for multiple platforms, flag it for manual review unless the source explicitly confirms cross-platform presence.
Handle Format Violations
What to watch: The model outputs handles that violate platform username rules—too long, invalid characters, or reserved words. These fail silently when pushed to APIs. Guardrail: Embed platform-specific format constraints in the prompt (character limits, allowed characters). Add a post-extraction validator that checks each handle against platform regex patterns and rejects or flags violations.
Evaluation Rubric
Use this rubric to test the quality of the social handle extraction and normalization prompt before shipping. Each criterion targets a specific failure mode common in platform attribution, @-prefix stripping, and URL-to-handle conversion.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Handle Normalization | Output handle is stripped of @ prefix, URL path, and trailing punctuation for all supported platforms | Handle retains @, http://, or trailing slash characters | Parse output handle field; assert no leading @ or protocol prefix; regex check for valid handle characters only |
Platform Detection Accuracy | Platform field matches the source URL domain or explicit context clue with >95% accuracy on a labeled test set | Platform misattributed (e.g., twitter.com URL labeled as LinkedIn) or null when platform is clearly indicated | Run 50 labeled examples with known platforms; measure precision/recall; flag any null platform when URL domain is present |
URL-to-Handle Conversion | Full profile URL is correctly converted to bare handle without query parameters or fragments | Handle contains query string (?), fragment (#), or trailing path segments beyond the username | Test with 20 varied profile URL formats per platform; assert extracted handle matches known ground truth |
Ambiguous Platform Attribution | When platform cannot be determined, confidence_score is <0.7 and platform field is null with a non-empty ambiguity_reason | High confidence score assigned to a guess or platform field populated with a likely-but-unverified platform | Feed inputs with no platform signals; assert confidence_score <0.7, platform is null, ambiguity_reason is populated |
Multi-Handle Extraction | All distinct handles are extracted as separate array elements with correct per-handle platform attribution | Multiple handles concatenated into one string, or only the first handle extracted when input contains several | Input text containing 3+ handles across platforms; assert output array length matches; verify each handle-platform pair |
Invalid Input Handling | Empty string or non-social-text input returns empty handles array, null platform, and confidence_score of 0.0 without throwing errors | Model hallucinates a handle from noise, returns non-zero confidence, or produces malformed JSON on empty input | Send empty string, random prose with no handles, and pure emoji; assert handles array is empty and confidence_score is 0.0 |
Schema Compliance | Output is valid JSON matching the expected schema with all required fields present and correctly typed | Missing required fields, wrong types (e.g., string instead of array), or extra hallucinated fields not in the output contract | Validate output against JSON Schema; assert no missing required fields; assert no additional properties unless explicitly allowed |
Confidence Score Calibration | Confidence_score correlates with extraction difficulty: high for clean URLs, medium for @mentions in prose, low for ambiguous text | Confidence_score is always 1.0 regardless of input quality, or scores are inconsistent across similar-difficulty examples | Run stratified test set (clean URLs, noisy text, ambiguous); assert monotonic relationship between input clarity and confidence_score |
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 extraction prompt and a simple JSON schema. Use a single model call without retries. Accept [INPUT_TEXT] and return {"handles": [{"platform": "...", "handle": "...", "confidence": "..."}]}. Skip URL-to-handle conversion initially—just extract @mentions and explicit platform:handle pairs.
Prompt snippet
codeExtract social media handles from [INPUT_TEXT]. Return JSON with handles array containing platform, handle, and confidence fields. Strip @ prefixes. If platform is ambiguous, mark as "unknown".
Watch for
- Platform misattribution when multiple platforms share handle formats
- Missing handles embedded in URLs (e.g., twitter.com/username)
- Over-extraction of non-handle @mentions like email addresses or code annotations
- Confidence scores that are uniformly high without real discrimination

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