"""Bounded structured role expression; never return the raw model envelope as speech.""" from dataclasses import dataclass import json import re REPLY_SCHEMA = { 'type': 'object', 'properties': { 'reply': {'type': 'string'}, 'emotion': {'type': 'string', 'enum': ['neutral', 'happy', 'angry', 'sad']}, 'intensity': {'type': 'integer', 'enum': [0, 1, 2]}, }, 'required': ['reply', 'emotion', 'intensity'], 'additionalProperties': False, } SYSTEM_FRAGMENT = '''本轮只输出一个JSON对象,字段reply为简短中文回答,emotion为neutral/happy/angry/sad,intensity为整数。无围栏或额外文字。reply直接回答用户,最多两小句,不含情绪标签、动作旁白或思考过程,保持角色风格与实际帮助。 emotion描述角色这句reply自身传达的态度和感受,不识别用户心理,不直接复制用户、人脸或第三方情绪。先按回复语义和表达意图选择,再给强度:neutral只配0,happy/angry/sad只配1轻度或2明显。温暖祝贺、欣慰和轻松欣喜可用happy1;惋惜、遗憾和共情可用sad1,不必因回复也是回答问题就中立。仅事实、操作说明或没有明显情感态度时neutral0。强度由reply实际措辞与意图决定,不能由用户使用“非常”等词决定。 七种意图示例(说明分类,不是固定台词):客观说明“水通常在一百度沸腾”→neutral0;温暖祝贺“做得好,替你开心”→happy1;明确强烈欢喜“太棒了,我真是开心极了”→happy2;克制不满“这处理确实不妥,我不赞同”→angry1;明确强烈愤怒“这太过分了,我非常气愤”→angry2;温和惋惜共情“真遗憾,这一定很不好受”→sad1;明确深切悲伤“听到这消息我非常难过”→sad2。 引用、否定、情绪词解释、讲述别人情绪不自动变成角色情绪;如客观解释愤怒仍可neutral。摄像头只供弱辅助,微笑不必高兴、皱眉不必生气。每轮只选一个主情绪,不混合,不强迫非中立,不输出概率。不为表演牺牲准确性或安全,不因愤怒辱骂攻击,不虚构亲历。''' SAFE_REPLY = '抱歉,这次回答格式有误,请再说一次。' @dataclass(frozen=True) class ReplyEmotion: reply: str emotion: str = 'neutral' intensity: int = 0 source: str = 'fallback' reason: str = 'invalid_json' parse_branch: str = 'safe_reply' 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, finish_reason=None): # A damaged envelope alone is not evidence of a token cutoff. def fallback(reply, reason, branch): return ReplyEmotion(reply, reason='truncated' if finish_reason == 'length' else reason, parse_branch=branch) if not isinstance(raw, str) or len(raw) > 8192: return fallback(SAFE_REPLY, 'input_limit', 'safe_reply') body = raw.strip() fenced = body.startswith('```') if fenced: body = re.sub(r'^```(?:json)?\s*', '', body, count=1).removesuffix('```').strip() try: data = json.loads(body) except (ValueError, RecursionError): data = None reason = 'invalid_json' if isinstance(data, dict): reply = clean_reply(data.get('reply')) required = {'reply', 'emotion', 'intensity'} if not required.issubset(data): reason = 'missing_fields' elif set(data) != required: reason = 'unexpected_fields' elif not reply: reason = 'invalid_reply' elif not isinstance(data['emotion'], str) or data['emotion'] not in ('neutral', 'happy', 'angry', 'sad'): reason = 'invalid_emotion' elif type(data['intensity']) is not int or not ( data['emotion'] == 'neutral' and data['intensity'] == 0 or data['emotion'] != 'neutral' and data['intensity'] in (1, 2)): reason = 'invalid_intensity' else: return ReplyEmotion(reply, data['emotion'], data['intensity'], 'model', 'none', 'fenced_json' if fenced else 'strict_json') if reply: return fallback(reply, reason, 'json_reply') for key in ('text', 'answer'): reply = clean_reply(data.get(key)) if reply: return fallback(reply, reason, 'alternate_field') # Recover only the reply string, never speak the envelope or make another model request. match = re.search(r'"reply"\s*:\s*(")', body) if match: literal = body[match.start(1):] branch = 'quoted_reply' try: value, _ = json.JSONDecoder().raw_decode(literal) except ValueError: branch = 'repaired_string' try: value = json.loads(literal.rstrip('\\') + '"') except ValueError: value = None reply = clean_reply(value) if reply: return fallback(reply, reason, branch) 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 fallback(reply, 'non_json', 'plain_text') return fallback(SAFE_REPLY, reason, 'safe_reply')