Books/Prompt Engineering Essentials/Anatomy of a Good Prompt

    Anatomy of a Good Prompt

    Anatomy of a Good Prompt

    Every effective prompt is built from the same five components. You don't always need all five, but knowing them gives you a reliable framework for writing prompts that consistently produce great results.

    The Five Components

    ComponentWhat It DoesExample
    RoleTells the AI who to be"You are a senior React developer"
    TaskWhat you want done"Write a custom hook for form validation"
    ContextBackground information"The app uses TypeScript and Zod for schemas"
    FormatHow the output should look"Return the code with JSDoc comments"
    ConstraintsLimits and boundaries"No external libraries. Keep it under 50 lines"

    Let's explore each one in detail.

    1. Role — Who Should the AI Be?

    Setting a role activates a specific "mode" in the AI's responses. It changes the vocabulary, depth, and perspective of the output.

    You are a senior backend engineer with 10 years of experience
    in Node.js and PostgreSQL.
    
    You are a patient programming tutor who explains concepts to
    complete beginners using simple analogies.
    
    You are a technical writer who creates clear, concise API
    documentation following the Diataxis framework.
    

    Why it matters: Without a role, the AI defaults to a generic "helpful assistant" voice. With a role, it tailors the response to that persona's expertise and communication style.

    Role Tips

    • Be specific: "senior React developer" is better than "programmer"
    • Include experience level: it changes the depth of the response
    • Add personality when useful: "patient," "concise," "detail-oriented"

    2. Task — What Do You Want Done?

    The task is the core of your prompt. Make it unambiguous. Use action verbs: write, explain, compare, analyze, refactor, debug, create, list, summarize.

    Weak tasks:

    Help me with authentication
    Tell me about databases
    Make this better
    

    Strong tasks:

    Write a login function using Firebase Authentication that supports
    both Google sign-in and email/password.
    
    Compare Firestore and PostgreSQL for a real-time chat application.
    List pros and cons of each in a table.
    
    Refactor this function to reduce its cyclomatic complexity from 12 to
    under 5. Extract helper functions as needed.
    

    3. Context — What Does the AI Need to Know?

    Context is the background information that shapes the response. The more relevant context you provide, the better the output.

    Types of context you can include:

    • Technology stack: "Using Next.js 14, TypeScript, Tailwind CSS, and Firebase"
    • Current situation: "The app currently has 500 users and is growing 20% monthly"
    • Existing code: Paste relevant code snippets
    • Error messages: Include the full error and stack trace
    • Audience: "This documentation is for junior developers new to APIs"
    • Previous attempts: "I tried X but it didn't work because Y"
    Context: I'm building a SaaS application with Next.js 14 (App Router),
    TypeScript, and Firebase. The app has user authentication with Google
    sign-in. Users belong to organizations, and each organization has
    multiple projects. I need to implement role-based access control
    where users can be "admin," "editor," or "viewer" within an organization.
    

    4. Format — How Should the Output Look?

    Telling the AI how to structure its response prevents rambling and makes the output immediately usable.

    Common format instructions:

    - Respond with only the code, no explanations
    - Format as a markdown table with columns: Feature, Pros, Cons
    - Return valid JSON matching this schema: { name: string, items: string[] }
    - Use bullet points, not paragraphs
    - Write step-by-step instructions numbered 1 through N
    - Include code comments explaining each section
    - Provide the answer in under 200 words
    

    Example with format:

    Compare React, Vue, and Svelte for building a component library.
    
    Format your response as a markdown table with these columns:
    | Framework | Learning Curve | Performance | Ecosystem | Best For |
    
    Follow the table with a 2-sentence recommendation.
    

    5. Constraints — What Should the AI Avoid?

    Constraints prevent common problems: outputs that are too long, use the wrong tools, or miss important requirements.

    Constraints:
    - Do not use any external libraries
    - The function must be pure (no side effects)
    - Keep the response under 300 words
    - Do not include deprecated APIs
    - Use only ES2020+ syntax
    - Handle edge cases: empty input, null values, arrays with 0 or 1 element
    

    Constraints are especially useful when you have seen the AI make mistakes before. Each constraint is a guardrail that keeps the output on track.

    Before and After: Full Prompt Improvements

    Example 1: Building a Feature

    Before (vague):

    Add search to my app
    

    After (structured):

    Role: You are a senior frontend developer experienced with React and TypeScript.
    
    Task: Build a search component that filters a list of products in real time
    as the user types.
    
    Context: The app uses React 18, TypeScript, and Tailwind CSS. Products are
    stored in a state array with this shape:
    { id: string; name: string; category: string; price: number }
    
    Format: Provide the complete component code with:
    - A styled search input with a magnifying glass icon
    - Debounced input (300ms delay)
    - Case-insensitive search across name and category fields
    - "No results found" message when the filter returns empty
    
    Constraints:
    - Do not use any external search libraries
    - Use React hooks (useState, useMemo, useCallback)
    - Component must be accessible (proper ARIA labels)
    

    Example 2: Writing Documentation

    Before:

    Document this function
    

    After:

    Role: You are a technical writer who creates developer documentation.
    
    Task: Write documentation for the following function.
    
    Context:
    [paste the function code here]
    
    Format:
    - Start with a one-sentence summary
    - Add a "Parameters" section as a table (name, type, description)
    - Add a "Returns" section
    - Include 2-3 usage examples with different inputs
    - Add a "Throws" section listing possible errors
    
    Constraints:
    - Use JSDoc format
    - Keep examples realistic, not "foo/bar" placeholders
    

    The Universal Prompt Template

    Here is a template you can copy and adapt for any task:

    Role: You are a [specific role with relevant expertise].
    
    Task: [Clear action verb] [specific deliverable].
    
    Context:
    - [Technology stack / environment]
    - [Current situation / background]
    - [Any relevant code, errors, or data]
    
    Format:
    - [How the output should be structured]
    - [Length, style, or presentation requirements]
    
    Constraints:
    - [What to avoid]
    - [Limitations and boundaries]
    - [Edge cases to handle]
    

    You do not need every section every time. For simple questions, Task alone might be enough. But when the output matters, using more components consistently produces better results.

    Quick Decision Guide

    SituationComponents to Use
    Quick factual questionTask only
    Code generationRole + Task + Context + Constraints
    DebuggingTask + Context (code + error)
    Learning a conceptRole (tutor) + Task + Format
    Complex featureAll five components
    Content generationRole + Task + Format + Constraints

    Try it now: Take a task you need to accomplish with AI. Write the prompt using all five components. Notice how much more specific and useful the output becomes compared to a quick, unstructured request.


    🌐 www.genai-mentor.ai