Skip to main content
Version: Next

AI System Overview

CommandKit's @commandkit/ai plugin allows you to execute your bot commands using large language models. This enables you to use your bot's features entirely through natural language.

warning

This is an experimental feature and is subject to change.

Installation

npm install @commandkit/ai

You also need to install the AI SDK for the model you want to use. For example, if you want to use Google Gemini, you can install the @ai-sdk/google package:

npm install @ai-sdk/google

Refer to the AI SDKs documentation for more information on how to set up the AI SDK for your model.

Usage

commandkit.config.ts
import { defineConfig } from 'commandkit';
import { ai } from '@commandkit/ai';

export default defineConfig({
plugins: [ai()],
});

Architecture Overview

The AI system consists of several key components:

Core Components

  1. AI Plugin - Manages the AI system lifecycle and message processing
  2. Configuration System - Handles AI model selection and behavior customization
  3. Context Management - Provides request context and state management
  4. Tool System - Enables AI to execute functions and commands
  5. 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:

  • Basic information about itself
  • Server/guild information
  • Basic user data
  • Basic channel data
  • Available commands
  • 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 (commandkit, 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 (commandkit, 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 const ai: AiCommand<typeof aiConfig> = async (ctx) => {
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());
info

For a better cache management solution, check out the @commandkit/cache plugin guide.

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

  1. Always validate permissions before executing sensitive operations
  2. Sanitize user inputs to prevent injection attacks
  3. Implement rate limiting to prevent abuse
  4. Use structured error handling for better user experience
  5. Cache frequently accessed data for better performance
  6. Log operations for debugging and monitoring
  7. 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

  1. Install the AI package: npm install @commandkit/ai
  2. Configure your AI model in src/ai.ts
  3. Create AI-compatible commands with aiConfig and ai functions
  4. Test your setup with simple commands
  5. Gradually add more complex functionality

Next Steps