MinAI - Về trang chủ
Lý thuyết
11/1335 phút
Đang tải...

Chatbot Interface

Xây dựng chatbot interface cho RAG system với Telegram, Slack, Web

💻 Chatbot Interface

0

🎯 Mục tiêu bài học

TB5 min

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.

1

📋 Interface Options

TB5 min
Diagram
Đang vẽ diagram...

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?

2

📱 Option 1: Telegram Bot

TB5 min
Diagram
Đang vẽ diagram...

Setup Telegram Bot

JavaScript
1// Step 1: Create bot with @BotFather
2// /newbot → name → get API token
3
4// Step 2: n8n Telegram Trigger
5// - Credential: Telegram API token
6// - Updates: Message
7
8// Step 3: Process message
9// Code node: Extract message
10const chatId = $json.message.chat.id;
11const userMessage = $json.message.text;
12const userName = $json.message.from.first_name;
13
14return {
15 json: {
16 chatId,
17 query: userMessage,
18 userName,
19 sessionId: `tg_${chatId}`
20 }
21};

Telegram Response

JavaScript
1// After RAG pipeline generates answer
2// Telegram node: Send Message
3// Chat ID: {{ $json.chatId }}
4// Text: {{ $json.answer }}
5
6// For long answers, split into multiple messages
7function 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

JavaScript
1// Code node: Handle commands
2const text = $json.message.text;
3
4if (text === '/start') {
5 return { json: {
6 response: "Welcome! Ask me anything about our knowledge base.",
7 isCommand: true
8 }};
9}
10
11if (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: true
15 }};
16}
17
18// Regular question
19return { 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?

3

💬 Option 2: Slack Bot

TB5 min
Diagram
Đang vẽ diagram...
JavaScript
1// Slack Trigger node
2// Event: message (in channel or DM)
3// Or: App Mention (when @bot is mentioned)
4
5// Extract Slack message
6const channelId = $json.event.channel;
7const userId = $json.event.user;
8const text = $json.event.text.replace(/<@.*?>/, '').trim(); // Remove @mention
9const threadTs = $json.event.thread_ts || $json.event.ts;
10
11return {
12 json: {
13 channelId,
14 userId,
15 query: text,
16 threadTs, // Reply in thread
17 sessionId: `slack_${channelId}_${threadTs}`
18 }
19};
JavaScript
1// Slack node: Reply
2// Channel: {{ $json.channelId }}
3// Thread ID: {{ $json.threadTs }}
4// Message: formatted answer with blocks
5
6const slackBlocks = [
7 {
8 type: "section",
9 text: {
10 type: "mrkdwn",
11 text: $json.answer
12 }
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?

4

🌐 Option 3: Web Chat Widget

TB5 min
JavaScript
1// Webhook endpoint for web chat
2// POST /webhook/chat
3// Body: { "message": "...", "sessionId": "..." }
4
5// Respond to Webhook node
6const response = {
7 answer: $json.aiAnswer,
8 sources: $json.sources,
9 confidence: $json.confidence,
10 sessionId: $json.sessionId
11};
12
13// Frontend can be:
14// - Simple HTML/JS chat widget
15// - React component
16// - n8n Chat widget (built-in)

n8n Chat Widget

JavaScript
1// n8n provides a built-in chat widget
2// Configuration in workflow:
3// 1. Use "Chat Trigger" node (not Webhook)
4// 2. Connect to AI Agent with RAG
5// 3. Widget auto-generated at workflow URL
6
7// Chat Trigger node settings:
8// - Authentication: None or API Key
9// - 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?

5

🔒 Session and Rate Limiting

TB5 min
JavaScript
1// Code node: Rate limiting per user
2const userId = $json.userId;
3const now = Date.now();
4
5// Track in memory or Redis
6// Max 20 messages per minute per user
7const userRequests = getUserRequests(userId);
8const recentRequests = userRequests.filter(t => now - t < 60000);
9
10if (recentRequests.length >= 20) {
11 return { json: {
12 answer: "You are sending too many messages. Please wait a moment.",
13 rateLimited: true
14 }};
15}
16
17// Record this request
18recentRequests.push(now);

Checkpoint

Rate limiting nên set bao nhiêu messages/minute? Tại sao cần rate limiting?

6

📊 Feedback Collection

TB5 min
JavaScript
1// After each response, offer feedback buttons
2// Telegram: Inline keyboard
3// Slack: Message actions
4// Web: Thumbs up/down
5
6// Telegram inline keyboard
7const keyboard = {
8 inline_keyboard: [[
9 { text: "Helpful", callback_data: `feedback_good_${messageId}` },
10 { text: "Not helpful", callback_data: `feedback_bad_${messageId}` }
11 ]]
12};
13
14// Track feedback for quality improvement
15const feedback = {
16 messageId: $json.messageId,
17 query: $json.originalQuery,
18 answer: $json.answer,
19 rating: $json.feedbackType,
20 timestamp: new Date().toISOString()
21};
22
23// Save to Google Sheets for analysis
Interface Tips
  • 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?

7

📝 Bài tập thực hành

TB5 min
Exercises
  1. Build Telegram bot kết nối RAG pipeline
  2. Hoặc build Slack bot với thread replies
  3. Add feedback collection (thumbs up/down)
  4. 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.