76 lines
3.9 KiB
Python
76 lines
3.9 KiB
Python
"""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'
|
||
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')
|