44 lines
1.7 KiB
Python
44 lines
1.7 KiB
Python
"""HTTP adapters for chat; business logic lives in services."""
|
|
|
|
from flask import Blueprint, Response, request, stream_with_context
|
|
|
|
from .. import business_service, chat_service
|
|
|
|
bp = Blueprint('chat', __name__)
|
|
|
|
@bp.route('/stream_chat', methods=['GET', 'POST'])
|
|
def stream_chat():
|
|
def error(message):
|
|
return Response(chat_service.sse({'e':message}) + chat_service.sse({'d':1}), mimetype='text/event-stream')
|
|
|
|
if request.method == 'POST':
|
|
data = request.get_json(silent=True)
|
|
if not isinstance(data, dict):
|
|
return error('请求格式无效,请重新发送问题。')
|
|
msg = data.get('msg', '')
|
|
conv_id = data.get('conv_id')
|
|
else:
|
|
msg = request.args.get('msg', '')
|
|
conv_id = request.args.get('conv_id')
|
|
if not isinstance(msg, str):
|
|
return error('问题必须是文本,请重新输入。')
|
|
msg = msg.strip()
|
|
if isinstance(conv_id, (bool, float)):
|
|
return error('会话编号无效,请新建对话后重试。')
|
|
if conv_id not in (None, '', 0):
|
|
if not isinstance(conv_id, (str, int)) or not str(conv_id).isdigit():
|
|
return error('会话编号无效,请新建对话后重试。')
|
|
conv_id = int(conv_id)
|
|
if not 0 < conv_id <= 9223372036854775807:
|
|
return error('会话编号无效,请新建对话后重试。')
|
|
else:
|
|
conv_id = None
|
|
frames, headers = chat_service.create_chat_stream(msg, conv_id)
|
|
body = frames if isinstance(frames, str) else stream_with_context(frames)
|
|
return Response(body, mimetype='text/event-stream', headers=headers)
|
|
|
|
|
|
@bp.route('/api/feedback', methods=['POST'])
|
|
def feedback():
|
|
return business_service.feedback(request.get_json(silent=True) or {})
|