💬 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 interface3- Conversation history4- Multiple chat sessions5- Custom AI personality6- Export conversationsUI 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 Button5│ └── Repeating Group (conversations)6│7└── Chat Area (80% width)8 ├── Chat Header9 ├── Messages Container10 │ └── Repeating Group (messages)11 └── Input Area12 ├── Text Input13 └── Send ButtonBuilding the Sidebar
Conversation List
Text
1Repeating Group:2- Type: Conversation3- Data source: 4 Search for Conversations5 where user = Current User6 where is_archived = no7 sorted by last_message_date desc8 9Cell content:10- Title text (truncated)11- Date12- Message count badgeClick to Switch
Text
1Workflow: Conversation cell clicked2 31. Set current_conversation = This cell's Conversation42. Scroll chat to bottomNew Chat Button
Text
1Workflow: New Chat clicked2 31. Create new Conversation4 - title: "New Chat"5 - user: Current User6 - created_date: Current date7 82. Set current_conversation = Result of step 1Building Chat Area
Messages Display
Text
1Repeating Group:2- Type: Message3- Data source:4 Search for Messages5 where conversation = current_conversation6 sorted by created_date ascending7 8- Layout: Column9- Cell: Message bubble componentMessage Bubble Design
Text
1Conditional styling:2 3If role = "user":4- Align: right5- Background: blue6- Text: white7 8If role = "assistant":9- Align: left10- Background: gray11- Text: black12 13Both:14- Rounded corners15- Padding16- Max-width: 70%Auto-scroll
Text
1After new message:21. Use "Scroll to" action32. Target: bottom of repeating group43. Or use anchor element at bottomInput Section
Elements
Text
11. Multiline Input2 - Placeholder: "Type your message..."3 - Stretch to fit: No4 - Max height: 100px5 62. Send Button7 - Icon: arrow or send8 - Conditional: disabled when input emptyEnter to Send
Text
1Input element:2- Detect Enter key3- Trigger send workflow4- Shift+Enter for new lineCore Workflow: Send Message
Text
1Button "Send" clicked:2 3Step 1: Validate4- If input empty, stop workflow5 6Step 2: Create user message7- Create Message8 - content: input text9 - role: "user"10 - conversation: current_conversation11 12Step 3: Clear input13- Reset input to empty14 15Step 4: Set loading16- Set is_loading = yes17 18Step 5: Build messages array19- Search all Messages in conversation20- Format for OpenAI API21 22Step 6: Call OpenAI API23- Messages: conversation history24- System prompt: AI personality25 26Step 7: Create assistant message27- Create Message28 - content: API response29 - role: "assistant"30 - conversation: current_conversation31 32Step 8: Update conversation33- last_message_date: Current date34- message_count: +235 36Step 9: Clear loading37- Set is_loading = no38 39Step 10: Scroll to bottomBuilding 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 workflow2- Build JSON server-side3- More control4 5Method 2: API connector6- Dynamic message array7- Use :formatted as textMessage History Limit
Token Management
Text
1Don't send unlimited history!2 3Limit to last 10-20 messages:4- Prevents token overflow5- Reduces cost6- Maintains relevant context7 8Search for Messages:9- conversation = current10- sorted by created_date desc11- :items until #1012- :reversed (for correct order)System Prompt
Default Personality
Text
1"You are a helpful AI assistant. Be:2- Friendly and professional3- Concise but thorough4- Helpful and patient5- Accurate (say 'I don't know' if uncertain)"Custom Personalities
Text
1Option for users to customize:2 3Data field: Conversation.system_prompt4 5Presets:6- General Assistant7- Writing Helper8- Code Assistant9- Business Advisor10- Creative PartnerAuto-naming Conversations
First Message Title
Text
1After first user message:2 31. Call OpenAI4 Prompt: "Generate a 3-5 word title for this chat:5 {first_message}"6 72. Update Conversation titleOr Simple Approach
Text
1Title = First 30 characters of first message + "..."Loading States
Typing Indicator
Text
1While waiting for response:2- Show animated dots3- "AI is typing..."4- Disable send buttonImplementation
Text
1Animated element:2- Three dots3- CSS animation4- Visible when is_loading5 6Or use GIF/Lottie animationExtra Features
Delete Conversation
Text
1Workflow:21. Confirm popup32. Make changes to Conversation:4 is_archived = yes53. Set current_conversation = empty64. Show success messageExport Chat
Text
1Export button:21. Format all messages as text32. Add timestamps43. Download as .txt fileClear Chat
Text
1Start fresh in current conversation:21. Delete all Messages in conversation32. Reset message_count43. Keep conversationError Handling
Handle Errors
Text
1API failures:21. Show error message (not technical)32. "Sorry, I couldn't respond. Please try again."43. Enable retry54. Log error for debuggingMobile Optimization
Responsive Layout
Text
1Mobile (<768px):2- Hide sidebar by default3- Show hamburger menu4- Full-width chat5- Slide-in sidebar6 7Desktop:8- Side-by-side layout9- Fixed sidebarTouch Optimizations
Text
1- Larger touch targets2- Swipe to show sidebar3- Pull to refresh4- Keyboard awareTesting Checklist
Test Your Chatbot
Text
1☐ Create new conversation2☐ Send messages3☐ Receive AI responses4☐ Switch between conversations5☐ Loading indicator shows6☐ Auto-scroll works7☐ History persists8☐ Delete conversation9☐ Mobile responsive10☐ Error handling worksBài Tập
Complete Project
Build AI Chatbot:
- Set up database (Conversation, Message)
- Create chat page layout
- Build sidebar with conversation list
- Build chat message display
- Implement send workflow
- Add loading states
- Auto-name conversations
- Test conversation memory
- Add delete/export features
- Optimize for mobile
Tiếp theo: Bài 11 - Building AI Analysis Tool
