💻 Chatbot Interface
🎯 Mục tiêu bài học
Sau bài học này, bạn sẽ:
✅ Biết các interface options cho RAG chatbot
✅ Xây dựng Telegram Bot kết nối RAG pipeline
✅ Implement Slack Bot với thread replies
✅ Setup Web Chat Widget với n8n built-in widget
✅ Thêm session management, rate limiting, và feedback collection
Kết nối RAG pipeline với chatbot interfaces — Telegram, Slack, hoặc web chat widget.
📋 Interface Options
Checkpoint
n8n RAG chatbot có thể kết nối với những platforms nào? Platform nào best cho use case nào?
📱 Option 1: Telegram Bot
Setup Telegram Bot
1// Step 1: Create bot with @BotFather2// /newbot → name → get API token34// Step 2: n8n Telegram Trigger5// - Credential: Telegram API token6// - Updates: Message78// Step 3: Process message9// Code node: Extract message10const chatId = $json.message.chat.id;11const userMessage = $json.message.text;12const userName = $json.message.from.first_name;1314return {15 json: {16 chatId,17 query: userMessage,18 userName,19 sessionId: `tg_${chatId}`20 }21};Telegram Response
1// After RAG pipeline generates answer2// Telegram node: Send Message3// Chat ID: {{ $json.chatId }}4// Text: {{ $json.answer }}56// For long answers, split into multiple messages7function splitMessage(text, maxLength = 4096) {8 const parts = [];9 while (text.length > 0) {10 parts.push(text.substring(0, maxLength));11 text = text.substring(maxLength);12 }13 return parts;14}Telegram Commands
1// Code node: Handle commands2const text = $json.message.text;34if (text === '/start') {5 return { json: {6 response: "Welcome! Ask me anything about our knowledge base.",7 isCommand: true8 }};9}1011if (text === '/help') {12 return { json: {13 response: "Commands:\n/ask [question] - Ask a question\n/sources - Show last sources\n/clear - Clear history",14 isCommand: true15 }};16}1718// Regular question19return { json: { query: text, isCommand: false } };Checkpoint
Liệt kê các bước setup Telegram Bot với n8n. Cách handle commands /start, /help, /clear?
💬 Option 2: Slack Bot
1// Slack Trigger node2// Event: message (in channel or DM)3// Or: App Mention (when @bot is mentioned)45// Extract Slack message6const channelId = $json.event.channel;7const userId = $json.event.user;8const text = $json.event.text.replace(/<@.*?>/, '').trim(); // Remove @mention9const threadTs = $json.event.thread_ts || $json.event.ts;1011return {12 json: {13 channelId,14 userId,15 query: text, 16 threadTs, // Reply in thread17 sessionId: `slack_${channelId}_${threadTs}`18 }19};1// Slack node: Reply2// Channel: {{ $json.channelId }} 3// Thread ID: {{ $json.threadTs }}4// Message: formatted answer with blocks56const slackBlocks = [7 {8 type: "section",9 text: {10 type: "mrkdwn",11 text: $json.answer12 }13 },14 {15 type: "context",16 elements: [{17 type: "mrkdwn",18 text: `Sources: ${$json.sources.join(', ')} | Confidence: ${$json.confidence}`19 }]20 }21];Checkpoint
Mô tả cách setup Slack Bot với thread replies. Tại sao thread replies quan trọng?
🌐 Option 3: Web Chat Widget
1// Webhook endpoint for web chat2// POST /webhook/chat3// Body: { "message": "...", "sessionId": "..." }45// Respond to Webhook node6const response = {7 answer: $json.aiAnswer,8 sources: $json.sources,9 confidence: $json.confidence,10 sessionId: $json.sessionId11};1213// Frontend can be:14// - Simple HTML/JS chat widget15// - React component16// - n8n Chat widget (built-in)n8n Chat Widget
1// n8n provides a built-in chat widget2// Configuration in workflow:3// 1. Use "Chat Trigger" node (not Webhook)4// 2. Connect to AI Agent with RAG5// 3. Widget auto-generated at workflow URL67// Chat Trigger node settings:8// - Authentication: None or API Key9// - Initial Messages: ["Hi! Ask me anything about our docs."]10// - Suggested Questions: ["What is our refund policy?", "How to contact support?"]Checkpoint
n8n Chat Widget config như thế nào? Cần dùng node gì thay vì Webhook?
🔒 Session and Rate Limiting
1// Code node: Rate limiting per user2const userId = $json.userId;3const now = Date.now();45// Track in memory or Redis6// Max 20 messages per minute per user7const userRequests = getUserRequests(userId);8const recentRequests = userRequests.filter(t => now - t < 60000);910if (recentRequests.length >= 20) {11 return { json: {12 answer: "You are sending too many messages. Please wait a moment.",13 rateLimited: true14 }};15}1617// Record this request18recentRequests.push(now);Checkpoint
Rate limiting nên set bao nhiêu messages/minute? Tại sao cần rate limiting?
📊 Feedback Collection
1// After each response, offer feedback buttons2// Telegram: Inline keyboard3// Slack: Message actions4// Web: Thumbs up/down56// Telegram inline keyboard7const keyboard = {8 inline_keyboard: [[9 { text: "Helpful", callback_data: `feedback_good_${messageId}` },10 { text: "Not helpful", callback_data: `feedback_bad_${messageId}` }11 ]]12};1314// Track feedback for quality improvement15const feedback = {16 messageId: $json.messageId,17 query: $json.originalQuery,18 answer: $json.answer,19 rating: $json.feedbackType,20 timestamp: new Date().toISOString()21};2223// Save to Google Sheets for analysis- Telegram: Best cho personal use, mobile-friendly
- Slack: Best cho team/company internal bots
- Web: Best cho customer-facing support
- Thread replies: Luôn reply in thread để giữ channel clean
Checkpoint
Feedback collection gồm những gì? Tại sao cần track feedback cho quality improvement?
📝 Bài tập thực hành
- Build Telegram bot kết nối RAG pipeline
- Hoặc build Slack bot với thread replies
- Add feedback collection (thumbs up/down)
- Implement rate limiting per user
Checkpoint
Liệt kê 4 exercises. Bạn chọn Telegram hay Slack và tại sao?
🚀 Bài tiếp theo
Capstone Project → — Xây dựng Knowledge Base Chatbot hoàn chỉnh.
