155 lines
7.0 KiB
Python
155 lines
7.0 KiB
Python
"""Single-call action envelope and structural incremental expression preparation.
|
||
|
||
Preparation is speculative preload only. Final strict validation is authoritative.
|
||
No partial JSON regex, repaired header or nested after-action expression is published.
|
||
"""
|
||
from copy import deepcopy
|
||
from dataclasses import dataclass, replace
|
||
import json
|
||
|
||
from reply_emotion import REPLY_SCHEMA, ReplyEmotion, SAFE_REPLY, clean_reply, parse_reply
|
||
|
||
EXPRESSION_SCHEMA = deepcopy(REPLY_SCHEMA)
|
||
ACTION_SCHEMA = {
|
||
'type': 'object',
|
||
'properties': {
|
||
'emotion': deepcopy(REPLY_SCHEMA['properties']['emotion']),
|
||
'intensity': deepcopy(REPLY_SCHEMA['properties']['intensity']),
|
||
'reply': {'type': 'string'},
|
||
'action': {'type': 'string', 'enum': ['none', 'dance']},
|
||
'after_action': {'anyOf': [{'type': 'null'}, EXPRESSION_SCHEMA]},
|
||
},
|
||
'required': ['emotion', 'intensity', 'reply', 'action', 'after_action'],
|
||
'additionalProperties': False,
|
||
}
|
||
|
||
ACTION_FRAGMENT = '''外层字段按emotion、intensity、reply、action、after_action顺序输出,只有这五个字段。
|
||
reply最多20个汉字;action只能none或dance,非表演请求、否定、引用不触发表演。动作可用性以本轮网关摘要为准,不选择文件或URL;不可用时不能假装已跳舞。
|
||
action=none时after_action=null。action=dance时reply是简短表演前回应;after_action必须是同一次生成的{reply,emotion,intensity},reply最多20个汉字,表演结束后自然发问或接续对话,句式自然多样,不能断言未来用户反应、具体舞步或准确当前时刻。后续表达只属于后续发言。角色表情视觉仅slightly,不通过大张嘴/哭泣表现。'''
|
||
|
||
|
||
def unique_object(pairs):
|
||
result = {}
|
||
for key, value in pairs:
|
||
if key in result:
|
||
raise ValueError('duplicate_key')
|
||
result[key] = value
|
||
return result
|
||
|
||
|
||
def expression(emotion, intensity):
|
||
return isinstance(emotion, str) and emotion in ('neutral', 'happy', 'angry', 'sad') and \
|
||
type(intensity) is int and (intensity == 0 if emotion == 'neutral' else intensity in (1, 2))
|
||
|
||
|
||
@dataclass(frozen=True)
|
||
class ActionReply:
|
||
speech: ReplyEmotion
|
||
action: str = 'none'
|
||
after: ReplyEmotion | None = None
|
||
action_reason: str = 'unavailable'
|
||
|
||
|
||
def parse_action_reply(raw, finish_reason=None, available=False):
|
||
try:
|
||
if not isinstance(raw, str) or len(raw) > 8192:
|
||
raise ValueError('input_limit')
|
||
data = json.loads(raw, object_pairs_hook=unique_object)
|
||
if not isinstance(data, dict):
|
||
raise ValueError('not_object')
|
||
except (ValueError, RecursionError) as error:
|
||
# Legacy safe recovery is for speech only. No action survives a damaged envelope.
|
||
speech = parse_reply(raw, finish_reason)
|
||
if str(error) == 'duplicate_key':
|
||
speech = replace(speech, emotion='neutral', intensity=0, source='fallback', reason='duplicate_key')
|
||
return ActionReply(speech, action_reason='invalid_envelope')
|
||
base = {key: data[key] for key in ('reply', 'emotion', 'intensity') if key in data}
|
||
speech = parse_reply(json.dumps(base), finish_reason)
|
||
if set(data) != set(ACTION_SCHEMA['required']):
|
||
return ActionReply(speech, action_reason='envelope_fields')
|
||
if data['action'] == 'none' and data['after_action'] is None:
|
||
return ActionReply(speech, action_reason='none')
|
||
if data['action'] != 'dance':
|
||
return ActionReply(speech, action_reason='invalid_action')
|
||
if not available:
|
||
# An unsupported action promise must not be spoken to an old/unprepared client.
|
||
return ActionReply(ReplyEmotion('当前还没有可用的舞蹈,可以先聊聊天。', reason='action_unavailable'),
|
||
action_reason='unavailable')
|
||
after = data['after_action']
|
||
if not isinstance(after, dict) or set(after) != {'reply', 'emotion', 'intensity'}:
|
||
return ActionReply(speech, action_reason='invalid_after')
|
||
parsed = parse_reply(json.dumps(after), finish_reason)
|
||
if speech.source != 'model' or parsed.source != 'model' or finish_reason == 'length':
|
||
return ActionReply(speech, action_reason='invalid_or_truncated')
|
||
return ActionReply(speech, 'dance', parsed, 'none')
|
||
|
||
|
||
class ExpressionPrefix:
|
||
"""Accept exactly complete top-level header values + their delimiters, in order.
|
||
|
||
Must be gated by independently probed strict schema capability. Even there a
|
||
candidate never changes visible emotion; final mismatch cancels preparation.
|
||
"""
|
||
def __init__(self, turn):
|
||
self.turn = turn
|
||
self.raw = ''
|
||
self.candidate = None
|
||
self.invalid = False
|
||
|
||
def feed(self, chunk, current_turn):
|
||
if self.invalid or current_turn != self.turn:
|
||
self.invalid = True
|
||
return None
|
||
self.raw += chunk
|
||
if len(self.raw) > 8192:
|
||
self.invalid = True
|
||
return None
|
||
decoder = json.JSONDecoder(object_pairs_hook=unique_object)
|
||
text = self.raw.lstrip()
|
||
if not text.startswith('{'):
|
||
if text: self.invalid = True
|
||
return None
|
||
pos = 1
|
||
found = {}
|
||
for expected in ('emotion', 'intensity'):
|
||
try:
|
||
while pos < len(text) and text[pos].isspace(): pos += 1
|
||
key, pos = decoder.raw_decode(text, pos)
|
||
if key != expected:
|
||
self.invalid = True
|
||
return None
|
||
while pos < len(text) and text[pos].isspace(): pos += 1
|
||
if pos == len(text): return None
|
||
if text[pos] != ':':
|
||
self.invalid = True
|
||
return None
|
||
pos += 1
|
||
while pos < len(text) and text[pos].isspace(): pos += 1
|
||
value, pos = decoder.raw_decode(text, pos)
|
||
while pos < len(text) and text[pos].isspace(): pos += 1
|
||
if pos == len(text): return None
|
||
if text[pos] != ',':
|
||
self.invalid = True
|
||
return None
|
||
pos += 1
|
||
found[key] = value
|
||
except (ValueError, RecursionError):
|
||
return None # A split escape/number/string may become valid on next chunk.
|
||
if not expression(found['emotion'], found['intensity']):
|
||
self.invalid = True
|
||
return None
|
||
candidate = (found['emotion'], found['intensity'])
|
||
if self.candidate is None:
|
||
self.candidate = candidate
|
||
return candidate
|
||
return None
|
||
|
||
def consistent(self, result, current_turn):
|
||
try:
|
||
obj = json.loads(self.raw, object_pairs_hook=unique_object)
|
||
valid = isinstance(obj, dict) and set(obj) == set(ACTION_SCHEMA['required'])
|
||
except (ValueError, RecursionError):
|
||
valid = False
|
||
return valid and not self.invalid and current_turn == self.turn and result.speech.source == 'model' and \
|
||
self.candidate == (result.speech.emotion, result.speech.intensity)
|