豆包复刻:原生安卓(Compose + 内嵌 Termux)+ Web / Windows
一个界面照着豆包抠的 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。
This commit is contained in:
180
android/kernel/agent_loop.py
Normal file
180
android/kernel/agent_loop.py
Normal file
@@ -0,0 +1,180 @@
|
||||
"""
|
||||
Agent 主循环:系统提示词 + 多轮工具调用 + 流式输出。
|
||||
|
||||
对应 Node 版 server/src/agent.mjs 的 runAgent。两种安全模式:
|
||||
open 所有工具都交给模型
|
||||
restricted 只有白名单里的工具可用(连执行都会再拦一道,见 tools_runtime.execute_tool)
|
||||
|
||||
同步实现(生成器 + 普通函数),因为上游是 stdlib urllib 的阻塞式读取;
|
||||
在 HTTP 服务里每个请求占一个线程,ThreadingHTTPServer 正好够用。
|
||||
"""
|
||||
|
||||
import json
|
||||
from typing import Callable, Optional
|
||||
|
||||
import store
|
||||
import tools_runtime
|
||||
from providers import stream_chat
|
||||
|
||||
MAX_TOOL_RESULT_CHARS = 6000
|
||||
|
||||
|
||||
def truncate(text, max_len: int = MAX_TOOL_RESULT_CHARS) -> str:
|
||||
"""工具结果截断:和 Node 版的 truncate 一样,超长就截断并标注。"""
|
||||
if isinstance(text, str):
|
||||
out = text
|
||||
else:
|
||||
try:
|
||||
out = json.dumps(text, ensure_ascii=False)
|
||||
except (TypeError, ValueError):
|
||||
out = str(text)
|
||||
return f'{out[:max_len]}\n…(已截断)' if len(out) > max_len else out
|
||||
|
||||
|
||||
def _max_rounds(settings: dict) -> int:
|
||||
raw = settings.get('maxRounds')
|
||||
try:
|
||||
value = int(float(raw))
|
||||
except (TypeError, ValueError):
|
||||
value = 6
|
||||
if not value: # 0 / 空 都按默认 6 处理(对应 JS 的 `Number(x) || 6`)
|
||||
value = 6
|
||||
return max(1, min(12, value))
|
||||
|
||||
|
||||
def run_agent(*, settings: dict, messages: list, agent=None, emit: Callable[[dict], None],
|
||||
should_stop: Optional[Callable[[], bool]] = None) -> dict:
|
||||
"""
|
||||
跑一轮完整对话。
|
||||
|
||||
settings 当前设置
|
||||
messages [{role, content}] 历史(不含 system)
|
||||
agent 当前智能体(systemPrompt 覆盖全局的)
|
||||
emit 事件回调,直接往 SSE 里写
|
||||
should_stop 客户端是否已断开(断了就别再往上游要字了)
|
||||
"""
|
||||
provider = store.provider_info(settings)
|
||||
tool_defs = tools_runtime.build_tool_defs(settings)
|
||||
max_rounds = _max_rounds(settings)
|
||||
mode = (settings.get('security') or {}).get('mode') or 'open'
|
||||
system_prompt = ((agent or {}).get('systemPrompt') or '').strip() or settings.get('systemPrompt') or ''
|
||||
thinking_level = settings.get('thinkingLevel') or 'auto'
|
||||
|
||||
emit({
|
||||
'type': 'start',
|
||||
'provider': settings.get('provider'),
|
||||
'model': provider.get('model'),
|
||||
'tools': len(tool_defs),
|
||||
'mode': mode,
|
||||
'thinkingLevel': thinking_level,
|
||||
'agent': {'id': agent.get('id'), 'name': agent.get('name')} if agent else None,
|
||||
})
|
||||
|
||||
convo = []
|
||||
if system_prompt.strip():
|
||||
convo.append({'role': 'system', 'content': system_prompt})
|
||||
convo.extend(messages)
|
||||
|
||||
answer = ''
|
||||
reasoning_all = ''
|
||||
tool_call_count = 0
|
||||
usage = None
|
||||
|
||||
for round_index in range(max_rounds):
|
||||
round_text = ''
|
||||
tool_calls = []
|
||||
|
||||
for event in stream_chat(
|
||||
# 注意:这里的 provider 是"提供商名字"(ark/openai),
|
||||
# 和上面 provider_info 出来的对象不是一回事
|
||||
provider=settings.get('provider'),
|
||||
base_url=provider.get('baseUrl'),
|
||||
api_key=settings.get('apiKey') or '',
|
||||
model=provider.get('model'),
|
||||
messages=convo,
|
||||
tools=tool_defs if tool_defs else None,
|
||||
temperature=settings.get('temperature'),
|
||||
thinking_level=thinking_level,
|
||||
should_stop=should_stop,
|
||||
):
|
||||
kind = event.get('type')
|
||||
if kind == 'text':
|
||||
round_text += event['text']
|
||||
# 所有轮次的文本都要累积:只调用工具的那一轮通常没有正文,
|
||||
# 真正给用户的回答在最后一轮,漏掉会让保存下来的消息变空。
|
||||
answer += event['text']
|
||||
emit({'type': 'delta', 'text': event['text'], 'round': round_index})
|
||||
elif kind == 'reasoning':
|
||||
reasoning_all += event['text']
|
||||
emit({'type': 'reasoning', 'text': event['text'], 'round': round_index})
|
||||
elif kind == 'tool_calls':
|
||||
tool_calls = event.get('toolCalls') or []
|
||||
elif kind == 'usage':
|
||||
usage = event.get('usage')
|
||||
|
||||
if not tool_calls:
|
||||
emit({
|
||||
'type': 'done',
|
||||
'content': answer,
|
||||
'reasoning': reasoning_all,
|
||||
'rounds': round_index + 1,
|
||||
'toolCalls': tool_call_count,
|
||||
'usage': usage,
|
||||
})
|
||||
return {
|
||||
'content': answer, 'reasoning': reasoning_all,
|
||||
'rounds': round_index + 1, 'toolCalls': tool_call_count, 'usage': usage,
|
||||
}
|
||||
|
||||
convo.append({
|
||||
'role': 'assistant',
|
||||
'content': round_text or '',
|
||||
'tool_calls': [
|
||||
{
|
||||
'id': tc.get('id'),
|
||||
'type': 'function',
|
||||
'function': {
|
||||
'name': tc.get('name'),
|
||||
# 参数原样回传:模型可能给出坏 JSON,服务端往往还能自己纠正
|
||||
'arguments': tc.get('argsRaw') or json.dumps(tc.get('args') or {}, ensure_ascii=False),
|
||||
},
|
||||
}
|
||||
for tc in tool_calls
|
||||
],
|
||||
})
|
||||
|
||||
for tc in tool_calls:
|
||||
tool_call_count += 1
|
||||
emit({'type': 'tool_call', 'id': tc.get('id'), 'name': tc.get('name'), 'args': tc.get('args')})
|
||||
try:
|
||||
result = tools_runtime.execute_tool(tc.get('name'), tc.get('args') or {}, settings)
|
||||
except BaseException as exc: # noqa: BLE001 - 工具炸了也要把错误喂回模型
|
||||
result = {'ok': False, 'error': f'{type(exc).__name__}: {exc}'}
|
||||
if result.get('ok'):
|
||||
raw = result.get('result')
|
||||
payload = truncate('(无输出)' if raw is None else raw)
|
||||
else:
|
||||
payload = f"调用失败:{result.get('error') or '未知错误'}"
|
||||
emit({
|
||||
'type': 'tool_result',
|
||||
'id': tc.get('id'),
|
||||
'name': tc.get('name'),
|
||||
'ok': bool(result.get('ok')),
|
||||
'result': payload,
|
||||
})
|
||||
convo.append({'role': 'tool', 'tool_call_id': tc.get('id'), 'content': payload})
|
||||
|
||||
# 轮次用尽:仍然把已经拿到的正文给用户,并标记 truncated
|
||||
emit({
|
||||
'type': 'done',
|
||||
'content': answer,
|
||||
'reasoning': reasoning_all,
|
||||
'rounds': max_rounds,
|
||||
'toolCalls': tool_call_count,
|
||||
'usage': usage,
|
||||
'truncated': True,
|
||||
})
|
||||
return {
|
||||
'content': answer, 'reasoning': reasoning_all,
|
||||
'rounds': max_rounds, 'toolCalls': tool_call_count, 'usage': usage,
|
||||
}
|
||||
Reference in New Issue
Block a user