-
Notifications
You must be signed in to change notification settings - Fork 173
Fix: Chatbot returns blockchain definition for gibberish inputs instead of fallback response #195
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Conversation
This commit fixes multiple UX issues with the mobile/tablet sidebar: Issues Fixed: - Background interaction bleed-through: Users could click/interact with main content while sidebar was open - Missing scroll lock: Background content could scroll while sidebar was active - Non-scrollable sidebar: Drawer content would be cut off if it exceeded viewport height - Accessibility improvements: Added proper ARIA labels Changes Made: 1. Added body scroll lock using useEffect hook - Locks scroll when sidebar opens with overflow:hidden and position:fixed - Preserves and restores scroll position on close - Prevents background scrolling completely 2. Enhanced overlay/scrim interaction blocking - Added touch-none class to prevent touch events - Added explicit pointerEvents: 'auto' for better blocking - Added aria-hidden for accessibility 3. Made sidebar content scrollable - Restructured sidebar with flexbox (flex flex-col) - Header section: flex-shrink-0 (fixed) - Content area: flex-1 overflow-y-auto (scrollable) 4. Improved accessibility - Added aria-label to close button - Added aria-hidden to overlay Testing: - Verified background clicks are blocked (0 interactions) - Verified scroll lock works (0px scroll achieved) - Verified sidebar content is scrollable - Verified overlay closes sidebar on click Resolves issues with sidebar UX and interaction blocking.
- Add zero-vector check in chatbot/app.py to detect gibberish inputs - Return fallback response 'I do not understand...' for unknown words - Create Next.js API route to proxy requests to Python backend - Fixes issue where chatbot defaulted to blockchain_intro for gibberish
WalkthroughThe changes enhance chatbot robustness and frontend integration. A guard clause in the Python backend prevents model invocation when no recognized words are detected. A new Next.js API route bridges frontend and backend communication. The mobile header component adds scroll-locking behavior and an interactive sidebar overlay with accessibility improvements. Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
🧹 Nitpick comments (2)
client/app/api/chat/route.ts (1)
8-14: Consider adding timeout and request validation.The fetch request has no timeout, which could cause the route to hang if the backend is unresponsive. Additionally, validating the request body before forwarding would improve security.
Consider these improvements:
// Add timeout const controller = new AbortController(); const timeoutId = setTimeout(() => controller.abort(), 10000); // 10s timeout try { // Validate request body const body = await request.json(); if (!body.message || typeof body.message !== 'string') { return NextResponse.json( { message: 'Invalid request: message field required' }, { status: 400 } ); } const response = await fetch(`${process.env.CHATBOT_API_URL}/api/chat`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body), signal: controller.signal, }); // ... rest of logic } finally { clearTimeout(timeoutId); }client/app/components/Header/Header.tsx (1)
141-142: Contradictory pointer event styles.The overlay has both
touch-none(Tailwind class settingpointer-events: none) and inlinestyle={{ pointerEvents: 'auto' }}. While the inline style overrides the class, this creates confusing code. If you want pointer events enabled, removetouch-nonefrom the className.Apply this diff to remove the contradictory class:
- className="fixed inset-0 bg-black bg-opacity-50 z-40 touch-none" + className="fixed inset-0 bg-black bg-opacity-50 z-40" style={{ pointerEvents: 'auto' }}Alternatively, if you prefer Tailwind utilities, remove the inline style:
- className="fixed inset-0 bg-black bg-opacity-50 z-40 touch-none" - style={{ pointerEvents: 'auto' }} + className="fixed inset-0 bg-black bg-opacity-50 z-40"
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (3)
chatbot/app.py(1 hunks)client/app/api/chat/route.ts(1 hunks)client/app/components/Header/Header.tsx(5 hunks)
🔇 Additional comments (3)
chatbot/app.py (1)
67-69: LGTM! Zero-vector check correctly prevents gibberish from reaching the model.The guard correctly identifies inputs with no recognized vocabulary words and returns the fallback response without invoking the model. This addresses the stated bug where gibberish was being mapped to "blockchain_intro".
client/app/components/Header/Header.tsx (2)
29-61: LGTM! Scroll-lock implementation follows best practices.The useEffect correctly locks body scroll when the sidebar opens, saves the scroll position, and restores it on close. The cleanup handler ensures styles are reset on unmount, preventing scroll-lock bugs if the component is removed while the sidebar is open.
147-147: Nice accessibility improvements!The
aria-hidden="true"on the overlay andaria-label="Close sidebar"on the close button properly support screen reader users.Also applies to: 162-162
| const body = await request.json(); | ||
|
|
||
| // Forward the request to the Python chatbot backend | ||
| const response = await fetch('http://localhost:5000/api/chat', { |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hardcoded localhost URL breaks in production.
The backend URL is hardcoded to http://localhost:5000, which will fail when the Next.js app is deployed. Use an environment variable to configure the backend URL.
Apply this diff to use an environment variable:
- const response = await fetch('http://localhost:5000/api/chat', {
+ const response = await fetch(`${process.env.CHATBOT_API_URL || 'http://localhost:5000'}/api/chat`, {Then add CHATBOT_API_URL to your .env.local and production environment configuration.
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const response = await fetch('http://localhost:5000/api/chat', { | |
| const response = await fetch(`${process.env.CHATBOT_API_URL || 'http://localhost:5000'}/api/chat`, { |
🤖 Prompt for AI Agents
In client/app/api/chat/route.ts around line 8 the fetch target is hardcoded to
http://localhost:5000 which will break in production; replace the hardcoded URL
with a configurable environment variable (use NEXT_PUBLIC_CHATBOT_API_URL for
client-exposed code), e.g. build the fetch URL from
process.env.NEXT_PUBLIC_CHATBOT_API_URL with a sensible fallback for local dev,
and ensure you add CHATBOT API URL to your .env.local and production environment
settings (set NEXT_PUBLIC_CHATBOT_API_URL=http://localhost:5000 for local).
| const data = await response.json(); | ||
| return NextResponse.json(data); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Missing HTTP status validation.
The code doesn't check if the backend request succeeded before parsing JSON. If the backend returns a 4xx or 5xx status, the error response will be returned to the client as if it were a success.
Apply this diff to validate the response status:
const data = await response.json();
+
+ if (!response.ok) {
+ return NextResponse.json(
+ data,
+ { status: response.status }
+ );
+ }
+
return NextResponse.json(data);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const data = await response.json(); | |
| return NextResponse.json(data); | |
| const data = await response.json(); | |
| if (!response.ok) { | |
| return NextResponse.json( | |
| data, | |
| { status: response.status } | |
| ); | |
| } | |
| return NextResponse.json(data); |
🤖 Prompt for AI Agents
In client/app/api/chat/route.ts around lines 16-17, the code immediately parses
and returns response.json() without validating HTTP status; change it to first
check response.ok, and if false read the response body (json or text) and return
a NextResponse with that body and the same response.status, otherwise parse and
return the successful JSON; ensure the returned NextResponse preserves the
backend status for error responses.
| } catch (error) { | ||
| console.error('Error communicating with chatbot:', error); | ||
| return NextResponse.json( | ||
| { message: 'Application not found' }, | ||
| { status: 500 } | ||
| ); |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Error message is misleading.
The generic "Application not found" message doesn't accurately describe potential failures (network errors, backend errors, JSON parsing errors, etc.). This could confuse users and make debugging harder.
Apply this diff to provide a more accurate error message:
} catch (error) {
console.error('Error communicating with chatbot:', error);
return NextResponse.json(
- { message: 'Application not found' },
+ { message: 'Failed to communicate with chatbot service' },
{ status: 500 }
);📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| } catch (error) { | |
| console.error('Error communicating with chatbot:', error); | |
| return NextResponse.json( | |
| { message: 'Application not found' }, | |
| { status: 500 } | |
| ); | |
| } catch (error) { | |
| console.error('Error communicating with chatbot:', error); | |
| return NextResponse.json( | |
| { message: 'Failed to communicate with chatbot service' }, | |
| { status: 500 } | |
| ); |
🤖 Prompt for AI Agents
In client/app/api/chat/route.ts around lines 18 to 23, the catch block returns a
misleading fixed message "Application not found"; replace it so the response
message reflects the actual error (e.g., use error instanceof Error ?
error.message : String(error)) and keep the status 500, and update the
console.error to log the error and its stack when available to aid debugging.
Issue
Chatbot returns blockchain definition for gibberish inputs instead of fallback response
Currently the chatbot doesn't know what to do when gibberish or unknown words (not in bag of words) are typed as query.
Problem
The chatbot matches unknown inputs (gibberish or words not in training data) to the "blockchain_intro" intent instead of any fallback intent. When something other than the training data is typed, it returns the blockchain definition by default.
Solution
Added a zero-vector check in chatbot/app.py before passing input to the model. If the input tensor is empty (no known words recognized), the chatbot immediately returns the fallback response "I do not understand..." without making a prediction.
Changes Made
X.sum().item() == 0check to detect gibberish inputsTesting
Tested with multiple gibberish inputs:
Valid inputs still work correctly:
📸 Screenshots
Summary by CodeRabbit
New Features
Bug Fixes
✏️ Tip: You can customize this high-level summary in your review settings.