Skip to content

Construct Effective Prompts

Build beginner 20 min javascript
Sources not yet verified

Learn to build structured prompts using JavaScript template literals and understand the anatomy of a good prompt.

1. Understand the Scenario

You're building a document summarizer. Before calling any API, you need to construct well-structured prompts that give the model clear context and instructions.

Learning Objectives

  • Understand the components of an effective prompt
  • Use template literals for dynamic prompt construction
  • Structure prompts with system context and user input
  • Handle edge cases in prompt templates

Concepts You'll Practice

2. Follow the Instructions

What You'll Build

A prompt builder that constructs structured prompts for document summarization. You'll learn the anatomy of effective prompts:

  1. System context - Define the assistant's role and constraints
  2. Task instructions - Clear, specific directions
  3. Input formatting - How to present user content
  4. Output formatting - Expected response structure

Step 1: Basic Prompt Template

Start with a simple template literal that combines instructions with user input.

// Simple prompt template
function buildSummaryPrompt(document) {
  return `Summarize the following document in 2-3 sentences:

${document}`;
}

// Try it
const doc = "JavaScript was created in 1995 by Brendan Eich. It was originally called Mocha, then LiveScript.";
console.log(buildSummaryPrompt(doc));

Step 2: Add Structure and Constraints

Real-world prompts need more structure. Add role definition, constraints, and output formatting.

// Structured prompt with constraints
function buildStructuredPrompt(document, options = {}) {
  const { maxSentences = 3, style = 'professional', includeKeyPoints = true } = options;
  
  return `You are a document summarization assistant.

Rules:
- Write exactly ${maxSentences} sentences
- Use ${style} language
${includeKeyPoints ? '- Include the main key points' : ''}

<document>
${document}
</document>

Provide your summary:`;
}

console.log(buildStructuredPrompt("AI assistants are transforming how developers work.", { maxSentences: 2 }));

Your Task

Complete the buildAdvancedPrompt function in the starter code. It should:

  1. Accept document text and configuration options
  2. Build a prompt with system context, formatting rules, and the document
  3. Handle missing or empty documents gracefully
  4. Support multiple output formats (bullets, paragraph, JSON)

3. Try It Yourself

starter_code.ts Interactive
/**
 * Build an advanced summarization prompt
 * @param {string} document - The document to summarize
 * @param {object} options - Configuration options
 * @returns {string} - The formatted prompt
 */
function buildAdvancedPrompt(document, options = {}) {
  // Default options
  const {
    role = 'You are a helpful document analyst.',
    format = 'paragraph',  // 'paragraph', 'bullets', or 'json'
    maxLength = 100,       // Maximum words
    audience = 'general'   // 'general', 'technical', 'executive'
  } = options;

  // TODO: Handle empty or missing document
  if (!document || document.trim() === '') {
    // What should we return here?
  }

  // TODO: Build the system context section
  const systemContext = ``;

  // TODO: Build format-specific instructions
  let formatInstructions = '';
  if (format === 'bullets') {
    // Instructions for bullet point output
  } else if (format === 'json') {
    // Instructions for JSON output
  } else {
    // Instructions for paragraph output
  }

  // TODO: Combine all parts into final prompt
  return ``;
}

// Test your implementation
const testDoc = `The Model Context Protocol (MCP) is an open standard 
that enables AI assistants to securely connect to external data sources 
and tools. It was introduced by Anthropic in late 2024.`;

console.log('=== Paragraph Format ===');
console.log(buildAdvancedPrompt(testDoc, { format: 'paragraph' }));

console.log('\n=== Bullet Format ===');
console.log(buildAdvancedPrompt(testDoc, { format: 'bullets', maxLength: 50 }));

console.log('\n=== Empty Document ===');
console.log(buildAdvancedPrompt(''));

4. Get Help (If Needed)

Reveal progressive hints
Hint 1: Start with the empty document check - return an error message string.
Hint 2: Use an object to map audience types to their guidance text, then look it up.
Hint 3: For JSON format, show the exact structure you want. Models follow examples well.

5. Check the Solution

Reveal the complete solution
solution.ts
/**
 * Key Points:
 * - Line ~13: Always validate inputs - empty prompts waste API calls
 * - Line ~19: Map audiences to specific guidance for consistency
 * - Line ~30: Different output formats need different instructions
 * - Line ~49: XML-style tags help models identify document boundaries
 */

interface PromptOptions {
  role?: string;
  format?: 'paragraph' | 'bullets' | 'json';
  maxLength?: number;
  audience?: 'general' | 'technical' | 'executive';
}

/**
 * Build an advanced summarization prompt
 * @param document - The document to summarize
 * @param options - Configuration options
 * @returns The formatted prompt
 */
function buildAdvancedPrompt(document: string, options: PromptOptions = {}): string {
  const {
    role = 'You are a helpful document analyst.',
    format = 'paragraph',
    maxLength = 100,
    audience = 'general'
  } = options;

  // Handle empty or missing document
  if (!document || document.trim() === '') {
    return 'Error: No document provided for summarization.';
  }

  // Build system context with audience awareness
  const audienceGuidance: Record<PromptOptions['audience'] & string, string> = {
    general: 'Use clear, accessible language.',
    technical: 'Include technical details and terminology.',
    executive: 'Focus on business impact and key decisions.'
  };

  const systemContext = `${role}

Audience: ${audience}
Guidance: ${audienceGuidance[audience]}`;

  // Build format-specific instructions
  let formatInstructions = '';
  if (format === 'bullets') {
    formatInstructions = `Output as bullet points:
- Use 3-5 bullet points
- Each bullet should be one clear idea
- Maximum ${maxLength} words total`;
  } else if (format === 'json') {
    formatInstructions = `Output as JSON with this structure:
{
  "summary": "...",
  "keyPoints": ["...", "..."],
  "wordCount": <number>
}`;
  } else {
    formatInstructions = `Output as a single paragraph.
Maximum ${maxLength} words.
Be concise but complete.`;
  }

  // Combine all parts
  return `${systemContext}

## Task
Summarize the document below.

## Format Requirements
${formatInstructions}

## Document
<document>
${document.trim()}
</document>

## Your Summary`;
}

// Test the implementation
const testDoc = `The Model Context Protocol (MCP) is an open standard 
that enables AI assistants to securely connect to external data sources 
and tools. It was introduced by Anthropic in late 2024.`;

console.log('=== Paragraph Format ===');
console.log(buildAdvancedPrompt(testDoc, { format: 'paragraph' }));

console.log('\n=== Bullet Format ===');
console.log(buildAdvancedPrompt(testDoc, { format: 'bullets', maxLength: 50 }));

console.log('\n=== JSON Format (Technical) ===');
console.log(buildAdvancedPrompt(testDoc, { format: 'json', audience: 'technical' }));

console.log('\n=== Empty Document ===');
console.log(buildAdvancedPrompt(''));
L13: Always validate inputs - empty prompts waste API calls
L19: Map audiences to specific guidance for consistency
L30: Different output formats need different instructions
L49: XML-style tags help models identify document boundaries

Common Mistakes

Not trimming whitespace from document

Why it's wrong: Leading/trailing whitespace in prompts wastes tokens and can confuse models.

How to fix: Use document.trim() before inserting into the template.

Forgetting to handle undefined options

Why it's wrong: Accessing properties of undefined throws an error.

How to fix: Use destructuring with default values: const { format = 'paragraph' } = options;

Test Cases

Handles empty document

Input: buildAdvancedPrompt('')
Expected: Error: No document provided for summarization.

Default format is paragraph

Input: buildAdvancedPrompt('Test doc').includes('paragraph')
Expected: true

Bullet format includes bullets instructions

Input: buildAdvancedPrompt('Test', {format: 'bullets'}).includes('bullet')
Expected: true
Tempered AI Forged Through Practice, Not Hype

Keyboard Shortcuts

j
Next page
k
Previous page
h
Section home
/
Search
?
Show shortcuts
m
Toggle sidebar
Esc
Close modal
Shift+R
Reset all progress
? Keyboard shortcuts