Skip to content

[feature]:AI Chatbot support #4

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

Open
wants to merge 52 commits into
base: master
Choose a base branch
from
Open

[feature]:AI Chatbot support #4

wants to merge 52 commits into from

Conversation

arvi18
Copy link

@arvi18 arvi18 commented Apr 21, 2025

What's changed?

I've added an ai chatbot support, I'm unable to config the ai endpoints as I wasn't able to translate the ai config docs

closes apache#2303

Checklist

  • I have read the Contributing Guide
  • I have written the necessary doc or comment.
  • I have added the necessary unit tests and all cases have passed.

Add or update API

  • I have added the necessary e2e tests and all cases have passed.

Summary by CodeRabbit

  • New Features

    • Introduced a chatbot interface accessible via a floating button, allowing users to interact with an AI assistant within the app.
    • Added chat message components with copy-to-clipboard functionality for AI responses.
    • Provided options to send, reset, and view chat messages in a popup chat window.
  • Style

    • Added new styles for the chatbot and chat message components to enhance the chat interface appearance.

@arvi18
Copy link
Author

arvi18 commented Apr 21, 2025

Screen.Recording.2024-09-20.at.1.51.33.AM.1.1.mov

@arvi18
Copy link
Author

arvi18 commented Apr 21, 2025

Screen.Recording.2024-09-20.at.1.51.33.AM.1.1.mov

Ok, I'll test it later

@arvi18
Copy link
Author

arvi18 commented Apr 21, 2025

Sure, please let me know the feedback I'll accommodate the changes.

@arvi18
Copy link
Author

arvi18 commented Apr 21, 2025

Sure, please let me know the feedback I'll accommodate the changes.

Take a look at the code, ci fail

@arvi18
Copy link
Author

arvi18 commented Apr 21, 2025

Sure, please let me know the feedback I'll accommodate the changes.

Here are a few questions to look at:
1、Fix the ci failure issue
2、The back end returned sse streaming data, the front end did not display it and reported an error
image

Copy link

coderabbitai bot commented Apr 21, 2025

Walkthrough

This update introduces a new chatbot feature to the web application. It adds two new Angular components: ChatbotComponent for the interactive chat interface and ChatMessageComponent for displaying individual chat messages with copy-to-clipboard functionality. The application layout is updated to include the chatbot component, and all necessary styles and templates for the new components are provided. The shared module is updated to declare and export these components, making them available throughout the app. The chatbot interacts with a backend AI endpoint and includes error handling and chat reset functionality.

Changes

File(s) Change Summary
web-app/src/app/app.component.ts Imports HttpClient and adds <app-chatbot> to the component template.
web-app/src/app/shared/components/chat-message/chat-message.component.ts
...component.html
...component.css
Adds ChatMessageComponent with input for message, copy-to-clipboard logic, template, and styles.
web-app/src/app/shared/components/chatbot/chatbot.component.ts
...component.html
...component.css
Adds ChatbotComponent with popup chat UI, message handling, backend interaction, template, and styles.
web-app/src/app/shared/shared.module.ts Declares and exports ChatbotComponent and ChatMessageComponent in the shared module.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant ChatbotComponent
    participant HttpClient
    participant AI_Backend

    User->>ChatbotComponent: Clicks chatbot button / types message
    ChatbotComponent->>ChatbotComponent: Shows popup / updates userInput
    User->>ChatbotComponent: Sends message (button or Enter)
    ChatbotComponent->>ChatbotComponent: Adds user message to messages
    ChatbotComponent->>HttpClient: POST /api/ai with userInput
    HttpClient->>AI_Backend: Sends request
    AI_Backend-->>HttpClient: Returns AI response
    HttpClient-->>ChatbotComponent: Receives response
    ChatbotComponent->>ChatbotComponent: Adds AI message to messages
    User->>ChatbotComponent: Clicks copy on AI message
    ChatbotComponent->>ChatbotComponent: Copies text to clipboard, shows "Copied!" hint
Loading

Poem

In the corner, a chatbot appears,
Ready for questions, worries, or cheers.
Copy a message with the tap of a paw,
AI replies with wisdom and awe.
Reset the chat, start anew—
Rabbits love features that help you!
🐇💬✨

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@visz11
Copy link
Collaborator

visz11 commented Apr 21, 2025

@coderabbitai full review

Copy link

coderabbitai bot commented Apr 21, 2025

✅ Actions performed

Full review triggered.

@visz11
Copy link
Collaborator

visz11 commented Apr 22, 2025

@coderabbitai full review

Copy link

coderabbitai bot commented Apr 22, 2025

✅ Actions performed

Full review triggered.

@visz11
Copy link
Collaborator

visz11 commented Apr 22, 2025

@coderabbitai full review

Copy link

coderabbitai bot commented Apr 22, 2025

✅ Actions performed

Full review triggered.

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: 7

🧹 Nitpick comments (8)
web-app/src/app/app.component.ts (1)

1-1: Remove unused import

The HttpClient import is added but not used in this component. It should be removed to keep the code clean and avoid confusion.

-import { HttpClient } from '@angular/common/http';
web-app/src/app/shared/components/chat-message/chat-message.component.html (1)

1-10: Add visual distinction between user and AI messages

Currently, the only visual difference between AI and user messages is the copy button. Consider adding different styling or positioning for AI vs. user messages to improve readability.

web-app/src/app/shared/components/chatbot/chatbot.component.html (1)

1-19: Consider adding auto-scroll for chat messages

As more messages are added to the chat, the user will need to manually scroll to see the latest messages. Consider adding auto-scroll functionality to always show the most recent messages.

web-app/src/app/shared/components/chat-message/chat-message.component.css (2)

30-46: Improve tooltip positioning for better accessibility

The hint's absolute positioning with negative top value might cause it to be cut off in certain viewport sizes. Consider using a more reliable positioning approach.

 .hint {
   position: absolute;
-  top: -10px;
+  top: -25px;
   left: 50%;
   transform: translateX(-50%);
   background-color: #3f51b5;
   color: white;
   padding: 3px 8px;
   border-radius: 4px;
   font-size: 0.75rem;
   opacity: 0;
   transition: opacity 0.3s ease-in-out;
+  z-index: 1001; /* Ensure tooltip is above other elements */
 }

1-10: Add support for different message types

The current styling doesn't visually differentiate between user and AI messages. Consider adding different background colors or alignment.

 .message {
   margin-bottom: 5px;
   padding: 5px;
   border-radius: 4px;
   background-color: #f1f1f1;
   max-width: 100%;
   word-wrap: break-word;
   display: flex;
   align-items: center;
 }
+
+.message.user-message {
+  background-color: #e3f2fd;
+  align-self: flex-end;
+}
+
+.message.ai-message {
+  background-color: #f1f1f1;
+  align-self: flex-start;
+}
web-app/src/app/shared/components/chatbot/chatbot.component.ts (1)

43-45: Add confirmation for chat reset

Consider adding a confirmation dialog before clearing all messages to prevent accidental data loss.

   resetChat() {
-    this.messages = [];
+    if (confirm('Are you sure you want to reset the chat? All messages will be lost.')) {
+      this.messages = [];
+    }
   }
web-app/src/app/shared/components/chatbot/chatbot.component.css (2)

55-62: Add loading indicator for ongoing AI responses

Since the AI will likely take time to respond, add a styling for a loading indicator.

 .chat-messages {
   flex-grow: 1;
   overflow-y: auto; /* Enables vertical scrolling */
   max-height: 200px; /* Set a maximum height for the chat window */
   margin-bottom: 10px;
   width: 100%;
   padding-right: 5px; /* Optional: Adds some padding for better readability */
 }
+
+.loading-indicator {
+  display: inline-block;
+  width: 20px;
+  height: 20px;
+  border: 2px solid rgba(0, 0, 0, 0.1);
+  border-radius: 50%;
+  border-top-color: #3f51b5;
+  animation: spin 1s ease-in-out infinite;
+}
+
+@keyframes spin {
+  to { transform: rotate(360deg); }
+}

16-30: Add responsive styling for mobile devices

The current fixed width might not work well on small mobile screens. Consider adding media queries.

 .popup {
   position: fixed;
   bottom: 5rem;
   right: 2rem;
   width: 310px;
   max-height: 400px;
   border: 1px solid #ccc;
   border-radius: 8px;
   box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
   background-color: white;
   z-index: 1000;
   display: flex;
   flex-direction: column;
   justify-content: space-between;
 }
+
+/* Responsive styling for mobile devices */
+@media (max-width: 480px) {
+  .popup {
+    width: 90%;
+    right: 5%;
+    left: 5%;
+  }
+}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between b02837b and 8412b9e.

⛔ Files ignored due to path filters (1)
  • web-app/src/assets/img/chatbot-icon.svg is excluded by !**/*.svg
📒 Files selected for processing (8)
  • web-app/src/app/app.component.ts (2 hunks)
  • web-app/src/app/shared/components/chat-message/chat-message.component.css (1 hunks)
  • web-app/src/app/shared/components/chat-message/chat-message.component.html (1 hunks)
  • web-app/src/app/shared/components/chat-message/chat-message.component.ts (1 hunks)
  • web-app/src/app/shared/components/chatbot/chatbot.component.css (1 hunks)
  • web-app/src/app/shared/components/chatbot/chatbot.component.html (1 hunks)
  • web-app/src/app/shared/components/chatbot/chatbot.component.ts (1 hunks)
  • web-app/src/app/shared/shared.module.ts (3 hunks)
🔇 Additional comments (5)
web-app/src/app/app.component.ts (1)

14-17: LGTM! Integration of chatbot component

The chatbot component is properly integrated into the main application template, allowing it to be available across the entire application.

web-app/src/app/shared/shared.module.ts (2)

25-26: LGTM! Components properly imported

The chatbot components are correctly imported.


35-37: LGTM! Components properly registered

The components are correctly added to the COMPONENTS array, ensuring they are declared and exported by the SharedModule.

web-app/src/app/shared/components/chat-message/chat-message.component.ts (1)

1-23: Well-structured component for displaying chat messages

The implementation looks good. The component takes a message input and properly implements the copy-to-clipboard functionality with appropriate error handling and user feedback via the timeout.

web-app/src/app/shared/components/chatbot/chatbot.component.ts (1)

14-14: LGTM: Proper dependency injection

Good use of Angular's dependency injection for HttpClient.

Comment on lines +1 to +7
<div class="message" *ngIf="message.sender === 'AI'">
<p><strong>{{ message.sender }}:</strong> {{ message.text }}</p>
<button class="copy-btn" (click)="copyToClipboard(message.text)">
📋
<span class="hint" *ngIf="copied">Copied!</span>
</button>
</div>
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve accessibility for the copy button

The copy button lacks proper accessibility attributes, which makes it difficult for screen reader users to understand its purpose.

-<button class="copy-btn" (click)="copyToClipboard(message.text)">
+<button class="copy-btn" (click)="copyToClipboard(message.text)" aria-label="Copy message to clipboard" title="Copy to clipboard">
  📋
  <span class="hint" *ngIf="copied">Copied!</span>
</button>

<app-chat-message *ngFor="let message of messages" [message]="message"></app-chat-message>
</div>
<div class="input-container">
<input type="text" [(ngModel)]="userInput" (keydown.enter)="sendMessage()" placeholder="Type your message..." />
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add input validation

Currently, the user can send empty messages as there's no validation on the input. This could result in unnecessary API calls and empty messages in the chat.

-<input type="text" [(ngModel)]="userInput" (keydown.enter)="sendMessage()" placeholder="Type your message..." />
+<input type="text" [(ngModel)]="userInput" (keydown.enter)="userInput.trim() && sendMessage()" placeholder="Type your message..." />
-<button (click)="sendMessage()">Send</button>
+<button (click)="sendMessage()" [disabled]="!userInput.trim()">Send</button>

Comment on lines +1 to +3
<button class="float" (click)="togglePopup()">
<img src="../assets/img/chatbot-icon.svg" alt="Ai Chat" />
</button>
Copy link

Choose a reason for hiding this comment

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

💡 Verification agent

🧩 Analysis chain

Verify the asset path for the chatbot icon

The image path uses a relative path which might be incorrect depending on the project structure. Angular typically uses absolute paths from the assets folder.


🏁 Script executed:

#!/bin/bash
# Check if the chatbot icon exists at the specified path
# Find the assets directory and check for the chatbot-icon.svg
echo "Checking for chatbot icon file..."
fd -t f "chatbot-icon.svg" --full-path

Length of output: 155


Use an absolute asset path for the chatbot icon

The file chatbot-icon.svg does exist at web-app/src/assets/img/chatbot-icon.svg and will be served from /assets/img/chatbot-icon.svg. Relying on a relative path (../assets/...) can break when the app is on a nested route, since URLs resolve against the current browser path. Update the src to an absolute path:

<button class="float" (click)="togglePopup()">
-  <img src="../assets/img/chatbot-icon.svg" alt="Ai Chat" />
+  <img src="/assets/img/chatbot-icon.svg" alt="Ai Chat" />
</button>

— Ensure that all other asset references follow this pattern to avoid similar routing issues.

Comment on lines +6 to +15
<button class="close-btn" (click)="togglePopup()">✖</button>
<h3>Chatbot</h3>
<div class="chat-window">
<div class="chat-messages">
<app-chat-message *ngFor="let message of messages" [message]="message"></app-chat-message>
</div>
<div class="input-container">
<input type="text" [(ngModel)]="userInput" (keydown.enter)="sendMessage()" placeholder="Type your message..." />
<button (click)="sendMessage()">Send</button>
<button class="reset-btn" (click)="resetChat()">Reset</button>
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Improve accessibility for buttons and inputs

The buttons and inputs in the chatbot lack proper accessibility attributes, making them difficult to use with screen readers.

-<button class="close-btn" (click)="togglePopup()">✖</button>
+<button class="close-btn" (click)="togglePopup()" aria-label="Close chatbot">✖</button>
<h3>Chatbot</h3>
<div class="chat-window">
  <div class="chat-messages">
    <app-chat-message *ngFor="let message of messages" [message]="message"></app-chat-message>
  </div>
  <div class="input-container">
-   <input type="text" [(ngModel)]="userInput" (keydown.enter)="sendMessage()" placeholder="Type your message..." />
+   <input type="text" [(ngModel)]="userInput" (keydown.enter)="sendMessage()" placeholder="Type your message..." aria-label="Message input" />
-   <button (click)="sendMessage()">Send</button>
+   <button (click)="sendMessage()" aria-label="Send message">Send</button>
-   <button class="reset-btn" (click)="resetChat()">Reset</button>
+   <button class="reset-btn" (click)="resetChat()" aria-label="Reset chat">Reset</button>
  </div>
</div>
📝 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
<button class="close-btn" (click)="togglePopup()"></button>
<h3>Chatbot</h3>
<div class="chat-window">
<div class="chat-messages">
<app-chat-message *ngFor="let message of messages" [message]="message"></app-chat-message>
</div>
<div class="input-container">
<input type="text" [(ngModel)]="userInput" (keydown.enter)="sendMessage()" placeholder="Type your message..." />
<button (click)="sendMessage()">Send</button>
<button class="reset-btn" (click)="resetChat()">Reset</button>
<button class="close-btn" (click)="togglePopup()" aria-label="Close chatbot"></button>
<h3>Chatbot</h3>
<div class="chat-window">
<div class="chat-messages">
<app-chat-message *ngFor="let message of messages" [message]="message"></app-chat-message>
</div>
<div class="input-container">
<input
type="text"
[(ngModel)]="userInput"
(keydown.enter)="sendMessage()"
placeholder="Type your message..."
aria-label="Message input"
/>
<button (click)="sendMessage()" aria-label="Send message">Send</button>
<button class="reset-btn" (click)="resetChat()" aria-label="Reset chat">Reset</button>
</div>
</div>

Comment on lines +1 to +19
<button class="float" (click)="togglePopup()">
<img src="../assets/img/chatbot-icon.svg" alt="Ai Chat" />
</button>
<div class="popup" *ngIf="isPopupVisible">
<div class="popup-content">
<button class="close-btn" (click)="togglePopup()">✖</button>
<h3>Chatbot</h3>
<div class="chat-window">
<div class="chat-messages">
<app-chat-message *ngFor="let message of messages" [message]="message"></app-chat-message>
</div>
<div class="input-container">
<input type="text" [(ngModel)]="userInput" (keydown.enter)="sendMessage()" placeholder="Type your message..." />
<button (click)="sendMessage()">Send</button>
<button class="reset-btn" (click)="resetChat()">Reset</button>
</div>
</div>
</div>
</div>
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add loading state and error handling

The chatbot UI doesn't show any loading indicators or error messages when interacting with the AI backend. This could lead to a poor user experience if the backend is slow or returns an error.

Add loading and error handling states to the template:

<div class="popup" *ngIf="isPopupVisible">
  <div class="popup-content">
    <button class="close-btn" (click)="togglePopup()">✖</button>
    <h3>Chatbot</h3>
    <div class="chat-window">
      <div class="chat-messages">
        <app-chat-message *ngFor="let message of messages" [message]="message"></app-chat-message>
+       <div *ngIf="isLoading" class="loading-indicator">AI is thinking...</div>
+       <div *ngIf="errorMessage" class="error-message">{{errorMessage}}</div>
      </div>
      <div class="input-container">
-       <input type="text" [(ngModel)]="userInput" (keydown.enter)="sendMessage()" placeholder="Type your message..." />
+       <input type="text" [(ngModel)]="userInput" (keydown.enter)="sendMessage()" placeholder="Type your message..." [disabled]="isLoading" />
-       <button (click)="sendMessage()">Send</button>
+       <button (click)="sendMessage()" [disabled]="isLoading || !userInput.trim()">Send</button>
        <button class="reset-btn" (click)="resetChat()">Reset</button>
      </div>
    </div>
  </div>
</div>
📝 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
<button class="float" (click)="togglePopup()">
<img src="../assets/img/chatbot-icon.svg" alt="Ai Chat" />
</button>
<div class="popup" *ngIf="isPopupVisible">
<div class="popup-content">
<button class="close-btn" (click)="togglePopup()"></button>
<h3>Chatbot</h3>
<div class="chat-window">
<div class="chat-messages">
<app-chat-message *ngFor="let message of messages" [message]="message"></app-chat-message>
</div>
<div class="input-container">
<input type="text" [(ngModel)]="userInput" (keydown.enter)="sendMessage()" placeholder="Type your message..." />
<button (click)="sendMessage()">Send</button>
<button class="reset-btn" (click)="resetChat()">Reset</button>
</div>
</div>
</div>
</div>
<button class="float" (click)="togglePopup()">
<img src="../assets/img/chatbot-icon.svg" alt="Ai Chat" />
</button>
<div class="popup" *ngIf="isPopupVisible">
<div class="popup-content">
<button class="close-btn" (click)="togglePopup()"></button>
<h3>Chatbot</h3>
<div class="chat-window">
<div class="chat-messages">
<app-chat-message *ngFor="let message of messages" [message]="message"></app-chat-message>
<div *ngIf="isLoading" class="loading-indicator">AI is thinking...</div>
<div *ngIf="errorMessage" class="error-message">{{errorMessage}}</div>
</div>
<div class="input-container">
<input
type="text"
[(ngModel)]="userInput"
(keydown.enter)="sendMessage()"
placeholder="Type your message..."
[disabled]="isLoading"
/>
<button (click)="sendMessage()" [disabled]="isLoading || !userInput.trim()">Send</button>
<button class="reset-btn" (click)="resetChat()">Reset</button>
</div>
</div>
</div>
</div>

Comment on lines +26 to +36
this.http.post('/api/ai', { text: this.userInput }).subscribe(
(response: any) => {
// Add AI's response to the chat window
this.messages.push({ sender: 'AI', text: "sample answer" });
},
(error) => {
// Handle error response
this.messages.push({ sender: 'AI', text: 'Error communicating with AI' });
console.error('Error communicating with AI:', error);
}
);
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix hardcoded AI response and add SSE streaming support

The current implementation doesn't use the actual API response and lacks support for SSE streaming mentioned in the PR description. This is likely causing the frontend display issue mentioned in the PR comments.

       // Send the message to the AI backend
-      this.http.post('/api/ai', { text: this.userInput }).subscribe(
-        (response: any) => {
-          // Add AI's response to the chat window
-          this.messages.push({ sender: 'AI', text: "sample answer" });
-        },
-        (error) => {
-          // Handle error response
-          this.messages.push({ sender: 'AI', text: 'Error communicating with AI' });
-          console.error('Error communicating with AI:', error);
-        }
-      );
+      // Add a placeholder response initially
+      const responseIndex = this.messages.length;
+      this.messages.push({ sender: 'AI', text: 'Thinking...' });
+      
+      // Setup EventSource for SSE streaming
+      const source = new EventSource(`/api/ai/stream?query=${encodeURIComponent(this.userInput)}`);
+      
+      let responseText = '';
+      
+      source.onmessage = (event) => {
+        try {
+          const data = JSON.parse(event.data);
+          if (data.text) {
+            responseText += data.text;
+            // Update the ongoing response
+            this.messages[responseIndex] = { sender: 'AI', text: responseText };
+          }
+        } catch (e) {
+          console.error('Error parsing SSE data:', e);
+        }
+      };
+      
+      source.onerror = (error) => {
+        console.error('SSE Error:', error);
+        // If responseText is empty, show error message, otherwise keep what we received
+        if (!responseText) {
+          this.messages[responseIndex] = { sender: 'AI', text: 'Error communicating with AI' };
+        }
+        source.close();
+      };
+      
+      source.addEventListener('end', () => {
+        source.close();
+      });
📝 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
this.http.post('/api/ai', { text: this.userInput }).subscribe(
(response: any) => {
// Add AI's response to the chat window
this.messages.push({ sender: 'AI', text: "sample answer" });
},
(error) => {
// Handle error response
this.messages.push({ sender: 'AI', text: 'Error communicating with AI' });
console.error('Error communicating with AI:', error);
}
);
// Send the message to the AI backend
// Add a placeholder response initially
const responseIndex = this.messages.length;
this.messages.push({ sender: 'AI', text: 'Thinking...' });
// Setup EventSource for SSE streaming
const source = new EventSource(
`/api/ai/stream?query=${encodeURIComponent(this.userInput)}`
);
let responseText = '';
source.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
if (data.text) {
responseText += data.text;
// Update the ongoing response
this.messages[responseIndex] = { sender: 'AI', text: responseText };
}
} catch (e) {
console.error('Error parsing SSE data:', e);
}
};
source.onerror = (error) => {
console.error('SSE Error:', error);
// If nothing has come through yet, show an error message
if (!responseText) {
this.messages[responseIndex] = {
sender: 'AI',
text: 'Error communicating with AI'
};
}
source.close();
};
// Close the connection when the server signals end-of-stream
source.addEventListener('end', () => {
source.close();
});

Comment on lines +1 to +9
.float {
position: fixed;
bottom: 2rem;
right: 2rem;
border: none;
background: transparent;
padding: 0;
cursor: pointer;
}
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add accessibility attributes to the chat button

Improve accessibility by adding appropriate ARIA attributes to the floating chat button.

This will help screen readers identify the purpose of the button. Update the HTML template to include these attributes:

<button class="float" aria-label="Open chat assistant" title="Chat with AI assistant">
  <img src="path-to-chat-icon.png" alt="Chat icon">
</button>

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.

[Task] Make a page to support sse stream return at the back end
7 participants