Files
baji-vc/gateway/tests/test_llm_provider.py
T

141 lines
8.3 KiB
Python

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 reply_emotion import REPLY_SCHEMA
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})
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'})
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'][1:], messages[1:])
self.assertTrue(body['messages'][0]['content'].startswith(messages[0]['content']))
self.assertIn('时区:Asia/Shanghai', body['messages'][0]['content'])
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'}, {'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):
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.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'])
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')