Master AI-powered content generation for diverse use cases. Learn to generate articles, emails, social posts, and structured JSON output with proper content moderation and quality control.
Content generation is one of the most practical and widely-used applications of AI in production systems. From marketing copy to customer emails, product descriptions to social media posts, AI can dramatically accelerate content creation while maintaining quality and consistency.
However, successful AI content generation goes far beyond simple prompts. Production systems require structured output, content templates, moderation pipelines, and quality controls to ensure reliability and appropriateness for business use.
In this lesson, you'll learn professional techniques for building content generation systems that work in real-world applications. You'll master different content types, implement JSON mode for structured output, create reusable templates, integrate moderation, and build quality controls that ensure your generated content meets business requirements.
Effective content generation requires understanding and controlling key parameters that influence output quality, creativity, and consistency.
Core Generation Parameters:
Temperature (0.0 - 2.0):
Controls randomness and creativity in outputs.
max_tokens:
Controls the maximum length of generated content.
Best Practices:
top_p (Nucleus Sampling, 0.0 - 1.0):
Alternative to temperature - considers top probability mass.
Note: Use temperature OR top_p, not both simultaneously.
frequency_penalty (-2.0 to 2.0):
Reduces repetition of tokens based on how often they appear.
presence_penalty (-2.0 to 2.0):
Reduces repetition regardless of frequency.
Parameter Combinations by Use Case:
Technical Documentation:
1{
2 temperature: 0.2,
3 max_tokens: 1000,
4 presence_penalty: 0.0,
5 frequency_penalty: 0.3
6}Marketing Copy:
1{
2 temperature: 0.8,
3 max_tokens: 300,
4 presence_penalty: 0.6,
5 frequency_penalty: 0.5
6}Customer Emails:
1{
2 temperature: 0.5,
3 max_tokens: 400,
4 presence_penalty: 0.3,
5 frequency_penalty: 0.2
6}Social Media Posts:
1{
2 temperature: 0.9,
3 max_tokens: 100,
4 presence_penalty: 0.8,
5 frequency_penalty: 0.7
6}Advanced: Response Format (JSON Mode):
Ensures output is valid JSON for structured data extraction.
1{
2 response_format: { type: "json_object" },
3 temperature: 0.3 // Lower temp for structured output
4}Parameter Selection Strategy:
JSON mode ensures AI responses are valid, parseable JSON objects - critical for production systems that process AI outputs programmatically.
Why JSON Mode Matters:
Reliability:
Integration:
Use Cases:
How JSON Mode Works:
Step 1: Enable JSON Mode
1{
2 response_format: { type: "json_object" }
3}Step 2: Specify Schema in Prompt
The model needs to know what JSON structure you want:
1const prompt = `Extract user information as JSON:
2{
3 "name": "string",
4 "email": "string",
5 "phone": "string",
6 "interests": ["array", "of", "strings"]
7}
8
9Text: "${userInput}"`;Step 3: Parse Response
1const data = JSON.parse(completion.choices[0].message.content);JSON Mode Best Practices:
1. Always Specify Schema:
2. Use Lower Temperature:
3. Handle Edge Cases:
4. Validate Output:
Common Pitfalls to Avoid:
❌ Don't: Assume perfect JSON every time
✅ Do: Wrap parsing in try-catch
❌ Don't: Leave schema ambiguous
✅ Do: Provide exact structure with examples
❌ Don't: Use high temperature with JSON mode
✅ Do: Keep temperature < 0.5
❌ Don't: Skip validation
✅ Do: Validate all required fields
Content templates enable scalable, consistent content generation with dynamic personalization - essential for production systems handling thousands of unique requests.
Template Architecture:
1. Template Structure:
1System Prompt (Role + Constraints)
2 ↓
3Template Pattern (Format + Style)
4 ↓
5Variable Injection (Personalization)
6 ↓
7Generation Parameters (Temperature, etc.)
8 ↓
9Output Validation2. Template Types:
Fixed Template:
Strict structure, minimal variation
Semi-Structured Template:
Defined sections, flexible content
Dynamic Template:
Adaptive structure based on context
Template Design Patterns:
Pattern 1: Role-Based Templates
1const templates = {
2 customerService: {
3 role: "You are a professional customer service representative",
4 tone: "friendly, helpful, empathetic",
5 constraints: ["Be concise", "Offer solutions", "Stay positive"]
6 },
7 technical: {
8 role: "You are a technical documentation writer",
9 tone: "clear, precise, educational",
10 constraints: ["Use examples", "Be accurate", "Avoid jargon"]
11 }
12};Pattern 2: Context Injection
1function buildPrompt(template, context) {
2 return `${template.role}. ${template.tone}.
3
4Context: ${context.userInfo}
5
6Task: ${context.task}
7
8Constraints:
9${template.constraints.map(c => `- ${c}`).join('\n')}
10
11Generate:`;
12}Pattern 3: Multi-Stage Generation
1// Stage 1: Generate outline
2const outline = await generateOutline(topic);
3
4// Stage 2: Expand each section
5const sections = await Promise.all(
6 outline.sections.map(s => generateSection(s))
7);
8
9// Stage 3: Combine and polish
10const final = await polishContent(sections.join('\n'));Personalization Techniques:
User-Level Personalization:
Context-Aware Generation:
Dynamic Variable Injection:
1const variables = {
2 userName: "Sarah",
3 productName: "Pro Plan",
4 expiryDate: "Dec 31",
5 renewalPrice: "$99",
6 discount: "20%"
7};
8
9const template = `Hi {{userName}},
10
11Your {{productName}} subscription expires on {{expiryDate}}.
12
13Renew now for {{renewalPrice}} ({{discount}} off!)
14
15Best regards`;
16
17// Replace variables
18const personalized = Object.entries(variables).reduce(
19 (text, [key, value]) => text.replace(`{{${key}}}`, value),
20 template
21);Advanced Template Features:
Conditional Sections:
1if (user.isPremium) {
2 prompt += "Mention premium benefits.\n";
3}
4
5if (user.cartAbandoned) {
6 prompt += "Include 10% discount code.\n";
7}A/B Testing:
1const variants = {
2 A: { temperature: 0.7, style: "professional" },
3 B: { temperature: 0.9, style: "casual" }
4};
5
6const variant = Math.random() < 0.5 ? 'A' : 'B';
7const params = variants[variant];Template Versioning:
1const templateVersions = {
2 'v1.0': originalTemplate,
3 'v2.0': improvedTemplate,
4 'v2.1': currentTemplate
5};
6
7const template = templateVersions[user.templateVersion || 'v2.1'];Content moderation ensures AI-generated content is appropriate, safe, and aligned with brand guidelines - critical for production systems serving real users.
Why Content Moderation Matters:
Legal Compliance:
Brand Safety:
User Safety:
Moderation Strategies:
1. Pre-Generation Filtering:
Screen input before generating content
1// Check user input for inappropriate content
2const inputModeration = await moderateInput(userPrompt);
3if (inputModeration.flagged) {
4 return { error: "Input contains inappropriate content" };
5}
6
7// Then proceed with generation
8const content = await generateContent(userPrompt);2. Post-Generation Validation:
Screen output after generation
1const content = await generateContent(prompt);
2
3// Check generated content
4const outputModeration = await moderateOutput(content);
5if (outputModeration.flagged) {
6 // Regenerate with stricter parameters
7 return await generateContent(prompt, { temperature: 0.3 });
8}
9
10return content;3. Hybrid Approach:
Check both input and output
1// Most robust for production
2const inputCheck = await moderateInput(userPrompt);
3if (inputCheck.flagged) throw new Error("Invalid input");
4
5const content = await generateContent(userPrompt);
6
7const outputCheck = await moderateOutput(content);
8if (outputCheck.flagged) {
9 // Log for review
10 logModerationIssue(outputCheck);
11 // Regenerate or return error
12 return { error: "Unable to generate appropriate content" };
13}
14
15return content;OpenAI Moderation API:
Categories:
Response Format:
1{
2 flagged: true/false,
3 categories: {
4 hate: true/false,
5 sexual: true/false,
6 // ... other categories
7 },
8 category_scores: {
9 hate: 0.0-1.0,
10 sexual: 0.0-1.0,
11 // ... confidence scores
12 }
13}Custom Moderation Rules:
Beyond API moderation, implement business-specific rules:
Brand Voice Compliance:
1function checkBrandCompliance(content) {
2 const violations = [];
3
4 // Check for banned phrases
5 if (content.includes("guaranteed")) {
6 violations.push("Avoid absolute claims");
7 }
8
9 // Check tone
10 if (content.match(/[A-Z]{3,}/)) {
11 violations.push("Excessive capitalization");
12 }
13
14 // Check length
15 if (content.length > maxLength) {
16 violations.push("Content too long");
17 }
18
19 return { compliant: violations.length === 0, violations };
20}Quality Thresholds:
1function assessQuality(content) {
2 const checks = {
3 hasCall ToAction: /click|buy|subscribe|learn more/i.test(content),
4 hasValue Proposition: content.length > 100,
5 properFormatting: !content.includes("undefined"),
6 noPlaceholders: !/\{\{.*\}\}/.test(content)
7 };
8
9 return Object.values(checks).every(c => c);
10}Moderation Best Practices:
Quality control ensures AI-generated content meets business requirements, maintains consistency, and delivers value - separating prototype experiments from production-ready systems.
Quality Dimensions:
1. Accuracy:
2. Relevance:
3. Completeness:
4. Consistency:
5. Readability:
Quality Control Strategies:
Pre-Generation Controls:
1. Prompt Engineering:
1// Bad: Vague prompt
2"Write about AI"
3
4// Good: Specific prompt
5`Write a 200-word blog introduction about AI for developers.
6- Start with a relatable problem
7- Include 2 practical use cases
8- End with a call-to-action
9- Tone: Professional but friendly`2. Parameter Tuning:
1// For consistency and quality
2{
3 temperature: 0.3, // Lower for factual content
4 top_p: 0.9,
5 presence_penalty: 0.3,
6 max_tokens: 600 // Generous buffer
7}Post-Generation Validation:
1. Structural Validation:
1function validateStructure(content, requirements) {
2 return {
3 hasIntroduction: content.includes("Introduction") || content.startsWith(...),
4 hasBody: content.length > 200,
5 hasConclusion: content.includes("conclusion") || content.endsWith(...),
6 meetsMinLength: content.length >= requirements.minLength,
7 meetsMaxLength: content.length <= requirements.maxLength,
8 hasRequiredSections: requirements.sections.every(s => content.includes(s))
9 };
10}2. Content Analysis:
1function analyzeQuality(content) {
2 const sentences = content.split(/[.!?]+/).filter(Boolean);
3 const words = content.split(/\s+/);
4
5 return {
6 wordCount: words.length,
7 sentenceCount: sentences.length,
8 avgSentenceLength: words.length / sentences.length,
9 readabilityScore: calculateReadability(content),
10 containsPlaceholders: /\{\{|\[\[|XXX|TODO/.test(content),
11 hasProperFormatting: checkFormatting(content)
12 };
13}3. Semantic Validation:
1async function validateRelevance(content, originalPrompt) {
2 // Use embeddings to check similarity
3 const contentEmbedding = await getEmbedding(content);
4 const promptEmbedding = await getEmbedding(originalPrompt);
5
6 const similarity = cosineSimilarity(contentEmbedding, promptEmbedding);
7
8 return {
9 relevant: similarity > 0.7, // Threshold
10 similarity
11 };
12}Automated Quality Scoring:
Score Components:
Implementation:
1function calculateQualityScore(content, requirements) {
2 let score = 0;
3
4 // Structure (25 points)
5 const structure = validateStructure(content, requirements);
6 score += Object.values(structure).filter(Boolean).length * 5;
7
8 // Relevance (25 points)
9 const analysis = analyzeQuality(content);
10 if (analysis.wordCount >= requirements.minWords) score += 10;
11 if (!analysis.containsPlaceholders) score += 10;
12 if (analysis.readabilityScore > 60) score += 5;
13
14 // Completeness (25 points)
15 if (analysis.sentenceCount >= 5) score += 10;
16 if (content.includes(requirements.callToAction)) score += 15;
17
18 // Format (25 points)
19 if (analysis.hasProperFormatting) score += 25;
20
21 return Math.min(score, 100);
22}Quality Thresholds:
Continuous Improvement:
1. Collect Feedback:
2. Analyze Patterns:
3. Iterate and Refine:
A complete content generation system demonstrating all lesson concepts: multiple content types, structured JSON output, dynamic templates, content moderation, and comprehensive quality control.
1<!DOCTYPE html>
2<html lang="en">
3<head>
4 <meta charset="UTF-8">
5 <meta name="viewport" content="width=device-width, initial-scale=1.0">
6 <title>Content Generation Studio</title>
7</head>
8<body>
9 <div class="container">
10 <header class="hero">
11 <h1>📝 Content Generation Studio</h1>
12 <p class="subtitle">Professional AI-powered content creation with quality controls</p>
13 </header>
14
15 <!-- Content Type Selector -->
16 <section class="card">
17 <h2>🎯 Select Content Type</h2>
18 <div class="content-types">
19 <button class="type-btn active" onclick="selectContentType('email')" data-type="email">
20 📧 Email
21 </button>
22 <button class="type-btn" onclick="selectContentType('blog')" data-type="blog">
23 📰 Blog Post
24 </button>
25 <button class="type-btn" onclick="selectContentType('social')" data-type="social">
26 📱 Social Media
27 </button>
28 <button class="type-btn" onclick="selectContentType('product')" data-type="product">
29 🛍️ Product Description
30 </button>
31 <button class="type-btn" onclick="selectContentType('json')" data-type="json">
32 📋 Structured JSON
33 </button>
34 </div>
35 </section>
36
37 <!-- Email Generator -->
38 <section id="email-form" class="card content-form">
39 <h2>📧 Email Generator</h2>
40 <div class="form-group">
41 <label>Email Type:</label>
42 <select id="email-type">
43 <option value="welcome">Welcome Email</option>
44 <option value="promotional">Promotional</option>
45 <option value="transactional">Transactional</option>
46 <option value="follow-up">Follow-up</option>
47 </select>
48 </div>
49 <div class="form-group">
50 <label>Recipient Name:</label>
51 <input type="text" id="email-recipient" value="Sarah" />
52 </div>
53 <div class="form-group">
54 <label>Context:</label>
55 <textarea id="email-context" rows="3">New customer who signed up for Pro plan</textarea>
56 </div>
57 <div class="form-group">
58 <label>Tone:</label>
59 <select id="email-tone">
60 <option value="professional">Professional</option>
61 <option value="friendly">Friendly</option>
62 <option value="casual">Casual</option>
63 </select>
64 </div>
65 <button class="btn btn-primary" onclick="generateEmail()">Generate Email</button>
66 </section>
67
68 <!-- Blog Post Generator -->
69 <section id="blog-form" class="card content-form hidden">
70 <h2>📰 Blog Post Generator</h2>
71 <div class="form-group">
72 <label>Topic:</label>
73 <input type="text" id="blog-topic" value="AI Content Generation" />
74 </div>
75 <div class="form-group">
76 <label>Target Audience:</label>
77 <input type="text" id="blog-audience" value="Developers" />
78 </div>
79 <div class="form-group">
80 <label>Keywords (comma-separated):</label>
81 <input type="text" id="blog-keywords" value="AI, GPT, content, automation" />
82 </div>
83 <div class="form-group">
84 <label>Length:</label>
85 <select id="blog-length">
86 <option value="300">Short (300 words)</option>
87 <option value="500" selected>Medium (500 words)</option>
88 <option value="800">Long (800 words)</option>
89 </select>
90 </div>
91 <button class="btn btn-primary" onclick="generateBlog()">Generate Blog Post</button>
92 </section>
93
94 <!-- Social Media Generator -->
95 <section id="social-form" class="card content-form hidden">
96 <h2>📱 Social Media Generator</h2>
97 <div class="form-group">
98 <label>Platform:</label>
99 <select id="social-platform">
100 <option value="twitter">Twitter/X</option>
101 <option value="linkedin">LinkedIn</option>
102 <option value="facebook">Facebook</option>
103 <option value="instagram">Instagram</option>
104 </select>
105 </div>
106 <div class="form-group">
107 <label>Topic:</label>
108 <input type="text" id="social-topic" value="Product launch announcement" />
109 </div>
110 <div class="form-group">
111 <label>Include Hashtags:</label>
112 <input type="checkbox" id="social-hashtags" checked />
113 </div>
114 <div class="form-group">
115 <label>Include Emoji:</label>
116 <input type="checkbox" id="social-emoji" checked />
117 </div>
118 <button class="btn btn-primary" onclick="generateSocial()">Generate Post</button>
119 </section>
120
121 <!-- Product Description Generator -->
122 <section id="product-form" class="card content-form hidden">
123 <h2>🛍️ Product Description Generator</h2>
124 <div class="form-group">
125 <label>Product Name:</label>
126 <input type="text" id="product-name" value="Wireless Noise-Canceling Headphones" />
127 </div>
128 <div class="form-group">
129 <label>Key Features (one per line):</label>
130 <textarea id="product-features" rows="4">Active noise cancellation
13140-hour battery life
132Premium sound quality
133Comfortable fit</textarea>
134 </div>
135 <div class="form-group">
136 <label>Target Customer:</label>
137 <input type="text" id="product-customer" value="Music enthusiasts and travelers" />
138 </div>
139 <div class="form-group">
140 <label>Style:</label>
141 <select id="product-style">
142 <option value="persuasive">Persuasive</option>
143 <option value="technical">Technical</option>
144 <option value="lifestyle">Lifestyle</option>
145 </select>
146 </div>
147 <button class="btn btn-primary" onclick="generateProduct()">Generate Description</button>
148 </section>
149
150 <!-- JSON Extractor -->
151 <section id="json-form" class="card content-form hidden">
152 <h2>📋 Structured JSON Extractor</h2>
153 <div class="form-group">
154 <label>Extraction Type:</label>
155 <select id="json-type">
156 <option value="contact">Contact Information</option>
157 <option value="product">Product Data</option>
158 <option value="event">Event Details</option>
159 <option value="sentiment">Sentiment Analysis</option>
160 </select>
161 </div>
162 <div class="form-group">
163 <label>Input Text:</label>
164 <textarea id="json-input" rows="5">Hi, I'm Sarah Johnson from TechCorp. You can reach me at [email protected] or call 555-0123. We're interested in your enterprise plan.</textarea>
165 </div>
166 <button class="btn btn-primary" onclick="extractJSON()">Extract JSON</button>
167 </section>
168
169 <!-- Generation Parameters -->
170 <section class="card">
171 <h2>⚙️ Generation Parameters</h2>
172 <div class="parameters-grid">
173 <div class="param-control">
174 <label>Temperature: <span id="temp-value">0.7</span></label>
175 <input type="range" id="temperature" min="0" max="1" step="0.1" value="0.7" oninput="updateParam('temp')">
176 <small>Lower = More focused, Higher = More creative</small>
177 </div>
178 <div class="param-control">
179 <label>Max Length: <span id="length-value">500</span> words</label>
180 <input type="range" id="max-length" min="100" max="1000" step="50" value="500" oninput="updateParam('length')">
181 </div>
182 </div>
183 </section>
184
185 <!-- Output Section -->
186 <section id="output-section" class="card hidden">
187 <h2>✨ Generated Content</h2>
188
189 <div class="output-header">
190 <div class="quality-badge" id="quality-badge"></div>
191 <button class="btn btn-secondary" onclick="copyToClipboard()">📋 Copy</button>
192 <button class="btn btn-secondary" onclick="regenerate()">🔄 Regenerate</button>
193 </div>
194
195 <div class="output-content" id="generated-content"></div>
196
197 <div class="quality-report" id="quality-report"></div>
198
199 <div class="moderation-report" id="moderation-report"></div>
200 </section>
201
202 <!-- Tips Section -->
203 <section class="card tips-section">
204 <h2>💡 Content Generation Best Practices</h2>
205 <div class="tips-grid">
206 <div class="tip-card">
207 <h3>🎯 Be Specific</h3>
208 <p>Provide clear context, audience, and tone requirements for consistent results.</p>
209 </div>
210 <div class="tip-card">
211 <h3>🔧 Tune Parameters</h3>
212 <p>Lower temperature (0.2-0.4) for factual content, higher (0.7-0.9) for creative.</p>
213 </div>
214 <div class="tip-card">
215 <h3>✅ Always Validate</h3>
216 <p>Check generated content for quality, accuracy, and brand compliance before use.</p>
217 </div>
218 <div class="tip-card">
219 <h3>📊 Use JSON Mode</h3>
220 <p>For structured data extraction, use JSON mode for reliable, parseable output.</p>
221 </div>
222 <div class="tip-card">
223 <h3>🛡️ Moderate Content</h3>
224 <p>Always run moderation on generated content before publishing to users.</p>
225 </div>
226 <div class="tip-card">
227 <h3>🔄 Iterate</h3>
228 <p>Test different prompts and parameters to find what works best for your use case.</p>
229 </div>
230 </div>
231 </section>
232 </div>
233</body>
234</html>This comprehensive Content Generation Studio demonstrates all key concepts from Lesson 5:
🎯 Complete Coverage of Lesson Concepts:
1. Multiple Content Types:
2. Parameter Control:
3. Content Templates:
4. Structured JSON Output:
5. Quality Control:
6. Content Moderation:
Educational Features:
Production-Ready Patterns:
Interactive Elements:
This demo serves as both a learning tool and a practical reference for building production content generation systems with proper quality controls and moderation.
Excellent work mastering content generation! You now understand parameters, JSON mode, templates, moderation, and quality controls. In our next lesson, "Text Analysis and NLP Tasks," you'll learn to extract insights from content using sentiment analysis, entity recognition, text classification, summarization, and language detection. Get ready to build systems that understand and analyze text at scale!
Your progress is saved in this browser, on this device only.