from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from django.http import JsonResponse
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
from django.contrib.sessions.models import Session
from .models import ChatSession, ChatMessage
from ethanicbot.langchain.agent import get_agent
@csrf_exempt
def chat_view(request):
"""
Handles the chat functionality of EthanicBot.
This view processes both POST and GET requests for the bot's interaction.
"""
if request.method == "POST":
message = request.POST.get("message")
session_key = request.session.session_key or request.session.save() or request.session.session_key
# Get or create ChatSession for this user
chat_session, _ = ChatSession.objects.get_or_create(session_key=session_key, defaults={
"user": request.user if request.user.is_authenticated else None
})
# Save user message in the database
ChatMessage.objects.create(session=chat_session, is_user=True, message=message)
# Get the bot response using the agent
agent = get_agent()
try:
response = agent.invoke({"input": message})
reply = response["response"]
except Exception as e:
reply = f"Sorry, I encountered an error: {e}"
# Save bot response in the database
ChatMessage.objects.create(session=chat_session, is_user=False, message=reply)
return JsonResponse({"response": reply})
return render(request, "ethanicbot/chat.html")
def ethanicbot_chatbox_partial(request):
"""
Renders the chatbox partial template to be injected dynamically
on every page that includes it.
"""
html = render_to_string("ethanicbot/partials/ethanicbot_chatbox.html", request=request)
return JsonResponse({"html": mark_safe(html)})