一个界面照着豆包抠的 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。
237 lines
7.7 KiB
JavaScript
237 lines
7.7 KiB
JavaScript
/**
|
||
* 提供商调用层:火山方舟 / OpenAI / DeepSeek / Kimi / 智谱 / 通义 / 硅基流动 / OpenRouter …
|
||
* 全都是 OpenAI 兼容协议,所以这里只有一份实现。
|
||
* 统一暴露:
|
||
* chatOnce() - 非流式
|
||
* streamChat() - 流式(async generator,吐 text / tool_calls / usage)
|
||
* listModels() - 拉取模型列表(可选能力,失败不致命)
|
||
*/
|
||
|
||
import { PROVIDER_PRESETS } from './config.mjs';
|
||
|
||
function joinUrl(baseUrl, suffix) {
|
||
return `${String(baseUrl || '').replace(/\/+$/, '')}${suffix}`;
|
||
}
|
||
|
||
/**
|
||
* 思考强度怎么传给服务端 —— 由预设里的 thinkingMode 决定。
|
||
*
|
||
* 别写死成"是 ark 就发 thinking、是 openai 就发 reasoning_effort":
|
||
* 现在支持的兼容厂商有十来家,各自认的字段不一样,
|
||
* 而**给不认这个字段的服务发过去,有些会直接 400**。所以认不出来的一律 'none'。
|
||
*
|
||
* 'ark' → 顶层 thinking: {type: enabled|disabled}
|
||
* 'effort' → reasoning_effort: low|medium|high
|
||
* 'none' → 什么都不发(DeepSeek / Kimi / 通义 / 硅基流动 等自己决定要不要思考)
|
||
*/
|
||
export function thinkingModeOf(provider) {
|
||
return PROVIDER_PRESETS[provider]?.thinkingMode || 'none';
|
||
}
|
||
|
||
function applyThinking({ provider, level, body }) {
|
||
const value = level || 'auto';
|
||
if (value === 'auto') return body;
|
||
|
||
const mode = thinkingModeOf(provider);
|
||
if (mode === 'ark') {
|
||
body.thinking = { type: value === 'off' ? 'disabled' : 'enabled' };
|
||
return body;
|
||
}
|
||
if (mode === 'effort') {
|
||
if (value === 'off') {
|
||
delete body.reasoning_effort;
|
||
} else {
|
||
body.reasoning_effort = value === 'high' ? 'high' : value === 'low' ? 'low' : 'medium';
|
||
}
|
||
}
|
||
return body;
|
||
}
|
||
|
||
/**
|
||
* 推理模型(o 系列 / gpt-5 系)不接受 temperature 等采样参数,
|
||
* 而且"传默认值"也算传了,所以这里直接 delete,不是改回默认值。
|
||
*/
|
||
const REASONING_MODEL_RE = /^(o1|o3|o4|gpt-5|gpt-6)/i;
|
||
|
||
export function normalizeBody({ provider, model, thinkingLevel, body }) {
|
||
if (thinkingModeOf(provider) === 'effort' && REASONING_MODEL_RE.test(String(model || ''))) {
|
||
delete body.temperature;
|
||
delete body.top_p;
|
||
delete body.presence_penalty;
|
||
delete body.frequency_penalty;
|
||
delete body.logprobs;
|
||
if (body.max_tokens != null) {
|
||
body.max_completion_tokens = body.max_tokens;
|
||
delete body.max_tokens;
|
||
}
|
||
// 推理模型默认就带思考,off 时明确要求最小
|
||
if (thinkingLevel === 'off') body.reasoning_effort = 'minimal';
|
||
}
|
||
return applyThinking({ provider, level: thinkingLevel, body });
|
||
}
|
||
|
||
function buildBody({ provider, model, messages, tools, temperature, stream, thinkingLevel }) {
|
||
const body = {
|
||
model,
|
||
messages,
|
||
stream: Boolean(stream),
|
||
};
|
||
if (typeof temperature === 'number' && Number.isFinite(temperature)) {
|
||
body.temperature = temperature;
|
||
}
|
||
if (Array.isArray(tools) && tools.length > 0) {
|
||
body.tools = tools;
|
||
body.tool_choice = 'auto';
|
||
}
|
||
return normalizeBody({ provider, model, thinkingLevel, body });
|
||
}
|
||
|
||
async function post({ baseUrl, apiKey, body, signal, timeoutMs = 180000 }) {
|
||
if (!apiKey) {
|
||
throw new Error('缺少 API Key:请在「设置 → AI 内核」里填写,或在 server/.env 里配置');
|
||
}
|
||
const controller = new AbortController();
|
||
const timer = setTimeout(() => controller.abort(new Error('上游请求超时')), timeoutMs);
|
||
const onAbort = () => controller.abort(signal?.reason);
|
||
signal?.addEventListener('abort', onAbort, { once: true });
|
||
try {
|
||
return await fetch(joinUrl(baseUrl, '/chat/completions'), {
|
||
method: 'POST',
|
||
headers: {
|
||
'Content-Type': 'application/json',
|
||
Authorization: `Bearer ${apiKey}`,
|
||
},
|
||
body: JSON.stringify(body),
|
||
signal: controller.signal,
|
||
});
|
||
} finally {
|
||
clearTimeout(timer);
|
||
signal?.removeEventListener('abort', onAbort);
|
||
}
|
||
}
|
||
|
||
export async function chatOnce(opts) {
|
||
const res = await post({ ...opts, body: buildBody({ ...opts, stream: false }) });
|
||
const text = await res.text();
|
||
if (!res.ok) throw new Error(`上游 ${res.status}:${text.slice(0, 600)}`);
|
||
let json;
|
||
try {
|
||
json = JSON.parse(text);
|
||
} catch {
|
||
throw new Error(`上游返回非 JSON:${text.slice(0, 300)}`);
|
||
}
|
||
const message = json.choices?.[0]?.message || {};
|
||
return {
|
||
content: message.content || '',
|
||
reasoning: message.reasoning_content || '',
|
||
toolCalls: (message.tool_calls || []).map((tc) => ({
|
||
id: tc.id,
|
||
name: tc.function?.name,
|
||
argsRaw: tc.function?.arguments || '{}',
|
||
args: safeParse(tc.function?.arguments),
|
||
})),
|
||
usage: json.usage,
|
||
raw: json,
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 流式调用。yield 出的事件:
|
||
* {type:'text', text}
|
||
* {type:'reasoning', text}
|
||
* {type:'tool_calls', toolCalls}
|
||
* {type:'usage', usage}
|
||
* {type:'finish', reason}
|
||
*/
|
||
export async function* streamChat(opts) {
|
||
const res = await post({ ...opts, body: buildBody({ ...opts, stream: true }) });
|
||
if (!res.ok || !res.body) {
|
||
const detail = await res.text().catch(() => '');
|
||
throw new Error(`上游 ${res.status}:${detail.slice(0, 600)}`);
|
||
}
|
||
|
||
const reader = res.body.getReader();
|
||
const decoder = new TextDecoder();
|
||
const toolAcc = new Map();
|
||
let buffer = '';
|
||
let finishReason = null;
|
||
|
||
while (true) {
|
||
const { done, value } = await reader.read();
|
||
if (done) break;
|
||
buffer += decoder.decode(value, { stream: true });
|
||
|
||
let nl;
|
||
while ((nl = buffer.indexOf('\n')) >= 0) {
|
||
const line = buffer.slice(0, nl).trim();
|
||
buffer = buffer.slice(nl + 1);
|
||
if (!line || line.startsWith(':')) continue;
|
||
if (!line.startsWith('data:')) continue;
|
||
const payload = line.slice(5).trim();
|
||
if (payload === '[DONE]') continue;
|
||
let json;
|
||
try {
|
||
json = JSON.parse(payload);
|
||
} catch {
|
||
continue;
|
||
}
|
||
const choice = json.choices?.[0];
|
||
if (!choice) {
|
||
if (json.usage) yield { type: 'usage', usage: json.usage };
|
||
continue;
|
||
}
|
||
if (choice.finish_reason) finishReason = choice.finish_reason;
|
||
const delta = choice.delta || {};
|
||
if (typeof delta.reasoning_content === 'string' && delta.reasoning_content) {
|
||
yield { type: 'reasoning', text: delta.reasoning_content };
|
||
}
|
||
if (typeof delta.content === 'string' && delta.content) {
|
||
yield { type: 'text', text: delta.content };
|
||
}
|
||
for (const tc of delta.tool_calls || []) {
|
||
const idx = tc.index ?? 0;
|
||
const acc = toolAcc.get(idx) || { id: '', name: '', argsRaw: '' };
|
||
if (tc.id) acc.id = tc.id;
|
||
if (tc.function?.name) acc.name = tc.function.name;
|
||
if (tc.function?.arguments) acc.argsRaw += tc.function.arguments;
|
||
toolAcc.set(idx, acc);
|
||
}
|
||
if (json.usage) yield { type: 'usage', usage: json.usage };
|
||
}
|
||
}
|
||
|
||
const toolCalls = [...toolAcc.entries()]
|
||
.sort((a, b) => a[0] - b[0])
|
||
.map(([, v], i) => ({
|
||
id: v.id || `call_${i}`,
|
||
name: v.name,
|
||
argsRaw: v.argsRaw || '{}',
|
||
args: safeParse(v.argsRaw),
|
||
}))
|
||
.filter((tc) => tc.name);
|
||
|
||
if (toolCalls.length) yield { type: 'tool_calls', toolCalls };
|
||
yield { type: 'finish', reason: finishReason };
|
||
}
|
||
|
||
export async function listModels({ baseUrl, apiKey, signal }) {
|
||
if (!apiKey) throw new Error('缺少 API Key');
|
||
const res = await fetch(joinUrl(baseUrl, '/models'), {
|
||
headers: { Authorization: `Bearer ${apiKey}` },
|
||
signal,
|
||
});
|
||
if (!res.ok) throw new Error(`上游 ${res.status}`);
|
||
const json = await res.json();
|
||
return (json.data || []).map((m) => m.id).filter(Boolean);
|
||
}
|
||
|
||
export function safeParse(raw) {
|
||
if (raw == null) return {};
|
||
if (typeof raw === 'object') return raw;
|
||
try {
|
||
return JSON.parse(raw);
|
||
} catch {
|
||
return { __raw: String(raw) };
|
||
}
|
||
}
|