开源、超轻量级 AI Agent 运行时框架nanobot
nanobot 是由 Xubin Ren (HKUDS) 发起并维护的一个开源、超轻量级 AI Agent 运行时框架。它面向希望完全掌控自己的 AI Agent 技术栈的用户,提供一个小而可阅读的代码核心,以及构建真正长运行 Agent 所需的实用组件:WebUI、聊天通道、工具调用、记忆系统、MCP 协议支持、模型路由和部署方案。nanobot 是一个设计精良、轻量但功能完备的个人 AI Ag
nanobot
仓库地址: https://github.com/HKUDS/nanobot
文档地址: https://nanobot.wiki
PyPI 包名: nanobot-ai
许可证: MIT
Python 要求: >=3.11
一、项目概述
1.1 什么是 nanobot
nanobot 是由 Xubin Ren (HKUDS) 发起并维护的一个开源、超轻量级 AI Agent 运行时框架。它面向希望完全掌控自己的 AI Agent 技术栈的用户,提供一个小而可阅读的代码核心,以及构建真正长运行 Agent 所需的实用组件:WebUI、聊天通道、工具调用、记忆系统、MCP 协议支持、模型路由和部署方案。
1.2 核心设计理念
- 持久化工作流: 目标(goal)、记忆、工具和聊天上下文在长运行任务中持续存活
- 聊天原生: 支持 WebUI、API、飞书、微信、钉钉、QQ 等多种聊天平台
- 模型自由: 支持 OpenAI 兼容 API、本地 LLM、图像生成和多模型回退
- 小内核: 可读的内部实现,MCP/记忆/部署/自动化等能力内置但不臃肿
- 完全自主: 可检查、可定制、可自托管、可扩展
1.3 技术栈
| 组件 | 技术 |
|---|---|
| 语言 | Python >=3.11 |
| CLI 框架 | Typer |
| 数据验证 | Pydantic / Pydantic Settings |
| 通信 | websockets, httpx, socket.io |
| 日志 | Loguru |
| 终端 UI | Rich, prompt-toolkit, questionary |
| 定时任务 | croniter |
| 版本控制 | dulwich (纯 Python git) |
| LLM SDK | openai, anthropic (原生 SDK,已移除 litellm) |
1.4 架构
nanobot 围绕一个小型 Agent 循环构建:消息从聊天应用进入,LLM 决定是否需要工具,记忆或技能仅在需要时作为上下文注入,而不是成为沉重的编排层。核心路径保持可读且易于扩展。
主要模块:
- Agent Runner: 核心 agent 循环,处理消息、工具调用、迭代
- Providers: LLM 提供商抽象层(支持 30+ 提供商)
- Channels: 聊天通道插件(WebSocket/微信/飞书/钉钉/QQ/邮件等)
- Tools: 内置工具(shell 执行、文件读写、网页搜索/抓取、图像生成)
- Memory: 两阶段记忆系统(Consolidator + Dream)
- Gateway: 统一网关,同时监听所有启用的通道
- WebUI: 内置浏览器界面,无需额外构建步骤
- MCP: Model Context Protocol 集成
二、安装步骤
2.1 环境准备
- Python 3.11 或更高版本
- 推荐在虚拟环境中安装
python3 -m venv ~/.venv/nanobot
source ~/.venv/nanobot/bin/activate
pip install -U pip
2.2 安装方式(三种任选其一)
方式一:从 PyPI 安装(推荐日常使用,最稳定)
pip install nanobot-ai
方式二:使用 uv 安装(最快)
# 先安装 uv
pip install uv
uv tool install nanobot-ai
方式三:从源码安装(获取最新功能)
git clone https://github.com/HKUDS/nanobot.git
cd nanobot
pip install -e .
2.3 可选依赖安装
根据需求安装额外的功能模块:
# API 服务(OpenAI 兼容接口)
pip install "nanobot-ai[api]"
# 微信通道
pip install "nanobot-ai[weixin]"
# 企业微信通道
pip install "nanobot-ai[wecom]"
# PDF 高级处理
pip install "nanobot-ai[pdf]"
# 飞书/钉钉/Telegram 等已包含在主包中
2.4 验证安装
nanobot --version
# 应输出当前版本号,如 0.2.1
2.5 升级
# PyPI 升级
pip install -U nanobot-ai
nanobot --version
# uv 升级
uv tool upgrade nanobot-ai
nanobot --version
三、初始配置
3.1 首次初始化
nanobot onboard
此命令会在 ~/.nanobot/ 下创建配置文件和工作区。如果要使用交互式向导:
nanobot onboard --wizard
3.2 配置文件位置
主配置文件: ~/.nanobot/config.json
3.3 配置 API Key
在 ~/.nanobot/config.json 中设置 API Key。推荐使用 ${环境变量名} 语法引用环境变量:
{
"providers": {
"openrouter": {
"apiKey": "${OPENROUTER_API_KEY}"
},
"deepseek": {
"apiKey": "${DEEPSEEK_API_KEY}"
},
"zhipu": {
"apiKey": "${ZHIPUAI_API_KEY}"
}
}
}
3.4 配置模型
{
"agents": {
"defaults": {
"provider": "openrouter",
"model": "anthropic/claude-opus-4-6",
"maxTokens": 8192,
"contextWindowTokens": 200000,
"timezone": "Asia/Shanghai"
}
}
}
3.5 支持的国内 LLM 提供商(详细配置)
| 提供商 | 配置名 | API Key 获取 |
|---|---|---|
| 通义千问 | dashscope |
dashscope.console.aliyuncs.com |
| 智谱 GLM | zhipu |
open.bigmodel.cn |
| 月之暗面 Kimi | moonshot |
platform.moonshot.cn |
| 深度求索 | deepseek |
platform.deepseek.com |
| MiniMax | minimax |
platform.minimaxi.com |
| 硅基流动 | siliconflow |
siliconflow.cn |
| 火山引擎 | volcengine |
volcengine.com |
| 阶跃星辰 | stepfun |
platform.stepfun.com |
| 小米 MiMo | xiaomi_mimo |
platform.xiaomimimo.com |
| 百度千帆 | qianfan |
cloud.baidu.com |
| 蚂蚁百灵 | ant_ling |
developer.ant-ling.com |
| 字节海外 | byteplus |
byteplus.com |
智谱 GLM 配置示例:
{
"providers": {
"zhipu": {
"apiKey": "${ZHIPUAI_API_KEY}"
}
},
"agents": {
"defaults": {
"provider": "zhipu",
"model": "glm-4-plus"
}
}
}
通义千问 (阿里云百炼) 配置示例:
{
"providers": {
"dashscope": {
"apiKey": "${DASHSCOPE_API_KEY}",
"apiBase": "https://dashscope.aliyuncs.com/compatible-mode/v1"
}
},
"agents": {
"defaults": {
"provider": "dashscope",
"model": "qwen-max"
}
}
}
DeepSeek 配置示例:
{
"providers": {
"deepseek": {
"apiKey": "${DEEPSEEK_API_KEY}"
}
},
"agents": {
"defaults": {
"provider": "deepseek",
"model": "deepseek-v4-pro"
}
}
}
本地 Ollama 配置示例:
{
"providers": {
"ollama": {
"apiKey": null,
"apiBase": "http://localhost:11434/v1"
}
},
"agents": {
"defaults": {
"provider": "ollama",
"model": "qwen2.5:7b"
}
}
}
自定义 OpenAI 兼容端点:
{
"providers": {
"custom": {
"apiKey": "${MY_API_KEY}",
"apiBase": "https://your-api-endpoint.com/v1"
}
},
"agents": {
"defaults": {
"provider": "custom",
"model": "your-model-name"
}
}
}
3.6 模型预设与回退
{
"agents": {
"defaults": {
"modelPreset": "fast",
"fallbackModels": ["deep"]
}
},
"modelPresets": {
"fast": {
"model": "openai/gpt-4.1-mini",
"provider": "openai",
"maxTokens": 4096,
"temperature": 0.2
},
"deep": {
"model": "anthropic/claude-opus-4-5",
"provider": "anthropic",
"maxTokens": 8192,
"reasoningEffort": "high"
}
}
}
运行时使用 /model fast 或 /model deep 切换预设。
3.7 环境变量管理密钥
推荐使用环境变量而非将密钥明文写入配置文件:
# .env 文件或 shell 中导出
export OPENROUTER_API_KEY="sk-or-xxx"
export DEEPSEEK_API_KEY="sk-xxx"
配置文件中引用:
{ "providers": { "openrouter": { "apiKey": "${OPENROUTER_API_KEY}" } } }
四、使用方法
4.1 CLI 命令参考
| 命令 | 说明 |
|---|---|
nanobot onboard |
初始化配置和工作区 |
nanobot onboard --wizard |
交互式引导向导 |
nanobot agent |
进入交互式聊天模式 |
nanobot agent -m "消息" |
发送单条消息并获取回复 |
nanobot agent -w <工作区> |
指定工作区运行 |
nanobot agent -c <配置文件> |
指定配置文件运行 |
nanobot gateway |
启动网关(连接所有启用的通道) |
nanobot serve |
启动 OpenAI 兼容 API 服务 |
nanobot status |
查看状态 |
nanobot channels status |
查看通道状态 |
nanobot provider login <提供商> |
OAuth 登录提供商 |
nanobot channels login <通道> |
交互式登录通道 |
4.2 方式一:命令行聊天
# 交互式聊天
nanobot agent
# 单条消息
nanobot agent -m "你好,请介绍一下自己"
# 指定工作区和配置
nanobot agent -c ~/.nanobot/config.json -w /path/to/workspace -m "hello"
# 纯文本输出(不带 markdown 格式)
nanobot agent --no-markdown
# 显示运行时日志
nanobot agent --logs
# 退出交互模式: 输入 exit / quit / :q 或按 Ctrl+D
4.3 方式二:WebUI(内置浏览器界面)
这是 nanobot 最核心的交互方式之一,v0.2.1 版本已将其打造为每日工作台面。
1. 在配置中启用 WebSocket 通道:
{
"channels": {
"websocket": {
"enabled": true,
"host": "127.0.0.1",
"port": 8765,
"websocketRequiresToken": false,
"streaming": true
}
}
}
2. 启动网关:
nanobot gateway
3. 打开浏览器访问:
http://127.0.0.1:8765
WebUI 功能:
- 实时流式对话
- 思考过程可视化(Thought/response 时间线)
- 文件上传(图片、PDF、Word、Excel、PPT)
- 图像生成(点击 Image Generation 按钮,选择比例)
- 项目工作区管理
- 模型预设切换
- 多语言界面切换
- 暗色模式
- LAN 局域网访问(另一台设备也可以访问)
局域网访问配置:
{
"channels": {
"websocket": {
"enabled": true,
"host": "0.0.0.0",
"port": 8765,
"tokenIssueSecret": "your-secret-here"
}
},
"gateway": {
"host": "0.0.0.0"
}
}
4.4 方式三:OpenAI 兼容 API
将 nanobot 暴露为标准 OpenAI API 端点,供外部程序调用。
1. 安装 API 依赖:
pip install "nanobot-ai[api]"
2. 启动服务:
nanobot serve
默认绑定 127.0.0.1:8900。
3. API 端点:
| 端点 | 方法 | 说明 |
|---|---|---|
/health |
GET | 健康检查 |
/v1/models |
GET | 查看可用模型 |
/v1/chat/completions |
POST | 对话补全 |
4. 调用示例 (curl):
curl http://127.0.0.1:8900/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"messages": [{"role": "user", "content": "你好"}],
"session_id": "my-session"
}'
5. 流式输出:
curl http://127.0.0.1:8900/v1/chat/completions \
-H "Content-Type: application/json" \
-d '{
"messages": [{"role": "user", "content": "你好"}],
"stream": true
}'
6. 文件上传 (multipart/form-data):
# 单文件
curl http://127.0.0.1:8900/v1/chat/completions \
-F "message=请总结这份报告" \
-F "files=@report.docx"
# 多文件
curl http://127.0.0.1:8900/v1/chat/completions \
-F "message=比较这些文件" \
-F "files=@chart.png" \
-F "files=@data.xlsx" \
-F "session_id=my-session"
支持的文件类型:
- 图片: PNG, JPEG, GIF, WebP
- 文档: PDF, Word (.docx), Excel (.xlsx), PowerPoint (.pptx)
- 文本: TXT, Markdown, CSV, JSON 等
7. Python 调用:
import requests
resp = requests.post(
"http://127.0.0.1:8900/v1/chat/completions",
json={
"messages": [{"role": "user", "content": "你好"}],
"session_id": "my-session",
},
timeout=120,
)
resp.raise_for_status()
print(resp.json()["choices"][0]["message"]["content"])
8. 使用 OpenAI SDK:
from openai import OpenAI
client = OpenAI(
base_url="http://127.0.0.1:8900/v1",
api_key="dummy", # API 模式不需要真实 key
)
resp = client.chat.completions.create(
model="your-model",
messages=[{"role": "user", "content": "你好"}],
extra_body={"session_id": "my-session"},
)
print(resp.choices[0].message.content)
4.5 方式四:Python SDK 编程使用
将 nanobot 作为 Python 库使用,无需 CLI 和网关:
import asyncio
from nanobot import Nanobot
async def main():
# 从配置文件加载
bot = Nanobot.from_config()
# 发送消息
result = await bot.run("东京现在几点?")
print(result.content)
# 指定工作区
bot2 = Nanobot.from_config(workspace="/my/project")
# 隔离会话
result = await bot2.run("hi", session_key="user-alice")
asyncio.run(main())
高级用法 — 挂钩(Hooks)监控:
from nanobot import Nanobot
from nanobot.agent import AgentHook, AgentHookContext
class AuditHook(AgentHook):
def __init__(self):
super().__init__()
self.calls = []
async def before_execute_tools(self, context: AgentHookContext):
for tc in context.tool_calls:
self.calls.append(tc.name)
print(f"[工具调用] {tc.name}({tc.arguments})")
async def main():
bot = Nanobot.from_config()
hook = AuditHook()
result = await bot.run("列出 /tmp 下的文件", hooks=[hook])
print(result.content)
print(f"观测到的工具调用: {hook.calls}")
asyncio.run(main())
流式输出 Hook:
class StreamingHook(AgentHook):
def wants_streaming(self) -> bool:
return True
async def on_stream(self, context: AgentHookContext, delta: str) -> None:
print(delta, end="", flush=True)
async def on_stream_end(self, context: AgentHookContext, *, resuming: bool) -> None:
print()
4.6 方式五:飞书/钉钉/微信/QQ 等聊天应用
飞书 (推荐 — 无需公网 IP)
飞书使用 WebSocket 长连接,不需要公网 IP 或域名。
1. 创建飞书机器人:
- 访问 飞书开放平台
- 创建新应用,启用"机器人"能力
- 添加权限:
im:message、im:message.p2p_msg:readonly、cardkit:card:write(流式输出需要) - 添加事件:
im.message.receive_v1,选择"长连接"模式 - 获取 App ID 和 App Secret
2. 配置:
{
"channels": {
"feishu": {
"enabled": true,
"appId": "cli_xxx",
"appSecret": "your-secret",
"allowFrom": ["ou_你的open_id"],
"groupPolicy": "mention",
"streaming": true
}
}
}
3. 启动:
nanobot gateway
微信 (Weixin)
使用 HTTP 长轮询,扫码登录,无需本地微信客户端。
1. 安装微信支持:
pip install "nanobot-ai[weixin]"
2. 配置:
{
"channels": {
"weixin": {
"enabled": true,
"allowFrom": ["*"]
}
}
}
3. 登录:
nanobot channels login weixin
# 扫码登录
# 使用 --force 强制重新登录
nanobot channels login weixin --force
4. 启动:
nanobot gateway
钉钉
使用 Stream 模式,无需公网 IP。
{
"channels": {
"dingtalk": {
"enabled": true,
"clientId": "YOUR_APP_KEY",
"clientSecret": "YOUR_APP_SECRET",
"allowFrom": ["YOUR_STAFF_ID"]
}
}
}
nanobot gateway
QQ 官方机器人 (仅私聊):
{
"channels": {
"qq": {
"enabled": true,
"appId": "YOUR_APP_ID",
"secret": "YOUR_SECRET",
"allowFrom": ["YOUR_OPENID"],
"msgFormat": "plain"
}
}
}
Napcat QQ (支持群聊等完整功能):
{
"channels": {
"napcat": {
"enabled": true,
"wsUrl": "ws://127.0.0.1:3001",
"accessToken": "YOUR_TOKEN",
"allowFrom": ["*"],
"groupPolicy": "mention",
"welcomeNewMembers": true
}
}
}
企业微信
pip install "nanobot-ai[wecom]"
{
"channels": {
"wecom": {
"enabled": true,
"botId": "your_bot_id",
"secret": "your_secret",
"allowFrom": ["your_id"]
}
}
}
Mochat (Claw IM)
最简单的方式 — 直接让 nanobot 帮你注册:
在 nanobot 中发送以下消息(替换为你的邮箱):
Read https://raw.githubusercontent.com/HKUDS/MoChat/refs/heads/main/skills/nanobot/skill.md and register on MoChat. My Email account is xxx@xxx Bind me as your owner and DM me on MoChat.
nanobot 会自动完成注册、配置并连接。然后重启:
nanobot gateway
五、核心功能详解
5.1 内置工具
Shell 执行
Agent 可以执行 shell 命令:
{
"tools": {
"exec": {
"enable": true,
"timeout": 60,
"sandbox": "bwrap",
"pathAppend": ""
}
}
}
enable: 是否启用 shell 执行工具timeout: 命令超时时间(秒),0 表示不限制sandbox: 沙箱后端,设置为"bwrap"启用 bubblewrap 沙箱(仅 Linux)pathAppend: 追加到 PATH 的额外目录
文件操作
Agent 可读写文件、编辑代码、列出目录。安全选项:
{
"tools": {
"restrictToWorkspace": true // 限制所有工具只能访问工作区目录
}
}
网页搜索
默认启用,默认使用 DuckDuckGo(无需 API Key):
{
"tools": {
"web": {
"enable": true,
"search": {
"provider": "duckduckgo", // 或 brave, tavily, kagi, jina, volcengine 等
"apiKey": "",
"maxResults": 5
},
"proxy": null,
"userAgent": null
}
}
}
支持的搜索提供商:
| 提供商 | 是否免费 | 配置 |
|---|---|---|
| DuckDuckGo | 免费(默认) | 无需配置 |
| Brave | 付费 | 需 API Key |
| Tavily | 付费 | 需 API Key |
| Jina | 免费层(10M tokens) | 需 API Key |
| Kagi | 付费 | 需 API Key |
| 火山引擎 | 月度配额 | 需 API Key |
| SearXNG | 免费(自托管) | 需 baseUrl |
网页抓取
默认使用 Jina Reader 将网页转为 Markdown 格式,本地有 readability-lxml 作为后备:
{
"tools": {
"web": {
"fetch": {
"useJinaReader": true
}
}
}
}
SSRF 防护
可配置受信任的私有网段白名单:
{
"tools": {
"ssrfWhitelist": ["100.64.0.0/10"]
}
}
5.2 图像生成
默认禁用,需在配置中启用:
{
"tools": {
"imageGeneration": {
"enabled": true,
"provider": "openrouter",
"model": "openai/gpt-5.4-image-2",
"defaultAspectRatio": "1:1",
"defaultImageSize": "1K",
"maxImagesPerTurn": 4
}
}
}
支持的图像提供商: OpenRouter, AIHubMix, MiniMax, Gemini, Ollama, 阶跃星辰, 智谱
WebUI 使用:
- 在输入框旁点击 “Image Generation”
- 选择比例: Auto / 1:1 / 3:4 / 9:16 / 4:3 / 16:9
- 描述要生成的图像
- 可对已有图片进行编辑(“让它更暖色调”、“换个背景”)
5.3 MCP (Model Context Protocol)
支持连接外部 MCP 工具服务器,与 Claude Desktop / Cursor 配置兼容:
{
"tools": {
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/dir"]
},
"remote-server": {
"url": "https://example.com/mcp/",
"headers": {"Authorization": "Bearer xxxxx"},
"toolTimeout": 120
}
}
}
}
支持两种传输模式:
- Stdio: 本地进程(command + args)
- HTTP: 远程端点(url + headers)
可精确控制启用哪些工具:
{
"tools": {
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path"],
"enabledTools": ["read_file", "mcp_filesystem_write_file"]
}
}
}
}
5.4 记忆系统
nanobot 拥有两阶段记忆架构:
阶段一: Consolidator(上下文压缩)
- 当会话过大时,自动压缩旧消息为摘要
- 摘要追加到
memory/history.jsonl - 保留最近的 8 条消息为活跃上下文
阶段二: Dream(长期记忆整合)
- 定期运行(默认每 2 小时)
- 读取
history.jsonl中的新条目 - 智能更新
SOUL.md、USER.md、MEMORY.md - 支持版本控制和回滚
工作区文件结构:
~/.nanobot/workspace/
├── SOUL.md # 机器人的长期风格和沟通方式
├── USER.md # 关于用户的稳定知识
├── HEARTBEAT.md # 周期性任务
└── memory/
├── MEMORY.md # 项目事实、决策和持久上下文
├── history.jsonl # 只追加的历史摘要
├── .cursor # Consolidator 游标
├── .dream_cursor # Dream 消费游标
└── .git/ # 长期记忆的版本历史
记忆配置:
{
"agents": {
"defaults": {
"dream": {
"intervalH": 2,
"modelOverride": null,
"maxBatchSize": 20,
"maxIterations": 10
},
"idleCompactAfterMinutes": 15
}
}
}
记忆命令:
| 命令 | 功能 |
|---|---|
/dream |
立即运行 Dream 整合 |
/dream-log |
查看最近的 Dream 变更 |
/dream-restore |
列出最近的记忆版本 |
/dream-restore <sha> |
恢复到特定记忆版本 |
5.5 持久化目标 (/goal)
/goal 命令允许设置跨轮次持续的目标:
/goal 每天早上 9 点检查天气并发送摘要
目标会在多轮对话中持续存在,agent 会围绕它持续工作。
5.6 自动压缩 (Auto Compact)
当用户空闲超过设定时间,自动压缩旧上下文:
{
"agents": {
"defaults": {
"idleCompactAfterMinutes": 15
}
}
}
5.7 子 Agent 并发
{
"agents": {
"defaults": {
"maxConcurrentSubagents": 2
}
}
}
默认同时只允许 1 个子 agent,可调整以适应更强的提供商。
5.8 禁用特定技能
{
"agents": {
"defaults": {
"disabledSkills": ["github", "weather"]
}
}
}
5.9 多实例运行
为不同通道创建独立的 nanobot 实例:
# 初始化不同实例
nanobot onboard --config ~/.nanobot-feishu/config.json --workspace ~/.nanobot-feishu/workspace
nanobot onboard --config ~/.nanobot-weixin/config.json --workspace ~/.nanobot-weixin/workspace
# 分别启动
nanobot gateway --config ~/.nanobot-feishu/config.json
nanobot gateway --config ~/.nanobot-weixin/config.json
每个实例使用独立的配置、工作区、定时任务和运行时状态。
5.10 周期性任务 (Heartbeat)
网关每 30 分钟检查 HEARTBEAT.md,执行其中的活动任务:
# 编辑周期性任务
# ~/.nanobot/workspace/HEARTBEAT.md
内容格式:
## Active Tasks
- [ ] 检查天气预报并发送摘要
- [ ] 扫描邮箱查找紧急邮件
完成的任务应从文件中删除。你也可以直接告诉 agent “添加一个周期性任务”,它会自动更新 HEARTBEAT.md。
六、聊天内命令
这些命令在所有聊天通道和交互会话中可用:
| 命令 | 说明 |
|---|---|
/new |
停止当前任务,开始新对话 |
/stop |
停止当前任务 |
/restart |
重启机器人 |
/status |
显示机器人状态 |
/model |
显示当前模型和可用预设 |
/model <预设名> |
切换运行时模型预设 |
/goal |
设置/查看持久化目标 |
/dream |
立即运行 Dream 记忆整合 |
/dream-log |
查看最近的记忆变更 |
/dream-restore |
列出记忆版本 |
/history |
查看历史消息 |
/help |
显示可用命令 |
/pairing |
列出待审批的配对请求 |
/pairing approve <码> |
审批配对码 |
/pairing deny <码> |
拒绝配对请求 |
七、安全配置
7.1 沙箱执行
{
"tools": {
"restrictToWorkspace": true,
"exec": {
"sandbox": "bwrap"
}
}
}
bwrap 沙箱使进程只能看到工作区(读写)和媒体目录(只读),配置文件和 API Key 被隐藏。仅限 Linux(需安装 bubblewrap)。
7.2 完全禁用 Shell
{
"tools": {
"exec": {
"enable": false
}
}
}
7.3 配对访问控制
新用户 DM 机器人时会收到配对码(如 ABCD-EFGH),需你审批后才可访问:
nanobot agent -m "/pairing approve ABCD-EFGH"
7.4 通道级访问控制
{
"channels": {
"feishu": {
"enabled": true,
"allowFrom": ["ou_你的ID"] // 或 ["*"] 允许所有人
}
}
}
八、部署方案
8.1 Docker 部署
构建镜像:
cd /path/to/nanobot
docker build -t nanobot .
初始化配置:
docker run -v ~/.nanobot:/home/nanobot/.nanobot --rm nanobot onboard
编辑配置文件 (宿主机上):
vim ~/.nanobot/config.json
启动网关:
# 注意: Docker 中需要将 host 改为 0.0.0.0
docker run \
--cap-drop ALL --cap-add SYS_ADMIN \
--security-opt apparmor=unconfined \
--security-opt seccomp=unconfined \
-v ~/.nanobot:/home/nanobot/.nanobot \
-p 18790:18790 -p 8765:8765 \
nanobot gateway
Docker Compose:
docker compose run --rm nanobot-cli onboard # 首次设置
vim ~/.nanobot/config.json # 添加 API Key
docker compose up -d nanobot-gateway # 启动网关
权限问题修复:
sudo chown -R 1000:1000 ~/.nanobot
Docker 中的 config.json 需要:
{
"gateway": { "host": "0.0.0.0" },
"channels": {
"websocket": {
"enabled": true,
"host": "0.0.0.0",
"port": 8765,
"tokenIssueSecret": "your-secret-here"
}
}
}
8.2 Linux 系统服务 (systemd)
创建服务文件 ~/.config/systemd/user/nanobot-gateway.service:
[Unit]
Description=Nanobot Gateway
After=network.target
[Service]
Type=simple
ExecStart=%h/.local/bin/nanobot gateway
Restart=always
RestartSec=10
NoNewPrivileges=yes
ProtectSystem=strict
ReadWritePaths=%h
[Install]
WantedBy=default.target
启用并启动:
systemctl --user daemon-reload
systemctl --user enable --now nanobot-gateway
常用操作:
systemctl --user status nanobot-gateway # 查看状态
systemctl --user restart nanobot-gateway # 重启
journalctl --user -u nanobot-gateway -f # 查看日志
注销后保持运行:
loginctl enable-linger $USER
8.3 环境变量传递 (Docker)
# nanobot.env 文件
OPENROUTER_API_KEY=sk-or-xxx
DEEPSEEK_API_KEY=sk-xxx
# 启动
docker run --rm --env-file=./nanobot.env \
-v ~/.nanobot:/home/nanobot/.nanobot \
nanobot gateway
九、WebSocket 协议(开发者参考)
nanobot 可作为 WebSocket 服务器,允许外部客户端实时交互。
连接 URL:
ws://{host}:{port}{path}?client_id={id}&token=***
Python 客户端示例:
import asyncio, json
import websockets
async def main():
async with websockets.connect("ws://127.0.0.1:8765/?client_id=alice") as ws:
# 收到 ready 事件
ready = json.loads(await ws.recv())
print(ready) # {"event": "ready", "chat_id": "...", "client_id": "alice"}
# 发送消息
await ws.send(json.dumps({"content": "Hello nanobot!"}))
# 接收回复
reply = json.loads(await ws.recv())
print(reply["text"])
asyncio.run(main())
协议事件:
| 事件 | 方向 | 说明 |
|---|---|---|
ready |
服务器 → 客户端 | 连接建立 |
message |
服务器 → 客户端 | 完整回复 |
delta |
服务器 → 客户端 | 流式文本块 |
stream_end |
服务器 → 客户端 | 流结束 |
reasoning_delta |
服务器 → 客户端 | 推理过程流 |
reasoning_end |
服务器 → 客户端 | 推理结束 |
error |
服务器 → 客户端 | 软错误 |
多聊天复用: 一个连接可同时运行多个 chat_id:
// 创建新聊天
{"type": "new_chat"}
// 附加到现有聊天
{"type": "attach", "chat_id": "xxx"}
// 发送消息到指定聊天
{"type": "message", "chat_id": "xxx", "content": "hello"}
十、配置速查表
10.1 完整配置示例
{
"gateway": {
"host": "127.0.0.1",
"port": 18790
},
"providers": {
"deepseek": {
"apiKey": "${DEEPSEEK_API_KEY}"
},
"zhipu": {
"apiKey": "${ZHIPUAI_API_KEY}"
}
},
"agents": {
"defaults": {
"provider": "deepseek",
"model": "deepseek-v4-pro",
"maxTokens": 8192,
"contextWindowTokens": 262144,
"timezone": "Asia/Shanghai",
"workspace": "~/.nanobot/workspace",
"unifiedSession": false,
"maxConcurrentSubagents": 1,
"idleCompactAfterMinutes": 15,
"dream": {
"intervalH": 2,
"modelOverride": null,
"maxBatchSize": 20,
"maxIterations": 10
},
"disabledSkills": []
}
},
"tools": {
"restrictToWorkspace": true,
"exec": {
"enable": true,
"timeout": 60,
"sandbox": "bwrap"
},
"web": {
"enable": true,
"search": {
"provider": "duckduckgo",
"maxResults": 5
},
"fetch": {
"useJinaReader": true
}
},
"imageGeneration": {
"enabled": false,
"provider": "openrouter",
"model": "openai/gpt-5.4-image-2"
},
"mcpServers": {}
},
"channels": {
"sendProgress": true,
"sendToolHints": false,
"sendMaxRetries": 3,
"websocket": {
"enabled": true,
"host": "127.0.0.1",
"port": 8765,
"streaming": true
},
"feishu": {
"enabled": false,
"appId": "",
"appSecret": "",
"allowFrom": ["*"],
"groupPolicy": "mention",
"streaming": true
},
"weixin": {
"enabled": false,
"allowFrom": ["*"]
}
}
}
10.2 关键配置项速查
| 配置项 | 默认值 | 说明 |
|---|---|---|
agents.defaults.timezone |
UTC | 时区,设为 Asia/Shanghai 使用北京时间 |
agents.defaults.unifiedSession |
false | 跨通道共享会话 |
agents.defaults.idleCompactAfterMinutes |
0(关闭) | 空闲后自动压缩 |
tools.restrictToWorkspace |
false | 限制工具只能访问工作区 |
tools.exec.sandbox |
“” | 沙箱: “” 或 “bwrap” |
tools.exec.enable |
true | 是否启用 shell 执行 |
tools.exec.timeout |
60 | shell 命令超时(秒) |
tools.web.enable |
true | 是否启用网页工具 |
tools.web.search.provider |
duckduckgo | 搜索提供商 |
tools.imageGeneration.enabled |
false | 是否启用图像生成 |
channels.websocket.enabled |
false | 是否启用 WebUI |
channels.sendProgress |
true | 流式发送进度 |
channels.sendToolHints |
false | 显示工具调用提示 |
channels.sendMaxRetries |
3 | 消息发送最大重试次数 |
channels.transcriptionProvider |
groq | 语音转文字后端 |
十一、常见问题与注意事项
11.1 配置文件更新
如果配置文件版本过旧,运行 nanobot onboard 并选择 N 不覆盖,nanobot 会自动合并缺失的默认字段并保留现有设置。
11.2 权限问题
Docker 中遇到 “Permission denied”:
sudo chown -R 1000:1000 ~/.nanobot
11.3 API Key 安全
- 始终使用
${环境变量名}引用密钥 - 不要将明文密钥提交到版本控制
- 生产环境使用 systemd
EnvironmentFile=或 Docker--env-file
11.4 日志查看
# systemd 服务
journalctl --user -u nanobot-gateway -f
# Docker
docker compose logs -f nanobot-gateway
# 直接运行
nanobot agent --logs
11.5 健康检查
网关在 gateway.host:gateway.port 暴露健康检查端点:
curl http://127.0.0.1:18790/health
# 返回: {"status":"ok"}
十二、项目社区
- GitHub: https://github.com/HKUDS/nanobot
- 文档: https://nanobot.wiki
十三、总结
nanobot 是一个设计精良、轻量但功能完备的个人 AI Agent 框架。其核心优势:
- 极简内核: 代码可读性强,易于理解和定制
- 丰富的通道支持: 飞书、微信、钉钉、QQ 等国内主流平台全覆盖
- 强大的记忆系统: 两阶段记忆架构,支持版本控制和回滚
- 灵活的多模型支持: 30+ 提供商,支持模型回退和预设切换
- 内置 WebUI: 无需额外构建,开箱即用
- 标准 API: OpenAI 兼容接口和 Python SDK
- 生产级部署: Docker、systemd、macOS LaunchAgent
- 安全可控: 沙箱执行、工作区隔离、配对访问控制
- MCP 支持: 连接外部工具服务器
- 活跃开发: 从 2026 年 2 月首发至今持续迭代,v0.2.1 已进入工作台面阶段
适合场景:
- 个人 AI 助手(CLI/WebUI/飞书/微信)
- 企业内部分发的 AI Bot(飞书/钉钉/企微)
- 集成到现有系统的 AI 服务(OpenAI API/Python SDK)
- 研究 AI Agent 架构和最佳实践
更多推荐


所有评论(0)