Inferensys

Prompt

Inline Code vs Fenced Block Disambiguation Prompt Template

A practical prompt playbook for classifying inline code spans and fenced code blocks in markdown, extracting only fenced blocks for file operations while preserving inline code for prose rendering.
MLOps engineer reviewing model serving infrastructure on laptop, container orchestration visible, technical workspace.
PROMPT PLAYBOOK

When to Use This Prompt

Define the job, reader, and constraints for disambiguating inline code from fenced code blocks.

This prompt is designed for documentation generators, markdown parsers, and coding agents that must reliably separate inline code spans from fenced code blocks in AI-generated or user-provided markdown. The core job is classification: every backtick-delimited segment in the input must be identified as either an inline element (destined for prose rendering) or a fenced block (destined for file operations, execution, or structured extraction). The ideal user is a developer building a pipeline that consumes markdown and needs to route code to different downstream systems—syntax highlighters, file writers, or notebook converters—without corrupting the document structure.

Use this prompt when your application processes mixed-content markdown where both inline code references and full fenced blocks coexist, and misclassification would break rendering or cause executable code to leak into prose. It is particularly valuable when the input source is an LLM that may inconsistently format code, use non-standard fence lengths, or embed backtick-heavy prose like regex patterns or shell examples. Do not use this prompt when you only need to extract all code indiscriminately, when the input is guaranteed to contain only fenced blocks, or when you are operating in a streaming context where fence state must be tracked incrementally—use the Streaming Code Block Extraction Prompt Template for that scenario. This prompt assumes you have the complete markdown text available for holistic analysis.

Before integrating this prompt, ensure your pipeline can handle the output schema: a list of classified elements, each with a type (inline or fenced), the raw content, and metadata like language tags and fence lengths. The prompt includes boundary-case handling for single-line fences, backtick-heavy prose, and nested backtick patterns. After classification, route fenced blocks to your code extraction or file-writing harness and inline spans to your markdown renderer. If your use case involves regulated documentation, medical records, or legal filings, add a human review step before any code block is written to disk or executed. Start by running the provided eval cases against your model to confirm classification accuracy before wiring this into a production pipeline.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Inline Code vs Fenced Block Disambiguation prompt works well and where it introduces risk. Use these cards to decide if this prompt fits your pipeline before integrating it.

01

Good Fit: Documentation Post-Processing

Use when: You have a model generating markdown documentation and you need to reliably separate executable code examples from explanatory prose. Guardrail: Run the prompt as a second-pass classifier after generation, not as a constraint during the initial generation step.

02

Bad Fit: Real-Time Streaming

Avoid when: You need to disambiguate inline code from fenced blocks in a streaming response where the fence state is incomplete. Risk: The prompt requires the full response to count backticks and detect boundaries. Guardrail: Use a streaming state machine for real-time extraction and reserve this prompt for complete response post-processing.

03

Required Input: Complete Markdown Response

What to watch: The prompt cannot classify code elements without the full response text. Truncated or partial responses produce unreliable fence detection. Guardrail: Validate that the input contains complete markdown with balanced or explicitly closed fences before calling the prompt.

04

Operational Risk: Backtick-Heavy Prose

What to watch: Documentation about markdown itself, regex, or shell scripting often contains literal backtick characters in prose that can be misclassified as code spans. Guardrail: Include few-shot examples of backtick-heavy prose in the prompt template and add a post-extraction validator that checks for prose-length inline code misclassifications.

05

Operational Risk: Single-Line Fence Ambiguity

What to watch: A single line wrapped in triple backticks can be either a one-line fenced block or a malformed inline span. Models often default to one interpretation inconsistently. Guardrail: Add an explicit rule in the prompt for minimum fenced block content length and flag ambiguous single-line cases for human review or heuristic resolution.

06

Pipeline Position: Before File Write Operations

What to watch: If you write extracted fenced blocks directly to disk without disambiguation, inline code fragments can become corrupted files. Guardrail: Insert this prompt as a mandatory classification gate after extraction and before any file system write. Only blocks classified as 'fenced' with high confidence should trigger file creation.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt that disambiguates inline code spans from fenced code blocks in markdown, extracting only fenced blocks for file operations while preserving inline code for prose rendering.

This prompt template forces the model to classify every code-like element in a markdown response as either an inline code span or a fenced code block, then extract only the fenced blocks into a structured array. Use it when your documentation generator, coding agent, or markdown parser must reliably separate prose-level code references from file-worthy code segments. The template includes explicit boundary-case handling for single-line fences, backtick-heavy prose, and nested code references that commonly cause misclassification.

text
You are a precise markdown parser that distinguishes inline code spans from fenced code blocks. Your task is to analyze the provided markdown content and classify every code-like element, then extract only the fenced code blocks into a structured output.

## INPUT
Analyze the following markdown content:

```markdown
[INPUT_MARKDOWN]

CLASSIFICATION RULES

  1. Inline code spans: Single backtick-wrapped text (like this) or double-backtick-wrapped text when the content contains single backticks. These appear within paragraph text and are not standalone blocks. Do NOT extract these.
  2. Fenced code blocks: Text wrapped in triple backticks (```) or triple tildes (~~~) that appear on their own lines, optionally preceded by a language tag. These are standalone content blocks. Extract these.
  3. Boundary cases:
    • Single-line fenced blocks (code) are still fenced blocks if the opening and closing fences are on the same line or adjacent lines with no paragraph text between them.
    • Prose containing multiple backticks for discussion purposes (e.g., "use ``` to open a fence") is NOT a fenced block unless the backticks appear on dedicated lines.
    • Nested backtick patterns inside fenced blocks (showing markdown examples) are part of the fenced block content, not separate blocks.

OUTPUT SCHEMA

Return a JSON object with this exact structure: { "inline_code_spans": [ { "content": "the code text without backticks", "position": {"line_start": 0, "line_end": 0, "char_start": 0, "char_end": 0}, "surrounding_text": "brief context from surrounding prose" } ], "fenced_blocks": [ { "language": "detected language tag or null", "content": "the code content without fences", "fence_type": "backtick or tilde", "position": {"line_start": 0, "line_end": 0}, "is_complete": true } ], "classification_notes": ["any ambiguous cases and how they were resolved"] }

CONSTRAINTS

  • Never extract inline code spans into the fenced_blocks array.
  • Always include position information for traceability.
  • Flag any ambiguous elements in classification_notes.
  • If a fenced block appears incomplete (missing closing fence), set is_complete to false and include what was found.
  • Preserve exact whitespace and indentation within fenced block content.
  • Do not modify or escape the content of extracted blocks.

EXAMPLES

Example 1: Mixed inline and fenced code Input: Use the print() function like this:

python
print("hello")

Expected classification:

  • inline_code_spans: [{"content": "print()", ...}]
  • fenced_blocks: [{"language": "python", "content": "print("hello")", ...}]

Example 2: Single-line fence Input:

bash
ls -la

Expected classification:

  • inline_code_spans: []
  • fenced_blocks: [{"language": "bash", "content": "ls -la", ...}]

Example 3: Backtick-heavy prose Input: To create a fenced block, type on a new line, then your code, then again.

Expected classification:

  • inline_code_spans: []
  • fenced_blocks: []
  • classification_notes: ["Triple backticks appear in prose context, not on dedicated lines"]

OUTPUT

Return only the JSON object. No markdown fences, no commentary.

Adapt this template by replacing [INPUT_MARKDOWN] with your actual markdown content. For production pipelines, consider adding [OUTPUT_SCHEMA] variations if you need additional metadata like file paths, insertion markers, or execution environment specs. The classification rules section is the most critical to customize—adjust boundary case handling based on the specific failure patterns you observe in your model's outputs. If you're processing streaming responses, pair this with a state machine that tracks fence open/close state across chunks rather than relying on the prompt alone.

Before deploying, test this prompt against a golden dataset containing at least 20 examples that include: single-line fences, backtick-heavy prose, nested code blocks, missing closing fences, tilde-based fences, and inline code containing backticks. Run eval checks for precision (did we extract only real fenced blocks?) and recall (did we miss any fenced blocks?). Common failure modes include misclassifying single-line fences as inline code and treating prose discussions about markdown syntax as fenced blocks. If your model consistently fails on boundary cases, add more explicit examples to the prompt rather than lengthening the rules section.

IMPLEMENTATION TABLE

Prompt Variables

Inputs required for the Inline Code vs Fenced Block Disambiguation prompt to operate reliably in a documentation or markdown parsing pipeline.

PlaceholderPurposeExampleValidation Notes

[RAW_MARKDOWN_INPUT]

The full markdown string containing a mix of inline code spans and fenced code blocks to be classified.

Check the config.py file for settings.

python
print('hello')

Must be a non-empty string. Validate that the input contains at least one backtick character; if not, the prompt should return an empty classification list.

[CLASSIFICATION_SCHEMA]

A JSON Schema or explicit instruction defining the output structure for each classified element (type, content, language, fence_depth).

{"type": "object", "properties": {"element_type": {"enum": ["inline_code", "fenced_block"]}, "content": {"type": "string"}, "language": {"type": ["string", "null"]}}}

Must be a valid JSON Schema or a strict prose description of the output contract. Validate that the schema includes an enum constraint for element_type to prevent unclassified outputs.

[EXTRACTION_MODE]

Specifies whether the prompt should extract only fenced blocks, only inline code, or classify all elements.

fenced_blocks_only

Must be one of: fenced_blocks_only, inline_code_only, classify_all. Validate against a controlled vocabulary before prompt assembly to prevent ambiguous extraction instructions.

[FENCE_DELIMITER_POLICY]

Defines how to handle non-standard fence lengths, indented fences, or single-line fenced blocks.

{"min_fence_length": 3, "allow_indented": false, "single_line_blocks": "classify_as_fenced"}

Must be a valid JSON object with explicit rules for each edge case. If null, the prompt defaults to CommonMark spec behavior. Validate that min_fence_length is an integer >= 3.

[LANGUAGE_TAG_MAP]

A mapping of language aliases to canonical language identifiers for normalization.

{"py": "python", "js": "javascript", "sh": "bash"}

Must be a valid JSON object. Validate that keys are lowercase strings and values are non-empty strings. If null, no alias normalization is performed.

[MAX_CODE_BLOCK_LENGTH]

A character limit for extracted fenced block content to prevent memory exhaustion in downstream file operations.

50000

Must be a positive integer. Validate that the value is within the system's safe processing limits. Blocks exceeding this length should be truncated with a warning flag in the output.

[BACKTICK_ESCAPE_RULES]

Instructions for handling prose that contains backtick characters used for emphasis or as literal characters rather than code delimiters.

Treat backtick pairs inside fenced blocks as literal content. For inline prose, a single backtick without a closing pair within 100 characters is not a code span.

Must be a non-empty string or null. If null, the prompt uses CommonMark backtick parsing rules. Validate that the rules explicitly address the case of unpaired backticks in prose.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the disambiguation prompt into a documentation generator or markdown parser with validation, retries, and safe file operations.

This prompt is designed to sit between a raw model response and a downstream system that needs to separate inline code from fenced code blocks. The typical integration point is a post-processing step in a documentation generator, a coding agent's response handler, or a markdown-to-notebook converter. The prompt expects a single [INPUT] containing the full markdown text and returns a structured JSON object with two arrays: fenced_blocks for file operations and inline_spans for prose rendering. Do not use this prompt for streaming responses where fence state is incomplete; use the Streaming Code Block Extraction prompt instead.

Wire the prompt into your application with a validation layer before any file write or database insert. Parse the JSON output and run these checks: (1) every fenced_block must have a non-empty content and a language tag that matches your allowed language list; (2) no inline_span should contain triple-backtick sequences, which would indicate a misclassification; (3) the sum of extracted elements should not exceed the original input's code-like token count by more than 10%, a signal of duplication. If validation fails, retry once with the same prompt but append the validation errors as a [CONSTRAINTS] field: "Previous extraction failed validation: [list specific errors]. Re-extract and correct these issues." After two failures, log the raw response and route to a human review queue rather than silently writing broken output.

For model choice, prefer models with strong JSON mode and instruction-following benchmarks (GPT-4o, Claude 3.5 Sonnet, or Gemini 1.5 Pro). Set response_format to json_object and supply the output schema in the API call's structured output parameter, not just in the prompt text. This dual enforcement reduces fence misclassification by catching malformed JSON before it reaches your application. For tool-use integrations, expose the output schema as a tool parameter so the model can self-validate before responding. Log every extraction with the input hash, model version, validation pass/fail, and retry count for observability. The most common production failure mode is single-line fenced blocks (e.g., `code`) being classified as inline code—add an eval case for this boundary in your regression test suite before shipping.

IMPLEMENTATION TABLE

Expected Output Contract

Structured output schema for the Inline Code vs Fenced Block Disambiguation Prompt. Use this contract to validate model responses before routing code elements to file operations or prose rendering pipelines.

Field or ElementType or FormatRequiredValidation Rule

classification_result

object

Top-level object must parse as valid JSON. Reject if not parseable.

classification_result.elements

array

Array must contain at least one element. Reject if empty or missing.

classification_result.elements[].type

string (enum: inline_code, fenced_block)

Must be exactly 'inline_code' or 'fenced_block'. Reject any other value.

classification_result.elements[].content

string

Must contain the raw code text without surrounding backticks for inline, without opening/closing fences for blocks. Null or empty string not allowed.

classification_result.elements[].language

string | null

For fenced_block, should match language tag if present. For inline_code, must be null. Reject if inline_code has a non-null language.

classification_result.elements[].start_line

integer

Line number in original input where element begins. Must be >= 1. Reject if negative or zero.

classification_result.elements[].end_line

integer

Line number where element ends. Must be >= start_line. Reject if end_line < start_line.

classification_result.elements[].confidence

number (0.0-1.0)

Must be between 0.0 and 1.0 inclusive. Values below 0.7 should trigger human review for ambiguous cases.

PRACTICAL GUARDRAILS

Common Failure Modes

What breaks first when disambiguating inline code from fenced blocks and how to guard against it.

01

Backtick-Heavy Prose Misclassification

What to watch: Prose containing multiple backticks (e.g., shell prompts, markdown tutorials) triggers false-positive fence detection. Single backticks inside prose are mistaken for inline code, and triple-backtick sequences in example text are parsed as block delimiters. Guardrail: Require fenced blocks to have a newline immediately after the opening fence and before the closing fence. Reject any fence delimiter that appears mid-line or lacks surrounding whitespace.

02

Single-Line Fence Ambiguity

What to watch: A single line surrounded by triple backticks (e.g., ``` print('hello') ```) is ambiguous—it could be a one-line fenced block or an inline code span with backtick padding. Classifiers often default to block mode, breaking inline rendering. Guardrail: Enforce a minimum content length or line-count threshold for fenced block classification. Treat single-line backtick-wrapped content as inline unless an explicit language tag is present.

03

Missing or Inconsistent Language Tags

What to watch: Fenced blocks without language identifiers (bare ```) are extracted as code blocks but cannot be validated, syntax-highlighted, or routed to language-specific processors. Mixed tagged and untagged blocks in the same response cause downstream tooling failures. Guardrail: Apply a fallback language detection step for untagged blocks and flag them with a confidence score. Reject blocks below a confidence threshold or route them to a manual review queue before file insertion.

04

Nested Fence Delimiter Confusion

What to watch: Documentation or tutorial responses that show how to write fenced code blocks contain nested triple-backtick sequences. A naive parser matches the first ``` it sees as a closer, truncating the block and leaving orphaned content. Guardrail: Use a stack-based fence tracker that pairs openers with matching closers at the same indentation level. Reject responses where fence depth does not return to zero by end-of-response.

05

Inline Code Spans Inside Fenced Blocks

What to watch: Fenced code blocks that contain markdown examples with inline code spans (single backticks inside the block) confuse post-extraction renderers. The extracted block is treated as raw code, but downstream markdown parsers re-interpret the inner backticks. Guardrail: After extraction, scan block content for unescaped backtick sequences that could be misinterpreted. Escape or flag them before passing to markdown renderers. Document this as a known limitation in extraction output metadata.

06

Whitespace-Only Content Blocks

What to watch: Model responses occasionally produce fenced blocks containing only whitespace, newlines, or a single comment character. These pass fence validation but produce empty files or no-op insertions downstream. Guardrail: Post-extraction, strip each block and discard any with zero non-whitespace characters. Log discarded blocks with their position for traceability. Add a minimum-content-length threshold to extraction configuration.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to evaluate the quality of the Inline Code vs Fenced Block Disambiguation prompt before shipping. Each criterion targets a known failure mode for markdown parsers and documentation generators.

CriterionPass StandardFailure SignalTest Method

Fenced Block Recall

All fenced code blocks in [INPUT] are extracted with correct language tags and content.

A fenced block is missing from the output array, or its content is truncated.

Run against a golden set of 20 mixed markdown documents. Assert extracted block count matches expected count exactly.

Inline Code Precision

No inline code spans are incorrectly classified as fenced blocks in the output.

An inline span like single backtick appears in the extracted blocks array.

Include documents with heavy backtick usage in prose. Assert zero false positives for inline spans in the fenced block output.

Single-Line Fence Handling

Single-line fenced blocks (e.g., python print('hi') ) are correctly extracted as a block, not ignored.

A single-line fenced block is missing from the output or classified as inline code.

Test with boundary cases: single-line fences, fences with no newlines, and fences immediately adjacent to text. Assert extraction count.

Nested Backtick Disambiguation

Prose containing triple backticks inside inline code (e.g., Use ``` fences) is not treated as a fenced block.

A false fenced block is extracted from a paragraph demonstrating markdown syntax.

Feed documents that explain markdown fencing. Assert that no code block is extracted from explanatory prose sections.

Language Tag Preservation

The [LANGUAGE] field for each extracted block matches the original fence info string exactly, including compound tags.

Language tag is missing, normalized without instruction, or truncated (e.g., js instead of javascript).

Use fences with compound tags like bash {.line-numbers} or python3. Assert exact string match in output.

Empty Block Handling

Empty fenced blocks ( ) are extracted with an empty content string and a confidence flag if specified.

Empty fences are silently dropped or cause a parsing error that loses subsequent blocks.

Include empty fence pairs in test input. Assert block exists in output with content length zero.

Unclosed Fence Recovery

If [ERROR_TOLERANCE] is enabled, an unclosed fence at EOF is extracted with a fence_incomplete: true flag.

An unclosed fence causes the entire tail of the document to be captured as block content or is dropped entirely.

Truncate a document mid-fence. Assert the block is extracted with an incomplete flag and does not consume subsequent prose.

Output Schema Compliance

The output strictly matches [OUTPUT_SCHEMA] with all required fields present and correctly typed.

Output is missing block_index, language is null when it should be an empty string, or extra fields are present.

Validate output against the JSON Schema. Assert no schema violations for any test case in the evaluation suite.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a small set of test documents. Remove the strict output schema and let the model return a simple JSON array of classified elements. Use a lightweight post-processing step to separate inline code from fenced blocks.

code
Classify each code element in [INPUT] as either "inline" or "fenced". Return a JSON array of objects with "type" and "content" fields.

Watch for

  • Single-line fences (```python print('hello') ```) misclassified as inline
  • Backtick-heavy prose (e.g., markdown tutorials) triggering false positives
  • Missing language tags on otherwise valid fenced blocks
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.