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
+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]