I wish for a user to interact with a chat window and to receive responses from backed(as a bot), all of which is recorded under a session, But a new session seems to be created every time instead of the current one persisting.
I have tried a lot of things, even creating a bare bones version of the project just to attempt session management but I have consistently failed.
At the beggining I assumed it had to do with my models i created, I created my own session object with a one to many relationship where one session may have many chatMessages
class Session(models.Model):
session_id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable = False)
start_time = models.DateTimeField(default=timezone.now)
end_time = models.DateTimeField(null=True, blank=True) # inititalized empty originally
session_length = models.DurationField(null= True, blank=True)
#each message by bot and user is recorded in the chatmessages model linked to an instance of their unique session
# that was created
class chatMessages(models.Model):
session = models.ForeignKey(Session, on_delete=models.CASCADE, related_name='messages')
role = models.CharField(max_length=50)
content= models.TextField()
timestamp = models.DateTimeField(default=timezone.now)
I later on decided to change the session_id to match the Django made middle ware one, wondering if the discrepancy between the two was causing an issue.
In my view this is how I called it
def chat(request):
try:
# Ensure a Django session exists
if not request.session.session_key:
request.session.save()
session_id = request.session.session_key
session, created = Session.objects.get_or_create(
session_id=session_id,
defaults={'start_time': timezone.now()}
)
This would just check if a Django sessionid exists, if it does exist it simply gets that existing session.
My temporary “frontend” I believe was behaving correctly too
function displayMessage(message, isUser) {
const chatWindow = document.getElementById('chat-window');
const messageBubble = document.createElement('div');
messageBubble.className = isUser ? 'bubble user' : 'bubble response';
messageBubble.textContent = message;
chatWindow.appendChild(messageBubble);
chatWindow.scrollTop = chatWindow.scrollHeight;
}
// Function to load chat history
async function loadChatHistory() {
const chatWindow = document.getElementById('chat-window');
chatWindow.innerHTML = ''; // Clear existing messages
try {
const response = await fetch('http://127.0.0.1:8000/chat/', {
method: 'GET',
headers: {
'X-CSRFToken': getCookie('csrftoken'),
},
credentials: 'include'
});
if (response.ok) {
const data = await response.json();
data.chat_history.forEach(message => {
displayMessage(message.content, message.role === 'user');
});
} else {
console.error('Error loading chat history:', response.statusText);
}
} catch (error) {
console.error('Error loading chat history:', error);
}
}
So again, summarizing my issue. I wish to have a chatwindow where a user sends an input, that input is appended as a bubble to the window, that input is sent to the backend and the backend sends a response that is also appended to the window. Simple enough, the hard part is is that I wish to manage these sessions and record them, my attempts at adding session management always make it so the bubbles disappear(only when session management is in place) and every input is considered a single session. A new session is being created with every message.
I have tried changing my Session model session_id from a uuid one to simply use the django one that’s provided. I have tried Going without a sessionid, passing sessionid as a header into the backend, recreating the project from scratch to attempt a miniature version of session management. Youtube videos, AI, you name it.
I am at a loss as to what to do. I would greatly appreciate not only assistance but if anyone has code or could replicate a simple chat window with response from user and predetermined messages from backend with proper session management, I would love to take a look at it and try and reverse engineer it.