-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
1071 lines (912 loc) · 41.8 KB
/
Copy pathapp.js
File metadata and controls
1071 lines (912 loc) · 41.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Course Data and State Management
class CourseManager {
constructor() {
this.currentPage = 'home';
this.completedModules = new Set();
this.quizAnswers = [];
this.quizData = this.generateQuizData();
this.currentQuestionIndex = 0;
this.savedPrompts = this.loadSavedPrompts();
this.initializeEventListeners();
this.updateProgress();
}
initializeEventListeners() {
// Navigation listeners
document.querySelectorAll('.nav-link').forEach(link => {
link.addEventListener('click', (e) => {
e.preventDefault();
const page = e.target.getAttribute('data-page');
this.goToPage(page);
});
});
// Technique tab listeners
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.addEventListener('click', (e) => {
this.switchTechniqueTab(e.target.getAttribute('data-technique'));
});
});
// Lab tab listeners
document.querySelectorAll('.lab-tab').forEach(btn => {
btn.addEventListener('click', (e) => {
this.switchLabTab(e.target.getAttribute('data-lab'));
});
});
// Use case selector listeners
document.querySelectorAll('.use-case-card').forEach(card => {
card.addEventListener('click', (e) => {
this.selectUseCase(e.currentTarget.getAttribute('data-use-case'));
});
});
// Comparison scenario listener
const comparisonSelect = document.getElementById('comparison-scenario');
if (comparisonSelect) {
comparisonSelect.addEventListener('change', (e) => {
this.updateTechniqueComparison(e.target.value);
});
}
}
goToPage(pageId) {
// Hide all pages
document.querySelectorAll('.page').forEach(page => {
page.classList.remove('active');
});
// Show target page
const targetPage = document.getElementById(pageId);
if (targetPage) {
targetPage.classList.add('active');
this.currentPage = pageId;
// Update navigation
document.querySelectorAll('.nav-link').forEach(link => {
link.classList.remove('active');
});
const activeLink = document.querySelector(`[data-page="${pageId}"]`);
if (activeLink) {
activeLink.classList.add('active');
}
// Mark module as completed if it's a module page
if (pageId.startsWith('module')) {
this.markModuleCompleted(pageId);
}
// Scroll to top
window.scrollTo(0, 0);
}
}
markModuleCompleted(moduleId) {
this.completedModules.add(moduleId);
const navLink = document.querySelector(`[data-page="${moduleId}"]`);
if (navLink) {
navLink.classList.add('completed');
}
this.updateProgress();
this.saveProgress();
}
updateProgress() {
const totalModules = 6;
const completedCount = this.completedModules.size;
const progressPercent = (completedCount / totalModules) * 100;
const progressFill = document.getElementById('overall-progress');
const progressText = document.getElementById('progress-text');
if (progressFill) {
progressFill.style.width = `${progressPercent}%`;
}
if (progressText) {
progressText.textContent = `${Math.round(progressPercent)}% Complete`;
}
}
switchTechniqueTab(technique) {
// Hide all technique content
document.querySelectorAll('.technique-content').forEach(content => {
content.classList.remove('active');
});
// Show target technique
const targetContent = document.getElementById(technique);
if (targetContent) {
targetContent.classList.add('active');
}
// Update tab buttons
document.querySelectorAll('.tab-btn').forEach(btn => {
btn.classList.remove('active');
});
const activeTab = document.querySelector(`[data-technique="${technique}"]`);
if (activeTab) {
activeTab.classList.add('active');
}
}
switchLabTab(lab) {
// Hide all lab content
document.querySelectorAll('.lab-content').forEach(content => {
content.classList.remove('active');
});
// Show target lab
const targetContent = document.getElementById(lab);
if (targetContent) {
targetContent.classList.add('active');
}
// Update tab buttons
document.querySelectorAll('.lab-tab').forEach(btn => {
btn.classList.remove('active');
});
const activeTab = document.querySelector(`[data-lab="${lab}"]`);
if (activeTab) {
activeTab.classList.add('active');
}
}
selectUseCase(useCase) {
// Update card selection
document.querySelectorAll('.use-case-card').forEach(card => {
card.classList.remove('selected');
});
const selectedCard = document.querySelector(`[data-use-case="${useCase}"]`);
if (selectedCard) {
selectedCard.classList.add('selected');
}
// Show prompt builder
const promptBuilder = document.getElementById('application-prompt-builder');
if (promptBuilder) {
promptBuilder.classList.add('show');
}
// Generate template prompt based on use case
this.generateUseCasePrompt(useCase);
}
generateUseCasePrompt(useCase) {
const templates = {
'customer-service': `As a customer service expert, analyze this customer message and provide:
1. Issue categorization (Technical, Billing, General)
2. Urgency level (Low, Medium, High)
3. Suggested response approach
4. Any escalation recommendations
Customer message: [INSERT MESSAGE]
Response format:
Category:
Urgency:
Approach:
Escalation: `,
'content-moderation': `As a content moderation specialist, review this content for:
1. Inappropriate language or hate speech
2. Spam or promotional content
3. Misinformation or false claims
4. Community guideline violations
Content: [INSERT CONTENT]
Assessment:
Violations:
Action Required:
Confidence Level: `,
'data-analysis': `As a data analyst, examine this dataset/report and provide:
1. Key insights and trends
2. Statistical significance of findings
3. Potential correlations or patterns
4. Actionable recommendations
Data: [INSERT DATA]
Analysis:
Key Insights:
Trends:
Recommendations: `,
'document-processing': `As a document processing expert, analyze this document and extract:
1. Key information and entities
2. Document type and purpose
3. Important dates, numbers, or references
4. Summary of main points
Document: [INSERT DOCUMENT]
Extraction:
Type:
Key Info:
Summary: `
};
const textarea = document.querySelector('#application-prompt-builder textarea');
if (textarea && templates[useCase]) {
textarea.value = templates[useCase];
}
}
updateTechniqueComparison(scenario) {
const comparisons = {
'math': {
'Zero-Shot': { rating: 3, description: 'Basic calculation ability' },
'Few-Shot': { rating: 4, description: 'Consistent format with examples' },
'Chain-of-Thought': { rating: 5, description: 'Step-by-step reasoning, highest accuracy' }
},
'writing': {
'Zero-Shot': { rating: 4, description: 'Good creative baseline' },
'Few-Shot': { rating: 5, description: 'Consistent style with examples' },
'Chain-of-Thought': { rating: 3, description: 'Over-structured for creativity' }
},
'analysis': {
'Zero-Shot': { rating: 3, description: 'Surface-level insights' },
'Few-Shot': { rating: 4, description: 'Consistent analytical framework' },
'Chain-of-Thought': { rating: 5, description: 'Thorough step-by-step analysis' }
},
'classification': {
'Zero-Shot': { rating: 4, description: 'Good for simple categories' },
'Few-Shot': { rating: 5, description: 'Excellent with examples' },
'Chain-of-Thought': { rating: 3, description: 'Unnecessary complexity' }
}
};
const resultsContainer = document.getElementById('comparison-results');
if (resultsContainer && comparisons[scenario]) {
const comparisonData = comparisons[scenario];
let html = '<div class="technique-comparison">';
Object.entries(comparisonData).forEach(([technique, data]) => {
const stars = '⭐'.repeat(data.rating);
html += `
<div class="comparison-card">
<h4>${technique}</h4>
<div class="rating">${stars}</div>
<p>${data.description}</p>
</div>
`;
});
html += '</div>';
resultsContainer.innerHTML = html;
}
}
saveProgress() {
const progress = {
completedModules: Array.from(this.completedModules),
currentPage: this.currentPage,
savedPrompts: this.savedPrompts
};
localStorage.setItem('promptEngineeringProgress', JSON.stringify(progress));
}
loadProgress() {
const saved = localStorage.getItem('promptEngineeringProgress');
if (saved) {
const progress = JSON.parse(saved);
this.completedModules = new Set(progress.completedModules || []);
this.savedPrompts = progress.savedPrompts || [];
// Update UI
progress.completedModules?.forEach(moduleId => {
const navLink = document.querySelector(`[data-page="${moduleId}"]`);
if (navLink) {
navLink.classList.add('completed');
}
});
this.updateProgress();
}
}
loadSavedPrompts() {
const saved = localStorage.getItem('savedPrompts');
return saved ? JSON.parse(saved) : [];
}
savePrompt(prompt, title) {
const promptData = {
id: Date.now(),
title: title || 'Untitled Prompt',
content: prompt,
createdAt: new Date().toLocaleDateString()
};
this.savedPrompts.push(promptData);
localStorage.setItem('savedPrompts', JSON.stringify(this.savedPrompts));
this.updatePromptLibrary();
}
updatePromptLibrary() {
const library = document.getElementById('prompt-library');
if (!library) return;
if (this.savedPrompts.length === 0) {
library.innerHTML = '<p class="empty-state">No saved prompts yet. Create and save prompts to build your library!</p>';
return;
}
let html = '';
this.savedPrompts.forEach(prompt => {
html += `
<div class="saved-prompt-item">
<h4>${prompt.title}</h4>
<div class="saved-prompt-text">${prompt.content}</div>
<div class="prompt-meta">Saved on ${prompt.createdAt}</div>
</div>
`;
});
library.innerHTML = html;
}
generateQuizData() {
return [
{
question: "What performance improvement can proper prompt engineering achieve according to research?",
options: ["25%", "50%", "76%", "90%"],
correct: 2,
explanation: "Research shows that proper prompt engineering can create up to 76% performance differences in AI outputs.",
topic: "Foundation"
},
{
question: "Which technique involves providing 2-5 examples to guide model behavior?",
options: ["Zero-shot prompting", "Few-shot prompting", "Chain-of-thought", "Meta prompting"],
correct: 1,
explanation: "Few-shot prompting uses 2-5 examples to establish patterns and guide the model's responses.",
topic: "Essential Techniques"
},
{
question: "Chain-of-thought prompting is most effective for:",
options: ["Creative writing", "Mathematical reasoning", "Simple classifications", "Role-playing scenarios"],
correct: 1,
explanation: "Chain-of-thought prompting excels at mathematical reasoning and complex logical problems by encouraging step-by-step thinking.",
topic: "Essential Techniques"
},
{
question: "According to research, role prompting has what impact on correctness?",
options: ["Significant improvement", "Moderate improvement", "Minimal impact", "Negative impact"],
correct: 2,
explanation: "Research shows role prompting has minimal impact on correctness but can improve response style and domain-specific language.",
topic: "Essential Techniques"
},
{
question: "What is the primary advantage of zero-shot prompting?",
options: ["Highest accuracy", "No examples needed", "Best for complex tasks", "Most consistent formatting"],
correct: 1,
explanation: "Zero-shot prompting's main advantage is that it requires no examples, making it quick and simple to implement.",
topic: "Advanced Techniques"
},
{
question: "Self-consistency technique involves:",
options: ["Using the same prompt repeatedly", "Generating multiple reasoning paths", "Checking for grammatical consistency", "Maintaining consistent formatting"],
correct: 1,
explanation: "Self-consistency generates multiple reasoning paths and selects the most consistent answer across attempts.",
topic: "Advanced Techniques"
},
{
question: "In the Reddit crisis detection case study, what was the F1 score improvement?",
options: ["0 to 0.25", "0 to 0.53", "0.25 to 0.75", "0.53 to 0.90"],
correct: 1,
explanation: "Expert prompt engineering improved the F1 score from 0 to 0.53 in Reddit suicide crisis detection.",
topic: "Applications"
},
{
question: "Medical coding accuracy improved from 0% to what percentage using few-shot prompting?",
options: ["70%", "80%", "90%", "95%"],
correct: 2,
explanation: "Few-shot prompting with medical examples achieved 90% accuracy in ICD-10 medical coding tasks.",
topic: "Applications"
},
{
question: "What matters more than length in prompt engineering?",
options: ["Vocabulary complexity", "Structure and clarity", "Number of examples", "Technical terminology"],
correct: 1,
explanation: "Research consistently shows that structure and clarity matter more than prompt length for effectiveness.",
topic: "Foundation"
},
{
question: "Which technique combination is most effective for complex analytical tasks?",
options: ["Zero-shot + Role", "Few-shot + Chain-of-thought", "Role + Meta prompting", "Few-shot + Zero-shot"],
correct: 1,
explanation: "Combining few-shot examples with chain-of-thought reasoning provides the best results for complex analytical tasks.",
topic: "Advanced Techniques"
},
{
question: "The Input-Instruction-Output framework emphasizes:",
options: ["Using technical language", "Providing clear structure", "Making prompts longer", "Including multiple examples"],
correct: 1,
explanation: "The Input-Instruction-Output framework emphasizes providing clear structure to guide AI responses effectively.",
topic: "Foundation"
},
{
question: "Meta prompting is primarily used for:",
options: ["Improving existing prompts", "Creating longer responses", "Adding more examples", "Reducing prompt complexity"],
correct: 0,
explanation: "Meta prompting uses prompts to generate or improve other prompts, focusing on prompt optimization.",
topic: "Advanced Techniques"
},
{
question: "In A/B testing prompts, what should you primarily measure?",
options: ["Response length", "Processing time", "Output quality and consistency", "Token usage"],
correct: 2,
explanation: "A/B testing should focus on output quality and consistency to determine which prompt performs better.",
topic: "Interactive Labs"
},
{
question: "Context and specificity in prompts lead to:",
options: ["Longer responses", "More creative outputs", "Dramatically improved results", "Reduced processing time"],
correct: 2,
explanation: "Providing relevant context and specific requirements dramatically improves AI response quality and relevance.",
topic: "Foundation"
},
{
question: "Which MMLU benchmark performance is highest?",
options: ["Zero-shot (65%)", "Few-shot (78%)", "Chain-of-thought (85%)", "All perform equally"],
correct: 2,
explanation: "Chain-of-thought prompting achieved the highest MMLU benchmark performance at 85%.",
topic: "Advanced Techniques"
},
{
question: "Business process automation saw what efficiency improvement?",
options: ["150%", "200%", "300%", "400%"],
correct: 2,
explanation: "The business process automation case study showed a 300% efficiency improvement in ticket processing.",
topic: "Applications"
},
{
question: "When should you use few-shot prompting over zero-shot?",
options: ["For simple tasks", "When examples are unavailable", "For consistent formatting needs", "For creative writing"],
correct: 2,
explanation: "Few-shot prompting is ideal when you need consistent formatting and have specific patterns to follow.",
topic: "Essential Techniques"
},
{
question: "The key to effective prompt iteration is:",
options: ["Making prompts longer", "Adding more examples", "Testing and measuring results", "Using technical terms"],
correct: 2,
explanation: "Effective prompt iteration requires systematic testing and measurement of results to guide improvements.",
topic: "Interactive Labs"
}
];
}
}
// Initialize course manager
const courseManager = new CourseManager();
// Global functions for HTML onclick handlers
function goToPage(pageId) {
courseManager.goToPage(pageId);
}
function checkPromptImprovement() {
const textarea = document.querySelector('.practice-area textarea');
const feedback = document.getElementById('prompt-feedback');
if (!textarea || !feedback) return;
const userPrompt = textarea.value.trim();
if (userPrompt.length < 20) {
feedback.innerHTML = `
<div class="feedback-result incorrect">Needs Improvement</div>
<div class="feedback-explanation">Your prompt is too short. Try adding more context, specific instructions, and desired output format.</div>
`;
} else if (userPrompt.toLowerCase().includes('expert') || userPrompt.toLowerCase().includes('specific') || userPrompt.toLowerCase().includes('format')) {
feedback.innerHTML = `
<div class="feedback-result correct">Great Improvement!</div>
<div class="feedback-explanation">Excellent! You've added context, specificity, or role assignment. This prompt is much more likely to produce useful results.</div>
`;
} else {
feedback.innerHTML = `
<div class="feedback-result">Good Start</div>
<div class="feedback-explanation">Better than the original! Consider adding: role assignment ("As an expert..."), specific output format, or more context about the desired response.</div>
`;
}
feedback.classList.add('show');
}
function testFewShotPrompt() {
const textarea = document.querySelector('#few-shot textarea');
const result = document.getElementById('few-shot-result');
if (!textarea || !result) return;
const prompt = textarea.value.trim();
if (prompt.length < 50) {
result.innerHTML = `
<div class="feedback-result">Prompt too short</div>
<div class="feedback-explanation">A few-shot prompt should include 2-5 examples showing the input-output pattern you want.</div>
`;
} else if (prompt.includes('Example') && prompt.includes('→')) {
result.innerHTML = `
<div class="feedback-result correct">Excellent Few-Shot Prompt!</div>
<div class="feedback-explanation">Your prompt includes clear examples with the input → output format. This will help the model understand the pattern.</div>
`;
} else {
result.innerHTML = `
<div class="feedback-result">Good attempt</div>
<div class="feedback-explanation">Consider adding more examples with clear input → output format to establish the pattern better.</div>
`;
}
result.classList.add('show');
}
function testChainThoughtPrompt() {
const textarea = document.querySelector('#chain-thought textarea');
const result = document.getElementById('chain-thought-result');
if (!textarea || !result) return;
const prompt = textarea.value.trim();
if (prompt.toLowerCase().includes('step by step') || prompt.toLowerCase().includes('first') || prompt.toLowerCase().includes('then')) {
result.innerHTML = `
<div class="feedback-result correct">Perfect Chain-of-Thought!</div>
<div class="feedback-explanation">Your prompt encourages step-by-step reasoning, which will lead to more accurate mathematical solutions.</div>
`;
} else {
result.innerHTML = `
<div class="feedback-result">Needs step-by-step guidance</div>
<div class="feedback-explanation">Add phrases like "Think step by step", "First...", "Then...", "Finally..." to encourage systematic reasoning.</div>
`;
}
result.classList.add('show');
}
function testRolePrompt() {
const textarea = document.querySelector('#role-prompting textarea');
const result = document.getElementById('role-result');
if (!textarea || !result) return;
const prompt = textarea.value.trim();
if (prompt.toLowerCase().includes('you are') || prompt.toLowerCase().includes('as a') || prompt.toLowerCase().includes('expert')) {
result.innerHTML = `
<div class="feedback-result correct">Good Role Assignment!</div>
<div class="feedback-explanation">You've assigned a specific role/expertise. While research shows minimal impact on correctness, this can improve response style and domain-specific language.</div>
`;
} else {
result.innerHTML = `
<div class="feedback-result">Add role assignment</div>
<div class="feedback-explanation">Try starting with "You are a [role]..." or "As a [expert type]..." to assign specific expertise or perspective.</div>
`;
}
result.classList.add('show');
}
function testApplicationPrompt() {
const textarea = document.querySelector('#application-prompt-builder textarea');
const testInput = document.querySelector('#application-prompt-builder .builder-section:nth-child(2) textarea');
const results = document.getElementById('application-results');
if (!textarea || !results) return;
const prompt = textarea.value.trim();
const testData = testInput ? testInput.value.trim() : '';
if (prompt.length < 100) {
results.innerHTML = `
<div class="feedback-result">Prompt needs more detail</div>
<div class="feedback-explanation">Real-world applications need detailed prompts with specific instructions, output formats, and context.</div>
`;
} else if (prompt.includes('format') && prompt.includes(':')) {
results.innerHTML = `
<div class="feedback-result correct">Professional Application Prompt!</div>
<div class="feedback-explanation">Great job! Your prompt includes structured output format and clear instructions - perfect for business applications.</div>
${testData ? `<div class="test-preview"><strong>Test Output Preview:</strong><br>This prompt would process: "${testData}" and provide structured results in your specified format.</div>` : ''}
`;
} else {
results.innerHTML = `
<div class="feedback-result">Good foundation</div>
<div class="feedback-explanation">Consider adding specific output format requirements (Category:, Action:, etc.) to make it more actionable for business use.</div>
`;
}
results.classList.add('show');
}
// Prompt Builder Lab Functions
function generatePrompt() {
const technique = document.querySelector('input[name="technique"]:checked')?.value;
const task = document.getElementById('task-definition')?.value;
const context = document.getElementById('context-input')?.value;
const outputFormat = document.getElementById('output-format')?.value;
const output = document.getElementById('generated-prompt-output');
if (!technique || !task) {
alert('Please select a technique and define a task.');
return;
}
let prompt = '';
switch(technique) {
case 'zero-shot':
prompt = `${context ? context + '\n\n' : ''}${task}`;
if (outputFormat !== 'paragraph') {
prompt += `\n\nFormat your response as ${outputFormat.replace('-', ' ')}.`;
}
break;
case 'few-shot':
prompt = `${context ? context + '\n\n' : ''}Here are some examples:\n\nExample 1: [Input] → [Output]\nExample 2: [Input] → [Output]\nExample 3: [Input] → [Output]\n\nNow, ${task.toLowerCase()}`;
break;
case 'chain-thought':
prompt = `${context ? context + '\n\n' : ''}${task}\n\nThink step by step:\n1. First, analyze...\n2. Then, consider...\n3. Finally, conclude...`;
break;
case 'role':
prompt = `You are an expert in this field. ${context ? context + '\n\n' : ''}${task}\n\nProvide a detailed, professional response based on your expertise.`;
break;
}
if (outputFormat !== 'paragraph') {
const formatInstructions = {
'bullet-points': 'Use bullet points for your response.',
'json': 'Provide your response in JSON format.',
'table': 'Format your response as a table.',
'numbered-list': 'Use a numbered list format.'
};
prompt += `\n\n${formatInstructions[outputFormat]}`;
}
if (output) {
output.textContent = prompt;
}
}
function copyPrompt() {
const output = document.getElementById('generated-prompt-output');
if (output) {
navigator.clipboard.writeText(output.textContent).then(() => {
alert('Prompt copied to clipboard!');
});
}
}
function testGeneratedPrompt() {
const output = document.getElementById('generated-prompt-output');
if (output && output.textContent.trim()) {
alert('In a real application, this would test your prompt with sample inputs and show results.');
} else {
alert('Please generate a prompt first.');
}
}
function savePrompt() {
const output = document.getElementById('generated-prompt-output');
if (!output || !output.textContent.trim()) {
alert('Please generate a prompt first.');
return;
}
const title = prompt('Enter a title for this prompt:') || 'Untitled Prompt';
courseManager.savePrompt(output.textContent, title);
alert('Prompt saved to your library!');
}
// A/B Testing Functions
function addTestCase() {
const testInputs = document.querySelector('.test-inputs');
const caseCount = testInputs.querySelectorAll('.test-case').length;
const newCase = document.createElement('div');
newCase.className = 'test-case';
newCase.innerHTML = `<input type="text" class="form-control" placeholder="Test case ${caseCount + 1}..." id="test-case-${caseCount + 1}">`;
const addButton = testInputs.querySelector('button');
testInputs.insertBefore(newCase, addButton);
}
function runABTest() {
const promptA = document.getElementById('prompt-a')?.value;
const promptB = document.getElementById('prompt-b')?.value;
const results = document.getElementById('ab-test-results');
if (!promptA || !promptB) {
alert('Please enter both prompt variants.');
return;
}
const testCases = [];
document.querySelectorAll('.test-case input').forEach((input, index) => {
if (input.value.trim()) {
testCases.push(input.value.trim());
}
});
if (testCases.length === 0) {
alert('Please add at least one test case.');
return;
}
// Simulate results
const resultsA = document.getElementById('results-a');
const resultsB = document.getElementById('results-b');
const metrics = document.getElementById('performance-metrics');
let htmlA = '';
let htmlB = '';
testCases.forEach((testCase, index) => {
htmlA += `<div class="result-item"><strong>Test ${index + 1}:</strong> Simulated response for "${testCase}" using Prompt A</div>`;
htmlB += `<div class="result-item"><strong>Test ${index + 1}:</strong> Simulated response for "${testCase}" using Prompt B</div>`;
});
if (resultsA) resultsA.innerHTML = htmlA;
if (resultsB) resultsB.innerHTML = htmlB;
// Simulate performance metrics
const accuracyA = 75 + Math.random() * 20;
const accuracyB = 70 + Math.random() * 25;
const winner = accuracyA > accuracyB ? 'A' : 'B';
if (metrics) {
metrics.innerHTML = `
<div class="metric">
<strong>Prompt A Accuracy:</strong> ${accuracyA.toFixed(1)}%
</div>
<div class="metric">
<strong>Prompt B Accuracy:</strong> ${accuracyB.toFixed(1)}%
</div>
<div class="metric winner">
<strong>Winner:</strong> Prompt ${winner} (${Math.abs(accuracyA - accuracyB).toFixed(1)}% difference)
</div>
`;
}
if (results) {
results.classList.add('show');
}
}
// Technique Mixer Functions
function mixTechniques() {
const selectedTechniques = [];
document.querySelectorAll('.checkbox-grid input[type="checkbox"]:checked').forEach(cb => {
selectedTechniques.push(cb.value);
});
const task = document.getElementById('mixer-task')?.value;
const output = document.getElementById('mixed-prompt-output');
const explanation = document.getElementById('combination-explanation');
if (selectedTechniques.length === 0 || !task) {
alert('Please select at least one technique and define a task.');
return;
}
let prompt = '';
let explanationText = 'This combination works because:\n\n';
// Build combined prompt
if (selectedTechniques.includes('role')) {
prompt += 'You are an expert in this field. ';
explanationText += '• Role assignment provides domain expertise and professional perspective\n';
}
if (selectedTechniques.includes('context')) {
prompt += 'Given the following context: [CONTEXT HERE]\n\n';
explanationText += '• Rich context helps the AI understand the specific situation and requirements\n';
}
if (selectedTechniques.includes('few-shot')) {
prompt += 'Here are examples:\nExample 1: [Input] → [Output]\nExample 2: [Input] → [Output]\n\n';
explanationText += '• Few-shot examples establish clear patterns and expected output format\n';
}
prompt += task;
if (selectedTechniques.includes('chain-thought')) {
prompt += '\n\nThink step by step and show your reasoning process.';
explanationText += '• Chain-of-thought reasoning improves accuracy on complex problems\n';
}
if (selectedTechniques.includes('format')) {
prompt += '\n\nFormat your response as:\n1. Main Point:\n2. Supporting Details:\n3. Conclusion:';
explanationText += '• Structured formatting ensures consistent, actionable outputs\n';
}
if (selectedTechniques.includes('constraints')) {
prompt += '\n\nConstraints:\n- Keep response under 200 words\n- Use clear, non-technical language\n- Include specific examples';
explanationText += '• Clear constraints guide the AI toward desired response characteristics\n';
}
if (output) {
output.textContent = prompt;
}
if (explanation) {
explanation.textContent = explanationText;
}
}
// Quiz Functions
function startQuiz() {
const intro = document.querySelector('.quiz-intro');
const container = document.getElementById('quiz-container');
if (intro) intro.classList.add('hidden');
if (container) container.classList.remove('hidden');
courseManager.currentQuestionIndex = 0;
courseManager.quizAnswers = [];
showQuestion();
}
function showQuestion() {
const question = courseManager.quizData[courseManager.currentQuestionIndex];
const questionText = document.getElementById('question-text');
const answerOptions = document.getElementById('answer-options');
const currentQuestion = document.getElementById('current-question');
const totalQuestions = document.getElementById('total-questions');
const progress = document.getElementById('quiz-progress');
const prevBtn = document.getElementById('prev-btn');
const nextBtn = document.getElementById('next-btn');
if (questionText) questionText.textContent = question.question;
if (currentQuestion) currentQuestion.textContent = courseManager.currentQuestionIndex + 1;
if (totalQuestions) totalQuestions.textContent = courseManager.quizData.length;
if (progress) {
const progressPercent = ((courseManager.currentQuestionIndex + 1) / courseManager.quizData.length) * 100;
progress.style.width = `${progressPercent}%`;
}
if (answerOptions) {
let html = '';
question.options.forEach((option, index) => {
const isSelected = courseManager.quizAnswers[courseManager.currentQuestionIndex] === index;
html += `
<button class="answer-option ${isSelected ? 'selected' : ''}" onclick="selectAnswer(${index})">
${option}
</button>
`;
});
answerOptions.innerHTML = html;
}
if (prevBtn) {
prevBtn.disabled = courseManager.currentQuestionIndex === 0;
}
if (nextBtn) {
if (courseManager.currentQuestionIndex === courseManager.quizData.length - 1) {
nextBtn.textContent = 'Finish Quiz';
} else {
nextBtn.textContent = 'Next →';
}
}
}
function selectAnswer(answerIndex) {
courseManager.quizAnswers[courseManager.currentQuestionIndex] = answerIndex;
// Update UI
document.querySelectorAll('.answer-option').forEach((btn, index) => {
btn.classList.toggle('selected', index === answerIndex);
});
}
function previousQuestion() {
if (courseManager.currentQuestionIndex > 0) {
courseManager.currentQuestionIndex--;
showQuestion();
}
}
function nextQuestion() {
if (courseManager.currentQuestionIndex < courseManager.quizData.length - 1) {
courseManager.currentQuestionIndex++;
showQuestion();
} else {
finishQuiz();
}
}
function finishQuiz() {
const container = document.getElementById('quiz-container');
const results = document.getElementById('quiz-results');
if (container) container.classList.add('hidden');
if (results) results.classList.remove('hidden');
calculateQuizResults();
}
function calculateQuizResults() {
let correctAnswers = 0;
const topicScores = {};
courseManager.quizData.forEach((question, index) => {
const userAnswer = courseManager.quizAnswers[index];
const isCorrect = userAnswer === question.correct;
if (isCorrect) correctAnswers++;
// Track topic scores
if (!topicScores[question.topic]) {
topicScores[question.topic] = { correct: 0, total: 0 };
}
topicScores[question.topic].total++;
if (isCorrect) topicScores[question.topic].correct++;
});
const scorePercent = Math.round((correctAnswers / courseManager.quizData.length) * 100);
const passed = scorePercent >= 80;
// Update results display
const finalScore = document.getElementById('final-score');
const passStatus = document.getElementById('pass-status');
const topicScoresDiv = document.getElementById('topic-scores');
const recommendations = document.getElementById('recommendations');
const certificateSection = document.getElementById('certificate-section');
if (finalScore) finalScore.textContent = scorePercent;
if (passStatus) {
passStatus.textContent = passed ? '✅ Congratulations! You Passed!' : '❌ Keep Learning!';
passStatus.className = `pass-status ${passed ? 'passed' : 'failed'}`;
}
// Topic breakdown
if (topicScoresDiv) {
let html = '';
Object.entries(topicScores).forEach(([topic, scores]) => {
const percent = Math.round((scores.correct / scores.total) * 100);
html += `
<div class="topic-score">
<span>${topic}</span>
<span>${scores.correct}/${scores.total}</span>
<div class="topic-bar">
<div class="topic-fill" style="width: ${percent}%"></div>
</div>
</div>
`;
});
topicScoresDiv.innerHTML = html;
}
// Recommendations
if (recommendations) {
let html = '';
const weakTopics = Object.entries(topicScores)
.filter(([topic, scores]) => (scores.correct / scores.total) < 0.7)
.map(([topic]) => topic);
if (weakTopics.length > 0) {
html += `<div class="recommendation-item">📚 Review these topics: ${weakTopics.join(', ')}</div>`;
}
if (scorePercent < 80) {
html += `<div class="recommendation-item">🔄 Retake the quiz after reviewing the course materials</div>`;
html += `<div class="recommendation-item">💡 Focus on hands-on practice with the interactive labs</div>`;