Lesson 2 of 8

Prompt Structure & Anatomy

Components of effective prompts: instructions, context, examples, and constraints

The Anatomy of an Effective Prompt

A well-structured prompt typically contains several key components. Understanding these components helps you craft prompts that consistently produce high-quality outputs.

🧩 The Four Core Components

  • 1. Instructions: What you want the model to do (the task)
  • 2. Context: Background information to inform the response
  • 3. Examples: Demonstrations of desired input/output patterns
  • 4. Constraints: Boundaries, format requirements, and limitations

1. Instructions (The Task)

Instructions tell the model exactly what you want it to do. Be specific and use action verbs.

// ❌ Vague Instruction
"JavaScript arrays"

// ✅ Clear Instruction
"Explain the difference between map, filter, and reduce 
in JavaScript with a code example for each."

// ❌ Ambiguous
"Help with my code"

// ✅ Specific
"Debug this function to fix the infinite loop:
[code]
Explain what's causing the loop and provide a corrected version."

// Power Verbs for Instructions:
// - Explain, Describe, Compare, Analyze
// - Write, Create, Generate, Build
// - Convert, Transform, Translate, Refactor
// - List, Summarize, Outline, Categorize
// - Debug, Fix, Optimize, Improve
// - Review, Critique, Evaluate, Assess

2. Context (Background Information)

Context provides the information the model needs to give a relevant, accurate response.

// ❌ No Context
"How do I fix this error?"

// ✅ With Context
"I'm building a Next.js 14 app with the App Router.
I'm using TypeScript and Prisma for the database.

When I try to fetch data in a Server Component, I get:
Error: PrismaClient is not configured for edge runtime

My setup:
- Vercel Edge Functions
- Prisma 5.x
- PostgreSQL database

How do I fix this error?"

// Context Types to Include:
// - Technology stack (languages, frameworks, versions)
// - Environment (production, development, edge, serverless)
// - User type (who you're building for)
// - Prior attempts (what you've already tried)
// - Constraints (time, resources, requirements)

3. Examples (Demonstrations)

Examples show the model exactly what kind of output you want. This is called "few-shot prompting."

// Provide input/output examples

"Convert the following company descriptions into taglines.

Example 1:
Company: We make project management software for remote teams
Tagline: Work together, anywhere

Example 2:
Company: We provide AI-powered code review tools
Tagline: Ship better code, faster

Now convert this:
Company: We build accessible design systems for enterprise apps
Tagline:"

// For Code Generation
"Generate TypeScript interfaces from these examples:

Example Input:
{ "name": "John", "age": 30, "email": "john@example.com" }

Example Output:
interface User {
  name: string;
  age: number;
  email: string;
}

Now generate an interface for:
{ "id": 1, "title": "Hello", "published": true, "tags": ["tech", "ai"] }"

4. Constraints (Boundaries)

Constraints define the boundaries of the response: format, length, style, what to include or avoid.

// Format Constraints
"Return your answer as a JSON object with this structure:
{
  "summary": "...",
  "keyPoints": [...],
  "recommendation": "..."
}"

// Length Constraints
"Summarize this article in exactly 3 bullet points."
"Keep your response under 100 words."
"Provide a detailed explanation (at least 500 words)."

// Style Constraints
"Write in a conversational, friendly tone."
"Use technical language appropriate for senior developers."
"Explain like I'm a beginner with no programming experience."

// Inclusion/Exclusion Constraints
"Include code examples in TypeScript."
"Don't include any external library dependencies."
"Focus only on performance, not code style."
"Avoid deprecated APIs."

// Combined Constraints Example
"Review this React component. Your response should:
- Be under 200 words
- Focus on accessibility issues only
- Include specific WCAG guidelines violated
- Provide code fixes for each issue
- Use plain language, no jargon"

Putting It All Together

// Complete Prompt Template
/*
[ROLE/PERSONA - optional]
[CONTEXT - background information]
[INSTRUCTIONS - the task]
[EXAMPLES - demonstrations]
[CONSTRAINTS - boundaries and format]
[INPUT - the actual content to process]
*/

// Real Example: API Documentation Generator

"You are a technical writer specializing in API documentation.

CONTEXT:
I'm building a REST API for an e-commerce platform.
The API uses Express.js with TypeScript.
Documentation will be read by frontend developers.

TASK:
Generate API documentation for the following endpoint.

FORMAT:
Use this structure for the documentation:
- Endpoint: [method] [path]
- Description: [what it does]
- Parameters: [table of params]
- Request Body: [JSON schema]
- Response: [success and error examples]
- Example: [curl command]

CONSTRAINTS:
- Keep descriptions concise (1-2 sentences)
- Include TypeScript types for request/response
- Show both success (200) and error (400, 404) responses

ENDPOINT CODE:
```typescript
router.post('/products', async (req, res) => {
  const { name, price, category } = req.body;
  const product = await Product.create({ name, price, category });
  res.status(201).json(product);
});
```"

Prompt Templates

// Template 1: Code Generation
const codeGenPrompt = `
Write a [LANGUAGE] function that [TASK].

Requirements:
- [REQUIREMENT 1]
- [REQUIREMENT 2]

Include:
- Type annotations
- Error handling
- JSDoc comments

Example usage:
[EXAMPLE]
`;

// Template 2: Code Review
const reviewPrompt = `
Review this code for:
1. Bugs and edge cases
2. Performance issues
3. Best practices

For each issue:
- Quote the problematic code
- Explain the problem
- Provide a fix

Code:
[CODE]
`;

// Template 3: Explanation
const explainPrompt = `
Explain [CONCEPT] to a developer who [BACKGROUND].

Include:
- Simple definition
- Real-world analogy
- Code example
- Common use cases
- Common mistakes to avoid

Keep it under [WORD COUNT] words.
`;

✅ Structure Best Practices

  • • Put the most important information first
  • • Use clear section headers or labels
  • • Be explicit about format (JSON, markdown, code, etc.)
  • • Include both positive (do this) and negative (don't do this) instructions
  • • Use delimiters like triple backticks or XML tags to separate sections
  • • Test and iterate on your prompt structure