import json import os from copy import deepcopy from urllib.parse import urlsplit from reply_emotion import REPLY_SCHEMA from server_clock import ServerClock class LLMProvider: def __init__(self, environ=None): env = os.environ if environ is None else environ self.clock = ServerClock(env.get('LAN_LLM_TIME_ZONE', 'Asia/Shanghai')) 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.expression_prepare = verified_local and env.get('LAN_LLM_EXPRESSION_PREPARE', '1') == '1' self.structured_output = env.get('LAN_LLM_STRUCTURED_OUTPUT', 'json_schema' if verified_local else 'prompt') self.expression_prepare = self.expression_prepare and self.structured_output == 'json_schema' if self.structured_output not in ('prompt', 'json_schema'): raise ValueError('invalid LLM structured output mode') def request(self, messages, *, max_tokens=64, action_plan=False): body = {'model': self.model, 'messages': self.clock.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': from action_reply import ACTION_SCHEMA body['response_format'] = {'type': 'json_schema', 'json_schema': { 'name': 'role_reply', 'strict': True, 'schema': deepcopy(ACTION_SCHEMA if action_plan else REPLY_SCHEMA)}} headers = {'Authorization': 'Bearer ' + self.api_key} if self.api_key else {} return self.base_url + '/chat/completions', headers, body