intent-cli
Version:
A fully functional CLI built with TypeScript and modern tools
230 lines • 10.2 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.intentParser = exports.IntentParser = exports.IntentCategory = void 0;
const natural_1 = __importDefault(require("natural"));
const compromise_1 = __importDefault(require("compromise"));
const chalk_1 = __importDefault(require("chalk"));
// Initialize NLP tools
const tokenizer = new natural_1.default.WordTokenizer();
const stemmer = natural_1.default.PorterStemmer;
const classifier = new natural_1.default.BayesClassifier();
// Intent categories
var IntentCategory;
(function (IntentCategory) {
IntentCategory["SYSTEM_INFO"] = "system_info";
IntentCategory["FILE_OPERATIONS"] = "file_operations";
IntentCategory["PRODUCTIVITY"] = "productivity";
IntentCategory["NETWORK"] = "network";
IntentCategory["CALCULATOR"] = "calculator";
IntentCategory["TIMER"] = "timer";
IntentCategory["NOTES"] = "notes";
IntentCategory["HELP"] = "help";
IntentCategory["EXIT"] = "exit";
IntentCategory["UNKNOWN"] = "unknown";
})(IntentCategory || (exports.IntentCategory = IntentCategory = {}));
class IntentParser {
constructor() {
this.isInitialized = false;
this.initializeTrainingData();
}
initializeTrainingData() {
// Train the classifier with sample phrases
const trainingData = [
// System Info
['show system information', IntentCategory.SYSTEM_INFO],
['check cpu usage', IntentCategory.SYSTEM_INFO],
['how much memory', IntentCategory.SYSTEM_INFO],
['disk space', IntentCategory.SYSTEM_INFO],
['system stats', IntentCategory.SYSTEM_INFO],
['computer info', IntentCategory.SYSTEM_INFO],
// File Operations
['create file', IntentCategory.FILE_OPERATIONS],
['read file', IntentCategory.FILE_OPERATIONS],
['delete file', IntentCategory.FILE_OPERATIONS],
['list files', IntentCategory.FILE_OPERATIONS],
['search file', IntentCategory.FILE_OPERATIONS],
['make directory', IntentCategory.FILE_OPERATIONS],
// Productivity
['start timer', IntentCategory.PRODUCTIVITY],
['pomodoro', IntentCategory.PRODUCTIVITY],
['take notes', IntentCategory.PRODUCTIVITY],
['calculator', IntentCategory.PRODUCTIVITY],
['calculate', IntentCategory.PRODUCTIVITY],
['math', IntentCategory.PRODUCTIVITY],
// Network
['check internet', IntentCategory.NETWORK],
['test connection', IntentCategory.NETWORK],
['ping', IntentCategory.NETWORK],
['network status', IntentCategory.NETWORK],
// Help
['help', IntentCategory.HELP],
['what can you do', IntentCategory.HELP],
['commands', IntentCategory.HELP],
['show options', IntentCategory.HELP],
// Exit
['exit', IntentCategory.EXIT],
['quit', IntentCategory.EXIT],
['bye', IntentCategory.EXIT],
['close', IntentCategory.EXIT],
['goodbye', IntentCategory.EXIT]
];
// Train the classifier
trainingData.forEach(([phrase, category]) => {
classifier.addDocument(phrase, category);
});
classifier.train();
this.isInitialized = true;
}
parseIntent(input) {
if (!this.isInitialized) {
this.initializeTrainingData();
}
const cleanedInput = input.toLowerCase().trim();
const tokens = tokenizer.tokenize(cleanedInput) || [];
// Use natural classification
const classifications = classifier.getClassifications(cleanedInput);
const bestClassification = classifications[0];
// Use compromise for entity extraction
const doc = (0, compromise_1.default)(cleanedInput);
// Extract entities
const entities = this.extractEntities(doc, tokens);
// Determine confidence and category
const confidence = bestClassification ? bestClassification.value : 0;
const category = this.mapToIntentCategory(bestClassification?.label || IntentCategory.UNKNOWN);
// Get suggested action
const suggestedAction = this.getSuggestedAction(category, entities, cleanedInput);
return {
category,
confidence: Math.round(confidence * 100) / 100,
entities,
originalText: input,
suggestedAction
};
}
extractEntities(doc, tokens) {
const entities = {};
// Extract numbers
const numbers = doc.numbers().json();
if (numbers.length > 0) {
entities.numbers = numbers.map((n) => n.number);
}
// Extract file extensions
const fileExtensions = tokens.filter(token => token.startsWith('.'));
if (fileExtensions.length > 0) {
entities.fileExtensions = fileExtensions;
}
// Extract time expressions
const timeExpressions = doc.match('#Time').json();
if (timeExpressions.length > 0) {
entities.timeExpressions = timeExpressions.map((t) => t.text);
}
// Extract durations
const durationWords = ['minute', 'minutes', 'hour', 'hours', 'second', 'seconds'];
const durations = tokens.filter(token => durationWords.includes(token));
if (durations.length > 0) {
entities.durations = durations;
}
// Extract file operations
const fileOps = ['create', 'make', 'delete', 'remove', 'read', 'open', 'list', 'search', 'find'];
const operations = tokens.filter(token => fileOps.includes(token));
if (operations.length > 0) {
entities.operations = operations;
}
return entities;
}
mapToIntentCategory(label) {
switch (label) {
case 'system_info':
return IntentCategory.SYSTEM_INFO;
case 'file_operations':
return IntentCategory.FILE_OPERATIONS;
case 'productivity':
return IntentCategory.PRODUCTIVITY;
case 'network':
return IntentCategory.NETWORK;
case 'calculator':
return IntentCategory.CALCULATOR;
case 'timer':
return IntentCategory.TIMER;
case 'notes':
return IntentCategory.NOTES;
case 'help':
return IntentCategory.HELP;
case 'exit':
return IntentCategory.EXIT;
default:
return IntentCategory.UNKNOWN;
}
}
getSuggestedAction(category, entities, originalText) {
const tokens = originalText.toLowerCase().split(' ');
switch (category) {
case IntentCategory.SYSTEM_INFO:
if (entities.operations?.includes('cpu') || tokens.includes('cpu')) {
return 'Show CPU information';
}
if (entities.operations?.includes('memory') || tokens.includes('memory')) {
return 'Show memory usage';
}
return 'Show system overview';
case IntentCategory.FILE_OPERATIONS:
if (entities.operations?.includes('create') || entities.operations?.includes('make')) {
return 'Create new file';
}
if (entities.operations?.includes('delete') || entities.operations?.includes('remove')) {
return 'Delete file';
}
if (entities.operations?.includes('list')) {
return 'List directory contents';
}
if (entities.operations?.includes('search') || entities.operations?.includes('find')) {
return 'Search for files';
}
return 'File operation menu';
case IntentCategory.PRODUCTIVITY:
if (entities.operations?.includes('timer') || tokens.includes('timer')) {
return 'Start timer';
}
if (entities.operations?.includes('calculate') || entities.numbers?.length > 0) {
return 'Open calculator';
}
if (entities.operations?.includes('note') || tokens.includes('note')) {
return 'Take notes';
}
return 'Productivity tools';
case IntentCategory.NETWORK:
return 'Check network status';
case IntentCategory.HELP:
return 'Show help menu';
case IntentCategory.EXIT:
return 'Exit application';
default:
return 'Show main menu';
}
}
getAvailableIntents() {
return Object.values(IntentCategory).filter(category => category !== IntentCategory.UNKNOWN);
}
isHighConfidence(intent) {
return intent.confidence >= 0.7;
}
formatIntentResult(intent) {
const confidenceColor = intent.confidence >= 0.8 ? 'green' :
intent.confidence >= 0.6 ? 'yellow' : 'red';
return [
`${chalk_1.default.bold('Intent:')} ${chalk_1.default.cyan(intent.category.replace('_', ' ').toUpperCase())}`,
`${chalk_1.default.bold('Confidence:')} ${chalk_1.default[confidenceColor](`${(intent.confidence * 100).toFixed(1)}%`)}`,
`${chalk_1.default.bold('Suggested Action:')} ${chalk_1.default.white(intent.suggestedAction || 'None')}`,
intent.entities && Object.keys(intent.entities).length > 0
? `${chalk_1.default.bold('Entities:')} ${JSON.stringify(intent.entities, null, 2)}`
: ''
].filter(Boolean).join('\n');
}
}
exports.IntentParser = IntentParser;
// Export singleton instance
exports.intentParser = new IntentParser();
//# sourceMappingURL=intent-parser.js.map