Skip to content
All posts
6 min read
markdown
ai
llm
validation
api

Validating LLM Markdown Output: A Production Playbook (2026)

LLMs return Markdown that's usually right and occasionally broken — unbalanced fences, bad tables, skipped headings, dead links. Here's how to validate AI output programmatically before you trust it.

LLM Markdown is usually well-formed — which is exactly why the failures are dangerous. The 1-in-50 response with an unbalanced code fence, a table that doesn't parse, a heading that jumps from H2 to H4, or a confidently hallucinated link will sail through your app and break a page, a PDF export, or a downstream parser. If you display or store AI Markdown, you need to validate it like any other untrusted input.

This is a production playbook: what goes wrong, which checks to run, and how to wire them in with the validate and audit APIs — including what to do when validation fails.

Why validate AI Markdown at all?

Three reasons, in order of severity:

  1. It breaks rendering. An unterminated ``` fence swallows the rest of the document. A malformed pipe table renders as raw text.
  2. It breaks downstream tools. If the Markdown feeds a static site generator, a PDF pipeline, or a parser, structural errors cascade.
  3. It's a security and trust issue. Hallucinated links, missing alt text, and injected HTML are quality and safety problems. (For the XSS angle specifically, see rendering ChatGPT Markdown safely.)

Validation is cheap insurance: the validate endpoint never renders or modifies the document — it just reports issues with a line, rule, and severity.

What actually goes wrong in LLM Markdown

FailureSymptomCaught by
Unbalanced code fenceRest of doc becomes codeGFM audit
Fence missing languageNo syntax highlightingGFM audit
Malformed pipe tableRenders as raw | textGFM audit
Heading jump (H2→H4)Broken outline, bad a11yheadings audit
Multiple H1sSEO/structure issueheadings audit
Missing space after ###Heading doesn't rendervalidate
Inconsistent bullets*/-/+ mixedvalidate
Hallucinated/dead links404s in published contentextract links
Missing image alt textAccessibility failureextract images
Trailing whitespace / blank-line spamNoisy diffsvalidate

The core validation call

async function validateMarkdown(markdown) {
  const res = await fetch("https://trymarkdownviewer.com/api/v1/validate", {
    method: "POST",
    headers: {
      "Authorization": `Bearer ${process.env.MDV_API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ markdown }),
  });
  return (await res.json()).data; // { valid, issueCount, issues: [...] }
}
{
  "valid": false,
  "issueCount": 2,
  "issues": [
    { "line": 1, "message": "Missing space after `#` in heading.", "rule": "heading-space", "severity": "warning" },
    { "line": 12, "message": "Use `-` for unordered list items.", "rule": "consistent-bullets", "severity": "info" }
  ]
}

Gate on severity — block on error/warning, treat info as cosmetic.

A layered validation pipeline

For production AI features, chain checks by importance and cost:

LLM output
   │
   ├─ 1. validate        (fast, always)        /api/v1/validate
   ├─ 2. GFM audit       (fences, tables)       /api/v1/audit/gfm
   ├─ 3. headings audit  (outline integrity)    /api/v1/audit/headings
   ├─ 4. links/images    (dead refs, alt text)  /api/v1/extract/{links,images}
   └─ 5. render+sanitize (only if all pass)      /api/v1/render
async function gateAiMarkdown(markdown) {
  const v = await validateMarkdown(markdown);
  const blocking = v.issues.filter(i => i.severity !== "info");
  if (blocking.length) {
    return { ok: false, stage: "validate", issues: blocking };
  }
  // ...repeat for GFM/headings/links as needed...
  return { ok: true };
}

You don't need all five for every use case — pick by where the output goes (a chat bubble needs render-safety; a docs commit needs the full chain).

What to do when validation fails

You have four strategies; choose by context:

StrategyWhenHow
Auto-fixCosmetic issuesRun /api/v1/format to normalize bullets, blank lines, trailing space
RegenerateStructural breakageRe-prompt the model with the specific issues appended
RejectSafety/quality gateBlock storage/display; log for review
SurfaceHuman-in-the-loopShow issues in an editor UI for an author to fix

Self-healing re-prompt

The most effective pattern for structural errors is feeding the validator's output back to the model:

if (!result.ok) {
  const issueText = result.issues
    .map(i => `- line ${i.line} [${i.rule}]: ${i.message}`)
    .join("\n");
  const repaired = await llm.chat([
    { role: "assistant", content: markdown },
    { role: "user", content:
      `Your Markdown has these issues. Return corrected Markdown only:\n${issueText}` },
  ]);
}

Because each issue carries a precise line and rule, the model gets actionable feedback and usually fixes it on the second pass.

Validating tool-call and structured output

When the LLM produces Markdown inside a JSON tool response or a structured field:

  1. Extract the Markdown field.
  2. Validate it independently (don't trust schema validity to mean Markdown validity).
  3. For tables specifically, the GFM audit confirms the first table parses; the CSV/table tools can round-trip it to verify structure.

If the model returns JSON that should become Markdown (e.g., an API response to display), the JSON to Markdown tool/endpoint gives you deterministic, always-valid output — sometimes better than asking the model to format the table itself.

Manual spot-checks during development

While building the feature, paste sample model outputs into the browser tools to see failures fast:

Build a small corpus of real model outputs (including the weird ones) and run them through your gate as regression tests.

Performance and cost

  • Validate is fast — a single pass, typically under 30ms for documents under 32 KiB, and it never renders.
  • Cache by content hash — identical Markdown always produces identical results.
  • Validate before render — it's cheaper than rendering, so use it as a pre-flight to avoid wasted render calls on broken input.

Common mistakes

1. Assuming LLM Markdown is always valid. The rare broken response is the one that breaks production.

2. Validating only for safety. Sanitization (XSS) and validation (structure) are different jobs — do both. See safe HTML rendering.

3. Hard-failing on cosmetic issues. Auto-fix info-level problems with format; don't reject the whole response.

4. No re-prompt loop. Feeding issues back to the model fixes most structural errors automatically.

5. Ignoring links. Hallucinated URLs are a top LLM failure — extract and check them.

Quick reference

CheckEndpointCatches
General lint/api/v1/validateheadings, bullets, whitespace
GFM compliance/api/v1/audit/gfmfences, tables, H1
Outline/api/v1/audit/headingsjumps, multi-H1
Links/api/v1/extract/linksdead/hallucinated URLs
Images/api/v1/extract/imagesmissing alt text
Render (safe)/api/v1/rendersanitized HTML

LLM Markdown is untrusted input that looks trustworthy. Validate it before you store or display it, feed failures back to the model to self-heal, and only render once it passes — that's the difference between an AI feature that occasionally breaks and one that holds up in production.

Written by Markdown Viewer Team. Found this useful? Try the editor →

Keep reading

Hand-picked articles related to this one.