Skip to content

Commit

Permalink
welcome frontend
Browse files Browse the repository at this point in the history
  • Loading branch information
dhrumilp12 committed Jun 9, 2024
1 parent d81d37b commit f7d23ff
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 62 deletions.
6 changes: 6 additions & 0 deletions client/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"@mui/material": "^5.15.19",
"axios": "^1.7.2",
"jwt-decode": "^4.0.0",
"lodash": "^4.17.21",
"react": "^18.3.1",
"react-dom": "^18.2.0",
"react-redux": "^9.1.2",
Expand Down
88 changes: 28 additions & 60 deletions client/src/Components/chatComponent.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,76 +2,44 @@ import React, { useState, useEffect, useContext } from 'react';
import axios from 'axios';
import { UserContext } from './userContext';


const ChatComponent = () => {
const { user } = useContext(UserContext);
const userId = user?.userId;
const [chatId, setChatId] = useState(null);
const [messages, setMessages] = useState([]);
const [inputText, setInputText] = useState('');
const [turnId, setTurnId] = useState(0);
const userId = user?.userId;
const [welcomeMessage, setWelcomeMessage] = useState('');
// Fetch initial message when component mounts
useEffect(() => {
if (userId) {
axios.post(`/api/ai/mental_health/welcome/${userId}`)
.then(response => {
const initialMessage = response.data.message;
setMessages(prevMessages => [...prevMessages, { sender: 'AI', text: initialMessage }]);
console.log('Data:', response.data);
setChatId(response.data.chatId);
})
.catch(error => {
console.error('Error fetching initial message:', error);
setMessages(prevMessages => [...prevMessages, { sender: 'AI', text: "Sorry, there was a problem starting the chat. Please try again later." }]);
const fetchWelcomeMessage = async () => {
const response = await fetch(`/api/ai/mental_health/welcome/${userId}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
}
}, [userId]);


const sendMessage = () => {
if (!userId || !chatId) {
console.error("User ID or Chat ID is undefined.");
return;
}
const data = await response.json();
if (response.ok) {
setWelcomeMessage(data.message);
} else {
console.error('Failed to fetch welcome message:', data);
setWelcomeMessage('Error fetching welcome message.');
}
};

if (inputText.trim()) {
console.log("Sending message with UserID:", userId, " and ChatID:", chatId, " and TurnID:", turnId);
axios.post(`/api/ai/mental_health/${userId}/${chatId}`, { prompt: inputText })
.then(response => {
const aiMessage = response.data.message;
setMessages(prevMessages => [...prevMessages, { sender: 'User', text: inputText }, { sender: 'AI', text: aiMessage }]);
setInputText('');
setTurnId(prevTurnId => prevTurnId + 1); // Increment turnId for the next message
})
.catch(error => console.error('Error sending message:', error));
if (userId) {
fetchWelcomeMessage();
}
}
};

const handleFinalizeChat = () => {
if (!userId || !chatId) {
console.error("User ID or Chat ID is undefined.");
return;
}

axios.post(`/api/ai/mental_health/finalize/${userId}/${chatId}`)
.then(() => console.log('Chat finalized successfully'))
.catch(error => console.error('Error finalizing chat:', error));
};
}, [userId]);


return (
<div>
<div className="chat-box">
{messages.map((message, index) => (
<p key={index} className={message.sender === 'AI' ? 'ai-message' : 'user-message'}>
{message.text}
</p>
))}

return (
<div>
<h1>Welcome to Mental Health Companion</h1>
<p>{welcomeMessage}</p>
</div>
<input type="text" value={inputText} onChange={e => setInputText(e.target.value)} />
<button onClick={sendMessage}>Send</button>
<button onClick={handleFinalizeChat}>End Chat</button>
</div>
);
};
);
}

export default ChatComponent;
4 changes: 2 additions & 2 deletions server/tools/langchain.py
Original file line number Diff line number Diff line change
Expand Up @@ -237,9 +237,9 @@ def get_chat_history(user_id, chat_id, history_scope:ChatHistoryScope):
if history_scope == ChatHistoryScope.ALL:
turns = list(collection.find({"user_id": user_id}).sort({"timestamp": -1}))
elif history_scope == ChatHistoryScope.PREVIOUS:
turns = list(collection.find({"user_id": user_id, "chat_id": (chat_id - 1)}).sort({"timestamp": -1}))
turns = list(collection.find({"user_id": user_id, "chat_id": (chat_id - 1)}).sort({"timestamp": -1}).limit(5))
elif history_scope == ChatHistoryScope.CURRENT:
turns = list(collection.find({"user_id": user_id, "chat_id": chat_id}).sort({"timestamp": -1}))
turns = list(collection.find({"user_id": user_id, "chat_id": chat_id}).sort({"timestamp": -1}).limit(5))

turns.reverse()
history_list = []
Expand Down

0 comments on commit f7d23ff

Please sign in to comment.