Bot WA AI dengan Claude (Anthropic)

Tutorial integrasi Claude AI dari Anthropic dengan WhatsApp Bot. Lebih helpful dan aman. Code example lengkap!

Bot WA AI dengan Claude (Anthropic)
Bot WA AI dengan Claude (Anthropic)

Claude = AI yang helpful dan aman!

Claude dari Anthropic dikenal sebagai AI yang sangat helpful, harmless, dan honest. Cocok untuk customer service dan bisnis.


Kenapa Claude?

📊 KEUNGGULAN CLAUDE:

✅ HELPFUL
   • Jawaban detail dan akurat
   • Mau membantu berbagai task
   • Tidak mudah menolak

✅ HARMLESS
   • Tidak generate konten berbahaya
   • Aman untuk bisnis
   • Family-friendly

✅ HONEST
   • Mengakui ketidaktahuan
   • Tidak hallucinate berlebihan
   • Transparan tentang limitasi

✅ CONTEXT PANJANG
   • Hingga 200K tokens
   • Ingat percakapan panjang
   • Bisa proses dokumen besar

Perbandingan Model

📊 CLAUDE VS COMPETITORS:

                Claude    GPT-4    Gemini
Context         200K      128K     1M
Safety          ⭐⭐⭐⭐⭐   ⭐⭐⭐⭐    ⭐⭐⭐⭐
Helpfulness     ⭐⭐⭐⭐⭐   ⭐⭐⭐⭐⭐   ⭐⭐⭐⭐
Indonesian      ⭐⭐⭐⭐     ⭐⭐⭐⭐⭐   ⭐⭐⭐⭐
Price           $$        $$$      $

CLAUDE MODELS:
- Claude 3.5 Sonnet - Best balance
- Claude 3 Opus - Most powerful
- Claude 3 Haiku - Fastest & cheapest

Setup Claude API

Step 1: Dapat API Key

📝 LANGKAH:

1. Daftar di console.anthropic.com
2. Verify email dan phone
3. Add payment method
4. Create API key
5. Simpan key dengan aman

Step 2: Install SDK

bash

npm install @anthropic-ai/sdk

Step 3: Basic Integration

javascript

const Anthropic = require('@anthropic-ai/sdk');

const anthropic = new Anthropic({
    apiKey: process.env.ANTHROPIC_API_KEY
});

async function askClaude(userMessage, conversationHistory = []) {
    const systemPrompt = `Kamu adalah customer service AI untuk toko online [BRAND].

INFORMASI TOKO:
- Nama: [BRAND]
- Jam operasional: 08:00-21:00 WIB
- Produk: Fashion wanita
- Pengiriman: Seluruh Indonesia

PANDUAN:
- Jawab dalam Bahasa Indonesia yang ramah
- Gunakan emoji secukupnya
- Jika tidak tahu, akui dan tawarkan hubungkan ke admin
- Jangan buat informasi yang tidak ada
- Fokus membantu customer`;

    const messages = [
        ...conversationHistory,
        { role: 'user', content: userMessage }
    ];

    const response = await anthropic.messages.create({
        model: 'claude-3-5-sonnet-20241022',
        max_tokens: 1024,
        system: systemPrompt,
        messages: messages
    });

    return response.content[0].text;
}

Integrasi dengan WhatsApp

Full Implementation:

javascript

const { default: makeWASocket } = require('@whiskeysockets/baileys');
const Anthropic = require('@anthropic-ai/sdk');

const anthropic = new Anthropic({
    apiKey: process.env.ANTHROPIC_API_KEY
});

// Store conversation history per user
const conversations = new Map();

// System prompt untuk bisnis
const SYSTEM_PROMPT = `Kamu adalah Tia, AI assistant untuk [BRAND].

TENTANG [BRAND]:
- Toko fashion wanita online
- Berdiri sejak 2020
- Free ongkir Jabodetabek min. 200k

PRODUK UNGGULAN:
- Dress: Rp 150.000 - 500.000
- Blouse: Rp 100.000 - 300.000
- Celana: Rp 120.000 - 350.000

CARA ORDER:
1. Pilih produk
2. Kirim: ORDER [nama produk] [size] [warna]
3. Isi alamat
4. Transfer ke BCA 1234567890 a/n [BRAND]
5. Kirim bukti transfer

KEBIJAKAN:
- Retur: 7 hari jika ada cacat
- Refund: 3-5 hari kerja
- Garansi: Jahitan 30 hari

GAYA KOMUNIKASI:
- Ramah dan helpful
- Bahasa Indonesia casual
- Emoji secukupnya 😊
- Panggil "Kak"

BATASAN:
- Jangan buat harga/promo yang tidak ada
- Jika tidak yakin, bilang akan konfirmasi ke tim
- Untuk komplain serius, hubungkan ke admin`;

async function getAIResponse(userId, userMessage) {
    // Get or create conversation history
    if (!conversations.has(userId)) {
        conversations.set(userId, []);
    }
    
    const history = conversations.get(userId);
    
    // Add user message to history
    history.push({ role: 'user', content: userMessage });
    
    // Keep only last 20 messages to manage context
    const recentHistory = history.slice(-20);
    
    try {
        const response = await anthropic.messages.create({
            model: 'claude-3-5-sonnet-20241022',
            max_tokens: 1024,
            system: SYSTEM_PROMPT,
            messages: recentHistory
        });
        
        const aiResponse = response.content[0].text;
        
        // Add AI response to history
        history.push({ role: 'assistant', content: aiResponse });
        
        // Update stored history
        conversations.set(userId, history.slice(-20));
        
        return aiResponse;
        
    } catch (error) {
        console.error('Claude API error:', error);
        return 'Maaf kak, ada gangguan sistem. Coba lagi ya atau ketik ADMIN untuk bicara dengan tim kami 🙏';
    }
}

// WhatsApp handler
sock.ev.on('messages.upsert', async ({ messages }) => {
    for (const msg of messages) {
        if (!msg.message || msg.key.fromMe) continue;
        
        const userId = msg.key.remoteJid;
        const text = msg.message.conversation || 
                     msg.message.extendedTextMessage?.text || '';
        
        if (!text) continue;
        
        // Check for admin escalation
        if (text.toLowerCase() === 'admin') {
            await sock.sendMessage(userId, {
                text: 'Baik kak, saya hubungkan dengan admin ya. Mohon tunggu sebentar... 🙏'
            });
            // Notify admin
            continue;
        }
        
        // Get AI response
        const response = await getAIResponse(userId, text);
        
        // Send response with natural delay
        await new Promise(r => setTimeout(r, 1500 + Math.random() * 1000));
        
        await sock.sendMessage(userId, { text: response });
    }
});

Advanced Features

Dengan Product Catalog:

javascript

const PRODUCT_CATALOG = `
KATALOG PRODUK:

1. DRESS COLLECTION
   - Dress Bunga Sakura | Rp 250.000 | S,M,L,XL | Pink, Putih, Biru
   - Dress Polos Elegan | Rp 200.000 | S,M,L | Hitam, Navy, Maroon
   - Maxi Dress Bohemian | Rp 350.000 | All Size | Cream, Coklat

2. BLOUSE COLLECTION
   - Blouse Katun Premium | Rp 150.000 | S,M,L,XL | Putih, Pink, Mint
   - Blouse Silk Look | Rp 180.000 | S,M,L | Champagne, Black
   
3. CELANA
   - Kulot Wide Leg | Rp 175.000 | S,M,L,XL | Hitam, Cream, Abu
   - Celana Palazzo | Rp 200.000 | All Size | Navy, Maroon
`;

const SYSTEM_PROMPT_WITH_CATALOG = `
${SYSTEM_PROMPT}

${PRODUCT_CATALOG}

Ketika customer tanya produk, berikan info lengkap dari katalog.
Jika produk tidak ada di katalog, bilang tidak tersedia.
`;

Dengan Function Calling:

javascript

async function getAIResponseWithTools(userId, userMessage) {
    const tools = [
        {
            name: 'check_stock',
            description: 'Cek ketersediaan stok produk',
            input_schema: {
                type: 'object',
                properties: {
                    product_name: { type: 'string' },
                    size: { type: 'string' },
                    color: { type: 'string' }
                },
                required: ['product_name']
            }
        },
        {
            name: 'create_order',
            description: 'Buat pesanan baru',
            input_schema: {
                type: 'object',
                properties: {
                    product_name: { type: 'string' },
                    size: { type: 'string' },
                    color: { type: 'string' },
                    quantity: { type: 'number' }
                },
                required: ['product_name', 'size', 'color']
            }
        },
        {
            name: 'track_order',
            description: 'Lacak status pesanan',
            input_schema: {
                type: 'object',
                properties: {
                    order_id: { type: 'string' }
                },
                required: ['order_id']
            }
        }
    ];
    
    const response = await anthropic.messages.create({
        model: 'claude-3-5-sonnet-20241022',
        max_tokens: 1024,
        system: SYSTEM_PROMPT,
        messages: [{ role: 'user', content: userMessage }],
        tools: tools
    });
    
    // Check if Claude wants to use a tool
    if (response.stop_reason === 'tool_use') {
        const toolUse = response.content.find(c => c.type === 'tool_use');
        
        // Execute the tool
        const toolResult = await executeToolFunction(
            toolUse.name, 
            toolUse.input
        );
        
        // Continue conversation with tool result
        const finalResponse = await anthropic.messages.create({
            model: 'claude-3-5-sonnet-20241022',
            max_tokens: 1024,
            system: SYSTEM_PROMPT,
            messages: [
                { role: 'user', content: userMessage },
                { role: 'assistant', content: response.content },
                { 
                    role: 'user', 
                    content: [{
                        type: 'tool_result',
                        tool_use_id: toolUse.id,
                        content: JSON.stringify(toolResult)
                    }]
                }
            ]
        });
        
        return finalResponse.content[0].text;
    }
    
    return response.content[0].text;
}

async function executeToolFunction(name, input) {
    switch (name) {
        case 'check_stock':
            return await checkProductStock(input);
        case 'create_order':
            return await createNewOrder(input);
        case 'track_order':
            return await trackOrderStatus(input);
        default:
            return { error: 'Unknown function' };
    }
}

Pricing Claude

💰 HARGA CLAUDE (per 1M tokens):

CLAUDE 3.5 SONNET:
- Input: $3.00
- Output: $15.00

CLAUDE 3 HAIKU (Budget):
- Input: $0.25
- Output: $1.25

ESTIMASI BIAYA:
- 1 chat ≈ 500 tokens
- 1000 chats ≈ 500K tokens
- Cost: ~$1.5-7.5/1000 chats

TIPS HEMAT:
- Pakai Haiku untuk simple queries
- Sonnet untuk complex conversations
- Cache system prompt
- Limit context length

Best Practices

DO ✅

- System prompt yang detail
- Maintain conversation context
- Handle errors gracefully
- Provide human escalation
- Monitor usage dan costs
- Test thoroughly

DON'T ❌

- Unlimited context (costly)
- No error handling
- Skip human fallback
- Ignore rate limits
- Expose API key
- Trust AI 100%

FAQ

Claude vs ChatGPT untuk WhatsApp?

Claude lebih safe dan helpful untuk customer service. ChatGPT lebih versatile untuk creative tasks.

Berapa biaya per bulan?

Tergantung volume. 1000 chats/hari ≈ $50-150/bulan dengan Sonnet.

Bisa Bahasa Indonesia?

Ya, sangat bagus. Claude memahami Bahasa Indonesia dengan baik termasuk slang.


Kesimpulan

Claude = AI yang aman untuk bisnis!

FeatureClaudeGPT-4
Safety⭐⭐⭐⭐⭐⭐⭐⭐⭐
Context200K128K
Price$$$$$
Indonesia⭐⭐⭐⭐⭐⭐⭐⭐⭐

Buat Bot Claude Sekarang →


Artikel Terkait