🔄 Handling AI Responses
Xử lý AI responses hiệu quả cho UX tốt hơn.
Response Types
Text
11. Plain Text - Simple output22. JSON - Structured data33. Markdown - Formatted text44. Code - Programming snippets55. Lists - Bullet/numberedRequesting Structured Output
JSON Format
Text
1Prompt:2"Analyze this text and return JSON:3{4 'sentiment': 'positive/negative/neutral',5 'confidence': 0.0-1.0,6 'topics': ['topic1', 'topic2'],7 'summary': 'brief summary'8}9 10Text: {user_input}"Ensuring Valid JSON
JSON Tips
Text
1Add to prompt:2"Return ONLY valid JSON. No markdown formatting.3No explanations before or after.4Just the JSON object."5 6Or use response_format parameter:7{8 "response_format": { "type": "json_object" }9}Parsing JSON in Bubble
Basic Parsing
Text
1Steps:21. API returns text: {"name": "John", "age": 30}32. Use expression: result:formatted as JSON:name43. Extract specific valuesWith JSON Plugin
Text
1Toolbox or JSON plugins:21. Parse JSON action32. Access nested values43. Handle arrays54. Error handlingArrays
Text
1Response: {"items": ["A", "B", "C"]}2 3In Bubble:41. Parse as JSON52. Access: response:items63. Use in Repeating GroupDisplaying Responses
Plain Text
Text
1Simple display:2- Text element3- Multiline enabled4- Auto-width or fixedMarkdown Rendering
Text
1For markdown responses:21. Use Rich Text Editor (read-only)32. Or Markdown plugin43. Convert markdown → HTMLFormatted Output
Text
1Make output readable:2- Headers styled3- Lists formatted4- Code highlighted5- Links clickableLoading States
Basic Loading
Text
1User experience:21. Button clicked32. Show loading spinner43. Disable inputs54. "AI is thinking..."65. Response arrives76. Hide loading, show resultImplementation
Text
1Page State: is_loading (yes/no)2 3Workflow:41. Set is_loading = yes52. Call AI API63. Set is_loading = no74. Display result8 9Conditionals:10- Button: not clickable when is_loading11- Spinner: visible when is_loading12- Result: visible when not is_loadingProgressive Feedback
Text
1For long operations:2- "Analyzing your input..."3- "Generating response..."4- "Almost done..."5 6Or typing animation effectStreaming Responses
Why Stream?
Text
1Without streaming:2- User waits 5-10 seconds3- Then sees full response4 5With streaming:6- Text appears word by word7- Feels faster, more engaging8- Like ChatGPT experienceImplementation (Advanced)
Text
1Bubble limitations:2- No native SSE support3- Requires plugin or backend4 5Options:61. Backend server (Node.js)72. Third-party service83. Simulate with animationError Handling
Common Errors
Text
11. API timeout22. Rate limit exceeded33. Invalid response44. Empty response55. Content filteredUser-Friendly Messages
Text
1Instead of:2"Error 429: Rate limit exceeded"3 4Show:5"We're getting a lot of requests! 6Please try again in a few seconds. 🙏"Retry Logic
Text
1Workflow:21. API call fails32. Wait 2 seconds43. Retry (max 2 times)54. If still fails, show error65. Offer manual retry buttonError UI
Text
1┌────────────────────────────┐2│ ⚠️ Something went wrong │3│ │4│ We couldn't process your │5│ request. Please try again.│6│ │7│ [Try Again] [Contact Us] │8└────────────────────────────┘Response Validation
Check Before Display
Text
1Validate response:21. Not empty32. Valid format (if JSON)43. Contains expected fields54. Within size limits65. No harmful contentContent Filtering
Text
1Post-process:2- Remove unwanted text3- Filter profanity4- Check for errors5- Format appropriatelySaving Responses
When to Save
Text
1Save AI responses when:2- User history needed3- Chat conversations4- Generated content library5- Analytics requiredData Structure
Text
1AIResponse:2- user (User)3- prompt_used (text)4- input (text)5- output (text)6- created_date (date)7- tokens_used (number)8- is_favorite (yes/no)User History
Text
1Build history feature:21. Save each response32. Show in "My History"43. Allow favorites54. Re-use or copy65. Delete optionCopy to Clipboard
Implementation
Text
1Copy button workflow:21. Button clicked32. Copy to clipboard: Result Text's value43. Show "Copied!" feedback54. Reset after 2 secondsFeedback
Text
1States:2- Default: "Copy"3- Copied: "✓ Copied!"4- Auto-reset to defaultExport Options
Download as File
Text
1Options:2- Copy to clipboard3- Download as .txt4- Download as .docx5- Send to email6- Save to appFormat for Export
Text
1Before export:21. Clean up formatting32. Add metadata (date, title)43. Convert if needed54. Generate download linkPerformance Tips
Optimize Performance
Text
11. Cache frequent responses22. Show partial results quickly33. Use appropriate timeouts44. Compress large responses55. Clean old data periodicallyMulti-Language Responses
Detect Language
Text
1Add to prompt:2"Respond in the same language as the user's input."3 4Or specify:5"Respond in {user_language}"RTL Support
Text
1For Arabic, Hebrew:2- Detect language3- Apply RTL styling4- Proper text alignmentAccessibility
Screen Reader Support
Text
1- ARIA labels for loading2- Announce new content3- Keyboard navigation4- High contrast optionsReadable Output
Text
1- Sufficient font size2- Line spacing3- Contrast ratio4- Resize supportBài Tập
Practice
Xây dựng Response Handler:
- Create loading animation
- Parse JSON response
- Display formatted output
- Add copy button
- Implement error handling
- Save response history
Tiếp theo: Bài 9 - Building AI Writing App
