#!/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