Files
baji-vc/gateway/llm_provider.py
T

42 lines
2.4 KiB
Python

import json
import os
from copy import deepcopy
from urllib.parse import urlsplit
from reply_emotion import REPLY_SCHEMA
class LLMProvider:
def __init__(self, environ=None):
env = os.environ if environ is None else environ
self.base_url = env.get('LAN_LLM_BASE_URL', 'http://127.0.0.1:8888/v1').rstrip('/')
self.model = env.get('LAN_LLM_MODEL', 'qwen3.8-27b')
self.api_key = env.get('LAN_LLM_API_KEY', '')
url = urlsplit(self.base_url)
if url.scheme not in ('http', 'https') or not url.hostname or url.username or url.password or url.query or url.fragment:
raise ValueError('invalid LLM base URL')
if not self.model or any(c in self.api_key for c in '\r\n'):
raise ValueError('invalid LLM configuration')
raw = env.get('LAN_LLM_CHAT_TEMPLATE_KWARGS')
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