Mengapa AI Integration Penting?
AI bukan lagi future - ini adalah present. Companies yang mengintegrasikan AI:
- Increase productivity by 30-40%
- Reduce operational costs significantly
- Deliver better user experiences
- Stay competitive in the market
Architecture untuk AI Integration
┌──────────────┐
│ User Request │
└──────┬───────┘
│
▼
┌──────────────────┐
│ Input Validation │
└────────┬─────────┘
│
▼
┌──────────────────┐
│ Cache Check │ ◄── Redis/Memory cache
└────────┬─────────┘
│ (MISS)
▼
┌──────────────────┐
│ AI Model API │ ◄── OpenAI/Anthropic
└────────┬─────────┘
│
▼
┌──────────────────┐
│ Response Cache │ ◄── Store for future requests
└────────┬─────────┘
│
▼
┌──────────────────┐
│ User Response │
└──────────────────┘
Prompt Engineering Tips
1. Clear Instructions
❌ BAD:
"Summarize this article"
✅ GOOD:
"Summarize this article in 3 bullet points.
Focus on key findings and actionable insights.
Target audience: C-level executives"
2. Few-Shot Examples
const prompt = `
Classify sentiment: positive, negative, or neutral
Examples:
"This product is amazing!" → positive
"Terrible experience" → negative
"It's okay" → neutral
Classify: "${userText}" →
`;
3. System Prompt
const messages = [
{
role: "system",
content: "You are a helpful backend engineer assistant. Provide concise, practical advice."
},
{
role: "user",
content: "How do I optimize database queries?"
}
];
Cost Optimization
1. Prompt Caching
// Store common prompts di cache
const cachedPrompts = new Map();
async function getAIResponse(userInput) {
const cacheKey = hashPrompt(userInput);
if (cachedPrompts.has(cacheKey)) {
return cachedPrompts.get(cacheKey);
}
const response = await openai.createChatCompletion({
model: "gpt-4",
messages: userInput
});
cachedPrompts.set(cacheKey, response);
return response;
}
2. Token Management
// Estimate tokens before calling API
const tokenCount = (text) => Math.ceil(text.length / 4);
const maxTokens = 1000;
if (tokenCount(prompt) > maxTokens) {
// Truncate or summarize first
}
3. Rate Limiting
const rateLimit = require('express-rate-limit');
const aiLimiter = rateLimit({
windowMs: 60 * 1000, // 1 minute
max: 10, // 10 requests per minute
message: 'Too many AI requests'
});
app.post('/api/ai/generate', aiLimiter, async (req, res) => {
// Handle request
});
Error Handling & Resilience
class AIService {
async callAI(prompt, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
const response = await openai.createChatCompletion({
model: "gpt-4",
messages: [{ role: "user", content: prompt }],
timeout: 30000
});
return response.choices[0].message.content;
} catch (error) {
if (error.status === 429) { // Rate limited
await this.sleep(Math.pow(2, i) * 1000);
continue;
}
if (error.status === 500) { // Server error
await this.sleep(Math.pow(2, i) * 1000);
continue;
}
throw error;
}
}
throw new Error('Max retries exceeded');
}
sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
}
Monitoring & Observability
// Track AI usage and costs
const aiMetrics = {
totalRequests: 0,
totalTokens: 0,
totalCost: 0,
averageLatency: 0,
errorRate: 0
};
// Log every AI call
async function trackAICall(model, inputTokens, outputTokens, latency) {
const cost = calculateCost(model, inputTokens, outputTokens);
aiMetrics.totalRequests++;
aiMetrics.totalTokens += (inputTokens + outputTokens);
aiMetrics.totalCost += cost;
aiMetrics.averageLatency = (aiMetrics.averageLatency + latency) / 2;
logger.info('AI Call tracked', {
model,
tokens: inputTokens + outputTokens,
cost,
latency
});
}
Security Considerations
1. API Key Management
// ❌ WRONG
const apiKey = "sk-xxxxx"; // In code!
// ✅ RIGHT
const apiKey = process.env.OPENAI_API_KEY;
// ✅ BETTER - Using secrets management
const apiKey = await secretsManager.get('openai-api-key');
2. Input Validation
// Protect against prompt injection
function sanitizePrompt(userInput) {
// Remove potentially harmful patterns
return userInput
.replace(/<script|<iframe/gi, '')
.trim()
.slice(0, 2000); // Limit length
}
3. Output Sanitization
// Never blindly trust AI output
function sanitizeOutput(aiResponse) {
// Remove code execution patterns
// Remove sensitive data patterns
// Validate format
return cleanedResponse;
}
Production Checklist
- Error handling & retries implemented
- Rate limiting configured
- Cost monitoring active
- Caching strategy in place
- Logging & monitoring setup
- Security measures implemented
- Load testing completed
- Fallback strategy ready
- Documentation complete
- Team training done
Resources: