2026-02-27 19:44:49 +03:30
|
|
|
"""
|
|
|
|
|
ویوهای RAG — چت با استریم
|
|
|
|
|
"""
|
|
|
|
|
from django.http import StreamingHttpResponse
|
|
|
|
|
from rest_framework import status
|
|
|
|
|
from rest_framework.request import Request
|
|
|
|
|
from rest_framework.response import Response
|
|
|
|
|
from rest_framework.views import APIView
|
|
|
|
|
|
|
|
|
|
from .chat import chat_rag_stream
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
class ChatView(APIView):
|
|
|
|
|
"""
|
|
|
|
|
چت RAG با استریم.
|
2026-02-27 20:06:46 +03:30
|
|
|
POST با {"message": "متن سوال", "sensor_uuid": "uuid-سنسور"}
|
|
|
|
|
sensor_uuid اجباری — هر کاربر فقط به دیتای خودش دسترسی دارد.
|
2026-02-27 19:44:49 +03:30
|
|
|
"""
|
|
|
|
|
|
|
|
|
|
def post(self, request: Request):
|
2026-02-27 20:06:46 +03:30
|
|
|
data = request.data if request.method == "POST" else request.query_params
|
|
|
|
|
message = data.get("message")
|
|
|
|
|
sensor_uuid = data.get("sensor_uuid")
|
|
|
|
|
|
2026-02-27 19:44:49 +03:30
|
|
|
if not message or not isinstance(message, str):
|
|
|
|
|
return Response(
|
|
|
|
|
{"code": 400, "msg": "پارامتر message الزامی است."},
|
|
|
|
|
status=status.HTTP_400_BAD_REQUEST,
|
|
|
|
|
)
|
|
|
|
|
message = str(message).strip()
|
|
|
|
|
if not message:
|
|
|
|
|
return Response(
|
|
|
|
|
{"code": 400, "msg": "پیام نباید خالی باشد."},
|
|
|
|
|
status=status.HTTP_400_BAD_REQUEST,
|
|
|
|
|
)
|
2026-02-27 20:06:46 +03:30
|
|
|
if not sensor_uuid or not isinstance(sensor_uuid, str):
|
|
|
|
|
return Response(
|
|
|
|
|
{"code": 400, "msg": "پارامتر sensor_uuid الزامی است."},
|
|
|
|
|
status=status.HTTP_400_BAD_REQUEST,
|
|
|
|
|
)
|
|
|
|
|
sensor_uuid = str(sensor_uuid).strip()
|
|
|
|
|
if not sensor_uuid:
|
|
|
|
|
return Response(
|
|
|
|
|
{"code": 400, "msg": "sensor_uuid نباید خالی باشد."},
|
|
|
|
|
status=status.HTTP_400_BAD_REQUEST,
|
|
|
|
|
)
|
2026-02-27 19:44:49 +03:30
|
|
|
|
|
|
|
|
def generate():
|
|
|
|
|
try:
|
2026-02-27 20:06:46 +03:30
|
|
|
for chunk in chat_rag_stream(message, sensor_uuid=sensor_uuid):
|
2026-02-27 19:44:49 +03:30
|
|
|
yield chunk
|
|
|
|
|
except Exception as e:
|
|
|
|
|
yield f"\n[خطا: {e}]"
|
|
|
|
|
|
|
|
|
|
return StreamingHttpResponse(
|
|
|
|
|
generate(),
|
|
|
|
|
content_type="text/plain; charset=utf-8",
|
|
|
|
|
)
|