Cara Balas WA Otomatis dengan AI/ChatGPT

Tutorial auto reply WhatsApp dengan AI dan ChatGPT. Bot cerdas yang bisa menjawab berbagai pertanyaan. Panduan lengkap!

Cara Balas WA Otomatis dengan AI/ChatGPT
Cara Balas WA Otomatis dengan AI/ChatGPT

AI = Auto reply yang benar-benar pintar!

Berbeda dengan keyword-based yang kaku, AI-powered auto reply bisa memahami konteks dan menjawab pertanyaan yang belum pernah diprogram sebelumnya.


Keyword vs AI

📊 PERBANDINGAN:

KEYWORD-BASED:
- Trigger: kata exact
- Response: template fixed
- Limitasi: hanya yang diprogram
- Contoh: "harga" → kirim price list

AI-POWERED:
- Trigger: intent/maksud
- Response: generated dinamis
- Bisa jawab yang tidak diprogram
- Contoh: "brp sih harganya kl beli 3?"
  → Jawab dengan kalkulasi

Cara Kerja AI Auto Reply

🔄 FLOW:

1. Customer kirim pesan
   "Produk A sama B bedanya apa ya?"

2. Bot terima & kirim ke AI
   [Message → OpenAI API]

3. AI proses dengan context
   [Product knowledge + conversation history]

4. AI generate response
   "Perbedaan Produk A dan B:
    - A untuk kulit kering...
    - B untuk kulit berminyak..."

5. Bot kirim ke customer
   [Response → WhatsApp]

Setup AI Auto Reply

Requirement:

📋 YANG DIBUTUHKAN:

1. WHATSAPP CONNECTION:
   • Official API (Cloud API)
   • Atau Unofficial (Baileys)

2. AI API:
   • OpenAI (ChatGPT)
   • Anthropic (Claude)
   • Google (Gemini)

3. KNOWLEDGE BASE:
   • Info produk/layanan
   • FAQ
   • Kebijakan bisnis

4. SERVER:
   • Untuk jalankan bot 24/7

Integrasi OpenAI:

javascript

const OpenAI = require('openai');

const openai = new OpenAI({
    apiKey: process.env.OPENAI_API_KEY
});

// System prompt dengan knowledge bisnis
const systemPrompt = `
Kamu adalah customer service [BRAND], toko online skincare.

TENTANG KAMI:
- Berdiri sejak 2020
- Produk skincare lokal berkualitas
- Free ongkir min. Rp 150.000

PRODUK UTAMA:
1. Facial Wash - Rp 89.000
2. Toner - Rp 99.000
3. Serum - Rp 149.000
4. Moisturizer - Rp 119.000

KEBIJAKAN:
- Retur 7 hari jika ada cacat
- Garansi originalitas
- Pembayaran: Transfer, E-wallet

INSTRUKSI:
- Jawab dengan ramah dan helpful
- Gunakan bahasa casual Indonesia
- Jika tidak tahu, bilang akan cek dulu
- Jangan buat informasi palsu
- Arahkan ke CS manusia jika kompleks
`;

async function generateAIResponse(userMessage, conversationHistory) {
    const messages = [
        { role: 'system', content: systemPrompt },
        ...conversationHistory,
        { role: 'user', content: userMessage }
    ];
    
    const response = await openai.chat.completions.create({
        model: 'gpt-4o-mini',
        messages: messages,
        max_tokens: 500,
        temperature: 0.7
    });
    
    return response.choices[0].message.content;
}

Integrasi ke WhatsApp:

javascript

// Handle incoming message
async function handleMessage(from, message) {
    // Get conversation history
    const history = await getConversationHistory(from, 10);
    
    // Generate AI response
    const aiResponse = await generateAIResponse(message, history);
    
    // Save to history
    await saveMessage(from, 'user', message);
    await saveMessage(from, 'assistant', aiResponse);
    
    // Send via WhatsApp
    await sendWhatsAppMessage(from, aiResponse);
}

// Conversation history management
async function getConversationHistory(userId, limit = 10) {
    const messages = await db.messages
        .find({ userId })
        .sort({ timestamp: -1 })
        .limit(limit)
        .toArray();
    
    return messages.reverse().map(m => ({
        role: m.role,
        content: m.content
    }));
}

Knowledge Base Setup

Structured Knowledge:

javascript

const knowledgeBase = {
    products: [
        {
            name: 'Gentle Facial Wash',
            price: 89000,
            description: 'Pembersih wajah lembut untuk semua jenis kulit',
            ingredients: ['Aloe vera', 'Green tea', 'Vitamin E'],
            usage: 'Gunakan pagi dan malam',
            stock: 'available'
        },
        // ... more products
    ],
    
    faq: [
        {
            question: 'Berapa lama pengiriman?',
            answer: '2-3 hari untuk Jawa, 4-7 hari luar Jawa'
        },
        // ... more FAQ
    ],
    
    policies: {
        return: '7 hari jika ada cacat produksi',
        shipping: 'Free ongkir min Rp 150.000',
        payment: ['Transfer Bank', 'GoPay', 'OVO', 'DANA']
    }
};

// Convert to system prompt
function buildSystemPrompt(knowledgeBase) {
    let prompt = 'Kamu adalah CS [BRAND].\n\n';
    
    prompt += 'PRODUK:\n';
    knowledgeBase.products.forEach(p => {
        prompt += `- ${p.name}: Rp ${p.price.toLocaleString()}\n`;
        prompt += `  ${p.description}\n`;
    });
    
    prompt += '\nFAQ:\n';
    knowledgeBase.faq.forEach(f => {
        prompt += `Q: ${f.question}\nA: ${f.answer}\n\n`;
    });
    
    return prompt;
}

RAG (Retrieval Augmented Generation):

javascript

// Untuk knowledge base yang besar
const { OpenAIEmbeddings } = require('langchain/embeddings/openai');
const { PineconeStore } = require('langchain/vectorstores/pinecone');

// Index knowledge ke vector database
async function indexKnowledge(documents) {
    const embeddings = new OpenAIEmbeddings();
    
    await PineconeStore.fromDocuments(documents, embeddings, {
        pineconeIndex: pineconeClient.Index('knowledge-base')
    });
}

// Retrieve relevant context
async function getRelevantContext(query) {
    const embeddings = new OpenAIEmbeddings();
    const vectorStore = await PineconeStore.fromExistingIndex(embeddings, {
        pineconeIndex: pineconeClient.Index('knowledge-base')
    });
    
    const results = await vectorStore.similaritySearch(query, 3);
    
    return results.map(r => r.pageContent).join('\n\n');
}

// AI response with RAG
async function generateRAGResponse(userMessage, history) {
    const context = await getRelevantContext(userMessage);
    
    const systemPrompt = `
        Kamu adalah CS [BRAND].
        
        INFORMASI RELEVAN:
        ${context}
        
        Jawab berdasarkan informasi di atas.
        Jika tidak ada info, bilang akan cek dulu.
    `;
    
    return await openai.chat.completions.create({
        model: 'gpt-4o-mini',
        messages: [
            { role: 'system', content: systemPrompt },
            ...history,
            { role: 'user', content: userMessage }
        ]
    });
}

Hybrid Approach

AI + Keyword Fallback:

javascript

async function handleMessage(from, message) {
    // Check keyword triggers first
    const keywordResponse = checkKeywordTrigger(message);
    
    if (keywordResponse) {
        // Keyword match - use template
        return await sendMessage(from, keywordResponse);
    }
    
    // No keyword match - use AI
    const aiResponse = await generateAIResponse(message);
    return await sendMessage(from, aiResponse);
}

// Keyword untuk yang critical/exact
const keywordTriggers = {
    'rekening': 'BCA 1234567890 a.n. [BRAND]',
    'alamat': 'Jl. Example No. 123, Jakarta',
    'cs': 'Menghubungkan ke CS... mohon tunggu.',
    'manusia': 'Menghubungkan ke CS... mohon tunggu.'
};

AI dengan Guardrails:

javascript

async function generateSafeAIResponse(userMessage, history) {
    const response = await generateAIResponse(userMessage, history);
    
    // Check for problematic content
    if (containsSensitiveInfo(response)) {
        return 'Untuk informasi tersebut, mohon hubungi CS kami langsung ya.';
    }
    
    // Check confidence - jika AI tidak yakin
    if (response.includes('tidak yakin') || response.includes('tidak tahu')) {
        // Escalate to human
        await escalateToHuman(from);
        return 'Pertanyaan menarik! Saya akan hubungkan dengan tim kami untuk jawaban yang lebih akurat.';
    }
    
    return response;
}

Cost Management

javascript

// Track API usage
async function trackUsage(userId, inputTokens, outputTokens) {
    const cost = (inputTokens * 0.00015 + outputTokens * 0.0006) / 1000;
    
    await db.usage.updateOne(
        { userId, date: today() },
        { 
            $inc: { 
                requests: 1, 
                inputTokens, 
                outputTokens,
                cost 
            }
        },
        { upsert: true }
    );
}

// Rate limiting per user
async function checkRateLimit(userId) {
    const usage = await db.usage.findOne({ 
        userId, 
        date: today() 
    });
    
    if (usage && usage.requests >= 50) {
        return {
            allowed: false,
            message: 'Maaf, quota harian tercapai. Silakan hubungi CS langsung.'
        };
    }
    
    return { allowed: true };
}

Contoh Percakapan

👤 Customer: "Hai, produk untuk kulit berminyak apa ya?"

🤖 AI Bot: "Hai kak! 👋

Untuk kulit berminyak, aku rekomendasikan:

1️⃣ Oil Control Facial Wash - Rp 89.000
   Pembersih yang mengontrol minyak berlebih

2️⃣ Pore Minimizing Toner - Rp 99.000
   Memperkecil pori dan matte finish

3️⃣ Lightweight Moisturizer - Rp 119.000
   Pelembab ringan, non-greasy

Mau aku jelasin lebih detail yang mana kak? 😊"

👤 Customer: "Yg toner itu aman buat bumil ga?"

🤖 AI Bot: "Pertanyaan bagus kak! 

Untuk ibu hamil, sebaiknya konsultasi dulu dengan dokter ya kak. Meskipun bahan-bahan kami umumnya aman, setiap kehamilan berbeda.

Kalau mau, aku bisa share ingredients list-nya ke dokter obgyn kakak untuk dicek.

Atau kami punya juga lini khusus 'Gentle Care' yang formulanya lebih mild. Mau info tentang itu? 💕"

Best Practices

DO ✅

- Set system prompt yang jelas
- Include knowledge yang akurat
- Limit response length
- Handle unknown gracefully
- Monitor dan improve
- Fallback ke manusia

DON'T ❌

- Biarkan AI hallucinate
- Skip content moderation
- No cost tracking
- Ignore conversation context
- Over-promise AI capability
- No human fallback

FAQ

AI mahal tidak?

GPT-4o-mini sangat affordable. ~$0.15/1M input tokens. Untuk SMB, bisa <$10/bulan.

Bagaimana kalau AI salah jawab?

Guardrails + human fallback. AI jawab umum, escalate yang kompleks.

Perlu training model sendiri?

Tidak untuk kebanyakan case. System prompt + RAG sudah cukup powerful.


Kesimpulan

AI auto reply = Next level automation!

Keyword-BasedAI-Powered
KakuFleksibel
LimitedUnlimited
Exact matchIntent-based
SimpleIntelligent

Setup AI Auto Reply →


Artikel Terkait