用户要求"全部超时做成可调"。改造前 15 个超时散在 10 个文件里当模块级常量, 说不清一共有几个,也答不了"哪些能调"。 内核 - 新增 android/kernel/timeouts.py:**超时的唯一一份定义**(DEFAULT + SPECS), 带每项的 名字/分组/说明/默认值/上下界;get() 一律夹取,用户填什么都不炸 - 新增 GET/POST /api/timeouts(清单 + 当前值 + 保存 + 恢复默认) - 各处改现读:tools_runtime(tool)、builtin_tools(shell/pythonRun)、 doubao_entry(termux)、providers(model)、speech(tts/stt)、 mcp_client(请求/连接/调用)、meeting(meetingNode)、custom_nodes(customNode)、 app.py 的 SSE 心跳 - ask_user / show_ui 用 TIMEOUT_KEYS 声明"哪个参数该用设置里的值", 内核调用前注入(工具的默认值退化成单独跑时的兜底) - store.py:timeouts 走**整体替换**而不是深合并 —— 深合并会让"改回默认"删不掉 安卓 - data/AppTimeouts.kt:客户端缓存(OkHttp 的 readTimeout、文件选择没法现问内核) - KernelClient:readTimeout 跟着 sseRead 走,改完重建连接池;新增 timeouts 接口 - ui/TimeoutsScreen.kt:全屏界面,按分组列出、-/+ 与输入框、恢复默认 - 设置页加「超时」卡片入口;NativeBridge 的本地接口请求 / 选文件等待接上 - Settings 模型加 TimeoutItem / TimeoutsState(字段全部来自内核) Node 端(Web/exe) - 新增 server/src/timeouts.mjs(和 Python 那份逐字对应) - config.mjs 加 timeouts(同样整体替换);speech / python-tools / mcp / providers 各处改读;index.mjs 加 /api/timeouts 验证 - 新增 scripts/verify-timeouts.py:清单完整性、边界容错(文字/空串/负数/超大值/ 带单位/None)、**扫内核有没有漏网的硬编码超时**(带白名单)、 工具侧声明、以及和 Node 端逐项对拍 - 实测真机:界面显示 18 项来自内核 → 点 + 保存 → 内核 heartbeat 15→25 → 恢复默认 → 回 15;askUser 显示"不限时" 文档:README §3.13;docs/AI界面能力.md 的"不限时要三处一起改"补上可调入口。 版本 2.0.46。
299 lines
12 KiB
Python
299 lines
12 KiB
Python
"""
|
||
上游调用层:火山方舟 / 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
|
||
import timeouts
|
||
|
||
# 推理模型(o 系列 / gpt-5 系)不接受 temperature 等采样参数
|
||
REASONING_MODEL_RE = re.compile(r'^(o1|o3|o4|gpt-5|gpt-6)', re.IGNORECASE)
|
||
|
||
# ★ 模型请求的超时**不在这里** —— 它和别的超时一起收在 timeouts.py 里
|
||
# (设置 → 超时 → 等模型回复)。以前这里是 `DEFAULT_TIMEOUT_MS = 180000`,
|
||
# 用户改不了;现在每次请求现读,改了立刻生效、不用重启。
|
||
def model_timeout_s() -> float:
|
||
"""等模型返回的秒数(读设置,出错时回落 180 秒)"""
|
||
try:
|
||
return float(timeouts.get('model'))
|
||
except Exception: # noqa: BLE001 - 设置读不出来也不能让请求发不出去
|
||
return 180.0
|
||
|
||
|
||
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=model_timeout_s())
|
||
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=model_timeout_s())
|
||
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)}
|