Files
baji-vc/scripts/check-reply-structure.py
T

67 lines
4.6 KiB
Python

#!/usr/bin/env python3
"""Four bounded public compatibility calls; current Qwen and saved Doubao, no live config changes."""
from pathlib import Path
import base64,json,subprocess
root=Path(__file__).resolve().parents[1]
CORE=r'''
import json,time,httpx
from llm_provider import LLMProvider
from reply_emotion import SYSTEM_FRAGMENT,parse_reply
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字段的可朗读正文。用简短中文直接回答。\n'+SYSTEM_FRAGMENT},{'role':'user','content':prompt}]
url,headers,body=provider.request(messages,max_tokens=160)
row={'case':name}
try:
with client.stream('POST',url,headers=headers,json=body) as r:
row['http_status']=r.status_code;r.raise_for_status()
for line in r.iter_lines():
if not line.startswith('data:'):continue
data=line[5:].strip()
if data=='[DONE]':break
for choice in json.loads(data).get('choices',[]):
delta=choice.get('delta',{}).get('content') or ''
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,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':provider.structured_output,'single_system_single_request':True,'results':rows}))
raise SystemExit(0 if passed else 1)
'''
REMOTE=r'''
import tempfile,pathlib,sys,base64,os,subprocess,json
root=pathlib.Path('/home/gorios-spark-2/lan-voice')
pid=subprocess.check_output(['systemctl','--user','show','lan-voice-gateway.service','-p','MainPID','--value'],text=True).strip()
running=dict(x.split('=',1) for x in pathlib.Path('/proc/'+pid+'/environ').read_bytes().decode().split('\0') if '=' in x)
with tempfile.TemporaryDirectory(prefix='reply-structure-') as d:
for name,content in bundle.items():pathlib.Path(d,name).write_bytes(base64.b64decode(content))
code='import sys\nsys.path.insert(0,'+repr(d)+')\n'+core
qwen=subprocess.run([sys.executable,'-'],input=code,text=True,capture_output=True,timeout=70,env={**os.environ,**running})
# Existing private provider file is loaded only into a subprocess; never copied or logged.
doubao=subprocess.run(['bash','-c','set -a; source .runtime/gori-baji-llm.env; source .runtime/gori-baji-provider.env; exec .venv/bin/python -'],cwd=root,input=code,text=True,capture_output=True,timeout=70)
rows={}
for name,result in [('qwen_current',qwen),('doubao_saved',doubao)]:
try:rows[name]=json.loads(result.stdout)
except ValueError:rows[name]={'status':'failed','returncode':result.returncode,'stderr_present':bool(result.stderr)}
passed=all(r.get('status')=='passed' for r in rows.values())
print(json.dumps({'status':'passed' if passed else 'failed','results':rows,'live_configuration_changed':False,'real_weights_verified':False}))
raise SystemExit(0 if passed else 1)
'''
bundle={name:base64.b64encode((root/'gateway'/name).read_bytes()).decode() for name in ('llm_provider.py','reply_emotion.py','server_clock.py','action_reply.py')}
payload='bundle='+repr(bundle)+'\ncore='+repr(CORE)+'\n'+REMOTE
r=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=150)
if r.stdout:
data=json.loads(r.stdout);out=root/'logs/voice-investigation/reply-structure.json';out.parent.mkdir(parents=True,exist_ok=True)
if out.exists():out.with_name('reply-structure-previous.json').write_bytes(out.read_bytes())
out.write_text(json.dumps(data,indent=2)+'\n');print(json.dumps(data))
if r.stderr:print('Remote stderr present (content suppressed).')
raise SystemExit(r.returncode)