363 lines
15 KiB
Python
363 lines
15 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""AI 选课助手的原生 WebSocket 传输层。
|
||
|
||
协议(每个 WebSocket 连接处理一条 AI 消息):
|
||
- 客户端连接后发送 {"type": "chat", "message": "..."}(兼容旧格式 {"message": "..."})。
|
||
- 服务端推送 text_delta / tool_started / tool_finished / confirmation_required /
|
||
ask_user / error / done / heartbeat 事件,最后以 stream_end 收尾。
|
||
- 客户端可随时发送 {"type": "stop"} 取消生成(也会停止待执行的工具)。
|
||
- confirmation_required 事件要求客户端回传 {"type": "confirm", "call_id": "...",
|
||
"approved": true/false},写操作只有在确认后才会执行。
|
||
- ask_user 事件把前端输入框变成选择器,客户端回传 {"type": "ask_answer",
|
||
"call_id": "...", "selected": [...], "text": "补充说明"},答案作为工具结果返回模型。
|
||
"""
|
||
import json
|
||
import threading
|
||
import time
|
||
from collections import deque
|
||
from queue import Empty, Queue
|
||
|
||
from flask import current_app
|
||
from flask_login import current_user
|
||
|
||
from app.ai_assistant import stream_chat, get_ai_settings
|
||
from app.ai_usage import get_user_daily_usage, record_usage
|
||
from app.models import AiConversation, AiConversationMessage, db
|
||
|
||
|
||
_SENTENCE_ENDINGS = set('。!?!?;;\n')
|
||
_CLOSING_QUOTES = set('”’》))]}」』')
|
||
_MAX_TEXT_FRAME = 120
|
||
_HEARTBEAT_INTERVAL = 15
|
||
_CONFIRM_TIMEOUT = 180
|
||
# 计费走管理员共享 API Key:每用户每分钟最多 10 条消息。
|
||
_RATE_LIMIT_MAX = 10
|
||
_RATE_LIMIT_WINDOW = 60.0
|
||
|
||
_rate_lock = threading.Lock()
|
||
_rate_hits = {}
|
||
|
||
|
||
def _rate_limit_allow(user_id) -> bool:
|
||
now = time.monotonic()
|
||
with _rate_lock:
|
||
hits = _rate_hits.setdefault(user_id, deque())
|
||
while hits and now - hits[0] > _RATE_LIMIT_WINDOW:
|
||
hits.popleft()
|
||
if len(hits) >= _RATE_LIMIT_MAX:
|
||
return False
|
||
hits.append(now)
|
||
return True
|
||
|
||
|
||
class _DecisionGate:
|
||
"""等待用户在界面上回应(确认写操作 / 回答 ask_user 选择器)。
|
||
|
||
同一时刻只有一个挂起的请求。resolve 的 value 对确认是 bool,
|
||
对 ask_user 是答案 dict({'selected': [...], 'text': '...'})。
|
||
"""
|
||
|
||
def __init__(self):
|
||
self._cond = threading.Condition()
|
||
self._call_id = None
|
||
self._decision = None
|
||
self._early = None # (call_id, value):早于等待开始到达的答案(脚本/极速客户端)
|
||
|
||
def request(self, call_id: str, timeout: float = _CONFIRM_TIMEOUT) -> bool:
|
||
"""阻塞等待用户决定;超时、拒绝或连接断开都返回 False。"""
|
||
decision = self._wait(call_id, timeout)
|
||
return bool(decision)
|
||
|
||
def ask(self, call_id: str, payload=None, timeout: float = _CONFIRM_TIMEOUT):
|
||
"""阻塞等待用户回答 ask_user;返回答案 dict,超时或连接断开返回 None。
|
||
|
||
payload 是向用户展示的提问内容(question/options/multiple),仅为对齐
|
||
ask(call_id, payload) 的调用约定,答案以 resolve 回传的值为准。
|
||
"""
|
||
decision = self._wait(call_id, timeout)
|
||
return decision if isinstance(decision, dict) else None
|
||
|
||
def _wait(self, call_id: str, timeout: float):
|
||
with self._cond:
|
||
call_id = str(call_id)
|
||
self._call_id = call_id
|
||
self._decision = None
|
||
# 事件 yield 后答案可能在等待开始前就到,先认领缓冲的早到答案
|
||
if self._early and self._early[0] == call_id:
|
||
value, self._early = self._early[1], None
|
||
self._call_id = None
|
||
return value
|
||
decided = self._cond.wait_for(lambda: self._decision is not None, timeout=timeout)
|
||
self._call_id = None
|
||
decision, self._decision = self._decision, None
|
||
return decision if decided else None
|
||
|
||
def resolve(self, call_id: str, value) -> None:
|
||
with self._cond:
|
||
call_id = str(call_id)
|
||
if self._call_id == call_id and self._decision is None:
|
||
self._decision = value
|
||
self._cond.notify_all()
|
||
elif self._call_id is None and self._early is None:
|
||
# 尚无等待者:缓冲给随后 _wait 的同一 call_id 认领
|
||
self._early = (call_id, value)
|
||
|
||
def abandon(self) -> None:
|
||
"""用户停止或连接断开时结束等待,确认视为拒绝、提问视为无回答。"""
|
||
with self._cond:
|
||
if self._decision is None:
|
||
self._decision = False
|
||
self._cond.notify_all()
|
||
|
||
|
||
class _UserRef:
|
||
"""把当前用户固化成纯 Python 对象,避免后台线程访问别的线程的 ORM 会话。"""
|
||
|
||
def __init__(self, user, conversation_id=None):
|
||
self.id = user.id
|
||
self.school_id = user.school_id or 'sdmu'
|
||
self.conversation_id = conversation_id
|
||
account = user.get_jwxt_account() or {}
|
||
self._jwxt_username = str(account.get('username', '') or '')
|
||
|
||
def get_jwxt_account(self):
|
||
if not self._jwxt_username:
|
||
return None
|
||
return {'username': self._jwxt_username}
|
||
|
||
|
||
def _safe_send(ws, payload: dict) -> bool:
|
||
try:
|
||
ws.send(json.dumps(payload, ensure_ascii=False))
|
||
return True
|
||
except Exception:
|
||
return False
|
||
|
||
|
||
def _drain_sentence_buffer(buffer: str, force: bool = False):
|
||
"""把模型 token 聚合成自然句子,返回待发送帧和未完成的尾部。"""
|
||
frames = []
|
||
while buffer:
|
||
cut = -1
|
||
for index, char in enumerate(buffer):
|
||
if char in _SENTENCE_ENDINGS:
|
||
cut = index + 1
|
||
while cut < len(buffer) and buffer[cut] in _CLOSING_QUOTES:
|
||
cut += 1
|
||
break
|
||
if cut < 0 and len(buffer) >= _MAX_TEXT_FRAME:
|
||
cut = buffer.rfind(' ', 0, _MAX_TEXT_FRAME + 1)
|
||
if cut <= 0:
|
||
cut = _MAX_TEXT_FRAME
|
||
if cut <= 0:
|
||
break
|
||
frames.append(buffer[:cut])
|
||
buffer = buffer[cut:]
|
||
if force and buffer:
|
||
frames.append(buffer)
|
||
buffer = ''
|
||
return frames, buffer
|
||
|
||
|
||
def _load_conversation_messages(user, content):
|
||
conversation = AiConversation.query.filter_by(user_id=user.id).first()
|
||
if not conversation:
|
||
conversation = AiConversation(user_id=user.id)
|
||
db.session.add(conversation)
|
||
db.session.flush()
|
||
db.session.add(AiConversationMessage(
|
||
conversation_id=conversation.id,
|
||
role='user',
|
||
content=content[:4000],
|
||
))
|
||
db.session.commit()
|
||
recent = conversation.messages.order_by(AiConversationMessage.id.desc()).limit(20).all()
|
||
messages = [{'role': item.role, 'content': item.content} for item in reversed(recent)]
|
||
return conversation, messages
|
||
|
||
|
||
def _save_assistant_message(conversation_id, content: str) -> None:
|
||
"""保存回答(含被用户停止时的部分内容),避免下一轮对话丢失上下文。"""
|
||
if not conversation_id or not content:
|
||
return
|
||
db.session.add(AiConversationMessage(
|
||
conversation_id=conversation_id,
|
||
role='assistant',
|
||
content=content[:4000],
|
||
))
|
||
db.session.commit()
|
||
|
||
|
||
def register_ai_websocket(sock):
|
||
"""注册 /api/ai/chat/ws。"""
|
||
|
||
@sock.route('/api/ai/chat/ws')
|
||
def ai_chat_websocket(ws):
|
||
if not current_user.is_authenticated:
|
||
_safe_send(ws, {'type': 'error', 'message': '请先登录后使用 AI 选课助手'})
|
||
return
|
||
|
||
user_id = current_user.id
|
||
if not _rate_limit_allow(user_id):
|
||
_safe_send(ws, {'type': 'error', 'message': '发送太频繁了,请稍等一分钟再试'})
|
||
return
|
||
|
||
# 每日 token 限额(limit=0 表示不限制):超限直接拒绝本轮对话。
|
||
try:
|
||
used_today, _calls_today, daily_limit = get_user_daily_usage(user_id)
|
||
except Exception:
|
||
current_app.logger.exception('读取 AI 每日用量失败')
|
||
used_today, daily_limit = 0, 0
|
||
if daily_limit and used_today >= daily_limit:
|
||
_safe_send(ws, {
|
||
'type': 'error',
|
||
'message': f'今日 AI 用量已达上限({used_today:,}/{daily_limit:,} tokens),请明天再试或联系管理员调整',
|
||
})
|
||
return
|
||
|
||
conversation_id = None
|
||
gate = _DecisionGate()
|
||
stop_requested = threading.Event()
|
||
final_message = ''
|
||
reader_thread = None
|
||
|
||
try:
|
||
raw_message = ws.receive()
|
||
data = json.loads(raw_message or '{}')
|
||
content = str(data.get('message', '')).strip()
|
||
if not content:
|
||
_safe_send(ws, {'type': 'error', 'message': '请发送一条消息'})
|
||
return
|
||
|
||
conversation, messages = _load_conversation_messages(current_user, content)
|
||
conversation_id = conversation.id
|
||
# 在请求线程内固化用户数据,后台线程不再触碰 ORM 对象。
|
||
user = _UserRef(current_user, conversation_id=conversation_id)
|
||
model_name = str(get_ai_settings().get('model') or '')
|
||
|
||
def usage_sink(input_tokens, output_tokens):
|
||
"""每轮模型响应完成后的用量回调:落库,并超限即时停止后续轮次。"""
|
||
try:
|
||
record_usage(user_id, model_name, input_tokens, output_tokens)
|
||
used_now, _c, day_limit = get_user_daily_usage(user_id)
|
||
if day_limit and used_now >= day_limit:
|
||
stop_requested.set()
|
||
gate.abandon()
|
||
except Exception:
|
||
current_app.logger.exception('AI 用量记录失败')
|
||
|
||
# 模型请求可能长时间没有任何 token。生成器放到后台线程,主线程
|
||
# 每 15 秒发送一个空心跳,避免 Nginx/负载均衡器误判连接已断开。
|
||
event_queue = Queue()
|
||
app = current_app._get_current_object()
|
||
|
||
def produce_events():
|
||
from app.url_manager import push_school, pop_school
|
||
push_school(user.school_id)
|
||
try:
|
||
with app.app_context():
|
||
for event in stream_chat(
|
||
user, messages,
|
||
cancel_check=stop_requested.is_set,
|
||
confirm=gate.request,
|
||
usage_sink=usage_sink,
|
||
ask=gate.ask,
|
||
):
|
||
event_queue.put(event)
|
||
except Exception:
|
||
current_app.logger.exception('AI WebSocket 流生成失败')
|
||
event_queue.put({'type': 'error', 'message': 'AI 流式响应异常,请稍后重试'})
|
||
finally:
|
||
pop_school()
|
||
event_queue.put(None)
|
||
|
||
threading.Thread(target=produce_events, daemon=True).start()
|
||
|
||
def read_control_frames():
|
||
"""读取客户端控制帧:stop 取消生成,confirm 回传写操作确认。
|
||
|
||
simple-websocket 内部线程负责收 socket,receive 只是读缓冲,
|
||
与主线程的 send 并发是安全的。连接断开同样视为停止,
|
||
避免后台继续调用模型和执行工具。
|
||
"""
|
||
try:
|
||
while True:
|
||
raw = ws.receive()
|
||
if raw is None:
|
||
break
|
||
try:
|
||
control = json.loads(raw)
|
||
except (TypeError, ValueError):
|
||
continue
|
||
if control.get('type') == 'stop':
|
||
stop_requested.set()
|
||
gate.abandon()
|
||
break
|
||
if control.get('type') == 'confirm':
|
||
gate.resolve(str(control.get('call_id', '')), bool(control.get('approved')))
|
||
if control.get('type') == 'ask_answer':
|
||
gate.resolve(str(control.get('call_id', '')), {
|
||
'selected': control.get('selected') or [],
|
||
'text': str(control.get('text') or ''),
|
||
})
|
||
except Exception:
|
||
pass
|
||
finally:
|
||
stop_requested.set()
|
||
gate.abandon()
|
||
|
||
reader_thread = threading.Thread(target=read_control_frames, daemon=True)
|
||
reader_thread.start()
|
||
|
||
text_buffer = ''
|
||
|
||
def send_text_frames(force=False):
|
||
nonlocal text_buffer
|
||
frames, text_buffer = _drain_sentence_buffer(text_buffer, force=force)
|
||
for frame in frames:
|
||
ws.send(json.dumps({'type': 'text_delta', 'delta': frame}, ensure_ascii=False))
|
||
|
||
while True:
|
||
try:
|
||
event = event_queue.get(timeout=_HEARTBEAT_INTERVAL)
|
||
except Empty:
|
||
ws.send(json.dumps({'type': 'heartbeat', 'delta': ''}, ensure_ascii=False))
|
||
continue
|
||
if event is None:
|
||
break
|
||
if event.get('type') == 'text_delta':
|
||
delta = event.get('delta', '')
|
||
final_message += delta
|
||
text_buffer += delta
|
||
send_text_frames()
|
||
elif event.get('type') == 'done':
|
||
final_message = event.get('message', final_message)
|
||
send_text_frames(force=True)
|
||
ws.send(json.dumps(event, ensure_ascii=False))
|
||
else:
|
||
# 工具/确认事件前先发完模型上一段文字,保持“输出 → 工具 → 输出”的顺序。
|
||
send_text_frames(force=True)
|
||
ws.send(json.dumps(event, ensure_ascii=False))
|
||
|
||
send_text_frames(force=True)
|
||
_save_assistant_message(conversation_id, final_message)
|
||
reason = 'cancelled' if stop_requested.is_set() else 'complete'
|
||
# 应用层明确通知客户端:所有文本和工具事件都已发送完毕。
|
||
_safe_send(ws, {'type': 'stream_end', 'reason': reason})
|
||
except Exception:
|
||
current_app.logger.exception('AI WebSocket 对话失败')
|
||
# 连接中断也保留已生成的部分回答,避免下一轮对话丢失上下文。
|
||
try:
|
||
db.session.rollback()
|
||
_save_assistant_message(conversation_id, final_message)
|
||
except Exception:
|
||
db.session.rollback()
|
||
finally:
|
||
stop_requested.set()
|
||
gate.abandon()
|
||
# 等控制帧读取线程随客户端 close 退出(正常情况下客户端收到
|
||
# stream_end 后立即关闭),保持完整的 close handshake,避免
|
||
# handler 提前返回导致代理截断连接;超时则交给 flask_sock 收尾。
|
||
if reader_thread is not None:
|
||
reader_thread.join(timeout=30)
|