Notes
Notes - notes.io |
Django view for handling chatbot dashboard requests.
Streaming-only implementation with secure error handling.
"""
import logging
import os
from django.contrib.auth.decorators import login_required
from django.http import StreamingHttpResponse,JsonResponse
from django.shortcuts import render,get_object_or_404
from django.utils import timezone
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST,require_GET
from dotenv import load_dotenv
from .chat_assistant import stream_chat_assistant
from .constants import ASSISTANT_ROLE, USER_ROLE
from .models import ChatSession, CustomUser, Message
# =====================================
# LOGGER CONFIGURATION
# =====================================
logger = logging.getLogger("crs")
# Load environment variables
load_dotenv()
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
# =====================================
# INTERNAL HELPERS
# =====================================
def _generate_chat_title(text: str) -> str:
"""
Generate chat title from first user message.
"""
if not text:
return "New Chat"
title = text.strip().split("n")[0][:60]
return title if title else "New Chat"
# =====================================
# STREAMING VIEW
# =====================================
# pylint: disable=no-member
@csrf_exempt
@require_POST
@login_required(login_url="login")
def chat_dashboard_stream_view(request):
"""
Handle chatbot streaming requests securely.
Also persists chat session and messages.
"""
try:
if not OPENAI_API_KEY:
logger.error("Missing OpenAI environment configuration.")
return StreamingHttpResponse(
"Something went wrong. Please try again later.",
status=500,
content_type="text/plain",
)
user = request.user
user_input = request.POST.get("message")
image_file = request.FILES.get("image")
chat_session_id = request.POST.get("chat_session_id")
# chat_session_id = 14 # for testing
if not user_input and not image_file:
return StreamingHttpResponse(
"Something went wrong. Please try again later.",
status=400,
content_type="text/plain",
)
# =====================================
# CHAT SESSION RESOLUTION
# =====================================
chat_session = None
if chat_session_id:
try:
chat_session = ChatSession.objects.get(
id=chat_session_id,
user=user,
is_deleted=False
)
except ChatSession.DoesNotExist:
chat_session = None
if not chat_session:
chat_session = ChatSession.objects.create(
user=user,
title=_generate_chat_title(user_input),
created_at=timezone.now(),
updated_at=timezone.now(),
last_response_id=None,
)
# =====================================
# LOAD HISTORY
# =====================================
history_qs = Message.objects.filter(
chat_session=chat_session
).order_by("created_at")
history = [
{
"role": msg.role,
"content": msg.content
}
for msg in history_qs
]
# =====================================
# SAVE USER MESSAGE
# =====================================
if user_input:
Message.objects.create(
chat_session=chat_session,
role=USER_ROLE,
content=user_input.strip(),
)
# =====================================
# STREAM GENERATOR
# =====================================
def response_stream():
assistant_chunks = []
response_id = None
try:
generator = stream_chat_assistant(
user_input=user_input or "",
api_key=OPENAI_API_KEY,
image_file=image_file,
history=history,
previous_response_id=chat_session.last_response_id,
)
for chunk in generator:
if isinstance(chunk, dict) and chunk.get("type") == "response_id":
response_id = chunk.get("value")
continue
if chunk:
assistant_chunks.append(chunk)
yield chunk
except Exception: # pylint: disable=broad-exception-caught
logger.exception("Streaming error.")
yield "Something went wrong. Please try again later."
finally:
# =====================================
# ALWAYS SAVE AFTER STREAM
# =====================================
full_response = "".join(assistant_chunks).strip()
if full_response:
Message.objects.create(
chat_session=chat_session,
role=ASSISTANT_ROLE,
content=full_response,
response_id=response_id,
)
# Update session safely
chat_session.updated_at = timezone.now()
# Only update response ID if we received a new valid one
if response_id:
chat_session.last_response_id = response_id
chat_session.save()
# =====================================
# STREAM RESPONSE WITH SESSION HEADER
# =====================================
response = StreamingHttpResponse(
response_stream(),
content_type="text/plain"
)
# Send session ID to frontend via header (production-grade)
response["X-Session-Id"] = str(chat_session.id)
return response
except Exception: # pylint: disable=broad-exception-caught
logger.exception("Unexpected error in chat_dashboard_stream_view.")
return StreamingHttpResponse(
"Something went wrong. Please try again later.",
status=500,
content_type="text/plain",
)
# =====================================
# CHAT PAGE
# =====================================
@login_required(login_url="login")
def chat_dashboard_page(request):
"""
Render the AI chat dashboard page.
Optimized query with safe fallbacks.
"""
# Fetch authenticated user with profile in a single query
user = CustomUser.objects.select_related("profile").get(pk=request.user.pk)
# Build full name and fallback to email if empty
full_name = f"{user.first_name} {user.last_name}".strip()
if not full_name:
full_name = user.email
# Return blank if company is missing
company_name = ""
if hasattr(user, "profile") and user.profile.company:
company_name = user.profile.company
context = {
"full_name": full_name,
"company_name": company_name,
}
return render(request, "crs/chat_dashboard.html", context)
# =====================================
# CHAT HISTORY SIDEBAR API
# =====================================
@require_GET
@login_required(login_url="login")
def chat_history_list_api(request):
"""
Returns all chat sessions for logged-in user and their count .
Used for sidebar listing.
"""
user = request.user
sessions_qs = (
ChatSession.objects
.filter(user=user, is_deleted=False)
.order_by("-updated_at")
)
sessions = sessions_qs.values(
"id",
"title",
"created_at",
"updated_at",
)
return JsonResponse({
"success": True,
"count": sessions_qs.count(),
"data": list(sessions),
})
# =====================================
# CHAT MESSAGE LOAD API
# =====================================
@require_GET
@login_required(login_url="login")
def chat_messages_api(request, session_id):
"""
Returns all messages for a specific chat session.
Used when user clicks a chat title.
"""
user = request.user
chat_session = get_object_or_404(
ChatSession,
id=session_id,
user=user,
is_deleted=False,
)
messages = (
Message.objects
.filter(chat_session=chat_session)
.order_by("created_at")
.values(
"id",
"role",
"content",
"created_at",
)
)
return JsonResponse({
"success": True,
"session": {
"id": chat_session.id,
"title": chat_session.title,
},
"messages": list(messages),
})
# =====================================
# CHAT RENAME API
# =====================================
@require_POST
@login_required(login_url="login")
def chat_rename_api(request, session_id):
"""
Rename chat session title.
"""
user = request.user
new_title = request.POST.get("title", "").strip()
if not new_title:
return JsonResponse(
{"success": False, "error": "Title cannot be empty."},
status=400,
)
try:
chat_session = ChatSession.objects.get(
id=session_id,
user=user,
is_deleted=False,
)
except ChatSession.DoesNotExist:
return JsonResponse(
{"success": False, "error": "Chat session not found."},
status=404,
)
chat_session.title = new_title[:100] # safety limit
chat_session.updated_at = timezone.now()
chat_session.save(update_fields=["title", "updated_at"])
return JsonResponse({
"success": True,
"data": {
"id": chat_session.id,
"title": chat_session.title,
},
})
# =====================================
# CHAT DELETE API
# =====================================
@require_POST
@login_required(login_url="login")
def chat_delete_api(request, session_id):
"""
Soft delete chat session.
"""
user = request.user
try:
chat_session = ChatSession.objects.get(
id=session_id,
user=user,
is_deleted=False,
)
except ChatSession.DoesNotExist:
return JsonResponse(
{"success": False, "error": "Chat session not found."},
status=404,
)
chat_session.is_deleted = True
chat_session.updated_at = timezone.now()
chat_session.save(update_fields=["is_deleted", "updated_at"])
return JsonResponse({
"success": True,
"message": "Chat deleted successfully.",
})
![]() |
Notes is a web-based application for online taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000+ notes created and continuing...
With notes.io;
- * You can take a note from anywhere and any device with internet connection.
- * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
- * You can quickly share your contents without website, blog and e-mail.
- * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
- * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.
Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.
Easy: Notes.io doesn’t require installation. Just write and share note!
Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )
Free: Notes.io works for 14 years and has been free since the day it was started.
You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;
Email: [email protected]
Twitter: http://twitter.com/notesio
Instagram: http://instagram.com/notes.io
Facebook: http://facebook.com/notesio
Regards;
Notes.io Team
