Iodine98 / dora-back

A Python backend for Document Retrieval and Analysis (DoRA).
MIT License
0 stars 1 forks source link

Create Websocket endpoints #62

Open Iodine98 opened 1 month ago

Iodine98 commented 1 month ago

Replicate the Flask app in app.py, but with Websocket endpoints. To achieve this, perform the following steps:

Duplicate app.py but rewrite with Websockets

The original code:

https://github.com/Iodine98/dora-back/blob/ef44bc69930edc6f91497e55163afde73ecd0590/app.py#L360-L376

New example code:

from flask import Flask, request
from flask_socketio import SocketIO, emit
import uuid

@socketio.on('prompt')
def handle_prompt(data):
    """Handles the prompt request from the client via WebSocket."""
    try:
        session_id = str(data["sessionId"])
        message = str(data["prompt"])

        # Validate the sessionId is a UUID
        try:
            uuid_obj = uuid.UUID(session_id, version=4)
            if str(uuid_obj) != session_id:
                raise ValueError("Invalid sessionId format")
        except ValueError:
            emit('response', {"error": "Invalid sessionId format"})
            return

        chatbot = Chatbot(user_id=session_id)
        prompt_response = PromptResponse(
            message="Prompt result is found under the result key.",
            error="",
            result=chatbot.send_prompt(message)
        )
        emit('response', prompt_response.to_dict())
    except KeyError as e:
        emit('response', {"error": f"Missing key: {str(e)}"})
    except Exception as e:
        emit('response', {"error": str(e)})

Add uvicorn as a service to Dockerfile

Original line: https://github.com/Iodine98/dora-back/blob/ef44bc69930edc6f91497e55163afde73ecd0590/Dockerfile#L105 Add following line:

uvicorn app:app --host 0.0.0.0 --port 8000

Test function