AI System Overview
CommandKit's AI system provides a comprehensive framework for creating intelligent Discord bots that can understand natural language and execute commands through large language models.
Architecture Overview
The AI system consists of several key components:
graph TD
A[Discord Message] --> B[Message Filter]
B --> C[AI Model Selection]
C --> D[System Prompt Generation]
D --> E[AI Processing]
E --> F[Tool Execution]
F --> G[Response Generation]
G --> H[Discord Reply]
I[Built-in Tools] --> F
J[Custom Tools] --> F
K[AI Commands] --> F
Core Components
- AI Plugin - Manages the AI system lifecycle and message processing
- Configuration System - Handles AI model selection and behavior customization
- Context Management - Provides request context and state management
- Tool System - Enables AI to execute functions and commands
- Command Integration - Allows existing commands to be AI-accessible
Key Features
Natural Language Processing
The AI system can understand natural language requests and map them to specific commands:
User: "Can you ban @user for spamming?"
AI: Executes ban command with user parameter and reason
Dynamic Model Selection
Choose different AI models based on context:
selectAiModel: async (ctx, message) => {
if (message.member?.permissions.has('Administrator')) {
return { model: premiumModel }; // Better model for admins
}
return { model: standardModel };
};
Built-in Discord Integration
The AI has access to Discord-specific information:
- Server/guild information
- User and role data
- Channel management
- Permission checking
- Message history
Extensible Tool System
Create custom tools for AI to use:
const customTool = createTool({
name: 'weather',
description: 'Get weather information',
parameters: z.object({
location: z.string(),
}),
execute: async (ctx, params) => {
return await getWeatherData(params.location);
},
});
AI Command Flow
1. Message Reception
// Discord message received
message: 'Hey bot, can you play some music?';
2. Message Filtering
messageFilter: async (message) => {
return message.mentions.users.has(message.client.user.id);
};
3. Context Creation
const ctx = new AiContext({
message,
params: {},
commandkit,
});
4. AI Processing
const result = await generateText({
model,
prompt: userMessage,
system: systemPrompt,
tools: availableTools,
});
5. Tool Execution
// AI decides to use the music command
await musicCommand.ai({
action: 'play',
query: 'music',
});
6. Response Generation
await message.reply('🎵 Now playing music!');
Configuration Levels
Basic Configuration
configureAI({
selectAiModel: async () => ({ model: myModel }),
messageFilter: async (message) =>
message.mentions.users.has(message.client.user.id),
});
Advanced Configuration
configureAI({
selectAiModel: async (ctx, message) => ({
model: selectBestModel(message),
maxSteps: 10,
temperature: 0.7,
}),
messageFilter: customMessageFilter,
prepareSystemPrompt: customSystemPrompt,
onProcessingStart: startProcessing,
onResult: handleResult,
onError: handleError,
});
Security Considerations
Permission Validation
export async function ai(ctx: AiContext) {
if (!ctx.message.member?.permissions.has('RequiredPermission')) {
throw new Error('Insufficient permissions');
}
// Continue with command
}
Input Sanitization
const sanitizedInput = sanitizeInput(ctx.ai.params.userInput);
Rate Limiting
const rateLimiter = new RateLimiter(5, 60000); // 5 requests per minute
Performance Optimization
Caching
const cache = new Map();
const cachedResult = cache.get(cacheKey) || (await expensiveOperation());
Async Processing
// Handle long operations asynchronously
processLongOperation(params).then((result) => {
message.reply(`Operation completed: ${result}`);
});
Efficient Database Queries
// Batch operations instead of individual queries
const users = await database.user.findMany({
where: { id: { in: userIds } },
});
Error Handling
Graceful Degradation
try {
return await primaryMethod();
} catch (error) {
console.warn('Primary method failed, using fallback');
return await fallbackMethod();
}
User-Friendly Messages
catch (error) {
const userMessage = getHumanReadableError(error);
await message.reply(userMessage);
}
Best Practices
- Always validate permissions before executing sensitive operations
- Sanitize user inputs to prevent injection attacks
- Implement rate limiting to prevent abuse
- Use structured error handling for better user experience
- Cache frequently accessed data for better performance
- Log operations for debugging and monitoring
- Test AI commands thoroughly before deployment
Integration Examples
Music Bot
"Play some rock music" → musicCommand.ai({ action: 'play', genre: 'rock' })
Moderation
"Timeout @user for 10 minutes" → moderationCommand.ai({ action: 'timeout', user: 'id', duration: 600 })
Server Management
"Create a new text channel called general" → adminCommand.ai({ action: 'create-channel', name: 'general', type: 'text' })
Getting Started
- Install the AI package:
npm install @commandkit/ai
- Configure your AI model in
src/ai.ts
- Create AI-compatible commands with
aiConfig
andai
functions - Test your setup with simple commands
- Gradually add more complex functionality
Next Steps
- AI Configuration - Set up your AI models
- Creating AI Commands - Make commands AI-accessible
- Custom Tools - Extend AI capabilities
- Best Practices - Production-ready implementations