Construct Effective Prompts
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:
- System context - Define the assistant's role and constraints
- Task instructions - Clear, specific directions
- Input formatting - How to present user content
- 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:
- Accept document text and configuration options
- Build a prompt with system context, formatting rules, and the document
- Handle missing or empty documents gracefully
- Support multiple output formats (bullets, paragraph, JSON)
3. Try It Yourself
/**
* 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
5. Check the Solution
Reveal the complete solution
/**
* 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('')); 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
buildAdvancedPrompt('')Error: No document provided for summarization.Default format is paragraph
buildAdvancedPrompt('Test doc').includes('paragraph')trueBullet format includes bullets instructions
buildAdvancedPrompt('Test', {format: 'bullets'}).includes('bullet')true