diff --git a/client/src/App.jsx b/client/src/App.jsx index 523c3f83..9caa45e9 100644 --- a/client/src/App.jsx +++ b/client/src/App.jsx @@ -1,4 +1,4 @@ -import React, { useState,useEffect } from 'react'; +import React, { useState,useEffect, useContext } from 'react'; import { UserProvider } from './Components/userContext'; import { BrowserRouter as Router, Routes, Route, useLocation } from 'react-router-dom'; import ChatComponent from './Components/chatComponent'; // Ensure this path is correct @@ -10,18 +10,21 @@ import ChatInterface from './Components/chatInterface'; import MoodLogging from './Components/moodLogging'; import MoodLogs from './Components/moodLogs'; import { CssBaseline, Box } from '@mui/material'; +import { UserContext } from './Components/userContext'; function App() { + const { user } = useContext(UserContext); + useEffect(() => { document.body.style.backgroundColor = '#f5f5f5'; }, []); return ( - + - } /> + :} /> } /> } /> } /> @@ -29,11 +32,12 @@ function App() { } /> - + ); } function Layout({ children }) { + const { user } = useContext(UserContext); const location = useLocation(); const noNavRoutes = ['/auth']; // List of routes that shouldn't show the navbar or sidebar const showNav = !noNavRoutes.includes(location.pathname); diff --git a/client/src/Components/chatInterface.jsx b/client/src/Components/chatInterface.jsx index f8e6add3..af306cfb 100644 --- a/client/src/Components/chatInterface.jsx +++ b/client/src/Components/chatInterface.jsx @@ -1,63 +1,244 @@ -import React, { useState, useContext, useCallback } from 'react'; +import React, { useState, useContext,useCallback } from 'react'; +import axios from 'axios'; +import { Box, Card, CardContent, Typography, TextField, Button, List, ListItem, ListItemText, CircularProgress, Snackbar, Divider } from '@mui/material'; +import MuiAlert from '@mui/material/Alert'; +import SendIcon from '@mui/icons-material/Send'; +import ExitToAppIcon from '@mui/icons-material/ExitToApp'; +import PersonIcon from '@mui/icons-material/Person'; import { UserContext } from './userContext'; +import Aria from '../Assets/Images/Aria.jpg'; // Adjust the path to where your logo is stored +import { Avatar } from '@mui/material'; -const ChatInterface = () => { + + +const ChatComponent = () => { const { user } = useContext(UserContext); - const userId = user?.userId; + const userId = user?.userId; const [chatId, setChatId] = useState(0); const [turnId, setTurnId] = useState(0); const [input, setInput] = useState(''); const [messages, setMessages] = useState([]); - const sendMessage = async () => { - if (!input.trim()) return; + const [isLoading, setIsLoading] = useState(false); + const [open, setOpen] = useState(false); + const [snackbarMessage, setSnackbarMessage] = useState(''); + const [snackbarSeverity, setSnackbarSeverity] = useState('info'); - const body = JSON.stringify({ - prompt: input, - turn_id: turnId - }); - const response = await fetch(`/api/ai/mental_health/${userId}/${chatId}`, { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: body - }); - - const data = await response.json(); + const handleSnackbarClose = (event, reason) => { + if (reason === 'clickaway') { + return; + } + setOpen(false); + }; + const finalizeChat = useCallback(async () => { + if (chatId === null) return; + setIsLoading(true); + try { + const response = await fetch(`/api/ai/mental_health/finalize/${userId}/${chatId}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' } + }); + + const data = await response.json(); if (response.ok) { - setMessages([...messages, { message: input, sender: 'user' }, { message: data.message, sender: 'agent' }]); - setTurnId(prev => prev + 1); - setInput(''); + setSnackbarMessage('Chat finalized successfully'); + setSnackbarSeverity('success'); + // Reset chat state to start a new chat + setChatId(null); + setTurnId(0); + setMessages([]); + // Optionally, fetch a new welcome message or reset other relevant states + } else { - console.error('Failed to send message:', data); + setSnackbarMessage('Failed to finalize chat'); + setSnackbarSeverity('error'); } - }; - - // Handle input changes - const handleInputChange = useCallback((event) => { - setInput(event.target.value); - }, []); - - return ( -
-

Welcome to Mental Health Companion

-
- {messages.map((msg, index) => ( -
- {msg.message} -
- ))} -
- - -
- ); -} + } catch (error) { + setSnackbarMessage('Error finalizing chat'); + setSnackbarSeverity('error'); + } finally { + setIsLoading(false); + setOpen(true); + } +}, [userId, chatId]); + + const sendMessage = useCallback(async () => { + if (!input.trim()) return; + console.log(chatId); + setIsLoading(true); + + + try { + const body = JSON.stringify({ + prompt: input, + turn_id: turnId + }); + const response = await fetch(`/api/ai/mental_health/${userId}/${chatId}`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: body + }); + + const data = await response.json(); + console.log(data); + if (response.ok) { + setMessages(prev => [...prev, { message: input, sender: 'user' }, { message: data, sender: 'agent' }]); + setTurnId(prev => prev + 1); + setInput(''); + } else { + console.error('Failed to send message:', data); + } + }catch (error) { + console.error('Failed to send message:', error); + } finally { + setIsLoading(false); + + } + }, [input, userId, chatId, turnId]); + + // Handle input changes + const handleInputChange = useCallback((event) => { + setInput(event.target.value); + }, []); -export default ChatInterface; + return ( + <> + + + + + {messages.length === 0 && ( + + App Logo + + + )} + + + + Welcome to Mental Health Companion + + + + + + {messages.map((msg, index) => ( + + + + {msg.sender === 'agent' && ( + + )} + + + + {msg.sender === 'user' && ( + + + + )} + + + ))} + + + + + + {isLoading ? : ( + + )} + + + + + + {snackbarMessage} + + + + + ); + }; + + +export default ChatComponent; diff --git a/client/src/Components/userContext.jsx b/client/src/Components/userContext.jsx index bdcd6300..132d584f 100644 --- a/client/src/Components/userContext.jsx +++ b/client/src/Components/userContext.jsx @@ -1,7 +1,7 @@ import React, { createContext, useState, useCallback } from 'react'; import axios from 'axios'; import { useNavigate } from 'react-router-dom'; -export const UserContext = createContext(null); +export const UserContext = createContext({ user: null }); export const UserProvider = ({ children }) => { const [user, setUser] = useState(null); diff --git a/client/src/Components/userProfile.jsx b/client/src/Components/userProfile.jsx index 6d2b4ec6..f94fac39 100644 --- a/client/src/Components/userProfile.jsx +++ b/client/src/Components/userProfile.jsx @@ -57,7 +57,7 @@ const theme = createTheme({ }); const StyledForm = styled(Paper)(({ theme }) => ({ - marginTop: theme.spacing(10), + marginTop: theme.spacing(4), padding: theme.spacing(4), display: 'flex', flexDirection: 'column', diff --git a/client/src/main.jsx b/client/src/main.jsx index 27fae8b1..87d1310e 100644 --- a/client/src/main.jsx +++ b/client/src/main.jsx @@ -2,11 +2,14 @@ import React from 'react' import ReactDOM from 'react-dom/client' import App from './App.jsx' import { BrowserRouter } from 'react-router-dom'; +import { UserProvider } from './Components/userContext'; ReactDOM.createRoot(document.getElementById('root')).render( + + , ) \ No newline at end of file diff --git a/server/routes/ai.py b/server/routes/ai.py index 00b3a5cd..7705bbc9 100644 --- a/server/routes/ai.py +++ b/server/routes/ai.py @@ -72,7 +72,9 @@ def get_mental_health_agent_welcome(user_id): def run_mental_health_agent(user_id, chat_id): ENV = os.environ.get("FLASK_ENV") body = request.get_json() - + if not body: + return jsonify({"error": "No data provided"}), 400 + prompt = body.get("prompt") turn_id = body.get("turn_id") @@ -98,19 +100,20 @@ def run_mental_health_agent(user_id, chat_id): """ timestamp = datetime.now().isoformat() - - response = get_langchain_agent_response(f"mental-health-{ENV}", - "chatbot_logs", - system_message, - prompt, - user_id, - int(chat_id), - turn_id + 1, - timestamp, - ChatHistoryScope.ALL) - - return jsonify(response), 200 - + try: + response = get_langchain_agent_response(f"mental-health-{ENV}", + "chatbot_logs", + system_message, + prompt, + user_id, + int(chat_id), + turn_id + 1, + timestamp, + ChatHistoryScope.ALL) + + return jsonify(response), 200 + except Exception as e: + return jsonify({"error": str(e)}), 500 @ai_routes.post("/ai/mental_health/finalize//") def set_mental_health_end_state(user_id, chat_id):