This commit is contained in:
lingyun 2025-06-17 18:19:41 +08:00
parent 4911f3024f
commit e105003815
4 changed files with 343 additions and 342 deletions

View File

@ -1,134 +1,134 @@
from flask import Blueprint, jsonify, request from flask import Blueprint, jsonify, request
from ..models import Session, Message from ..models import Session, Message
from .. import db from .. import db
from . import globals from . import globals
import json,ast import json,ast
# from .report_routes import consultation # from .report_routes import consultation
message_routes = Blueprint('message', __name__) message_routes = Blueprint('message', __name__)
def filter_data(data): def filter_data(data):
return { return {
"content": data.get("content"), "content": data.get("content"),
"remark": data.get("remark"), "remark": data.get("remark"),
"role": data.get("role"), "role": data.get("role"),
"sessionId": data.get("sessionId") "sessionId": data.get("sessionId")
} }
def validate_session_id(sessionId): def validate_session_id(sessionId):
"""验证sessionId是否提供且存在于Session表中""" """验证sessionId是否提供且存在于Session表中"""
if not sessionId: if not sessionId:
return jsonify({"error": "sessionId is required"}), 400 return jsonify({"error": "sessionId is required"}), 400
session = Session.query.filter_by(id=sessionId).first() session = Session.query.filter_by(id=sessionId).first()
if not session: if not session:
return jsonify({"error": "Session not found"}), 404 return jsonify({"error": "Session not found"}), 404
return None return None
@message_routes.route('/get-message/<int:sessionId>', methods=['GET']) @message_routes.route('/get-message/<int:sessionId>', methods=['GET'])
def get_message(sessionId): def get_message(sessionId):
"""获取当前用户的所有会话""" """获取当前用户的所有会话"""
validation_result = validate_session_id(sessionId) validation_result = validate_session_id(sessionId)
if validation_result: if validation_result:
return validation_result return validation_result
messages = Message.query.filter_by(sessionId=sessionId).all() messages = Message.query.filter_by(sessionId=sessionId).all()
return jsonify(messages=[message.to_dict() for message in messages]), 200 return jsonify(messages=[message.to_dict() for message in messages]), 200
@message_routes.route('/add-message', methods=['POST']) @message_routes.route('/add-message', methods=['POST'])
def add_message(): def add_message():
"""添加会话""" """添加会话"""
data = request.get_json() data = request.get_json()
print("22222222request",request) print("22222222request",request)
result = filter_data(data) result = filter_data(data)
validation_result = validate_session_id(result["sessionId"]) # 修改为字典访问方式 validation_result = validate_session_id(result["sessionId"]) # 修改为字典访问方式
if validation_result: if validation_result:
return validation_result return validation_result
if not result["role"]: # 修改为字典访问方式 if not result["role"]: # 修改为字典访问方式
return jsonify({"error": "role is required"}), 400 return jsonify({"error": "role is required"}), 400
new_message = Message(**result) new_message = Message(**result)
db.session.add(new_message) db.session.add(new_message)
db.session.commit() db.session.commit()
return jsonify({'message': 'message added successfully', 'data': new_message.to_dict()}), 201 return jsonify({'message': 'message added successfully', 'data': new_message.to_dict()}), 201
@message_routes.route('/update-message/<int:messageId>/<int:sessionId>', methods=['PUT']) @message_routes.route('/update-message/<int:messageId>/<int:sessionId>', methods=['PUT'])
def update_message(messageId, sessionId): def update_message(messageId, sessionId):
"""更新会话""" """更新会话"""
print("1111111111111111111request",request) print("1111111111111111111request",request)
data = request.get_json() data = request.get_json()
remark = data.get("remark") # 修改为字典访问方式 remark = data.get("remark") # 修改为字典访问方式
validation_result = validate_session_id(sessionId) # 修改为字典访问方式 validation_result = validate_session_id(sessionId) # 修改为字典访问方式
if validation_result: if validation_result:
return validation_result # 修改为字典访问方式 return validation_result # 修改为字典访问方式
message = Message.query.filter_by(id=messageId).first() # 修改为字典访问方式 message = Message.query.filter_by(id=messageId).first() # 修改为字典访问方式
if not message: # 修改为字典访问方式 if not message: # 修改为字典访问方式
return jsonify({"error": "message not found"}), 404 # 修改为字典访问方式 return jsonify({"error": "message not found"}), 404 # 修改为字典访问方式
if remark: if remark:
message.remark = remark # 修改为字典访问方式 message.remark = remark # 修改为字典访问方式
db.session.commit() # 修改为字典访问方式 db.session.commit() # 修改为字典访问方式
return jsonify({'message': 'message updated successfully'}) return jsonify({'message': 'message updated successfully'})
@message_routes.route('/to-chat', methods=['POST']) @message_routes.route('/to-chat', methods=['POST'])
def to_chat(): def to_chat():
print("请求头:", dict(request.headers)) # 检查Content-Type print("请求头:", dict(request.headers)) # 检查Content-Type
print("原始字节数据:", request.get_data()) # 检查数据是否合法 print("原始字节数据:", request.get_data()) # 检查数据是否合法
print("1111111111111111111request",request) print("1111111111111111111request",request)
# if not request.is_json: # if not request.is_json:
# return jsonify({"error": "Content-Type must be application/json"}), 401 # return jsonify({"error": "Content-Type must be application/json"}), 401
# # 2. 获取外层JSON数据 # # 2. 获取外层JSON数据
# try: # try:
# data = request.json # data = request.json
# print("外层JSON数据:", data) # print("外层JSON数据:", data)
# except Exception as e: # except Exception as e:
# return jsonify({"error": f"外层JSON解析失败: {str(e)}"}), 402 # return jsonify({"error": f"外层JSON解析失败: {str(e)}"}), 402
# # 3. 解析嵌套的JSON字符串msgList和patientInfo # # 3. 解析嵌套的JSON字符串msgList和patientInfo
# try: # try:
# # 解析msgList字符串 -> 列表) # # 解析msgList字符串 -> 列表)
# msg_list = json.loads(data["msgList"]) # msg_list = json.loads(data["msgList"])
# print("解析后的msgList:", msg_list) # print("解析后的msgList:", msg_list)
# # 解析patientInfo字符串 -> 字典) # # 解析patientInfo字符串 -> 字典)
# patient_info = json.loads(data["patientInfo"]) # patient_info = json.loads(data["patientInfo"])
# print("解析后的patientInfo:", patient_info) # print("解析后的patientInfo:", patient_info)
# except json.JSONDecodeError as e: # except json.JSONDecodeError as e:
# return jsonify({"error": f"嵌套JSON解析失败: {str(e)}"}), 403 # return jsonify({"error": f"嵌套JSON解析失败: {str(e)}"}), 403
# except KeyError as e: # except KeyError as e:
# return jsonify({"error": f"缺少必要字段: {str(e)}"}), 404 # return jsonify({"error": f"缺少必要字段: {str(e)}"}), 404
data = request.json data = request.json
print("1111111111111111111data",data) print("1111111111111111111data",data)
patientId = data['patientId'] patientId = data['patientId']
msgList = data['msgList'] msgList = data['msgList']
patient_info = data['patientInfo'] patient_info = data['patientInfo']
print("222222222patient_info",patient_info) print("222222222patient_info",patient_info)
if len(msgList) == 0: if len(msgList) == 0:
globals.consultation.init_session(patientId,case_data=patient_info) globals.consultation.init_session(patientId,case_data=patient_info)
content = None content = None
else: else:
content = data['msgList'][-1]['content'] content = data['msgList'][-1]['content']
print("333333333content",type(content)) print("333333333content",type(content))
value, option, system = None, None, None value, option, system = None, None, None
cur_card, answer = globals.consultation.qa_chat(patientId, content, msgList) cur_card, answer = globals.consultation.qa_chat(patientId, content, msgList)
if cur_card and cur_card[0] and cur_card[0]['status'] == 'success': if cur_card and cur_card[0] and cur_card[0]['status'] == 'success':
value, option, system = cur_card[0]['option_value'], cur_card[1], cur_card[2] value, option, system = cur_card[0]['option_value'], cur_card[1], cur_card[2]
return jsonify({ return jsonify({
'answer': answer, 'answer': answer,
'analysis': { 'analysis': {
'value': value, 'option': option, 'system': system 'value': value, 'option': option, 'system': system
} }
}), 201 }), 201

View File

@ -1,119 +1,119 @@
import os import os
from dotenv import load_dotenv from dotenv import load_dotenv
from src.session import SessionState from src.session import SessionState
from src.case_info import format_to_report from src.case_info import format_to_report
import ast import ast
class Consultation: class Consultation:
def __init__(self): def __init__(self):
# initialize one patient and session state # initialize one patient and session state
self.session_map = {} self.session_map = {}
def init_session(self, session_id, case_data): def init_session(self, session_id, case_data):
load_dotenv() load_dotenv()
self.session_map[session_id] = SessionState(case_data) self.session_map[session_id] = SessionState(case_data)
def qa_chat(self, session_id, content, msgList, question=None): def qa_chat(self, session_id, content, msgList, question=None):
session_state = self.session_map[session_id] session_state = self.session_map[session_id]
print(777777,session_state.__dict__) print(777777,session_state.__dict__)
session_state.history = msgList session_state.history = msgList
print("5555555session_state.option",session_state.option) print("5555555session_state.option",session_state.option)
if_overall = '总体评估' in session_state.option if session_state.option else False if_overall = '总体评估' in session_state.option if session_state.option else False
session_state.process_query_task(content, overall=if_overall) session_state.process_query_task(content, overall=if_overall)
print(8888,session_state.__dict__) print(8888,session_state.__dict__)
cur_card = [session_state.info, session_state.option, session_state.agent_names[session_state.agent_order]] cur_card = [session_state.info, session_state.option, session_state.agent_names[session_state.agent_order]]
print("66666cur_card",cur_card) print("66666cur_card",cur_card)
if not session_state.info or session_state.info['status'] == 'success': if not session_state.info or session_state.info['status'] == 'success':
# update recorded information and update agent's knowledge # update recorded information and update agent's knowledge
session_state.update() session_state.update()
# choose agent and # choose agent and
session_state.choose_agent_and_option_task() session_state.choose_agent_and_option_task()
if session_state.option == '': if session_state.option == '':
session_state.choose_agent_and_option_task() session_state.choose_agent_and_option_task()
elif session_state.info['status'] == 'need_clarification': elif session_state.info['status'] == 'need_clarification':
session_state.missing_info = session_state.info['missing_info'] session_state.missing_info = session_state.info['missing_info']
# doctor asks the question # doctor asks the question
stream_state = session_state.doctor_state_task() stream_state = session_state.doctor_state_task()
if session_state.if_end(): if session_state.if_end():
pass pass
self.session_map[session_id] = session_state self.session_map[session_id] = session_state
return cur_card, stream_state return cur_card, stream_state
def save_result(self, session_id): def save_result(self, session_id):
return self.session_map[session_id].patient.recorded_info return self.session_map[session_id].patient.recorded_info
def format_report(self, session_id): def format_report(self, session_id):
return format_to_report(self.session_map[session_id].patient.recorded_info) return format_to_report(self.session_map[session_id].patient.recorded_info)
# if __name__ == '__main__': # if __name__ == '__main__':
# print(os.getenv('CASE')) # print(os.getenv('CASE'))
# consultation = Consultation() # consultation = Consultation()
# consultation.qa_chat() # consultation.qa_chat()
"""import os """import os
from dotenv import load_dotenv from dotenv import load_dotenv
from src.session import SessionState from src.session import SessionState
from src.case_info import format_to_report from src.case_info import format_to_report
# globals.consultation.init_session(case_data=data) # globals.consultation.init_session(case_data=data)
# import os # import os
# from dotenv import load_dotenv # from dotenv import load_dotenv
# from session import SessionState # from session import SessionState
# from case_info import format_to_report # from case_info import format_to_report
class Consultation: class Consultation:
def __init__(self): def __init__(self):
# initialize one patient and session state # initialize one patient and session state
self.session_map = {} self.session_map = {}
def init_session(self, case_data): def init_session(self, case_data):
load_dotenv() load_dotenv()
self.session_map = SessionState(case_data) self.session_map = SessionState(case_data)
def qa_chat(self, question=None): def qa_chat(self, question=None):
session_state = self.session_map session_state = self.session_map
if_overall = '总体评估' in session_state.option if session_state.option else False if_overall = '总体评估' in session_state.option if session_state.option else False
session_state.process_query_task(question, overall=if_overall) session_state.process_query_task(question, overall=if_overall)
cur_card = [session_state.info, session_state.option, session_state.agent_names[session_state.agent_order]] cur_card = [session_state.info, session_state.option, session_state.agent_names[session_state.agent_order]]
if not session_state.info or session_state.info['status'] == 'success': if not session_state.info or session_state.info['status'] == 'success':
# update recorded information and update agent's knowledge # update recorded information and update agent's knowledge
session_state.update() session_state.update()
# choose agent and option # choose agent and option
session_state.choose_agent_and_option_task() session_state.choose_agent_and_option_task()
if session_state.option == '': if session_state.option == '':
session_state.choose_agent_and_option_task() session_state.choose_agent_and_option_task()
elif session_state.info['status'] == 'need_clarification': elif session_state.info['status'] == 'need_clarification':
session_state.missing_info = session_state.info['missing_info'] session_state.missing_info = session_state.info['missing_info']
# doctor asks the question # doctor asks the question
stream_state = session_state.doctor_state_task() stream_state = session_state.doctor_state_task()
if session_state.if_end(): if session_state.if_end():
pass pass
self.session_map = session_state self.session_map = session_state
return cur_card, stream_state return cur_card, stream_state
def save_result(self): def save_result(self):
return self.session_map.patient.recorded_info return self.session_map.patient.recorded_info
def format_report(self): def format_report(self):
return format_to_report(self.session_map.patient.recorded_info) return format_to_report(self.session_map.patient.recorded_info)
# def save_result(self): # def save_result(self):
# return self.session_state.patient.recorded_info # return self.session_state.patient.recorded_info
# def format_report(self): # def format_report(self):
# return format_to_report(self.session_state.patient.recorded_info) # return format_to_report(self.session_state.patient.recorded_info)
""" """
if __name__ == '__main__': if __name__ == '__main__':
print(os.getenv('CASE')) print(os.getenv('CASE'))
consultation = Consultation() consultation = Consultation()
consultation.qa_chat() consultation.qa_chat()

View File

@ -1,90 +1,90 @@
from src.agents import doctor_state, choose_agent, init_multi_agents from src.agents import doctor_state, choose_agent, init_multi_agents
from src.utils import get_q_template, init_logger, process_stream from src.utils import get_q_template, init_logger, process_stream
from src.patient import Patient from src.patient import Patient
# from agents import doctor_state, choose_agent, init_multi_agents # from agents import doctor_state, choose_agent, init_multi_agents
# from utils import get_q_template, init_logger, process_stream # from utils import get_q_template, init_logger, process_stream
# from patient import Patient # from patient import Patient
class SessionState: class SessionState:
def __init__(self, case): def __init__(self, case):
self.patient = Patient(case) self.patient = Patient(case)
self.agent_order = -1 self.agent_order = -1
self.agent_names = ['circulatory_system', 'respiratory_system', 'nervous_system'] self.agent_names = ['circulatory_system', 'respiratory_system', 'nervous_system']
self.cur_agent = None self.cur_agent = None
self.agents = init_multi_agents(self.agent_names) self.agents = init_multi_agents(self.agent_names)
self.query = None self.query = None
self.info = None self.info = None
self.option = None self.option = None
self.q_templates = None self.q_templates = None
self.missing_info = None self.missing_info = None
self.history = [] self.history = []
self.logger = init_logger() self.logger = init_logger()
def get_agent_name(self): def get_agent_name(self):
return self.agent_names[self.agent_order] return self.agent_names[self.agent_order]
def if_end(self): def if_end(self):
return self.option == '' and self.agent_order == len(self.agent_names) - 1 return self.option == '' and self.agent_order == len(self.agent_names) - 1
def add_to_history(self, role, message): def add_to_history(self, role, message):
pass pass
# self.history.append({"role": role, "content": message}) # self.history.append({"role": role, "content": message})
# print("history:",self.history) # print("history:",self.history)
def process_query_task(self, cur_query, overall=False): def process_query_task(self, cur_query, overall=False):
if cur_query: if cur_query:
print(7777,cur_query) print(7777,cur_query)
# self.add_to_history('user', cur_query) # self.add_to_history('user', cur_query)
self.logger.info('query: ' + str(cur_query)) self.logger.info('query: ' + str(cur_query))
else: else:
self.logger.info('query: None') self.logger.info('query: None')
info = self.cur_agent.process_query(self.option, self.patient, self.history, info = self.cur_agent.process_query(self.option, self.patient, self.history,
self.logger, overall) if self.cur_agent else None self.logger, overall) if self.cur_agent else None
self.query = cur_query self.query = cur_query
self.info = info self.info = info
self.logger.info('information in the query: ' + str(info)) self.logger.info('information in the query: ' + str(info))
def choose_agent_and_option_task(self): def choose_agent_and_option_task(self):
# choose next system agent # choose next system agent
current_agent_order, chosen_agent = choose_agent(self.option, self.agent_order, self.agents) current_agent_order, chosen_agent = choose_agent(self.option, self.agent_order, self.agents)
self.agent_order, self.cur_agent = current_agent_order, chosen_agent self.agent_order, self.cur_agent = current_agent_order, chosen_agent
self.logger.info("chosen agent: " + self.agent_names[current_agent_order]) self.logger.info("chosen agent: " + self.agent_names[current_agent_order])
# choose option # choose option
if self.cur_agent: if self.cur_agent:
print("!!!!!!!!!!!",self.cur_agent) print("!!!!!!!!!!!",self.cur_agent)
self.option = self.cur_agent.choose_option(self.history, self.patient, self.logger) self.option = self.cur_agent.choose_option(self.history, self.patient, self.logger)
print("!!!!!!!!!!!self.option",self.option) print("!!!!!!!!!!!self.option",self.option)
self.q_templates = get_q_template(self.get_agent_name(), self.option) self.q_templates = get_q_template(self.get_agent_name(), self.option)
self.missing_info = None self.missing_info = None
self.logger.info('current option and question templates:\n' + self.option + ' ' + str(self.q_templates)) self.logger.info('current option and question templates:\n' + self.option + ' ' + str(self.q_templates))
def doctor_state_task(self): def doctor_state_task(self):
n = 3 n = 3
stream_state = doctor_state(self.history, self.patient, self.option, self.q_templates, self.missing_info, self.logger) stream_state = doctor_state(self.history, self.patient, self.option, self.q_templates, self.missing_info, self.logger)
state_list = process_stream(stream_state) if type(stream_state) != str else [stream_state[i:i+3] for i in range(0, len(stream_state), 3)] state_list = process_stream(stream_state) if type(stream_state) != str else [stream_state[i:i+3] for i in range(0, len(stream_state), 3)]
if len(self.history) == 0: if len(self.history) == 0:
s = '我是您的麻醉评估医生。我们接下来需要了解一些基本情况。' s = '我是您的麻醉评估医生。我们接下来需要了解一些基本情况。'
state = [s[i:i+3] for i in range(0, len(s), 3)] + state_list state = [s[i:i+3] for i in range(0, len(s), 3)] + state_list
elif self.if_end(): elif self.if_end():
s = '谢谢你的配合,我们已经了解了你的整体情况,再见!' s = '谢谢你的配合,我们已经了解了你的整体情况,再见!'
state = [s[i:i+3] for i in range(0, len(s), 3)] state = [s[i:i+3] for i in range(0, len(s), 3)]
else: else:
state = state_list state = state_list
# self.add_to_history('assistant', ''.join(state)) # self.add_to_history('assistant', ''.join(state))
self.missing_info = None self.missing_info = None
self.logger.info('doctor statement: ' + ''.join(state)) self.logger.info('doctor statement: ' + ''.join(state))
self.logger.info('HISTORY:\n' + str(self.history) + '\n\n') self.logger.info('HISTORY:\n' + str(self.history) + '\n\n')
print('DOCTOR:', ''.join(state)) print('DOCTOR:', ''.join(state))
return state return state
def update(self): def update(self):
if self.info: self.patient.update_info(self.option, self.info) if self.info: self.patient.update_info(self.option, self.info)
if self.cur_agent: self.cur_agent.update_knowledge(self.option, self.info) if self.cur_agent: self.cur_agent.update_knowledge(self.option, self.info)

1
test.py Normal file
View File

@ -0,0 +1 @@
print(112)