92 lines
5.4 KiB
Python
92 lines
5.4 KiB
Python
#!/usr/bin/env python3
|
|
"""Exactly four public local-Qwen requests, 160 tokens. No raw reply/keys/voice data."""
|
|
from pathlib import Path
|
|
import base64
|
|
import json
|
|
import subprocess
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
REMOTE = r'''
|
|
import asyncio, json, pathlib, ssl, subprocess, sys, tempfile, time, urllib.request
|
|
import httpx
|
|
root=pathlib.Path('/home/gorios-spark-2/lan-voice')
|
|
result={'status':'failed','paid_calls':0,'max_tokens':160,'rows':[],'device':'not_run'}
|
|
async def main():
|
|
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))
|
|
with opener.open('https://192.168.31.61:5011/health',timeout=5) as response:health=json.load(response)
|
|
if health.get('busy'):raise RuntimeError('busy_no_probe')
|
|
pid=subprocess.check_output(['systemctl','--user','show','lan-voice-gateway.service','-p','MainPID','--value'],text=True).strip()
|
|
env=dict(item.split('=',1) for item in pathlib.Path('/proc/'+pid+'/environ').read_bytes().decode().split('\0') if '=' in item)
|
|
from llm_provider import LLMProvider
|
|
from action_reply import ACTION_FRAGMENT, ExpressionPrefix, parse_action_reply
|
|
from reply_emotion import SYSTEM_FRAGMENT
|
|
provider=LLMProvider(env)
|
|
assert provider.base_url=='http://127.0.0.1:8888/v1' and provider.model=='qwen3.8-27b' and provider.structured_output=='json_schema'
|
|
cases=[('fact','七乘八等于多少?只给出结果。',False),
|
|
('dance','请跳一段舞,然后自然问我一句。',True),
|
|
('sympathy','朋友比赛落选了,请简短安慰。',False),
|
|
('negation','不要跳舞,只说你好。',True)]
|
|
async with httpx.AsyncClient(timeout=40,trust_env=False) as client:
|
|
for name,text,available in cases:
|
|
system=SYSTEM_FRAGMENT+'\n'+ACTION_FRAGMENT+'\n网关实际可用动作:'+('dance' if available else '无')
|
|
url,headers,body=provider.request([{'role':'system','content':system},{'role':'user','content':text}],max_tokens=160,action_plan=True)
|
|
parser=ExpressionPrefix(1);raw='';finish='not_provided';done=False;prepare_ms=None;first_ms=None;chunks=0
|
|
start=time.monotonic()
|
|
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 choice in data.get('choices',[]):
|
|
value=choice.get('finish_reason')
|
|
if value is not None:finish=value if value in ('stop','length','content_filter','tool_calls','function_call') else 'unknown'
|
|
delta=choice.get('delta',{}).get('content') or ''
|
|
if not delta:continue
|
|
chunks+=1
|
|
if first_ms is None:first_ms=round((time.monotonic()-start)*1000,2)
|
|
raw+=delta
|
|
if parser.feed(delta,1) is not None:prepare_ms=round((time.monotonic()-start)*1000,2)
|
|
assert len(raw)<=8192
|
|
parsed=parse_action_reply(raw,finish,available)
|
|
try:keys=list(json.loads(raw))
|
|
except ValueError:keys=[]
|
|
row={'case':name,'http_status':response.status_code,'sse_done':done,'finish_reason':finish,
|
|
'top_level_fields':keys,'source':parsed.speech.source,'emotion':parsed.speech.emotion,'intensity':parsed.speech.intensity,
|
|
'reply_chars':len(parsed.speech.reply),'action':parsed.action,'action_reason':parsed.action_reason,
|
|
'after_valid':parsed.after is not None,'chunks':chunks,'first_ms':first_ms,'prepare_ms':prepare_ms,
|
|
'complete_ms':round((time.monotonic()-start)*1000,2),'header_final_consistent':parser.consistent(parsed,1)}
|
|
result['rows'].append(row)
|
|
assert done and finish=='stop' and parsed.speech.source=='model' and parsed.action_reason=='none','schema_or_budget_failed'
|
|
assert parsed.action==('dance' if name=='dance' else 'none'),'action_semantics_failed'
|
|
result.update(status='passed',provider=provider.model,mode=provider.structured_output,zone=provider.clock.zone.key,
|
|
capability_scope='four fixed public observations; prepare preload only, final validation required')
|
|
with tempfile.TemporaryDirectory(prefix='action-schema-probe-') as folder:
|
|
import base64
|
|
for name,content in sources.items():pathlib.Path(folder,name).write_bytes(base64.b64decode(content))
|
|
sys.path.insert(0,folder)
|
|
try:asyncio.run(main())
|
|
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))
|
|
raise SystemExit(result['status']!='passed')
|
|
'''
|
|
|
|
sources = {name: base64.b64encode((ROOT/'gateway'/name).read_bytes()).decode() for name in
|
|
('llm_provider.py','server_clock.py','reply_emotion.py','action_reply.py')}
|
|
payload = 'sources='+repr(sources)+'\n'+REMOTE
|
|
run = 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=190)
|
|
if run.stdout:
|
|
report = json.loads(run.stdout)
|
|
out=ROOT/'logs/action-emotion/schema-probe.json';out.parent.mkdir(parents=True,exist_ok=True)
|
|
out.write_text(json.dumps(report,indent=2)+'\n')
|
|
print(json.dumps(report,indent=2))
|
|
if run.stderr:print('Remote stderr present; contents suppressed.')
|
|
raise SystemExit(run.returncode)
|