Inferensys

Prompt

YAML Indentation Error Recovery Prompt

A practical prompt playbook for using YAML Indentation Error Recovery Prompt 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, reader, and constraints for the YAML Indentation Error Recovery Prompt.

This prompt is for DevOps and platform engineers who receive LLM-generated YAML that fails to parse due to indentation errors, tab characters, or incorrect nesting levels. The job is to recover a valid YAML document that preserves all original key-value data and conforms to a provided schema, without losing semantic content. Use this prompt when a YAML parser rejects the model output with indentation-related errors and you need a structured repair before the payload can be consumed by deployment tools, configuration managers, or CI/CD pipelines.

The prompt expects three inputs: the malformed YAML string, the raw parser error message, and an optional YAML schema or example document that defines the expected structure. It instructs the model to normalize whitespace, replace tabs with spaces, correct indentation depth to match the schema's nesting hierarchy, and preserve all keys, values, comments, and anchors. The output must include the repaired YAML, a list of specific corrections made, and a boolean flag indicating whether the repair was lossless. Do not use this prompt for semantic errors like incorrect values or missing required keys—those require a different repair workflow such as the Missing Required Field Injection Prompt or the YAML Schema Validation Retry Prompt.

This prompt is not a substitute for schema validation or type checking. It focuses exclusively on whitespace and structural indentation. If the model output contains fundamentally malformed YAML syntax beyond indentation—such as unclosed quotes, invalid anchors, or duplicate keys—the repair may be partial. In those cases, wire this prompt into a broader Structured Output Repair Harness that can route to format-specific sub-prompts. For high-risk production pipelines, always validate the repaired YAML against the target schema and log both the original error and the repair diff before applying the configuration.

PRACTICAL GUARDRAILS

Use Case Fit

Where the YAML Indentation Error Recovery Prompt works well and where it introduces risk.

01

Good Fit: CI/CD Pipeline Artifacts

Use when: LLM-generated Kubernetes manifests, Docker Compose files, or CI configs fail YAML linting due to inconsistent indentation. Guardrail: Validate the repaired output against the target tool's schema (e.g., kubectl --dry-run=client) before applying.

02

Bad Fit: Lossy Semantic Repair

Avoid when: The original YAML contains multi-line strings with significant leading whitespace (e.g., embedded scripts or markdown). Risk: Aggressive whitespace normalization can corrupt string content. Guardrail: Use a structural diff to flag altered scalar blocks for human review.

03

Required Inputs

Must provide: The malformed YAML string, the target indentation style (spaces vs. tabs, count), and an optional JSON Schema or YAML Schema for validation. Guardrail: Without a schema, the prompt can fix syntax but cannot guarantee semantic correctness against your application's expected structure.

04

Operational Risk: Tab-Character Hell

Risk: Mixed tabs and spaces in the input can cause the model to misjudge nesting depth, collapsing or splitting parent-child relationships. Guardrail: Pre-process the input to detect mixed whitespace and add a specific instruction to treat tabs as a configurable number of spaces before sending to the model.

05

Operational Risk: Silent Key Dropping

Risk: The model might drop a duplicate key or a comment-anchored value to produce valid YAML, losing critical configuration data. Guardrail: Always run a key-set comparison between the original parsed partial output and the repaired output to detect missing top-level or nested keys.

06

Operational Risk: Over-Aggressive Nesting

Risk: A single leading space error can cause the model to incorrectly nest a top-level block under a previous sibling. Guardrail: Pair this prompt with a schema validator in a retry loop. If the repaired structure violates the schema, feed the violation back as context for a second pass.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt template for recovering from YAML indentation errors with schema validation.

This template provides the core instruction set for an LLM to repair YAML with indentation errors. It is designed to be wrapped in your application's retry harness, receiving the original malformed YAML, the validation error, and an optional schema. The prompt forces the model to act as a strict syntax corrector, not a content editor, ensuring all key-value data is preserved.

yaml
system: |
  You are a YAML repair engine. Your only job is to fix indentation and whitespace errors in the provided YAML document.
  You must preserve all key-value pairs, comments, and anchors exactly as provided.
  Do not add, remove, or reorder any keys or values.
  Do not change any scalar values, including strings, numbers, or booleans.
  Normalize all indentation to consistent spaces (never tabs).
  If a [YAML_SCHEMA] is provided, ensure the repaired output validates against it.
  If the document contains fatal structural errors that cannot be reliably repaired, output a JSON error object instead of guessing.

human: |
  Repair the indentation and whitespace errors in the YAML document below.

  Validation Error:
  [VALIDATION_ERROR]

  Malformed YAML:
  [MALFORMED_YAML]

  Schema (optional):
  [YAML_SCHEMA]

  Output only the corrected YAML. If repair is impossible, output a JSON object with the key "repair_error" and a "reason" field.

To adapt this template, replace the placeholders with your runtime data. [MALFORMED_YAML] is the raw string that failed parsing. [VALIDATION_ERROR] is the exact error message from your YAML parser (e.g., PyYAML, yaml.v3). [YAML_SCHEMA] is an optional JSON Schema or similar structural definition. If you don't have a schema, remove that line from the human message and the corresponding instruction from the system prompt. The final instruction to output a JSON error object on fatal failure is critical for preventing the model from hallucinating a plausible but incorrect YAML document when the input is too damaged to fix.

IMPLEMENTATION TABLE

Prompt Variables

Required inputs for the YAML Indentation Error Recovery Prompt. Each variable must be supplied at runtime to enable reliable whitespace normalization, nesting correction, and schema validation.

PlaceholderPurposeExampleValidation Notes

[MALFORMED_YAML]

The raw YAML string with indentation errors, tab characters, or incorrect nesting levels

apiVersion: v1\nkind: Pod\nmetadata:\n name: example\n\tspec:\n containers:\n - name: app

Must be a non-empty string. Check for presence of tab characters or inconsistent leading whitespace before passing to the prompt.

[TARGET_SCHEMA]

A YAML or JSON Schema describing the expected structure, required fields, and allowed nesting

{"type": "object", "required": ["apiVersion", "kind", "metadata", "spec"], "properties": {"apiVersion": {"type": "string"}, "kind": {"type": "string"}}}

Must be a valid JSON Schema or YAML schema string. Validate schema syntax before use. Null allowed if schema validation is not required.

[ERROR_CONTEXT]

The raw error message from the YAML parser or linter indicating the line number and nature of the failure

yaml.parser.ParserError: while parsing a block mapping\n in "<string>", line 4, column 5:\n spec:\n ^\nexpected <block end>, but found '<block mapping start>'

Must be a non-empty string. Parse the error message to extract line numbers and error types before feeding into the prompt. Null allowed if no prior parse attempt was made.

[INDENTATION_STYLE]

The target indentation style: spaces or tabs, and the number of spaces per level

spaces:2

Must match pattern 'spaces:N' or 'tabs' where N is a positive integer. Default to 'spaces:2' if not specified. Validate against allowed values before use.

[PRESERVATION_RULES]

A list of keys or paths whose values must be preserved exactly, even if they contain unusual whitespace

["metadata.annotations.description", "spec.template.spec.containers[*].command"]

Must be a valid JSON array of string paths. Each path should use dot notation with optional [*] for array wildcards. Null allowed if no special preservation is needed.

[MAX_RETRY_DEPTH]

The maximum number of nested levels the repair prompt should attempt to correct before flagging for human review

10

Must be a positive integer between 1 and 50. Default to 20 if not specified. Higher values risk infinite loops in deeply nested structures.

[OUTPUT_FORMAT]

The desired output format: corrected YAML string, or a structured repair report with the corrected YAML and a change log

repair_report

Must be one of 'corrected_yaml' or 'repair_report'. Default to 'corrected_yaml' if not specified. Validate against allowed enum values.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the YAML Indentation Error Recovery Prompt into an automated CI/CD or configuration management pipeline.

This prompt is designed to be the core logic within a retry-and-repair harness, not a standalone chat interaction. The typical integration point is a post-inference validation step in a pipeline that generates or modifies YAML files, such as a Kubernetes manifest generator, a CI/CD config writer, or an infrastructure-as-code assistant. When the primary model output fails a strict YAML linter or schema validator, the harness should catch the error, package the failed YAML and the specific error messages, and invoke this recovery prompt. The goal is to produce a clean, schema-compliant YAML document without losing the semantic content of the original, flawed output.

To implement this, wrap the prompt template in a function that accepts three inputs: the raw, invalid YAML string, a list of structured error objects from your linter (e.g., yamllint or js-yaml), and an optional YAML schema definition. The function should construct the [INVALID_YAML] and [ERROR_CONTEXT] placeholders precisely. For [ERROR_CONTEXT], format each error as a single line: Line [L]: [Error Message]. The harness must then call the LLM with this assembled prompt. On receiving the response, extract the corrected_yaml field from the JSON output. Do not trust the output yet. Immediately run the extracted YAML through the same linter and schema validator that triggered the recovery. If it passes, the repair is successful. If it fails, you have two choices: feed the new error back into the prompt for a second attempt (up to a defined retry budget, typically 2-3 attempts), or escalate to a human operator with the original and all attempted repairs logged.

For production use, implement strict guardrails around this loop. Log every attempt, including the original invalid YAML, the error context sent to the model, the raw model response, and the final validation result. This audit trail is critical for debugging systemic prompt failures or model drift. Use a repair_confidence threshold from the model's output to decide whether to auto-apply the fix or flag it for review. For high-risk environments like production infrastructure changes, always require human approval before applying any auto-repaired YAML, regardless of validation success. Avoid using this prompt for YAML documents that contain sensitive secrets; if you must, ensure the logging pipeline redacts them before persistence.

IMPLEMENTATION TABLE

Expected Output Contract

Fields, format, and validation rules for the YAML Indentation Error Recovery Prompt output. Use this contract to validate the corrected YAML payload before passing it to downstream parsers.

Field or ElementType or FormatRequiredValidation Rule

corrected_yaml

string (valid YAML)

Parse check: must parse without errors using a strict YAML 1.2 parser. No tab characters allowed. All nesting must use consistent indentation (2 or 4 spaces).

indentation_style

string (enum)

Enum check: must be '2-space' or '4-space'. Must match the detected or specified indentation of the input. No mixed indentation within a single document.

repair_log

array of objects

Schema check: each element must have 'line' (integer), 'issue' (string from allowed set: 'tab_character', 'inconsistent_indent', 'wrong_nesting_level', 'missing_parent'), 'action' (string describing the fix applied).

validation_passed

boolean

Value check: must be true. If false, the output is invalid and must not be used. The repair prompt must not return a payload that fails schema validation.

validation_errors

array of strings or null

Null check: must be null when validation_passed is true. Must contain specific error messages when validation_passed is false. Empty array is not allowed when validation_passed is false.

original_key_count

integer

Range check: must be greater than 0. Must equal the number of top-level keys in the input YAML. Used to verify no data loss occurred during repair.

repaired_key_count

integer

Equality check: must equal original_key_count. A mismatch indicates keys were dropped or added during repair and requires human review.

schema_version

string or null

Format check: if provided, must match the schema version used for validation. Null allowed when no schema was provided. Used for audit trail and debugging.

PRACTICAL GUARDRAILS

Common Failure Modes

YAML indentation errors are among the most common and destructive failures in LLM-generated configuration. A single misplaced space can break a deployment pipeline. These cards cover the specific ways YAML repair fails and how to guard against them.

01

Semantic Drift During Nesting Repair

What to watch: When the model corrects indentation, it may inadvertently move a key-value pair under a different parent, changing the intended structure. A timeout setting meant for a database connection might end up under a logging config. Guardrail: Always diff the repaired YAML against the original, flagging any key that changed its parent path. Require a structured repair_log field that lists every node whose depth or parent changed.

02

Tab-Character Blindness

What to watch: YAML parsers reject tab characters outright, but many models treat tabs as equivalent to spaces during reasoning. The model may claim the YAML is valid while tabs remain in the output. Guardrail: Run a pre-validation check that scans for \t characters before attempting schema validation. If tabs are found, instruct the model to replace all tabs with spaces using the detected or specified indent size before any other repair step.

03

Schema-Ambiguous List Items

What to watch: When a YAML list item is misaligned, the model cannot determine whether it belongs to the parent list or should be a sibling. The model may guess and flatten a nested list into a single sequence, losing the grouping. Guardrail: Provide the exact YAML schema as part of the repair prompt context. Instruct the model to preserve the cardinality of all sequences. If the original had 3 items in a nested list, the repaired output must also have 3 items in that same list.

04

Multi-Document YAML Separator Corruption

What to watch: LLMs often strip or mishandle --- document separators and ... terminators, merging multiple YAML documents into one or dropping documents entirely. Guardrail: Count the number of documents in the input and enforce the same count in the output. If the model cannot recover a specific document, it must insert a placeholder document with a repair_error key rather than silently dropping it.

05

Comment and Anchor Loss

What to watch: YAML anchors (&anchor), aliases (*alias), and merge keys (<<) are frequently destroyed during repair. Comments are almost always stripped. For Kubernetes or CI/CD configs, this loss breaks templating and shared configuration blocks. Guardrail: Explicitly instruct the model to preserve all anchors, aliases, and merge keys by name. If a comment exists on a line that required repair, the model must re-attach the comment to the repaired line or log it as lost in the repair report.

06

Infinite Retry on Unrepairable Input

What to watch: If the original YAML is fundamentally ambiguous—such as a flat list of keys with no indentation clues—the model may hallucinate a structure that passes schema validation but is semantically wrong. Repeated retries produce different wrong outputs without converging. Guardrail: Set a hard retry budget of 3 attempts. After the budget is exhausted, escalate to a human operator with the original input, the schema, and all repair attempts logged. Never ship a repaired output that required more than 3 attempts without human approval.

IMPLEMENTATION TABLE

Evaluation Rubric

Criteria for evaluating the quality and safety of a YAML repair output before it is passed to a downstream parser or deployment pipeline.

CriterionPass StandardFailure SignalTest Method

Schema Compliance

Output passes validation against the provided [YAML_SCHEMA] without errors.

Validator returns errors for missing required keys, type mismatches, or enum violations.

Automated: Parse output with a YAML schema validator (e.g., kubeval, yamale).

Whitespace Normalization

All indentation uses spaces (not tabs) and nesting depth is consistent with the input structure.

A YAML parser throws an indentation error, or a character is detected in the output.

Automated: grep -P ' ' on the output file returns empty. Parse with a strict YAML parser.

Data Preservation

All non-whitespace key-value pairs from the [MALFORMED_YAML] input are present and unchanged.

A key from the input is missing, a value has been altered, or a new key has been hallucinated.

Automated: Deep-compare the parsed input (best-effort) and output data structures after normalizing whitespace.

Semantic Integrity

The logical structure (list items, map nesting) matches the intended structure of the input.

A list item has been incorrectly nested under a parent map, or a map has been flattened into a list.

Automated: Compare the JSON representations of the input and output for structural equivalence. Manual: Spot-check complex nested blocks.

Repair Confidence Flag

The [REPAIR_CONFIDENCE] field is true only if all fixes are deterministic; false if any ambiguity existed.

Confidence is true but a destructive change was made, or false for a trivial whitespace-only fix.

Automated: Assert that REPAIR_CONFIDENCE is a boolean. Manual: Review the repair_log for ambiguous actions.

Repair Log Accuracy

The repair_log contains a specific entry for every change made, mapping the line to the fix.

The log is empty but the output differs from the input, or the log describes a fix that wasn't applied.

Automated: Check that the number of log entries matches the number of structural diffs. Manual: Verify a sample of log entries.

No Destructive Coercion

No data types were silently changed (e.g., string 'yes' to boolean true) without an explicit log entry.

A value's type in the output differs from the input without a corresponding repair_log entry explaining the coercion.

Automated: Traverse the parsed input and output, flagging any type mismatches not documented in the repair_log.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Add schema validation, a retry budget of 3 attempts, structured repair logging, and a repair confidence score. Feed validator error output back into the retry prompt with escalating specificity. Stop when valid or budget exhausted.

Prompt modification: Append to the base prompt:

code
After repair, validate against this schema:
[YAML_SCHEMA]

If validation fails, return:
- corrected_yaml: the repaired YAML
- repair_log: array of {line, original_indent, corrected_indent, action}
- confidence: 0.0-1.0 per repair action
- validation_errors_remaining: list of unresolved issues

Watch for

  • Silent format drift across retry attempts
  • Confidence scores that don't correlate with actual correctness
  • Missing human review for low-confidence repairs
  • Retry loops that exceed latency budgets
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.