Skip to main content
Skip to main content

AI & Machine Learning Services

Mifty provides seamless integration with AI and machine learning services, enabling you to add intelligent features like content generation, chatbots, image analysis, and natural language processing to your applications.

OpenAI Integration

🤖ai

OpenAI API Integration

Complete OpenAI integration supporting GPT models, DALL-E, Whisper, and embeddings for intelligent application features

Installation

npm run adapter install openai

Environment Variables

OPENAI_API_KEYRequired

OpenAI API key from your OpenAI account

Example: sk-proj-1234567890abcdefghijklmnopqrstuvwxyz
OPENAI_ORGANIZATION

OpenAI organization ID (optional)

Example: org-1234567890abcdefghijklmnop
OPENAI_DEFAULT_MODEL

Default GPT model to use

Example: gpt-4(Default: gpt-3.5-turbo)
OPENAI_MAX_TOKENS

Default maximum tokens for responses

Example: 2000(Default: 1000)
Complete .env example:
OPENAI_API_KEY=sk-proj-1234567890abcdefghijklmnopqrstuvwxyz
OPENAI_ORGANIZATION=org-1234567890abcdefghijklmnop
OPENAI_DEFAULT_MODEL=gpt-4
OPENAI_MAX_TOKENS=2000

AI-Powered Features Implementation

Intelligent Content Generation

// Smart blog post generator
const generateBlogPost = async (topic: string, keywords: string[], targetAudience: string) => {
const prompt = `
Write a comprehensive blog post about "${topic}" for ${targetAudience}.
Include these keywords naturally: ${keywords.join(', ')}.
Structure: Introduction, 3-4 main sections, conclusion.
Tone: Professional but engaging.
Length: ~800 words.
`;

const content = await generateContent(prompt, {
model: 'gpt-4',
maxTokens: 2000,
temperature: 0.7
});

return content;
};

// Product description generator
const generateProductDescription = async (productData: any) => {
const prompt = `
Create a compelling product description for:
Name: ${productData.name}
Category: ${productData.category}
Features: ${productData.features.join(', ')}
Target audience: ${productData.targetAudience}

Make it persuasive, highlight benefits, and include a call-to-action.
`;

return await generateContent(prompt, { maxTokens: 300 });
};

Smart Customer Support

// AI-powered support ticket classification
const classifyTicket = async (ticketContent: string) => {
const prompt = `
Classify this support ticket into one of these categories:
- Technical Issue
- Billing Question
- Feature Request
- Bug Report
- General Inquiry

Also determine the urgency level (Low, Medium, High, Critical).

Ticket: "${ticketContent}"

Respond in JSON format: {"category": "...", "urgency": "...", "summary": "..."}
`;

const response = await generateContent(prompt, {
temperature: 0.3 // Lower temperature for more consistent classification
});

return JSON.parse(response);
};

// Generate suggested responses
const generateSupportResponse = async (ticketContent: string, category: string) => {
const prompt = `
Generate a helpful, professional response to this ${category} support ticket:
"${ticketContent}"

Be empathetic, provide actionable solutions, and maintain a friendly tone.
`;

return await generateContent(prompt, { maxTokens: 400 });
};

Personalization Engine

// Content personalization based on user behavior
const personalizeContent = async (userId: string, contentType: string) => {
// Get user preferences and behavior
const userProfile = await getUserProfile(userId);
const userBehavior = await getUserBehavior(userId);

const prompt = `
Personalize ${contentType} content for a user with these characteristics:
- Interests: ${userProfile.interests.join(', ')}
- Previous interactions: ${userBehavior.topCategories.join(', ')}
- Engagement level: ${userBehavior.engagementLevel}
- Preferred content length: ${userProfile.preferredLength}

Generate 3 personalized content suggestions with titles and brief descriptions.
`;

const suggestions = await generateContent(prompt, { maxTokens: 500 });
return suggestions;
};

Cost Optimization Strategies

Caching and Efficiency

// Implement intelligent caching
import Redis from 'redis';

const redis = Redis.createClient();

const cachedGeneration = async (prompt: string, options: any) => {
// Create cache key from prompt and options
const cacheKey = `ai:${Buffer.from(prompt + JSON.stringify(options)).toString('base64')}`;

// Check cache first
const cached = await redis.get(cacheKey);
if (cached) {
return JSON.parse(cached);
}

// Generate new content
const result = await generateContent(prompt, options);

// Cache for 24 hours
await redis.setex(cacheKey, 86400, JSON.stringify(result));

return result;
};

// Batch processing for efficiency
const batchProcess = async (items: string[], processor: Function) => {
const batchSize = 5;
const results = [];

for (let i = 0; i < items.length; i += batchSize) {
const batch = items.slice(i, i + batchSize);
const batchResults = await Promise.all(
batch.map(item => processor(item))
);
results.push(...batchResults);

// Rate limiting delay
await new Promise(resolve => setTimeout(resolve, 1000));
}

return results;
};

Usage Monitoring

// Track AI service usage and costs
const trackUsage = async (service: string, operation: string, tokens: number, cost: number) => {
await db.query(`
INSERT INTO ai_usage_logs (service, operation, tokens_used, cost, timestamp)
VALUES (?, ?, ?, ?, NOW())
`, [service, operation, tokens, cost]);
};

// Generate usage reports
const generateUsageReport = async (timeframe: string) => {
const report = await db.query(`
SELECT
service,
operation,
SUM(tokens_used) as total_tokens,
SUM(cost) as total_cost,
COUNT(*) as request_count
FROM ai_usage_logs
WHERE timestamp >= DATE_SUB(NOW(), INTERVAL ? DAY)
GROUP BY service, operation
`, [timeframe === 'week' ? 7 : 30]);

return report;
};

Security and Privacy

Data Protection

// Sanitize data before sending to AI services
const sanitizeForAI = (text: string) => {
// Remove PII patterns
return text
.replace(/\b\d{3}-\d{2}-\d{4}\b/g, '[SSN]') // SSN
.replace(/\b\d{4}[\s-]?\d{4}[\s-]?\d{4}[\s-]?\d{4}\b/g, '[CARD]') // Credit card
.replace(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g, '[EMAIL]') // Email
.replace(/\b\d{3}[\s-]?\d{3}[\s-]?\d{4}\b/g, '[PHONE]'); // Phone
};

// Audit AI interactions
const auditAIInteraction = async (userId: string, prompt: string, response: string) => {
await db.query(`
INSERT INTO ai_audit_log (user_id, prompt_hash, response_hash, timestamp)
VALUES (?, ?, ?, NOW())
`, [
userId,
crypto.createHash('sha256').update(prompt).digest('hex'),
crypto.createHash('sha256').update(response).digest('hex')
]);
};

Testing AI Features

Unit Testing AI Functions

// Mock OpenAI responses for testing
jest.mock('@mifty/openai');

describe('AI Content Generation', () => {
beforeEach(() => {
(OpenAIService as jest.Mocked<typeof OpenAIService>).mockClear();
});

test('should generate blog post content', async () => {
const mockResponse = {
choices: [{ message: { content: 'Generated blog post content...' } }]
};

OpenAIService.prototype.createCompletion = jest.fn().mockResolvedValue(mockResponse);

const result = await generateBlogPost('AI in Healthcare', ['AI', 'healthcare'], 'doctors');

expect(result).toContain('Generated blog post content');
expect(OpenAIService.prototype.createCompletion).toHaveBeenCalledWith(
expect.objectContaining({
model: 'gpt-4',
messages: expect.arrayContaining([
expect.objectContaining({ role: 'user' })
])
})
);
});
});

Performance Monitoring

AI Service Health Checks

// Monitor AI service performance
const healthCheck = async () => {
try {
const start = Date.now();
await generateContent('Test prompt', { maxTokens: 10 });
const responseTime = Date.now() - start;

return {
status: 'healthy',
responseTime,
timestamp: new Date().toISOString()
};
} catch (error) {
return {
status: 'unhealthy',
error: error.message,
timestamp: new Date().toISOString()
};
}
};

// Set up monitoring alerts
setInterval(async () => {
const health = await healthCheck();

if (health.status === 'unhealthy' || health.responseTime > 10000) {
// Send alert to monitoring system
console.error('AI service health check failed:', health);
}
}, 60000); // Check every minute

Next Steps

After setting up AI services, you might want to:

Best Practices

  1. Prompt Engineering: Craft clear, specific prompts with examples and context
  2. Cost Management: Monitor usage, implement caching, and use appropriate models
  3. Error Handling: Implement robust error handling and fallback mechanisms
  4. Privacy: Sanitize sensitive data before sending to AI services
  5. Testing: Create comprehensive tests with mocked AI responses
  6. Monitoring: Track performance, costs, and quality metrics
  7. User Experience: Provide loading states and graceful degradation