Lý thuyết
50 phút
Bài 10/15

Building AI Chatbot App

Xây dựng ứng dụng AI Chatbot với conversation history

💬 Building AI Chatbot App

Xây dựng AI Chatbot hoàn chỉnh với conversation memory.

Project Overview

What We'll Build

Text
1AI Chatbot Features:
2- Real-time chat interface
3- Conversation history
4- Multiple chat sessions
5- Custom AI personality
6- Export conversations

UI Preview

Text
1┌─────────────────────────────────────────────┐
2│ 🤖 AI Assistant [New Chat] 👤 │
3├─────────────────────────────────────────────┤
4│ │ Previous Chats │ │
5│ │ │ │
6│ │ ○ Marketing... │ [Bot] Hi! I'm your AI │
7│ │ ○ Product Q&A │ assistant. How can I │
8│ │ ○ Research │ help you today? │
9│ │ │ │
10│ │ [+ New Chat] │ [User] What are │
11│ │ │ the best AI tools? │
12│ │ │ │
13│ │ │ [Bot] There are many │
14│ │ │ great AI tools! Here │
15│ │ │ are some categories... │
16│ │ │ │
17│ ├────────────────┼──────────────────────────│
18│ │ [Type your message...] │
19│ │ [Send →] │
20└─────────────────────────────────────────────┘

Database Design

Data Types

Text
1Conversation:
2- title (text)
3- created_date (date)
4- last_message_date (date)
5- user (User)
6- is_archived (yes/no)
7- message_count (number)
8
9Message:
10- content (text)
11- role (text: user/assistant)
12- conversation (Conversation)
13- created_date (date)
14- tokens_used (number)

Page Setup

Page States

Text
1Custom States on Page:
2- current_conversation (Conversation)
3- is_loading (yes/no)
4- input_text (text)

Layout Structure

Text
1Main Group (row layout):
2├── Sidebar (20% width)
3│ ├── Header "Previous Chats"
4│ ├── New Chat Button
5│ └── Repeating Group (conversations)
6
7└── Chat Area (80% width)
8 ├── Chat Header
9 ├── Messages Container
10 │ └── Repeating Group (messages)
11 └── Input Area
12 ├── Text Input
13 └── Send Button

Building the Sidebar

Conversation List

Text
1Repeating Group:
2- Type: Conversation
3- Data source:
4 Search for Conversations
5 where user = Current User
6 where is_archived = no
7 sorted by last_message_date desc
8
9Cell content:
10- Title text (truncated)
11- Date
12- Message count badge

Click to Switch

Text
1Workflow: Conversation cell clicked
2
31. Set current_conversation = This cell's Conversation
42. Scroll chat to bottom

New Chat Button

Text
1Workflow: New Chat clicked
2
31. Create new Conversation
4 - title: "New Chat"
5 - user: Current User
6 - created_date: Current date
7
82. Set current_conversation = Result of step 1

Building Chat Area

Messages Display

Text
1Repeating Group:
2- Type: Message
3- Data source:
4 Search for Messages
5 where conversation = current_conversation
6 sorted by created_date ascending
7
8- Layout: Column
9- Cell: Message bubble component

Message Bubble Design

Text
1Conditional styling:
2
3If role = "user":
4- Align: right
5- Background: blue
6- Text: white
7
8If role = "assistant":
9- Align: left
10- Background: gray
11- Text: black
12
13Both:
14- Rounded corners
15- Padding
16- Max-width: 70%

Auto-scroll

Text
1After new message:
21. Use "Scroll to" action
32. Target: bottom of repeating group
43. Or use anchor element at bottom

Input Section

Elements

Text
11. Multiline Input
2 - Placeholder: "Type your message..."
3 - Stretch to fit: No
4 - Max height: 100px
5
62. Send Button
7 - Icon: arrow or send
8 - Conditional: disabled when input empty

Enter to Send

Text
1Input element:
2- Detect Enter key
3- Trigger send workflow
4- Shift+Enter for new line

Core Workflow: Send Message

Text
1Button "Send" clicked:
2
3Step 1: Validate
4- If input empty, stop workflow
5
6Step 2: Create user message
7- Create Message
8 - content: input text
9 - role: "user"
10 - conversation: current_conversation
11
12Step 3: Clear input
13- Reset input to empty
14
15Step 4: Set loading
16- Set is_loading = yes
17
18Step 5: Build messages array
19- Search all Messages in conversation
20- Format for OpenAI API
21
22Step 6: Call OpenAI API
23- Messages: conversation history
24- System prompt: AI personality
25
26Step 7: Create assistant message
27- Create Message
28 - content: API response
29 - role: "assistant"
30 - conversation: current_conversation
31
32Step 8: Update conversation
33- last_message_date: Current date
34- message_count: +2
35
36Step 9: Clear loading
37- Set is_loading = no
38
39Step 10: Scroll to bottom

Building Messages Array

Format for API

Text
1OpenAI expects:
2[
3 {"role": "system", "content": "You are..."},
4 {"role": "user", "content": "First message"},
5 {"role": "assistant", "content": "Reply"},
6 {"role": "user", "content": "Second message"}
7]

In Bubble

Text
1Method 1: Backend workflow
2- Build JSON server-side
3- More control
4
5Method 2: API connector
6- Dynamic message array
7- Use :formatted as text

Message History Limit

Token Management
Text
1Don't send unlimited history!
2
3Limit to last 10-20 messages:
4- Prevents token overflow
5- Reduces cost
6- Maintains relevant context
7
8Search for Messages:
9- conversation = current
10- sorted by created_date desc
11- :items until #10
12- :reversed (for correct order)

System Prompt

Default Personality

Text
1"You are a helpful AI assistant. Be:
2- Friendly and professional
3- Concise but thorough
4- Helpful and patient
5- Accurate (say 'I don't know' if uncertain)"

Custom Personalities

Text
1Option for users to customize:
2
3Data field: Conversation.system_prompt
4
5Presets:
6- General Assistant
7- Writing Helper
8- Code Assistant
9- Business Advisor
10- Creative Partner

Auto-naming Conversations

First Message Title

Text
1After first user message:
2
31. Call OpenAI
4 Prompt: "Generate a 3-5 word title for this chat:
5 {first_message}"
6
72. Update Conversation title

Or Simple Approach

Text
1Title = First 30 characters of first message + "..."

Loading States

Typing Indicator

Text
1While waiting for response:
2- Show animated dots
3- "AI is typing..."
4- Disable send button

Implementation

Text
1Animated element:
2- Three dots
3- CSS animation
4- Visible when is_loading
5
6Or use GIF/Lottie animation

Extra Features

Delete Conversation

Text
1Workflow:
21. Confirm popup
32. Make changes to Conversation:
4 is_archived = yes
53. Set current_conversation = empty
64. Show success message

Export Chat

Text
1Export button:
21. Format all messages as text
32. Add timestamps
43. Download as .txt file

Clear Chat

Text
1Start fresh in current conversation:
21. Delete all Messages in conversation
32. Reset message_count
43. Keep conversation

Error Handling

Handle Errors
Text
1API failures:
21. Show error message (not technical)
32. "Sorry, I couldn't respond. Please try again."
43. Enable retry
54. Log error for debugging

Mobile Optimization

Responsive Layout

Text
1Mobile (<768px):
2- Hide sidebar by default
3- Show hamburger menu
4- Full-width chat
5- Slide-in sidebar
6
7Desktop:
8- Side-by-side layout
9- Fixed sidebar

Touch Optimizations

Text
1- Larger touch targets
2- Swipe to show sidebar
3- Pull to refresh
4- Keyboard aware

Testing Checklist

Test Your Chatbot
Text
1☐ Create new conversation
2☐ Send messages
3☐ Receive AI responses
4☐ Switch between conversations
5☐ Loading indicator shows
6☐ Auto-scroll works
7☐ History persists
8☐ Delete conversation
9☐ Mobile responsive
10☐ Error handling works

Bài Tập

Complete Project

Build AI Chatbot:

  1. Set up database (Conversation, Message)
  2. Create chat page layout
  3. Build sidebar with conversation list
  4. Build chat message display
  5. Implement send workflow
  6. Add loading states
  7. Auto-name conversations
  8. Test conversation memory
  9. Add delete/export features
  10. Optimize for mobile

Tiếp theo: Bài 11 - Building AI Analysis Tool