Lý thuyết
30 phút
Bài 8/15

Handling AI Responses

Xử lý, format và hiển thị AI responses trong no-code apps

🔄 Handling AI Responses

Xử lý AI responses hiệu quả cho UX tốt hơn.

Response Types

Text
11. Plain Text - Simple output
22. JSON - Structured data
33. Markdown - Formatted text
44. Code - Programming snippets
55. Lists - Bullet/numbered

Requesting 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:name
43. Extract specific values

With JSON Plugin

Text
1Toolbox or JSON plugins:
21. Parse JSON action
32. Access nested values
43. Handle arrays
54. Error handling

Arrays

Text
1Response: {"items": ["A", "B", "C"]}
2
3In Bubble:
41. Parse as JSON
52. Access: response:items
63. Use in Repeating Group

Displaying Responses

Plain Text

Text
1Simple display:
2- Text element
3- Multiline enabled
4- Auto-width or fixed

Markdown Rendering

Text
1For markdown responses:
21. Use Rich Text Editor (read-only)
32. Or Markdown plugin
43. Convert markdown → HTML

Formatted Output

Text
1Make output readable:
2- Headers styled
3- Lists formatted
4- Code highlighted
5- Links clickable

Loading States

Basic Loading

Text
1User experience:
21. Button clicked
32. Show loading spinner
43. Disable inputs
54. "AI is thinking..."
65. Response arrives
76. Hide loading, show result

Implementation

Text
1Page State: is_loading (yes/no)
2
3Workflow:
41. Set is_loading = yes
52. Call AI API
63. Set is_loading = no
74. Display result
8
9Conditionals:
10- Button: not clickable when is_loading
11- Spinner: visible when is_loading
12- Result: visible when not is_loading

Progressive Feedback

Text
1For long operations:
2- "Analyzing your input..."
3- "Generating response..."
4- "Almost done..."
5
6Or typing animation effect

Streaming Responses

Why Stream?

Text
1Without streaming:
2- User waits 5-10 seconds
3- Then sees full response
4
5With streaming:
6- Text appears word by word
7- Feels faster, more engaging
8- Like ChatGPT experience

Implementation (Advanced)

Text
1Bubble limitations:
2- No native SSE support
3- Requires plugin or backend
4
5Options:
61. Backend server (Node.js)
72. Third-party service
83. Simulate with animation

Error Handling

Common Errors

Text
11. API timeout
22. Rate limit exceeded
33. Invalid response
44. Empty response
55. Content filtered

User-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 fails
32. Wait 2 seconds
43. Retry (max 2 times)
54. If still fails, show error
65. Offer manual retry button

Error 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 empty
32. Valid format (if JSON)
43. Contains expected fields
54. Within size limits
65. No harmful content

Content Filtering

Text
1Post-process:
2- Remove unwanted text
3- Filter profanity
4- Check for errors
5- Format appropriately

Saving Responses

When to Save

Text
1Save AI responses when:
2- User history needed
3- Chat conversations
4- Generated content library
5- Analytics required

Data 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 response
32. Show in "My History"
43. Allow favorites
54. Re-use or copy
65. Delete option

Copy to Clipboard

Implementation

Text
1Copy button workflow:
21. Button clicked
32. Copy to clipboard: Result Text's value
43. Show "Copied!" feedback
54. Reset after 2 seconds

Feedback

Text
1States:
2- Default: "Copy"
3- Copied: "✓ Copied!"
4- Auto-reset to default

Export Options

Download as File

Text
1Options:
2- Copy to clipboard
3- Download as .txt
4- Download as .docx
5- Send to email
6- Save to app

Format for Export

Text
1Before export:
21. Clean up formatting
32. Add metadata (date, title)
43. Convert if needed
54. Generate download link

Performance Tips

Optimize Performance
Text
11. Cache frequent responses
22. Show partial results quickly
33. Use appropriate timeouts
44. Compress large responses
55. Clean old data periodically

Multi-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 language
3- Apply RTL styling
4- Proper text alignment

Accessibility

Screen Reader Support

Text
1- ARIA labels for loading
2- Announce new content
3- Keyboard navigation
4- High contrast options

Readable Output

Text
1- Sufficient font size
2- Line spacing
3- Contrast ratio
4- Resize support

Bài Tập

Practice

Xây dựng Response Handler:

  1. Create loading animation
  2. Parse JSON response
  3. Display formatted output
  4. Add copy button
  5. Implement error handling
  6. Save response history

Tiếp theo: Bài 9 - Building AI Writing App