Inferensys

Prompt

Free Text to CSV Record Repair Prompt Template

A practical prompt playbook for using Free Text to CSV Record Repair Prompt Template in production AI workflows.
Operations team reviewing AI workflow automation on laptop, workflow builder visible, casual office setup.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, the reader, and the operational constraints for the Free Text to CSV Record Repair prompt.

This prompt is for integration engineers and data pipeline operators who receive narrative or semi-structured text from a model when a structured CSV output was expected. The primary job-to-be-done is to convert a messy, free-text model response into a clean, delimited, and consistently ordered CSV record that can be ingested by downstream systems without manual cleanup. The ideal user is someone building a production data extraction pipeline who needs a reliable repair step after a primary structured-output generation attempt has failed or produced an unparseable result.

Use this prompt when the model's output contains the correct data but in the wrong shape—for example, a paragraph describing a transaction instead of a comma-separated row, or a markdown list of fields instead of a quoted CSV line. The prompt is designed to enforce consistent column ordering, proper quoting of fields containing commas or newlines, and escaping of double-quote characters. It is not suitable for repairing outputs where the underlying data is missing, hallucinated, or factually incorrect; for those cases, pair this with a factuality or hallucination-removal prompt from the Output Repair pillar. Do not use this prompt when the model has already produced valid CSV that merely needs schema validation—use a schema-mismatch repair prompt instead.

Before wiring this into an application, define the exact column schema you require and provide it as part of the [OUTPUT_SCHEMA] placeholder. The prompt works best when the expected columns are explicitly listed with their data types and a brief description, so the model can map narrative fields to the correct columns. For high-stakes pipelines involving financial, legal, or healthcare data, always add a human review step after repair and log both the original and repaired outputs for auditability. The next section provides the copy-ready template you can adapt and test against your own failure cases.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Free Text to CSV Record Repair prompt works and where it introduces risk. Use these cards to decide if this prompt is the right tool before wiring it into a production pipeline.

01

Good Fit: Narrative-to-Row Recovery

Use when: a model returned prose, bullet points, or markdown instead of structured CSV, and you need to recover delimited records for a downstream ingestion pipeline. Guardrail: always validate column count, delimiter consistency, and quote escaping before inserting into a database.

02

Bad Fit: High-Volume Streaming Pipelines

Avoid when: you are processing thousands of records per second where repair latency and cost per token make a repair prompt more expensive than discarding and re-requesting structured output. Guardrail: use this prompt as a fallback in a retry queue, not as the primary path for high-throughput structured generation.

03

Required Input: Column Schema Definition

What to watch: without an explicit column list and expected data types, the model will invent columns, reorder fields, or omit critical data. Guardrail: always pass a strict [COLUMN_SCHEMA] with field names, order, and type hints. Validate output columns match exactly before accepting the result.

04

Operational Risk: Delimiter Collision

What to watch: free-text input often contains commas, pipes, or tabs that collide with your chosen CSV delimiter, producing misaligned columns downstream. Guardrail: implement a post-repair harness check that counts delimiters per row against the expected column count, and reject or re-quote rows that fail the check.

05

Operational Risk: Embedded Newlines in Fields

What to watch: narrative text frequently contains line breaks that break CSV row boundaries when not properly quoted. Guardrail: instruct the prompt to always wrap fields containing newlines in double quotes, and add a validator that detects unquoted newlines before accepting the output.

06

Bad Fit: Numeric Precision Recovery

Avoid when: the source text contains financial figures, measurements, or identifiers where rounding or format changes would corrupt meaning. Guardrail: for precision-sensitive fields, route to a type-specific normalization prompt instead. This prompt repairs structure, not semantic value accuracy.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for converting free-text model responses into clean, delimited CSV records with consistent column ordering and proper escaping.

This prompt template is designed for integration engineers who need to repair model outputs that failed to produce structured CSV data directly. When a model returns a narrative response, markdown table, or semi-structured text instead of a clean CSV row, this prompt converts that raw output into a properly delimited record with quoted fields, escaped special characters, and consistent column ordering. The template uses square-bracket placeholders that you replace with your specific schema, input text, and output constraints before sending it to the model.

text
You are a data normalization assistant. Your task is to convert the provided free-text model response into a single, valid CSV record.

## INPUT TEXT
[RAW_MODEL_OUTPUT]

## TARGET SCHEMA
You must produce a CSV row with exactly these columns, in this order:
[COLUMN_NAMES]

## RULES
1. Extract values from the input text for each column. If a value is not present, use an empty string.
2. Enclose every field value in double quotes.
3. Escape any double quotes within field values by doubling them ("" -> """").
4. Join fields with a comma delimiter. Do not add spaces around commas.
5. Output ONLY the CSV row. Do not include headers, markdown fences, explanations, or any other text.
6. If the input contains multiple potential records, extract only the first complete record.
7. Normalize [NORMALIZATION_RULES] as specified.

## OUTPUT FORMAT EXAMPLE
Given columns ["Name", "Role", "Start Date"], a correct output would look like:
"Jane Doe","Senior Engineer","2024-01-15"

## CONSTRAINTS
[ADDITIONAL_CONSTRAINTS]

## RISK LEVEL
[RISK_LEVEL]

Produce the CSV row now.

To adapt this template, replace [RAW_MODEL_OUTPUT] with the free-text response you need to repair. Set [COLUMN_NAMES] to a comma-separated list of your target column headers in the exact order required by your downstream CSV parser. Use [NORMALIZATION_RULES] to specify any domain-specific transformations, such as date format standardization (YYYY-MM-DD), phone number canonicalization (+1-555-0100), or enum value mapping ('admin' -> 'Administrator'). The [ADDITIONAL_CONSTRAINTS] placeholder lets you add field-specific rules like numeric range checks or required-field enforcement. Set [RISK_LEVEL] to low, medium, or high to control how aggressively the model should handle ambiguous or missing values—high-risk scenarios should trigger empty fields rather than guesses. After copying the template, test it against at least five representative inputs, including edge cases with missing fields, embedded commas, and double-quote characters, before wiring it into your production pipeline.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the Free Text to CSV Record Repair prompt. 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

[FREE_TEXT_INPUT]

The raw narrative or unstructured text that contains the records to be converted into CSV rows

Customer John Doe (ID: 4821) purchased 3 widgets at $12.50 each on 2024-03-15. Shipping to 123 Main St, Springfield.

Check that input is non-empty string with minimum 10 characters. Reject null or whitespace-only inputs before prompt assembly.

[EXPECTED_COLUMNS]

Ordered list of column names that define the CSV header and field extraction targets

customer_name, customer_id, product, quantity, unit_price, total, date, shipping_address

Validate that column list is non-empty array of unique strings. Each column name must be alphanumeric with underscores only. Reject duplicate column names.

[DELIMITER]

The character used to separate fields in the output CSV

,

Must be a single character. Common values: comma, tab, pipe. Validate that delimiter does not appear unescaped in any expected column name.

[QUOTE_CHAR]

The character used to wrap fields containing delimiters, newlines, or special characters

"

Must be a single character distinct from delimiter. Default to double-quote. Validate that quote char is not present in unquoted field values.

[RECORD_SEPARATOR]

The character or sequence used to separate individual records in the free text input

\n\n

Must be a non-empty string. Common values: double newline, single newline, semicolon. Validate that separator reliably splits input into distinct record blocks.

[NULL_REPRESENTATION]

The string to use when a field cannot be extracted from the input text

NULL

Must be a string that does not conflict with valid field values. Common values: empty string, NULL, N/A. Validate that null representation is distinct from all expected valid field values.

[MAX_RECORDS]

Upper bound on the number of CSV rows to produce, preventing runaway generation

500

Must be a positive integer. Default to 500 for safety. Validate that value is between 1 and 10000. Reject zero or negative values.

[ESCAPE_RULES]

Specification for how to handle characters that conflict with delimiter or quote char inside field values

double-quote-escaping

Must be one of: double-quote-escaping, backslash-escaping, or strip-conflicts. Validate against allowed enum values. Default to double-quote-escaping for RFC 4180 compliance.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the Free Text to CSV Record Repair prompt into a production application with validation, retries, and safe ingestion.

The Free Text to CSV Record Repair prompt is designed to sit inside a post-generation repair loop, not as the primary structured output generator. Wire this prompt after your initial model call returns narrative text or markdown instead of valid CSV. The harness should catch the malformed output, extract the raw text, inject it into the [RAW_TEXT] placeholder along with the expected [COLUMN_HEADERS] and any [FIELD_CONSTRAINTS], and call the repair model. This is a recovery path, so treat it as a fallback with its own timeout, cost budget, and failure mode.

Validation is mandatory before accepting the repaired output. After the repair model returns a CSV string, run it through a deterministic parser that checks: (1) the number of columns matches the expected header count, (2) every row has the same number of fields after quote-aware splitting, (3) no unescaped delimiter characters exist inside unquoted fields, and (4) required columns contain non-empty values. If validation fails, you have three options: retry the repair prompt once with the validation error message appended to [RAW_TEXT] as context, fall back to a simpler model with a stricter prompt, or escalate the record to a human review queue. Do not silently ingest broken CSV into downstream systems—corrupted delimiters will shift columns and poison databases.

Model choice matters for this task. Smaller, faster models often struggle with consistent quote escaping and delimiter discipline, especially when the raw text contains commas, quotes, or newlines inside field values. Prefer a mid-tier or higher model with strong instruction-following for the repair step. If latency is critical, use a fast model for the initial generation and reserve a more capable model for the repair path. Log every repair attempt with the original raw text, the repaired CSV, validation results, and the model version used. This trace data is essential for debugging systemic failures—if a particular input pattern consistently fails repair, you may need to adjust the upstream prompt or add a preprocessing step before the repair call.

Delimiter conflicts are the most common production failure. If your raw text contains the same character you're using as the CSV delimiter (e.g., commas in address fields), the repair model must quote those fields correctly. Your harness should detect this risk by scanning [RAW_TEXT] for the target delimiter character before calling the repair prompt. If the text is delimiter-heavy, consider using a less common delimiter like the pipe character (|) or tab, and specify this explicitly in the [FIELD_CONSTRAINTS] section of the prompt. For high-risk pipelines where data integrity is non-negotiable, add a post-repair reconciliation step: count the number of records in the raw text (if known) and verify the CSV row count matches. Mismatched counts indicate the model dropped or merged records and should trigger escalation.

Wire this into your application as a recoverable error handler, not a silent fixer. Wrap the repair call in a try-catch block with explicit logging, a maximum of two retries, and a dead-letter queue for records that fail all repair attempts. If you're processing a batch, isolate failed records so one bad repair doesn't block the entire pipeline. For regulated or financial data, always require human review on repaired records before they enter the system of record—the repair prompt is a recovery tool, not a guarantee of correctness. Monitor the repair rate as a key health metric: a rising repair rate signals that your primary structured output prompt needs attention, and you should invest in fixing the root cause rather than relying indefinitely on the repair path.

IMPLEMENTATION TABLE

Expected Output Contract

Defines the exact CSV record structure, field types, and validation rules that the repair prompt must produce. Use this contract to build downstream parsers and validation harnesses.

Field or ElementType or FormatRequiredValidation Rule

CSV Header Row

String (comma-separated)

Must be present as first line; column count must match [EXPECTED_COLUMNS] count; column names must match [EXPECTED_COLUMNS] exactly (case-sensitive)

Data Row Count

Integer

Must equal 1 unless [INPUT] contains multiple records; each logical record in [INPUT] must produce exactly one data row

Field Quoting

Double-quoted strings

conditional

Fields containing commas, double quotes, or line breaks must be wrapped in double quotes; embedded double quotes must be escaped as two double quotes

[COLUMN_NAME] Value

Per [COLUMN_TYPES] mapping

conditional

Must match declared type in [COLUMN_TYPES]; null allowed only if column marked optional; empty string converted to null unless column disallows null

Delimiter Consistency

Comma character

All rows must use exactly the same delimiter; no mixed delimiters within output; trailing delimiter on last field prohibited

Line Ending

LF or CRLF

All rows must use consistent line endings; no mixed LF/CRLF within output; no blank lines between header and data rows

Escape Character Handling

Backslash or double-quote escaping

No unescaped special characters in unquoted fields; backslash escapes must be consistent if used; no bare newlines inside fields

Encoding

UTF-8

Output must be valid UTF-8; no BOM unless [INCLUDE_BOM] is true; no mojibake or replacement characters from encoding errors

PRACTICAL GUARDRAILS

Common Failure Modes

When converting free text to CSV, these are the most common production failures and how to prevent them before they corrupt downstream pipelines.

01

Delimiter Collision in Unquoted Fields

What to watch: The model outputs a comma inside a field without wrapping it in quotes, splitting one record into two malformed rows. This happens most often with addresses, descriptions, or names containing commas. Guardrail: Require quoted fields in the prompt template and add a post-processing validator that counts fields per row against the expected column count, flagging mismatches for repair.

02

Missing or Extra Columns on Subset of Rows

What to watch: The model produces most rows with the correct number of columns but drops or adds a field on a few rows, often due to optional data or hallucinated additions. Guardrail: Validate column count consistency across all rows before ingestion. If variance is detected, route the entire batch to a repair retry with explicit column schema reinforcement rather than patching individual rows.

03

Unescaped Quotes Breaking Field Boundaries

What to watch: A field contains double quotes that are not escaped with a second double quote, causing the CSV parser to treat the quote as a field terminator and corrupting all subsequent fields in that row. Guardrail: Add an escape-character normalization step that scans for lone double quotes inside quoted fields and escapes them before parsing. Include a pre-ingestion lint check that rejects files with unbalanced quotes.

04

Header-to-Data Misalignment After Repair

What to watch: The repair prompt reorders columns or renames headers without updating the data rows, producing valid CSV that maps values to the wrong fields downstream. Guardrail: Freeze the header row as a constant in the prompt template and instruct the model to preserve exact column ordering. Validate that the output header matches the expected header exactly before accepting the repair.

05

Newline Characters Inside Quoted Fields

What to watch: Multi-line text fields contain raw newlines that break row boundaries when the CSV is read line-by-line by streaming parsers or log processors. Guardrail: Normalize all newlines within quoted fields to a safe placeholder during repair, or ensure the output uses standard CSV multi-line field quoting that the target parser supports. Test with a streaming parser before production.

06

Encoding Artifacts from Model Output

What to watch: The model introduces smart quotes, em-dashes, non-breaking spaces, or other Unicode characters that look correct but break strict CSV parsers or downstream ETL tools expecting ASCII. Guardrail: Add a character normalization pass that replaces common Unicode punctuation with ASCII equivalents and strips invisible control characters. Validate encoding as UTF-8 without BOM before ingestion.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the Free Text to CSV Record Repair prompt before deploying it into a production pipeline. Each criterion targets a specific failure mode common in narrative-to-CSV conversion.

CriterionPass StandardFailure SignalTest Method

Column Count Consistency

Every output row has exactly the same number of columns as the header row

Row has fewer or more delimited fields than the header; misaligned columns in downstream parsers

Parse output with a CSV library and assert that len(row) == len(header) for every row

Delimiter Conflict Avoidance

No unescaped delimiter characters appear inside quoted field values

Field value splits incorrectly when a comma, tab, or pipe exists inside an unquoted field

Scan output for the delimiter character outside of quoted field boundaries; assert zero occurrences

Quote Character Escaping

All double-quote characters inside quoted fields are escaped by doubling them

Parser interprets an internal quote as the end of the field, corrupting the record

Parse output with a strict CSV parser and verify no parse errors; spot-check fields known to contain quotes

Header Presence and Ordering

First row contains exactly the expected column names in the specified order

Header row is missing, contains extra columns, renames columns, or reorders them

Extract the first row and assert it matches the expected header list exactly

Field Value Integrity

Every field value from the source text is preserved without truncation, addition, or modification

Field contains truncated text, hallucinated values not in the source, or missing required data

For a golden set of source texts, assert that extracted values match expected ground-truth values per field

Newline Handling

Multi-line field values are properly quoted and internal newlines are preserved without breaking the record

A newline inside a field value starts a new row, causing a row-count mismatch or parser failure

Include a source text with a multi-line field in the test suite; assert row count equals 1 (plus header) after parse

Empty and Null Field Representation

Empty fields are represented as empty quoted strings; truly missing data uses a consistent null sentinel

Empty fields are omitted entirely, causing column shift; null fields are inconsistently represented

Parse output and assert that every row has a value for every column; check null sentinel consistency across rows

Encoding and Special Character Preservation

Output is valid UTF-8; special characters, accents, and non-ASCII text are preserved without mojibake

Characters are replaced with question marks, boxes, or escape sequences that downstream systems cannot interpret

Open the output file with UTF-8 encoding; assert no UnicodeDecodeError; spot-check non-ASCII source fields

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Add explicit schema validation, retry logic with error feedback, and structured logging. Include a post-processing harness that validates row counts, column counts, delimiter consistency, and quote escaping before the output enters any downstream system.

Prompt snippet

code
Convert the following free text into CSV rows using these exact columns in order: [COLUMN_LIST].

Rules:
- Every field must be double-quoted.
- Embedded quotes must be escaped by doubling them.
- Every row must have exactly [COLUMN_COUNT] fields.
- If a field value is missing, output an empty quoted string "".
- Do not include a header row.

Text:
[INPUT_TEXT]

If the text does not contain enough information to fill all columns for a row, still output the row with empty fields for missing values.

Watch for

  • Silent format drift when the model switches delimiter style mid-output
  • Rows with extra or missing fields that pass a naive row-count check
  • Unescaped newlines inside quoted fields breaking line-by-line parsers
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.