YAML Metadata Warning:empty or missing yaml metadata in repo card

Check out the documentation for more information.

πŸ€– AgriEdu Chatbot

Sistem chatbot cerdas dengan Flask API dan Neural Network untuk bahasa Indonesia.

πŸš€ Cara Setup dan Menjalankan

1. Setup Python Virtual Environment

# Buat virtual environment
python -m venv venv

# Aktifkan virtual environment
# Untuk Windows:
venv\Scripts\activate

# Untuk Linux/Mac:
source venv/bin/activate

2. Install Dependencies

pip install -r requirements.txt

Dependencies yang dibutuhkan:

  • Flask 3.1.1
  • Flask-CORS 5.0.0
  • TensorFlow 2.18.0
  • NLTK 3.9.1
  • scikit-learn 1.6.0
  • numpy 2.2.0

3. Persiapan Model

Sebelum menjalankan aplikasi, pastikan file model sudah ada:

  • chatbot_model.h5 - Model neural network
  • words.pkl - Vocabulary
  • classes.pkl - Intent classes
  • intents.json - Data training (sudah tersedia)

Catatan: File model dapat diperoleh dengan menjalankan train_chatbot.ipynb di Google Colab

4. Menjalankan Aplikasi

python chatbot.py

Aplikasi akan berjalan di: http://localhost:5000

5. Testing

Buka browser dan akses:

  • Web Interface: http://localhost:5000
  • Health Check: http://localhost:5000/health
  • API Test: http://localhost:5000/test

πŸ“‘ API Documentation

Base URL

http://localhost:5000

API Endpoints

1. Health Check

GET /api/v1/health

Response:

{
    "status": "healthy",
    "model_loaded": true,
    "message": "AgriEdu Chatbot API is running"
}

2. Chat with Bot

POST /api/v1/chat
Content-Type: application/json

{
    "message": "Halo, apa kabar?"
}

Response:

{
    "user_message": "Halo, apa kabar?",
    "response": "Halo! Kabar baik nih! Kamu gimana kabarnya?",
    "intent": "greeting",
    "confidence": 0.95,
    "timestamp": "2024-01-01T12:00:00.000000"
}

3. List Available Intents

GET /api/v1/intents

Response:

{
    "intents": ["greeting", "goodbye", "thanks", "help", "nature_general"],
    "total": 50
}

4. Test Bot with Sample Messages

GET /api/v1/test

Response:

{
    "test_results": [
        {
            "message": "Halo",
            "response": "Halo! Ada yang bisa saya bantu?",
            "intent": "greeting",
            "confidence": 0.98
        },
        // ... more test results
    ],
    "total_tests": 5
}

πŸ’¬ Sending Messages to Chatbot

Request Format

To send a message to the chatbot, make a POST request to /api/v1/chat with the following format:

POST /api/v1/chat
Content-Type: application/json

{
    "message": "Your message here"
}

Response Format

The chatbot will respond with a JSON object containing:

  • user_message: The message you sent
  • response: The chatbot's response
  • intent: The detected intent category
  • confidence: Confidence score (0-1)
  • timestamp: When the response was generated
{
    "user_message": "Halo, siapa nama kamu?",
    "response": "Halo! Saya AgriEdu Bot, asisten virtual untuk pendidikan alam.",
    "intent": "greeting",
    "confidence": 0.95,
    "timestamp": "2024-01-01T12:00:00.000000"
}

Example Implementations

Python

import requests

def chat_with_bot(message):
    response = requests.post(
        "http://localhost:5000/api/v1/chat",
        json={"message": message}
    )
    return response.json()

# Example usage
response = chat_with_bot("Halo, siapa nama kamu?")
print("Bot:", response["response"])

JavaScript

async function chatWithBot(message) {
    const response = await fetch("http://localhost:5000/api/v1/chat", {
        method: "POST",
        headers: {
            "Content-Type": "application/json"
        },
        body: JSON.stringify({ message })
    });
    return response.json();
}

// Example usage
chatWithBot("Halo, siapa nama kamu?")
    .then(response => console.log("Bot:", response.response))
    .catch(error => console.error("Error:", error));

cURL

curl -X POST http://localhost:5000/api/v1/chat \
  -H "Content-Type: application/json" \
  -d '{"message": "Halo, siapa nama kamu?"}'

Error Handling

If there's an error, the API will return an appropriate HTTP status code and error message:

{
    "error": "Error message description"
}

Common error scenarios:

  • 400 Bad Request: Invalid message format
  • 500 Internal Server Error: Server-side error
  • 503 Service Unavailable: Model not loaded

Best Practices

  1. Always check the response status code
  2. Handle network errors gracefully
  3. Implement retry logic for failed requests
  4. Cache responses for frequently asked questions
  5. Monitor the confidence score to handle low-confidence responses appropriately

πŸ’» Implementation Examples

Python

import requests

BASE_URL = "http://localhost:5000/api/v1"

def chat_with_bot(message):
    response = requests.post(
        f"{BASE_URL}/chat",
        json={"message": message}
    )
    return response.json()

def check_health():
    response = requests.get(f"{BASE_URL}/health")
    return response.json()

def get_intents():
    response = requests.get(f"{BASE_URL}/intents")
    return response.json()

# Example usage
if __name__ == "__main__":
    # Check API health
    health = check_health()
    print("API Status:", health["status"])
    
    # Chat with bot
    response = chat_with_bot("Halo, siapa nama kamu?")
    print("Bot:", response["response"])

JavaScript/TypeScript

class AgriEduBot {
    private baseUrl: string;

    constructor(baseUrl: string = "http://localhost:5000/api/v1") {
        this.baseUrl = baseUrl;
    }

    async chat(message: string): Promise<any> {
        const response = await fetch(`${this.baseUrl}/chat`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ message })
        });
        return response.json();
    }

    async checkHealth(): Promise<any> {
        const response = await fetch(`${this.baseUrl}/health`);
        return response.json();
    }

    async getIntents(): Promise<any> {
        const response = await fetch(`${this.baseUrl}/intents`);
        return response.json();
    }
}

// Example usage
const bot = new AgriEduBot();

// Chat with bot
bot.chat("Halo, siapa nama kamu?")
    .then(response => console.log("Bot:", response.response))
    .catch(error => console.error("Error:", error));

cURL

# Health check
curl http://localhost:5000/api/v1/health

# Chat with bot
curl -X POST http://localhost:5000/api/v1/chat \
  -H "Content-Type: application/json" \
  -d '{"message": "Halo AgriEdu Bot!"}'

# Get intents
curl http://localhost:5000/api/v1/intents

# Test bot
curl http://localhost:5000/api/v1/test

πŸ”’ Error Handling

The API returns standard HTTP status codes:

  • 200 OK: Request successful
  • 400 Bad Request: Invalid request format
  • 404 Not Found: Endpoint not found
  • 500 Internal Server Error: Server-side error

Error Response Format:

{
    "error": "Error message description"
}

πŸ“š API Documentation

For interactive API documentation, visit:

http://localhost:5000/api/docs

This provides a Swagger UI interface where you can:

  • View all available endpoints
  • Test API calls directly
  • See request/response schemas
  • Download OpenAPI specification

πŸ’» Contoh Penggunaan API

Menggunakan cURL:

# Test health check
curl http://localhost:5000/health

# Kirim pesan ke chatbot
curl -X POST http://localhost:5000/chat \
  -H "Content-Type: application/json" \
  -d '{"message": "Halo AgriEdu Bot!"}'

# Lihat daftar intent
curl http://localhost:5000/intents

Menggunakan JavaScript:

1. Fungsi Dasar Chat

// Fungsi untuk chat dengan bot
async function chatWithBot(message) {
    try {
        const response = await fetch('http://localhost:5000/chat', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ message: message })
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        console.log('Bot:', data.response);
        return data;
    } catch (error) {
        console.error('Error:', error);
        return { error: 'Gagal mengirim pesan' };
    }
}

// Contoh penggunaan
chatWithBot('Siapa nama kamu?');

2. Implementasi Chat Interface Lengkap

class AgriEduChatbot {
    constructor(apiUrl = 'http://localhost:5000') {
        this.apiUrl = apiUrl;
        this.chatContainer = null;
        this.messageInput = null;
        this.sendButton = null;
    }

    // Inisialisasi chat interface
    init(containerId) {
        this.chatContainer = document.getElementById(containerId);
        this.createChatInterface();
        this.bindEvents();
    }

    // Buat struktur HTML chat
    createChatInterface() {
        this.chatContainer.innerHTML = `
            <div class="chat-header">
                <h3>πŸ€– AgriEdu Chatbot</h3>
                <span class="status" id="status">Online</span>
            </div>
            <div class="chat-messages" id="chatMessages">
                <div class="message bot-message">
                    <div class="message-content">
                        Halo! Saya AgriEdu Bot. Ada yang bisa saya bantu?
                    </div>
                </div>
            </div>
            <div class="chat-input">
                <input type="text" id="messageInput" placeholder="Ketik pesan Anda..." />
                <button id="sendButton">Kirim</button>
            </div>
            <div class="quick-actions">
                <button class="quick-btn" data-message="Halo">πŸ‘‹ Halo</button>
                <button class="quick-btn" data-message="Siapa nama kamu?">❓ Siapa kamu</button>
                <button class="quick-btn" data-message="Ceritakan tentang alam">🌿 Tentang Alam</button>
                <button class="quick-btn" data-message="Terima kasih">πŸ™ Terima kasih</button>
            </div>
        `;

        this.messageInput = document.getElementById('messageInput');
        this.sendButton = document.getElementById('sendButton');
    }

    // Bind event listeners
    bindEvents() {
        // Send button click
        this.sendButton.addEventListener('click', () => {
            this.sendMessage();
        });

        // Enter key press
        this.messageInput.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                this.sendMessage();
            }
        });

        // Quick action buttons
        document.querySelectorAll('.quick-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const message = e.target.getAttribute('data-message');
                this.messageInput.value = message;
                this.sendMessage();
            });
        });
    }

    // Kirim pesan
    async sendMessage() {
        const message = this.messageInput.value.trim();
        if (!message) return;

        // Tampilkan pesan user
        this.addMessage(message, 'user');
        this.messageInput.value = '';

        // Tampilkan typing indicator
        this.showTyping();

        try {
            // Kirim ke API
            const response = await fetch(`${this.apiUrl}/chat`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ message: message })
            });

            const data = await response.json();

            // Hapus typing indicator
            this.hideTyping();

            if (data.error) {
                this.addMessage('Maaf, terjadi kesalahan. Silakan coba lagi.', 'bot', 'error');
            } else {
                // Tampilkan respons bot dengan info tambahan
                this.addMessage(data.response, 'bot', 'success', {
                    intent: data.intent,
                    confidence: data.confidence
                });
            }

        } catch (error) {
            this.hideTyping();
            this.addMessage('Koneksi bermasalah. Pastikan server berjalan.', 'bot', 'error');
            console.error('Error:', error);
        }
    }

    // Tambah pesan ke chat
    addMessage(text, sender, status = '', metadata = null) {
        const messagesContainer = document.getElementById('chatMessages');
        const messageDiv = document.createElement('div');
        messageDiv.className = `message ${sender}-message ${status}`;

        let metadataHtml = '';
        if (metadata) {
            metadataHtml = `
                <div class="message-metadata">
                    <small>Intent: ${metadata.intent} | Confidence: ${(metadata.confidence * 100).toFixed(1)}%</small>
                </div>
            `;
        }

        messageDiv.innerHTML = `
            <div class="message-content">${text}</div>
            ${metadataHtml}
            <div class="message-time">${new Date().toLocaleTimeString()}</div>
        `;

        messagesContainer.appendChild(messageDiv);
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }

    // Tampilkan typing indicator
    showTyping() {
        const messagesContainer = document.getElementById('chatMessages');
        const typingDiv = document.createElement('div');
        typingDiv.className = 'message bot-message typing';
        typingDiv.id = 'typingIndicator';
        typingDiv.innerHTML = `
            <div class="message-content">
                <div class="typing-dots">
                    <span></span><span></span><span></span>
                </div>
            </div>
        `;
        messagesContainer.appendChild(typingDiv);
        messagesContainer.scrollTop = messagesContainer.scrollHeight;
    }

    // Hapus typing indicator
    hideTyping() {
        const typingIndicator = document.getElementById('typingIndicator');
        if (typingIndicator) {
            typingIndicator.remove();
        }
    }

    // Cek status API
    async checkHealth() {
        try {
            const response = await fetch(`${this.apiUrl}/health`);
            const data = await response.json();

            const statusElement = document.getElementById('status');
            if (data.status === 'healthy') {
                statusElement.textContent = 'Online';
                statusElement.className = 'status online';
            } else {
                statusElement.textContent = 'Offline';
                statusElement.className = 'status offline';
            }
        } catch (error) {
            const statusElement = document.getElementById('status');
            statusElement.textContent = 'Offline';
            statusElement.className = 'status offline';
        }
    }
}

// Inisialisasi chatbot
document.addEventListener('DOMContentLoaded', function() {
    const chatbot = new AgriEduChatbot();
    chatbot.init('chatContainer');

    // Cek status setiap 30 detik
    chatbot.checkHealth();
    setInterval(() => chatbot.checkHealth(), 30000);
});

3. CSS untuk Styling Chat

.chat-container {
    max-width: 400px;
    height: 600px;
    border: 1px solid #ddd;
    border-radius: 10px;
    display: flex;
    flex-direction: column;
    font-family: Arial, sans-serif;
}

.chat-header {
    background: #4CAF50;
    color: white;
    padding: 15px;
    border-radius: 10px 10px 0 0;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.status.online { color: #90EE90; }
.status.offline { color: #FFB6C1; }

.chat-messages {
    flex: 1;
    padding: 10px;
    overflow-y: auto;
    background: #f9f9f9;
}

.message {
    margin: 10px 0;
    display: flex;
    flex-direction: column;
}

.user-message {
    align-items: flex-end;
}

.bot-message {
    align-items: flex-start;
}

.message-content {
    max-width: 80%;
    padding: 10px 15px;
    border-radius: 18px;
    word-wrap: break-word;
}

.user-message .message-content {
    background: #007bff;
    color: white;
    border-bottom-right-radius: 5px;
}

.bot-message .message-content {
    background: white;
    border: 1px solid #ddd;
    border-bottom-left-radius: 5px;
}

.message-metadata {
    font-size: 11px;
    color: #666;
    margin-top: 5px;
}

.message-time {
    font-size: 10px;
    color: #999;
    margin-top: 5px;
}

.chat-input {
    display: flex;
    padding: 10px;
    border-top: 1px solid #ddd;
}

.chat-input input {
    flex: 1;
    padding: 10px;
    border: 1px solid #ddd;
    border-radius: 20px;
    outline: none;
}

.chat-input button {
    margin-left: 10px;
    padding: 10px 20px;
    background: #4CAF50;
    color: white;
    border: none;
    border-radius: 20px;
    cursor: pointer;
}

.quick-actions {
    padding: 10px;
    display: flex;
    gap: 5px;
    flex-wrap: wrap;
    border-top: 1px solid #eee;
}

.quick-btn {
    padding: 5px 10px;
    background: #f0f0f0;
    border: 1px solid #ddd;
    border-radius: 15px;
    cursor: pointer;
    font-size: 12px;
}

.quick-btn:hover {
    background: #e0e0e0;
}

.typing-dots {
    display: flex;
    gap: 3px;
}

.typing-dots span {
    width: 8px;
    height: 8px;
    border-radius: 50%;
    background: #999;
    animation: typing 1.4s infinite ease-in-out;
}

.typing-dots span:nth-child(1) { animation-delay: -0.32s; }
.typing-dots span:nth-child(2) { animation-delay: -0.16s; }

@keyframes typing {
    0%, 80%, 100% { transform: scale(0); }
    40% { transform: scale(1); }
}

4. HTML untuk Implementasi

<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AgriEdu Chatbot</title>
    <link rel="stylesheet" href="chat-styles.css">
</head>
<body>
    <div class="container">
        <h1>πŸ€– AgriEdu Chatbot Demo</h1>
        <div id="chatContainer" class="chat-container"></div>
    </div>

    <script src="chatbot.js"></script>
</body>
</html>

Menggunakan Python:

import requests

def chat_with_bot(message):
    url = "http://localhost:5000/chat"
    payload = {"message": message}

    response = requests.post(url, json=payload)
    data = response.json()

    print(f"User: {data['user_message']}")
    print(f"Bot: {data['response']}")
    print(f"Intent: {data['intent']} (Confidence: {data['confidence']:.2f})")

    return data

# Contoh penggunaan
chat_with_bot("Ceritakan tentang alam")

πŸ“ Struktur File

simple-chatbot/
β”œβ”€β”€ chatbot.py              # File utama Flask API
β”œβ”€β”€ requirements.txt        # Dependencies Python
β”œβ”€β”€ intents.json           # Data training
β”œβ”€β”€ train_chatbot.ipynb    # Notebook untuk training model
β”œβ”€β”€ templates/
β”‚   └── index.html         # Web interface
β”œβ”€β”€ application/
β”‚   β”œβ”€β”€ index.css          # Styling
β”‚   └── index.js           # JavaScript
└── README.md              # Dokumentasi ini

# File model (dari training):
β”œβ”€β”€ chatbot_model.h5       # Model neural network
β”œβ”€β”€ words.pkl              # Vocabulary
└── classes.pkl            # Intent classes

πŸ”§ Troubleshooting

Jika model tidak ditemukan:

# Pastikan file model ada di direktori yang sama dengan chatbot.py
ls -la *.h5 *.pkl

Jika ada error NLTK:

import nltk
nltk.download('punkt')
nltk.download('wordnet')

Jika ada error dependencies:

# Install ulang dengan upgrade
pip install --upgrade -r requirements.txt

# chatbot-agriedu

Downloads last month

-

Downloads are not tracked for this model. How to track
Inference Providers NEW
This model isn't deployed by any Inference Provider. πŸ™‹ Ask for provider support