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

95 lines
5.5 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 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')