import OpenAI from 'openai';
import { Todo } from './redis-client.js';
export class AIService {
private openai: OpenAI;
constructor(apiKey: string) {
this.openai = new OpenAI({
apiKey,
});
}
async analyzeTodos(todos: Todo[]): Promise<string> {
if (todos.length === 0) {
return 'No todos to analyze. Add some tasks first!';
}
const pendingTodos = todos.filter(t => t.status === 'pending');
if (pendingTodos.length === 0) {
return 'All tasks completed!';
}
const todosList = pendingTodos
.map((t, i) => `${i + 1}. ${t.title} - ${t.description}`)
.join('\n');
const prompt = `Analyze this task list and provide prioritization recommendations based on impact, urgency, dependencies, and effort.
Tasks:
${todosList}
Provide:
1. Top 3 highest priority tasks with brief explanation
2. Suggested order of execution
3. Tasks that could be delegated or eliminated
4. Quick wins that could be done immediately
Keep the response concise and actionable.`;
try {
const completion = await this.openai.chat.completions.create({
model: 'gpt-4o-mini',
messages: [
{
role: 'system',
content: 'Provide task prioritization analysis.'
},
{
role: 'user',
content: prompt
}
],
temperature: 0.7,
max_tokens: 1000,
});
return completion.choices[0]?.message?.content || 'Unable to generate analysis.';
} catch (error) {
console.error('OpenAI API error:', error);
return this.fallbackAnalysis(pendingTodos);
}
}
private fallbackAnalysis(todos: Todo[]): string {
const priorityOrder = { high: 1, medium: 2, low: 3 };
const sorted = [...todos].sort((a, b) => {
const aPriority = priorityOrder[a.priority || 'medium'];
const bPriority = priorityOrder[b.priority || 'medium'];
return aPriority - bPriority;
});
let analysis = 'Task Prioritization Analysis\n\n';
analysis += 'High Priority Tasks:\n';
const top3 = sorted.slice(0, 3);
top3.forEach((todo, i) => {
analysis += `${i + 1}. ${todo.title}\n → ${todo.description}\n`;
});
analysis += '\nRecommendation: Focus on completing high priority tasks first.\n';
analysis += `Total pending tasks: ${todos.length}\n`;
return analysis;
}
}