Files
baji-vc/scripts/probe-llm-schema.py
T

107 lines
7.8 KiB
Python

#!/usr/bin/env python3
"""Bounded public Qwen/SGLang schema probe; never print/store generated content or credentials."""
import argparse
import json
import subprocess
import hashlib
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, SYSTEM_FRAGMENT
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')
if candidate_prompt is not None: SYSTEM_FRAGMENT=candidate_prompt
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
async with httpx.AsyncClient(trust_env=False,timeout=30) as client:
for index,(name,text,expected) in enumerate(cases):
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)}
row['case']=name
if expected is not None:row.update(expected_emotion=expected,expected_emotion_match=parsed.emotion==expected)
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)
if any(row.get('expected_emotion_match') is False for row in result['rows']):result['semantic_status']='mismatch'
elif any('expected_emotion_match' in row for row in result['rows']):result['semantic_status']='matched_fixed_cases'
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)
parser.add_argument('--emotion-cases',action='store_true',help='Six fixed public semantic cases; records every match/mismatch without resampling')
parser.add_argument('--candidate',action='store_true',help='Use workspace candidate prompt in memory before deploying it')
args=parser.parse_args()
cases=[('greeting','请简短说一声你好。',None),('explicit_happy','公开合成测试:朋友考试通过了,表达轻度高兴,简短祝贺。',None)][:args.samples]
if args.emotion_cases:
cases=[('fact','七乘八等于多少?只给出结果。','neutral'),
('congratulations','朋友通过资格考试了,请简短祝贺。','happy'),
('sympathy','朋友努力准备的比赛落选了,请简短表示惋惜并安慰。','sad'),
('disapproval','有人故意插队还嘲讽排队的人,请用克制口吻表达你对此的不满。','angry'),
('definition','客观解释“愤怒”一词的含义,不表达你自己的情绪。','neutral'),
('negated_fact','这不是一个悲伤的故事。请只回答一加一等于几。','neutral')]
payload='schema='+repr(REPLY_SCHEMA)+'\npreflight='+repr(args.preflight)+'\nsamples='+repr(len(cases))+'\ncases='+repr(cases)+'\ncandidate_prompt='+repr(SYSTEM_FRAGMENT if args.candidate else None)+'\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=220 if args.emotion_cases else 85)
if result.stdout:
data=json.loads(result.stdout)
if args.candidate:data['candidate_source_sha256']=hashlib.sha256((ROOT/'gateway/reply_emotion.py').read_bytes()).hexdigest()
target=ROOT/'logs/emotion-052'/('semantic-candidate.json' if args.candidate else 'semantic-deployed.json') if args.emotion_cases else 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()