Downloads · 30 days
0
serpto/chatbot-agriedu
chatbot-agriedu is a machine learning model from serpto. Use it for the machine learning task on the model card, and read the license before you ship it in a product.
Sistem chatbot cerdas dengan Flask API dan Neural Network untuk bahasa Indonesia.
Downloads · 30 days
0
Access
Public
Updated Jun 11, 2025
Repo size
2.5 MB
Likes
0
Public
Click a slice to open those files.
.h52.2 MB · 86%
From the Hugging Face model README
Sistem chatbot cerdas dengan Flask API dan Neural Network untuk bahasa Indonesia.
# Buat virtual environment
python -m venv venv
# Aktifkan virtual environment
# Untuk Windows:
venv\Scripts\activate
# Untuk Linux/Mac:
source venv/bin/activate
pip install -r requirements.txt
Dependencies yang dibutuhkan:
Sebelum menjalankan aplikasi, pastikan file model sudah ada:
chatbot_model.h5 - Model neural networkwords.pkl - Vocabularyclasses.pkl - Intent classesintents.json - Data training (sudah tersedia)Catatan: File model dapat diperoleh dengan menjalankan
train_chatbot.ipynbdi Google Colab
python chatbot.py
Aplikasi akan berjalan di: http://localhost:5000
Buka browser dan akses:
http://localhost:5000http://localhost:5000/healthhttp://localhost:5000/testhttp://localhost:5000
GET /api/v1/health
Response:
{
"status": "healthy",
"model_loaded": true,
"message": "AgriEdu Chatbot API is running"
}
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"
}
GET /api/v1/intents
Response:
{
"intents": ["greeting", "goodbye", "thanks", "help", "nature_general"],
"total": 50
}
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
}
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"
}
The chatbot will respond with a JSON object containing:
user_message: The message you sentresponse: The chatbot's responseintent: The detected intent categoryconfidence: 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"
}
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"])
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 -X POST http://localhost:5000/api/v1/chat \
-H "Content-Type: application/json" \
-d '{"message": "Halo, siapa nama kamu?"}'
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 format500 Internal Server Error: Server-side error503 Service Unavailable: Model not loadedimport 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"])
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));
# 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
The API returns standard HTTP status codes:
200 OK: Request successful400 Bad Request: Invalid request format404 Not Found: Endpoint not found500 Internal Server Error: Server-side errorError Response Format:
{
"error": "Error message description"
}
For interactive API documentation, visit:
http://localhost:5000/api/docs
This provides a Swagger UI interface where you can:
# 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
// 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?');
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);
});
.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); }
}
<!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>
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")
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
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
#� �c�h�a�t�b�o�t�-�a�g�r�i�e�d�u� � �