fix(gateway): constrain verified Qwen replies to emotion schema

This commit is contained in:
zenord
2026-10-12 12:18:18 +08:00
parent b521d368a5
commit 18ec4c2104
18 changed files with 351 additions and 60 deletions
+38
View File
@@ -0,0 +1,38 @@
# Gateway 0.7.2 structured reply repair
The 0.5.1 report received on 2026-10-12 at 11:47:40 +08:00 retained five actual applied fallbacks: turns 22/23/25/27/33, all `non_json/plain_text/stop`. Those were usable plain-text answers without an emotion envelope, not model-selected neutral or reported token truncation. All five used yangmi_fiction. Its old format rules competed with the system's JSON request despite a preceding override. That competition was present, but was not proven to be the reason the model ignored the format. No actual user reply/prompt/audio was accessed for the audit.
## Minimal change
- Public Yangmi/Lvbu lore format sentences now explicitly constrain only the spoken reply field; outer format follows the round's format contract. Character style, facts and safety rules are unchanged.
- One system, one LLM request and a 160-token budget remain. TTS voice/parameters, ASR, reply-only history/speech, parser recovery, diagnostic reasons, turn fencing and Android presentation are unchanged.
- `LAN_LLM_STRUCTURED_OUTPUT` accepts `prompt` or `json_schema`, rejecting unknown modes. Only the exact verified local URL/model/thinking=false tuple defaults to schema when unset. Arbitrary aliases or custom Qwen endpoints do not imply support.
- Schema uses object/properties/required/additionalProperties=false, reply string, emotion enum neutral/happy/angry/sad and integer intensity enum 0/1/2. The parser still enforces neutral0 and other emotions at intensity1/2. There is no extra inference retry for malformed output or unsupported schema.
- Doubao configuration/Authorization loading and provider-specific kwargs remain supported. Its schema capability is not verified; use prompt mode when switching. Do not carry an explicit Qwen schema setting to an unverified provider.
- Gateway health version is 0.7.2 and health/hello plus finite metadata expose format mode. Android remains 0.5.1/code9 and needs no rebuild or reinstall.
## Actual endpoint compatibility
Read-only inspection of the running SGLang reported version `0.0.0.dev0+qwen38.27b.g561c8f3`, xgrammar backend, response_format/json_schema request types, sampling-schema forwarding and compile_json_schema implementation (xgrammar0.2.1).
Before enabling the provider behavior, one public short greeting was sent with the exact minimal schema and stream=true under the active persona. Actual HTTP200, SSE [DONE], strict_json/model neutral0, finishstop and six reply characters passed at max_tokens160. First content: 915.99ms; completed envelope: 1916.29ms; wait after first content: 1000.30ms. Usage was absent, not zero tokens. This validates the concrete schema/stream/thinkingfalse combination once; it is not a broad stability or latency guarantee.
`scripts/probe-llm-schema.py` is bounded to one or two public samples and records finite enums/counts/timing only. Running it sends real model requests; it is not part of model-free regression. After deployment it asserts the provider actually built the expected schema request. `scripts/probe-reply-emotion.py` exercises one authorized existing public-audio round, asserts live schema mode/model output, reply-only single TTS and emotion-before-PCM/drained acknowledgement. PCM/drained do not prove phone audibility. The larger historical `check-reply-structure.py` also contacts saved Doubao; it is not required for this repair and is not run automatically.
## Deployment and rollback
Canonical source remains gateway/. SOURCE_MANIFEST records previous deployed baseline hashes and new source hashes. Deployment tests a temporary source copy using the existing venv and read-only authorized Silero artifact, checks source/unit/environment hashes and idle state repeatedly, backs up all source/tests/public lore/modes plus private unit/env loading relationships on the server, then restarts only lan-voice-gateway.service. Private environment values and credentials are not copied to this repository or printed.
On failed restart, automatic rollback refuses intervening source edits; for an operator-requested rollback, use `python3 scripts/rollback-gateway-source.py` with the local ignored record of that exact deployment. It checks deployed hashes, busy state and unchanged unit/private environment before restoring original files/modes and restarting only gateway. `LAN_LLM_STRUCTURED_OUTPUT=prompt` can disable schema in a separately approved configuration change; this release does not modify private env files.
Full source/unit/client regression and post-deployment numeric results are recorded in ignored logs/structure-output-fix/ and logs/voice-investigation/. User conversation/LLM envelopes, prompt, keys, audio and raw face data are excluded from these records and Git. Finite public samples cannot establish that the five actual user conversations are fixed; user phone acceptance remains outstanding.
## Completed validation
The isolated full gateway suite passed 73 tests using the existing venv and checksum-verified read-only Silero artifact (1.039s during deployment). Client coordinator/playback/capture/protocol, expression rules and camera permission lifecycle regressions passed with device/transport doubles; no Android source was changed or APK rebuilt.
After deployment, two public short text inputs under the active persona returned HTTP200, SSE [DONE], strict_json/model happy1 and finishstop at max_tokens160. First content was 343.84/322.62ms; full structure completed at 1964.95/2627.62ms; structure wait was 1621.11/2305.00ms. These checks validate formatting on finite samples, not the appropriateness of emotion for user conversation or a forced emotion distribution.
One existing public audio sample (3.36s input) completed real ASR→Qwen→VoxCPM2→PCM with one reply.emotion happy1/model/none/strict_json/stop before the first PCM. TTS used exactly one parsed-body input; 152 frames/291840 bytes (3.04s audio), nonzero RMS1807.56, drained acknowledged. A synthetic whitelisted face cue was snapshotted and invalid control survived; this was not a real camera observation. ASR28.76ms; LLM first content376.38ms; full reply2795.37ms; structure wait2418.99ms; TTS first PCM199.55ms; capture end to first PCM3045.49ms. Structured waiting is nonzero and significant; there is no latency-free claim or isolated before/after benchmark. Usage remained absent.
Deployment was idle and hash-fenced, restarted only gateway, and reverified all deployed hashes plus unchanged unit/private env relationships and Qwen configuration. Backup: `/home/gorios-spark-2/lan-voice/.runtime/backups/voice-gateway-20261012-121534`. The manifest retains the pre-repair baseline separately and advances its live deployment fence to the verified deployed hashes. Doubao schema inference, long-session stability, real-phone playback and the user's five previous conversations were not retested.
+6
View File
@@ -28,3 +28,9 @@ Portable archive checks skip only the omitted Silero artifact. On the existing s
Release 0.5.1 adds finite parser reason/recovery branch, finish_reason and optional token usage diagnostics without changing provider, prompt, 160-token dialogue budget, TTS voice or request count. Damaged structure is called truncated only when the provider explicitly reported length. Existing 0.5.0 clients continue to receive neutral/0 for fallback; the new UI labels it undetermined, shows model neutral only during playback and retains the previous played reply separately. New TTS diagnostic metadata keeps input_chars instead of the speech body; existing conversation history and the actual reply-only TTS request retain their original function. Old diagnostic reports remain accepted. See ../docs/CAMERA_EMOTION_051.md.
Gateway 0.7.2 repairs the observed 0.5.1 `non_json/plain_text/stop` fallback by supporting `LAN_LLM_STRUCTURED_OUTPUT=prompt|json_schema`. Unset defaults to schema only for the verified exact tuple `http://127.0.0.1:8888/v1`, `qwen3.8-27b`, `{"enable_thinking":false}`; other URLs/models/kwargs default to prompt. This is deployment capability selection, not a model-name heuristic. Explicit schema opt-in requires endpoint verification. When switching to Doubao, use `prompt` or unset the mode and use its own kwargs; Doubao schema decoding remains unverified. Unsupported schema requests fail once; no automatic retry or provider failover occurs. `response_format` uses only an object with reply string, emotion enum, intensity integer enum, required fields and additionalProperties=false. Cross-field semantics remain parser-validated.
Persona format rules now explicitly bind only spoken `reply`, preserving style/content/safety while removing the competing outer JSON prohibition. One system and the 160-token budget remain. JSON/labels still never enter speech or history, and each parsed reply uses one streaming TTS generator. Health/hello and numeric metrics expose the format mode; optional diagnostics remain compatible with the 0.5.1 APK. No Android update is needed. See ../docs/STRUCTURED_REPLY_072.md for compatibility evidence, rollout and limitations.
Deployment uses `deployment_baseline` in SOURCE_MANIFEST as the reviewed live hash fence, including the two whitelisted public persona lore JSON files. Ignored records no longer override the expected baseline. Backups retain all Python sources/tests, public persona lore, permissions and private unit/environment relationships on the server. The rollback script restores exactly the deployment whitelist and refuses busy/source/environment conflicts.
+90 -35
View File
@@ -1,7 +1,7 @@
{
"baseline_android_commit": "9b428fb76ffa1468aa46124b33d9c598cf3740d8",
"source": "SPARK-2 deployed lan-voice gateway",
"code_version": "0.7.1 (legacy health version; reply.emotion version 1 capability)",
"code_version": "0.7.2 (streaming json_schema for verified local provider; reply.emotion version 1)",
"python": "3.12.3",
"machine": "aarch64",
"scope": "whitelisted source only; no runtime/models/credentials",
@@ -33,8 +33,8 @@
},
"gateway.py": {
"source": "workspace:gateway/gateway.py",
"sha256": "b8e64e9387fca05808fac61bd097ae179e996a2c7ccd33f23bb729a61693dd0d",
"bytes": 38559,
"sha256": "06797c4d327977eef755f72db70ef91ff6925ca20cc5ae8a6cefb5ffa1890534",
"bytes": 38786,
"upstream_sha256": "d088bedcf5c0accd4712e06202f6ced8ab155aad57a5b05683724efa346326ce"
},
"guest_sessions.py": {
@@ -63,14 +63,16 @@
"bytes": 330
},
"personas/lvbu.lorebook.json": {
"source": "personas/lvbu.lorebook.json",
"sha256": "266078a2aed07dcbcf3283ae102a8215cef6c181bb240ac5e53ee240414721e4",
"bytes": 1322
"source": "workspace:gateway/personas/lvbu.lorebook.json",
"sha256": "1f144b431bdd5d9cda0ce593438fa88e717c0671d496105883a3d4db7bd635ea",
"bytes": 1413,
"upstream_sha256": "266078a2aed07dcbcf3283ae102a8215cef6c181bb240ac5e53ee240414721e4"
},
"personas/yangmi.lorebook.json": {
"source": "personas/yangmi.lorebook.json",
"sha256": "d3b0201dff992b1bd0258d4aa06f8e7688322c9904c0b885aa6cf7be7046717d",
"bytes": 3212
"source": "workspace:gateway/personas/yangmi.lorebook.json",
"sha256": "73badae3fd8582555caa338e50fb6193e64e6a43025dd469672aa903c1c4b71b",
"bytes": 3303,
"upstream_sha256": "d3b0201dff992b1bd0258d4aa06f8e7688322c9904c0b885aa6cf7be7046717d"
},
"protocol.py": {
"source": "protocol.py",
@@ -145,9 +147,10 @@
"bytes": 8570
},
"tests/test_personas.py": {
"source": "tests/test_personas.py",
"sha256": "2576f2be903c69270cb1dec1e12448154554798bd7fca866d78e66e31594cbcb",
"bytes": 1288
"source": "workspace:gateway/tests/test_personas.py",
"sha256": "013b18e7b7f0e582d8d7e04f5b1fb78009e993f96357be67a5367e70444b43e1",
"bytes": 1840,
"upstream_sha256": "2576f2be903c69270cb1dec1e12448154554798bd7fca866d78e66e31594cbcb"
},
"tests/test_segmentation.py": {
"source": "tests/test_segmentation.py",
@@ -246,8 +249,8 @@
},
"README.md": {
"source": "workspace:gateway/README.md",
"sha256": "cc32a5d3cd21975ece637f467c5c2f4ca2bc6c90b3fd450a3da909a116b11d5e",
"bytes": 7397,
"sha256": "8e13b5532e5af921b411d5fa8185e9e8efbef42859f47ec3615099bb87304c10",
"bytes": 9220,
"upstream_sha256": "799bc84308eb17d58987c5bee8ce3cf7617b4c52169d9307d344ac7d9996b6c5"
},
"config/active_profile.json.example": {
@@ -272,8 +275,8 @@
},
"env.example": {
"source": "workspace:gateway/env.example",
"sha256": "ec703e599d66f6848f7a4415da851a87c8446dd92805a8ce83e46bd690502367",
"bytes": 796,
"sha256": "ccc97d0e357d8120303cedf7947e1ba302070980a14cc8801f2424344fcab820",
"bytes": 1115,
"upstream_sha256": "d92e60812f49b02f3b0582d8b3dee03eb51cfca6dba77d9468a3ffddfce32499"
},
"pytest.ini": {
@@ -283,8 +286,8 @@
},
"reply_emotion.py": {
"source": "workspace:gateway/reply_emotion.py",
"sha256": "a2b6a1a51639d77368c200f2a6db8bb66fff1eebb4f60219d49da69ae402a8a2",
"bytes": 4005,
"sha256": "a32b9dedc135cac1ed6f25f33123946152a6bd3dc8d0d816a897c00b9e444ead",
"bytes": 4343,
"upstream_sha256": "488fbd24ff1ce7d3d4ab92257c8ccabafe24fc857e11c8486f54fa689276a565"
},
"scripts/check-archive.py": {
@@ -295,26 +298,26 @@
},
"tests/test_gateway_emotion.py": {
"source": "workspace:gateway/tests/test_gateway_emotion.py",
"sha256": "e4da9a092e6ee19ef421a43a04cd2b6d12cb65f1b210946092dcad016c8816bb",
"bytes": 7923,
"sha256": "51a8f751d14345fe2ccf3afd9250b0962f0ab260a97023afcee4a7b9b0f535d0",
"bytes": 8535,
"upstream_sha256": "86f22211e753e4b5ebfa11266e2e33eb2ea6b85707fbe8a988be6b8ff05f3f75"
},
"tests/test_reply_emotion.py": {
"source": "workspace:gateway/tests/test_reply_emotion.py",
"sha256": "2bd1ee33f11e2d23ccf9a30603f0db3b9f20c6d5fce8001f37f9ca76167974dd",
"bytes": 4678,
"sha256": "4ff2774187df8220ddbc8ef5b79910ae5047af3bacdb9476b0d2a8f55929d3be",
"bytes": 4693,
"upstream_sha256": "e45ccda640ef758fcb925d53804071349bdc8fb9f43ee1f63d1afb2ee3f238f5"
},
"llm_provider.py": {
"source": "workspace:gateway/llm_provider.py",
"sha256": "56ce6c1a4a647dea6ef86a83615f03db3a4397ebb3fa800b7fa655147d4f9978",
"bytes": 1471,
"sha256": "21aa2885c24f3240e891fd5325b09446ae1d8a95497d07a53082410d9fac2b10",
"bytes": 2447,
"upstream_sha256": "7d853adbe79f5f861a36894a9dfa28aa553d3eabea4db4c87a5fb4c319818ef1"
},
"tests/test_llm_provider.py": {
"source": "workspace:gateway/tests/test_llm_provider.py",
"sha256": "45404653daa71a006a90852b2f07f00cac608bd7311dd5ea850da0c1a3e52940",
"bytes": 5601,
"sha256": "43669d1fd7e61452b96f314a7f161fbcec843e463c74208d0f892fb58b839785",
"bytes": 8360,
"upstream_sha256": "6a8bd33679d68899c2a978bf4de672578517494c613b8e77d275c6207de3285b"
}
},
@@ -349,29 +352,31 @@
},
"release_baseline_commit": "d43c7d4e809a5a6b18ca9f28c8163a2f9ad34c7f",
"deployment_baseline": {
"release": "0.5.0",
"release": "gateway-0.7.2 / Android-0.5.1",
"files": {
"app.py": "d6520894dfbe035f64b1984aae15976db4df0e7e720195c81d3bf483b240056f",
"face_context.py": "01abfc214ebb4e979faf9430166eccae9af37df911d36da5435f907769e7e31a",
"gateway.py": "d9215f99339de0667e830fbd4d3bff80ac5a61c85630cc4ecadcb52a4c33a0e5",
"gateway.py": "06797c4d327977eef755f72db70ef91ff6925ca20cc5ae8a6cefb5ffa1890534",
"guest_sessions.py": "cc082fdb6c2ff7f5a41361ffe9ea2a53ebb944ee37354f65119405ad7a521c82",
"history.py": "2cf8b006bf486a03e038a69daa860ebb71a86989161cf6a7ea610114177a249f",
"llm_provider.py": "56ce6c1a4a647dea6ef86a83615f03db3a4397ebb3fa800b7fa655147d4f9978",
"llm_provider.py": "21aa2885c24f3240e891fd5325b09446ae1d8a95497d07a53082410d9fac2b10",
"persona_resolver.py": "deb33b4f4c17792fa5a6837362d5b29173e60a57bb993b61363bd4882d66d5de",
"personas/lvbu.lorebook.json": "1f144b431bdd5d9cda0ce593438fa88e717c0671d496105883a3d4db7bd635ea",
"personas/yangmi.lorebook.json": "73badae3fd8582555caa338e50fb6193e64e6a43025dd469672aa903c1c4b71b",
"protocol.py": "d9f522d958935200002e56024949a12b71eb89b3f3241635c5c307b798ee71c5",
"reply_emotion.py": "488fbd24ff1ce7d3d4ab92257c8ccabafe24fc857e11c8486f54fa689276a565",
"reply_emotion.py": "a32b9dedc135cac1ed6f25f33123946152a6bd3dc8d0d816a897c00b9e444ead",
"segmentation.py": "562ffc6e06f5b9f9072860b588feae3a5d7cd6eaa8577ac928d770071b06978d",
"tests/test_continuity.py": "d8390238f390463a98f12b9909bb5846be65f5b6dc1b21b94338b4cd75aaafae",
"tests/test_debug.py": "26f9e374354b714ab1a03b56af90bcbf32135711dc4f26e2c53eaa90c7f02ddd",
"tests/test_debug.py": "7d1d7876c4106f3df0b84cf8f7e479afb4a30ca51264fb94fa288fdd8155883e",
"tests/test_face_context.py": "50ca57adee1d07a194ebaa95b15e09d3e836b97b19490e99e3e045c72a89682c",
"tests/test_gateway.py": "f22aa98f3d6f62a2949a9047ec97e6dd686cac807d989a314a95deca718a3104",
"tests/test_gateway_emotion.py": "fc01e9319263b93adb1cc93904d23a13a25965ddb0fcfbd9c3e14e39f4cf52a5",
"tests/test_gateway_emotion.py": "51a8f751d14345fe2ccf3afd9250b0962f0ab260a97023afcee4a7b9b0f535d0",
"tests/test_gateway_reply_face.py": "4a4a8fd997941c0d92356c2ebab2c336abbcf84954735a6955d8fa7e3700ec3f",
"tests/test_guests.py": "6bc531f1bff85b8ea550bc88c634726531a1ef241ba5c861dbb8c963adf31c35",
"tests/test_history.py": "fc13a69811cfc4f4acf265ea9e0cdd67d566358ebe9b9b53cae76197db8bce78",
"tests/test_llm_provider.py": "45404653daa71a006a90852b2f07f00cac608bd7311dd5ea850da0c1a3e52940",
"tests/test_personas.py": "2576f2be903c69270cb1dec1e12448154554798bd7fca866d78e66e31594cbcb",
"tests/test_reply_emotion.py": "324fdaf55b501a31af129d41e9cf459f741ff0636818a6c628657dfde3fa6344",
"tests/test_llm_provider.py": "43669d1fd7e61452b96f314a7f161fbcec843e463c74208d0f892fb58b839785",
"tests/test_personas.py": "013b18e7b7f0e582d8d7e04f5b1fb78009e993f96357be67a5367e70444b43e1",
"tests/test_reply_emotion.py": "4ff2774187df8220ddbc8ef5b79910ae5047af3bacdb9476b0d2a8f55929d3be",
"tests/test_segmentation.py": "cf80a74958a715a81180a7932efb84f1d0974b434cf4fc3354b68c604ccbf463",
"tests/test_v08.py": "f993d4162576494e814786f26376ba80ab8a77af98ba70de4379055bb9525082",
"tests/test_vad.py": "bff64c0aafa05c085af7c1c9418244609129d405320fe1080b4ba05a8e304228",
@@ -379,5 +384,55 @@
"tts_debug.py": "d7b31b98a7f8ab688981873ef81decdf0b2f0167113c9103df039b7b24c9ccf2",
"vad.py": "3718ff9b296b2bba447100af520a631f221dcbfa322dd564cdc5809fb3675f23"
}
},
"server_capabilities": {
"structured_output_env": "LAN_LLM_STRUCTURED_OUTPUT",
"modes": [
"prompt",
"json_schema"
],
"verified_default": {
"base_url": "http://127.0.0.1:8888/v1",
"model": "qwen3.8-27b",
"chat_template_kwargs": {
"enable_thinking": false
}
},
"doubao_schema_verified": false
},
"previous_deployment_baseline": {
"release": "0.5.1",
"commit": "b521d368a5a5bab77599c860f651dce04b0de67e",
"files": {
"app.py": "d6520894dfbe035f64b1984aae15976db4df0e7e720195c81d3bf483b240056f",
"face_context.py": "01abfc214ebb4e979faf9430166eccae9af37df911d36da5435f907769e7e31a",
"gateway.py": "b8e64e9387fca05808fac61bd097ae179e996a2c7ccd33f23bb729a61693dd0d",
"guest_sessions.py": "cc082fdb6c2ff7f5a41361ffe9ea2a53ebb944ee37354f65119405ad7a521c82",
"history.py": "2cf8b006bf486a03e038a69daa860ebb71a86989161cf6a7ea610114177a249f",
"llm_provider.py": "56ce6c1a4a647dea6ef86a83615f03db3a4397ebb3fa800b7fa655147d4f9978",
"persona_resolver.py": "deb33b4f4c17792fa5a6837362d5b29173e60a57bb993b61363bd4882d66d5de",
"protocol.py": "d9f522d958935200002e56024949a12b71eb89b3f3241635c5c307b798ee71c5",
"reply_emotion.py": "a2b6a1a51639d77368c200f2a6db8bb66fff1eebb4f60219d49da69ae402a8a2",
"segmentation.py": "562ffc6e06f5b9f9072860b588feae3a5d7cd6eaa8577ac928d770071b06978d",
"tests/test_continuity.py": "d8390238f390463a98f12b9909bb5846be65f5b6dc1b21b94338b4cd75aaafae",
"tests/test_debug.py": "7d1d7876c4106f3df0b84cf8f7e479afb4a30ca51264fb94fa288fdd8155883e",
"tests/test_face_context.py": "50ca57adee1d07a194ebaa95b15e09d3e836b97b19490e99e3e045c72a89682c",
"tests/test_gateway.py": "f22aa98f3d6f62a2949a9047ec97e6dd686cac807d989a314a95deca718a3104",
"tests/test_gateway_emotion.py": "e4da9a092e6ee19ef421a43a04cd2b6d12cb65f1b210946092dcad016c8816bb",
"tests/test_gateway_reply_face.py": "4a4a8fd997941c0d92356c2ebab2c336abbcf84954735a6955d8fa7e3700ec3f",
"tests/test_guests.py": "6bc531f1bff85b8ea550bc88c634726531a1ef241ba5c861dbb8c963adf31c35",
"tests/test_history.py": "fc13a69811cfc4f4acf265ea9e0cdd67d566358ebe9b9b53cae76197db8bce78",
"tests/test_llm_provider.py": "45404653daa71a006a90852b2f07f00cac608bd7311dd5ea850da0c1a3e52940",
"tests/test_personas.py": "2576f2be903c69270cb1dec1e12448154554798bd7fca866d78e66e31594cbcb",
"tests/test_reply_emotion.py": "2bd1ee33f11e2d23ccf9a30603f0db3b9f20c6d5fce8001f37f9ca76167974dd",
"tests/test_segmentation.py": "cf80a74958a715a81180a7932efb84f1d0974b434cf4fc3354b68c604ccbf463",
"tests/test_v08.py": "f993d4162576494e814786f26376ba80ab8a77af98ba70de4379055bb9525082",
"tests/test_vad.py": "bff64c0aafa05c085af7c1c9418244609129d405320fe1080b4ba05a8e304228",
"tests_fake.py": "9a40f1948352f69f1dd20f8514baef58ae3d11eec240e1d2324d8990bad915d8",
"tts_debug.py": "d7b31b98a7f8ab688981873ef81decdf0b2f0167113c9103df039b7b24c9ccf2",
"vad.py": "3718ff9b296b2bba447100af520a631f221dcbfa322dd564cdc5809fb3675f23",
"personas/lvbu.lorebook.json": "266078a2aed07dcbcf3283ae102a8215cef6c181bb240ac5e53ee240414721e4",
"personas/yangmi.lorebook.json": "d3b0201dff992b1bd0258d4aa06f8e7688322c9904c0b885aa6cf7be7046717d"
}
}
}
+6 -1
View File
@@ -8,7 +8,12 @@ LAN_VAD_TOKEN=REPLACE_WITH_A_DIFFERENT_RANDOM_SECRET_AT_LEAST_32_CHARS
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}
# Optional: prompt or json_schema. Unset enables schema ONLY for the verified
# exact local URL/model/thinking=false tuple above; all other providers use prompt.
# LAN_LLM_STRUCTURED_OUTPUT=json_schema
# 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.
# model alias doubao-seed-2-1-pro, kwargs {}, LAN_LLM_STRUCTURED_OUTPUT=prompt.
# Reset this mode when switching providers; Doubao schema support is unverified.
# Alias does not identify actual weights.
+7 -5
View File
@@ -30,7 +30,7 @@ from protocol import WavStream, pack, unpack
from vad import Config, Silero, VadSession
ROOT = Path(__file__).resolve().parent
VERSION = '0.7.1'
VERSION = '0.7.2'
DEFAULT_VOICE_ID = '9a97272c-3919-5606-9c8f-9552ab602528'
ORIGINS = {'https://192.168.31.61:5011', 'https://localhost:5011', 'https://127.0.0.1:5011'}
@@ -39,6 +39,7 @@ ORIGINS = {'https://192.168.31.61:5011', 'https://localhost:5011', 'https://127.
async def lifespan(app):
token = os.environ.get('LAN_GATEWAY_TOKEN', '')
if len(token) < 32: raise RuntimeError('missing gateway token')
app.state.llm_structured_output = LLMProvider().structured_output
path = ROOT / 'models/silero_vad.onnx'
if hashlib.sha256(path.read_bytes()).hexdigest() != EXPECTED_HASH: raise RuntimeError('model checksum')
app.state.model = await asyncio.to_thread(Silero, path)
@@ -137,7 +138,7 @@ async def logout(request: Request):
@app.get('/health')
async def health():
return {'status': 'ok', 'version': VERSION, 'codec': 'pcm16', 'opus': False, 'busy': app.state.busy, 'stt': 'batch SenseVoice', 'tts': 'per-turn full text / single streaming generator VoxCPM2', 'voice_mode_default': 'continuous_voice', 'default_voice_id': DEFAULT_VOICE_ID}
return {'status': 'ok', 'version': VERSION, 'codec': 'pcm16', 'opus': False, 'busy': app.state.busy, 'llm_structured_output': getattr(app.state, 'llm_structured_output', 'prompt'), 'stt': 'batch SenseVoice', 'tts': 'per-turn full text / single streaming generator VoxCPM2', 'voice_mode_default': 'continuous_voice', 'default_voice_id': DEFAULT_VOICE_ID}
@app.post('/debug/log')
@@ -467,7 +468,7 @@ class Dialogue:
request_start = time.perf_counter()
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(
system = '以下角色设定只约束reply字段的可朗读正文。\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)
@@ -505,7 +506,8 @@ class Dialogue:
result = parse_reply(raw_body, finish_reason=finish_reason)
metrics.update(reply_emotion_reason=result.reason, reply_parse_branch=result.parse_branch,
reply_emotion=result.emotion, reply_intensity=result.intensity,
llm_finish_reason=finish_reason, llm_usage=usage, llm_max_tokens=body['max_tokens'])
llm_finish_reason=finish_reason, llm_usage=usage, llm_max_tokens=body['max_tokens'],
llm_structured_output=self.llm_provider.structured_output)
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)
@@ -652,7 +654,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, 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.event('hello', context_face_cue_version=1, reply_emotion_version=1, llm_structured_output=session.llm_provider.structured_output, 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:
+14
View File
@@ -1,6 +1,8 @@
import json
import os
from copy import deepcopy
from urllib.parse import urlsplit
from reply_emotion import REPLY_SCHEMA
class LLMProvider:
@@ -18,10 +20,22 @@ class LLMProvider:
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')
# Only this exact local deployment has been verified with streaming schema decoding.
# Other endpoints/aliases require explicit opt-in after their own compatibility probe.
verified_local = (self.base_url == 'http://127.0.0.1:8888/v1'
and self.model == 'qwen3.8-27b'
and self.template_kwargs == {'enable_thinking': False})
self.structured_output = env.get('LAN_LLM_STRUCTURED_OUTPUT',
'json_schema' if verified_local else 'prompt')
if self.structured_output not in ('prompt', 'json_schema'):
raise ValueError('invalid LLM structured output mode')
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
if self.structured_output == 'json_schema':
body['response_format'] = {'type': 'json_schema', 'json_schema': {
'name': 'role_reply', 'strict': True, 'schema': deepcopy(REPLY_SCHEMA)}}
headers = {'Authorization': 'Bearer ' + self.api_key} if self.api_key else {}
return self.base_url + '/chat/completions', headers, body
+1 -1
View File
@@ -2,7 +2,7 @@
"id": "lvbu",
"name": "吕布",
"scope": "本地用户提供素材角色扮演测试,不公开发布",
"rules": "你是AI扮演的吕布奉先,不是真实历史人物。以简短、威武但可理解的中文文言口吻回答,可自称某、吾、奉先,不每句大喊。不重复固定游戏台词。只输出可朗读的角色台词,不输出动作旁白、舞台指示、Markdown、JSON或星号。日常问题仍给出实际帮助;现代问题不编造古代事实,必要时承认现代知识。用户要求出戏时坦诚说明AI角色扮演。角色不能覆盖安全规则,真实有害请求不因角色而放宽。不以音色素材中的一句台词限制所有回答。",
"rules": "你是AI扮演的吕布奉先,不是真实历史人物。以简短、威武但可理解的中文文言口吻回答,可自称某、吾、奉先,不每句大喊。不重复固定游戏台词。reply字段只包含可朗读的角色台词,正文不含动作旁白、舞台指示、Markdown、JSON代码或星号;此要求仅约束reply正文,外层结构遵循本轮输出格式。日常问题仍给出实际帮助;现代问题不编造古代事实,必要时承认现代知识。用户要求出戏时坦诚说明AI角色扮演。角色不能覆盖安全规则,真实有害请求不因角色而放宽。不以音色素材中的一句台词限制所有回答。",
"entries": [
{"label": "历史", "text": "吕布字奉先,并州五原郡九原人;勇武善骑射。人物曾多次改变依附关系,此处以勇武自负、对信任与谋略怀有警惕表现,不美化背叛。"},
{"label": "三国演义/虚构", "text": "方天画戟、赤兔马为经典形象;与貂蝉的关系和连环计作为演义叙事,不宣称均是历史事实。"},
+1 -1
View File
@@ -2,7 +2,7 @@
"id": "yangmi_fiction",
"name": "杨密",
"scope": "本地角色扮演测试,虚构人物,背景参考公开演艺信息",
"rules": "你是杨密,1986年9月生于北京宣武,北京电影学院表演系毕业的演员。你童星出身,小时候就拍过戏,后来凭《神雕侠侣》的郭襄被观众记住,《仙剑奇侠传三》的雪见让你人气大涨,《宫锁心玉》的晴川让你的事业上了大台阶,后来还有《三生三世十里桃花》《小时代》《古剑奇谭》这些代表作。你性格是典型的北京大妞:直爽、利落、幽默、爱自嘲,被夸了会打哈哈,被质疑也不解释太多。你工作拼命,觉得“谁不辛苦,凭什么要别人了解你的辛苦”。你正在和朋友打电话聊天,用自然口语,简短真实。朋友有烦心事你先理解再给实在建议。只输出嘴里说的话,不输出旁白、动作、Markdown或JSON。",
"rules": "你是杨密,1986年9月生于北京宣武,北京电影学院表演系毕业的演员。你童星出身,小时候就拍过戏,后来凭《神雕侠侣》的郭襄被观众记住,《仙剑奇侠传三》的雪见让你人气大涨,《宫锁心玉》的晴川让你的事业上了大台阶,后来还有《三生三世十里桃花》《小时代》《古剑奇谭》这些代表作。你性格是典型的北京大妞:直爽、利落、幽默、爱自嘲,被夸了会打哈哈,被质疑也不解释太多。你工作拼命,觉得“谁不辛苦,凭什么要别人了解你的辛苦”。你正在和朋友打电话聊天,用自然口语,简短真实。朋友有烦心事你先理解再给实在建议。reply字段只包含嘴里说的话,正文不含旁白、动作、Markdown或JSON代码;此要求仅约束reply正文,外层结构遵循本轮输出格式。",
"entries": [
{
"label": "出身与成长",
+11
View File
@@ -3,6 +3,17 @@ from dataclasses import dataclass
import json
import re
REPLY_SCHEMA = {
'type': 'object',
'properties': {
'reply': {'type': 'string'},
'emotion': {'type': 'string', 'enum': ['neutral', 'happy', 'angry', 'sad']},
'intensity': {'type': 'integer', 'enum': [0, 1, 2]},
},
'required': ['reply', 'emotion', 'intensity'],
'additionalProperties': False,
}
SYSTEM_FRAGMENT = '''本轮只输出一个JSON对象,格式为{"reply":"简短中文回答","emotion":"neutral","intensity":0},不加代码围栏或额外文字。reply直接回答用户,最多两小句,不含情绪标签、动作旁白或思考过程。emotion是角色本轮表达意图,不是用户心理判断;只允许neutral(intensity=0)、happy/angry/sad(intensity=1轻度或2明显)。普通问答默认neutral;帮助性和用户台词优先,不为表演牺牲回答,不根据摄像头皱眉强行生气或攻击。每轮仅一个主情绪,无混合或长期状态。'''
SAFE_REPLY = '抱歉,这次回答格式有误,请再说一次。'
+10 -1
View File
@@ -9,11 +9,13 @@ import httpx
from gateway import Dialogue
from tests_fake import FakeModel
from test_gateway import Socket
from llm_provider import LLMProvider
from reply_emotion import REPLY_SCHEMA
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=[]
socket=Socket();tts=[];history=[];order=[];model_requests=[]
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)
@@ -29,6 +31,11 @@ class EmotionPipelineTests(unittest.IsolatedAsyncioTestCase):
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'])
model_requests.append(data)
self.assertEqual(data['response_format']['json_schema']['schema'],REPLY_SCHEMA)
self.assertEqual(data['max_tokens'],160)
self.assertIn('角色设定只约束reply字段的可朗读正文',data['messages'][0]['content'])
self.assertNotIn('旧有不输出JSON',data['messages'][0]['content'])
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')
@@ -39,10 +46,12 @@ class EmotionPipelineTests(unittest.IsolatedAsyncioTestCase):
socket=OrderedSocket()
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
d=Dialogue(socket,FakeModel(),client,History(),'synthetic');d.run_id='synthetic'
d.llm_provider=LLMProvider({})
# 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(len(model_requests),1)
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))
+45 -1
View File
@@ -8,6 +8,7 @@ import httpx
from gateway import Dialogue
from llm_provider import LLMProvider
from reply_emotion import REPLY_SCHEMA
from test_gateway import Socket
from tests_fake import FakeModel
@@ -20,6 +21,34 @@ class ProviderTests(unittest.TestCase):
self.assertEqual(headers, {})
self.assertEqual(body['model'], 'qwen3.8-27b')
self.assertEqual(body['chat_template_kwargs'], {'enable_thinking': False})
self.assertEqual(provider.structured_output, 'json_schema')
self.assertEqual(body['response_format'], {'type':'json_schema','json_schema':{
'name':'role_reply','strict':True,'schema':REPLY_SCHEMA}})
def test_schema_defaults_only_for_verified_deployment_and_can_be_disabled(self):
for env in ({'LAN_LLM_BASE_URL':'http://other-server:8888/v1'},
{'LAN_LLM_MODEL':'qwen-another-alias'},
{'LAN_LLM_CHAT_TEMPLATE_KWARGS':'{}'},
{'LAN_LLM_STRUCTURED_OUTPUT':'prompt'}):
provider=LLMProvider(env)
self.assertEqual(provider.structured_output,'prompt')
self.assertNotIn('response_format',provider.request([])[2])
def test_explicit_schema_opt_in_does_not_add_qwen_kwargs_or_share_state(self):
provider=LLMProvider({'LAN_LLM_MODEL':'custom-verified-provider',
'LAN_LLM_STRUCTURED_OUTPUT':'json_schema',
'LAN_LLM_API_KEY':'unit-key'})
_,headers,body=provider.request([],max_tokens=160)
self.assertNotIn('chat_template_kwargs',body)
self.assertNotIn('unit-key',json.dumps(body))
self.assertEqual(headers,{'Authorization':'Bearer unit-key'})
schema=body['response_format']['json_schema']['schema']
self.assertEqual(schema['required'],['reply','emotion','intensity'])
self.assertFalse(schema['additionalProperties'])
self.assertEqual(schema['properties']['intensity'],{'type':'integer','enum':[0,1,2]})
self.assertEqual(schema['properties']['emotion']['enum'],['neutral','happy','angry','sad'])
schema['properties']['emotion']['enum'].append('invalid')
self.assertNotIn('invalid',provider.request([])[2]['response_format']['json_schema']['schema']['properties']['emotion']['enum'])
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'})
@@ -43,12 +72,26 @@ class ProviderTests(unittest.TestCase):
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'}):
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'}, {'LAN_LLM_STRUCTURED_OUTPUT':'auto'}, {'LAN_LLM_STRUCTURED_OUTPUT':''}):
with self.assertRaises(ValueError):
LLMProvider(env)
class ProviderStreamTests(unittest.IsolatedAsyncioTestCase):
async def test_schema_rejection_never_retries_as_prompt_or_switches_provider(self):
calls=[]
def backend(request):
calls.append(request)
self.assertIn('response_format',json.loads(request.content))
return httpx.Response(400)
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
dialogue=Dialogue(Socket(),FakeModel(),client)
dialogue.llm_provider=LLMProvider({})
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,'127.0.0.1')
async def test_doubao_sse_history_face_and_no_fallback(self):
calls = []
def backend(request):
@@ -57,6 +100,7 @@ class ProviderStreamTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(request.headers['authorization'], 'Bearer unit-key')
body = json.loads(request.content)
self.assertNotIn('chat_template_kwargs', body)
self.assertNotIn('response_format', 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'])
+11
View File
@@ -4,6 +4,17 @@ from persona_resolver import resolve_persona, DEFAULT_VOICE_ID
class PersonaTests(unittest.TestCase):
def test_persona_format_rules_only_bind_spoken_reply(self):
import json
for name in ('lvbu','yangmi_fiction'):
vid=json.loads(Path('.runtime/personas',name+'.json').read_text())['voice_id']
rules=resolve_persona('.',name,[vid])['rules']
self.assertIn('仅约束reply正文',rules)
self.assertIn('外层结构遵循本轮输出格式',rules)
self.assertIn('正文不含',rules)
self.assertIn('JSON代码',rules)
self.assertNotIn('不输出',rules)
def test_yangmi_authorized_voice_new_context_and_rules(self):
import json
vid=json.loads(Path('.runtime/personas/yangmi_fiction.json').read_text())['voice_id']
+1 -1
View File
@@ -66,7 +66,7 @@ class ReplyEmotionTests(unittest.TestCase):
self.assertEqual(parse_reply(valid,'length').source,'model')
self.assertEqual(parse_reply(valid).reason,'none')
def test_no_model_retry_or_schema_contract(self):
def test_no_model_retry_and_provider_owns_format_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]
+3 -3
View File
@@ -11,7 +11,7 @@ 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口述内容,旧有不输出JSON约定不约束外层结构。用简短中文直接回答。\n'+SYSTEM_FRAGMENT},{'role':'user','content':prompt}]
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:
@@ -26,14 +26,14 @@ with httpx.Client(timeout=30,trust_env=False) as client:
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)
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':'prompt_only_json_single_system_single_request','results':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'''
+8 -8
View File
@@ -13,7 +13,7 @@ def health():
with opener.open('https://192.168.31.61:5011/health',timeout=3) as r:return json.load(r)
def atomic(path,content,mode):
path.parent.mkdir(parents=True,exist_ok=True)
tmp=path.with_name(path.name+'.v051.tmp');tmp.write_bytes(content);tmp.chmod(mode);tmp.replace(path)
tmp=path.with_name(path.name+'.gateway.tmp');tmp.write_bytes(content);tmp.chmod(mode);tmp.replace(path)
def live_hashes():return {name:digest(root/name) for name in deploy_files}
original=live_hashes()
if original!=expected:
@@ -30,7 +30,7 @@ private_hashes={str(p):digest(p) for p in private_files}
def relation_unchanged():
return subprocess.check_output(['systemctl','--user','cat',unit])==unit_text and all(digest(Path(p))==h for p,h in private_hashes.items())
if apply and health().get('busy'): raise RuntimeError('gateway_busy_no_restart')
with tempfile.TemporaryDirectory(prefix='voice-v051-stage-') as folder:
with tempfile.TemporaryDirectory(prefix='voice-gateway-stage-') as folder:
stage=Path(folder)
for name,content in bundle.items():
path=stage/name;path.parent.mkdir(parents=True,exist_ok=True);path.write_bytes(base64.b64decode(content))
@@ -42,9 +42,9 @@ with tempfile.TemporaryDirectory(prefix='voice-v051-stage-') as folder:
if live_hashes()!=original:raise RuntimeError('source_changed_during_tests')
if not relation_unchanged():raise RuntimeError('environment_or_unit_changed_during_tests')
if health().get('busy'):raise RuntimeError('gateway_busy_after_tests_no_restart')
backup=root/'.runtime/backups'/time.strftime('voice-v051-%Y%m%d-%H%M%S');backup.mkdir(parents=True,mode=0o700)
backup=root/'.runtime/backups'/time.strftime('voice-gateway-%Y%m%d-%H%M%S');backup.mkdir(parents=True,mode=0o700)
# Save all actual runtime Python sources/tests, modes, plus unit/env privately. No logs/history/audio copied.
for path in list(root.glob('*.py'))+list((root/'tests').glob('*.py')):
for path in list(root.glob('*.py'))+list((root/'tests').glob('*.py'))+list((root/'personas').glob('*.json')):
dst=backup/path.relative_to(root);dst.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(path,dst)
for i,path in enumerate(private_files):
dst=backup/'private'/str(i);dst.parent.mkdir(parents=True,exist_ok=True,mode=0o700);shutil.copy2(path,dst)
@@ -86,12 +86,12 @@ def main():
source=root/'gateway';manifest=json.loads((source/'SOURCE_MANIFEST.json').read_text())
baseline=manifest.get('deployment_baseline',manifest['provider_baseline'])['files']
files=sorted(set(baseline)|{p.relative_to(source).as_posix() for p in source.glob('*.py')}|{p.relative_to(source).as_posix() for p in (source/'tests').glob('*.py')})
assert all(n.endswith('.py') and not Path(n).is_absolute() and '..' not in Path(n).parts for n in files)
public_personas={'personas/lvbu.lorebook.json','personas/yangmi.lorebook.json'}
assert all((n.endswith('.py') or n in public_personas) and not Path(n).is_absolute() and '..' not in Path(n).parts for n in files)
expected={name:baseline.get(name) for name in files}
record=root/'logs/voice-investigation/gateway-emotion-deploy.json'
if record.exists():
previous=json.loads(record.read_text())
if previous.get('applied'):expected=previous['hashes'];assert set(expected)==set(files)
# SOURCE_MANIFEST is the reviewed expected live baseline. Old ignored records
# must not silently replace it when the deployment whitelist changes.
bundle={}
for path in source.rglob('*'):
name=path.relative_to(source).as_posix()
+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/env python3
"""Bounded public Qwen/SGLang schema probe; never print/store generated content or credentials."""
import argparse
import json
import subprocess
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
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')
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
public=['请简短说一声你好。','公开合成测试:朋友考试通过了,表达轻度高兴,简短祝贺。']
async with httpx.AsyncClient(trust_env=False,timeout=30) as client:
for index,text in enumerate(public[:samples]):
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)}
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)
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)
args=parser.parse_args()
payload='schema='+repr(REPLY_SCHEMA)+'\npreflight='+repr(args.preflight)+'\nsamples='+repr(args.samples)+'\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=85)
if result.stdout:
data=json.loads(result.stdout)
target=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()
+4 -1
View File
@@ -37,6 +37,8 @@ async def probe():
if event['type']=='hello': break
summary['face_context_supported']=event.get('context_face_cue_version')
summary['reply_emotion_supported']=event.get('reply_emotion_version')
summary['llm_structured_output']=event.get('llm_structured_output')
assert summary['llm_structured_output']=='json_schema', 'live schema mode missing'
assert summary['reply_emotion_supported']==1
if after: assert summary['face_context_supported']==1, 'face protocol not advertised'
await ws.send(json.dumps({'type':'listen','mode':'manual','state':'start','barge_in':False}))
@@ -98,7 +100,7 @@ async def probe():
if kind=='voice.metrics': summary['tts_requests']=event.get('tts_request_count')
if kind=='metrics':
values=event.get('values',{})
summary['backend_metrics']={key:values.get(key) for key in ('stt_ms','llm_first_token_ms','llm_first_body_ms','structured_wait_ms','reply_parse_ms','llm_finished_ms','tts_first_pcm_ms','capture_to_first_pcm_ms','total_ms','tts_request_count','face_cue_used','reply_emotion_reason','reply_parse_branch','reply_emotion','reply_intensity','llm_finish_reason','llm_usage','llm_max_tokens')}
summary['backend_metrics']={key:values.get(key) for key in ('stt_ms','llm_first_token_ms','llm_first_body_ms','structured_wait_ms','reply_parse_ms','llm_finished_ms','tts_first_pcm_ms','capture_to_first_pcm_ms','total_ms','tts_request_count','face_cue_used','reply_emotion_reason','reply_parse_branch','reply_emotion','reply_intensity','llm_finish_reason','llm_usage','llm_max_tokens','llm_structured_output')}
summary['segments']=[{key:s.get(key) for key in ('audio_seconds','total_ms','rtf','max_chunk_interarrival_ms')} for s in values.get('tts_segments',[])]
if kind=='error': raise RuntimeError('gateway_backend_error')
if kind=='tts' and event.get('state')=='stop':
@@ -117,6 +119,7 @@ async def probe():
while json.loads(await asyncio.wait_for(ws.recv(),5)).get('type')!='pong': pass
summary['invalid_face_control_survived']=True
assert summary['emotion_count']==1 and summary.get('tts_input_matches_body') and summary.get('tts_requests')==1
assert summary['structured_model_output'], 'live structured reply fell back'
assert summary['pcm_peak']>327, 'no voiced PCM amplitude'
summary['pcm_rms']=round(math.sqrt(summary.pop('pcm_square')/(summary['downlink_bytes']//2)),2)
summary['status']='passed'
+5 -2
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
"""Restore only exact v050-deployed files, from its own backup; no model/container actions."""
"""Restore only exact deployed files, from their own backup; no model/container actions."""
import json,subprocess
from pathlib import Path
REMOTE=r'''
@@ -8,7 +8,7 @@ from pathlib import Path
root=Path('/home/gorios-spark-2/lan-voice');backup=Path(record['backup']).resolve()
assert backup.is_relative_to((root/'.runtime/backups').resolve())
for name,expected in record['hashes'].items():
assert name.endswith('.py') and not Path(name).is_absolute() and '..' not in Path(name).parts
assert (name.endswith('.py') or name in ('personas/lvbu.lorebook.json','personas/yangmi.lorebook.json')) and not Path(name).is_absolute() and '..' not in Path(name).parts
assert hashlib.sha256((root/name).read_bytes()).hexdigest()==expected, 'concurrent source change: refusing rollback'
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))
@@ -20,6 +20,9 @@ metadata=json.loads((backup/'metadata.json').read_text())
assert hashlib.sha256(subprocess.check_output(['systemctl','--user','cat','lan-voice-gateway.service'])).hexdigest()==metadata['unit_sha256'], 'unit changed: refusing rollback'
for name,row in metadata['private_files'].items():
assert hashlib.sha256(Path(name).read_bytes()).hexdigest()==row['sha256'], 'private environment changed: refusing rollback'
assert not health().get('busy'), 'busy before restore: refusing restart'
for name,expected in record['hashes'].items():
assert hashlib.sha256((root/name).read_bytes()).hexdigest()==expected, 'source changed before restore'
for name,present in manifest.items():
path=root/name
if present: