Skip to content

Commit

Permalink
streaming issue test
Browse files Browse the repository at this point in the history
  • Loading branch information
supermandee committed Dec 18, 2024
1 parent 1a43764 commit 67114a8
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 34 deletions.
8 changes: 4 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ Hey there! Meet MySpotiPal - your AI-powered music buddy that knows your Spotify

## What Can MySpotiPal Do? 🌟

## Playlist Management 🚀
## Playlist Generation & Management 🚀
```
"Can you create a playlist of bunker techno?"
"Please remove the song Sunset Lover from my playlist Beach Lounge Vibes"
Expand All @@ -30,13 +30,13 @@ Automatically create playlists and manage them in your Spotify account; this inc
```
MySpotiPal analyzes your listening habits across different timeframes (4 weeks, 6 months, or all time)

### Manage Your Music World 📚
### Manage Your Spotify World 📚
```
"Who do I follow on Spotify?"
"Show me my playlists"
"What podcasts have I saved?"
```
Keep track of your followed artists, playlists, and recent plays
Keep track of your followed artists, playlists, recent plays, saved tracks, podcasts, and audiobooks etc

### Learn About Any Artist, Songs, Playlists, Podcasts & More 🎤
```
Expand All @@ -45,7 +45,7 @@ Keep track of your followed artists, playlists, and recent plays
"Tell me about BTS"
"Did Elon Musk appear on 'The Joe Rogan Experience'?"
```
Get both general info and Spotify stats for any artist!
Get both general info and Spotify stats for any artist, song, audiobook and more!

### Get Music Recommendations 🎵
```
Expand Down
65 changes: 35 additions & 30 deletions static/js/chat.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,27 +16,30 @@ function createThinkingIndicator() {
async function sendMessage() {
const message = userInput.value.trim();
if (!message) return;

// Disable input and button while processing
userInput.disabled = true;
sendButton.disabled = true;

// Display user message
const userMessage = document.createElement('div');
userMessage.className = 'chat-bubble user-message';
userMessage.textContent = message;
chatBox.appendChild(userMessage);

// Clear input
userInput.value = '';
// Create and show thinking indicator in the message flow

// Show thinking indicator
const thinkingIndicator = createThinkingIndicator();
chatBox.appendChild(thinkingIndicator);
chatBox.scrollTop = chatBox.scrollHeight;

let lastContent = ''; // Track last content to avoid duplicates


// Prepare the bot message container (we'll update this as chunks arrive)
const botMessage = document.createElement('div');
botMessage.className = 'chat-bubble bot-message';
chatBox.appendChild(botMessage);

try {
const response = await fetch('/ask', {
method: 'POST',
Expand All @@ -45,54 +48,56 @@ async function sendMessage() {
},
body: `query=${encodeURIComponent(message)}`
});

// Handle 401 Unauthorized
if (response.status === 401) {
const json = await response.json();
thinkingIndicator.innerHTML = `<a href="${json.redirect}">Session expired. Log in again</a>`;
botMessage.innerHTML = `<a href="${json.redirect}">Session expired. Log in again</a>`;
showError(json.error || 'Session expired. Please log in again.');
return;
}

// Handle other non-OK responses
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}

// Create bot message container to replace thinking indicator
const botMessage = document.createElement('div');
botMessage.className = 'chat-bubble bot-message';

// Replace thinking indicator with actual message container
chatBox.replaceChild(botMessage, thinkingIndicator);


const reader = response.body.getReader();
const decoder = new TextDecoder();
let fullMessage = '';

let lastContent = ''; // Track last chunk for incremental updates
let firstChunk = true; // To know when the first actual response arrives

while (true) {
const {done, value} = await reader.read();
if (done) {
console.log("Stream done");
break;
}

const chunk = decoder.decode(value, {stream: true});
console.log("Raw chunk:", chunk);
var cleanChunk = chunk;
if (cleanChunk && cleanChunk !== '[DONE]') {
if (cleanChunk !== lastContent) {
fullMessage += cleanChunk;

if (chunk && chunk !== '[DONE]') {
// Remove thinking indicator once we get the first real chunk
if (firstChunk && thinkingIndicator.parentNode) {
thinkingIndicator.remove();
firstChunk = false;
}

// Incrementally update the displayed content
if (chunk !== lastContent) {
fullMessage += chunk;
botMessage.innerHTML = marked.parse(fullMessage);
lastContent = cleanChunk;
lastContent = chunk;
chatBox.scrollTop = chatBox.scrollHeight; // Auto-scroll to bottom
}
chatBox.scrollTop = chatBox.scrollHeight;
}
}

} catch (error) {
console.error('Error:', error);
// Replace thinking indicator with error message
thinkingIndicator.innerHTML = 'Sorry, there was an error processing your request.';
botMessage.innerHTML = 'Sorry, there was an error processing your request.';
showError('An error occurred while processing your request.');
} finally {
// Re-enable input and button
Expand All @@ -118,4 +123,4 @@ function checkEnter(event) {
event.preventDefault();
sendMessage();
}
}
}

0 comments on commit 67114a8

Please sign in to comment.