This prompt is designed for developers and platform engineers building project scaffolding tools that consume AI-generated code. The core job is to take a raw model response containing multiple fenced code blocks with file path annotations, extract each block, and reconstruct the intended project directory structure. Use this when your application needs to turn a single AI response into a set of files ready for disk write operations, version control staging, or downstream CI/CD processing. The ideal user is integrating a coding agent, documentation generator, or tutorial builder where the model produces multi-file output in one turn.
Prompt
Extract Code Blocks and Generate File Tree Prompt Template

When to Use This Prompt
Define the job, reader, and constraints for extracting code blocks and generating a project file tree from AI responses.
Do not use this prompt when the AI response contains only a single file, when file paths are already known and managed by an external orchestrator, or when the primary need is streaming partial blocks for real-time rendering. This prompt assumes batch processing of complete responses. It is also inappropriate for responses where code blocks represent examples or alternatives rather than a cohesive project—using it there will produce a nonsensical file tree with conflicting or orphaned files. The prompt requires that the input model response uses fenced code blocks with explicit file path annotations, either as language tag suffixes or as preceding markdown comments.
Before implementing, ensure your application layer can handle the output: a validated file tree object with directory nodes, file leaf nodes, and content payloads. You must also implement safety checks for path traversal attacks, duplicate file targets, and missing parent directories. If the model response is ambiguous—for example, two blocks claim the same file path or a file has no parent directory—the prompt should flag these for human review rather than silently overwriting or creating orphaned files. Wire the output into a validation step that confirms file count consistency, checks for circular references, and verifies that every code block maps to exactly one file path before any disk write occurs.
Use Case Fit
Where the Extract Code Blocks and Generate File Tree prompt works for project scaffolding and where it fails. Use these cards to decide if this prompt fits your pipeline before you invest in integration.
Good Fit: Single-Response Multi-File Scaffolding
Use when: the model generates a complete project skeleton in one response with explicit file paths in fenced code blocks. Guardrail: validate that every extracted block has a unique, non-conflicting path before writing to disk. Reject the entire scaffold if any path collision is detected.
Bad Fit: Streaming or Incremental Generation
Avoid when: the model emits files across multiple streaming chunks or conversational turns. Guardrail: use a stateful accumulator to buffer all blocks before tree assembly. If the response is split across turns, require an explicit 'scaffold complete' signal before triggering file creation.
Required Input: Explicit File Paths per Block
Risk: code blocks without file path annotations produce orphaned files or force guesswork. Guardrail: the prompt must require a path comment or metadata line above every fenced block. Reject blocks missing path annotations and return them to the model for correction rather than guessing.
Operational Risk: Path Traversal and Overwrite
What to watch: model-generated paths containing ../, absolute paths, or symlink targets that escape the intended project root. Guardrail: normalize all paths, reject any that resolve outside the target directory, and require explicit user confirmation before overwriting existing files. Log every file write for audit.
Validation Gate: File Count Consistency
Risk: the model claims N files but produces N-1 blocks, or generates duplicate paths that silently overwrite content. Guardrail: count extracted blocks, compare against any stated file count in the response, and flag mismatches. If the model declares '5 files' but only 4 are extractable, fail the scaffold and request regeneration.
Degradation Mode: Missing Parent Directories
Risk: deeply nested file paths where intermediate directories are never explicitly created. Guardrail: after extracting all paths, compute the minimal set of directories required, create them before writing files, and report any gaps. If a file targets src/utils/helpers/string.ts but src/utils/ is missing, create the full tree rather than failing mid-write.
Copy-Ready Prompt Template
A reusable prompt template with square-bracket placeholders for extracting code blocks and generating a project file tree from an AI response.
This prompt template is the core instruction set for a project scaffolding tool. It directs the model to parse a raw AI response, extract all fenced code blocks with their associated file paths, infer a complete directory structure, and output a validated file tree. The template is designed to be copied directly into your application's system prompt or a dedicated extraction step. It uses square-bracket placeholders for all dynamic inputs, ensuring you can adapt it to different source materials and output requirements without rewriting the core logic.
textYou are a precise code block extraction and file tree generation engine. Your task is to process the provided [INPUT_TEXT] and produce a structured output. [INPUT_TEXT]: """ [RAW_MODEL_RESPONSE] """ [OUTPUT_SCHEMA]: You must output a single valid JSON object conforming to this structure: { "project_name": "string", // inferred from context or 'extracted-project' "file_tree": [ { "path": "string", // relative file path, e.g., 'src/utils/helpers.py' "content": "string", // the exact code block content "language": "string" // the language tag from the fenced code block } ], "warnings": ["string"] // list of any issues found, e.g., orphaned files, missing parent directories } [CONSTRAINTS]: 1. Parse all fenced code blocks (```) in [RAW_MODEL_RESPONSE]. 2. A code block's file path is determined by the first line immediately preceding the opening fence, which must match the pattern: `// File: [FILE_PATH]` or `# File: [FILE_PATH]`. 3. If a code block has no valid file path comment, add a warning to the "warnings" array and skip the block. 4. Infer the full directory tree from all extracted file paths. Create a flat list of file objects in "file_tree". 5. Detect and report any conflicting path assignments (two blocks for the same file) in "warnings". 6. Do not create content for missing parent directories; just note them in "warnings". 7. The output must be strictly valid JSON with no additional text outside the JSON object.
To adapt this template, replace the [RAW_MODEL_RESPONSE] placeholder with the actual text output from your primary coding agent or LLM call. You can tighten the [CONSTRAINTS] by adding rules for specific language tags, handling nested fences, or enforcing a maximum file count. For high-risk operations where the file tree will be written directly to disk, always add a validation step in your application harness to check for path traversal attacks (e.g., paths containing ../) and to confirm that the target directory is within an allowed project boundary before any file write occurs.
Prompt Variables
Inputs the Extract Code Blocks and Generate File Tree prompt needs to reliably parse AI responses, infer directory structures, and produce a validated file tree. Use these placeholders when constructing your prompt template.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[RAW_MODEL_RESPONSE] | The complete text output from the model containing fenced code blocks with file path annotations |
| Must be a non-empty string. Validate that the input contains at least one fenced code block. If empty, return an empty file tree with a warning. |
[FILE_PATH_PATTERN] | Regex or pattern used to identify file path declarations associated with code blocks | File: src/utils/helpers.py | Must compile as a valid regex. Test against common path formats including relative paths, absolute paths, and paths with spaces. Default pattern should match |
[LANGUAGE_ALIAS_MAP] | Mapping of language tag aliases to canonical file extensions for file naming fallback | {"py": ".py", "javascript": ".js", "sh": ".sh"} | Must be a valid JSON object. Keys should be lowercase language identifiers. Used only when a code block lacks an explicit file path. Validate that all values start with a dot. |
[ROOT_DIRECTORY] | Base directory under which all extracted files will be organized | generated_project/ | Must be a non-empty string ending with a forward slash. Validate that the path does not contain path traversal sequences like |
[MAX_DEPTH] | Maximum allowed directory depth for the generated file tree to prevent runaway nesting | 5 | Must be a positive integer between 1 and 20. Files or directories exceeding this depth should be flagged as errors and excluded from the tree. Prevents zip bomb-style path attacks. |
[ALLOWED_EXTENSIONS] | Whitelist of file extensions permitted for extraction and file creation | [".py", ".js", ".ts", ".yaml", ".json", ".md"] | Must be a valid JSON array of strings, each starting with a dot. If null or empty, allow all extensions. Use to block executable or sensitive file types from being written to disk. |
[CONFLICT_RESOLUTION] | Strategy for handling duplicate file paths or conflicting path assignments | error | Must be one of: |
[REQUIRE_PARENT_DIRS] | Whether to automatically create missing parent directories for extracted files | Must be a boolean. When true, missing directories are created. When false, files with missing parent directories are flagged as orphaned and excluded from the tree. Validate type coercion. |
Implementation Harness Notes
How to wire the file-tree extraction prompt into a project scaffolding app or coding agent workflow.
Integrating the extract-code-blocks-and-generate-file-tree prompt into an application requires treating the LLM call as one step in a deterministic pipeline. The prompt itself is designed to produce a structured JSON output containing a fileTree object and a validation report. Your application code, not the model, must own the final file-system writes. Before any disk operation, parse the model's JSON output and run the following application-level checks: reject any file path that contains .. traversal sequences, absolute paths, or characters outside the allowed set for your target operating system. The model's validation.orphanedFiles and validation.conflictingPaths arrays are advisory signals—your harness must treat them as blocking errors that prevent file creation until resolved, either by re-prompting with the specific conflict details or by surfacing the ambiguity to a human reviewer in the scaffold review UI.
Build a retry loop around the prompt call that catches JSON parse failures and schema validation errors. If the model returns malformed JSON, feed the raw output and the parse error message into a repair prompt from the Output Repair and Validation Prompts pillar, requesting a corrected JSON object conforming to the original schema. Set a maximum of two repair attempts before surfacing the failure to the user. For model choice, prefer models with strong JSON mode and structured output guarantees (e.g., GPT-4o with response_format set to json_schema, or Claude 3.5 Sonnet with tool-use extraction). Avoid models with known weaknesses in nested bracket balancing for this task. Log every extraction attempt—including the raw model response, the parsed file tree, validation warnings, and any repair steps—to an observability store keyed by a scaffold_run_id. This trace becomes essential for debugging silent failures where a file is created in the wrong location or with truncated content.
Before integrating this prompt into a production coding agent, implement a dry-run mode that performs all extraction, validation, and conflict detection but writes the proposed file tree to a review artifact instead of disk. This allows you to measure extraction accuracy against a golden dataset of AI-generated project structures. Track precision (did we create only intended files?), recall (did we miss any files the model described?), and path assignment accuracy (did every code block land in its declared directory?). If your application allows users to edit the proposed file tree before confirming, capture those corrections as preference data that can inform future fine-tuning or prompt adjustments. Avoid the common failure mode of trusting the model's file count without cross-referencing: always compare the number of extracted code blocks against the count of files in the generated tree and flag discrepancies for review.
Expected Output Contract
Defines the shape, types, and validation rules for the output of the Extract Code Blocks and Generate File Tree prompt. Use this contract to build a parser that validates the model's response before any file system operations are performed.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
file_tree | object | Must be a single JSON object. Top-level keys are directory names. Reject if not parseable as JSON. | |
file_tree.<directory> | object | string | If value is a string, it is a file path relative to the key. If an object, it is a subdirectory. Reject empty string keys. | |
file_tree.<directory>.<filename> | string | Value must be the full, unescaped content of the code block. Null or empty string is allowed only if the file is intentionally empty. | |
extracted_blocks | array | Must be an array of objects. Reject if missing or not an array. Length must match the number of files in file_tree. | |
extracted_blocks[].file_path | string | Must be a relative path string. Must exactly match a leaf-node path in file_tree. Reject if absolute path or contains '..' traversal. | |
extracted_blocks[].language | string | null | Must be a string if a language tag was present in the fence, otherwise null. Validate against a known list of language identifiers. | |
extracted_blocks[].content | string | Must be the raw string content inside the code fence. Reject if content contains the opening or closing fence delimiter. | |
orphaned_blocks | array | Must be an array of objects for any extracted code block that could not be assigned to a file path. Must be empty if all blocks are assigned. Validate length + extracted_blocks length equals total fenced blocks found. |
Common Failure Modes
What breaks first when extracting code blocks and generating a file tree, and how to guard against it.
Broken or Mismatched Fences
What to watch: The model uses inconsistent backtick counts, mixes tildes with backticks, or omits the closing fence entirely. This causes the parser to merge adjacent blocks or drop content. Guardrail: Implement a fence-normalization step that standardizes all fences to triple backticks before extraction. Add a recovery pass that treats end-of-response as an implicit fence close, logging a warning for each auto-closed block.
Missing or Ambiguous Language Tags
What to watch: Code blocks arrive without language identifiers, or the tag is too generic (shell vs bash, python vs python3). Downstream file-tree generation then assigns incorrect extensions or skips blocks. Guardrail: Maintain a canonical language-to-extension map. When a tag is missing, run a content-based language detection fallback. If confidence is below 90%, flag the block for human review and default to .txt rather than guessing.
Orphaned File Paths and Missing Directories
What to watch: The model specifies file paths like src/utils/helpers.py without including the parent directories in the file tree. The generated scaffold has files floating outside any directory structure. Guardrail: After extracting all file paths, compute the set of required parent directories. Auto-create any missing directories in the output tree and emit a missing_parent warning for each one so the user can verify the intended structure.
Conflicting Path Assignments
What to watch: Two code blocks claim the same file path, or a block is assigned to both a file and a directory path. The file tree becomes ambiguous and the last-write-wins behavior silently drops content. Guardrail: Before writing the file tree, check for duplicate path targets. If duplicates are found, either merge the content with conflict markers or abort and return a structured error listing every conflicting path for manual resolution.
Path Traversal and Unsafe File Paths
What to watch: The model generates paths containing ../, absolute paths like /etc/config, or symlink-adjacent patterns that could write outside the intended project root. Guardrail: Validate every extracted path against a whitelist of allowed prefixes. Reject any path containing .. segments or starting with /. Normalize paths and resolve them relative to a sandbox root, throwing a hard error if the resolved path escapes the root.
File Count and Content Length Mismatch
What to watch: The model's introductory text claims "5 files" but only 3 code blocks are extracted, or a block is truncated mid-expression. The generated file tree silently omits files or contains broken code. Guardrail: After extraction, compare the expected file count from any summary text against the actual extracted count. Log a discrepancy warning. Additionally, run a completeness check on each block: if it ends mid-expression (unclosed braces, unterminated strings), flag it for review.
Evaluation Rubric
Criteria for testing output quality before shipping the Extract Code Blocks and Generate File Tree prompt. Run these checks against a golden dataset of 20-50 AI responses containing mixed code blocks, file paths, and edge cases.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
File Tree Completeness | Every file path extracted from code blocks appears in the generated tree with correct parent directories | Orphaned file entries or missing intermediate directories in the output tree | Parse the output tree structure and verify that for every extracted file path, all ancestor directories exist in the tree object |
File Count Consistency | The total number of files in the generated tree equals the number of code blocks with valid file path annotations | Mismatch between extracted code block count and tree leaf node count | Count code blocks with [FILE_PATH] annotations, count leaf nodes in the generated tree, assert equality |
Path Conflict Resolution | When two code blocks specify the same file path, the prompt resolves the conflict according to the defined strategy without silent data loss | Duplicate file paths in output or missing content from one of the conflicting blocks | Inject test cases with intentional duplicate paths, verify that output contains exactly one entry per path and that conflict resolution matches the specified strategy |
Directory Inference Accuracy | Missing parent directories are correctly inferred from file paths without requiring explicit directory creation instructions | Files placed at root level when their path implies nested directories, or invented directories not implied by any file path | Provide responses with paths like src/utils/helpers.ts without explicit mkdir instructions, verify tree contains src and src/utils nodes |
Empty Directory Handling | The prompt does not invent empty directories that have no corresponding files in the extracted code blocks | Presence of directories in the tree that contain zero files and were not explicitly requested | Audit generated tree for leaf directories with no files, flag any that lack an explicit [CREATE_DIR] marker from the input |
Malformed Path Rejection | File paths containing traversal attempts or invalid characters are flagged rather than silently included in the tree | Tree contains entries with ../, absolute paths, or null bytes | Inject test cases with paths like ../../../etc/passwd and /etc/config, verify these are excluded from output and flagged in a warnings array |
Cross-File Reference Validation | Internal imports and references between extracted files are checked for consistency against the generated tree | Import statements referencing files not present in the tree pass without warning | Provide multi-file responses with inter-file imports, parse import statements, verify each referenced module exists in the tree or appears in a missing-reference warning list |
Output Schema Compliance | The generated output matches the defined [OUTPUT_SCHEMA] with all required fields present and correctly typed | Missing required fields, type mismatches, or extra undocumented fields in the output | Validate output against the JSON Schema definition using a programmatic validator, reject any output that fails schema validation |
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
Use the base prompt with a single model call and minimal post-processing. Accept the raw file tree output and validate only the most critical fields: project_name, files array presence, and file_tree string. Skip strict schema enforcement and allow the model to infer directory structure from file paths without exhaustive validation.
Watch for
- Orphaned files with no parent directory
- Missing
project_namecausing downstream naming failures - File count mismatches between
filesarray andfile_treevisualization - Model inventing directories not implied by file paths

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