docs(develop): add single-page AI assistant context for developers (zh/en/ja)

This commit is contained in:
RockChinQ
2026-06-07 08:51:12 -04:00
parent bd34ad6acb
commit 3dec4a6925
4 changed files with 500 additions and 0 deletions
+3
View File
@@ -411,6 +411,7 @@
{
"group": "Core Development",
"pages": [
"en/develop/agent-context",
"en/develop/dev-config",
"en/develop/plugin-runtime",
"en/develop/comp-arch",
@@ -634,6 +635,7 @@
{
"group": "核心开发",
"pages": [
"zh/develop/agent-context",
"zh/develop/dev-config",
"zh/develop/plugin-runtime",
"zh/develop/comp-arch",
@@ -852,6 +854,7 @@
{
"group": "コア開発",
"pages": [
"ja/develop/agent-context",
"ja/develop/dev-config",
"ja/develop/plugin-runtime",
"ja/develop/comp-arch",
+166
View File
@@ -0,0 +1,166 @@
---
title: "AI Assistant Context"
description: "A single, copy-paste-the-whole-page context for AI coding assistants: LangBot's directory layout, how components are organized, how they connect at runtime, and how to set up the dev environment."
---
<Info title="This page is written for AI coding assistants (Claude Code / Cursor / Copilot / Codex, etc.).">
Copy the **entire content** of this page and paste it to your AI assistant. It will then understand LangBot's overall architecture, how each component is organized, how they connect at runtime, and how to configure the dev environment — without you having to explain it piece by piece.
</Info>
This page mirrors the `AGENTS.md` (with `CLAUDE.md` as a symlink) at each repository root, and serves as LangBot's "one-page onboarding" for developers and AI assistants.
## Project Overview
LangBot is an open-source, LLM-native instant-messaging bot development platform. It provides an out-of-the-box IM bot development experience with built-in Agent, RAG, MCP and other LLM application capabilities, supports mainstream global IM platforms, and exposes rich APIs for custom development.
LangBot has a comprehensive web frontend — almost every operation can be performed through it.
- **Backend**: Python (`>=3.11,<4.0`), dependencies managed by `uv`; the web framework is Quart (the async flavour of Flask). Both the HTTP API and the pre-built frontend are served by the backend on `http://127.0.0.1:5300`.
- **Frontend**: `web/` is a **Vite + React Router 7 + shadcn/ui + Tailwind CSS** SPA, managed by `pnpm` (note: this is **not** Next.js — the `dev` script is literally `vite`).
- **Plugin system**: The Plugin SDK, CLI (`lbp`), Plugin Runtime, Box (sandbox) Runtime, and the entity/API definitions shared between LangBot and plugins all live in a separate repository: [`langbot-plugin-sdk`](https://github.com/langbot-app/langbot-plugin-sdk). LangBot depends on it via the version-pinned `langbot-plugin` package in `pyproject.toml`.
## Repository Layout
```
LangBot/
├── main.py # Entrypoint shim -> langbot.__main__.main()
├── pyproject.toml # Python project + deps (uv), pins langbot-plugin==<x.y.z>
├── src/langbot/
│ ├── __main__.py # Real entrypoint, CLI args (e.g. --standalone-runtime)
│ ├── pkg/ # Core backend package
│ │ ├── api/ # HTTP API controllers + services (Quart)
│ │ ├── core/ # App bootstrap, stages, task manager
│ │ ├── platform/ # IM platform adapters, bot managers, session managers
│ │ ├── provider/ # LLM providers, requesters, tool providers
│ │ ├── pipeline/ # Pipelines, stages, query pool
│ │ ├── plugin/ # Bridge to the plugin runtime (connector.py / handler.py)
│ │ ├── box/ # Code-sandbox subsystem (Docker / nsjail / E2B backends)
│ │ ├── skill/ # Skill subsystem
│ │ ├── rag/ , vector/ # RAG + vector store
│ │ ├── command/ # Built-in commands
│ │ ├── persistence/ # ORM models + Alembic migrations (SQLite & PostgreSQL)
│ │ ├── storage/ # Object/file storage abstractions
│ │ ├── config/, entity/, discover/, utils/, telemetry/, survey/
│ ├── libs/ # Vendored SDKs (qq_official_api, wecom_api, etc.)
│ └── templates/ # Config/component templates (e.g. templates/config.yaml)
├── web/ # Frontend SPA (Vite + React Router 7 + shadcn + Tailwind)
└── docker/ # docker-compose deployment files
```
## How Components Are Organized
The core backend package `src/langbot/pkg/` is split into loosely-coupled submodules by responsibility:
| Module | Responsibility |
| --- | --- |
| `core` | Application lifecycle: startup stages load config, connect the DB, bring up subsystems in order, and manage background tasks. |
| `platform` | Adapters for each IM platform (Discord, Telegram, QQ, WeCom, Lark, etc.); send/receive messages, manage bots and sessions. |
| `provider` | LLM providers and requesters (OpenAI-compatible and native APIs), plus tool providers callable by the Agent. |
| `pipeline` | The message-processing pipeline: routes one message through trigger, AI processing, output, and safety stages. |
| `plugin` | Bridge between the LangBot main process and the plugin runtime — connect, exchange actions, forward events. |
| `box` | Code-sandbox subsystem providing isolated code execution for skills/tools; selects Docker / nsjail / E2B by availability. |
| `skill` / `rag` / `vector` | Skill, retrieval-augmented generation, and vector-store capabilities. |
| `persistence` | ORM entity definitions and Alembic migrations; a single set of scripts works on both SQLite and PostgreSQL. |
On the plugin side (defined in `langbot-plugin-sdk`), components are organized around a single `BasePlugin`:
- **Command**: user-triggered actions (e.g. `!weather tokyo`).
- **Tool**: functions the LLM calls during Agent execution (e.g. fetch weather, query a database).
- **EventListener**: handlers for events in the message pipeline (e.g. auto-reply, content filtering).
Each plugin runs in its own process, with its lifecycle managed by the plugin runtime (discover → install deps → load → initialize → register components → ready → terminate).
## How Things Connect at Runtime
```
┌──────────────┐ HTTP/API ┌──────────────┐
│ Browser/Web │ ────────────► │ │
│ (Vite SPA) │ :3000/origin │ LangBot │
└──────────────┘ │ backend │
│ (Quart) │
┌───────────────────────────┤ :5300 ├─────────────────────────┐
│ stdio or WebSocket └──────────────┘ stdio or WebSocket │
▼ ▼
┌──────────────┐ ┌──────────────┐
│ Plugin │ separate process, │ Box │ code sandbox
│ Runtime │ launches each plugin │ Runtime │ Docker/nsjail/E2B
│ :5400 / :5401│ │ :5410 │
└──────────────┘ └──────────────┘
```
- **Frontend ↔ Backend**: In dev, the frontend runs standalone on `:3000` and reaches the backend `:5300` via `VITE_API_BASE_URL` in `web/.env`; in production the frontend is pre-built into static files served by the backend on the same origin.
- **Backend ↔ Plugin Runtime**:
- When LangBot is **started directly** (not in a container), the backend **spawns** the runtime itself and talks over **stdio** (lightweight/personal use). stdio **cannot auto-reconnect** — after a disconnect you must restart LangBot; a common failure is an **orphan runtime process** from a previous backend still holding `5400`/`5401` — kill it and restart.
- When LangBot runs in a **container**, it connects to a standalone runtime over **WebSocket** (production). Control port defaults to `5400`, debug port to `5401`. Config: `plugin.runtime_ws_url` in `data/config.yaml` (e.g. `ws://langbot_plugin_runtime:5400/control/ws`).
- **Backend ↔ Box Runtime**: The Box subsystem connects to the Box runtime over a control channel (default port `5410`), which executes sandboxed code in Docker / nsjail / E2B.
- The full guide for debugging the runtime, CLI and SDK is in [Debugging Plugin Runtime, CLI, SDK](/en/develop/plugin-runtime); detailed flags and architecture are in the `langbot-plugin-sdk` repo's `AGENTS.md`.
## Development Environment Setup
Full guide: [Development Configuration](/en/develop/dev-config). Summary:
### Backend
```bash
pip install uv
uv sync --dev # uv creates a .venv/ for you; point your editor's interpreter at it
uv run main.py # serves API + frontend on http://127.0.0.1:5300
```
On first run the config file is generated at `data/config.yaml`. SQLite is the default (zero setup); PostgreSQL is supported. Migrations run automatically on startup.
### Frontend
Requires Node.js and [pnpm](https://pnpm.io/installation).
```bash
cd web
cp .env.example .env # Windows: copy .env.example .env
pnpm install
pnpm dev # http://127.0.0.1:3000 (npm install / npm run dev also work)
```
`pnpm dev` reads `VITE_API_BASE_URL` from `web/.env` so the dev frontend can reach the backend on `:5300`.
### Code Formatting
CI runs lint + format checks. Install the pre-commit hooks so the same checks run locally before each commit:
```bash
uv run pre-commit install
```
### Database Migrations
After changing ORM models, generate a migration:
```bash
# Run from the project root (requires data/config.yaml)
uv run python -m langbot.pkg.persistence.alembic_runner autogenerate "describe your change"
```
`autogenerate` detects schema changes (add/drop columns and tables, type changes), but **data migrations** (e.g. mutating JSON field contents) must be hand-written into the generated script. `env.py` sets `render_as_batch=True`, so SQLite's ALTER TABLE limits are handled automatically — no per-database branching needed. Migrations execute automatically on startup.
## Development Standards
- LangBot is a global project: **all code comments and docstrings must be in English**, and every user-facing string must support **i18n** (`en_US` + `zh_Hans` at minimum, plus `ja_JP` where the repo already has it).
- LangBot is adopted in both toC and toB scenarios — always consider compatibility and security.
- **Commit message format**: `<type>(<scope>): <subject>`
- `type`: one of `feat`, `fix`, `docs`, `style`, `refactor`, `perf`, `test`, `chore`, etc.
- `scope`: the affected package/module/file/class.
- `subject`: a concise description of the change.
## Some Principles
- Keep it simple, stupid.
- Entities should not be multiplied unnecessarily.
- 八荣八耻 (Eight Honors and Eight Shames):
Shame in guessing interfaces; honor in carefully checking them.
Shame in vague execution; honor in seeking confirmation.
Shame in assuming business logic; honor in human confirmation.
Shame in inventing interfaces; honor in reusing existing ones.
Shame in skipping verification; honor in proactive testing.
Shame in breaking architecture; honor in following conventions.
Shame in pretending to understand; honor in honest ignorance.
Shame in blind changes; honor in careful refactoring.
+166
View File
@@ -0,0 +1,166 @@
---
title: "AI アシスタント開発コンテキスト"
description: "AI コーディングアシスタントにページ全体をそのままコピー&ペーストできる LangBot のコンテキスト:ディレクトリ構成、コンポーネントの構成方法、実行時の接続関係、開発環境のセットアップ。"
---
<Info title="このページは AI コーディングアシスタント(Claude Code / Cursor / Copilot / Codex など)向けです。">
このページの**すべての内容**をコピーして AI アシスタントに貼り付けてください。そうすれば、LangBot の全体アーキテクチャ、各コンポーネントの構成方法、実行時の接続関係、開発環境の設定方法を、あなたが逐一説明しなくても把握できます。
</Info>
このページは各リポジトリのルートにある `AGENTS.md`(`CLAUDE.md` はそのシンボリックリンク)と内容を一致させており、LangBot プロジェクトの開発者および AI アシスタント向け「1 ページ入門」です。
## プロジェクト概要
LangBot はオープンソースの LLM ネイティブなインスタントメッセージングボット開発プラットフォームです。すぐに使える IM ボット開発体験を提供し、Agent、RAG、MCP などの LLM アプリケーション機能を内蔵し、世界の主要 IM プラットフォームに対応し、カスタム開発のための豊富な API を提供します。
LangBot は充実した Web フロントエンドを備えており、ほぼすべての操作をフロントエンドから行えます。
- **バックエンド**:Python(`>=3.11,<4.0`)、依存関係は `uv` で管理。Web フレームワークは Quart(Flask の非同期版)。HTTP API とビルド済みフロントエンドはいずれもバックエンドが `http://127.0.0.1:5300` で提供します。
- **フロントエンド**:`web/` は **Vite + React Router 7 + shadcn/ui + Tailwind CSS** の SPA で、`pnpm` で管理します(注意:Next.js では**ありません**。`dev` スクリプトは `vite` です)。
- **プラグインシステム**:プラグイン SDK、CLI(`lbp`)、プラグインランタイム、Box(サンドボックス)ランタイム、および LangBot とプラグインで共有されるエンティティ/API 定義は、すべて別リポジトリ [`langbot-plugin-sdk`](https://github.com/langbot-app/langbot-plugin-sdk) にあります。LangBot は `pyproject.toml` でバージョン固定した `langbot-plugin` パッケージを通じて依存します。
## リポジトリ構成
```
LangBot/
├── main.py # エントリーシム -> langbot.__main__.main()
├── pyproject.toml # Python プロジェクト + 依存(uv)、langbot-plugin==<x.y.z> を固定
├── src/langbot/
│ ├── __main__.py # 実際のエントリーポイント、CLI 引数(例:--standalone-runtime)
│ ├── pkg/ # コアバックエンドパッケージ
│ │ ├── api/ # HTTP API コントローラ + サービス(Quart)
│ │ ├── core/ # アプリ起動、ステージ、タスクマネージャ
│ │ ├── platform/ # IM プラットフォームアダプタ、ボット管理、セッション管理
│ │ ├── provider/ # LLM プロバイダ、リクエスタ、ツールプロバイダ
│ │ ├── pipeline/ # パイプライン、ステージ、クエリプール
│ │ ├── plugin/ # プラグインランタイムへのブリッジ(connector.py / handler.py)
│ │ ├── box/ # コードサンドボックスサブシステム(Docker / nsjail / E2B バックエンド)
│ │ ├── skill/ # スキルサブシステム
│ │ ├── rag/ , vector/ # RAG とベクトルストア
│ │ ├── command/ # 組み込みコマンド
│ │ ├── persistence/ # ORM モデル + Alembic マイグレーション(SQLite & PostgreSQL)
│ │ ├── storage/ # オブジェクト/ファイルストレージ抽象
│ │ ├── config/, entity/, discover/, utils/, telemetry/, survey/
│ ├── libs/ # 同梱 SDK(qq_official_api、wecom_api など)
│ └── templates/ # 設定/コンポーネントテンプレート(例:templates/config.yaml)
├── web/ # フロントエンド SPA(Vite + React Router 7 + shadcn + Tailwind)
└── docker/ # docker-compose デプロイファイル
```
## コンポーネントの構成方法
コアバックエンドパッケージ `src/langbot/pkg/` は責務ごとに疎結合なサブモジュールに分割されています:
| モジュール | 責務 |
| --- | --- |
| `core` | アプリケーションのライフサイクル:起動ステージが設定読み込み・DB 接続・各サブシステムの起動を順に行い、バックグラウンドタスクを管理。 |
| `platform` | 各 IM プラットフォーム(Discord、Telegram、QQ、WeCom、Lark など)のアダプタ。メッセージ送受信、ボットとセッションの管理。 |
| `provider` | LLM プロバイダとリクエスタ(OpenAI 互換および各社ネイティブ API)、Agent が呼び出すツールプロバイダ。 |
| `pipeline` | メッセージ処理パイプライン:1 つのメッセージをトリガー・AI 処理・出力・安全の各ステージに通す。 |
| `plugin` | LangBot 本体とプラグインランタイム間のブリッジ。接続・アクション送受信・イベント転送。 |
| `box` | コードサンドボックスサブシステム。スキル/ツールに隔離されたコード実行環境を提供し、可用性に応じて Docker / nsjail / E2B を選択。 |
| `skill` / `rag` / `vector` | スキル、検索拡張生成、ベクトルストアの機能。 |
| `persistence` | ORM エンティティ定義と Alembic マイグレーション。単一のスクリプトセットで SQLite と PostgreSQL の両方に対応。 |
プラグイン側のコンポーネント(`langbot-plugin-sdk` で定義)は 1 つの `BasePlugin` を中心に構成されます:
- **Command**:ユーザーが能動的に起動するコマンド(例:`!weather tokyo`)。
- **Tool**:LLM が Agent 実行中に呼び出す関数(例:天気取得、データベース照会)。
- **EventListener**:メッセージパイプライン中のイベントを監視するハンドラ(例:自動返信、コンテンツフィルタ)。
各プラグインは独立したプロセスで実行され、プラグインランタイムがライフサイクルを統一管理します(発見 → 依存インストール → ロード → 初期化 → コンポーネント登録 → 準備完了 → 終了)。
## 実行時の接続関係
```
┌──────────────┐ HTTP/API ┌──────────────┐
│ ブラウザ/Web │ ────────────► │ │
│ (Vite SPA) │ :3000/同一 │ LangBot │
└──────────────┘ オリジン │ バックエンド │
│ (Quart) │
┌───────────────────────────┤ :5300 ├─────────────────────────┐
│ stdio または WebSocket └──────────────┘ stdio または WebSocket │
▼ ▼
┌──────────────┐ ┌──────────────┐
│ プラグイン │ 独立プロセス、 │ Box │ コードサンドボックス
│ ランタイム │ 各プラグインを起動 │ ランタイム │ Docker/nsjail/E2B
│ :5400 / :5401│ │ :5410 │
└──────────────┘ └──────────────┘
```
- **フロントエンド ↔ バックエンド**:開発時はフロントエンドが `:3000` で単独動作し、`web/.env` の `VITE_API_BASE_URL` を通じてバックエンド `:5300` にアクセス。本番ではフロントエンドが静的ファイルにビルドされ、バックエンドが同一オリジンで提供します。
- **バックエンド ↔ プラグインランタイム**:
- LangBot を**直接起動**した場合(コンテナ外)、バックエンドが自らランタイムを**起動**し、**stdio** で通信します(軽量/個人向け)。stdio は**自動再接続できません**——切断後は LangBot の再起動が必要です。よくある障害は、前のバックエンドが残した**孤児ランタイムプロセス**が `5400`/`5401` を占有しているケースで、それを kill して再起動します。
- LangBot を**コンテナ**で実行する場合、**WebSocket** で独立したランタイムに接続します(本番向け)。制御ポートは既定 `5400`、デバッグポートは `5401`。設定:`data/config.yaml` の `plugin.runtime_ws_url`(例:`ws://langbot_plugin_runtime:5400/control/ws`)。
- **バックエンド ↔ Box ランタイム**:Box サブシステムは制御チャネル(既定ポート `5410`)で Box ランタイムに接続し、ランタイムが Docker / nsjail / E2B でサンドボックスコードを実行します。
- ランタイム・CLI・SDK のデバッグ方法の詳細は[「プラグインランタイム、CLI、SDK のデバッグ」](/ja/develop/plugin-runtime)を参照。詳細なフラグとアーキテクチャは `langbot-plugin-sdk` リポジトリの `AGENTS.md` にあります。
## 開発環境のセットアップ
詳細は[「開発設定」](/ja/develop/dev-config)を参照。要点:
### バックエンド
```bash
pip install uv
uv sync --dev # uv が .venv/ を自動作成。エディタのインタプリタをそこに向ける
uv run main.py # http://127.0.0.1:5300 で API + フロントエンドを提供
```
初回起動時に設定ファイルが `data/config.yaml` に生成されます。既定は SQLite(設定不要)で、PostgreSQL にも対応。マイグレーションは起動時に自動実行されます。
### フロントエンド
Node.js と [pnpm](https://pnpm.io/ja/installation) が必要です。
```bash
cd web
cp .env.example .env # Windows: copy .env.example .env
pnpm install
pnpm dev # http://127.0.0.1:3000(npm install / npm run dev も可)
```
`pnpm dev` は `web/.env` の `VITE_API_BASE_URL` を読み込み、開発時のフロントエンドがバックエンド `:5300` にアクセスできるようにします。
### コードフォーマット
CI で lint + format チェックが走ります。pre-commit フックをインストールして、同じチェックを各コミット前にローカルで実行してください:
```bash
uv run pre-commit install
```
### データベースマイグレーション
ORM モデルを変更したらマイグレーションを生成します:
```bash
# プロジェクトルートで実行(data/config.yaml が必要)
uv run python -m langbot.pkg.persistence.alembic_runner autogenerate "変更内容の説明"
```
`autogenerate` はスキーマ変更(列・テーブルの追加/削除、型変更)を検出しますが、**データマイグレーション**(JSON フィールドの内容変更など)は生成スクリプトに手書きする必要があります。`env.py` で `render_as_batch=True` が設定されており、SQLite の ALTER TABLE 制限が自動処理されるため、データベース種別ごとの分岐は不要です。マイグレーションは起動時に自動実行されます。
## 開発規約
- LangBot はグローバルなプロジェクトです:**すべてのコードコメントと docstring は英語**で、ユーザー向けの文字列はすべて **i18n** に対応する必要があります(最低限 `en_US` + `zh_Hans`、リポジトリに日本語がある箇所は `ja_JP` も)。
- LangBot は toC・toB の両シナリオで採用されているため、常に互換性とセキュリティを考慮してください。
- **コミットメッセージ形式**:`<type>(<scope>): <subject>`
- `type`:`feat`、`fix`、`docs`、`style`、`refactor`、`perf`、`test`、`chore` など。
- `scope`:影響を受けるパッケージ/モジュール/ファイル/クラス。
- `subject`:変更内容の簡潔な説明。
## いくつかの原則
- Keep it simple, stupid.
- 必要がなければエンティティを増やさない。
- 八荣八耻(八つの栄誉と八つの恥):
以瞎猜接口为耻,以认真查询为荣。
以模糊执行为耻,以寻求确认为荣。
以臆想业务为耻,以人类确认为荣。
以创造接口为耻,以复用现有为荣。
以跳过验证为耻,以主动测试为荣。
以破坏架构为耻,以遵循规范为荣。
以假装理解为耻,以诚实无知为荣。
以盲目修改为耻,以谨慎重构为荣。
+165
View File
@@ -0,0 +1,165 @@
---
title: "AI 助手开发上下文"
description: "可直接整页复制、粘贴给 AI 编程助手的 LangBot 项目上下文:目录结构、组件组织方式、运行期连接关系与开发环境配置。"
---
<Info title="本页面是为 AI 编程助手(Claude Code / Cursor / Copilot / Codex 等)准备的。">
直接把本页**全部内容**复制粘贴给你的 AI 助手,它即可快速了解 LangBot 的整体架构、各组件如何组织、运行期如何连接,以及如何配置开发环境,无需你再逐条解释。
</Info>
本页内容与各仓库根目录的 `AGENTS.md`(`CLAUDE.md` 为其软链接)保持一致,是 LangBot 项目面向开发者与 AI 助手的"一页上手"说明。
## 项目概览
LangBot 是一个开源的、LLM 原生的即时通信机器人开发平台,提供开箱即用的 IM 机器人开发体验,内置 Agent、RAG、MCP 等 LLM 应用能力,支持全球主流 IM 平台,并提供丰富的 API 以供二次开发。
LangBot 拥有完整的 Web 前端,几乎所有操作都可以通过前端完成。
- **后端**:Python(`>=3.11,<4.0`),使用 `uv` 管理依赖;Web 框架为 Quart(Flask 的异步版本)。HTTP API 与预编译好的前端都由后端在 `http://127.0.0.1:5300` 上提供服务。
- **前端**:`web/` 是 **Vite + React Router 7 + shadcn/ui + Tailwind CSS** 的 SPA,使用 `pnpm` 管理依赖(注意:**不是** Next.js,`dev` 脚本就是 `vite`)。
- **插件系统**:插件 SDK、CLI(`lbp`)、插件运行时、Box 沙箱运行时以及 LangBot 与插件共享的实体/API 定义,全部位于独立仓库 [`langbot-plugin-sdk`](https://github.com/langbot-app/langbot-plugin-sdk)。LangBot 通过 `pyproject.toml` 中固定版本的 `langbot-plugin` 包依赖它。
## 仓库目录结构
```
LangBot/
├── main.py # 入口垫片 -> langbot.__main__.main()
├── pyproject.toml # Python 项目与依赖(uv),固定 langbot-plugin==<x.y.z>
├── src/langbot/
│ ├── __main__.py # 真正的入口,定义 CLI 参数(如 --standalone-runtime)
│ ├── pkg/ # 核心后端包
│ │ ├── api/ # HTTP API 控制器 + 服务(Quart)
│ │ ├── core/ # 应用引导、启动阶段(stages)、任务管理器
│ │ ├── platform/ # IM 平台适配器、机器人管理、会话管理
│ │ ├── provider/ # LLM 提供商、请求器、工具提供者
│ │ ├── pipeline/ # 流水线、阶段、查询池
│ │ ├── plugin/ # 连接插件运行时的桥接层(connector.py / handler.py)
│ │ ├── box/ # 代码沙箱子系统(Docker / nsjail / E2B 后端)
│ │ ├── skill/ # 技能子系统
│ │ ├── rag/ , vector/ # RAG 与向量存储
│ │ ├── command/ # 内置命令
│ │ ├── persistence/ # ORM 模型 + Alembic 迁移(SQLite 与 PostgreSQL)
│ │ ├── storage/ # 对象/文件存储抽象
│ │ ├── config/, entity/, discover/, utils/, telemetry/, survey/
│ ├── libs/ # 内置 SDK(qq_official_api、wecom_api 等)
│ └── templates/ # 配置/组件模板(如 templates/config.yaml)
├── web/ # 前端 SPA(Vite + React Router 7 + shadcn + Tailwind)
└── docker/ # docker-compose 部署文件
```
## 组件如何组织
LangBot 后端的核心包 `src/langbot/pkg/` 按职责拆分为若干子模块,彼此低耦合:
| 模块 | 职责 |
| --- | --- |
| `core` | 应用生命周期:启动阶段(stages)按序加载配置、连接数据库、拉起各子系统,并管理后台任务。 |
| `platform` | 各 IM 平台的适配器(Discord、Telegram、QQ、企业微信、飞书等),负责收发消息、管理机器人与会话。 |
| `provider` | LLM 提供商与请求器(OpenAI 兼容、各家原生 API),以及供 Agent 调用的工具提供者。 |
| `pipeline` | 消息处理流水线:把一条消息经过触发、AI 处理、输出、安全等阶段串联起来。 |
| `plugin` | LangBot 主程序与插件运行时之间的桥接层,负责连接、收发动作、转发事件。 |
| `box` | 代码沙箱子系统,为技能/工具提供隔离的代码执行环境,按可用性选择 Docker / nsjail / E2B 后端。 |
| `skill` / `rag` / `vector` | 技能、检索增强生成与向量存储能力。 |
| `persistence` | ORM 实体定义与 Alembic 数据库迁移,单套脚本同时兼容 SQLite 与 PostgreSQL。 |
插件侧的组件(在 `langbot-plugin-sdk` 中定义)则围绕一个 `BasePlugin` 组织:
- **Command(命令)**:用户主动触发的指令(如 `!weather tokyo`)。
- **Tool(工具)**:供 LLM 在 Agent 执行过程中调用的函数(如查天气、查数据库)。
- **EventListener(事件监听器)**:监听消息流水线中的事件(如自动回复、内容过滤)。
每个插件运行在独立进程中,由插件运行时统一管理生命周期(发现 → 安装依赖 → 加载 → 初始化 → 注册组件 → 就绪 → 终止)。
## 运行期如何连接
```
┌──────────────┐ HTTP/API ┌──────────────┐
│ 浏览器/前端 │ ──────────► │ │
│ (Vite SPA) │ :3000/同域 │ LangBot │
└──────────────┘ │ 后端 │
│ (Quart) │
┌─────────────────────────┤ :5300 ├─────────────────────────┐
│ stdio 或 WebSocket └──────────────┘ stdio 或 WebSocket │
▼ ▼
┌──────────────┐ ┌──────────────┐
│ 插件运行时 │ 独立进程,逐个拉起插件 │ Box 运行时 │ 代码沙箱
│ :5400 / :5401│ │ :5410 │ Docker/nsjail/E2B
└──────────────┘ └──────────────┘
```
- **前端 ↔ 后端**:开发时前端独立跑在 `:3000`,通过 `web/.env` 的 `VITE_API_BASE_URL` 访问后端 `:5300`;生产环境前端被预编译为静态文件由后端同域提供。
- **后端 ↔ 插件运行时**:
- 用户**直接启动** LangBot(非容器)时,后端自己**拉起**运行时并通过 **stdio** 通信(轻量/个人场景)。stdio **不能自动重连**——断开后需重启 LangBot;常见故障是上一个后端遗留的**孤儿运行时进程**仍占用 `5400`/`5401`,杀掉后重启即可。
- LangBot 运行在**容器**中时,通过 **WebSocket** 连接到独立的运行时(生产场景)。控制端口默认 `5400`,调试端口默认 `5401`。相关配置:`data/config.yaml` 的 `plugin.runtime_ws_url`(如 `ws://langbot_plugin_runtime:5400/control/ws`)。
- **后端 ↔ Box 运行时**:Box 子系统通过控制通道连接到 Box 运行时(默认端口 `5410`),运行时在 Docker / nsjail / E2B 中执行沙箱代码。
- 调试运行时、CLI 与 SDK 的完整方法见[《调试插件运行时、CLI、SDK》](/zh/develop/plugin-runtime),详细参数与架构在 `langbot-plugin-sdk` 仓库的 `AGENTS.md` 中。
## 开发环境配置
完整说明见[《开发配置》](/zh/develop/dev-config)。要点如下:
### 后端
```bash
pip install uv
uv sync --dev # uv 会自动创建 .venv/;请把编辑器解释器指向它
uv run main.py # 在 http://127.0.0.1:5300 提供 API + 前端
```
首次启动会在 `data/config.yaml` 生成配置文件。默认使用 SQLite(零配置),同时支持 PostgreSQL;迁移在启动时自动执行。
### 前端
需要 Node.js 与 [pnpm](https://pnpm.io/zh/installation)。
```bash
cd web
cp .env.example .env # Windows: copy .env.example .env
pnpm install
pnpm dev # http://127.0.0.1:3000(也可用 npm install / npm run dev)
```
`pnpm dev` 会读取 `web/.env` 中的 `VITE_API_BASE_URL`,使开发态前端能访问后端 `:5300`。
### 代码格式化
仓库 CI 会跑 lint + format 检查。安装 pre-commit 钩子,让同样的检查在每次提交前于本地运行:
```bash
uv run pre-commit install
```
### 数据库迁移
修改 ORM 模型后生成迁移:
```bash
# 在项目根目录运行(需已有 data/config.yaml)
uv run python -m langbot.pkg.persistence.alembic_runner autogenerate "描述你的变更"
```
`autogenerate` 能检测 schema 变更(增删列/表、类型变更),但**数据迁移**(如修改 JSON 字段内容)需手写进生成的脚本。`env.py` 设置了 `render_as_batch=True`,会自动处理 SQLite 的 ALTER TABLE 限制,无需按数据库类型分支。迁移在 LangBot 启动时自动执行。
## 开发规范
- LangBot 是全球化项目:**所有代码注释与文档字符串必须为英文**,所有面向用户的文案必须支持 **i18n**(至少 `en_US` + `zh_Hans`,仓库已有日文处则补 `ja_JP`)。
- LangBot 同时被 toC 与 toB 场景采用,请始终考虑兼容性与安全性。
- **提交信息格式**:`<type>(<scope>): <subject>`
- `type`:`feat`、`fix`、`docs`、`style`、`refactor`、`perf`、`test`、`chore` 等。
- `scope`:受影响的包/模块/文件/类。
- `subject`:简洁的变更描述。
## 一些原则
- Keep it simple, stupid.
- 如无必要,勿增实体。
- 八荣八耻:
以瞎猜接口为耻,以认真查询为荣。
以模糊执行为耻,以寻求确认为荣。
以臆想业务为耻,以人类确认为荣。
以创造接口为耻,以复用现有为荣。
以跳过验证为耻,以主动测试为荣。
以破坏架构为耻,以遵循规范为荣。
以假装理解为耻,以诚实无知为荣。
以盲目修改为耻,以谨慎重构为荣。