Skip to content

Commit

Permalink
every route works on frontend
Browse files Browse the repository at this point in the history
  • Loading branch information
dhrumilp12 committed Jun 10, 2024
1 parent f5c9f07 commit 9469b33
Show file tree
Hide file tree
Showing 5 changed files with 177 additions and 18 deletions.
2 changes: 2 additions & 0 deletions client/src/App.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import AuthComponent from './Components/authComponent';
import UserProfile from './Components/userProfile';
import Sidebar from './Components/sideBar';
import Navbar from './Components/navBar';
import ChatInterface from './Components/chatInterface';
import MoodLogging from './Components/moodLogging';
import MoodLogs from './Components/moodLogs';
import { CssBaseline, Box } from '@mui/material';
Expand All @@ -21,6 +22,7 @@ function App() {
<Layout>
<Routes>
<Route path="/" element={<ChatComponent />} />
<Route path="/chat" element={<ChatInterface />} />
<Route path="/auth" element={<AuthComponent />} />
<Route path="/user/profile/:userId" element={<UserProfile />} />
<Route path="/user/mood_logging" element={<MoodLogging />} />
Expand Down
106 changes: 95 additions & 11 deletions client/src/Components/chatComponent.jsx
Original file line number Diff line number Diff line change
@@ -1,45 +1,129 @@
import React, { useState, useEffect, useContext } from 'react';
import React, { useState, useEffect, useContext,useCallback } from 'react';
import axios from 'axios';
import { UserContext } from './userContext';


const ChatComponent = () => {
const { user } = useContext(UserContext);
const userId = user?.userId;
const userId = user?.userId;
const [chatId, setChatId] = useState(null);
const [turnId, setTurnId] = useState(0);
const [input, setInput] = useState('');
const [messages, setMessages] = useState([]);
const [isLoading, setIsLoading] = useState(false);
const [welcomeMessage, setWelcomeMessage] = useState('');
// Fetch initial message when component mounts
useEffect(() => {
if (userId) {
const fetchWelcomeMessage = async () => {
if (!userId) return;
setIsLoading(true);
try {
const response = await fetch(`/api/ai/mental_health/welcome/${userId}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
}
});
const data = await response.json();
console.log(data);
if (response.ok) {
setWelcomeMessage(data.message);
setChatId(data.chat_id);
console.log(data.chat_id);
} else {
console.error('Failed to fetch welcome message:', data);
setWelcomeMessage('Error fetching welcome message.');
}
} catch (error) {
console.error('Network or server error:', error);
}finally {
setIsLoading(false);
}
};
fetchWelcomeMessage();
}, [userId]);

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' }
});

if (userId) {
fetchWelcomeMessage();
}
const data = await response.json();
if (response.ok) {
console.log('Chat finalized successfully:', data.message);
} else {
console.error('Failed to finalize chat:', data.error);
}
}, [userId]);
} catch (error) {
console.error('Error finalizing chat:', error);
} finally {
setIsLoading(false);
}
}, [userId, chatId]);


const sendMessage = useCallback(async () => {
if (!input.trim() || chatId === undefined) 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);
}, []);

return (
<div>
<h1>Welcome to Mental Health Companion</h1>
<p>{welcomeMessage}</p>
<div className="chat-container">
{messages.map((msg, index) => (
<div key={index} className={`message ${msg.sender}`}>
{msg.message}
</div>
))}
</div>
);
}

<input
type="text"
value={input}
onChange={handleInputChange}
placeholder="Type your message here..."
disabled={isLoading}
/>
<button onClick={sendMessage}disabled={isLoading || !input.trim()}>Send</button>
<button onClick={finalizeChat} disabled={isLoading}>End Chat</button>
</div>
);
}

export default ChatComponent;
63 changes: 63 additions & 0 deletions client/src/Components/chatInterface.jsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import React, { useState, useContext, useCallback } from 'react';
import { UserContext } from './userContext';

const ChatInterface = () => {
const { user } = useContext(UserContext);
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 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();

if (response.ok) {
setMessages([...messages, { message: input, sender: 'user' }, { message: data.message, sender: 'agent' }]);
setTurnId(prev => prev + 1);
setInput('');
} else {
console.error('Failed to send message:', data);
}
};

// Handle input changes
const handleInputChange = useCallback((event) => {
setInput(event.target.value);
}, []);

return (
<div>
<h1>Welcome to Mental Health Companion</h1>
<div className="chat-container">
{messages.map((msg, index) => (
<div key={index} className={`message ${msg.sender}`}>
{msg.message}
</div>
))}
</div>
<input
type="text"
value={input}
onChange={handleInputChange}
placeholder="Type your message here..."
/>
<button onClick={sendMessage}>Send</button>
</div>
);
}

export default ChatInterface;
20 changes: 15 additions & 5 deletions server/routes/ai.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import os
from datetime import datetime
import logging

from flask import jsonify
from flask import Blueprint, request
from werkzeug.exceptions import InternalServerError

Expand Down Expand Up @@ -89,10 +89,20 @@ def run_mental_health_agent(user_id, chat_id):
timestamp,
ChatHistoryScope.ALL)

return response
return jsonify(response), 200


@ai_routes.post("/ai/mental_health/finalize/<user_id>/<chat_id>")
def set_mental_health_end_state(user_id):
# Here, it gets the initial state of the app
pass
def set_mental_health_end_state(user_id, chat_id):
# Simulate some logic to handle the end state
try:
# Your logic here, for example:
logger.info(f"Finalizing chat {chat_id} for user {user_id}")

# Potentially update the database or perform other cleanup operations
# For now, let's assume it's a simple response:
return jsonify({"message": "Chat session finalized successfully"}), 200

except Exception as e:
logger.error(f"Error during finalizing chat: {e}")
return jsonify({"error": "Failed to finalize chat"}), 500
4 changes: 2 additions & 2 deletions server/tools/langchain.py
Original file line number Diff line number Diff line change
Expand Up @@ -235,11 +235,11 @@ def get_chat_history(user_id, chat_id, history_scope:ChatHistoryScope):

turns = []
if history_scope == ChatHistoryScope.ALL:
turns = list(collection.find({"user_id": user_id}).sort({"timestamp": -1}))
turns = list(collection.find({"user_id": user_id}).sort({"timestamp": -1}).limit(5))
elif history_scope == ChatHistoryScope.PREVIOUS:
turns = list(collection.find({"user_id": user_id, "chat_id": (chat_id - 1)}).sort({"timestamp": -1}))
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 9469b33

Please sign in to comment.