可以跑了 准备做系统

This commit is contained in:
CakeCN
2024-12-28 17:11:24 +08:00
parent f3791850b0
commit 1280a978f5
24 changed files with 2053 additions and 324 deletions

View File

@@ -1,4 +1,4 @@
from flask import Flask, session, request, jsonify, render_template, send_from_directory
from flask import Flask, redirect, session, request, jsonify, render_template, send_from_directory, url_for
from flask_cors import CORS
from flask_socketio import SocketIO, join_room, emit, Namespace
import markdown
@@ -14,13 +14,13 @@ sys.path.insert(0, current_dir)
from AlgoriAgent.projects.algoriAgent.agent_manager import AgentManager
app = Flask(__name__)
# socketio = SocketIO(app, cors_allowed_origins="*",ping_timeout=60, ping_interval=5)
socketio = SocketIO(app, cors_allowed_origins="http://localhost:9888") # 设置跨域支持
socketio = SocketIO(app, cors_allowed_origins="*",ping_timeout=60, ping_interval=5)
# socketio = SocketIO(app, cors_allowed_origins="http://localhost:9888") # 设置跨域支持
import logging
app.secret_key = 'cakebaker'
app.logger.setLevel(logging.DEBUG)
# 配置 CORS
CORS(app, resources={r"/*": {"origins": "http://localhost:9888"},}, supports_credentials=True)
CORS(app, resources={r"/*": {"origins": "http://127.0.0.1:9090"},}, supports_credentials=True)
userid_recorder = {} # user_id&path -> session['user_id']
@@ -46,6 +46,7 @@ class VSCodeNamespace(Namespace):
path = dataconfig.get('path')
print(f"User {user_id} connected with path: {path}")
useruuid = user_id2uuid[user_id]
join_room(useruuid, namespace='/vscode')
if backboard_manager.get_backboard(useruuid) == None:
backboard_manager.add_backboard(useruuid, path)
@@ -94,9 +95,13 @@ def realtime_response(config, realtime_action):
'''
Agent and Chat
'''
agent_manager = AgentManager()
agent_manager = AgentManager(app = app, socketio = socketio)
user_threads = {}
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
# 初始化线程池
executor = ThreadPoolExecutor(max_workers=10)
class AgentNamespace(Namespace):
def on_login(self, data):
data = json.loads(data)
@@ -112,27 +117,48 @@ class AgentNamespace(Namespace):
markdown = fmd.read()
markdown_prompts = fmdp.read()
score_prompts = fsp.read()
user_uuid, agent = agent_manager.new_agent(markdown, markdown_prompts, score_prompts, id=user_uuid)
user_uuid, agent = agent_manager.new_agent(markdown, markdown_prompts, score_prompts, id=user_uuid, root_path=f'{user}/{folder_name}')
print(user_uuid)
join_room(user_uuid) # 将该用户加入以user_id为名的room
join_room(user_uuid, namespace='/agent') # 将该用户加入以user_id为名的room
backboard_manager.add_backboard(user_uuid, folder_name)
def on_language(self, language):
id = session.get('user_id')
agent_manager.change_language(id, language)
def on_message(self, data):
print(f"Message from client: {data}")
id = session.get('user_id')
if (type(data)==str):
data = json.loads(data)
print(id)
# 构造回复消息
res = agent_manager.invoke(id, data, backboard_manager.get_backboard(id).get_info_prompt())
reply = f"AI: {res.content['speak']}"
# 将回复发送回前端
emit('message', reply)
if data['type'] == 'text':
res = agent_manager.invoke(id, data['data'], backboard_manager.get_backboard(id).get_info_prompt())
print('=*='*20)
print(res.content)
reply = f"AI: {res.content['speak']}"
with app.app_context():
emit('message',reply, room=id, namespace='/agent')
emit('request_function',res.content['function'], room=id, namespace='/agent')
# for res in agent_manager.invoke(id, data, backboard_manager.get_backboard(id).get_info_prompt(), reset=True):
# print('=*='*20)
# print(res.content)
# if ('speak' in res.content):
# reply = f"AI: {res.content['speak']}"
# with app.app_context(): emit('message',reply, room=id, namespace='/agent')
# if ('function' in res.content):
# functions = res.content['function']
# if functions is None: break
# if len(functions)==0:break
if data['type'] == 'function':
agent_manager.function_call(id, data['data'])
def on_disconnect(self):
print("VSCode client disconnected")
'''
Markdown to HTML
'''
@@ -207,6 +233,7 @@ Vscode
@app.route('/desktop/<user_id>/<path>')
def hello_world(user_id, path):
if 'user_id' not in session:
# return redirect(url_for('login'))
session['user_id'] = 'user_' + str(uuid.uuid4())
print("user "+ user_id + "uuid is"+ session['user_id'])
user_id2uuid[user_id] = session['user_id']
@@ -220,7 +247,7 @@ def hello_world(user_id, path):
config_path = os.path.join(path_dir, '.config')
with open(config_path, 'w') as f:
f.write(f"user_id={user_id}\npath={path}")
return render_template('index.html', user_id=user_id, path=path)
return render_template('desktop.html', user_id=user_id, path=path)
@app.route('/vscode_data', methods=['POST'])
@@ -238,6 +265,65 @@ def get_session():
'''
Login
'''
@app.route('/login')
def login():
if 'user_id' not in session:
return render_template('login.html')
else:
return redirect(url_for('/'))
from db.user_list import UserList
users_list = UserList()
@app.route('/login_post', methods=['POST'])
def login_post():
# 获取请求的 JSON 数据
data = request.get_json()
username = data.get('username')
password = data.get('password')
user = users_list.get_user(username)
if user is None:
return jsonify({'success': False, 'message': '用户名或密码错误'})
if user['password'] != password:
return jsonify({'success': False, 'message': '用户名或密码错误'})
session['user_id'] = 'user_' + str(uuid.uuid4())
print("user "+ username + "uuid is"+ session['user_id'])
user_id2uuid[username] = session['user_id']
uuid2user_id[session['user_id']] = username
return jsonify({'success': True, 'message': '登录成功'})
'''
DashBoard
'''
@app.route('/dashboard')
def dashboard():
if 'user_id' not in session:
return redirect(url_for('login'))
return render_template('dashboard.html')
'''
Book
'''
@app.route('/book/<book_name>')
def book(book_name):
return render_template('book.html', book_name=book_name)
@app.route('/')
def home_index():
return render_template('index.html')
if __name__ == '__main__':
socketio.on_namespace(VSCodeNamespace('/vscode'))
socketio.on_namespace(AgentNamespace('/agent'))