一个界面照着豆包抠的 AI 助手。主力是安卓端,完全离线自主:不依赖电脑、 不需要另外装 Termux。 安卓端 - 原生 Jetpack Compose,7 个页面,配色/圆角/间距对着真机截图量出来的 - 完整动效:抽屉滑入、页面切换、气泡淡入上移、面板底部升起、typing 三点、按钮回弹 - 内置 Termux:bash/apt/pkg 388 个命令、真 pty 终端; pty 不可用的 ROM 上自动降级成命令控制台 - APK 内嵌 CPython 3.13(Chaquopy),AI 内核跑在手机上 - 设备能力:定位 / 陀螺仪 / 加速度计 / 光线 / 电量 / 剪贴板 - 语音:朗读 + 语音输入,火山豆包音色 / OpenAI 兼容 / 设备自带三级引擎 AI 能力 - 10 家 OpenAI 兼容提供商:方舟 / OpenAI / DeepSeek / Kimi / 智谱 / 通义 / 硅基流动 / OpenRouter / 本地 Ollama / 自定义 - 思考强度按各家支持情况发不同字段(thinking / reasoning_effort / 不发), 认不出来的一律不发,避免给不支持的厂商发字段直接 400 - MCP 三种传输(http / stdio / inproc)、工具热加载、文件上传、权限模式 跨端 - 安卓走原生 Compose,Web / Windows 走 Lynx - Node 与 Python 两份内核接口逐字段一致,关键路径都有对拍脚本 自检脚本(都不需要真 Key) - verify-phone.mjs 设备端 24 项验收 - verify-speech.mjs 语音链路 31 项,两份内核各跑一遍 - parity-thinking.mjs 思考强度映射对拍 - probe-settings-wipe.mjs 设置防清空攻击测试 - mock-llm.mjs 假的 OpenAI + 火山语音服务 许可 MIT;第三方组件(Termux Apache-2.0、Chaquopy、Compose、LynxJS、Electron) 的授权见 LICENSE。
290 lines
12 KiB
Python
290 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
|
||
|
||
# 推理模型(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)}
|