"""Bounded structured role expression; never return the raw model envelope as speech.""" from dataclasses import dataclass import json import re SYSTEM_FRAGMENT = '''本轮只输出一个JSON对象,格式为{"reply":"简短中文回答","emotion":"neutral","intensity":0},不加代码围栏或额外文字。reply直接回答用户,最多两小句,不含情绪标签、动作旁白或思考过程。emotion是角色本轮表达意图,不是用户心理判断;只允许neutral(intensity=0)、happy/angry/sad(intensity=1轻度或2明显)。普通问答默认neutral;帮助性和用户台词优先,不为表演牺牲回答,不根据摄像头皱眉强行生气或攻击。每轮仅一个主情绪,无混合或长期状态。''' SAFE_REPLY = '抱歉,这次回答格式有误,请再说一次。' @dataclass(frozen=True) class ReplyEmotion: reply: str emotion: str = 'neutral' intensity: int = 0 source: str = 'fallback' def clean_reply(value): if not isinstance(value, str): return None value = value.strip() # Structured envelopes/code must never become TTS input, including nested replies. if not value or len(value) > 1000 or value.startswith(('{', '[', '```')): return None if re.search(r'"(?:reply|emotion|intensity)"\s*:', value): return None return value def parse_reply(raw): if not isinstance(raw, str) or len(raw) > 8192: return ReplyEmotion(SAFE_REPLY) body = raw.strip() if body.startswith('```'): body = re.sub(r'^```(?:json)?\s*', '', body, count=1).removesuffix('```').strip() try: data = json.loads(body) except (ValueError, RecursionError): data = None if isinstance(data, dict): reply = clean_reply(data.get('reply')) if reply: emotion, intensity = data.get('emotion'), data.get('intensity') if (set(data) == {'reply', 'emotion', 'intensity'} and type(intensity) is int and ((emotion == 'neutral' and intensity == 0) or (emotion in ('happy', 'angry', 'sad') and intensity in (1, 2)))): return ReplyEmotion(reply, emotion, intensity, 'model') return ReplyEmotion(reply) for key in ('text', 'answer'): reply = clean_reply(data.get(key)) if reply: return ReplyEmotion(reply) # Recover a usable quoted reply from a damaged/truncated envelope without another model call. match = re.search(r'"reply"\s*:\s*(")', body) if match: literal = body[match.start(1):] try: value, _ = json.JSONDecoder().raw_decode(literal) except ValueError: # Only a truncated string, never arbitrary suffix/JSON syntax recovery. try: value = json.loads(literal.rstrip('\\') + '"') except ValueError: value = None reply = clean_reply(value) if reply: return ReplyEmotion(reply) if not any(c in body for c in '{}[]') and not re.search(r'\b(?:reply|emotion|intensity)\s*[:=]', body): reply = clean_reply(body) if reply: return ReplyEmotion(reply) return ReplyEmotion(SAFE_REPLY)