Inferensys

Prompt

UUID and Surrogate Key Generation Prompt Template

A practical prompt playbook for generating valid, unique UUIDs and surrogate keys within structured AI outputs, designed for data engineers building reliable ingestion pipelines.
Data scientist building training data pipeline on laptop, data preprocessing visible, technical workspace.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for generating identifiers in AI workflows.

This prompt is for data engineers and platform builders who need an AI model to generate valid, unique identifiers as part of a structured output. The core job-to-be-done is producing UUIDs or surrogate keys that can be immediately ingested by a database, a data warehouse, or an API without post-processing. You should use this prompt when your workflow requires the model to create new records, assign primary keys, or link entities within a generated batch, and where identifier collisions or format violations would break downstream systems.

The ideal user is integrating AI into a data pipeline, an ETL process, or a record-generation service. Required context includes the target identifier format (e.g., UUIDv4, UUIDv7, a custom prefixed key like cust_), the scope of uniqueness (within a single response, across a batch, or globally), and any constraints like sortability or time-ordering. Do not use this prompt when you need cryptographically secure random identifiers for security-critical systems; the model is not a source of entropy. Do not use it when the identifier must be derived from existing data, such as a content hash or a deterministic namespace UUID, unless you explicitly provide the hashing or namespace logic as a tool.

Before implementing, define your validation contract. A successful output must pass format checks (e.g., regex for UUID structure), uniqueness checks across the generated set, and collision checks against any existing identifiers you provide in the context. For high-stakes ingestion, always add a post-generation validation layer in your application code that rejects the entire batch if any identifier fails, rather than attempting to repair individual keys. Start with a small, representative batch of 10-50 records to tune the prompt's format adherence before scaling to larger generation jobs.

PRACTICAL GUARDRAILS

Use Case Fit

Where this prompt works for identifier generation and where it fails.

01

Good Fit: Batch Record Generation

Use when: you need to generate a set of records for database insertion, test fixtures, or data migration where every record requires a unique, non-colliding primary key. Guardrail: always validate uniqueness across the entire generated batch with a post-generation script, not just within the prompt's claimed guarantees.

02

Good Fit: Idempotent API Payloads

Use when: an API client needs to submit a payload with a client-generated ID for idempotency. The prompt can produce a valid UUID that the client can reuse for retry safety. Guardrail: ensure the prompt is seeded with a deterministic input (e.g., hash of payload) to regenerate the same UUID for the same logical request.

03

Bad Fit: Cryptographic or Security Tokens

Avoid when: the identifier is used for session tokens, password reset links, API keys, or any security-sensitive context. LLM-generated UUIDs are not cryptographically random. Guardrail: use a secure random number generator in application code (e.g., secrets.token_urlsafe or uuid4 via os.urandom) for any security boundary.

04

Bad Fit: Distributed System Coordination

Avoid when: the identifier must be globally unique across multiple services, regions, or time without a central coordinator. LLMs have no distributed consensus mechanism. Guardrail: use UUIDv7, ULID, or Snowflake-style IDs generated by application code to ensure time-ordering and true uniqueness across nodes.

05

Required Input: Format Specification

Risk: the model defaults to UUIDv4 hex format, but your database may expect UUIDv7, ULID, or a custom surrogate key pattern. Guardrail: always provide an explicit format specification in the prompt, including version, encoding (hex, base64, raw), and any prefix or checksum requirements.

06

Operational Risk: Collision in Large Batches

Risk: for batches exceeding a few thousand records, the probability of an accidental collision increases, and the model has no mechanism to guarantee cross-response uniqueness. Guardrail: implement a post-generation uniqueness check and a retry loop that regenerates only colliding IDs, or use a deterministic derivation from a monotonic counter instead of relying on the model for uniqueness at scale.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt with square-bracket placeholders for generating validated UUIDs and surrogate keys in structured outputs.

This prompt template is designed to be copied directly into your prompt management system, IDE, or orchestration layer. It instructs the model to generate identifiers that conform to a specified format, guarantee uniqueness within the current batch, and avoid predictable collision patterns. Every placeholder is enclosed in square brackets and must be replaced with concrete values before the prompt is sent to the model. The template assumes you have already defined your target output schema, the number of records needed, and the identifier field name.

text
You are a data generation assistant that produces structured records with unique identifiers.

Generate [RECORD_COUNT] records as a JSON array. Each record must conform to the output schema below.

## Output Schema
[OUTPUT_SCHEMA]

## Identifier Field Requirements
The field named [ID_FIELD_NAME] must contain a unique identifier for each record with the following constraints:
- Format: [IDENTIFIER_FORMAT] (choose one: UUIDv4, UUIDv7, or SURROGATE_KEY)
- If SURROGATE_KEY: use the prefix [SURROGATE_PREFIX] followed by a zero-padded integer starting at [STARTING_VALUE] and incrementing by [INCREMENT_STEP]. Example: [SURROGATE_PREFIX]00001
- If UUIDv4: generate a random RFC 9562-compliant UUID.
- If UUIDv7: generate a time-ordered RFC 9562-compliant UUID with millisecond precision.
- Uniqueness: No two records in this batch may share the same identifier value.
- Collision avoidance: Do not use sequential or predictable values for UUID formats.

## Additional Constraints
[CONSTRAINTS]

## Examples of Valid Identifiers
[EXAMPLES]

## Risk Level
[RISK_LEVEL]

Return ONLY the JSON array. Do not include explanations, markdown fences, or additional text.

To adapt this template, replace each placeholder with your specific requirements. For [OUTPUT_SCHEMA], provide a complete JSON Schema or a natural-language description of the record structure. For [IDENTIFIER_FORMAT], select exactly one option and remove the others to prevent the model from choosing an unintended format. The [CONSTRAINTS] placeholder should include any additional field-level rules, such as non-nullable fields, enum restrictions, or cross-field validation logic. The [EXAMPLES] placeholder is critical for surrogate key formats: show the exact pattern the model should follow, including prefix, padding width, and starting value. Set [RISK_LEVEL] to LOW for non-critical data generation, MEDIUM when identifiers will be stored in a database, or HIGH when duplicates could cause data corruption, financial errors, or patient safety issues. For high-risk scenarios, always add a post-generation uniqueness check in your application layer rather than relying solely on the model's adherence to the prompt.

IMPLEMENTATION TABLE

Prompt Variables

Inputs the prompt needs to generate identifiers reliably. Each placeholder must be populated before the prompt is sent. Validation notes describe how to verify the input is well-formed before execution.

PlaceholderPurposeExampleValidation Notes

[IDENTIFIER_TYPE]

Specifies the kind of identifier to generate

UUIDv4

Must be one of: UUIDv4, UUIDv7, ULID, KSUID, SNOWFLAKE, or CUID2. Reject unknown values before prompt assembly.

[BATCH_SIZE]

Number of unique identifiers to generate in one response

100

Must be a positive integer between 1 and 10000. Parse as int and check range before sending. Larger batches increase collision risk in time-based schemes.

[OUTPUT_SCHEMA]

JSON Schema describing the output record shape that contains the identifier field

{"type": "object", "properties": {"id": {"type": "string"}}, "required": ["id"]}

Must parse as valid JSON Schema. Validate with a schema validator before prompt assembly. The schema must include exactly one field designated as the identifier field.

[IDENTIFIER_FIELD_NAME]

The JSON key where the generated identifier will be placed

record_id

Must be a non-empty string matching the identifier field in [OUTPUT_SCHEMA]. Check that this field exists in the schema and is typed as string.

[UNIQUENESS_SCOPE]

Defines the boundary within which identifiers must be unique

within_batch

Must be one of: within_batch, across_requests, or global. If across_requests, additional collision detection logic is required in the application layer.

[SORT_ORDER]

Whether generated identifiers should be sortable by creation time

Must be boolean true or false. When true, prefer UUIDv7, ULID, or KSUID. When false, UUIDv4 is acceptable. Validate type before sending.

[TIMESTAMP_PRECISION]

Precision level for time-based identifier components

millisecond

Must be one of: second, millisecond, microsecond, or nanosecond. Only applicable when [IDENTIFIER_TYPE] is UUIDv7, ULID, or KSUID. Ignored for UUIDv4 and CUID2.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the UUID and surrogate key generation prompt into an application or data pipeline with validation, retries, and idempotency checks.

Integrating a prompt that generates identifiers requires treating the model output as a data source with a schema contract, not as free text. The prompt template expects a [RECORD_COUNT] and an optional [KEY_FORMAT] (such as UUIDv4, UUIDv7, or a custom surrogate pattern). Your application layer must supply these parameters, parse the structured response, and validate every generated key before ingestion. The implementation harness wraps the prompt in a thin service that handles input validation, output parsing, retry logic, and uniqueness enforcement—turning an LLM call into a reliable key-generation utility.

Start by defining a validation function that checks each returned identifier against the requested format. For UUIDv4, verify the regex pattern ^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$. For UUIDv7, confirm the timestamp-ordered first segment and the version nibble. For custom surrogate keys, validate against the provided pattern. Reject any output that contains duplicates within the batch, null values, or keys that collide with existing records in your target database. Log every validation failure with the raw model output and the specific rejection reason—this data is essential for tuning the prompt or adjusting the model choice over time.

Wrap the model call in a retry loop with a hard limit (typically 3 attempts). On each retry, increment a retry counter in the prompt's [CONSTRAINTS] field and explicitly instruct the model that previous outputs contained duplicates or format violations. If the model consistently fails to produce valid keys, fall back to a deterministic UUID library (such as Python's uuid module or PostgreSQL's gen_random_uuid()) rather than blocking the pipeline. This hybrid approach keeps latency predictable: use the LLM when you need distributed, coordination-free key generation with custom formatting, but never let it become a single point of failure for record ingestion.

For production observability, instrument every call with the number of keys requested, the number of valid keys returned, the retry count, and the latency per attempt. Emit structured log events with a trace ID that ties the key-generation step to the upstream record-creation request. If your system uses a message queue or event stream, attach the generated keys to the original message envelope so downstream consumers can verify provenance. Avoid generating keys inside a database transaction that also inserts the records—instead, pre-generate keys, validate them, and then use an idempotent insert with a uniqueness constraint to catch any edge-case collisions.

When choosing a model for this task, prefer smaller, faster models that follow format instructions reliably. The task is mechanical, not semantic. Test across your candidate models with a golden dataset of expected key formats and batch sizes. Measure not just validity but also throughput and tail latency. If you observe format drift after model updates, add a regression test suite that runs the prompt against known inputs and asserts 100% format compliance and zero duplicates. Finally, never expose the raw prompt output to end users without validation—treat it as untrusted input until it passes your schema checks.

IMPLEMENTATION TABLE

Expected Output Contract

Field-level contract for UUID and surrogate key generation. Use this table to validate that every generated identifier meets format, uniqueness, and collision-prevention requirements before ingestion.

Field or ElementType or FormatRequiredValidation Rule

primary_key

string (UUID v4 format)

Must match regex ^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$. Parse with uuid library and assert version == 4.

surrogate_key

string (custom format per [KEY_FORMAT])

Must match the pattern defined in [KEY_FORMAT] (e.g., prefix-timestamp-random). Validate with provided regex. Reject if pattern mismatch.

generated_at

string (ISO 8601 UTC)

Must parse as valid ISO 8601 datetime with Z suffix. Must be within 5 seconds of server time at validation. Reject future or stale timestamps.

batch_id

string (UUID v4 format)

Shared across all records in a single generation batch. Must be identical for all rows in the response array. Validate cross-record consistency.

record_index

integer

Zero-based index within the batch. Must be sequential without gaps. Validate that indices form a complete 0..n-1 sequence for n records.

idempotency_token

string (SHA-256 hex)

If present, must be 64 lowercase hex characters. Generate from hash of [INPUT_CONTEXT] + batch_id + record_index. Validate deterministic reproduction on retry.

collision_check_hash

string (hex)

If [UNIQUENESS_CHECK] is true, include a hash of all generated primary_key values in the batch. Validate that no two records share the same primary_key within the batch.

source_identifier

string

If [SOURCE_SYSTEM] is provided, prepend as a namespace prefix to the surrogate_key. Validate that the prefix matches the provided value exactly, with no variation or omission.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first in identifier generation and how to guard against it.

01

Collision Within a Batch

What to watch: The model generates duplicate UUIDs or surrogate keys within a single output array, breaking uniqueness guarantees. This often happens when the model copies a pattern instead of generating fresh values. Guardrail: Add a post-generation uniqueness check that scans the output array for duplicate identifiers and rejects the entire batch if any collision is found. Instruct the model to treat each record independently.

02

Invalid UUID Format

What to watch: The model produces strings that look like UUIDs but violate RFC 4122, such as using the wrong version digit, non-hex characters, or incorrect hyphen positions. Guardrail: Validate every generated identifier against a strict UUID regex or a standard library parser. Reject non-conforming outputs and retry with explicit format instructions in the error feedback.

03

Deterministic Pattern Leakage

What to watch: The model generates keys that appear random but follow a predictable sequence (e.g., incrementing suffixes, repeated segments) because it overfits to few-shot examples. Guardrail: Include a randomness check in eval that verifies no two identifiers share long common prefixes or sequential patterns. Use a diverse set of example UUIDs in the prompt to break pattern mimicry.

04

Wrong Key Type for Context

What to watch: The model generates UUIDv4 when the schema requires UUIDv7 for time-sortable keys, or produces integer surrogates when a UUID string is expected. Guardrail: Explicitly declare the required UUID version or key format in the prompt constraints. Validate the version digit or key type against the schema before accepting the output.

05

Null or Missing Key Fields

What to watch: The model omits the identifier field entirely or sets it to null, especially for optional-seeming records at the end of a batch. Guardrail: Enforce required-field presence checks in the output validator. Reject any record where the key field is absent, null, or an empty string. Retry with a stricter instruction that every record must have a non-null identifier.

06

Cross-Record Key Contamination

What to watch: The model accidentally copies a key from one record to another when generating large batches, especially if records share similar content. Guardrail: Add a cross-record uniqueness assertion in the eval harness. If any two records share the same identifier, fail the batch and retry with an instruction to generate each key independently without referencing other records.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for testing UUID and surrogate key output quality before shipping. Use these checks to validate format compliance, uniqueness guarantees, and collision resistance in generated identifier batches.

CriterionPass StandardFailure SignalTest Method

Format Compliance

Every generated key matches the specified format (e.g., UUID v4, ULID, or custom [KEY_FORMAT])

Any key fails regex or format-specific parsing

Parse each key with a format-specific validator; reject any parse failure

Uniqueness Within Batch

All keys in a single generation batch are distinct with zero duplicates

Duplicate key detected in batch output

Hash all keys in the batch; assert hash set size equals batch count

Cross-Batch Collision Rate

No collisions across 10 independent batches of [BATCH_SIZE] keys each

Any key appears in more than one batch

Generate 10 batches; union all keys; assert total unique count equals 10 × [BATCH_SIZE]

Character Set Restriction

Keys contain only characters from the allowed set defined in [ALLOWED_CHARS]

Key contains character outside allowed set

Validate each key against [ALLOWED_CHARS] regex; reject any mismatch

Fixed Length Consistency

Every key has exactly [KEY_LENGTH] characters

Key length deviates from [KEY_LENGTH]

Measure string length of each key; assert all equal [KEY_LENGTH]

Null or Empty Key Absence

No key is null, empty string, or whitespace-only

Null or empty key present in output

Iterate all keys; assert each is non-null and length > 0 after trim

Schema Field Presence

Every output record includes the [KEY_FIELD_NAME] field with a non-null value

Record missing [KEY_FIELD_NAME] or field is null

Validate output against [OUTPUT_SCHEMA]; assert [KEY_FIELD_NAME] is required and populated

Deterministic Seed Isolation

When [SEED] is provided, keys are reproducible; when absent, keys are random

Same seed produces different keys across runs, or no-seed produces identical keys

Run generation twice with same [SEED]; assert identical output; run twice without seed; assert different output

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Add explicit format specification, uniqueness constraints within the batch, and a JSON Schema output contract. Include a post-generation validation step that checks RFC compliance and collision absence.

code
For each record in [INPUT_DATA], generate a [KEY_FORMAT] identifier.
Constraints:
- Version: [UUID_VERSION]
- Uniqueness: No two records may share the same identifier
- Output must conform to [OUTPUT_SCHEMA]

Watch for

  • Silent collisions when batch size exceeds model attention window
  • Timestamp-based UUIDs (v7) leaking generation order metadata
  • Missing validation hook before records enter downstream systems
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.