fix(gateway): constrain verified Qwen replies to emotion schema
This commit is contained in:
@@ -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.
|
||||
|
||||
@@ -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
@@ -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
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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": "方天画戟、赤兔马为经典形象;与貂蝉的关系和连环计作为演义叙事,不宣称均是历史事实。"},
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"id": "yangmi_fiction",
|
||||
"name": "杨密",
|
||||
"scope": "本地角色扮演测试,虚构人物,背景参考公开演艺信息",
|
||||
"rules": "你是杨密,1986年9月生于北京宣武,北京电影学院表演系毕业的演员。你童星出身,小时候就拍过戏,后来凭《神雕侠侣》的郭襄被观众记住,《仙剑奇侠传三》的雪见让你人气大涨,《宫锁心玉》的晴川让你的事业上了大台阶,后来还有《三生三世十里桃花》《小时代》《古剑奇谭》这些代表作。你性格是典型的北京大妞:直爽、利落、幽默、爱自嘲,被夸了会打哈哈,被质疑也不解释太多。你工作拼命,觉得“谁不辛苦,凭什么要别人了解你的辛苦”。你正在和朋友打电话聊天,用自然口语,简短真实。朋友有烦心事你先理解再给实在建议。只输出嘴里说的话,不输出旁白、动作、Markdown或JSON。",
|
||||
"rules": "你是杨密,1986年9月生于北京宣武,北京电影学院表演系毕业的演员。你童星出身,小时候就拍过戏,后来凭《神雕侠侣》的郭襄被观众记住,《仙剑奇侠传三》的雪见让你人气大涨,《宫锁心玉》的晴川让你的事业上了大台阶,后来还有《三生三世十里桃花》《小时代》《古剑奇谭》这些代表作。你性格是典型的北京大妞:直爽、利落、幽默、爱自嘲,被夸了会打哈哈,被质疑也不解释太多。你工作拼命,觉得“谁不辛苦,凭什么要别人了解你的辛苦”。你正在和朋友打电话聊天,用自然口语,简短真实。朋友有烦心事你先理解再给实在建议。reply字段只包含嘴里说的话,正文不含旁白、动作、Markdown或JSON代码;此要求仅约束reply正文,外层结构遵循本轮输出格式。",
|
||||
"entries": [
|
||||
{
|
||||
"label": "出身与成长",
|
||||
|
||||
@@ -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 = '抱歉,这次回答格式有误,请再说一次。'
|
||||
|
||||
|
||||
@@ -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))
|
||||
|
||||
@@ -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'])
|
||||
|
||||
@@ -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']
|
||||
|
||||
@@ -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]
|
||||
|
||||
Reference in New Issue
Block a user