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

This commit is contained in:
zenord
2026-10-12 10:57:14 +08:00
parent 19a7adccd9
commit d43c7d4e80
36 changed files with 1264 additions and 98 deletions
+2 -2
View File
@@ -13,7 +13,7 @@ from test_gateway import Socket
class ContinuityTests(unittest.IsolatedAsyncioTestCase):
async def test_multidelta_one_tts_and_realtime_text(self):
async def test_multidelta_one_tts_and_parsed_text(self):
socket=Socket();tts=[]
wav=io.BytesIO()
with wave.open(wav,'wb') as w:
@@ -25,7 +25,7 @@ class ContinuityTests(unittest.IsolatedAsyncioTestCase):
stream=''.join('data: '+json.dumps({'choices':[{'delta':{'content':x}}]},ensure_ascii=False)+'\n\n' for x in parts)+'data: [DONE]\n\n'
return httpx.Response(200,text=stream)
tts.append(json.loads(request.content))
self.assertEqual(len([e for e in socket.events if e['type']=='llm']),3)
self.assertEqual([e['text'] for e in socket.events if e['type']=='llm'], [''.join(parts)])
return httpx.Response(200,content=wav.getvalue())
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
d=Dialogue(socket,FakeModel(),client)
+66
View File
@@ -0,0 +1,66 @@
"""Actual pipeline: one system, parsed body/history/TTS, emotion before any PCM, turn fencing."""
import asyncio
import io
import json
import time
import unittest
import wave
import httpx
from gateway import Dialogue
from tests_fake import FakeModel
from test_gateway import Socket
class EmotionPipelineTests(unittest.IsolatedAsyncioTestCase):
async def test_seven_states_no_envelope_in_body_history_or_tts(self):
for emotion,intensity in [('neutral',0)]+[(e,i) for e in ('happy','angry','sad') for i in (1,2)]+[('invalid',2),('damaged',0)]:
socket=Socket();tts=[];history=[];order=[]
class OrderedSocket(Socket):
async def send_json(self,event): order.append(event['type']);await super().send_json(event)
async def send_bytes(self,frame): order.append('pcm');await super().send_bytes(frame)
class History:
async def begin(self,*args): pass
async def context(self,*args): return []
async def rows(self,*args): return []
async def finish(self,rid,answer,status): history.append((answer,status))
body=json.dumps(dict(reply='测试回答。',emotion=emotion,intensity=intensity),ensure_ascii=False)
if emotion=='damaged':body='{"reply":"测试回答。","emotion":'
expected=(emotion,intensity,'model') if emotion not in ('invalid','damaged') else ('neutral',0,'fallback')
def backend(request):
if 'transcriptions' in request.url.path:return httpx.Response(200,json={'text':'公开测试'})
if 'chat' in request.url.path:
data=json.loads(request.content);self.assertEqual([m['role'] for m in data['messages']],['system','user'])
self.assertNotIn('摄像头观察',data['messages'][0]['content'])
# Even a JSON envelope split inside a key must never leak as text.
return httpx.Response(200,text=''.join('data: '+json.dumps({'choices':[{'delta':{'content':part}}]})+'\n\n' for part in (body[:5],body[5:]))+'data: [DONE]\n\n')
tts.append(json.loads(request.content)['input']);out=io.BytesIO()
with wave.open(out,'wb') as w:
w.setnchannels(1);w.setsampwidth(2);w.setframerate(48000);w.writeframes(b'\x11\x01'*960)
return httpx.Response(200,content=out.getvalue())
socket=OrderedSocket()
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
d=Dialogue(socket,FakeModel(),client,History(),'synthetic');d.run_id='synthetic'
# Exercise both accepted voice modes; both synthesize just the parsed reply once.
d.voice_mode='fragment' if intensity==1 else 'continuous_voice'
await d.run(0,bytes(640))
self.assertEqual(tts,['测试回答。']);self.assertEqual(history,[('测试回答。','completed')])
self.assertEqual([e['text'] for e in socket.events if e['type']=='llm'],['测试回答。'])
events=[e for e in socket.events if e['type']=='reply.emotion'];self.assertEqual(len(events),1)
self.assertEqual((events[0]['emotion'],events[0]['intensity'],events[0]['source'],events[0]['turn_id']),(*expected,0))
self.assertGreater(events[0]['seq'],0);self.assertLess(order.index('reply.emotion'),order.index('pcm'))
self.assertTrue(socket.frames)
async def test_stale_generation_cannot_publish_emotion_or_speak(self):
entered=asyncio.Event();resume=asyncio.Event();socket=Socket()
class Slow(httpx.AsyncByteStream):
async def __aiter__(self):
yield b'data: {"choices":[{"delta":{"content":"{\\\"reply\\\":\\\"hello\\\""}}]}\n\n'
entered.set();await resume.wait()
yield b'data: [DONE]\n\n'
async with httpx.AsyncClient(transport=httpx.MockTransport(lambda req:httpx.Response(200,stream=Slow()))) as client:
d=Dialogue(socket,FakeModel(),client);queue=asyncio.Queue(2)
task=asyncio.create_task(d.generate(0,'test',queue,{},time.perf_counter()))
await entered.wait();await d.invalidate('new_turn');resume.set();await task
self.assertTrue(queue.empty())
self.assertFalse(any(e['type'] in ('llm','reply.emotion') for e in socket.events))
await d.event('reply.emotion',0,emotion='angry',intensity=2,source='model')
self.assertEqual([e['type'] for e in socket.events],['abort'])
+94
View File
@@ -0,0 +1,94 @@
import asyncio
import json
import time
import unittest
from unittest.mock import patch
import httpx
from gateway import Dialogue
from llm_provider import LLMProvider
from test_gateway import Socket
from tests_fake import FakeModel
class ProviderTests(unittest.TestCase):
def test_qwen_default_and_manual_return(self):
provider = LLMProvider({})
url, headers, body = provider.request([{'role': 'user', 'content': '公开问题'}])
self.assertEqual(url, 'http://127.0.0.1:8888/v1/chat/completions')
self.assertEqual(headers, {})
self.assertEqual(body['model'], 'qwen3.8-27b')
self.assertEqual(body['chat_template_kwargs'], {'enable_thinking': False})
def test_doubao_key_only_in_header_and_no_schema_requirement(self):
provider = LLMProvider({'LAN_LLM_BASE_URL': 'http://192.168.31.53:4000/v1/', 'LAN_LLM_MODEL': 'doubao-seed-2-1-pro', 'LAN_LLM_API_KEY': 'unit-key'})
messages = [{'role': 'system', 'content': '简短中文'}, {'role': 'user', 'content': '公开问题'}]
url, headers, body = provider.request(messages)
self.assertEqual(url, 'http://192.168.31.53:4000/v1/chat/completions')
self.assertEqual(headers['Authorization'], 'Bearer unit-key')
self.assertEqual(body['messages'], messages)
self.assertEqual(body['max_tokens'], 64)
self.assertTrue(body['stream'])
self.assertNotIn('chat_template_kwargs', body)
self.assertNotIn('response_format', body)
self.assertNotIn(provider.api_key, json.dumps(body) + url)
self.assertEqual(provider.request(messages, max_tokens=160)[2]['max_tokens'], 160)
def test_custom_kwargs_are_provider_local(self):
custom = LLMProvider({'LAN_LLM_MODEL': 'doubao-seed-2-1-pro', 'LAN_LLM_CHAT_TEMPLATE_KWARGS': '{"custom":true}'})
self.assertEqual(custom.request([])[2]['chat_template_kwargs'], {'custom': True})
self.assertEqual(LLMProvider({}).request([])[2]['chat_template_kwargs'], {'enable_thinking': False})
self.assertNotIn('chat_template_kwargs', LLMProvider({'LAN_LLM_MODEL': 'doubao-seed-2-1-pro'}).request([])[2])
def test_explicit_template_kwargs_and_invalid_configuration(self):
self.assertEqual(LLMProvider({'LAN_LLM_CHAT_TEMPLATE_KWARGS': '{}'}).template_kwargs, {})
for env in ({'LAN_LLM_BASE_URL': 'http://user:password@example.com/v1'}, {'LAN_LLM_BASE_URL': 'http://example.com/v1?key=secret'}, {'LAN_LLM_CHAT_TEMPLATE_KWARGS': '[]'}, {'LAN_LLM_API_KEY': 'bad\nheader'}):
with self.assertRaises(ValueError):
LLMProvider(env)
class ProviderStreamTests(unittest.IsolatedAsyncioTestCase):
async def test_doubao_sse_history_face_and_no_fallback(self):
calls = []
def backend(request):
calls.append(request)
self.assertEqual(str(request.url), 'http://192.168.31.53:4000/v1/chat/completions')
self.assertEqual(request.headers['authorization'], 'Bearer unit-key')
body = json.loads(request.content)
self.assertNotIn('chat_template_kwargs', body)
self.assertEqual(body['max_tokens'], 160)
self.assertEqual(sum(m['role']=='system' for m in body['messages']), 1)
self.assertIn('face-summary', body['messages'][0]['content'])
self.assertEqual(body['messages'][1]['content'], '历史问题')
content=json.dumps({'reply':'公开回答。','emotion':'happy','intensity':1})
return httpx.Response(200, text='data: '+json.dumps({'choices':[{'delta':{'content':content}}]})+'\n\ndata: [DONE]\n\n')
env = {'LAN_LLM_BASE_URL': 'http://192.168.31.53:4000/v1', 'LAN_LLM_MODEL': 'doubao-seed-2-1-pro', 'LAN_LLM_API_KEY': 'unit-key'}
with patch.dict('os.environ', env, clear=True):
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
socket = Socket()
dialogue = Dialogue(socket, FakeModel(), client)
dialogue.contexts[0] = [{'role': 'user', 'content': '历史问题'}]
dialogue.face_messages[0] = [{'content': 'face-summary'}]
queue = asyncio.Queue(2)
await dialogue.generate(0, '公开问题', queue, {}, time.perf_counter())
self.assertEqual(await queue.get(), '公开回答。')
self.assertIsNone(await queue.get())
self.assertEqual(len(calls), 1)
self.assertEqual(dialogue.answers[0], '公开回答。')
self.assertTrue(any(e['type'] == 'llm.finished' for e in socket.events))
emotion=next(e for e in socket.events if e['type']=='reply.emotion')
self.assertEqual((emotion['emotion'],emotion['intensity'],emotion['source']),('happy',1,'model'))
async def test_auth_failure_never_calls_second_provider(self):
calls = []
def backend(request):
calls.append(request)
return httpx.Response(401)
with patch.dict('os.environ', {'LAN_LLM_BASE_URL': 'http://192.168.31.53:4000/v1', 'LAN_LLM_MODEL': 'doubao-seed-2-1-pro'}, clear=True):
async with httpx.AsyncClient(transport=httpx.MockTransport(backend)) as client:
dialogue = Dialogue(Socket(), FakeModel(), client)
with self.assertRaises(httpx.HTTPStatusError):
await dialogue.generate(0, '公开问题', asyncio.Queue(2), {}, time.perf_counter())
self.assertEqual(len(calls), 1)
self.assertEqual(calls[0].url.host, '192.168.31.53')
+46
View File
@@ -0,0 +1,46 @@
import json
import unittest
from reply_emotion import parse_reply, SAFE_REPLY
class ReplyEmotionTests(unittest.TestCase):
def test_all_seven_states(self):
for emotion, intensity in [('neutral',0)]+[(e,i) for e in ('happy','angry','sad') for i in (1,2)]:
with self.subTest(emotion=emotion,intensity=intensity):
result=parse_reply(json.dumps(dict(reply='公开回答。',emotion=emotion,intensity=intensity)))
self.assertEqual((result.reply,result.emotion,result.intensity,result.source),('公开回答。',emotion,intensity,'model'))
def test_invalid_missing_and_wrong_types_keep_reply_fallback(self):
for fields in [dict(),dict(emotion='fear',intensity=2),dict(emotion='happy',intensity=0),
dict(emotion='neutral',intensity=2),dict(emotion='sad',intensity=True),
dict(emotion='happy',intensity=1.0),dict(emotion=[],intensity=1),
dict(emotion='sad',intensity=1,extra='ignored')]:
result=parse_reply(json.dumps(dict(reply='可用正文',**fields)))
self.assertEqual((result.reply,result.emotion,result.intensity,result.source),('可用正文','neutral',0,'fallback'))
def test_damaged_formats_recover_without_reading_envelope(self):
for raw, expected in [
('{"reply":"正文","emotion":','正文'),
('{"reply":"被截断的正文','被截断的正文'),
('{"reply":"转义\\n正文","intensity":???}', '转义\n正文'),
('普通的非JSON回答。','普通的非JSON回答。'),
('{"answer":"兼容正文"}', '兼容正文'),
('```json\n{"reply":"正文"}\n```','正文'),
('{"emotion":"happy"}',SAFE_REPLY),
('{"reply": {"evil":true}}',SAFE_REPLY),
('{"reply":"{\\"emotion\\":\\"happy\\"}"}',SAFE_REPLY),
('',SAFE_REPLY), ('x'*8193, SAFE_REPLY),
]:
with self.subTest(raw=raw):
result=parse_reply(raw)
self.assertEqual(result.reply,expected)
self.assertEqual((result.emotion,result.intensity,result.source),('neutral',0,'fallback'))
def test_no_model_retry_or_schema_contract(self):
from pathlib import Path
source=(Path(__file__).resolve().parents[1]/'gateway.py').read_text()
generate=source.split(' async def generate(')[1].split(' async def synthesize(')[0]
self.assertEqual(generate.count("self.client.stream('POST'"),1)
self.assertEqual(generate.count('self.llm_provider.request('),1)
self.assertNotIn('response_format', generate)
if __name__=='__main__': unittest.main()