def _escape(value): if value is None: return None return str(value).replace("'", "''") async def chat_session_messages(ns={}): """获取某次会话的全部消息""" session_id = ns.get('session_id') if not session_id: return {'status': False, 'msg': 'session_id is required'} userid = ns.get('userid') or await get_user() if not userid: return {'status': False, 'msg': '未找到用户'} db = DBPools() async with db.sqlorContext('kboss') as sor: try: sessions = await sor.R('chat_session', {'id': session_id, 'userid': userid}) if not sessions: return {'status': False, 'msg': '会话不存在'} sql = """ SELECT id, role, content, content_type, created_at FROM chat_message WHERE session_id = '%s' ORDER BY created_at ASC; """ % _escape(session_id) rows = await sor.sqlExe(sql, {}) messages = [] for row in rows: content = row.get('content') or '' if row.get('content_type') == 'mixed': import json try: content = json.loads(content) except Exception: pass if isinstance(content, list): text_parts = [p.get('text', '') for p in content if p.get('type') == 'text'] display = '\n'.join([t for t in text_parts if t]) or '[多媒体消息]' else: display = content messages.append({ 'id': row['id'], 'role': row['role'], 'content': display, 'created_at': row.get('created_at'), }) return { 'status': True, 'msg': 'get messages success', 'data': { 'session': sessions[0], 'messages': messages, }, } except Exception as e: return {'status': False, 'msg': 'get messages failed, %s' % str(e)} ret = await chat_session_messages(params_kw) return ret