-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathemail-classification.js
More file actions
165 lines (138 loc) · 4.69 KB
/
email-classification.js
File metadata and controls
165 lines (138 loc) · 4.69 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
#!/usr/bin/env node
/**
* Real-world Example: Email Classification Pipeline
* Uses model routing + caching + batching for maximum savings
*/
const ModelRouter = require('../model-router');
const PromptCache = require('../prompt-cache');
const ResponseCache = require('../response-cache');
class EmailClassifier {
constructor() {
this.router = new ModelRouter();
this.promptCache = new PromptCache();
this.responseCache = new ResponseCache({ maxSize: 5000 });
this.systemPrompt = `You are an expert email classifier. Classify emails into categories:
- urgent: Requires immediate action
- important: Worth reading but not urgent
- marketing: Promotional content
- spam: Unsolicited messages
- archive: Can be deleted or archived
Respond with ONLY the category name.`;
}
/**
* Classify a single email with optimization
*/
async classifyEmail(email) {
// Check response cache first
const cached = this.responseCache.get(email.subject, 'haiku-4-5');
if (cached) {
return { ...cached, source: 'cache' };
}
// Route based on complexity (check for indicators)
const complexity = this.analyzeEmailComplexity(email);
const routing = this.router.selectModel(email.subject, { requiresReasoning: complexity === 'complex' });
// Prepare for caching
const optimized = this.promptCache.optimizeForCaching([
{ role: 'user', content: email.subject }
], this.systemPrompt);
// Simulate API call
const result = {
category: this.simulateClassification(email),
model: routing.model,
confidence: Math.random() * 0.3 + 0.7, // 0.7-1.0
source: 'api'
};
// Cache the response
this.responseCache.set(email.subject, result, 'haiku-4-5');
return result;
}
/**
* Analyze email complexity
*/
analyzeEmailComplexity(email) {
const length = email.subject.length + (email.body?.length || 0);
const hasAttachments = email.attachments?.length > 0;
const isReply = email.inReplyTo !== undefined;
if (length > 1000 || hasAttachments || isReply) {
return 'complex';
}
return 'simple';
}
/**
* Simulate classification (replace with real API call)
*/
simulateClassification(email) {
const categories = ['urgent', 'important', 'marketing', 'spam', 'archive'];
const keywords = {
urgent: ['urgent', 'asap', 'critical', 'emergency'],
important: ['meeting', 'deadline', 'review', 'approval'],
marketing: ['sale', 'offer', 'discount', 'limited time'],
spam: ['unsubscribe', 'click here', 'guaranteed']
};
for (const [cat, words] of Object.entries(keywords)) {
for (const word of words) {
if (email.subject.toLowerCase().includes(word)) {
return cat;
}
}
}
return 'archive';
}
/**
* Batch process multiple emails
*/
async batchClassify(emails) {
const results = [];
const stats = {
total: emails.length,
cached: 0,
api: 0,
byModel: {}
};
for (const email of emails) {
const result = await this.classifyEmail(email);
results.push({ email: email.subject, ...result });
if (result.source === 'cache') stats.cached++;
if (result.source === 'api') stats.api++;
const model = result.model.split('/')[1];
stats.byModel[model] = (stats.byModel[model] || 0) + 1;
}
return { results, stats, cacheMetrics: this.responseCache.getStats() };
}
/**
* Get optimization report
*/
getReport() {
const cacheStats = this.responseCache.getStats();
return {
cacheMetrics: cacheStats,
optimizationImpact: {
estimatedSavings: `${cacheStats.hitRate} hit rate = ~50-70% cost reduction`,
cacheHits: cacheStats.hits,
apiCalls: cacheStats.misses,
totalQueries: cacheStats.hits + cacheStats.misses
}
};
}
}
// Example usage
if (require.main === module) {
const classifier = new EmailClassifier();
const testEmails = [
{ subject: 'Urgent: Server Down', body: 'Our production server is down' },
{ subject: 'Urgent: Server Down', body: 'Same email again (cached)' },
{ subject: 'Meeting Tomorrow at 3pm', body: 'Team standup' },
{ subject: 'Special Offer: 50% Off!', body: 'Limited time sale' },
{ subject: 'Unsubscribe from mailing list', body: 'Spam email' }
];
classifier.batchClassify(testEmails).then(result => {
console.log('Classification Results:');
result.results.forEach(r => {
console.log(` ${r.email}: ${r.category} (${r.source})`);
});
console.log('\nStats:', result.stats);
console.log('\nCache Metrics:', result.cacheMetrics);
console.log('\nOptimization Report:', classifier.getReport());
});
}
module.exports = EmailClassifier;