282 lines
13 KiB
Python
282 lines
13 KiB
Python
# myapp/sockets/namespaces.py
|
|
import json
|
|
import time
|
|
import requests
|
|
from flask import current_app, request, session, url_for
|
|
from flask_socketio import Namespace, join_room, leave_room, emit
|
|
from ..config import Config
|
|
|
|
from ..function_tools import judge
|
|
from ..function_tools import next_chapter
|
|
from ..services.backboard_service import realtime_response
|
|
from ..services.markdown_service import load_full_markdown_file
|
|
from ..services.course_service import save_learning_progress, upload_learning_progress_to_cloud
|
|
from ..extension_ase.ase_client import HSAEngineClient
|
|
from ..services.user_service import get_or_load_current_user
|
|
from ..services.course_service import load_learning_progress
|
|
from ..services.asectrl_service import (
|
|
on_connect_to_ase,
|
|
receive_ase_paste_detected,
|
|
receive_ase_dialog,
|
|
receive_ase_message_hint,
|
|
receive_ase_voice_out,
|
|
receive_ase_process,
|
|
receive_ase_judge,
|
|
receive_ase_next_chapter,
|
|
receive_ase_chapter_score
|
|
)
|
|
|
|
|
|
|
|
class VSCodeNamespace(Namespace):
|
|
def on_login(self,data):
|
|
self.app = current_app
|
|
ex = current_app.extensions
|
|
print("VSCode client connected")
|
|
dataconfig = data['config']
|
|
user_uuid = dataconfig.get('user_uuid')
|
|
path = dataconfig.get('path')
|
|
course_id = dataconfig.get('course_id')
|
|
lesson_id = dataconfig.get('chapter_id')
|
|
print(f"User {user_uuid} connected with path: {path}")
|
|
join_room(user_uuid, namespace='/vscode')
|
|
chatmanager = ex['user_uuid2chatmanager'][user_uuid]
|
|
chatmanager.set_vscode_ws(self)
|
|
|
|
|
|
def on_load_chapter(self, data):
|
|
dataconfig = data['config']
|
|
user_uuid = dataconfig.get('user_uuid')
|
|
ex = current_app.extensions
|
|
chatmanager = ex['user_uuid2chatmanager'][user_uuid]
|
|
chatmanager.load_code_in_markdown()
|
|
|
|
def on_message(self, data):
|
|
# print(f"Received from VSCode client: {data}")
|
|
dataconfig = data['config']
|
|
realtime_response(dataconfig, data)
|
|
# emit('response', {'message': 'Config data received and connection established'})
|
|
def on_disconnect(self, data):
|
|
print("VSCode client disconnected")
|
|
print("Disconnect reason:"+str(data))
|
|
|
|
|
|
class AgentNamespace(Namespace):
|
|
def _load_learning_progress(self, chatmanager, user_id, course_id, chapter_name, lesson_name, continue_learn):
|
|
"""加载并恢复用户学习进度
|
|
|
|
Args:
|
|
chatmanager: 聊天管理器实例
|
|
user_id: 用户ID
|
|
course_id: 课程ID
|
|
chapter_name: 章节名称
|
|
lesson_name: 课时名称
|
|
continue_learn: 是否继续学习
|
|
|
|
Returns:
|
|
int: 需要跳过的章节数
|
|
"""
|
|
need_skip_chapters = 0
|
|
|
|
if continue_learn: # 尝试加载用户学习进度
|
|
progress_result = load_learning_progress(user_id, course_id, chapter_name, lesson_name)
|
|
|
|
if progress_result['exists']:
|
|
progress = progress_result['data']
|
|
# 恢复学习进度数据
|
|
if 'scores' in progress:
|
|
# 根据scores的数量确定需要跳过的章节数
|
|
need_skip_chapters = len(progress['scores'])
|
|
chatmanager.scores = progress['scores']
|
|
|
|
# 恢复聊天历史
|
|
if 'chat_historys' in progress:
|
|
chatmanager.chat_historys = progress['chat_historys']
|
|
else:
|
|
chatmanager.chat_historys = []
|
|
|
|
# 恢复当前章节链
|
|
if 'chapter_chain_now' in progress:
|
|
chatmanager.chapter_chain_now = progress['chapter_chain_now']
|
|
upload_learning_progress_to_cloud(progress)
|
|
else:
|
|
# 使用默认值,确保有完整的结构
|
|
chatmanager.chat_historys = progress_result['data']['chat_historys']
|
|
chatmanager.scores = progress_result['data']['scores']
|
|
|
|
return need_skip_chapters
|
|
|
|
def on_login(self, data):
|
|
self.app = current_app
|
|
ex = current_app.extensions
|
|
uuid2username = ex["uuid2username"]
|
|
backboard_manager = ex["backboard_manager"]
|
|
data = json.loads(data)
|
|
user_uuid = data['user_uuid']
|
|
course_id = data['course_id']
|
|
lesson_name = data['lesson_name']
|
|
chapter_name = data['chapter_name']
|
|
user_id = uuid2username[user_uuid]
|
|
session['user_uuid'] = user_uuid
|
|
join_room(user_uuid, namespace='/agent') # 将该用户加入以user_id为名的room
|
|
print(f'User connected with session user_uuid: {user_uuid}')
|
|
|
|
user_uuid2chatmanager = ex["user_uuid2chatmanager"]
|
|
user_uuid2ase_client = ex["user_uuid2ase_client"]
|
|
if (user_uuid2ase_client.get(user_uuid,None) is not None and user_uuid2ase_client[user_uuid].connected):
|
|
user_uuid2ase_client[user_uuid].disconnect()
|
|
chatmanager = user_uuid2chatmanager[user_uuid]
|
|
chatmanager.function_manager.add_function(judge, {'course_id': course_id, 'root_path': f'/home/{user_id}/{course_id}/{chapter_name}/{lesson_name}'})
|
|
chatmanager.function_manager.add_function(next_chapter, {'user_uuid': user_uuid})
|
|
|
|
|
|
continue_learn = not chatmanager.restart
|
|
need_skip_chapters = self._load_learning_progress(chatmanager, user_id, course_id, chapter_name, lesson_name, continue_learn)
|
|
|
|
fmd,fmdp,fsp = load_full_markdown_file(course_id, chapter_name, lesson_name)
|
|
user_uuid2ase_client[user_uuid] = HSAEngineClient(current_app.config["ASE_ENGINE_URL"], current_app.config["ASE_ENGINE_NAMESPACE"],id=user_id, chatmanager = chatmanager)
|
|
chatmanager.init(user_uuid, user_uuid2ase_client[user_uuid],
|
|
fmd, fmdp, fsp, course_id, chapter_name, lesson_name, max_iter=5, app=current_app, socketio=self)
|
|
backboard_manager.add_backboard(user_uuid, user_id, course_id,
|
|
lesson_name, root_path=f'/home/{user_id}/{course_id}/{chapter_name}/{lesson_name}')
|
|
chatmanager.bb = backboard_manager.get_backboard(user_uuid)
|
|
# 如果有保存的进度,需要跳过已经完成的章节、无需清空代码、对话历史恢复
|
|
if continue_learn:
|
|
for _ in range(need_skip_chapters):
|
|
chatmanager.next_chapter()
|
|
emit('next_chapter', room=user_uuid, namespace='/agent')
|
|
# 恢复对话历史到前端 - 使用批量发送消息列表
|
|
if chatmanager.chat_historys:
|
|
emit('messages', chatmanager.chat_historys, room=user_uuid, namespace='/agent')
|
|
|
|
self.chatmanager = chatmanager
|
|
self.ase_client = user_uuid2ase_client[user_uuid]
|
|
user_uuid2ase_client[user_uuid].register_on_connect_entry(
|
|
callback=on_connect_to_ase,
|
|
entry=(self, user_uuid2ase_client[user_uuid]),
|
|
init_data={'room':user_uuid, 'restart':chatmanager.restart, 'asengine_url':current_app.config["ASE_ENGINE_URL"], 'asengine_token':current_app.config["ASE_ENGINE_URL_TOKEN"]}
|
|
)
|
|
user_uuid2ase_client[user_uuid].register_route_with_entry(
|
|
route='dialog',
|
|
callback=receive_ase_dialog,
|
|
entry=self,
|
|
init_data={'room': user_uuid}
|
|
)
|
|
user_uuid2ase_client[user_uuid].register_route_with_entry(
|
|
route='dialog-hint',
|
|
callback=receive_ase_message_hint,
|
|
entry=self,
|
|
init_data={'room': user_uuid}
|
|
)
|
|
user_uuid2ase_client[user_uuid].register_route_with_entry(
|
|
route='voice_out',
|
|
callback=receive_ase_voice_out,
|
|
entry=self,
|
|
init_data={'room': user_uuid}
|
|
)
|
|
user_uuid2ase_client[user_uuid].register_route_with_entry(
|
|
route='judge',
|
|
callback=receive_ase_judge,
|
|
entry=self,
|
|
init_data={'room': user_uuid}
|
|
)
|
|
user_uuid2ase_client[user_uuid].register_route_with_entry(
|
|
route='next_chapter',
|
|
callback=receive_ase_next_chapter,
|
|
entry=self,
|
|
init_data={'room': user_uuid}
|
|
)
|
|
user_uuid2ase_client[user_uuid].register_route_with_entry(
|
|
route='chapter_score',
|
|
callback=receive_ase_chapter_score,
|
|
entry=(get_or_load_current_user(),chatmanager),
|
|
init_data={'room': user_uuid}
|
|
)
|
|
user_uuid2ase_client[user_uuid].register_route_with_entry(
|
|
route='process',
|
|
callback=receive_ase_process,
|
|
entry=self,
|
|
init_data={'room': user_uuid}
|
|
)
|
|
user_uuid2ase_client[user_uuid].register_route_with_entry(
|
|
route='paste_detected',
|
|
callback=receive_ase_paste_detected,
|
|
entry=self,
|
|
init_data={'room': user_uuid}
|
|
)
|
|
user_uuid2ase_client[user_uuid].connect()
|
|
|
|
|
|
def on_language(self, language):
|
|
ex = current_app.extensions
|
|
|
|
def on_message(self, data):
|
|
ex = current_app.extensions
|
|
chatmanager = ex["user_uuid2chatmanager"]
|
|
uuid = session.get('user_uuid')
|
|
user_uuid2ase_client = ex["user_uuid2ase_client"]
|
|
if (type(data)==str):
|
|
data = json.loads(data)
|
|
if data['type'] == 'text':
|
|
res = user_uuid2ase_client[uuid].send_text('dialog', data['data'])
|
|
chatmanager[uuid].chat_historys.append({'role': 'user', 'content': data['data']})
|
|
|
|
if data['type'] == 'function': # 在这里 前端会发送允许执行的function与参数
|
|
d = data['data']
|
|
res = chatmanager[uuid].function_call(d['data']['name'], d['data'].get('args', {}))
|
|
d['data'] = res.to_dict()
|
|
emit(d['route'], d, room=uuid, namespace='/agent')
|
|
chatmanager[uuid].chat_historys.append({'role': 'user', 'content': data['data']})
|
|
user_uuid2ase_client[uuid].send_text(d['route'], data['data'])
|
|
|
|
def on_voice(self, voice_data):
|
|
ex = current_app.extensions
|
|
chatmanager = ex["user_uuid2chatmanager"]
|
|
uuid = session.get('user_uuid')
|
|
user_uuid2ase_client = ex["user_uuid2ase_client"]
|
|
res = user_uuid2ase_client[uuid].send_voice('voice_in', voice_data['data'])
|
|
|
|
|
|
def on_initiative(self,data): # 主动call
|
|
ex = current_app.extensions
|
|
uuid = session.get('user_uuid')
|
|
manager = ex["user_uuid2chatmanager"][uuid]
|
|
backboard_manager = ex["backboard_manager"]
|
|
if data['name'] == 'sample_judge':
|
|
manager.sample_judge(uuid, backboard_manager.get_backboard(uuid))
|
|
if data['name'] == 'judge':
|
|
res = manager.judge(uuid, backboard_manager.get_backboard(uuid))
|
|
emit('message', res.message, room=uuid, namespace='/agent')
|
|
|
|
|
|
def on_disconnect(self,data):
|
|
self.app.logger.info(f'AgentNamespace client disconnected, session user_uuid: {session.get("user_uuid", "unknown")}')
|
|
ex = current_app.extensions
|
|
uuid = session.get('user_uuid')
|
|
user_uuid2chatmanager = ex.get("user_uuid2chatmanager", {})
|
|
|
|
# 保存学习进度到MongoDB
|
|
try:
|
|
# 获取用户ID
|
|
uuid2username = ex.get("uuid2username", {})
|
|
user_id = uuid2username.get(uuid, "unknown")
|
|
self.app.logger.debug(f"get user's dialog his user_id={user_id}")
|
|
# 调用保存学习进度功能
|
|
chatmanager = user_uuid2chatmanager.get(uuid)
|
|
if chatmanager:
|
|
save_result = save_learning_progress(chatmanager, user_id)
|
|
|
|
except Exception as e:
|
|
self.app.logger.error(f"保存学习进度时发生异常: {str(e)}")
|
|
|
|
# 执行原有的断开连接逻辑
|
|
if uuid in user_uuid2chatmanager:
|
|
user_uuid2chatmanager[uuid].disconnect(uuid)
|
|
|
|
# 离开房间
|
|
if uuid:
|
|
leave_room(uuid, namespace='/agent')
|
|
|
|
self.app.logger.info("VSCode client disconnected")
|
|
self.app.logger.info(f"Disconnect reason: {str(data)}")
|