feat: merge reply emotions while preserving configurable Qwen/Doubao provider

This commit is contained in:
zenord
2026-10-12 10:57:14 +08:00
parent 19a7adccd9
commit d43c7d4e80
36 changed files with 1264 additions and 98 deletions
+9
View File
@@ -16,3 +16,12 @@ This directory contains the actual deployed SPARK-2 source, not just an Android-
8. Verify HTTPS health and authorized Origin/auth/hello/history, then run one bounded public-sample protocol check. Real Android speaker playback still needs a real phone; nonempty backend PCM does not prove audible output.
The v0.4.0 repair/context protocol and evidence boundaries are documented in `../docs/VOICE_REPAIR_040.md`. Archive and future deployments use this workspace's scripts with hash, backup, tests and busy checks. Archiving itself does not deploy or restart anything.
The 0.5.0 canonical source adds `reply_emotion.py`: one-system structured provider reply, validated one-turn role expression and reply-only speech/history. See `../docs/REPLY_EMOTION_050.md`. `scripts/deploy-gateway-source.py` in the repository root tests this complete source tree, hash-fences deployed modules, backs up and restarts only the gateway. Use that script for current releases; historical `backend/gateway.patch` is not the current restore source. `SOURCE_MANIFEST.json` includes current hashes and retained original provenance; a legacy 0.7.1 health version does not advertise feature completeness, so inspect hello capabilities.
`llm_provider.py` preserves the configurable OpenAI-compatible provider interface: `LAN_LLM_BASE_URL`, `LAN_LLM_MODEL`, private `LAN_LLM_API_KEY` (Authorization header only), and optional JSON-object `LAN_LLM_CHAT_TEMPLATE_KWARGS`. Missing configuration defaults to local `http://127.0.0.1:8888/v1`, `qwen3.8-27b`, thinking disabled. Non-Qwen model defaults omit Qwen kwargs; explicit kwargs stay local to that provider. The provider's original default budget is 64; the structured dialogue explicitly requests 160. There is no automatic failover or retry. Doubao's `doubao-seed-2-1-pro` is a LiteLLM alias, not evidence of actual model weights.
`SOURCE_MANIFEST.json.provider_baseline` records the latest observed SPARK2 hashes before this merge, including gateway `d088bedcf5c0accd4712e06202f6ced8ab155aad57a5b05683724efa346326ce`. Deployment fences against these hashes, not the superseded historical patch. Historical `scripts/deploy-gateway.py` is disabled. The existing unit and private environment loading relationships are backed up only on the server and checked unchanged. All Python sources/tests and original modes are backed up; only gateway is restarted after isolated tests and repeated source/busy checks. Use `scripts/rollback-gateway-source.py` for this exact deployment.
Portable archive checks skip only the omitted Silero artifact. On the existing server, run `python scripts/check-archive.py --vad-model /absolute/path/to/models/silero_vad.onnx` for the full suite, with checksum verification and an isolated read-only artifact link. This never downloads or changes a model or online service.
+115 -7
View File
@@ -1,7 +1,7 @@
{
"baseline_android_commit": "9b428fb76ffa1468aa46124b33d9c598cf3740d8",
"source": "SPARK-2 deployed lan-voice gateway",
"code_version": "0.7.1",
"code_version": "0.7.1 (legacy health version; reply.emotion version 1 capability)",
"python": "3.12.3",
"machine": "aarch64",
"scope": "whitelisted source only; no runtime/models/credentials",
@@ -32,9 +32,10 @@
"bytes": 2997
},
"gateway.py": {
"source": "gateway.py",
"sha256": "725577a378b688c24519ab2a0a9dfdb48723f365309e7ccccc9fc1de26c2894f",
"bytes": 38598
"source": "workspace:gateway/gateway.py",
"sha256": "d9215f99339de0667e830fbd4d3bff80ac5a61c85630cc4ecadcb52a4c33a0e5",
"bytes": 37391,
"upstream_sha256": "d088bedcf5c0accd4712e06202f6ced8ab155aad57a5b05683724efa346326ce"
},
"guest_sessions.py": {
"source": "guest_sessions.py",
@@ -117,9 +118,10 @@
"bytes": 2206
},
"tests/test_continuity.py": {
"source": "tests/test_continuity.py",
"sha256": "6dd818484a064dc3fc9efe5ca71cc11ffcd3a0dcc45ea4185065732dab0289cc",
"bytes": 2769
"source": "workspace:gateway/tests/test_continuity.py",
"sha256": "d8390238f390463a98f12b9909bb5846be65f5b6dc1b21b94338b4cd75aaafae",
"bytes": 2786,
"upstream_sha256": "6dd818484a064dc3fc9efe5ca71cc11ffcd3a0dcc45ea4185065732dab0289cc"
},
"tests/test_debug.py": {
"source": "tests/test_debug.py",
@@ -235,6 +237,112 @@
"source": "deployed interpreter distribution metadata",
"sha256": "26fec2a2814c6b52cc50015e3b838a4c42c257b495db66482f65e33c7207f90c",
"bytes": 5539
},
".gitignore": {
"source": "workspace:gateway/.gitignore",
"sha256": "7e416b444fb60e87e974827b31a18a16e9a519a3a5bd38e972b6e3c079784b37",
"bytes": 115
},
"README.md": {
"source": "workspace:gateway/README.md",
"sha256": "808a77916a8ba477cd6d95ae255cc661239c97031760d83fe38ea43c571deb6d",
"bytes": 6666,
"upstream_sha256": "799bc84308eb17d58987c5bee8ce3cf7617b4c52169d9307d344ac7d9996b6c5"
},
"config/active_profile.json.example": {
"source": "workspace:gateway/config/active_profile.json.example",
"sha256": "459f6ecbb0b431614eba68d19af0c792eaedc27aadd67d44a547900e78d78006",
"bytes": 82
},
"config/personas/lvbu.json.example": {
"source": "workspace:gateway/config/personas/lvbu.json.example",
"sha256": "8215a424addcc03a108c130fe91892ce1de78a122565ac9fdde0d986661c3c83",
"bytes": 53
},
"config/personas/yangmi_fiction.json.example": {
"source": "workspace:gateway/config/personas/yangmi_fiction.json.example",
"sha256": "0a959b34bb824b93314db01e722d6d4d445ad9dacd047a2f468706bcff2f0fe9",
"bytes": 55
},
"deploy/gateway.service.example": {
"source": "workspace:gateway/deploy/gateway.service.example",
"sha256": "9cbb5fcbf3f5df5c51d8b5d5020764e101903bc71d3d95ea10f6d1e006e7fe4f",
"bytes": 570
},
"env.example": {
"source": "workspace:gateway/env.example",
"sha256": "ec703e599d66f6848f7a4415da851a87c8446dd92805a8ce83e46bd690502367",
"bytes": 796,
"upstream_sha256": "d92e60812f49b02f3b0582d8b3dee03eb51cfca6dba77d9468a3ffddfce32499"
},
"pytest.ini": {
"source": "workspace:gateway/pytest.ini",
"sha256": "bc43448d7cfda3a84a240f9f4d6799b27ad0f2c6d4525dcfed577d14fccb1253",
"bytes": 144
},
"reply_emotion.py": {
"source": "workspace:gateway/reply_emotion.py",
"sha256": "488fbd24ff1ce7d3d4ab92257c8ccabafe24fc857e11c8486f54fa689276a565",
"bytes": 3114
},
"scripts/check-archive.py": {
"source": "workspace:gateway/scripts/check-archive.py",
"sha256": "6b5463e16b2cc68e4ef6e0c5cf8582fe18cc58df9d2ab63122153a428677af45",
"bytes": 2878,
"upstream_sha256": "e86ad90244932543fd653ed07e158cf96dba7c61e7945685c9c98bd044c41e5a"
},
"tests/test_gateway_emotion.py": {
"source": "workspace:gateway/tests/test_gateway_emotion.py",
"sha256": "fc01e9319263b93adb1cc93904d23a13a25965ddb0fcfbd9c3e14e39f4cf52a5",
"bytes": 4589,
"upstream_sha256": "86f22211e753e4b5ebfa11266e2e33eb2ea6b85707fbe8a988be6b8ff05f3f75"
},
"tests/test_reply_emotion.py": {
"source": "workspace:gateway/tests/test_reply_emotion.py",
"sha256": "324fdaf55b501a31af129d41e9cf459f741ff0636818a6c628657dfde3fa6344",
"bytes": 2701,
"upstream_sha256": "e45ccda640ef758fcb925d53804071349bdc8fb9f43ee1f63d1afb2ee3f238f5"
},
"llm_provider.py": {
"source": "workspace:gateway/llm_provider.py",
"sha256": "56ce6c1a4a647dea6ef86a83615f03db3a4397ebb3fa800b7fa655147d4f9978",
"bytes": 1471,
"upstream_sha256": "7d853adbe79f5f861a36894a9dfa28aa553d3eabea4db4c87a5fb4c319818ef1"
},
"tests/test_llm_provider.py": {
"source": "workspace:gateway/tests/test_llm_provider.py",
"sha256": "45404653daa71a006a90852b2f07f00cac608bd7311dd5ea850da0c1a3e52940",
"bytes": 5601,
"upstream_sha256": "6a8bd33679d68899c2a978bf4de672578517494c613b8e77d275c6207de3285b"
}
},
"archive_baseline_commit": "19a7adccd9322986eb0646b165b9ce1cf2650cf2",
"workspace_release": "0.5.0",
"provider_baseline": {
"source": "SPARK2 whitelist observed 2026-10-12",
"files": {
"app.py": "d6520894dfbe035f64b1984aae15976db4df0e7e720195c81d3bf483b240056f",
"protocol.py": "d9f522d958935200002e56024949a12b71eb89b3f3241635c5c307b798ee71c5",
"gateway.py": "d088bedcf5c0accd4712e06202f6ced8ab155aad57a5b05683724efa346326ce",
"tests_fake.py": "9a40f1948352f69f1dd20f8514baef58ae3d11eec240e1d2324d8990bad915d8",
"history.py": "2cf8b006bf486a03e038a69daa860ebb71a86989161cf6a7ea610114177a249f",
"vad.py": "3718ff9b296b2bba447100af520a631f221dcbfa322dd564cdc5809fb3675f23",
"persona_resolver.py": "deb33b4f4c17792fa5a6837362d5b29173e60a57bb993b61363bd4882d66d5de",
"tts_debug.py": "d7b31b98a7f8ab688981873ef81decdf0b2f0167113c9103df039b7b24c9ccf2",
"guest_sessions.py": "cc082fdb6c2ff7f5a41361ffe9ea2a53ebb944ee37354f65119405ad7a521c82",
"llm_provider.py": "7d853adbe79f5f861a36894a9dfa28aa553d3eabea4db4c87a5fb4c319818ef1",
"face_context.py": "01abfc214ebb4e979faf9430166eccae9af37df911d36da5435f907769e7e31a",
"segmentation.py": "562ffc6e06f5b9f9072860b588feae3a5d7cd6eaa8577ac928d770071b06978d",
"tests/test_debug.py": "26f9e374354b714ab1a03b56af90bcbf32135711dc4f26e2c53eaa90c7f02ddd",
"tests/test_gateway.py": "f22aa98f3d6f62a2949a9047ec97e6dd686cac807d989a314a95deca718a3104",
"tests/test_history.py": "fc13a69811cfc4f4acf265ea9e0cdd67d566358ebe9b9b53cae76197db8bce78",
"tests/test_guests.py": "6bc531f1bff85b8ea550bc88c634726531a1ef241ba5c861dbb8c963adf31c35",
"tests/test_vad.py": "bff64c0aafa05c085af7c1c9418244609129d405320fe1080b4ba05a8e304228",
"tests/test_continuity.py": "6dd818484a064dc3fc9efe5ca71cc11ffcd3a0dcc45ea4185065732dab0289cc",
"tests/test_personas.py": "2576f2be903c69270cb1dec1e12448154554798bd7fca866d78e66e31594cbcb",
"tests/test_segmentation.py": "cf80a74958a715a81180a7932efb84f1d0974b434cf4fc3354b68c604ccbf463",
"tests/test_llm_provider.py": "6a8bd33679d68899c2a978bf4de672578517494c613b8e77d275c6207de3285b",
"tests/test_v08.py": "f993d4162576494e814786f26376ba80ab8a77af98ba70de4379055bb9525082"
}
}
}
+8
View File
@@ -4,3 +4,11 @@ LAN_OPEN_MODE=1
LAN_GUEST_ENABLED=1
# The optional independent VAD service also needs its own secret.
LAN_VAD_TOKEN=REPLACE_WITH_A_DIFFERENT_RANDOM_SECRET_AT_LEAST_32_CHARS
# Optional provider settings; absence keeps the existing local Qwen defaults.
LAN_LLM_BASE_URL=http://127.0.0.1:8888/v1
LAN_LLM_MODEL=qwen3.8-27b
LAN_LLM_CHAT_TEMPLATE_KWARGS={"enable_thinking":false}
# Set API keys only in a private environment file. Do not commit them.
# LAN_LLM_API_KEY=REPLACE_WITH_PRIVATE_PROVIDER_KEY
# Doubao through existing LiteLLM: base http://192.168.31.53:4000/v1,
# model alias doubao-seed-2-1-pro, kwargs {}. Alias does not identify actual weights.
+44 -61
View File
@@ -19,10 +19,12 @@ from fastapi.staticfiles import StaticFiles
import uuid
from history import History
from face_context import FaceContext
from reply_emotion import SYSTEM_FRAGMENT, parse_reply
from guest_sessions import GuestSessions, COOKIE
from tts_debug import DebugStore
from persona_resolver import resolve_persona
from segmentation import Segmenter
from llm_provider import LLMProvider
from app import EXPECTED_HASH
from protocol import WavStream, pack, unpack
from vad import Config, Silero, VadSession
@@ -202,6 +204,7 @@ async def debug_download(request: Request):
class Dialogue:
def __init__(self, ws, model, client, history=None, conversation_id=None):
self.ws, self.client = ws, client
self.llm_provider = LLMProvider()
self.history = history
self.conversation_id = conversation_id
self.run_id = None
@@ -461,71 +464,51 @@ class Dialogue:
await self.drained()
async def generate(self, turn, text, queue, metrics, began):
segmenter = Segmenter(getattr(self, 'synthesis_mode', 'balanced'))
request_start = time.perf_counter()
continuous = self.voice_mode == 'continuous_voice'
full_text = ''
metrics.update(voice_mode=self.voice_mode, voice_id=self.voice_id, tts_request_count=0)
# Exactly one initial system: Qwen's deployed template rejects a second system.
system = '以下角色设定只约束reply字段的口述内容;其中旧有不输出JSON等格式约定不约束本轮外层结构。\n' + self.persona_rules + ''.join(
'\n\n' + item['content'] for item in self.face_messages.get(turn, [])) + '\n\n' + SYSTEM_FRAGMENT
messages = [{'role': 'system', 'content': system}] + self.contexts.get(turn, []) + [{'role': 'user', 'content': text}]
url, headers, body = self.llm_provider.request(messages, max_tokens=160)
raw_body = ''
async with asyncio.timeout(30):
async with self.client.stream('POST', url, headers=headers, json=body) as response:
response.raise_for_status()
event_data = []
async for line in response.aiter_lines():
if turn != self.turn: return
if line.startswith('data:'): event_data.append(line[5:].lstrip())
if line != '' or not event_data: continue
raw = '\n'.join(event_data); event_data = []
if raw == '[DONE]': break
data = json.loads(raw)
for choice in data.get('choices', []):
delta = choice.get('delta', {}).get('content') or ''
if not delta: continue
metrics.setdefault('llm_first_token_ms', round((time.perf_counter() - request_start) * 1000, 2))
raw_body += delta
if len(raw_body) > 8192: raise ValueError('structured reply limit')
if turn != self.turn: return
if not raw_body.strip(): raise ValueError('empty LLM body')
parse_start = time.perf_counter()
result = parse_reply(raw_body)
metrics['reply_parse_ms'] = round((time.perf_counter() - parse_start) * 1000, 2)
metrics['reply_emotion_source'] = result.source
metrics['llm_first_body_ms'] = round((time.perf_counter() - request_start) * 1000, 2)
metrics['structured_wait_ms'] = round(metrics['llm_first_body_ms'] - metrics.get('llm_first_token_ms', 0), 2)
metrics['llm_finished_ms'] = round((time.perf_counter() - began) * 1000, 2)
# Only the extracted reply enters events, persistent history and the single TTS generator.
self.answers[turn] = result.reply
await self.event('llm', turn, text=result.reply)
await self.event('reply.emotion', turn, emotion=result.emotion, intensity=result.intensity, source=result.source)
await self.event('llm.finished', turn, voice_mode=self.voice_mode, llm_finished_ms=metrics['llm_finished_ms'])
async def enqueue(fragment):
if fragment:
if 'first_fragment_ms' not in metrics: metrics['first_fragment_ms'] = round((time.perf_counter() - began) * 1000, 2)
metrics['segment_hardcuts'] = segmenter.hardcuts
metrics['segment_last_cut'] = segmenter.last_cut
metrics.setdefault('first_fragment_ms', round((time.perf_counter() - began) * 1000, 2))
await queue.put(fragment)
async with asyncio.timeout(30):
async with self.client.stream('POST', 'http://127.0.0.1:8888/v1/chat/completions', json={'model': 'qwen3.8-27b', 'messages': [{'role': 'system', 'content': '用简短中文直接回答,不输出思考过程、动作旁白、Markdown或JSON。最多两小句。' + self.persona_rules + ''.join('\n\n' + item['content'] for item in self.face_messages.get(turn, []))}] + self.contexts.get(turn, []) + [{'role': 'user', 'content': text}], 'max_tokens': 64, 'temperature': 0.3, 'stream': True, 'chat_template_kwargs': {'enable_thinking': False}}) as response:
response.raise_for_status()
lines = response.aiter_lines().__aiter__()
pending = asyncio.create_task(anext(lines))
event_data = []
try:
while True:
timeout = None if continuous else segmenter.timeout(time.perf_counter())
done, _ = await asyncio.wait({pending}, timeout=timeout)
if not done:
await enqueue(segmenter.take(time.perf_counter())); continue
try: line = pending.result()
except StopAsyncIteration: break
pending = asyncio.create_task(anext(lines))
if line.startswith('data:'): event_data.append(line[5:].lstrip())
if line != '' or not event_data: continue
raw = '\n'.join(event_data); event_data = []
if raw == '[DONE]': break
data = json.loads(raw)
for choice in data.get('choices', []):
delta = choice.get('delta', {}).get('content') or ''
if not delta: continue
if 'llm_first_body_ms' not in metrics:
metrics['llm_first_body_ms'] = round((time.perf_counter() - request_start) * 1000, 2)
if turn != self.turn: return
self.answers[turn] = (self.answers.get(turn, '') + delta)[:2000]
await self.event('llm', turn, text=delta)
full_text += delta
if len(full_text) > 1000: raise ValueError('TTS full text limit')
if not continuous:
await enqueue(segmenter.add(delta, time.perf_counter()))
while True:
fragment = segmenter.take(time.perf_counter())
if not fragment: break
await enqueue(fragment)
if turn != self.turn: return
if not full_text.strip(): raise ValueError('empty LLM body')
metrics['llm_finished_ms'] = round((time.perf_counter() - began) * 1000, 2)
await self.event('llm.finished', turn, voice_mode=self.voice_mode, llm_finished_ms=metrics['llm_finished_ms'])
if continuous:
await enqueue(full_text.strip())
else:
remainder = segmenter.take(time.perf_counter(), final=True)
queued = []
while not queue.empty():
queued.append(queue.get_nowait())
combined = ''.join(queued) + (remainder or '')
if combined:
metrics['final_queued_merge_chars'] = len(combined)
await enqueue(combined)
finally:
pending.cancel()
with contextlib.suppress(asyncio.CancelledError, StopAsyncIteration): await pending
# A validated reply is a single synthesis input in every voice mode.
await enqueue(result.reply)
await queue.put(None)
async def synthesize(self, turn, queue, metrics, began):
@@ -655,7 +638,7 @@ async def dialogue(ws: WebSocket):
session.voice_id = voice_id
session.debug_store = app.state.debug
session.debug_enabled = hello.get('tts_debug', True) is True
await session.event('hello', context_face_cue_version=1, version=VERSION, codec='pcm16', sample_rate=16000, output_sample_rate=48000, channels=1, frame_duration=20, header_version=1, conversation_id=cid, duplex_default=True, voice_mode=voice_mode, voice_id=voice_id, voices=app.state.voices)
await session.event('hello', context_face_cue_version=1, reply_emotion_version=1, version=VERSION, codec='pcm16', sample_rate=16000, output_sample_rate=48000, channels=1, frame_duration=20, header_version=1, conversation_id=cid, duplex_default=True, voice_mode=voice_mode, voice_id=voice_id, voices=app.state.voices)
await session.send_history()
started = time.monotonic()
while time.monotonic() - started < 600:
+27
View File
@@ -0,0 +1,27 @@
import json
import os
from urllib.parse import urlsplit
class LLMProvider:
def __init__(self, environ=None):
env = os.environ if environ is None else environ
self.base_url = env.get('LAN_LLM_BASE_URL', 'http://127.0.0.1:8888/v1').rstrip('/')
self.model = env.get('LAN_LLM_MODEL', 'qwen3.8-27b')
self.api_key = env.get('LAN_LLM_API_KEY', '')
url = urlsplit(self.base_url)
if url.scheme not in ('http', 'https') or not url.hostname or url.username or url.password or url.query or url.fragment:
raise ValueError('invalid LLM base URL')
if not self.model or any(c in self.api_key for c in '\r\n'):
raise ValueError('invalid LLM configuration')
raw = env.get('LAN_LLM_CHAT_TEMPLATE_KWARGS')
self.template_kwargs = json.loads(raw) if raw is not None else ({'enable_thinking': False} if self.model.lower().startswith('qwen') else {})
if not isinstance(self.template_kwargs, dict):
raise ValueError('invalid LLM chat template kwargs')
def request(self, messages, *, max_tokens=64):
body = {'model': self.model, 'messages': messages, 'max_tokens': max_tokens, 'temperature': 0.3, 'stream': True}
if self.template_kwargs:
body['chat_template_kwargs'] = self.template_kwargs
headers = {'Authorization': 'Bearer ' + self.api_key} if self.api_key else {}
return self.base_url + '/chat/completions', headers, body
+59
View File
@@ -0,0 +1,59 @@
"""Bounded structured role expression; never return the raw model envelope as speech."""
from dataclasses import dataclass
import json
import re
SYSTEM_FRAGMENT = '''本轮只输出一个JSON对象,格式为{"reply":"简短中文回答","emotion":"neutral","intensity":0},不加代码围栏或额外文字。reply直接回答用户,最多两小句,不含情绪标签、动作旁白或思考过程。emotion是角色本轮表达意图,不是用户心理判断;只允许neutral(intensity=0)、happy/angry/sad(intensity=1轻度或2明显)。普通问答默认neutral;帮助性和用户台词优先,不为表演牺牲回答,不根据摄像头皱眉强行生气或攻击。每轮仅一个主情绪,无混合或长期状态。'''
SAFE_REPLY = '抱歉,这次回答格式有误,请再说一次。'
@dataclass(frozen=True)
class ReplyEmotion:
reply: str
emotion: str = 'neutral'
intensity: int = 0
source: str = 'fallback'
def clean_reply(value):
if not isinstance(value, str): return None
value = value.strip()
# Structured envelopes/code must never become TTS input, including nested replies.
if not value or len(value) > 1000 or value.startswith(('{', '[', '```')): return None
if re.search(r'"(?:reply|emotion|intensity)"\s*:', value): return None
return value
def parse_reply(raw):
if not isinstance(raw, str) or len(raw) > 8192: return ReplyEmotion(SAFE_REPLY)
body = raw.strip()
if body.startswith('```'):
body = re.sub(r'^```(?:json)?\s*', '', body, count=1).removesuffix('```').strip()
try: data = json.loads(body)
except (ValueError, RecursionError): data = None
if isinstance(data, dict):
reply = clean_reply(data.get('reply'))
if reply:
emotion, intensity = data.get('emotion'), data.get('intensity')
if (set(data) == {'reply', 'emotion', 'intensity'} and type(intensity) is int and
((emotion == 'neutral' and intensity == 0) or
(emotion in ('happy', 'angry', 'sad') and intensity in (1, 2)))):
return ReplyEmotion(reply, emotion, intensity, 'model')
return ReplyEmotion(reply)
for key in ('text', 'answer'):
reply = clean_reply(data.get(key))
if reply: return ReplyEmotion(reply)
# Recover a usable quoted reply from a damaged/truncated envelope without another model call.
match = re.search(r'"reply"\s*:\s*(")', body)
if match:
literal = body[match.start(1):]
try: value, _ = json.JSONDecoder().raw_decode(literal)
except ValueError:
# Only a truncated string, never arbitrary suffix/JSON syntax recovery.
try: value = json.loads(literal.rstrip('\\') + '"')
except ValueError: value = None
reply = clean_reply(value)
if reply: return ReplyEmotion(reply)
if not any(c in body for c in '{}[]') and not re.search(r'\b(?:reply|emotion|intensity)\s*[:=]', body):
reply = clean_reply(body)
if reply: return ReplyEmotion(reply)
return ReplyEmotion(SAFE_REPLY)
+13 -1
View File
@@ -1,5 +1,6 @@
#!/usr/bin/env python3
"""Portable model-free archive regression: isolated temp root + synthetic persona manifests."""
import argparse
import json
import os
from pathlib import Path
@@ -9,11 +10,22 @@ import sys
import tempfile
root = Path(__file__).resolve().parents[1]
parser=argparse.ArgumentParser(description=__doc__)
parser.add_argument('--vad-model', type=Path, help='Existing authorized Silero artifact; read only, never downloaded')
args=parser.parse_args()
with tempfile.TemporaryDirectory(prefix='lan-voice-archive-check-') as folder:
stage = Path(folder)
for source in root.glob('*.py'): shutil.copy2(source, stage/source.name)
for name in ('tests','personas','web'):
shutil.copytree(root/name, stage/name, ignore=shutil.ignore_patterns('__pycache__'))
if args.vad_model:
import hashlib
model=args.vad_model.resolve(strict=True)
sys.path.insert(0,str(root))
from importlib.util import spec_from_file_location, module_from_spec
spec=spec_from_file_location('vad_app',root/'app.py');module=module_from_spec(spec);spec.loader.exec_module(module)
assert hashlib.sha256(model.read_bytes()).hexdigest()==module.EXPECTED_HASH, 'Silero artifact checksum'
(stage/'models').mkdir();(stage/'models/silero_vad.onnx').symlink_to(model)
target=stage/'.runtime/personas'; target.mkdir(parents=True)
for name in ('lvbu','yangmi_fiction'):
# Public dummy IDs only; no production profile/reference audio/runtime copied.
@@ -29,7 +41,7 @@ def safe(suite):
result=unittest.TestSuite()
for item in suite:
if isinstance(item,unittest.TestSuite): result.addTest(safe(item))
elif item.id().endswith('.test_silero_silence_and_state'):
elif item.id().endswith('.test_silero_silence_and_state') and not Path('models/silero_vad.onnx').exists():
# Model artifacts are intentionally absent; never download/load a model in archive checks.
item.setUp=lambda: (_ for _ in ()).throw(unittest.SkipTest('Silero artifact excluded from source archive'))
result.addTest(item)
+2 -2
View File
@@ -13,7 +13,7 @@ from test_gateway import Socket
class ContinuityTests(unittest.IsolatedAsyncioTestCase):
async def test_multidelta_one_tts_and_realtime_text(self):
async def test_multidelta_one_tts_and_parsed_text(self):
socket=Socket();tts=[]
wav=io.BytesIO()
with wave.open(wav,'wb') as w:
@@ -25,7 +25,7 @@ class ContinuityTests(unittest.IsolatedAsyncioTestCase):
stream=''.join('data: '+json.dumps({'choices':[{'delta':{'content':x}}]},ensure_ascii=False)+'\n\n' for x in parts)+'data: [DONE]\n\n'
return httpx.Response(200,text=stream)
tts.append(json.loads(request.content))
self.assertEqual(len([e for e in socket.events if e['type']=='llm']),3)
self.assertEqual([e['text'] for e in socket.events if e['type']=='llm'], [''.join(parts)])
return httpx.Response(200,content=wav.getvalue())
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
d=Dialogue(socket,FakeModel(),client)
+66
View File
@@ -0,0 +1,66 @@
"""Actual pipeline: one system, parsed body/history/TTS, emotion before any PCM, turn fencing."""
import asyncio
import io
import json
import time
import unittest
import wave
import httpx
from gateway import Dialogue
from tests_fake import FakeModel
from test_gateway import Socket
class EmotionPipelineTests(unittest.IsolatedAsyncioTestCase):
async def test_seven_states_no_envelope_in_body_history_or_tts(self):
for emotion,intensity in [('neutral',0)]+[(e,i) for e in ('happy','angry','sad') for i in (1,2)]+[('invalid',2),('damaged',0)]:
socket=Socket();tts=[];history=[];order=[]
class OrderedSocket(Socket):
async def send_json(self,event): order.append(event['type']);await super().send_json(event)
async def send_bytes(self,frame): order.append('pcm');await super().send_bytes(frame)
class History:
async def begin(self,*args): pass
async def context(self,*args): return []
async def rows(self,*args): return []
async def finish(self,rid,answer,status): history.append((answer,status))
body=json.dumps(dict(reply='测试回答。',emotion=emotion,intensity=intensity),ensure_ascii=False)
if emotion=='damaged':body='{"reply":"测试回答。","emotion":'
expected=(emotion,intensity,'model') if emotion not in ('invalid','damaged') else ('neutral',0,'fallback')
def backend(request):
if 'transcriptions' in request.url.path:return httpx.Response(200,json={'text':'公开测试'})
if 'chat' in request.url.path:
data=json.loads(request.content);self.assertEqual([m['role'] for m in data['messages']],['system','user'])
self.assertNotIn('摄像头观察',data['messages'][0]['content'])
# Even a JSON envelope split inside a key must never leak as text.
return httpx.Response(200,text=''.join('data: '+json.dumps({'choices':[{'delta':{'content':part}}]})+'\n\n' for part in (body[:5],body[5:]))+'data: [DONE]\n\n')
tts.append(json.loads(request.content)['input']);out=io.BytesIO()
with wave.open(out,'wb') as w:
w.setnchannels(1);w.setsampwidth(2);w.setframerate(48000);w.writeframes(b'\x11\x01'*960)
return httpx.Response(200,content=out.getvalue())
socket=OrderedSocket()
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
d=Dialogue(socket,FakeModel(),client,History(),'synthetic');d.run_id='synthetic'
# Exercise both accepted voice modes; both synthesize just the parsed reply once.
d.voice_mode='fragment' if intensity==1 else 'continuous_voice'
await d.run(0,bytes(640))
self.assertEqual(tts,['测试回答。']);self.assertEqual(history,[('测试回答。','completed')])
self.assertEqual([e['text'] for e in socket.events if e['type']=='llm'],['测试回答。'])
events=[e for e in socket.events if e['type']=='reply.emotion'];self.assertEqual(len(events),1)
self.assertEqual((events[0]['emotion'],events[0]['intensity'],events[0]['source'],events[0]['turn_id']),(*expected,0))
self.assertGreater(events[0]['seq'],0);self.assertLess(order.index('reply.emotion'),order.index('pcm'))
self.assertTrue(socket.frames)
async def test_stale_generation_cannot_publish_emotion_or_speak(self):
entered=asyncio.Event();resume=asyncio.Event();socket=Socket()
class Slow(httpx.AsyncByteStream):
async def __aiter__(self):
yield b'data: {"choices":[{"delta":{"content":"{\\\"reply\\\":\\\"hello\\\""}}]}\n\n'
entered.set();await resume.wait()
yield b'data: [DONE]\n\n'
async with httpx.AsyncClient(transport=httpx.MockTransport(lambda req:httpx.Response(200,stream=Slow()))) as client:
d=Dialogue(socket,FakeModel(),client);queue=asyncio.Queue(2)
task=asyncio.create_task(d.generate(0,'test',queue,{},time.perf_counter()))
await entered.wait();await d.invalidate('new_turn');resume.set();await task
self.assertTrue(queue.empty())
self.assertFalse(any(e['type'] in ('llm','reply.emotion') for e in socket.events))
await d.event('reply.emotion',0,emotion='angry',intensity=2,source='model')
self.assertEqual([e['type'] for e in socket.events],['abort'])
+94
View File
@@ -0,0 +1,94 @@
import asyncio
import json
import time
import unittest
from unittest.mock import patch
import httpx
from gateway import Dialogue
from llm_provider import LLMProvider
from test_gateway import Socket
from tests_fake import FakeModel
class ProviderTests(unittest.TestCase):
def test_qwen_default_and_manual_return(self):
provider = LLMProvider({})
url, headers, body = provider.request([{'role': 'user', 'content': '公开问题'}])
self.assertEqual(url, 'http://127.0.0.1:8888/v1/chat/completions')
self.assertEqual(headers, {})
self.assertEqual(body['model'], 'qwen3.8-27b')
self.assertEqual(body['chat_template_kwargs'], {'enable_thinking': False})
def test_doubao_key_only_in_header_and_no_schema_requirement(self):
provider = LLMProvider({'LAN_LLM_BASE_URL': 'http://192.168.31.53:4000/v1/', 'LAN_LLM_MODEL': 'doubao-seed-2-1-pro', 'LAN_LLM_API_KEY': 'unit-key'})
messages = [{'role': 'system', 'content': '简短中文'}, {'role': 'user', 'content': '公开问题'}]
url, headers, body = provider.request(messages)
self.assertEqual(url, 'http://192.168.31.53:4000/v1/chat/completions')
self.assertEqual(headers['Authorization'], 'Bearer unit-key')
self.assertEqual(body['messages'], messages)
self.assertEqual(body['max_tokens'], 64)
self.assertTrue(body['stream'])
self.assertNotIn('chat_template_kwargs', body)
self.assertNotIn('response_format', body)
self.assertNotIn(provider.api_key, json.dumps(body) + url)
self.assertEqual(provider.request(messages, max_tokens=160)[2]['max_tokens'], 160)
def test_custom_kwargs_are_provider_local(self):
custom = LLMProvider({'LAN_LLM_MODEL': 'doubao-seed-2-1-pro', 'LAN_LLM_CHAT_TEMPLATE_KWARGS': '{"custom":true}'})
self.assertEqual(custom.request([])[2]['chat_template_kwargs'], {'custom': True})
self.assertEqual(LLMProvider({}).request([])[2]['chat_template_kwargs'], {'enable_thinking': False})
self.assertNotIn('chat_template_kwargs', LLMProvider({'LAN_LLM_MODEL': 'doubao-seed-2-1-pro'}).request([])[2])
def test_explicit_template_kwargs_and_invalid_configuration(self):
self.assertEqual(LLMProvider({'LAN_LLM_CHAT_TEMPLATE_KWARGS': '{}'}).template_kwargs, {})
for env in ({'LAN_LLM_BASE_URL': 'http://user:password@example.com/v1'}, {'LAN_LLM_BASE_URL': 'http://example.com/v1?key=secret'}, {'LAN_LLM_CHAT_TEMPLATE_KWARGS': '[]'}, {'LAN_LLM_API_KEY': 'bad\nheader'}):
with self.assertRaises(ValueError):
LLMProvider(env)
class ProviderStreamTests(unittest.IsolatedAsyncioTestCase):
async def test_doubao_sse_history_face_and_no_fallback(self):
calls = []
def backend(request):
calls.append(request)
self.assertEqual(str(request.url), 'http://192.168.31.53:4000/v1/chat/completions')
self.assertEqual(request.headers['authorization'], 'Bearer unit-key')
body = json.loads(request.content)
self.assertNotIn('chat_template_kwargs', body)
self.assertEqual(body['max_tokens'], 160)
self.assertEqual(sum(m['role']=='system' for m in body['messages']), 1)
self.assertIn('face-summary', body['messages'][0]['content'])
self.assertEqual(body['messages'][1]['content'], '历史问题')
content=json.dumps({'reply':'公开回答。','emotion':'happy','intensity':1})
return httpx.Response(200, text='data: '+json.dumps({'choices':[{'delta':{'content':content}}]})+'\n\ndata: [DONE]\n\n')
env = {'LAN_LLM_BASE_URL': 'http://192.168.31.53:4000/v1', 'LAN_LLM_MODEL': 'doubao-seed-2-1-pro', 'LAN_LLM_API_KEY': 'unit-key'}
with patch.dict('os.environ', env, clear=True):
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
socket = Socket()
dialogue = Dialogue(socket, FakeModel(), client)
dialogue.contexts[0] = [{'role': 'user', 'content': '历史问题'}]
dialogue.face_messages[0] = [{'content': 'face-summary'}]
queue = asyncio.Queue(2)
await dialogue.generate(0, '公开问题', queue, {}, time.perf_counter())
self.assertEqual(await queue.get(), '公开回答。')
self.assertIsNone(await queue.get())
self.assertEqual(len(calls), 1)
self.assertEqual(dialogue.answers[0], '公开回答。')
self.assertTrue(any(e['type'] == 'llm.finished' for e in socket.events))
emotion=next(e for e in socket.events if e['type']=='reply.emotion')
self.assertEqual((emotion['emotion'],emotion['intensity'],emotion['source']),('happy',1,'model'))
async def test_auth_failure_never_calls_second_provider(self):
calls = []
def backend(request):
calls.append(request)
return httpx.Response(401)
with patch.dict('os.environ', {'LAN_LLM_BASE_URL': 'http://192.168.31.53:4000/v1', 'LAN_LLM_MODEL': 'doubao-seed-2-1-pro'}, clear=True):
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
dialogue = Dialogue(Socket(), FakeModel(), client)
with self.assertRaises(httpx.HTTPStatusError):
await dialogue.generate(0, '公开问题', asyncio.Queue(2), {}, time.perf_counter())
self.assertEqual(len(calls), 1)
self.assertEqual(calls[0].url.host, '192.168.31.53')
+46
View File
@@ -0,0 +1,46 @@
import json
import unittest
from reply_emotion import parse_reply, SAFE_REPLY
class ReplyEmotionTests(unittest.TestCase):
def test_all_seven_states(self):
for emotion, intensity in [('neutral',0)]+[(e,i) for e in ('happy','angry','sad') for i in (1,2)]:
with self.subTest(emotion=emotion,intensity=intensity):
result=parse_reply(json.dumps(dict(reply='公开回答。',emotion=emotion,intensity=intensity)))
self.assertEqual((result.reply,result.emotion,result.intensity,result.source),('公开回答。',emotion,intensity,'model'))
def test_invalid_missing_and_wrong_types_keep_reply_fallback(self):
for fields in [dict(),dict(emotion='fear',intensity=2),dict(emotion='happy',intensity=0),
dict(emotion='neutral',intensity=2),dict(emotion='sad',intensity=True),
dict(emotion='happy',intensity=1.0),dict(emotion=[],intensity=1),
dict(emotion='sad',intensity=1,extra='ignored')]:
result=parse_reply(json.dumps(dict(reply='可用正文',**fields)))
self.assertEqual((result.reply,result.emotion,result.intensity,result.source),('可用正文','neutral',0,'fallback'))
def test_damaged_formats_recover_without_reading_envelope(self):
for raw, expected in [
('{"reply":"正文","emotion":','正文'),
('{"reply":"被截断的正文','被截断的正文'),
('{"reply":"转义\\n正文","intensity":???}', '转义\n正文'),
('普通的非JSON回答。','普通的非JSON回答。'),
('{"answer":"兼容正文"}', '兼容正文'),
('```json\n{"reply":"正文"}\n```','正文'),
('{"emotion":"happy"}',SAFE_REPLY),
('{"reply": {"evil":true}}',SAFE_REPLY),
('{"reply":"{\\"emotion\\":\\"happy\\"}"}',SAFE_REPLY),
('',SAFE_REPLY), ('x'*8193, SAFE_REPLY),
]:
with self.subTest(raw=raw):
result=parse_reply(raw)
self.assertEqual(result.reply,expected)
self.assertEqual((result.emotion,result.intensity,result.source),('neutral',0,'fallback'))
def test_no_model_retry_or_schema_contract(self):
from pathlib import Path
source=(Path(__file__).resolve().parents[1]/'gateway.py').read_text()
generate=source.split(' async def generate(')[1].split(' async def synthesize(')[0]
self.assertEqual(generate.count("self.client.stream('POST'"),1)
self.assertEqual(generate.count('self.llm_provider.request('),1)
self.assertNotIn('response_format', generate)
if __name__=='__main__': unittest.main()