/**
* AI Prompt Management System
* Handles model-specific prompt optimization and use case templates
*/
export class PromptManager {
constructor() {
this.modelConfigs = {
claude: {
name: 'Claude',
maxTokens: 4096,
supportsSystemPrompts: true,
responseStyle: 'detailed',
strengths: ['reasoning', 'analysis', 'writing', 'following instructions'],
promptStyle: 'structured'
},
mistral: {
name: 'Mistral',
maxTokens: 2048,
supportsSystemPrompts: false,
responseStyle: 'concise',
strengths: ['efficiency', 'multilingual', 'code'],
promptStyle: 'direct'
},
gemini: {
name: 'Gemini',
maxTokens: 2048,
supportsSystemPrompts: true,
responseStyle: 'balanced',
strengths: ['multimodal', 'reasoning', 'creativity'],
promptStyle: 'conversational'
},
llama: {
name: 'Llama',
maxTokens: 2048,
supportsSystemPrompts: false,
responseStyle: 'straightforward',
strengths: ['efficiency', 'code', 'factual'],
promptStyle: 'simple'
},
gpt: {
name: 'GPT',
maxTokens: 4096,
supportsSystemPrompts: true,
responseStyle: 'creative',
strengths: ['creativity', 'conversation', 'general knowledge'],
promptStyle: 'flexible'
}
};
this.useCaseTemplates = {
emailReply: {
purpose: 'Generate personalized email replies',
context: ['original_email', 'user_style', 'relationship', 'tone'],
outputFormat: 'email',
requirements: ['professional', 'concise', 'actionable']
},
emailSummary: {
purpose: 'Summarize email content',
context: ['email_content', 'urgency', 'category'],
outputFormat: 'bullet_points',
requirements: ['accurate', 'brief', 'highlight_actions']
},
emailCategorization: {
purpose: 'Categorize emails intelligently',
context: ['sender', 'subject', 'content', 'patterns'],
outputFormat: 'structured_data',
requirements: ['consistent', 'logical', 'actionable']
},
contactAnalysis: {
purpose: 'Analyze email relationships for contact creation',
context: ['interaction_history', 'frequency', 'relationship_type'],
outputFormat: 'analysis',
requirements: ['accurate', 'relationship_aware', 'privacy_conscious']
},
newsDigest: {
purpose: 'Create news summaries from newsletters',
context: ['news_content', 'relevance', 'user_interests'],
outputFormat: 'digest',
requirements: ['concise', 'relevant', 'unbiased']
}
};
}
/**
* Generate optimized prompt for specific AI model and use case
*/
generatePrompt(useCase, model = 'claude', context = {}, userStyle = {}) {
const modelConfig = this.modelConfigs[model] || this.modelConfigs.claude;
const template = this.useCaseTemplates[useCase];
if (!template) {
throw new Error(`Unknown use case: ${useCase}`);
}
return this.buildPrompt(template, modelConfig, context, userStyle);
}
/**
* Build prompt based on model capabilities and use case
*/
buildPrompt(template, modelConfig, context, userStyle) {
const prompt = {
system: modelConfig.supportsSystemPrompts ? this.buildSystemPrompt(template, modelConfig, userStyle) : null,
user: this.buildUserPrompt(template, modelConfig, context, userStyle),
constraints: this.buildConstraints(template, modelConfig),
formatting: this.buildFormatting(template, modelConfig)
};
return prompt;
}
/**
* Build system prompt for models that support it
*/
buildSystemPrompt(template, modelConfig, userStyle) {
let systemPrompt = `You are an intelligent email assistant specialized in ${template.purpose.toLowerCase()}.`;
if (userStyle.writingStyle) {
systemPrompt += `\n\nUser's Writing Style: ${userStyle.writingStyle}`;
}
if (userStyle.signature) {
systemPrompt += `\nAlways end emails with: ${userStyle.signature}`;
}
systemPrompt += `\n\nKey Principles:`;
template.requirements.forEach(req => {
systemPrompt += `\n- Be ${req}`;
});
// Model-specific optimizations
if (modelConfig.name === 'Claude') {
systemPrompt += `\n\nApproach: Think step-by-step and provide detailed reasoning for decisions.`;
} else if (modelConfig.name === 'Mistral') {
systemPrompt += `\n\nApproach: Be direct and efficient in your responses.`;
} else if (modelConfig.name === 'Gemini') {
systemPrompt += `\n\nApproach: Consider multiple perspectives and provide balanced responses.`;
}
return systemPrompt;
}
/**
* Build user prompt with context
*/
buildUserPrompt(template, modelConfig, context, userStyle) {
let userPrompt = '';
// Add context sections
if (context.originalEmail) {
userPrompt += `ORIGINAL EMAIL:\n${this.formatEmailContext(context.originalEmail)}\n\n`;
}
if (context.userWritingStyle) {
userPrompt += `YOUR WRITING STYLE:\n${this.formatWritingStyle(context.userWritingStyle)}\n\n`;
}
if (context.relationship) {
userPrompt += `RELATIONSHIP CONTEXT: ${context.relationship}\n\n`;
}
if (context.additionalContext) {
userPrompt += `ADDITIONAL CONTEXT: ${context.additionalContext}\n\n`;
}
// Add task-specific instructions
userPrompt += this.getTaskInstructions(template, modelConfig);
return userPrompt;
}
/**
* Build constraints based on model limitations
*/
buildConstraints(template, modelConfig) {
const constraints = [];
// Token limits
if (modelConfig.maxTokens <= 2048) {
constraints.push('Keep response under 300 words');
} else {
constraints.push('Provide comprehensive but concise response');
}
// Model-specific constraints
if (!modelConfig.supportsSystemPrompts) {
constraints.push('Include all instructions in single prompt');
}
return constraints;
}
/**
* Build formatting requirements
*/
buildFormatting(template, modelConfig) {
const formatting = {
outputFormat: template.outputFormat
};
switch (template.outputFormat) {
case 'email':
formatting.structure = ['greeting', 'body', 'closing', 'signature'];
break;
case 'bullet_points':
formatting.structure = ['key_points', 'actions_needed'];
break;
case 'structured_data':
formatting.structure = ['category', 'priority', 'reasoning'];
break;
}
return formatting;
}
/**
* Get task-specific instructions
*/
getTaskInstructions(template, modelConfig) {
const instructions = {
emailReply: this.getEmailReplyInstructions(modelConfig),
emailSummary: this.getEmailSummaryInstructions(modelConfig),
emailCategorization: this.getCategorizationInstructions(modelConfig),
contactAnalysis: this.getContactAnalysisInstructions(modelConfig),
newsDigest: this.getNewsDigestInstructions(modelConfig)
};
return instructions[template.purpose] || '';
}
/**
* Email reply specific instructions
*/
getEmailReplyInstructions(modelConfig) {
let instructions = `TASK: Generate an email reply that matches the user's writing style and appropriately addresses the original email.
REQUIREMENTS:
1. Address all key points from the original email
2. Match the user's tone and writing style
3. Be professional but authentic
4. Include appropriate call-to-action if needed
5. Always end with "Best," as signature
OUTPUT FORMAT:
[Subject: Re: Original Subject]
[Greeting]
[Body paragraphs addressing the email]
[Closing]
Best,`;
// Model-specific optimizations
if (modelConfig.name === 'Claude') {
instructions += `\n\nAnalyze the original email's tone and context before responding. Consider the relationship dynamics and respond appropriately.`;
} else if (modelConfig.name === 'Mistral') {
instructions += `\n\nBe direct and efficient. Focus on the key points and provide a clear response.`;
} else if (modelConfig.name === 'Llama') {
instructions += `\n\nProvide a straightforward response that addresses the main points clearly.`;
}
return instructions;
}
/**
* Email summary instructions
*/
getEmailSummaryInstructions(modelConfig) {
return `TASK: Create a concise summary of the email content.
REQUIREMENTS:
1. Extract key information and main points
2. Identify any required actions
3. Note urgency level
4. Highlight important dates or deadlines
OUTPUT FORMAT:
📧 SUMMARY:
• [Main point 1]
• [Main point 2]
🎯 ACTIONS REQUIRED:
• [Action 1]
• [Action 2]
⏰ URGENCY: [Low/Medium/High]`;
}
/**
* Email categorization instructions
*/
getCategorizationInstructions(modelConfig) {
return `TASK: Categorize this email based on its content, sender, and context.
CATEGORIES:
- Personal: Family, friends, personal matters
- Business: Work, professional communications
- Financial: Banking, investments, bills
- Shopping: Orders, receipts, deliveries
- News: Newsletters, news updates
- Technical: Software, services, notifications
- Education: Schools, courses, learning
- Archive: Old, completed, or irrelevant items
OUTPUT FORMAT:
{
"category": "category_name",
"subcategory": "specific_type",
"priority": "high/medium/low",
"keep_in_inbox": true/false,
"reasoning": "explanation for categorization"
}`;
}
/**
* Contact analysis instructions
*/
getContactAnalysisInstructions(modelConfig) {
return `TASK: Analyze email interactions to determine if contacts should be created.
CRITERIA FOR CONTACT CREATION:
1. People you actively communicate with (sent emails to)
2. Family and friends from personal domains
3. Work colleagues and business contacts
4. Frequent meaningful interactions
EXCLUDE:
- Marketing emails
- Newsletters
- Automated systems
- One-time transactions
OUTPUT FORMAT:
{
"should_create_contact": true/false,
"contact_category": "Personal/Business/Education",
"relationship_type": "family/friend/colleague/client",
"interaction_frequency": "high/medium/low",
"reasoning": "explanation"
}`;
}
/**
* News digest instructions
*/
getNewsDigestInstructions(modelConfig) {
return `TASK: Create a digest of news content highlighting relevant information.
FOCUS AREAS:
- Technology and business news
- Important world events
- Market updates
- Policy changes that affect individuals
OUTPUT FORMAT:
📰 NEWS DIGEST
🔴 HIGH PRIORITY:
• [Critical news item 1]
• [Critical news item 2]
🟡 MEDIUM PRIORITY:
• [Important update 1]
• [Important update 2]
💡 INTERESTING:
• [Notable item 1]
• [Notable item 2]`;
}
/**
* Format email context for prompts
*/
formatEmailContext(email) {
return `From: ${email.from}
To: ${email.to || 'You'}
Subject: ${email.subject}
Date: ${email.date}
Content:
${email.content}`;
}
/**
* Format writing style for prompts
*/
formatWritingStyle(style) {
return `Tone: ${style.tone || 'Professional'}
Average Length: ${style.avgLength || 'Medium'} words
Common Phrases: ${style.commonPhrases ? style.commonPhrases.join(', ') : 'None specified'}
Formality: ${style.formality || 'Balanced'}
Signature: ${style.signature || 'Best,'}`;
}
/**
* Detect AI model from response or configuration
*/
detectModel(input) {
// In practice, this would detect from API responses or configuration
// For now, default to Claude
return 'claude';
}
/**
* Get optimal model for specific use case
*/
getOptimalModel(useCase, availableModels = ['claude']) {
const preferences = {
emailReply: ['claude', 'gpt', 'gemini', 'mistral', 'llama'],
emailSummary: ['claude', 'mistral', 'llama', 'gemini', 'gpt'],
emailCategorization: ['claude', 'gemini', 'mistral', 'llama', 'gpt'],
contactAnalysis: ['claude', 'gemini', 'gpt', 'mistral', 'llama'],
newsDigest: ['claude', 'gemini', 'gpt', 'mistral', 'llama']
};
const preferred = preferences[useCase] || ['claude'];
return preferred.find(model => availableModels.includes(model)) || availableModels[0];
}
/**
* Validate prompt length against model constraints
*/
validatePromptLength(prompt, model) {
const config = this.modelConfigs[model];
const estimatedTokens = prompt.length / 4; // Rough estimate
if (estimatedTokens > config.maxTokens * 0.7) { // Leave room for response
return {
valid: false,
reason: `Prompt too long for ${model} (estimated ${estimatedTokens} tokens, max ${config.maxTokens})`
};
}
return { valid: true };
}
}
export default PromptManager;