Skip to content

Conversation

@rishabh30Gupta
Copy link

@rishabh30Gupta rishabh30Gupta commented Dec 13, 2025

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

  • Backend (chatbot/app.py): Added X.sum().item() == 0 check to detect gibberish inputs
  • Frontend (client/app/api/chat/route.ts): Created Next.js API route to proxy requests to Python backend

Testing

Tested with multiple gibberish inputs:

  • "unga bunga junga" → Returns "I do not understand..."
  • "xyzabc123" → Returns "I do not understand..."
  • "asdfghjkl" → Returns "I do not understand..."

Valid inputs still work correctly:

  • "what is blockchain" → Returns blockchain definition
  • "hello" → Returns greeting

📸 Screenshots

image

Summary by CodeRabbit

  • New Features

    • Redesigned mobile sidebar with improved scroll behavior, overlay, and accessibility features
    • Implemented API route to forward chat requests to the backend service
  • Bug Fixes

    • Added graceful handling when input contains no recognized words

✏️ Tip: You can customize this high-level summary in your review settings.

Rishabh Gupta added 2 commits December 13, 2025 16:38
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
@coderabbitai
Copy link

coderabbitai bot commented Dec 13, 2025

Walkthrough

The 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

Cohort / File(s) Summary
Backend word recognition guard
chatbot/app.py
Early exit when bag-of-words vector sums to zero (no recognized words), returning a not-understood message without model invocation.
Frontend API bridge
client/app/api/chat/route.ts
New Next.js API route handling POST requests, forwarding JSON body to Python backend at http://localhost:5000/api/chat, and returning responses with error handling.
Mobile sidebar UX enhancement
client/app/components/Header/Header.tsx
Added useEffect hook for scroll locking when sidebar opens/closes, scroll position capture/restoration, overlay scrim element, dedicated sidebar panel with close button, and accessibility attributes.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Scroll locking mechanism in Header: verify scroll position restoration logic works correctly across viewport changes and doesn't interfere with other scroll handlers
  • API route integration: confirm backend contract alignment and error handling edge cases
  • Mobile sidebar overlay: test accessibility features (aria-hidden, focus management) and pointer event handling across browsers

Poem

🐰 A rabbit bounced through code so fine,
With guards that check each word's design,
A bridge was built to talk and share,
Scroll locked tight with mobile care! ✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The title directly and accurately summarizes the main fix: adding a guard to prevent the chatbot from returning blockchain definitions for gibberish inputs, instead returning a fallback response.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link

@coderabbitai coderabbitai bot left a 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 setting pointer-events: none) and inline style={{ pointerEvents: 'auto' }}. While the inline style overrides the class, this creates confusing code. If you want pointer events enabled, remove touch-none from 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

📥 Commits

Reviewing files that changed from the base of the PR and between 2d3a4dd and fa8e6d5.

📒 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 and aria-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', {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

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.

Suggested change
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).

Comment on lines +16 to +17
const data = await response.json();
return NextResponse.json(data);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

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.

Suggested change
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.

Comment on lines +18 to +23
} catch (error) {
console.error('Error communicating with chatbot:', error);
return NextResponse.json(
{ message: 'Application not found' },
{ status: 500 }
);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

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.

Suggested change
} 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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant