""" 上游调用层:火山方舟 / OpenAI / DeepSeek / Kimi / 智谱 / 通义 / 硅基流动 / OpenRouter … 全都是 OpenAI 兼容协议,所以这里只有一份实现。 对应 Node 版 server/src/providers.mjs,对外提供: chat_once() 非流式 stream_chat() 流式(生成器,吐 text / reasoning / tool_calls / usage / finish) list_models() 拉模型列表(可选能力,失败不致命) 为什么用 urllib.request 而不是 requests/httpx: 安卓(Chaquopy)里第三方库要额外打包,而 urllib 是标准库,装包体积为零; 流式读取只要 resp.readline() 逐行解析 SSE 就够了,不需要异步框架。 """ import gzip import json import re import urllib.error import urllib.request from typing import Callable, Iterator, Optional from defaults import PROVIDER_PRESETS # 推理模型(o 系列 / gpt-5 系)不接受 temperature 等采样参数 REASONING_MODEL_RE = re.compile(r'^(o1|o3|o4|gpt-5|gpt-6)', re.IGNORECASE) DEFAULT_TIMEOUT_MS = 180000 def join_url(base_url: str, suffix: str) -> str: return f"{str(base_url or '').rstrip('/')}{suffix}" def thinking_mode_of(provider: str) -> str: """ 这个提供商的思考强度该用哪个字段传 —— 由预设里的 thinkingMode 决定。 别写死成"是 ark 就发 thinking、是 openai 就发 reasoning_effort": 现在支持的兼容厂商有十来家,各家认的字段不一样, 而**给不认这个字段的服务发过去,有些会直接 400**。所以认不出来的一律 'none'。 """ preset = PROVIDER_PRESETS.get(provider) or {} return preset.get('thinkingMode') or 'none' def apply_thinking(provider: str, level: str, body: dict) -> dict: """ 思考强度映射(和 Node 版逐字一致): 'ark' → 顶层 thinking: {type: enabled|disabled} 'effort' → reasoning_effort: low|medium|high 'none' → 什么都不发(DeepSeek / Kimi / 通义 / 硅基流动 等自己决定) """ value = level or 'auto' if value == 'auto': return body mode = thinking_mode_of(provider) if mode == 'ark': body['thinking'] = {'type': 'disabled' if value == 'off' else 'enabled'} return body if mode == 'effort': if value == 'off': body.pop('reasoning_effort', None) else: body['reasoning_effort'] = 'high' if value == 'high' else 'low' if value == 'low' else 'medium' return body def normalize_body(provider: str, model: str, thinking_level: str, body: dict) -> dict: """ 推理模型不接受 temperature/top_p/... ,而且"传默认值"也算传了, 所以这里是 delete 而不是改回默认值(OpenAI 会对未知/不允许的参数直接 400)。 """ if thinking_mode_of(provider) == 'effort' and REASONING_MODEL_RE.match(str(model or '')): for key in ('temperature', 'top_p', 'presence_penalty', 'frequency_penalty', 'logprobs'): body.pop(key, None) if body.get('max_tokens') is not None: body['max_completion_tokens'] = body.pop('max_tokens') # 推理模型默认就带思考,off 时明确要求最小 if thinking_level == 'off': body['reasoning_effort'] = 'minimal' return apply_thinking(provider, thinking_level, body) def build_body(*, provider: str, model: str, messages: list, tools=None, temperature=None, stream: bool, thinking_level: str = 'auto') -> dict: body = {'model': model, 'messages': messages, 'stream': bool(stream)} # 只有真的是数字才带上 temperature(JS 用 typeof === 'number' + isFinite) if isinstance(temperature, (int, float)) and not isinstance(temperature, bool): body['temperature'] = temperature if isinstance(tools, list) and len(tools) > 0: body['tools'] = tools body['tool_choice'] = 'auto' return normalize_body(provider, model, thinking_level, body) class UpstreamError(RuntimeError): """上游返回非 2xx 或网络异常时抛出(消息里带状态码和响应片段)。""" def _request(url: str, api_key: str, body: dict | None = None, method: str = 'POST'): if not api_key: raise UpstreamError('缺少 API Key:请在「设置 → AI 内核」里填写,或在数据目录的 .env 里配置') data = None headers = {'Authorization': f'Bearer {api_key}'} if body is not None: data = json.dumps(body, ensure_ascii=False).encode('utf-8') headers['Content-Type'] = 'application/json' req = urllib.request.Request(url, data=data, headers=headers, method=method) try: # 不用 urlopen 的 with:流式响应要留给调用方边读边消费 return urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_MS / 1000) except urllib.error.HTTPError as exc: detail = '' try: detail = exc.read().decode('utf-8', errors='replace') except Exception: # noqa: BLE001 - 读不到正文就算了 detail = '' raise UpstreamError(f'上游 {exc.code}:{detail[:600]}') from exc except urllib.error.URLError as exc: raise UpstreamError(f'无法连接上游 {url}:{exc.reason}') from exc def _line_source(resp): """ 把响应体变成"可以逐行读的文本流"。 有些网关即使没请求 gzip 也会压缩,这里顺手解一下(br 需要第三方库,不处理)。 """ encoding = (resp.headers.get('Content-Encoding') or '').lower() if 'gzip' in encoding: return gzip.GzipFile(fileobj=resp) return resp def chat_once(*, provider: str, base_url: str, api_key: str, model: str, messages: list, tools=None, temperature=None, thinking_level: str = 'auto', **kwargs) -> dict: """非流式调用(内核目前用不到,保留给脚本/未来接口用)。""" body = build_body(provider=provider, model=model, messages=messages, tools=tools, temperature=temperature, stream=False, thinking_level=thinking_level) resp = _request(join_url(base_url, '/chat/completions'), api_key, body) try: text = resp.read().decode('utf-8', errors='replace') finally: resp.close() try: payload = json.loads(text) except ValueError as exc: raise UpstreamError(f'上游返回非 JSON:{text[:300]}') from exc message = ((payload.get('choices') or [{}])[0] or {}).get('message') or {} return { 'content': message.get('content') or '', 'reasoning': message.get('reasoning_content') or '', 'toolCalls': [ { 'id': tc.get('id'), 'name': (tc.get('function') or {}).get('name'), 'argsRaw': (tc.get('function') or {}).get('arguments') or '{}', 'args': safe_parse((tc.get('function') or {}).get('arguments')), } for tc in (message.get('tool_calls') or []) ], 'usage': payload.get('usage'), 'raw': payload, } def stream_chat(*, provider: str, base_url: str, api_key: str, model: str, messages: list, tools=None, temperature=None, thinking_level: str = 'auto', should_stop: Optional[Callable[[], bool]] = None, **kwargs) -> Iterator[dict]: """ 流式调用。yield 的事件(与 Node 版 streamChat 一一对应): {'type':'text', 'text'} / {'type':'reasoning', 'text'} {'type':'tool_calls', 'toolCalls'} / {'type':'usage', 'usage'} / {'type':'finish', 'reason'} should_stop:客户端断开时由 app.py 传入的回调;每读一行检查一次, 避免上游还在吐字而我们已经没人要了(安卓上尤其费电/费流量)。 """ body = build_body(provider=provider, model=model, messages=messages, tools=tools, temperature=temperature, stream=True, thinking_level=thinking_level) resp = _request(join_url(base_url, '/chat/completions'), api_key, body) tool_acc: dict = {} finish_reason = None try: source = _line_source(resp) while True: if should_stop and should_stop(): raise UpstreamError('客户端断开') raw = source.readline() if not raw: break line = raw.decode('utf-8', errors='replace').strip() if not line or line.startswith(':'): continue if not line.startswith('data:'): continue payload = line[5:].strip() if payload == '[DONE]': continue try: event = json.loads(payload) except ValueError: continue choices = event.get('choices') or [] choice = choices[0] if choices else None if not choice: # 只带 usage 的收尾包(很多网关这么发) if event.get('usage'): yield {'type': 'usage', 'usage': event['usage']} continue if choice.get('finish_reason'): finish_reason = choice['finish_reason'] delta = choice.get('delta') or {} # 思维链增量:方舟用 reasoning_content,部分网关用 reasoning reasoning = delta.get('reasoning_content') if isinstance(reasoning, str) and reasoning: yield {'type': 'reasoning', 'text': reasoning} content = delta.get('content') if isinstance(content, str) and content: yield {'type': 'text', 'text': content} for tc in delta.get('tool_calls') or []: idx = tc.get('index', 0) acc = tool_acc.setdefault(idx, {'id': '', 'name': '', 'argsRaw': ''}) if tc.get('id'): acc['id'] = tc['id'] fn = tc.get('function') or {} if fn.get('name'): acc['name'] = fn['name'] if fn.get('arguments'): acc['argsRaw'] += fn['arguments'] if event.get('usage'): yield {'type': 'usage', 'usage': event['usage']} finally: try: resp.close() except Exception: # noqa: BLE001 - 关闭失败无所谓 pass tool_calls = [] for index, key in enumerate(sorted(tool_acc.keys())): item = tool_acc[key] if not item['name']: continue tool_calls.append({ 'id': item['id'] or f'call_{index}', 'name': item['name'], 'argsRaw': item['argsRaw'] or '{}', 'args': safe_parse(item['argsRaw']), }) if tool_calls: yield {'type': 'tool_calls', 'toolCalls': tool_calls} yield {'type': 'finish', 'reason': finish_reason} def list_models(*, base_url: str, api_key: str) -> list: """ 拉上游模型列表(可选能力)。 注意错误文案要和 Node 版一致:这里**不带响应体**(Node 的 listModels 只抛 `上游 {status}`), 所以没有复用 _request,而是自己发一次请求。 """ if not api_key: raise UpstreamError('缺少 API Key') url = join_url(base_url, '/models') req = urllib.request.Request(url, headers={'Authorization': f'Bearer {api_key}'}, method='GET') try: resp = urllib.request.urlopen(req, timeout=DEFAULT_TIMEOUT_MS / 1000) except urllib.error.HTTPError as exc: raise UpstreamError(f'上游 {exc.code}') from exc except urllib.error.URLError as exc: raise UpstreamError(f'无法连接上游 {url}:{exc.reason}') from exc try: payload = json.loads(resp.read().decode('utf-8', errors='replace')) except ValueError as exc: raise UpstreamError('上游返回非 JSON') from exc finally: resp.close() return [m.get('id') for m in (payload.get('data') or []) if m.get('id')] def safe_parse(raw): """参数可能是字符串(流式拼接)也可能是对象,坏 JSON 时保留原文。""" if raw is None: return {} if isinstance(raw, (dict, list)): return raw try: return json.loads(raw) except (ValueError, TypeError): return {'__raw': str(raw)}