deep-chat icon indicating copy to clipboard operation
deep-chat copied to clipboard

Deep Chat connected to a WebSocket server as a stream ,but disconnected after transferring some characters

Open liang9886703 opened this issue 9 months ago • 1 comments

My English is poor.

I'm using Deep Chat connected to a WebSocket server as a stream, but the two are disconnected after transferring some characters. My frontend framework is vue, using a deep stream connection to my own server,as follows:

.vue

  connect='{
    "url": " http://192.168.1.10:5000/stream",
    "method": "POST",
    "headers": {"Content-Type": "application/json"},
    "stream": "true"
  }'

The server-side code will use falsh, The python code comes from .

The browser shows an error:POST http://192.168.1.10:5000/stream net::ERR_INCOMPLETE_CHUNKED_ENCODING 200 (OK)

I made some attempts and I found, In the send_stream function ,if Recursive generator functions is canceledand and all the characters are sent at once, there will be no error:

def send_stream(self, response_chunks):
     yield f"data: {json.dumps({'text': f'{response_chunks} '})}\n\n"

Below is the complete server code

def chat_stream(self, body):
    # Text messages are stored inside request body using the Deep Chat JSON format:
    # https://deepchat.dev/docs/connect
    print(body)
    response_chunks = "This is a response from a Flask server. Thank you for your message!".split(
        " ")
    response = Response(self.send_stream2(response_chunks), mimetype="text/event-stream")
    response.headers["Content-Type"] = "text/event-stream"
    response.headers["Cache-Control"] = "no-cache"
    response.headers["Connection"] = "keep-alive"
    response.headers["Access-Control-Allow-Origin"] = "*"
    return response

def send_stream(self, response_chunks, chunk_index=0):
    if chunk_index < len(response_chunks):
        chunk = response_chunks[chunk_index]
        yield f"data: {json.dumps({'text': f'{chunk} '})}\n\n"
        time.sleep(0.07)
        yield from self.send_stream(response_chunks, chunk_index + 1)
    else:
        yield ""


@app.route('/stream', methods=['POST'])
def stream_route():
    return custom.chat_stream(req_data)

if __name__ == '__main__':
    # 监听所有地址,方便外部访问;debug模式仅用于开发环境
    app.run(host='0.0.0.0', port=5000, debug=True)

thanks @OvidijusParsiunas

liang9886703 avatar Feb 20 '25 16:02 liang9886703