This prompt template is designed for the specific job of extracting hierarchically nested code blocks from AI-generated tutorials, documentation, or educational content. The ideal user is a developer building a documentation generator, a coding agent scaffold, or a content pipeline where a model's output contains code examples that themselves include embedded code blocks (e.g., a Markdown tutorial explaining how to write a Dockerfile that contains a shell script). The core challenge is that standard fenced-code-block regex fails when backtick fences are nested, causing extraction to stop at the first closing fence and corrupting the hierarchical structure. This prompt disambiguates inner and outer blocks by enforcing a structured extraction contract.
Prompt
Nested Code Block Extraction Prompt Template

When to Use This Prompt
Define the job, the user, and the constraints for nested code block extraction.
You should use this prompt when your input text is known to contain at least one level of nested fenced content, and you need to preserve the parent-child relationship between blocks for downstream file generation or rendering. The prompt requires a clear [INPUT] text, an optional [LANGUAGE_HINTS] list to aid disambiguation, and a defined [OUTPUT_SCHEMA] that specifies a tree structure with depth tracking. Do not use this prompt for flat, single-level code block extraction—simpler regex or standard extraction prompts are more cost-effective and less error-prone for that task. This prompt is overkill for responses that only contain inline code or a single fenced block.
Before wiring this into a production pipeline, you must define clear evaluation criteria for fence depth tracking and delimiter pair matching. Common failure modes include misinterpreting four-backtick fences as nested three-backtick fences, losing track of depth when a block contains an odd number of backticks in prose, and failing to reassemble a block when the model's output has a missing closing fence. The next step after reading this playbook is to copy the prompt template, adapt the [OUTPUT_SCHEMA] to match your application's object model, and run it against a golden dataset of intentionally nested examples to calibrate your validation logic.
Use Case Fit
Where the Nested Code Block Extraction prompt template delivers value and where it introduces risk. Use these cards to decide if this prompt fits your pipeline before you invest in integration.
Good Fit: Tutorial & Documentation Generators
Use when: your system generates multi-layered educational content where outer blocks explain a concept and inner blocks show embedded configuration or example snippets. Guardrail: Validate that every extracted inner block has a corresponding outer context block to prevent orphaned code fragments.
Good Fit: Multi-File Project Scaffolding
Use when: a coding agent outputs a project structure where top-level blocks represent files and nested blocks represent configuration or test fixtures within those files. Guardrail: Enforce a maximum nesting depth of 2 to prevent ambiguous ownership and simplify reassembly logic.
Bad Fit: Flat Single-File Code Generation
Avoid when: your use case only requires extracting a single, flat code block per response. The nested extraction logic adds unnecessary complexity and increases the risk of misclassifying standard fenced blocks. Guardrail: Route simple extraction tasks to a standard code block extraction prompt and reserve this template for responses known to contain hierarchical structures.
Required Inputs
What you must provide: a raw model response containing markdown with fenced code blocks, an expected maximum nesting depth, and a schema definition for the extracted block hierarchy. Guardrail: If the input response lacks language tags on outer blocks, pre-process with a language detection fallback before running nested extraction to improve block identification accuracy.
Operational Risk: Misaligned Delimiter Pairs
Risk: the model produces an uneven number of opening and closing fences, causing the extractor to merge adjacent blocks or drop content. Guardrail: Implement a fence-balance validator that counts opening and closing delimiters per nesting level and rejects or flags responses with mismatched pairs before extraction proceeds.
Operational Risk: Depth Creep in Agentic Loops
Risk: in multi-step agent workflows, nested blocks can accumulate depth with each iteration, eventually exceeding parser limits or producing unreadable output. Guardrail: Set a hard depth limit in the prompt instructions and add a post-extraction check that flattens or rejects blocks exceeding the configured maximum nesting level.
Copy-Ready Prompt Template
A reusable prompt template with square-bracket placeholders for extracting nested code blocks from AI-generated tutorials and documentation.
This prompt template is designed to extract and disambiguate nested fenced code blocks from model responses. It is particularly useful for tutorial and documentation generators where code blocks contain embedded examples within other code blocks. The template instructs the model to identify outer and inner blocks separately, track fence depth, and preserve hierarchical context so that downstream systems can reliably parse the structure without confusing nested delimiters.
codeYou are an expert code block extraction system. Your task is to parse the provided [INPUT_TEXT] and extract all fenced code blocks, including nested blocks where one code block contains another. You must disambiguate nested fences by tracking fence depth and delimiter pairs. ## Input [INPUT_TEXT] ## Output Schema Return a valid JSON object conforming to this structure: { "blocks": [ { "id": "string (unique identifier for this block)", "depth": "integer (0 for top-level, 1 for first nested level, etc.)", "parent_id": "string | null (id of the containing block, null for top-level)", "language": "string | null (language tag from opening fence, null if missing)", "content": "string (raw content inside the fences, excluding the fence delimiters themselves)", "opening_fence": "string (the exact opening fence string, e.g., ```python)", "closing_fence": "string (the exact closing fence string, typically ```)", "start_line": "integer (line number in [INPUT_TEXT] where the opening fence appears)", "end_line": "integer (line number in [INPUT_TEXT] where the closing fence appears)", "contains_nested_blocks": "boolean" } ], "extraction_issues": [ { "type": "string (e.g., 'unclosed_fence', 'misaligned_delimiter', 'ambiguous_nesting')", "location_line": "integer | null", "description": "string" } ] } ## Constraints [CONSTRAINTS] ## Examples [EXAMPLES] ## Instructions 1. Scan [INPUT_TEXT] line by line to identify all fenced code block delimiters (``` or ~~~). 2. Track fence depth by maintaining a stack of open fences. Each opening fence increases depth; each closing fence decreases depth. 3. Match closing fences to the nearest unmatched opening fence of the same delimiter type and length. 4. For each block, record the language tag if present on the opening fence. 5. If a closing fence is missing, report it in `extraction_issues` and treat the block as extending to the end of input. 6. If fence delimiters are misaligned (e.g., opening with ``` but closing with ~~~), report it and attempt recovery by matching the most recent compatible opener. 7. Preserve all whitespace and indentation within block content exactly as it appears. 8. Do not classify inline code spans (single backticks) as fenced blocks.
To adapt this template, replace the square-bracket placeholders with your specific inputs. [INPUT_TEXT] should contain the full model response or document to parse. [CONSTRAINTS] can specify additional rules such as maximum nesting depth, language filtering, or handling of indented fences. [EXAMPLES] should include one or two few-shot demonstrations showing correct extraction of nested blocks, especially edge cases like triple-nested fences or blocks where the inner block uses a different delimiter style than the outer block. Before deploying, validate the output against the JSON Schema and run eval checks for fence depth tracking accuracy and misaligned delimiter detection.
Prompt Variables
Required inputs for the nested code block extraction prompt. Each placeholder must be populated before the prompt is sent to the model. Validation notes describe how to verify the input is well-formed before execution.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[RAW_RESPONSE] | The full model response containing nested fenced code blocks to extract | Here is the outer block:
| Must be a non-empty string. Check for presence of at least one opening fence marker (```). Null or empty input should short-circuit before prompt execution. |
[OUTER_LANGUAGE] | Expected language tag for the outermost code block layer | python | Must match a known language identifier or be set to null for untagged outer blocks. Validate against a controlled vocabulary of supported languages. Mismatch with actual fence tag triggers a confidence downgrade in extraction output. |
[MAX_NESTING_DEPTH] | Maximum allowed fence nesting depth before extraction treats deeper fences as literal content | 3 | Must be a positive integer between 1 and 10. Depths above 5 should trigger a warning log. Values below 2 will cause inner blocks to be treated as literal text rather than extracted separately. |
[EXTRACTION_MODE] | Controls whether extraction returns only the outermost blocks, only the innermost blocks, or the full hierarchy | full_hierarchy | Must be one of: outermost_only, innermost_only, full_hierarchy. Invalid values should cause prompt rejection before model invocation. Default to full_hierarchy if null. |
[INCLUDE_POSITION_METADATA] | Whether to include line numbers, character offsets, and byte positions in extraction output | Must be boolean true or false. When true, output schema must include position fields. When false, position fields may be omitted. Mismatch between this flag and output schema fields is a contract error. | |
[FENCE_STYLE] | The fence delimiter style used in the response: backtick or tilde | backtick | Must be backtick or tilde. Mixed-style responses require separate extraction passes. Auto-detection from [RAW_RESPONSE] is acceptable but must log the detected style for audit. |
[OUTPUT_SCHEMA] | JSON Schema or type definition that the extraction output must conform to | {"type": "object", "properties": {"blocks": {"type": "array", "items": {"$ref": "#/definitions/ExtractedBlock"}}}, "required": ["blocks"]} | Must be a valid JSON Schema object or null. When provided, extraction output must pass schema validation before returning. When null, a default nested block schema is applied. Invalid schemas must be caught before prompt execution. |
[FAILURE_THRESHOLD] | Confidence score below which extraction results are flagged for human review or discarded | 0.85 | Must be a float between 0.0 and 1.0. Scores below threshold should route output to a review queue rather than downstream consumers. Set to 0.0 to disable threshold gating. Values above 0.95 may cause excessive false-positive rejections in noisy responses. |
Implementation Harness Notes
How to wire the nested code block extraction prompt into a reliable application pipeline.
The nested code block extraction prompt is designed to be a single step within a larger document processing or code generation pipeline. It should not be the first or last step. The typical harness wraps this prompt between a source ingestion step (which provides the raw markdown or text) and a validation step that verifies the structural integrity of the extracted blocks. Because the prompt handles disambiguation of nested fences, the application layer must preserve the raw response exactly as the model outputs it before any downstream parsing occurs. Any pre-processing that normalizes whitespace or escapes backticks will corrupt the fence hierarchy and cause extraction failures.
Wire the prompt into your application with a strict validation layer immediately after the model response. The expected output is a JSON object containing an outer_blocks array and an inner_blocks array, each with language, content, depth, and fence_type fields. Before passing this output to any file writer or database insert, validate that every opening fence has a corresponding closing fence at the same depth, that language tags are present or explicitly null, and that no block's content contains an unescaped fence that would break the nesting hierarchy. If validation fails, log the raw response and the validation error, then retry with the same prompt and a stronger constraint on fence integrity. After two failed retries, escalate the malformed response for human review rather than silently ingesting broken code blocks.
For production deployments, choose a model with strong instruction-following and structured output capabilities. If your provider supports it, use constrained decoding or structured output mode to enforce the JSON schema directly at the token level, bypassing the need for regex-based extraction. When constrained decoding is unavailable, implement a robust JSON extraction fallback that searches for the first complete JSON object in the response, tolerating markdown fences or surrounding prose. Always log the full prompt, response, extraction latency, and validation result for every call. This trace data is essential for debugging fence misalignment issues and for building a golden dataset of nested code block examples that can be used for regression testing when the prompt or model changes.
Expected Output Contract
Defines the exact structure, types, and validation rules for the nested code block extraction output. Use this contract to build a post-processing validator or to configure a strict JSON mode schema.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
outer_blocks | Array of objects | Must be a non-empty array. Each element must conform to the outer_block schema. | |
outer_blocks[].id | String | Must be a unique identifier within the response, formatted as 'outer-[index]'. | |
outer_blocks[].language | String or null | Must be a lowercase language tag from the opening fence (e.g., 'python', 'yaml') or null if untagged. Validate against a known language list. | |
outer_blocks[].content | String | Must contain the raw text between the outer fences. Must not be an empty string. | |
outer_blocks[].inner_blocks | Array of objects or null | If inner fences are detected, an array of inner_block objects. Otherwise, null. Must not be an empty array. | |
inner_blocks[].id | String | Must be a unique identifier within the parent outer block, formatted as 'inner-[parent_index]-[child_index]'. | |
inner_blocks[].language | String or null | Must be a lowercase language tag from the inner opening fence or null if untagged. | |
inner_blocks[].content | String | Must contain the raw text between the inner fences. Must not be an empty string. |
Common Failure Modes
Nested code blocks break naive regex extraction. These failures cascade into corrupted file writes, broken tutorials, and silent data loss in documentation pipelines. Guard against them before they reach production.
Fence Depth Mismatch
What to watch: The model uses the same number of backticks for outer and inner fences, making it impossible to distinguish nesting boundaries. A 3-backtick outer block containing a 3-backtick inner example collapses into one malformed block. Guardrail: Instruct the model to increase backtick count by one for each nesting level (outer uses ```, inner uses ````). Validate that closing fence lengths match their opening pairs before extraction.
Premature Fence Closure
What to watch: The extractor closes the outer block at the first ``` it encounters, treating the inner block's opening fence as the outer block's closing fence. The remaining content becomes orphaned text or a misidentified block. Guardrail: Implement a stack-based fence tracker that pushes on open and pops only on matching-length close. Reject extractions where the stack is non-empty at end-of-response or where a close has no matching open.
Language Tag Propagation Errors
What to watch: The inner block inherits the outer block's language tag during extraction, or the outer block loses its tag when the inner block is removed. A Python tutorial block containing a JSON config example gets both blocks labeled python. Guardrail: Assign language tags per-fence, not per-region. Extract each fence's tag independently and validate that inner-block tags differ from outer-block tags when the content semantics require it.
Backtick-Heavy Content Corruption
What to watch: Tutorials explaining markdown or code fences contain literal backtick sequences in prose or code strings. These are misidentified as structural fences, fragmenting the extraction. Guardrail: Require the model to escape or describe backtick sequences inside code blocks using concatenation or placeholder syntax. Validate extraction by counting expected block count from the prompt instruction and flagging mismatches.
Silent Inner Block Omission
What to watch: The extraction pipeline successfully parses outer blocks but drops inner blocks entirely because the regex or parser only captures the first match per region. Documentation ships with missing code examples. Guardrail: Use recursive or stack-based extraction that continues scanning inside captured blocks. Run a post-extraction count check: if the prompt requested N nested examples, verify N inner blocks were extracted.
Whitespace-Only Nesting Confusion
What to watch: The model uses indentation rather than distinct fence lengths to indicate nesting, producing blocks that look nested to humans but are flat to parsers. Extracted output loses hierarchical context. Guardrail: Explicitly forbid indentation-based nesting in the prompt template. Require distinct fence lengths or explicit nesting markers. Validate that extracted blocks carry a depth field and that depth values form a consistent tree.
Evaluation Rubric
Criteria to test the Nested Code Block Extraction prompt before shipping. Each row defines a pass standard, a failure signal, and a concrete test method.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Fence Depth Tracking | Outer block depth=0, inner block depth=1. Depth increments correctly for each nested level. | Depth counter is off by one or resets to zero inside a nested block. | Feed a response with 3 levels of nesting. Assert output array has correct depth values for each block. |
Delimiter Pair Matching | Every opening fence has a corresponding closing fence with the same backtick count. | An inner block's closing fence closes an outer block, or a block is left unclosed. | Parse a response with deliberately misaligned fences (e.g., outer `````, inner ```). Assert extraction fails with a specific error code. |
Inner Block Content Preservation | Inner block content is extracted as a complete, unmodified string, including its own fences. | Inner block content is truncated, or its fences are stripped and treated as part of the outer block. | Use a golden file with a known inner block. Assert the extracted inner content matches the golden file byte-for-byte. |
Outer Block Content Exclusion | Outer block content excludes the inner block's fences and content, represented as a placeholder token. | Outer block content includes the raw inner block, duplicating it in the output. | Extract blocks from a nested example. Assert the outer block's content string does not contain the inner block's raw text. |
Language Tag Inheritance | If an inner block lacks a language tag, it inherits the tag from its parent block. | Untagged inner blocks are assigned 'text' or null, breaking syntax highlighting in the target system. | Provide nested blocks where only the outer block has a language tag. Assert the inner block's language field matches the outer block's. |
Max Depth Exhaustion | Extraction stops at a configurable [MAX_DEPTH] and returns a warning for omitted deeper blocks. | The prompt attempts to extract beyond [MAX_DEPTH], causing a timeout or malformed output. | Set [MAX_DEPTH]=2. Feed a response with 4 nested levels. Assert the output contains exactly 2 levels and a warning flag. |
Unclosed Inner Block Recovery | If an inner block is unclosed, it is extracted as a partial block with a confidence score < 1.0. | An unclosed inner block consumes the rest of the response, or the entire extraction fails. | Feed a response where an inner block is missing its closing fence. Assert a partial block is returned with confidence < 1.0. |
Adjacent Sibling Blocks | Two sibling blocks at the same depth are extracted as separate entries with correct sequential indices. | Sibling blocks are merged into one, or their order is reversed. | Feed a response with two adjacent inner blocks inside one outer block. Assert the output array contains two distinct inner blocks with sequential indices. |
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
Start with the base extraction prompt and a simple fence-depth counter. Use a single pass that identifies opening and closing fences, tracks nesting level, and emits inner and outer blocks separately. Skip language tag validation and metadata parsing initially.
codeExtract all fenced code blocks from [INPUT]. Track fence depth. Output JSON with `blocks` array where each block has `content`, `depth`, and `fence_type`.
Watch for
- Single-backtick inline code misclassified as fenced blocks
- Unmatched closing fences causing depth underflow
- Blocks where inner fence uses same delimiter count as outer fence

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