File size: 8,500 Bytes
e706de2 |
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 |
/**
* Part 1 Capstone: Smart Email Classifier
*
* Build an AI system that organizes your inbox by classifying emails into categories.
*
* Skills Used:
* - Runnables for processing pipeline
* - Messages for structured classification
* - LLM wrapper for flexible model switching
* - Context for classification history
*
* Difficulty: βββββ
*/
import {SystemMessage, HumanMessage, Runnable, LlamaCppLLM} from '../../../src/index.js';
import {BaseCallback} from '../../../src/utils/callbacks.js';
import { readFileSync } from 'fs';
// ============================================================================
// EMAIL CLASSIFICATION CATEGORIES
// ============================================================================
const CATEGORIES = {
SPAM: 'Spam',
INVOICE: 'Invoice',
MEETING: 'Meeting Request',
URGENT: 'Urgent',
PERSONAL: 'Personal',
OTHER: 'Other'
};
// ============================================================================
// TODO 1: Email Parser Runnable
// ============================================================================
/**
* Parses raw email text into structured format
*
* Input: { subject: string, body: string, from: string }
* Output: { subject, body, from, timestamp }
*/
class EmailParserRunnable extends Runnable {
async _call(input, config) {
// TODO: Parse and structure the email
// Validate required fields (subject, body, from)
// Add timestamp
// Return structured email object
return null; // Replace with your implementation
}
}
// ============================================================================
// TODO 2: Email Classifier Runnable
// ============================================================================
/**
* Classifies email using LLM
*
* Input: { subject, body, from, timestamp }
* Output: { ...email, category, confidence, reason }
*/
class EmailClassifierRunnable extends Runnable {
constructor(llm) {
super();
this.llm = llm;
}
async _call(input, config) {
// TODO: Create a prompt for the LLM
// Ask it to classify the email into one of the categories
// Request: category, confidence (0-1), and reason
// TODO: Parse the LLM response
// Extract category, confidence, reason
// TODO: Return email with classification
return null; // Replace with your implementation
}
_buildPrompt(email) {
// TODO: Build a good classification prompt
// Include: categories, email details, instructions
return null; // Replace with your implementation
}
_parseClassification(response) {
// TODO: Parse LLM response into structured format
// Extract: category, confidence, reason
return null; // Replace with your implementation
}
}
// ============================================================================
// TODO 3: Classification History Callback
// ============================================================================
/**
* Tracks classification history using callbacks
*/
class ClassificationHistoryCallback extends BaseCallback {
constructor() {
super();
this.history = [];
}
async onEnd(runnable, output, config) {
// TODO: If this is an EmailClassifierRunnable, save the classification
// Store: timestamp, email subject, category, confidence
}
getHistory() {
return this.history;
}
getStatistics() {
// TODO: Calculate statistics
// - Total emails classified
// - Count per category
// - Average confidence
return null; // Replace with your implementation
}
printHistory() {
console.log('\nπ§ Classification History:');
console.log('β'.repeat(70));
// TODO: Print each classification nicely
}
printStatistics() {
console.log('\nπ Classification Statistics:');
console.log('β'.repeat(70));
// TODO: Print statistics
}
}
// ============================================================================
// TODO 4: Email Classification Pipeline
// ============================================================================
/**
* Complete pipeline: Parse β Classify β Store
*/
class EmailClassificationPipeline {
constructor(llm) {
// TODO: Create the pipeline
// parser -> classifier
// Add history callback
this.parser = null; // new EmailParserRunnable()
this.classifier = null; // new EmailClassifierRunnable(llm)
this.historyCallback = null; // new ClassificationHistoryCallback()
this.pipeline = null; // Build the pipeline
}
async classify(email) {
// TODO: Run the email through the pipeline
// Pass the history callback in config
return null; // Replace with your implementation
}
getHistory() {
return this.historyCallback.getHistory();
}
getStatistics() {
return this.historyCallback.getStatistics();
}
printHistory() {
this.historyCallback.printHistory();
}
printStatistics() {
this.historyCallback.printStatistics();
}
}
// ============================================================================
// TEST DATA
// ============================================================================
const TEST_EMAILS = JSON.parse(
readFileSync(new URL('./test-emails.json', import.meta.url), 'utf-8')
);
// ============================================================================
// MAIN FUNCTION
// ============================================================================
async function main() {
console.log('=== Part 1 Capstone: Smart Email Classifier ===\n');
// TODO: Initialize the LLM
// Adjust modelPath to your model
const llm = null; // new LlamaCppLLM({ ... })
// TODO: Create the classification pipeline
const pipeline = null; // new EmailClassificationPipeline(llm)
console.log('π¬ Processing emails...\n');
// TODO: Classify each test email
for (const email of TEST_EMAILS) {
// Classify
// Print result
}
// TODO: Print history and statistics
// pipeline.printHistory()
// pipeline.printStatistics()
// TODO: Cleanup
// await llm.dispose()
console.log('\nβ Capstone Project Complete!');
}
// Run the project
main().catch(console.error);
/**
* TODO CHECKLIST:
*
* [ ] 1. EmailParserRunnable
* - Parse email structure
* - Add timestamp
* - Validate fields
*
* [ ] 2. EmailClassifierRunnable
* - Build classification prompt
* - Call LLM
* - Parse response
* - Return classified email
*
* [ ] 3. ClassificationHistoryCallback
* - Track classifications in onEnd
* - Calculate statistics
* - Print history and stats
*
* [ ] 4. EmailClassificationPipeline
* - Build parser -> classifier pipeline
* - Add history callback
* - Implement classify method
*
* [ ] 5. Main function
* - Initialize LLM
* - Create pipeline
* - Process test emails
* - Print results
*
* EXPECTED OUTPUT:
*
* π¬ Processing emails...
*
* βοΈ Email from: promotions@shop.com
* Subject: π 70% OFF SALE! Limited Time Only!!!
* Category: Spam
* Confidence: 99.0%
* Reason: Promotional content with excessive punctuation
*
* βοΈ Email from: billing@company.com
* Subject: Invoice #12345 - Payment Due
* Category: Invoice
* Confidence: 98.0%
* Reason: Contains invoice number and payment information
*
* ... (more emails)
*
* π Classification Statistics:
* ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
* Total Emails: 24
*
* By Category:
* Spam: 3 (12.5%)
* Invoice: 4 (16.7%)
* Meeting Request: 5 (20.8%)
* Urgent: 3 (12.5%)
* Personal: 4 (16.7%)
* Other: 5 (20.8%)
*
* Average Confidence: 96.7%
*/ |