fix(gateway): constrain verified Qwen replies to emotion schema
This commit is contained in:
@@ -11,7 +11,7 @@ provider=LLMProvider();rows=[]
|
||||
with httpx.Client(timeout=30,trust_env=False) as client:
|
||||
for name,prompt in [('ordinary','一加一等于几?'),('happy','请用明显高兴的语气祝贺我完成公开练习。')]:
|
||||
start=time.perf_counter();first=None;raw='';finish=None
|
||||
messages=[{'role':'system','content':'以下角色设定只约束reply口述内容,旧有不输出JSON约定不约束外层结构。用简短中文直接回答。\n'+SYSTEM_FRAGMENT},{'role':'user','content':prompt}]
|
||||
messages=[{'role':'system','content':'以下角色设定只约束reply字段的可朗读正文。用简短中文直接回答。\n'+SYSTEM_FRAGMENT},{'role':'user','content':prompt}]
|
||||
url,headers,body=provider.request(messages,max_tokens=160)
|
||||
row={'case':name}
|
||||
try:
|
||||
@@ -26,14 +26,14 @@ with httpx.Client(timeout=30,trust_env=False) as client:
|
||||
if delta and first is None:first=round((time.perf_counter()-start)*1000,2)
|
||||
raw+=delta;finish=choice.get('finish_reason') or finish
|
||||
if len(raw)>8192:raise ValueError('reply bound')
|
||||
parsed=parse_reply(raw)
|
||||
parsed=parse_reply(raw,finish_reason=finish)
|
||||
row.update(source=parsed.source,emotion=parsed.emotion,intensity=parsed.intensity,reply_chars=len(parsed.reply),finish_reason=finish,first_token_ms=first)
|
||||
except Exception as error:row['error_type']=type(error).__name__
|
||||
row['elapsed_ms']=round((time.perf_counter()-start)*1000,2)
|
||||
if first is not None:row['structured_wait_ms']=round(row['elapsed_ms']-first,2)
|
||||
rows.append(row)
|
||||
passed=all(x.get('source')=='model' and x.get('finish_reason')=='stop' for x in rows)
|
||||
print(json.dumps({'status':'passed' if passed else 'failed','base_url':provider.base_url,'model_alias':provider.model,'chat_template_kwargs':provider.template_kwargs,'key_present':bool(provider.api_key),'strategy':'prompt_only_json_single_system_single_request','results':rows}))
|
||||
print(json.dumps({'status':'passed' if passed else 'failed','base_url':provider.base_url,'model_alias':provider.model,'chat_template_kwargs':provider.template_kwargs,'key_present':bool(provider.api_key),'strategy':provider.structured_output,'single_system_single_request':True,'results':rows}))
|
||||
raise SystemExit(0 if passed else 1)
|
||||
'''
|
||||
REMOTE=r'''
|
||||
|
||||
@@ -13,7 +13,7 @@ def health():
|
||||
with opener.open('https://192.168.31.61:5011/health',timeout=3) as r:return json.load(r)
|
||||
def atomic(path,content,mode):
|
||||
path.parent.mkdir(parents=True,exist_ok=True)
|
||||
tmp=path.with_name(path.name+'.v051.tmp');tmp.write_bytes(content);tmp.chmod(mode);tmp.replace(path)
|
||||
tmp=path.with_name(path.name+'.gateway.tmp');tmp.write_bytes(content);tmp.chmod(mode);tmp.replace(path)
|
||||
def live_hashes():return {name:digest(root/name) for name in deploy_files}
|
||||
original=live_hashes()
|
||||
if original!=expected:
|
||||
@@ -30,7 +30,7 @@ private_hashes={str(p):digest(p) for p in private_files}
|
||||
def relation_unchanged():
|
||||
return subprocess.check_output(['systemctl','--user','cat',unit])==unit_text and all(digest(Path(p))==h for p,h in private_hashes.items())
|
||||
if apply and health().get('busy'): raise RuntimeError('gateway_busy_no_restart')
|
||||
with tempfile.TemporaryDirectory(prefix='voice-v051-stage-') as folder:
|
||||
with tempfile.TemporaryDirectory(prefix='voice-gateway-stage-') as folder:
|
||||
stage=Path(folder)
|
||||
for name,content in bundle.items():
|
||||
path=stage/name;path.parent.mkdir(parents=True,exist_ok=True);path.write_bytes(base64.b64decode(content))
|
||||
@@ -42,9 +42,9 @@ with tempfile.TemporaryDirectory(prefix='voice-v051-stage-') as folder:
|
||||
if live_hashes()!=original:raise RuntimeError('source_changed_during_tests')
|
||||
if not relation_unchanged():raise RuntimeError('environment_or_unit_changed_during_tests')
|
||||
if health().get('busy'):raise RuntimeError('gateway_busy_after_tests_no_restart')
|
||||
backup=root/'.runtime/backups'/time.strftime('voice-v051-%Y%m%d-%H%M%S');backup.mkdir(parents=True,mode=0o700)
|
||||
backup=root/'.runtime/backups'/time.strftime('voice-gateway-%Y%m%d-%H%M%S');backup.mkdir(parents=True,mode=0o700)
|
||||
# Save all actual runtime Python sources/tests, modes, plus unit/env privately. No logs/history/audio copied.
|
||||
for path in list(root.glob('*.py'))+list((root/'tests').glob('*.py')):
|
||||
for path in list(root.glob('*.py'))+list((root/'tests').glob('*.py'))+list((root/'personas').glob('*.json')):
|
||||
dst=backup/path.relative_to(root);dst.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(path,dst)
|
||||
for i,path in enumerate(private_files):
|
||||
dst=backup/'private'/str(i);dst.parent.mkdir(parents=True,exist_ok=True,mode=0o700);shutil.copy2(path,dst)
|
||||
@@ -86,12 +86,12 @@ def main():
|
||||
source=root/'gateway';manifest=json.loads((source/'SOURCE_MANIFEST.json').read_text())
|
||||
baseline=manifest.get('deployment_baseline',manifest['provider_baseline'])['files']
|
||||
files=sorted(set(baseline)|{p.relative_to(source).as_posix() for p in source.glob('*.py')}|{p.relative_to(source).as_posix() for p in (source/'tests').glob('*.py')})
|
||||
assert all(n.endswith('.py') and not Path(n).is_absolute() and '..' not in Path(n).parts for n in files)
|
||||
public_personas={'personas/lvbu.lorebook.json','personas/yangmi.lorebook.json'}
|
||||
assert all((n.endswith('.py') or n in public_personas) and not Path(n).is_absolute() and '..' not in Path(n).parts for n in files)
|
||||
expected={name:baseline.get(name) for name in files}
|
||||
record=root/'logs/voice-investigation/gateway-emotion-deploy.json'
|
||||
if record.exists():
|
||||
previous=json.loads(record.read_text())
|
||||
if previous.get('applied'):expected=previous['hashes'];assert set(expected)==set(files)
|
||||
# SOURCE_MANIFEST is the reviewed expected live baseline. Old ignored records
|
||||
# must not silently replace it when the deployment whitelist changes.
|
||||
bundle={}
|
||||
for path in source.rglob('*'):
|
||||
name=path.relative_to(source).as_posix()
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Bounded public Qwen/SGLang schema probe; never print/store generated content or credentials."""
|
||||
import argparse
|
||||
import json
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / 'gateway'))
|
||||
from reply_emotion import REPLY_SCHEMA
|
||||
|
||||
REMOTE = r'''
|
||||
import asyncio, json, pathlib, ssl, subprocess, time, urllib.request
|
||||
import httpx
|
||||
from llm_provider import LLMProvider
|
||||
from reply_emotion import SYSTEM_FRAGMENT, parse_reply
|
||||
from persona_resolver import resolve_persona
|
||||
root=pathlib.Path('/home/gorios-spark-2/lan-voice')
|
||||
result={'status':'failed','public_samples':samples,'rows':[],'real_phone_playback':'not_tested'}
|
||||
async def probe():
|
||||
ctx=ssl.create_default_context(cafile=str(root/'.runtime/gateway-cert.pem'))
|
||||
op=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=ctx))
|
||||
with op.open('https://192.168.31.61:5011/health',timeout=5) as response: health=json.load(response)
|
||||
if health.get('busy'):raise RuntimeError('gateway_busy_probe_not_started')
|
||||
pid=subprocess.check_output(['systemctl','--user','show','lan-voice-gateway.service','-p','MainPID','--value'],text=True).strip()
|
||||
env=dict(x.split('=',1) for x in pathlib.Path('/proc/'+pid+'/environ').read_bytes().decode().split('\0') if '=' in x)
|
||||
p=LLMProvider(env)
|
||||
assert p.base_url=='http://127.0.0.1:8888/v1' and p.model=='qwen3.8-27b' and p.template_kwargs=={'enable_thinking':False}, 'provider_changed_probe_not_started'
|
||||
profile=json.loads((root/'.runtime/active_profile.json').read_text());persona=profile.get('persona','default')
|
||||
voice_ids=[]
|
||||
if persona in ('lvbu','yangmi_fiction'):voice_ids=[json.loads((root/'.runtime/personas'/f'{persona}.json').read_text())['voice_id']]
|
||||
rules=resolve_persona(root,persona,voice_ids)['rules']
|
||||
if preflight:system='以下角色设定只约束reply字段的口述内容;其中旧有不输出JSON等格式约定不约束本轮外层结构。\n'+rules+'\n\n'+SYSTEM_FRAGMENT
|
||||
else:system='以下角色设定只约束reply字段的可朗读正文。\n'+rules+'\n\n'+SYSTEM_FRAGMENT
|
||||
public=['请简短说一声你好。','公开合成测试:朋友考试通过了,表达轻度高兴,简短祝贺。']
|
||||
async with httpx.AsyncClient(trust_env=False,timeout=30) as client:
|
||||
for index,text in enumerate(public[:samples]):
|
||||
url,headers,body=p.request([{'role':'system','content':system},{'role':'user','content':text}],max_tokens=160)
|
||||
if preflight:body['response_format']={'type':'json_schema','json_schema':{'name':'role_reply','strict':True,'schema':schema}}
|
||||
else:assert body.get('response_format')=={'type':'json_schema','json_schema':{'name':'role_reply','strict':True,'schema':schema}}, 'schema_not_enabled'
|
||||
start=time.perf_counter();raw='';finish='not_provided';usage={};done=False;first=None;chunks=0
|
||||
async with client.stream('POST',url,headers=headers,json=body) as response:
|
||||
response.raise_for_status()
|
||||
async for line in response.aiter_lines():
|
||||
if not line.startswith('data:'):continue
|
||||
payload=line[5:].strip()
|
||||
if payload=='[DONE]':done=True;break
|
||||
data=json.loads(payload)
|
||||
for k,v in (data.get('usage') or {}).items():
|
||||
if k in ('prompt_tokens','completion_tokens','total_tokens') and type(v) is int:usage[k]=v
|
||||
for choice in data.get('choices',[]):
|
||||
if choice.get('finish_reason') is not None:finish=choice['finish_reason'] if choice['finish_reason'] in ('stop','length','content_filter','tool_calls','function_call') else 'unknown'
|
||||
delta=choice.get('delta',{}).get('content') or ''
|
||||
if delta:
|
||||
if first is None:first=round((time.perf_counter()-start)*1000,2)
|
||||
raw+=delta;chunks+=1
|
||||
assert len(raw)<=8192,'output_limit'
|
||||
elapsed=round((time.perf_counter()-start)*1000,2)
|
||||
parsed=parse_reply(raw,finish_reason=finish)
|
||||
row={'sample':index+1,'http_status':response.status_code,'sse_done':done,'chunks':chunks,'envelope_chars':len(raw),'reply_chars':len(parsed.reply),'emotion':parsed.emotion,'intensity':parsed.intensity,'source':parsed.source,'reason':parsed.reason,'parse_branch':parsed.parse_branch,'finish_reason':finish,'usage':usage,'max_tokens':160,'first_content_ms':first,'complete_ms':elapsed,'structured_wait_ms':round(elapsed-(first or elapsed),2)}
|
||||
result['rows'].append(row)
|
||||
assert done and finish=='stop' and parsed.source=='model' and parsed.parse_branch=='strict_json' and 0<len(parsed.reply)<=160, 'schema_validation_failed'
|
||||
result.update(status='passed',provider='qwen3.8-27b',thinking=False,format_mode='json_schema',persona=persona)
|
||||
try:asyncio.run(probe())
|
||||
except Exception as error:
|
||||
result['error_type']=type(error).__name__
|
||||
if isinstance(error,RuntimeError):result['reason']=str(error)
|
||||
if isinstance(error,httpx.HTTPStatusError):result['http_status']=error.response.status_code
|
||||
print(json.dumps(result,ensure_ascii=False))
|
||||
raise SystemExit(result['status']!='passed')
|
||||
'''
|
||||
|
||||
def main():
|
||||
parser=argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--preflight',action='store_true',help='Validate explicit schema before provider implementation is deployed')
|
||||
parser.add_argument('--samples',type=int,choices=(1,2),default=1)
|
||||
args=parser.parse_args()
|
||||
payload='schema='+repr(REPLY_SCHEMA)+'\npreflight='+repr(args.preflight)+'\nsamples='+repr(args.samples)+'\n'+REMOTE
|
||||
result=subprocess.run(['ssh','-o','BatchMode=yes','-o','ConnectTimeout=5','gorios-spark-2@192.168.31.61','cd /home/gorios-spark-2/lan-voice && exec .venv/bin/python -'],input=payload.encode(),capture_output=True,timeout=85)
|
||||
if result.stdout:
|
||||
data=json.loads(result.stdout)
|
||||
target=ROOT/'logs/structure-output-fix'/('schema-preflight.json' if args.preflight else 'schema-deployed.json')
|
||||
target.parent.mkdir(parents=True,exist_ok=True)
|
||||
target.write_text(json.dumps(data,ensure_ascii=False,indent=2)+'\n')
|
||||
print(json.dumps(data,ensure_ascii=False,indent=2))
|
||||
if result.stderr:print('Remote stderr present; unexpected contents suppressed.')
|
||||
raise SystemExit(result.returncode)
|
||||
|
||||
if __name__=='__main__':main()
|
||||
@@ -37,6 +37,8 @@ async def probe():
|
||||
if event['type']=='hello': break
|
||||
summary['face_context_supported']=event.get('context_face_cue_version')
|
||||
summary['reply_emotion_supported']=event.get('reply_emotion_version')
|
||||
summary['llm_structured_output']=event.get('llm_structured_output')
|
||||
assert summary['llm_structured_output']=='json_schema', 'live schema mode missing'
|
||||
assert summary['reply_emotion_supported']==1
|
||||
if after: assert summary['face_context_supported']==1, 'face protocol not advertised'
|
||||
await ws.send(json.dumps({'type':'listen','mode':'manual','state':'start','barge_in':False}))
|
||||
@@ -98,7 +100,7 @@ async def probe():
|
||||
if kind=='voice.metrics': summary['tts_requests']=event.get('tts_request_count')
|
||||
if kind=='metrics':
|
||||
values=event.get('values',{})
|
||||
summary['backend_metrics']={key:values.get(key) for key in ('stt_ms','llm_first_token_ms','llm_first_body_ms','structured_wait_ms','reply_parse_ms','llm_finished_ms','tts_first_pcm_ms','capture_to_first_pcm_ms','total_ms','tts_request_count','face_cue_used','reply_emotion_reason','reply_parse_branch','reply_emotion','reply_intensity','llm_finish_reason','llm_usage','llm_max_tokens')}
|
||||
summary['backend_metrics']={key:values.get(key) for key in ('stt_ms','llm_first_token_ms','llm_first_body_ms','structured_wait_ms','reply_parse_ms','llm_finished_ms','tts_first_pcm_ms','capture_to_first_pcm_ms','total_ms','tts_request_count','face_cue_used','reply_emotion_reason','reply_parse_branch','reply_emotion','reply_intensity','llm_finish_reason','llm_usage','llm_max_tokens','llm_structured_output')}
|
||||
summary['segments']=[{key:s.get(key) for key in ('audio_seconds','total_ms','rtf','max_chunk_interarrival_ms')} for s in values.get('tts_segments',[])]
|
||||
if kind=='error': raise RuntimeError('gateway_backend_error')
|
||||
if kind=='tts' and event.get('state')=='stop':
|
||||
@@ -117,6 +119,7 @@ async def probe():
|
||||
while json.loads(await asyncio.wait_for(ws.recv(),5)).get('type')!='pong': pass
|
||||
summary['invalid_face_control_survived']=True
|
||||
assert summary['emotion_count']==1 and summary.get('tts_input_matches_body') and summary.get('tts_requests')==1
|
||||
assert summary['structured_model_output'], 'live structured reply fell back'
|
||||
assert summary['pcm_peak']>327, 'no voiced PCM amplitude'
|
||||
summary['pcm_rms']=round(math.sqrt(summary.pop('pcm_square')/(summary['downlink_bytes']//2)),2)
|
||||
summary['status']='passed'
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Restore only exact v050-deployed files, from its own backup; no model/container actions."""
|
||||
"""Restore only exact deployed files, from their own backup; no model/container actions."""
|
||||
import json,subprocess
|
||||
from pathlib import Path
|
||||
REMOTE=r'''
|
||||
@@ -8,7 +8,7 @@ from pathlib import Path
|
||||
root=Path('/home/gorios-spark-2/lan-voice');backup=Path(record['backup']).resolve()
|
||||
assert backup.is_relative_to((root/'.runtime/backups').resolve())
|
||||
for name,expected in record['hashes'].items():
|
||||
assert name.endswith('.py') and not Path(name).is_absolute() and '..' not in Path(name).parts
|
||||
assert (name.endswith('.py') or name in ('personas/lvbu.lorebook.json','personas/yangmi.lorebook.json')) and not Path(name).is_absolute() and '..' not in Path(name).parts
|
||||
assert hashlib.sha256((root/name).read_bytes()).hexdigest()==expected, 'concurrent source change: refusing rollback'
|
||||
ctx=ssl.create_default_context(cafile=str(root/'.runtime/gateway-cert.pem'))
|
||||
opener=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=ctx))
|
||||
@@ -20,6 +20,9 @@ metadata=json.loads((backup/'metadata.json').read_text())
|
||||
assert hashlib.sha256(subprocess.check_output(['systemctl','--user','cat','lan-voice-gateway.service'])).hexdigest()==metadata['unit_sha256'], 'unit changed: refusing rollback'
|
||||
for name,row in metadata['private_files'].items():
|
||||
assert hashlib.sha256(Path(name).read_bytes()).hexdigest()==row['sha256'], 'private environment changed: refusing rollback'
|
||||
assert not health().get('busy'), 'busy before restore: refusing restart'
|
||||
for name,expected in record['hashes'].items():
|
||||
assert hashlib.sha256((root/name).read_bytes()).hexdigest()==expected, 'source changed before restore'
|
||||
for name,present in manifest.items():
|
||||
path=root/name
|
||||
if present:
|
||||
|
||||
Reference in New Issue
Block a user