Learning Center/Beginner Track/Lesson 2
BeginnerLesson 2 of 5~10 min read

The anatomy of a structured
prompt

Lesson 1 taught you what to include in a prompt. This lesson teaches you how to organize it. You'll learn a 6-section template, delimiter patterns, and walk away with 3 copy-paste templates you can use immediately.

The Insight

A prompt is a document, not a sentence

Most people write prompts like text messages — one unbroken paragraph that mixes the request, constraints, context, and desired format into a single stream of consciousness.

Effective prompts look more like well-organized documents. They have clear sections, each serving a distinct purpose. The AI can parse sectioned prompts more accurately because each instruction type is isolated and unambiguous.

Unstructured
I need you to be a TypeScript expert and help me write a middleware for rate limiting in my Express app. It should use Redis and allow 100 req/min per IP. Return just the code, use no external rate limit libraries, and make sure it returns 429 status with a Retry-After header. Also add tests please.
Structured
## SYSTEM You are a senior TypeScript engineer. ## CONTEXT Express 4 app, Redis via ioredis. ## TASK Write rate-limit middleware: 100 req/min/IP. Return 429 + Retry-After header on limit. ## RULES No external rate-limit libs. Include tests. ## OUTPUT Two code blocks: middleware.ts, middleware.test.ts

Same information, different structure. Both prompts contain the same requirements. But the structured version is scannable, unambiguous, and easier for the AI to parse into distinct instructions. Sections eliminate the guesswork.

The Template

Six sections of a complete prompt

Not every prompt needs all six. But knowing the full anatomy lets you pick the right sections for each situation. Think of this as the maximum template — scale down as needed.

S
C
T
R
O
E
recommended order
S

System / Role

01

Set the AI's identity and expertise level. This anchors everything that follows — a 'senior security engineer' interprets the same task differently than a 'junior frontend developer'.

## SYSTEM You are a senior backend engineer specializing in Node.js microservices and distributed systems. You write production-grade code with comprehensive error handling.
TIP:Place this first. It primes the AI's 'mindset' before it reads anything else.
C

Context

02

Provide background the AI can't infer: your tech stack, what you've tried, existing constraints, team conventions. Think of it as the briefing document before a meeting.

## CONTEXT - Project: E-commerce platform (Next.js 14, TypeScript, Prisma) - Database: PostgreSQL on Supabase - Auth: NextAuth with GitHub + Google providers - Current issue: Cart totals are inconsistent during high traffic - We follow the repository pattern with service layers
TIP:Bullet points > paragraphs. The AI parses structured context faster and more accurately.
T

Task

03

The core instruction. Be precise about the action, scope, and acceptance criteria. A good task section reads like a well-written ticket — anyone could pick it up and deliver the right thing.

## TASK Refactor the CartService to use optimistic locking for concurrent updates: 1. Add a version column to the Cart model 2. Implement compareAndSwap logic in updateCartItem() 3. Add retry logic (max 3 attempts) on version conflict 4. Ensure all cart operations are wrapped in transactions
TIP:Number your requirements. It forces clarity and makes it easy to verify the AI hit every point.
R

Rules & Constraints

04

Guardrails that prevent the AI from going off-track. Include what to avoid, performance requirements, style guidelines, and hard limits. Constraints focus the output dramatically.

## RULES - No external dependencies — use only packages already in package.json - All functions must have JSDoc comments - Maximum file length: 150 lines (split if needed) - Do NOT use any deprecated Prisma APIs - Error messages must be user-friendly (no stack traces in responses)
TIP:Negative constraints ('do NOT...') are as valuable as positive ones. They prevent common AI pitfalls.
O

Output Format

05

Specify exactly what the deliverable looks like: file structure, language, format, length, sections. This is the difference between getting raw text you need to reshape vs. getting exactly what you need.

## OUTPUT FORMAT Return your response as: 1. A single TypeScript file with the refactored CartService 2. A Prisma migration file for the schema change 3. A brief CHANGELOG entry (1-2 lines) Use code blocks with filenames. Do not include explanatory text between files.
TIP:The more specific your format, the less post-processing you need. Specify file names, code block languages, even comment styles.
E

Examples

06

Show the AI what good output looks like. Even one example dramatically improves consistency. This is called 'few-shot prompting' — you're teaching by demonstration, not just description.

## EXAMPLE Here's how a similar refactored service looks in our codebase: ```typescript export class OrderService { /** Process a new order with inventory validation */ async create(dto: CreateOrderDto): Promise<Order> { return this.prisma.$transaction(async (tx) => { const inventory = await tx.inventory.findUnique(...); if (!inventory) throw new AppError('ITEM_NOT_FOUND'); // ... rest of implementation }); } } ``` Follow this pattern for the CartService.
TIP:Examples beat instructions. If you can show what you want, always prefer that over describing it.

Technique

Delimiter patterns

How you separate sections matters. Delimiters create visual and semantic boundaries that help the AI parse your intent. Here are the four most effective patterns.

Markdown Headers

Recommended
## SECTION NAME

Clean, readable, universally understood

XML Tags

<context>...</context>

Best for nesting and complex multi-part prompts

Triple Dashes

---

Simple visual separator between blocks

Labeled Blocks

[ROLE]: ... [TASK]: ...

Compact format good for shorter prompts

Pick one and be consistent. Mixing delimiter styles within a single prompt confuses the AI about where sections begin and end. We recommend Markdown headers (##) for most use cases — they're clean, universally understood, and render nicely if you store prompts as documentation.

Templates

Copy, paste, customize

Three battle-tested templates built on the 6-section anatomy. Copy the one that fits your task, fill in the [BRACKETS], and send it. Each template is designed for a common developer workflow.

Build

Feature Builder

For building new features, components, or modules from scratch.

## SYSTEM You are a senior [LANGUAGE/FRAMEWORK] developer building production-grade software. ## CONTEXT - Project: [Brief description] - Stack: [Languages, frameworks, key libraries] - Relevant existing code: [Paste or describe patterns to follow] - Conventions: [Naming, file structure, testing approach] ## TASK Build [specific feature] that: 1. [Requirement 1 with acceptance criteria] 2. [Requirement 2 with acceptance criteria] 3. [Requirement 3 with acceptance criteria] ## RULES - Follow existing code patterns and naming conventions - No new dependencies unless absolutely necessary - Include error handling for [specific edge cases] - [Any performance/security constraints] ## OUTPUT FORMAT Return: 1. [Primary file(s) with path] 2. [Test file(s) with path] 3. Brief summary of design decisions ## EXAMPLE [Paste a similar feature from your codebase as reference]
Debug

Bug Hunter

For diagnosing and fixing bugs with root cause analysis.

## SYSTEM You are a debugging specialist for [STACK]. You find root causes, not surface-level fixes. ## CONTEXT - Application: [What the app does] - Environment: [Dev/staging/prod, OS, runtime version] - Bug behavior: [What happens vs. what should happen] - Reproduction steps: 1. [Step 1] 2. [Step 2] 3. [Step 3] - What I've tried: [Previous debugging attempts] ## TASK 1. Analyze the code below and identify the root cause 2. Explain WHY this bug occurs (not just what to change) 3. Provide the fix as a minimal diff 4. Suggest a preventive pattern to avoid similar bugs ## CODE ```[language] [Paste the relevant code here] ``` ## RULES - Do not refactor unrelated code - The fix must be backward-compatible - Explain your reasoning before showing the fix ## OUTPUT FORMAT ### Root Cause [1-2 sentences] ### Why It Happens [Technical explanation] ### Fix [Code diff] ### Prevention [Pattern or lint rule to prevent recurrence]
Review

Code Reviewer

For thorough code reviews with actionable feedback.

## SYSTEM You are a principal engineer conducting a code review. You balance pragmatism with quality — flag real issues, not style nitpicks. ## CONTEXT - Project: [Brief description] - This PR: [What the code change does] - Author level: [Junior/mid/senior — adjusts feedback tone] - Priority: [What matters most — security? performance? readability?] ## TASK Review the following code for: 1. Correctness — logic errors, edge cases, off-by-one errors 2. Security — injection, auth bypass, data exposure 3. Performance — N+1 queries, unnecessary re-renders, memory leaks 4. Maintainability — naming, complexity, test coverage gaps ## CODE ```[language] [Paste the code to review] ``` ## RULES - Max 5 comments (focus on highest impact) - Each comment must include: severity (critical/suggestion), the line or section, and a concrete fix - Do NOT flag minor style issues or formatting - Praise one thing that's done well ## OUTPUT FORMAT ### Summary [1-sentence overall assessment] ### Issues | # | Severity | Location | Issue | Suggested Fix | |---|----------|----------|-------|---------------| | 1 | ... | ... | ... | ... | ### What's Done Well [1 specific positive observation]

Practice

Your turn

Take this single-sentence prompt and expand it into a full 6-section structured prompt. Use the sections you learned above.

Expand this prompt
"Write tests for my authentication module."

Checklist — fill in each section:

SWhat testing expertise should the AI have?
CWhat framework? What does the auth module do?
TUnit tests? Integration? Which flows to cover?
RNo mocking the database? Min coverage %?
OJest? Vitest? File structure for test files?
EShow an example test from your existing suite?

Key Takeaways

Remember this

01

Sections > sentences

Break your prompt into labeled sections. The AI parses isolated instructions more accurately than a wall of text.

02

Templates save time

Start with a template, then customize. You'll write better prompts in half the time once you stop starting from scratch.

03

Examples are the secret weapon

Section 6 (Examples) is optional but powerful. One concrete example teaches the AI more than three paragraphs of instructions.