Bot WA AI dengan Google Gemini: Alternatif GPT
Tutorial integrasi Google Gemini dengan WhatsApp Bot. Free tier lebih besar dari OpenAI! Code example dan panduan lengkap
Cari alternatif ChatGPT yang lebih murah?
Google Gemini adalah jawabannya! Free tier yang generous dan kualitas yang kompetitif.
Gemini vs ChatGPT
| Aspek | Google Gemini | OpenAI ChatGPT |
|---|---|---|
| Free tier | 60 req/min | $5 credit |
| Bahasa ID | ⭐⭐⭐⭐ | ⭐⭐⭐⭐ |
| Speed | Fast | Fast |
| Quality | ⭐⭐⭐⭐ | ⭐⭐⭐⭐⭐ |
| Pricing | Very cheap | Cheap |
| Multi-modal | ✅ | ✅ |
Verdict: Gemini sangat bagus untuk budget-conscious!
Step 1: Dapatkan API Key
1. Kunjungi ai.google.dev
2. Login dengan Google Account
3. Click "Get API Key"
4. Create API key
5. Copy dan simpanFree tier: 60 requests per minute! Sangat generous untuk testing dan small business.
Step 2: Setup Project
bash
mkdir wa-gemini-bot
cd wa-gemini-bot
npm init -y
npm install whatsapp-web.js qrcode-terminal @google/generative-aiStep 3: Code Dasar
javascript
// index.js
const { Client, LocalAuth } = require('whatsapp-web.js');
const qrcode = require('qrcode-terminal');
const { GoogleGenerativeAI } = require('@google/generative-ai');
// Initialize Gemini
const genAI = new GoogleGenerativeAI(
process.env.GEMINI_API_KEY || 'your-api-key-here'
);
const model = genAI.getGenerativeModel({ model: 'gemini-pro' });
// Initialize WhatsApp
const client = new Client({
authStrategy: new LocalAuth()
});
client.on('qr', qr => {
qrcode.generate(qr, { small: true });
});
client.on('ready', () => {
console.log('Gemini Bot is ready!');
});
// System context (Gemini style)
const systemContext = `Kamu adalah customer service toko online [Nama Toko].
Tugas:
- Jawab pertanyaan produk
- Berikan rekomendasi
- Bantu proses order
Produk:
- Serum Vitamin C: Rp 150.000
- Moisturizer: Rp 100.000
- Sunscreen: Rp 125.000
Jawab dengan ramah dalam Bahasa Indonesia.`;
// Handle messages
client.on('message', async msg => {
if (msg.from.includes('@g.us')) return;
if (msg.fromMe) return;
try {
const prompt = `${systemContext}
Pertanyaan customer: ${msg.body}
Jawaban:`;
const result = await model.generateContent(prompt);
const response = result.response.text();
await msg.reply(response);
} catch (error) {
console.error('Gemini Error:', error);
await msg.reply('Maaf, terjadi kendala. Silakan chat admin.');
}
});
client.initialize();Step 4: Jalankan
bash
export GEMINI_API_KEY='your-key-here'
node index.jsAdvanced: Chat dengan History
javascript
const { GoogleGenerativeAI } = require('@google/generative-ai');
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
const model = genAI.getGenerativeModel({ model: 'gemini-pro' });
// Store chat sessions
const chatSessions = new Map();
async function getChatSession(userId) {
if (!chatSessions.has(userId)) {
const chat = model.startChat({
history: [
{
role: 'user',
parts: [{ text: 'Kamu adalah CS toko online. Jawab dalam Bahasa Indonesia dengan ramah.' }]
},
{
role: 'model',
parts: [{ text: 'Siap! Saya akan membantu sebagai CS dengan ramah dalam Bahasa Indonesia. Ada yang bisa saya bantu?' }]
}
],
generationConfig: {
maxOutputTokens: 500
}
});
chatSessions.set(userId, chat);
}
return chatSessions.get(userId);
}
client.on('message', async msg => {
if (msg.from.includes('@g.us')) return;
if (msg.fromMe) return;
try {
const chat = await getChatSession(msg.from);
const result = await chat.sendMessage(msg.body);
const response = result.response.text();
await msg.reply(response);
} catch (error) {
console.error('Error:', error);
// Reset session on error
chatSessions.delete(msg.from);
}
});
// Clear old sessions every hour
setInterval(() => {
chatSessions.clear();
}, 60 * 60 * 1000);Advanced: Multi-modal (Image)
Gemini bisa process image!
javascript
const { GoogleGenerativeAI } = require('@google/generative-ai');
const fs = require('fs');
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY);
const model = genAI.getGenerativeModel({ model: 'gemini-pro-vision' });
client.on('message', async msg => {
// Check if message has image
if (msg.hasMedia) {
const media = await msg.downloadMedia();
const imageParts = [
{
inlineData: {
data: media.data,
mimeType: media.mimetype
}
}
];
const prompt = 'Deskripsikan gambar ini dalam Bahasa Indonesia:';
const result = await model.generateContent([prompt, ...imageParts]);
const response = result.response.text();
await msg.reply(response);
}
});Use case: Customer kirim foto produk, bot identifikasi dan kasih info!
Gemini Models
| Model | Best For | Free |
|---|---|---|
| gemini-pro | Text tasks | ✅ |
| gemini-pro-vision | Text + Image | ✅ |
| gemini-1.5-pro | Long context | Limited |
| gemini-1.5-flash | Fast response | ✅ |
Rekomendasi untuk WA Bot: gemini-pro atau gemini-1.5-flash
Handling Rate Limits
javascript
const rateLimiter = {
requests: 0,
resetTime: Date.now() + 60000,
canMakeRequest() {
if (Date.now() > this.resetTime) {
this.requests = 0;
this.resetTime = Date.now() + 60000;
}
return this.requests < 60; // 60 per minute
},
makeRequest() {
this.requests++;
}
};
client.on('message', async msg => {
if (!rateLimiter.canMakeRequest()) {
await msg.reply('Mohon tunggu sebentar, sistem sedang sibuk.');
return;
}
rateLimiter.makeRequest();
// ... continue with Gemini request
});Error Handling
javascript
async function getGeminiResponse(prompt, retries = 3) {
for (let i = 0; i < retries; i++) {
try {
const result = await model.generateContent(prompt);
return result.response.text();
} catch (error) {
if (error.message.includes('RATE_LIMIT')) {
await delay(5000); // Wait 5 seconds
continue;
}
if (error.message.includes('SAFETY')) {
return 'Maaf, saya tidak bisa menjawab pertanyaan tersebut.';
}
if (i === retries - 1) {
throw error;
}
await delay(1000 * (i + 1));
}
}
}Gemini Safety Settings
javascript
const model = genAI.getGenerativeModel({
model: 'gemini-pro',
safetySettings: [
{
category: 'HARM_CATEGORY_HARASSMENT',
threshold: 'BLOCK_MEDIUM_AND_ABOVE'
},
{
category: 'HARM_CATEGORY_HATE_SPEECH',
threshold: 'BLOCK_MEDIUM_AND_ABOVE'
},
{
category: 'HARM_CATEGORY_SEXUALLY_EXPLICIT',
threshold: 'BLOCK_MEDIUM_AND_ABOVE'
},
{
category: 'HARM_CATEGORY_DANGEROUS_CONTENT',
threshold: 'BLOCK_MEDIUM_AND_ABOVE'
}
]
});Tips Optimasi
1. Use Caching
javascript
const cache = new Map();
async function getCachedResponse(key, generator) {
if (cache.has(key)) {
return cache.get(key);
}
const response = await generator();
cache.set(key, response);
setTimeout(() => cache.delete(key), 3600000); // 1 hour
return response;
}2. Prompt Engineering
javascript
// Good prompt structure for Gemini
const prompt = `
KONTEKS: Kamu adalah CS toko skincare.
PRODUK: Serum (Rp 150k), Moisturizer (Rp 100k)
INSTRUKSI: Jawab singkat, ramah, Bahasa Indonesia.
PERTANYAAN: ${userMessage}
JAWABAN:`;3. Fallback to Keyword
javascript
const keywords = {
'harga': 'Daftar harga: ...',
'alamat': 'Alamat kami: ...'
};
// Try keyword first (instant, free)
// Only use Gemini if no matchFAQ
Apakah Gemini gratis?
Ya, ada free tier! 60 requests per minute, cukup untuk small business. Setelah itu ada pricing tapi sangat murah.
Gemini vs ChatGPT, mana lebih bagus?
ChatGPT sedikit lebih bagus untuk task kompleks. Tapi Gemini lebih murah dengan free tier yang lebih besar. Untuk bot WA, keduanya sudah sangat cukup.
Bisa process gambar?
Bisa! Pakai model gemini-pro-vision. Customer bisa kirim foto, bot bisa analisis.
Kesimpulan
Google Gemini = Alternatif ChatGPT yang lebih hemat!
| Pro | Con |
|---|---|
| Free tier besar | Sedikit di bawah GPT-4 |
| Multi-modal | Safety filter ketat |
| Fast | - |
| Murah | - |
Perfect untuk budget-conscious bot!