This prompt is a post-generation repair step for API developers and data pipeline engineers who receive prose or narrative text from a model when they expected structured JSON. Instead of discarding the response or writing brittle regex, use this prompt to extract typed objects, normalize enums, and flag low-confidence fields. It belongs in a repair loop that activates after primary structured output generation fails validation—not as your first attempt at getting structured data.
Prompt
Narrative Response to Typed Record Prompt Template

When to Use This Prompt
Defines the repair-loop context for converting narrative model responses into typed application payloads.
The ideal user has already attempted schema-first prompting or function calling and received a correct but unstructured answer. For example, a model might return 'The user's name is Jane Doe, ID 44521, status active' instead of {"name": "Jane Doe", "id": 44521, "status": "active"}. This prompt converts that narrative into a valid application payload with field-level confidence flags, enum normalization (e.g., 'active' → ACTIVE), and type coercion. It requires you to supply the expected output schema, the raw narrative text, and any domain-specific enum mappings or constraints.
Do not use this prompt as your primary structured output strategy. Prefer schema-first prompting, function calling with strict JSON mode, or tool-use APIs for initial generation. Reserve this prompt for repair loops where validation has already failed, the model's answer is semantically correct, and the cost of re-generation is higher than the cost of extraction. In high-risk domains such as finance, healthcare, or legal, always route low-confidence extractions to human review rather than silently accepting repaired output. Wire this prompt into your application with a validation gate, a retry budget, and structured logging that tracks how often repair was needed—high repair rates signal that your primary generation strategy needs improvement.
Use Case Fit
Where the Narrative Response to Typed Record prompt works well and where it introduces unacceptable risk. Use these cards to decide if this repair pattern fits your pipeline before you integrate it.
Good Fit: Post-Generation Repair Layer
Use when: The primary structured output generation failed and you received prose, markdown, or semi-structured text instead of JSON. This prompt acts as a second-pass repair, not the first attempt at structure. Guardrail: Always attempt native structured output (function calling, JSON mode) first. Only invoke this repair prompt after validation confirms the primary output is malformed.
Bad Fit: Real-Time User-Facing Chat
Avoid when: Latency budgets are under 500ms or the user is waiting for a streaming response. This repair pattern adds a full second inference round. Guardrail: For chat surfaces, return a graceful fallback message and process the repair asynchronously. Never block the user on a repair loop.
Required Inputs
What you need: The original narrative response, the expected output schema with field types and descriptions, and any enum or normalization rules. Guardrail: Without a schema, the repair prompt becomes guesswork. Always pass a concrete schema—preferably the same one used for initial validation—so the repair targets the exact contract downstream systems expect.
Operational Risk: Hallucinated Field Values
What to watch: When the narrative is vague, the model may invent values to satisfy required fields rather than marking them as null or missing. Guardrail: Add explicit instructions to output null or a missing sentinel for any field not supported by the source text. Validate post-repair that every non-null value has a traceable origin in the input.
Operational Risk: Silent Type Coercion Errors
What to watch: The model may coerce types incorrectly—converting a string like 'twelve' to the integer 12, or normalizing an enum value to a close-but-wrong match. Guardrail: Run the repaired output through the same type validator used for primary outputs. Flag any field where the type changed during repair for human review, especially for financial, legal, or identity fields.
Cost and Latency Trade-Off
What to watch: Adding a repair pass doubles inference cost and latency for every malformed response. If 20% of primary outputs fail validation, this pattern adds significant overhead. Guardrail: Track repair invocation rate as a production metric. If repair rate exceeds 10%, invest in improving the primary prompt or fine-tuning rather than relying on the repair layer as a permanent fix.
Copy-Ready Prompt Template
A paste-ready template for converting narrative model responses into strictly typed records with validation flags.
This prompt template is designed for the repair step in your pipeline—when a model returns prose, markdown, or a semi-structured blob instead of the JSON object your application expects. It forces the model to extract, normalize, and type every field against a schema you define, and to flag any value it cannot confidently resolve. Use this when a primary structured-output generation attempt has failed and you need a reliable fallback that produces a machine-readable payload.
textYou are a strict data extraction engine. Your only job is to convert the provided narrative text into a single, valid JSON object that matches the output schema exactly. ## INPUT NARRATIVE [INPUT] ## OUTPUT SCHEMA You must produce a JSON object with exactly these fields. Do not add, omit, or rename any field. [OUTPUT_SCHEMA] ## EXTRACTION RULES 1. For each field in the schema, locate the corresponding value in the narrative. If the value is present, extract it and coerce it to the correct type. 2. If a value is ambiguous, choose the most likely interpretation and set a `confidence` flag for that field to `"low"`. 3. If a value is entirely missing from the narrative, set the field to `null` and set its `confidence` flag to `"absent"`. 4. Normalize all enums to the exact values listed in the schema. If the narrative uses a synonym, map it to the canonical enum value and set `confidence` to `"medium"`. 5. Normalize all dates to ISO 8601 format (YYYY-MM-DD). If only a partial date is available, use the earliest possible date in the implied range and set `confidence` to `"low"`. 6. Do not invent, infer, or hallucinate any value not supported by the narrative text. ## CONSTRAINTS [CONSTRAINTS] ## OUTPUT FORMAT Return ONLY a valid JSON object. Do not wrap it in markdown code fences. Do not include any explanatory text before or after the JSON. The JSON object must have this structure: { "record": { ... }, "field_confidence": { "field_name": "high" | "medium" | "low" | "absent" } }
To adapt this template, replace [INPUT] with the raw narrative text your model produced. Replace [OUTPUT_SCHEMA] with a JSON Schema fragment or a plain-text description of each field, its type, and its allowed enum values. Use [CONSTRAINTS] to add domain-specific rules—for example, 'amount must be a positive number with two decimal places' or 'status must be one of: active, pending, closed.' After the prompt runs, validate the output against your schema in application code before accepting it. If the field_confidence map shows any absent or low flags for required fields, route the record for human review or log it for later inspection.
Prompt Variables
Inputs required for the Narrative Response to Typed Record prompt. Each placeholder must be populated before the prompt is assembled and sent. Validation notes describe how to programmatically verify the input before execution.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[NARRATIVE_TEXT] | The free-text or markdown model response that failed structured output generation | The customer John Doe (john@example.com) reported a critical outage at 3:45 PM EST on the payment processing service. | Check string length > 0; reject null or empty input; log character count for token budget tracking |
[TARGET_SCHEMA] | JSON Schema definition describing the expected output record structure with field names, types, and constraints | {"type":"object","properties":{"name":{"type":"string"},"priority":{"type":"string","enum":["low","medium","high","critical"]}},"required":["name","priority"]} | Validate as parseable JSON Schema; confirm required fields are declared; reject schemas with circular references |
[FIELD_DESCRIPTIONS] | Natural language descriptions of each target field to guide extraction and normalization | name: Full name of the reporting user. priority: Incident severity level. Must be one of low, medium, high, or critical. | Check that every field in TARGET_SCHEMA has a corresponding description; flag missing descriptions before prompt assembly |
[ENUM_MAPPINGS] | Mapping of common free-text values to normalized enum values for each constrained field | {"priority": {"urgent": "critical", "p1": "critical", "minor": "low", "not urgent": "low"}} | Validate as parseable JSON object; confirm keys match field names from TARGET_SCHEMA; warn on unmapped enum values in schema |
[CONFIDENCE_THRESHOLD] | Minimum confidence score (0.0-1.0) required for each extracted field to be accepted without flagging | 0.7 | Check value is a float between 0.0 and 1.0; reject values outside range; default to 0.5 if not specified |
[NULL_HANDLING_RULES] | Instructions for how to handle missing or unextractable fields in the narrative | Set missing optional fields to null. Set missing required fields to null and set confidence to 0.0. Do not hallucinate values. | Check that rules cover both optional and required field behavior; reject rules that instruct hallucination; log for audit trail |
[OUTPUT_FORMAT] | Target output format specification, typically JSON with confidence flags per field | JSON object with fields matching TARGET_SCHEMA plus a _confidence object mapping each field to a 0.0-1.0 score | Validate that output format includes confidence reporting; confirm format is parseable by downstream consumers; reject format-only outputs without confidence |
Implementation Harness Notes
Wire this prompt into a post-generation validation pipeline to convert narrative model responses into typed records with automated repair and observability.
The Narrative Response to Typed Record prompt is a repair tool, not a primary generation prompt. It should be invoked only when your primary model fails to produce valid structured output and returns prose, markdown, or semi-structured text instead. The harness described here assumes you have already attempted structured generation (e.g., JSON mode, function calling, or strict schema instructions) and received a non-conforming response. Do not use this prompt as your first attempt at structured output—it is a recovery mechanism for production pipelines where retrying the primary model is too costly or has already failed.
Wire this prompt into a post-generation validation pipeline. Call the primary model, validate its output against your expected schema, and on failure, invoke this repair prompt with the raw response as [NARRATIVE_INPUT]. Parse the repair output as JSON, validate field types and required field presence, and check the _confidence flags. If any required field has _confidence below 0.7, route the record for human review. Log every repair invocation with the original output, the repaired record, and the confidence scores for observability. Set a maximum of one repair attempt per record to avoid infinite loops. For high-throughput pipelines, batch narratives and process asynchronously.
Model choice matters for repair reliability. Use a model with strong instruction-following and JSON output capabilities—GPT-4o, Claude 3.5 Sonnet, or Gemini 1.5 Pro are appropriate. Avoid smaller or older models that may hallucinate fields not present in the narrative or fail to respect the output schema. If your pipeline processes sensitive data, ensure the repair model runs in the same trust boundary as your primary model and that narratives do not contain PII that would violate data residency requirements. The repair prompt itself includes confidence flags, but you should also implement independent validation: check that extracted values appear in or are reasonably inferred from the source narrative, verify enum values match your allowed set, and confirm numeric fields parse correctly.
Observability is critical because repair is a fallback path that masks upstream failures. Log the following for every repair invocation: the original model output that triggered repair, the full repaired JSON record, per-field confidence scores, and whether the record passed or was routed to human review. Use structured logging so you can query repair rates by endpoint, model version, or schema. If repair rates exceed 5% of requests, investigate your primary prompt's structured output instructions or consider switching to a model with native structured output support. High repair rates indicate a systemic problem, not a normal operational condition.
For human review routing, build a simple queue or flagging mechanism. Records with low-confidence required fields should be surfaced with the original narrative, the repaired record, and the specific fields that failed the confidence threshold. Reviewers should be able to accept, correct, or reject the repair. Track reviewer corrections to improve your schema descriptions, field definitions, and few-shot examples in the primary prompt. Over time, patterns in human corrections will reveal where your extraction logic is weakest—use this data to refine both your primary generation prompt and your repair prompt's instructions.
Expected Output Contract
Defines the shape, types, and validation rules for the typed record produced by the repair prompt. Use this contract to build downstream parsers, database inserts, or API validation middleware.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
[RECORD_ID] | string (UUID v4) | Must parse as valid UUID v4. If missing, generate a new one and set [CONFIDENCE] to 'low'. | |
[EXTRACTED_FIELDS] | object | Must be a valid JSON object. Top-level keys must match the [TARGET_SCHEMA] exactly. No extra keys allowed. | |
[EXTRACTED_FIELDS].[FIELD_NAME] | per [TARGET_SCHEMA] | per [TARGET_SCHEMA] | Type must match the schema definition. If coercion fails, set value to null and append the field name to [REPAIR_LOG]. |
[ENUM_FIELDS] | array of strings | Each string must be a member of the allowed enum set defined in [TARGET_SCHEMA]. Non-matching values must be mapped to the closest match or set to null with a log entry. | |
[CONFIDENCE] | string (enum: 'high', 'medium', 'low') | Must be one of the three allowed values. Set to 'low' if any required field is null or any type coercion was performed. | |
[REPAIR_LOG] | array of strings | Must be a valid JSON array. Each entry must describe a specific repair action taken (e.g., 'Coerced field [FIELD_NAME] from string to number'). If no repairs were needed, use a single entry: 'No repairs performed.' | |
[SOURCE_EVIDENCE] | array of objects | Each object must have 'field' (string) and 'quote' (string) keys. 'quote' must be a verbatim substring from [INPUT_NARRATIVE]. Required only when [REQUIRE_CITATIONS] is true. |
Common Failure Modes
When converting narrative responses to typed records, these failures surface first in production. Each card pairs a common breakage pattern with a concrete guardrail you can implement before shipping.
Field Hallucination Under Ambiguity
What to watch: The model invents values for required fields when the source text is silent—fabricated dates, guessed enums, or placeholder names that look plausible but originate from the model rather than the input. This is most dangerous for fields like priority, status, or amount where a wrong value triggers downstream action. Guardrail: Require explicit null or MISSING tokens for absent fields in the output schema. Add a confidence field per extracted value and a post-extraction validator that flags any required field with confidence below threshold for human review.
Enum Drift and Category Invention
What to watch: The model produces category values outside your allowed enum—severity: "pretty bad" instead of severity: "high", or invents new statuses like pending_review when your system only accepts open, in_progress, closed. This breaks downstream database constraints and routing logic. Guardrail: Include the exact allowed enum values in the prompt template as a constraint block. Add a post-extraction enum validator that maps near-matches (fuzzy string matching) to canonical values and rejects unmappable outputs with a retry instruction containing the valid options.
Nested Structure Collapse
What to watch: The model flattens nested objects into top-level fields or converts arrays of objects into a single concatenated string. For example, line_items becomes line_items: "item1 $10, item2 $20" instead of an array of {name, price} objects. This silently passes JSON validation but breaks any code expecting traversable structures. Guardrail: Include a structural assertion in your eval harness that checks typeof or array length for every nested field. Add a repair step that detects stringified arrays and re-extracts them with an explicit schema reminder before accepting the output.
Temporal Format Inconsistency
What to watch: Dates arrive as "next Tuesday", "2024-03-15", "March 15th", or Unix timestamps within the same output. Timestamps mix timezones or drop UTC offsets silently. This breaks sorting, filtering, and scheduled actions downstream. Guardrail: Specify a single canonical format in the prompt (ISO 8601 with timezone). Add a post-extraction temporal normalizer that parses multiple formats, converts to the canonical form, and flags any value that fails parsing. For relative dates, require the model to output a temporal_grounding field explaining how it resolved the reference.
Source-Text Contamination in Output
What to watch: The model copies raw source text into structured fields instead of extracting the value—customer_name: "As mentioned in the email from John Smith regarding..." rather than customer_name: "John Smith". This contaminates database fields with narrative cruft and breaks exact-match lookups. Guardrail: Add an output constraint requiring each field to contain only the extracted value, not surrounding context. Implement a field-length validator that flags any value exceeding expected bounds (a name field shouldn't be 200 characters). Use a second-pass trim prompt for flagged fields.
Multi-Entity Confusion and Merging
What to watch: When the source text mentions multiple entities (multiple people, dates, or amounts), the model merges them into a single record or cross-contaminates fields—assigning Person A's email to Person B's record. This is especially dangerous in CRM, legal, or healthcare contexts where entity resolution errors create compliance risks. Guardrail: Design the prompt to extract one record per entity with explicit entity disambiguation instructions. Add a deduplication and cross-contamination check in the eval harness that verifies unique identifiers don't appear in multiple records unless expected. For high-stakes domains, require human review when multiple entities are detected.
Evaluation Rubric
Use this rubric to test the quality of typed records extracted from narrative model responses before shipping the prompt to production. Each criterion targets a common failure mode in unstructured-to-structured conversion.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Field Completeness | All required fields in [OUTPUT_SCHEMA] are present and non-null for every record | Missing required fields or null values where non-nullable fields are expected | Schema validation pass against [OUTPUT_SCHEMA] with required field check; count nulls per field across test set |
Type Correctness | Every field value matches its declared type in [OUTPUT_SCHEMA] (string, number, boolean, array, object) | String where number expected; boolean as string 'true'; array fields containing single string instead of array | JSON Schema validation with strict type checking; run typeof assertions on extracted values |
Enum Normalization | All enum-constrained fields contain only values from [ENUM_VALUES] list, normalized to canonical form | Variant spellings, synonyms, or invented categories not in approved enum set | Exact string match against allowed enum values; fuzzy match detection for near-miss variants |
Source Grounding | Every extracted value can be traced to a specific span in [INPUT_NARRATIVE]; no invented data | Values present in output but absent from source text; fabricated dates, amounts, or names | Manual spot-check on 20% of records; automated substring search for extracted values in source text |
Confidence Flag Accuracy | Fields with [CONFIDENCE_THRESHOLD] below minimum are correctly flagged as low-confidence | High-confidence flag on clearly ambiguous extraction; low-confidence flag on unambiguous source match | Compare confidence flags against human judgment on 50-record sample; measure false-positive and false-negative rate |
Array Cardinality | Array fields contain correct number of elements matching source evidence; no dropped or duplicated items | Three line items in source but only two extracted; single item wrapped in array correctly but duplicates appear | Count array elements per record; compare against expected counts from ground-truth annotations |
Null Handling | Optional fields are null when source provides no evidence; required fields never null | Empty string instead of null for missing optional fields; null in required field when source has clear evidence | Check null vs empty string distinction; verify null only appears in optional fields per [OUTPUT_SCHEMA] |
Record Boundary Integrity | Each extracted record represents exactly one entity from [INPUT_NARRATIVE]; no split or merged records | Single entity split across two records; two distinct entities merged into one record with mixed fields | Count extracted records vs expected entity count; check for duplicate identifiers or overlapping field values across records |
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
Use the base prompt with a single example of the desired output schema. Accept JSON or markdown-wrapped JSON. Add a post-processing step that strips markdown fences before parsing.
Prompt modification
codeIf the input contains a narrative description of a [RECORD_TYPE], extract the fields below and return ONLY valid JSON. If you cannot determine a field value, use null. [INPUT]: [NARRATIVE_TEXT] [OUTPUT_SCHEMA]: [JSON_SCHEMA]
Watch for
- Model wrapping JSON in ```json fences
- Missing null handling for absent fields
- Enum values that don't match the schema exactly
- Overly creative field inference when evidence is thin

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