chore: 初始化仓库,导入项目基线代码
Academy v0.8.3 完整代码基线:Go 后端(internal/cmd/cli/mcp-server/docreader)、 Vue 前端(frontend)、数据库迁移(migrations)、部署编排(docker/helm/deploy)与文档。 今日开发的培训推送管理改动随后单独提交。
This commit is contained in:
commit
7ec21f35b0
5767 files changed
+1436788
No files matched your search
@@ -0,0 +1,373 @@
|
||||
# 开发指南
|
||||
|
||||
开发环境使用 `docker-compose.dev.yml` 启动依赖服务,并支持独立运行 Go 后端、Web 前端和 docreader。代码修改后按所在模块执行构建与测试,再检查相关集成路径。
|
||||
|
||||
## 技术栈与环境要求 {#_1-技术栈与环境要求}
|
||||
|
||||
Academy 由三个可独立开发的进程组成:
|
||||
|
||||
| 组件 | 目录 | 语言 / 运行时 | 版本要求(来源) |
|
||||
| --- | --- | --- | --- |
|
||||
| 主后端 `app` | `cmd/server` + `internal/` | Go | **Go 1.26.0**(`go.mod` 中 `go 1.26.0`),需 CGO(DuckDB、sqlite-vec 绑定) |
|
||||
| 文档解析服务 `docreader` | `docreader/` | Python + gRPC | **Python >= 3.10.18**(`docreader/pyproject.toml` 中 `requires-python`),依赖用 **uv** 管理(仓库含 `uv.lock`,Docker 内 `uv sync --locked`) |
|
||||
| 前端 `frontend` | `frontend/` | Node.js + Vue 3 | Node 22 系(`devDependencies` 含 `@tsconfig/node22`、`@types/node ^22`),Vite 7 + TypeScript ~6.0 + Vue 3.5 + TDesign,版本号 `0.8.3` |
|
||||
| CLI | `cli/`(独立 Go module) | Go | Go 1.26(`.github/workflows/cli.yml` 矩阵 `go: ['1.26']`) |
|
||||
|
||||
推荐额外安装的开发工具:
|
||||
|
||||
```bash
|
||||
# 数据库迁移 CLI(scripts/migrate.sh 依赖)
|
||||
go install -tags 'postgres' github.com/golang-migrate/migrate/v4/cmd/migrate@latest
|
||||
|
||||
# 代码检查(make lint 调用)
|
||||
# 安装方式见 https://golangci-lint.run;仓库根有 .golangci.yml 配置
|
||||
|
||||
# Swagger 文档生成(make docs 调用)
|
||||
make install-swagger # go install github.com/swaggo/swag/cmd/swag@latest
|
||||
|
||||
# Python 依赖管理
|
||||
pip install uv # docreader 使用 uv sync 安装依赖
|
||||
|
||||
# Docker + Docker Compose(v2 插件或独立 docker-compose 均可,scripts/dev.sh 自动探测)
|
||||
```
|
||||
|
||||
## 快速开始:开发模式(推荐) {#_2-快速开始-开发模式-推荐}
|
||||
|
||||
开发模式在 Docker 中运行基础设施,在本地运行 `app` 和 `frontend`。修改应用代码后可直接重启进程,无需重建依赖镜像。入口为 `scripts/dev.sh`,Makefile 的 `dev-*` 目标封装了相应操作。
|
||||
|
||||
```bash
|
||||
# 1. 准备环境变量:dev.sh 会加载 .env(必须存在),再用 .env.local 覆盖(可选)
|
||||
cp .env.example .env
|
||||
|
||||
# 2. 启动基础设施(ParadeDB/Postgres + Redis + docreader,默认还带 Langfuse)
|
||||
make dev-start # 等价 ./scripts/dev.sh start
|
||||
make dev-start DEV_ARGS=--qdrant # 附加可选 profile
|
||||
|
||||
# 3. 另开终端:本地跑后端(内部执行 go run -ldflags=... ./cmd/server)
|
||||
make dev-app # 等价 ./scripts/dev.sh app
|
||||
|
||||
# 4. 再开终端:本地跑前端(cd frontend && npm install && npm run dev)
|
||||
make dev-frontend # 等价 ./scripts/dev.sh frontend
|
||||
|
||||
# 其他
|
||||
make dev-status # 查看容器状态
|
||||
make dev-logs # 查看日志
|
||||
make dev-stop # 停止
|
||||
make dev-restart # 重启
|
||||
```
|
||||
|
||||
前端 dev server 监听 `5173`(`frontend/vite.config.ts` 中 `server.port: 5173`),把 `/api`、`/files` 与 `/mcp/` 代理到后端。代理目标依次取进程环境变量 `VITE_DEV_PROXY_TARGET`、`FRONTEND_BACKEND_URL`,两者都未设置或为空时使用 `http://localhost:8080`。`DEV_PROXY_TARGET` 是配置文件中的内部常量,不是环境变量。
|
||||
|
||||
连接远程后端时,可在仓库根目录的 `.env.local` 中设置(将示例地址替换为实际后端地址):
|
||||
|
||||
```bash
|
||||
VITE_DEV_PROXY_TARGET=https://kb.example.com
|
||||
```
|
||||
|
||||
然后在仓库根目录运行 `make dev-frontend`;脚本会先加载根目录 `.env`,再用 `.env.local` 覆盖,并将变量导出给 Vite。修改代理目标后需要重启前端开发服务器。
|
||||
|
||||
如果直接在 `frontend/` 目录运行 npm 命令,应显式传入环境变量;该方式不会经过脚本加载仓库根目录的环境文件:
|
||||
|
||||
```bash
|
||||
cd frontend
|
||||
VITE_DEV_PROXY_TARGET=https://kb.example.com npm run dev
|
||||
```
|
||||
|
||||
`vite preview`(端口 `4173`)用生产构建产物起服务,是最接近 release 镜像的验证环境。它使用相同的代理路径和目标选择规则,可在 `frontend/` 目录执行 `npm run build` 后,用 `VITE_DEV_PROXY_TARGET=https://kb.example.com npm run preview` 连接远程后端。
|
||||
|
||||
### docker-compose.dev.yml 服务清单 {#_2-1-docker-compose-dev-yml-服务清单}
|
||||
|
||||
`docker-compose.dev.yml` 只包含依赖服务,不含 `app`/`frontend`。默认启动与 profile 可选服务如下(profile 通过 `dev.sh start` 的参数开启):
|
||||
|
||||
| 服务 | 镜像 | 端口(默认) | 启动条件 |
|
||||
| --- | --- | --- | --- |
|
||||
| `postgres` | `paradedb/paradedb:v0.25.11-pg17`(自带 pg_search/BM25) | `5432` | 默认启动 |
|
||||
| `redis` | `redis:7.0-alpine`(`--requirepass`) | `6379` | 默认启动 |
|
||||
| `docreader` | 本地构建 `docker/Dockerfile.docreader` | `50051`(gRPC) | 默认启动 |
|
||||
| `searxng`(+`searxng-init`) | `searxng/searxng:latest` | `127.0.0.1:8888` | `--searxng` / `--full`(compose profile `searxng`) |
|
||||
| `minio` | `pgsty/minio:latest` | `9000` / 控制台 `9001` | `--minio` / `--full` |
|
||||
| `qdrant` | `qdrant/qdrant:v1.16.2` | `6333` / `6334` | `--qdrant` / `--full` |
|
||||
| `opensearch` | `opensearchproject/opensearch:3.3.2`(关闭 security,纯 HTTP) | `9200` | profile `opensearch` / `full` |
|
||||
| `opensearch-dashboards` | `opensearchproject/opensearch-dashboards:3.3.0` | `5601` | profile `opensearch-ui`(按需单独启动) |
|
||||
| `milvus` | `milvusdb/milvus:v2.6.11`(standalone,内嵌 etcd) | `19530` / `9091` | profile `milvus` / `full` |
|
||||
| `neo4j` | `neo4j:latest`(APOC 插件) | `7474` / `7687` | `--neo4j` / `--full` |
|
||||
| `dex` | `dexidp/dex:latest`(OIDC 测试身份源,配置 `misc/dex-config.yaml`) | `5556` | `--dex` / `--full` |
|
||||
| `langfuse-web` / `langfuse-worker` / `langfuse-clickhouse` / `langfuse-minio` / `langfuse-db-init` | Langfuse v3 自建栈,复用 dev 的 postgres(独立 `langfuse` 库)与 redis(DB 1) | web `3000`、minio `9100/9101` | `--langfuse`(`dev.sh` 默认开启,`--no-langfuse` 关闭) |
|
||||
| `odl-hybrid` | 本地构建 `docker/Dockerfile.odl-hybrid`(Docling PDF 后端) | `5002` | `--odl-hybrid`(镜像较大,按需) |
|
||||
| `sandbox` | `wechatopenai/weknora-sandbox`(Skills 脚本执行沙箱,仅 build/pull,非常驻) | - | profile `full` |
|
||||
|
||||
`dev.sh start` 的可选参数:`--minio`、`--qdrant`、`--neo4j`、`--dex`、`--langfuse`(默认开)、`--no-langfuse`、`--odl-hybrid`、`--full`(全部可选服务,不含 odl-hybrid)。通过 Makefile 传参:`make dev-start DEV_ARGS=--odl-hybrid`。
|
||||
|
||||
### 本地单独跑 docreader {#_2-2-本地单独跑-docreader}
|
||||
|
||||
`dev-start` 默认把 docreader 跑在容器里;如需本地调试 Python 代码:
|
||||
|
||||
```bash
|
||||
cd docreader
|
||||
uv sync # 按 uv.lock 安装依赖(容器内为 uv sync --locked --no-dev)
|
||||
uv run -m docreader.main # 启动 gRPC 服务(与 Dockerfile CMD 一致),监听 DOCREADER_GRPC_PORT(默认 50051)
|
||||
```
|
||||
|
||||
docreader 的大量调优参数(PDF 渲染 DPI、扫描件判定、SSRF 白名单、gRPC TLS 等)以 `DOCREADER_*` 环境变量注入,完整清单见 `docker-compose.dev.yml` 的 `docreader.environment` 段。
|
||||
|
||||
### Lite 模式(零外部依赖) {#_2-3-lite-模式-零外部依赖}
|
||||
|
||||
Lite 模式把 SQLite(+sqlite-vec)与内存队列编译进单个二进制,适合快速体验与桌面端:
|
||||
|
||||
```bash
|
||||
make build-lite # 先构建前端到 web/,再 CGO 构建 Go(tags: sqlite_fts5);SKIP_FRONTEND=1 跳过前端
|
||||
make run-lite # 依赖 .env.lite,构建并启动 Academy-lite
|
||||
make package-lite # 打 tarball 发行包(scripts/package-lite.sh)
|
||||
make package-mac-app # 打 macOS .app(scripts/package-mac-app.sh)
|
||||
```
|
||||
|
||||
## Makefile 目标全览 {#_3-makefile-目标全览}
|
||||
|
||||
以下目标定义在根目录 `Makefile`,`make help` 也有一份中文帮助。
|
||||
|
||||
### 基础构建与运行 {#_3-1-基础构建与运行}
|
||||
|
||||
| 目标 | 作用 |
|
||||
| --- | --- |
|
||||
| `build` | `go build -o Academy ./cmd/server` |
|
||||
| `run` | 先 `build` 再运行 `./Academy` |
|
||||
| `test` | `go test -v ./...` |
|
||||
| `clean` | `go clean` 并删除二进制 |
|
||||
| `build-prod` | 生产构建:CGO_ENABLED=1,`-ldflags "-w -s"` 注入 Version/CommitID/BuildTime/GoVersion(`internal/handler` 包变量),并设置 protobuf `conflictPolicy=warn`(规避 qdrant/milvus proto 冲突) |
|
||||
| `fmt` | `go fmt ./...` |
|
||||
| `lint` | `golangci-lint run` |
|
||||
| `deps` | `go mod download` |
|
||||
| `docs` | `swag init`(参数见 Makefile,含 `--overridesFile ./docs/swag.overrides`)生成 Swagger 文档 |
|
||||
| `install-swagger` | 安装 `swag` CLI |
|
||||
|
||||
### Docker 镜像与服务管理 {#_3-2-docker-镜像与服务管理}
|
||||
|
||||
| 目标 | 作用 |
|
||||
| --- | --- |
|
||||
| `docker-build-app` | 构建 `wechatopenai/weknora-app`(`docker/Dockerfile.app`,注入 `scripts/get_version.sh` 的版本信息) |
|
||||
| `docker-build-docreader` | 构建 `wechatopenai/weknora-docreader`(`docker/Dockerfile.docreader`) |
|
||||
| `docker-build-frontend` | 多阶段构建 `wechatopenai/weknora-ui`(builder 内 `npm ci` + `npm run build`,无需宿主机预构建 dist;自动从 git 注入 `VITE_FRONTEND_COMMIT`) |
|
||||
| `docker-build-all` | 以上三个镜像 |
|
||||
| `docker-run` | 确保 `.env` 存在(缺失时从 `.env.example` 复制或 touch)后 `docker-compose up` |
|
||||
| `docker-stop` / `docker-restart` | `docker-compose down` / `stop -t 60` + `up` |
|
||||
| `start-all` / `stop-all` | `scripts/start_all.sh`(一键启动/停止全部服务) |
|
||||
| `start-ollama` / `start-docker` | `start_all.sh --ollama` / `--docker` |
|
||||
| `build-images` / `build-images-app` / `build-images-docreader` / `build-images-frontend` / `clean-images` | `scripts/build_images.sh` 从源码构建/清理镜像 |
|
||||
| `check-env` / `list-containers` / `pull-images` | `start_all.sh --check / --list / --pull` |
|
||||
| `show-platform` | 显示 `uname -m` 与 Docker 构建平台(amd64/arm64 自动探测) |
|
||||
| `clean-db` | 删除 `academy_postgres-data` / `academy_minio_data` / `academy_redis_data` 三个 Docker volume(**清空数据**) |
|
||||
|
||||
### 数据库迁移(详见《数据库与迁移》一章) {#_3-3-数据库迁移-详见《数据库与迁移》一章}
|
||||
|
||||
| 目标 | 作用 |
|
||||
| --- | --- |
|
||||
| `migrate-up` / `migrate-down` | `scripts/migrate.sh up / down` |
|
||||
| `migrate-version` | 查看当前迁移版本 |
|
||||
| `migrate-create name=xxx` | 创建一对新迁移文件 |
|
||||
| `migrate-force version=N` | 强制设置版本(dirty state 恢复) |
|
||||
| `migrate-goto version=N` | 迁移到指定版本 |
|
||||
|
||||
### 开发模式与 Lite {#_3-4-开发模式与-lite}
|
||||
|
||||
| 目标 | 作用 |
|
||||
| --- | --- |
|
||||
| `dev-start` / `dev-stop` / `dev-restart` / `dev-logs` / `dev-status` | `scripts/dev.sh start/stop/restart/logs/status`(支持 `DEV_ARGS` 传 profile 参数) |
|
||||
| `dev-app` | 本地 `go run ./cmd/server`(带版本 ldflags) |
|
||||
| `dev-frontend` | 本地 `npm run dev` |
|
||||
| `build-lite` / `run-lite` / `package-lite` / `package-mac-app` | Lite 模式构建/运行/打包(见 2.3) |
|
||||
| `download_spatial` | `go run cmd/download/duckdb/duckdb.go` 下载 DuckDB spatial 扩展(数据分析工具用) |
|
||||
|
||||
### 模型厂商目录 {#_3-5-模型厂商目录}
|
||||
|
||||
| 目标 | 作用 |
|
||||
| --- | --- |
|
||||
| `model-catalog-generate` | `python3 scripts/model-catalog/generate.py`,重新生成厂商目录的元数据与协议覆盖 |
|
||||
| `model-catalog-check` | 校验生成结果是否最新,并运行 `go test ./internal/models/...`(CI 同样校验) |
|
||||
| `model-catalog-diff` | 对比 models.dev 输出模型元数据差异报告,仅供人工审阅,不写回文件;可用 `VENDOR=deepseek` 只看单个厂商 |
|
||||
|
||||
厂商接入方式见[扩展点](03-extension-points.md)。
|
||||
|
||||
## 测试体系 {#_4-测试体系}
|
||||
|
||||
### Go 单元测试(主模块) {#_4-1-go-单元测试-主模块}
|
||||
|
||||
```bash
|
||||
make test # go test -v ./...
|
||||
# 或按包运行:
|
||||
go test ./internal/infrastructure/chunker/...
|
||||
go test -run TestXxx ./internal/application/service/...
|
||||
```
|
||||
|
||||
主模块测试广泛使用 `go-sqlmock`、`miniredis` 等内存替身(见 `go.mod`),大部分无需真实数据库即可运行。部分包依赖 CGO(DuckDB/sqlite-vec)。
|
||||
|
||||
### docreader 测试(Python) {#_4-2-docreader-测试-python}
|
||||
|
||||
测试位于 `docreader/tests/`,使用标准库 `unittest` 编写(文件内 `unittest.main()`),覆盖解析路由、并发、EPUB/Excel/MHTML/PDF 解析、SSRF 防护等:
|
||||
|
||||
```bash
|
||||
cd docreader
|
||||
uv sync
|
||||
uv run python -m unittest discover -s tests -v # 全部
|
||||
uv run python -m unittest tests.test_parser_routing # 单个
|
||||
```
|
||||
|
||||
### CLI 测试与验收测试 {#_4-3-cli-测试与验收测试}
|
||||
|
||||
`cli/` 是独立 Go module,自带 `cli/Makefile`:
|
||||
|
||||
```bash
|
||||
cd cli
|
||||
make test # go test ./...
|
||||
make test-coverage # 带覆盖率
|
||||
make lint # go vet
|
||||
```
|
||||
|
||||
跨切面的契约/集成测试集中在 `cli/acceptance/`(见 `cli/acceptance/doc.go`):
|
||||
|
||||
- `cli/acceptance/contract/` — envelope JSON 输出形状 golden 测试 + error.code 注册表一致性;
|
||||
- `cli/acceptance/e2e/` — 对真实 Academy server 的黑盒测试(testscript 风格),需要环境变量指向测试服务器;CI 侧由 `.github/workflows/cli-e2e.yml` 承载,**按需触发**(`workflow_dispatch` 手动,或给 PR 打 `acceptance-e2e` 标签),使用 secrets `ACADEMY_E2E_HOST` / `ACADEMY_E2E_TOKEN`。
|
||||
|
||||
### tests/ 目录与前端测试 {#_4-4-tests-目录与前端测试}
|
||||
|
||||
- `tests/miniprogram/miniprogram.test.js` — 小程序客户端的集成测试(Node 测试脚本),是 `tests/` 目前唯一内容;
|
||||
- 前端:`cd frontend && npm run type-check`(vue-tsc)与 `npm test`(`tsx --test`,Node test runner)。
|
||||
|
||||
## 代码规范与提交流程 {#_5-代码规范与提交流程}
|
||||
|
||||
### Go 代码规范 {#_5-1-go-代码规范}
|
||||
|
||||
仓库根 `.golangci.yml`(golangci-lint v2 配置格式):
|
||||
|
||||
```yaml
|
||||
version: 2
|
||||
linters-settings:
|
||||
lll:
|
||||
line-length: 120
|
||||
tab-width: 4
|
||||
linters:
|
||||
enable:
|
||||
- lll # 控制行宽(120 列)
|
||||
- govet
|
||||
- revive
|
||||
formatters:
|
||||
enable:
|
||||
- gofmt
|
||||
- gofumpt
|
||||
```
|
||||
|
||||
提交前建议执行:
|
||||
|
||||
```bash
|
||||
make fmt && make lint && make test
|
||||
```
|
||||
|
||||
注意格式化标准是 **gofumpt**(比 gofmt 更严格),行宽上限 120。
|
||||
|
||||
也可以安装仓库自带的 Git hooks(`./scripts/install-git-hooks.sh`,把 `core.hooksPath` 指向 `scripts/git-hooks`):pre-commit 检查空白字符、自动 gofmt 并在已安装时运行 golangci-lint;pre-push 按 CI 执行 gofmt 与 `go vet` / `go test` / `go build`。临时跳过可设 `SKIP_HOOKS=1`,只跳过 pre-push 的测试可设 `HOOK_SKIP_TEST=1`。
|
||||
|
||||
新增或升级第三方依赖、改动随发行物分发的数据文件时,需同步更新 `THIRD_PARTY_NOTICES.md` 与 `licenses/`,并用 `scripts/check-license-bundle.sh` 自检(`app.yml` 会执行同样的检查)。
|
||||
|
||||
### CI 与提交流程 {#_5-2-ci-与提交流程}
|
||||
|
||||
`.github/` 下的实际配置:
|
||||
|
||||
| 文件 | 触发路径 | 作用 |
|
||||
| --- | --- | --- |
|
||||
| `workflows/app.yml` | 根模块 Go 代码、`go.mod`、`config/`、`migrations/`、`scripts/`、`docker/Dockerfile.app`、许可证文件、模型目录数据 | 主模块检查:gofmt 格式校验(只针对 PR 内的提交)、`go vet`、`go test`、`go build ./cmd/server`;另校验第三方许可证包、模型厂商目录生成结果与 Git hooks 测试 |
|
||||
| `workflows/go-lint.yml` / `go-lint-cache.yml` | PR / main | golangci-lint 只报告 PR 相对合并基线新增的问题;`go-lint-cache.yml` 在 main 上预热缓存 |
|
||||
| `workflows/frontend.yml` | `frontend/`、`scripts/build_frontend_dist.sh` | Node 24:`npm test` + `npm run type-check` + `npm run build`;另构建 `frontend/Dockerfile` 多阶段镜像(不推送),并验证镜像内嵌入页与 MCP 代理路由(`scripts/test_embed_nginx.py`) |
|
||||
| `workflows/docreader.yml` | `docreader/`、`testdata/`、`packages/`、相关 Dockerfile | uv 装依赖 → `compileall` → `unittest discover docreader/tests`;再拉起 docreader gRPC 服务跑 `go test ./docreader/client ./docreader/proto` |
|
||||
| `workflows/mcp-server.yml` | `mcp-server/` | Python 3.10-3.13 矩阵测试;合入 main 后按 `pyproject.toml` 里的版本号用 PyPI Trusted Publishing 自动发布(版本已存在则跳过上传,不依赖打 tag) |
|
||||
| `workflows/cli.yml` | `cli/` | ubuntu/macos/windows 三平台矩阵,Go 1.26,`go build` + `go test -race -coverprofile` + `go vet` + skill wire 词表检查 |
|
||||
| `workflows/cli-e2e.yml` | 手动 / label | CLI 端到端验收(label `acceptance-e2e` 或手动触发,见 4.3) |
|
||||
| `workflows/docker-image.yml` | — | Docker 镜像构建发布 |
|
||||
| `workflows/release-lite.yml` | — | Lite 版本发布 |
|
||||
| `workflows/anydoc.yml` | `third_party/anydoc-go/`、`internal/infrastructure/docparser/` | 进程内 Office 解析引擎构建与测试 |
|
||||
| `workflows/dsh-plugin.yml` | `packages/dsh-academy/` | DeepSeek Harness 插件测试与发布 |
|
||||
| `pull_request_template.md` | — | PR 模板 |
|
||||
| `ISSUE_TEMPLATE/` | — | Issue 模板 |
|
||||
| `dependabot.yml` | — | 依赖升级机器人 |
|
||||
|
||||
四条按路径触发的检查(app / frontend / docreader / mcp-server)覆盖了主要模块,但本地先跑一遍仍然更省时间。前端可以直接用 `scripts/verify_frontend_pr.sh`,它按 CI 同样的顺序执行 `npm test` → `npm run type-check` → `npm run build`。
|
||||
|
||||
提交流程:fork / 分支 → 本地 `fmt + lint + test` → PR(按模板填写)→ 相关路径触发 CI。
|
||||
|
||||
## 调试技巧 {#_6-调试技巧}
|
||||
|
||||
### 日志级别 {#_6-1-日志级别}
|
||||
|
||||
日志实现在 `internal/logger/logger.go`(logrus)。级别由环境变量 `LOG_LEVEL` 控制,取值 `debug` / `info` / `warn`(`warning`)/ `error` / `fatal`,未设置或非法时默认 **debug**(`getLogLevelFromEnv()`)。`LOG_PATH` 控制输出路径;两者在 `main()` 加载 `.env` 后即时生效。docreader 侧同样读取 `LOG_LEVEL`(compose 中透传)。
|
||||
|
||||
每个请求带 `X-Request-ID` 贯穿 app 与 docreader 日志(docreader 的 `init_logging_request_id`),排查问题时先抓 request id。
|
||||
|
||||
### GIN_MODE 与 Swagger {#_6-2-gin-mode-与-swagger}
|
||||
|
||||
- `GIN_MODE=release` 时禁用 Swagger UI(`internal/router/router.go`)、并影响 embed channel 的安全行为。本地源码开发可设为 `debug`;Docker Compose 未设置此变量时默认使用 `release`。
|
||||
- Swagger 由 **app 后端**提供。默认地址为 `http://localhost:8080/swagger/index.html`;Compose 中若修改了 `APP_PORT`,应使用该宿主机映射端口。前端端口(默认 `80`)和 Vite 开发端口(默认 `5173`)没有配置 `/swagger/` 代理。
|
||||
- 发布镜像已包含 Swagger 文档;只有修改接口注释、需要重新生成文档并构建后端时,才需要运行 `make docs`。
|
||||
|
||||
#### Docker Compose 访问步骤
|
||||
|
||||
在项目 `.env` 中设置 `GIN_MODE=debug`,然后重新创建 app 容器,使环境变量生效(仅执行 `docker compose restart app` 不会更新容器环境):
|
||||
|
||||
```bash
|
||||
docker compose up -d --no-deps --force-recreate app
|
||||
docker compose exec app printenv GIN_MODE
|
||||
docker compose port app 8080
|
||||
```
|
||||
|
||||
确认第一条检查输出 `debug`,再用第二条检查显示的映射端口访问后端。例如输出 `0.0.0.0:8080` 时,本机访问 `http://localhost:8080/swagger/index.html`;从另一台机器访问时,将 `localhost` 替换为部署机器地址。排障结束后,将 `GIN_MODE` 恢复为 `release` 并重新创建 app 容器。
|
||||
|
||||
#### 打开后空白或加载失败
|
||||
|
||||
先检查请求是否到达后端(下面以默认后端端口 `8080` 为例):
|
||||
|
||||
```bash
|
||||
curl -i http://localhost:8080/swagger/index.html
|
||||
curl -i http://localhost:8080/swagger/doc.json
|
||||
```
|
||||
|
||||
正常情况下,两者返回 `200`:前者是包含 `swagger-ui` 的 HTML,后者是包含 `swagger` 和 `paths` 字段的 JSON。
|
||||
|
||||
| 现象 | 排查方向 |
|
||||
| --- | --- |
|
||||
| 状态码为 `200`,但 HTML 是普通前端页面(含 `<div id="app">`),页面空白或跳到登录页 | 请求落入了前端的 SPA 回退。改用 app 后端映射端口;登录前端不会为它增加 `/swagger/` 代理。 |
|
||||
| 后端返回 `401` 或 `404`,没有 Swagger UI | 核对访问端口以及容器内实际的 `GIN_MODE`;`release` 模式不注册 Swagger 路由,未匹配的请求可能进入认证中间件。 |
|
||||
| Swagger UI 出现,但提示无法加载 API 定义 | 单独检查同一后端的 `/swagger/doc.json` 响应;如使用自建反向代理,确保整个 `/swagger/` 路径及静态资源都被转发到 app。 |
|
||||
|
||||
### 数据库与迁移调试 {#_6-3-数据库与迁移调试}
|
||||
|
||||
- `AUTO_MIGRATE=false` 可关闭启动时自动迁移;`AUTO_RECOVER_DIRTY`(默认开启,设为 `false` 关闭)控制 dirty state 自动恢复(`internal/container/container.go`)。迁移失败只告警不阻断启动,注意看启动日志里的 `Database migration failed`。
|
||||
- `make migrate-version` 快速确认 schema 版本。
|
||||
|
||||
### LLM 链路观测(Langfuse) {#_6-4-llm-链路观测-langfuse}
|
||||
|
||||
`dev.sh start` 默认拉起自建 Langfuse(`http://localhost:3000`)。本地 `go run` 的 app 需要导出:
|
||||
|
||||
```bash
|
||||
export LANGFUSE_HOST=http://localhost:3000
|
||||
export LANGFUSE_PUBLIC_KEY=pk-lf-xxx
|
||||
export LANGFUSE_SECRET_KEY=sk-lf-xxx
|
||||
```
|
||||
|
||||
即可在 Langfuse UI 中查看每次会话的模型调用 trace(文档处理 span 亦落库到 `knowledge_processing_spans` 表,前端可视化)。
|
||||
|
||||
### pprof {#_6-5-pprof}
|
||||
|
||||
当前代码中**未内置** `net/http/pprof` 端点(`internal/`、`cmd/` 下无 pprof 引用)。如需性能剖析,可临时在 `cmd/server/main.go` 中 `import _ "net/http/pprof"` 并起一个独立 `http.ListenAndServe("localhost:6060", nil)`,或使用 `go test -bench . -cpuprofile` 针对具体包剖析。
|
||||
|
||||
### 分块策略诊断 {#_6-6-分块策略诊断}
|
||||
|
||||
chunker 提供 `SplitWithDiagnostics()`(`internal/infrastructure/chunker/strategy.go`),返回策略链选择、各 tier 被拒原因与文档画像,配合 `LOG_LEVEL=debug`(`chunker: tier %s rejected` 日志)可排查分块效果问题。
|
||||
|
||||
### 云镜像维护脚本 {#cloud-image-scripts}
|
||||
|
||||
`scripts/cloud-image/` 用于在专用、可丢弃的 Linux 制作机上准备分发镜像。常规部署使用[安装部署](../01-getting-started/02-installation.md),不需要运行这些脚本。
|
||||
|
||||
- `prepare.sh` 下载 `ACADEMY_REF` 对应的运行文件、拉取镜像并安装 systemd 服务。该引用还用于设置镜像版本,必须确认对应镜像标签存在。随仓库提供的 systemd 单元固定使用 `/opt/Academy`,只修改脚本的目录变量不足以迁移安装位置。
|
||||
- `cleanup.sh` 清除制镜像机的数据、密钥、SSH 授权、日志与 Docker 缓存并关机;其影响不限于 Academy 目录,只能用于检查过的专用制作机。
|
||||
- `firstboot.sh` 在新实例上生成密钥、写入 `.env` 并启动 Compose;完成后禁用首启服务,不会自删除脚本。
|
||||
|
||||
制镜像前需检查脚本与所选版本是否匹配。分发前必须用新实例验证启动、服务健康和密钥独立性;本说明不代表当前脚本已通过特定云平台的部署或上架验收。
|
||||
|
||||
首启排障查看 `journalctl -u academy-firstboot`、`/var/log/academy-firstboot.log` 与 `/opt/Academy` 下的 Compose 状态。`.firstboot.done` 在生成密钥之后、启动 Compose 之前写入,标记存在不代表服务健康。启动失败时保留已生成的 `.env` 和标记,修复原因后重新启动 Compose;删除标记重新生成密钥可能造成配置与已初始化数据库不一致。
|
||||
@@ -0,0 +1,435 @@
|
||||
# 数据库与迁移
|
||||
|
||||
Academy 使用版本化迁移维护数据库结构,PostgreSQL 与 SQLite 分别使用对应的迁移目录。应用启动时可自动执行迁移,也可通过脚本手动执行;新增字段或表时需要同步维护两条路径。
|
||||
|
||||
## 支持的数据库 {#_1-支持的数据库}
|
||||
|
||||
主应用通过 GORM 连接数据库,驱动由环境变量 `DB_DRIVER` 决定。`internal/container/container.go` 的 `initDatabase()` 中的 switch **只接受两个值**:
|
||||
|
||||
| `DB_DRIVER` | 说明 |
|
||||
| --- | --- |
|
||||
| `postgres` | 标准模式。既支持原生 PostgreSQL(+pgvector),也支持 **ParadeDB**(PostgreSQL 分支,内置 `pg_search`/BM25,官方 compose 默认镜像 `paradedb/paradedb:v0.25.11-pg17`)。GORM DSN 由 `DB_HOST/DB_PORT/DB_USER/DB_PASSWORD/DB_NAME` 拼装,强制 `sslmode=disable`、`TimeZone=UTC` |
|
||||
| `sqlite` | Lite 模式。路径取 `DB_PATH`(默认 `./data/academy.db`),DSN 附加 `_journal_mode=WAL&_busy_timeout=5000&_foreign_keys=on`,并加载 `sqlite-vec` 扩展(`sqlite_vec.Auto()`)做向量检索 |
|
||||
| 其他值 | 直接报错 `unsupported database driver` |
|
||||
|
||||
**MySQL 不是主库选项**:`go.mod` 里的 `go-sql-driver/mysql` 是给 Doris 检索引擎(MySQL 协议、`database/sql`)注册协议驱动用的(见 `container.go` import 注释)。`migrations/mysql/00-init-db.sql` 是一份仅含 10 张核心表(tenants/models/knowledge_bases/knowledges/sessions/messages/message_suggestion_sets/message_suggestion_events/chunks/chunk_revisions)的一次性 MySQL 建表脚本,**没有任何 Go 代码或脚本引用它**,未接入应用启动流程,可视为遗留/外部初始化用途。
|
||||
|
||||
检索引擎(向量/关键词索引的存储)与主库解耦,由 `RETRIEVE_DRIVER` 控制(postgres / elasticsearch / qdrant / milvus / sqlite 等,详见《扩展点指南》)。当 `RETRIEVE_DRIVER` 不含 `postgres` 时,迁移 DSN 会带上 `options=-c app.skip_embedding=true`,`embeddings` 表相关迁移通过该 GUC 条件跳过。
|
||||
|
||||
## 迁移目录结构 {#_2-迁移目录结构}
|
||||
|
||||
```text
|
||||
migrations/
|
||||
├── versioned/ # PostgreSQL/ParadeDB 版本化迁移:000000-000118 共 119 版(238 个 .up/.down.sql 文件)
|
||||
├── sqlite/ # SQLite 迁移:000000_init(压平的全量 schema)+ 000001-000036 增量版本
|
||||
├── paradedb/ # ParadeDB 附加脚本:00-init-db.sql、01-migrate-to-paradedb.sql(存量库切换)
|
||||
└── mysql/ # 00-init-db.sql,遗留的一次性 MySQL 建表脚本(未接入代码)
|
||||
```
|
||||
|
||||
- PostgreSQL 的 `versioned/` 从 `000000_init` 到 `000118_mcp_oauth_timestamp_tz`;
|
||||
- `sqlite/` 以 `000000_init` 作为压平后的全量初始化(JSONB→TEXT、SERIAL→AUTOINCREMENT 等方言差异已适配),其后追加增量版本(当前到 `000036_messages_attachment_lookup`),同样由 golang-migrate 顺序执行;
|
||||
- `uuid-ossp`、`vector`、`pg_trgm`、`pg_search` 等扩展由 `versioned/` 迁移自行创建(000000、000002);BM25 索引使用中文 Lindera 分词器建在 `embeddings.content` 上;
|
||||
- `paradedb/00-init-db.sql` 除扩展外还含一份旧版建表语句,**没有被 compose 或代码引用**。不要把它挂成数据库 initdb 脚本:它先建出的旧表会让 `000000_init` 失败。
|
||||
|
||||
### versioned/ 迁移史概览(按主题) {#_2-1-versioned-迁移史概览-按主题}
|
||||
|
||||
| 版本段 | 主题 | 引入的关键表/列 |
|
||||
| --- | --- | --- |
|
||||
| 000000 | 核心初始化 | `tenants`、`models`、`knowledge_bases`、`knowledges`、`chunks`、`sessions`、`messages` |
|
||||
| 000001 | 用户认证 + Agent + MCP | `users`、`auth_tokens`、`custom_agents`、`mcp_services`、`knowledge_tags` |
|
||||
| 000002-000011 | 向量/检索 | `embeddings`(HNSW + BM25,受 `app.skip_embedding` 门控)、`chunks.flags`、`seq_id`、ParadeDB BM25 索引 |
|
||||
| 000012-000018 | 跨租户协作 | `organizations`、`organization_members`、`kb_shares`、`agent_shares`、`organization_join_requests` |
|
||||
| 000019-000028 | 消息/IM 增强 | `messages` 扩列(images、rendered_content、agent_duration_ms)、`im_channels`、`im_channel_sessions` |
|
||||
| 000029-000036 | 数据源与向量库抽象 | `data_sources`、`sync_logs`、`web_search_providers`、`vector_stores`、KB 的 asr_config/vector_store_id |
|
||||
| 000037-000041 | Wiki 与任务队列 | `wiki_pages`、`wiki_folders`、`wiki_page_issues`、`wiki_log_entries`(已于 000077 移除)、`task_pending_ops`、`task_dead_letters` |
|
||||
| 000042-000054 | RBAC / 审计 / 邀请 / 系统设置 | `mcp_tool_approvals`、`tenant_members`、`audit_logs`、`organization_tenant_members`(原 `organization_members` 改名归档)、`user_resource_favorites`、`tenant_invitations`、`user_kb_pins`、`system_settings` 与 `users.is_system_admin`(000053)、邀请链接列 `tenant_invitations.token`/`accepted_count`(000054) |
|
||||
| 000055-000060 | 处理管道与嵌入渠道 | `knowledge_processing_spans`、`knowledges.pending_subtasks_count`(000056,`finalizing` 状态计数)、`embed_channels`、HNSW 1024 维索引 |
|
||||
| 000061-000067 | Wiki 层级 / OAuth / 文档多标签 / 主体身份 / 建议问题 | `wiki_pages` 层级列、`mcp_oauth_clients`、`mcp_oauth_tokens`、`knowledge_tag_relations`、主体身份列(000064:`tenants.api_principal_config`、`mcp_oauth_tokens.principal_type`/`principal_id`)、`tenant_api_keys`(000065,同时移除 `tenants.api_key`)、`message_suggestion_sets`、`message_suggestion_events` |
|
||||
| 000068-000074 | 存储/资源/临时文档 | `storage_backends`、`resources`、`resource_bindings`、`resource_access_grants`、`temporary_documents`、平台级 API key、OAuth 刷新租期 |
|
||||
| 000075-000076 | Wiki 版本历史与索引 | `wiki_page_revisions`、`wiki_pages.last_edit_source`/`last_editor_id`、`knowledges.metadata->>'external_id'` 前缀索引 |
|
||||
| 000077 | 移除 Wiki 操作日志 | DROP `wiki_log_entries`,并删除历史遗留的 `page_type = 'log'` 页面;Wiki 变更统一记入知识库活动流 |
|
||||
| 000078 | 分块编辑与自定义元数据 | `chunks` 增加 `source_content`/`content_revision`/`index_status`/`last_editor_id`/`context_header`,新增 `chunk_revisions` 表,`knowledges` 增加 `custom_metadata` |
|
||||
| 000079 | 知识库文件夹树 | `knowledges` 增加 `folder_path` 列并回填历史目录上传(原先路径塞在 `file_name` 里),新增 `(tenant_id, knowledge_base_id, folder_path)` 索引 |
|
||||
|
||||
### 000080 之后的迁移 {#_2-2-000080-之后的迁移}
|
||||
|
||||
| 版本 | 变更 |
|
||||
| --- | --- |
|
||||
| 000080 | knowledge_bases.auto_tag_config |
|
||||
| 000081 | messages.artifacts,持久化生成文件(000103 起改存 `message_artifacts` 表) |
|
||||
| 000082 | tenant_sandbox_configs,多命名后端与配置变更租期 |
|
||||
| 000083 | sessions.sandbox_config_id |
|
||||
| 000084 | 个人记忆六张表、tenants.memory_config、messages.used_memories |
|
||||
| 000085 | messages.usage |
|
||||
| 000086 | tenant_skills、tenant_skill_snapshots,安装与快照账本 |
|
||||
| 000087 | 技能 install_session_id / install_message_id,安装对话日志 |
|
||||
| 000088 | 快照 planned_name,创建前记录计划名称 |
|
||||
| 000089 | 技能 envs、tenant_user_env_vars |
|
||||
| 000090 | tenant_skill_catalog;tenant_skills.catalog_id,回填已有安装 |
|
||||
| 000091 | mcp_tool_approvals.enabled,默认 true |
|
||||
| 000092 | mcp_services.usage_instructions;`mcp_metadata` 表,持久化 MCP 服务的工具目录快照 |
|
||||
| 000093 | `browser_devices`、`browser_pairings`、`browser_task_interruptions`,浏览器连接的设备授权与配对 |
|
||||
| 000094 | memory_subjects.extraction_state、memory_items.replaces_id、`memory_extraction_sessions` 表(按会话记录抽取进度);修复旧版本中待确认推断过早替换已生效记忆的数据 |
|
||||
| 000095 | memory_item_embeddings.embedding(halfvec,仅在已安装 `vector` 扩展时添加)与检索索引 |
|
||||
| 000096 | 数据迁移:钉钉渠道 `mode` 从 webhook 改为 websocket(Stream)。需在钉钉开发者后台开启 Stream 模式;down 为空操作 |
|
||||
| 000097 | 会话分叉:sessions.parent_session_id / forked_from_message_id / fork_bootstrap,messages.sandbox_checkpoint |
|
||||
| 000098 | `fork_snapshot_leases` 表,记录分叉会话落库前拍下的沙箱快照,便于回收 |
|
||||
| 000099 | 将已安装的 pg_search 0.22.2–0.22.5 升级到 0.22.6;镜像未提供 0.22.6、其他版本或 `app.skip_embedding=true` 时跳过 |
|
||||
| 000100 | 删除 chunks 上只拖慢写入的三个索引:`idx_chunks_chunk_type`、`idx_chunks_content_hash`、`idx_chunks_tenant_kg` |
|
||||
| 000101 | knowledges.profile(文档画像),knowledge_bases.profile_config / generated_profile(AI 知识库描述) |
|
||||
| 000102 | `mcp_endpoints` 表,空间对外发布的 MCP 端点 |
|
||||
| 000103 | `message_artifacts` 表,从 `messages.artifacts` 回填;此后只读写新表。回填后旧列中有内容的行置为 NULL(列保留,兼容滚动升级中的旧实例);无法解析的 `file_size`/`created_at` 回退为 0 和消息创建时间,不中断迁移。down 迁移会把新表写回旧列 |
|
||||
| 000104 | tenant_skills.served,新版本安装中或失败时记录仍在镜像中提供的版本 |
|
||||
| 000105 | messages.context_checkpoint,Agent 上下文压缩摘要 |
|
||||
| 000106 | messages `(session_id, created_at DESC, id DESC)` 索引 `idx_messages_session_created_id`,以 `CREATE INDEX CONCURRENTLY` 创建,不阻塞写入;构建中断会留下 INVALID 索引,需先 `DROP INDEX` 再重跑迁移 |
|
||||
| 000107 | message_artifacts.deleted_at,用户删除的文件保留为墓碑行 |
|
||||
| 000108 | sessions.sandbox_config_tenant_id(BIGINT,默认 0),记录会话所用沙箱配置属于哪个空间;按沙箱配置回填使用共享 Agent 的会话 |
|
||||
| 000109 | sessions.host_workspace_dir(VARCHAR(1024)),Lite 桌面版主机沙箱的项目目录,创建后不再修改 |
|
||||
| 000110 | im_channels.locale(VARCHAR(16),默认空串),IM 渠道固定回复语言,空串使用部署默认值 |
|
||||
| 000111 | `model_catalog_configs`,管理员目录覆盖与最近版本历史 |
|
||||
| 000112 | embeddings 的 knowledge_id、chunk_id 索引;普通建索引,大表升级前可先同名 CONCURRENTLY 建立以降低阻塞 |
|
||||
| 000113 | `chunk_images` 图片投影表与同步触发器,从已有 image_info 回填画廊数据 |
|
||||
| 000114 | chunks.source_locators,原文引用定位信息 |
|
||||
| 000115 | 将适用版本的 pg_search / vector 扩展升级到 0.25.11 / 0.8.4,需先切换配套数据库镜像 |
|
||||
| 000116 | 将历史智能推理 Agent 的空 allowed_tools 数组写为显式默认工具列表 |
|
||||
| 000117 | messages.attachments 的有效用户消息 GIN 索引,用于附件引用保留查询 |
|
||||
| 000118 | MCP OAuth token/client 时间戳改为 timestamptz,旧字面值按 UTC 转换 |
|
||||
|
||||
SQLite 版本号独立演进,不能与 PostgreSQL 数字一一对应:
|
||||
|
||||
| SQLite 版本 | 变更 |
|
||||
| --- | --- |
|
||||
| 000001–000002 | 移除 Wiki 日志、文件夹路径 |
|
||||
| 000003–000004 | 自动标签、长期记忆 |
|
||||
| 000005 | 消息附件与邀请字段 |
|
||||
| 000006–000008 | 任务/死信、系统管理与设置、处理 spans/待处理子任务计数 |
|
||||
| 000009 | 历史 Embed memory 标志列;当前渠道接口不暴露此字段 |
|
||||
| 000010–000011 | 多标签关联、principal 模型 |
|
||||
| 000012–000013 | 消息 usage、MCP 工具 enabled(对应 000085、000091) |
|
||||
| 000014–000016 | 浏览器授权、记忆一致性、记忆向量检索索引(对应 000093–000095;SQLite 无向量列,仍在应用内排序) |
|
||||
| 000017 | 钉钉渠道改为 websocket(对应 000096) |
|
||||
| 000018–000019 | 会话分叉、分叉快照租约(对应 000097–000098) |
|
||||
| 000020–000022 | chunks 删冗余索引、知识画像、MCP 端点(对应 000100–000102) |
|
||||
| 000023 | `message_artifacts` 表,回填并清空旧列(对应 000103) |
|
||||
| 000024–000026 | messages.context_checkpoint、messages 会话时间索引、message_artifacts.deleted_at(对应 000105–000107) |
|
||||
| 000027 | sessions.sandbox_config_tenant_id(对应 000108;Lite 无共享空间,不回填) |
|
||||
| 000028 | 补建 `tenant_skills`、`tenant_skill_snapshots`、`tenant_skill_catalog`、`tenant_user_env_vars`(对应 000086–000090 与 000104)。此前 Lite 缺这四张表,技能读取凭据时报 `no such table` |
|
||||
| 000029–000030 | sessions.host_workspace_dir、im_channels.locale(对应 000109–000110) |
|
||||
| 000031 | `model_catalog_configs`(对应 000111) |
|
||||
| 000032–000033 | `chunk_images` 与 source_locators(对应 000113–000114) |
|
||||
| 000034 | 补齐 MCP usage_instructions 与 mcp_metadata(对应 000092) |
|
||||
| 000035 | Agent 显式默认工具(对应 000116) |
|
||||
| 000036 | 有效用户消息附件查询索引(对应 000117,SQLite 使用普通索引) |
|
||||
|
||||
PostgreSQL 的 000099、000112、000115、000118 没有 SQLite 对应版本。
|
||||
|
||||
基线 schema 与后续增量共同决定新建库和已有库的最终结果;不能只看新增迁移文件名判断 Lite 是否有某张表。
|
||||
|
||||
## 最终表结构 {#_3-最终表结构}
|
||||
|
||||
以下为全部 up 迁移叠加后的**最终生效结构**(后续迁移对早期表的 ALTER 已合并)。多数业务表带 `created_at` / `updated_at`,不少带 `deleted_at`(GORM 软删除),不再逐一列出。
|
||||
|
||||
### 租户与用户 {#_3-1-租户与用户}
|
||||
|
||||
| 表 | 用途 | 关键字段 |
|
||||
| --- | --- | --- |
|
||||
| `tenants` | 租户(工作空间),多租户体系根 | `id`(SERIAL,起始 10000)、`name`、`retriever_engines`(JSONB)、`status`、`storage_quota`/`storage_used`、`agent_config`/`context_config`/`conversation_config`/`web_search_config`/`credentials`/`api_principal_config`/`memory_config`(JSONB)、`default_storage_backend_id`。原 `api_key` 列已在 000065 迁入 `tenant_api_keys` 并删除 |
|
||||
| `users` | 登录用户 | `id`(UUID)、`username`(唯一)、`email`(唯一)、`password_hash`、`tenant_id`(FK→tenants,ON DELETE SET NULL)、`is_active`、`can_access_all_tenants`(跨空间访问)、`is_system_admin`(系统管理员,000053)、`preferences`(JSON) |
|
||||
| `auth_tokens` | 登录令牌 | `id`、`user_id`(FK→users,CASCADE)、`token`、`token_type`(access/refresh)、`expires_at`(TIMESTAMPTZ,000072 起)、`is_revoked` |
|
||||
| `tenant_members` | 租户级 RBAC 成员关系 | `user_id`+`tenant_id`(软删除下唯一)、`role`(owner/admin/contributor/viewer)、`status`、`invited_by`、`joined_at` |
|
||||
| `tenant_invitations` | 站内邀请与邀请链接 | `tenant_id`、`invitee_user_id`、`role`、`status`(pending/accepted/rejected)、`expires_at`;pending 唯一约束;`token`(邀请链接,唯一)/`accepted_count`(000054) |
|
||||
| `tenant_api_keys` | 租户/平台 API Key | `tenant_id`(platform 作用域时为 NULL)、`scope_type`(tenant/platform,CHECK 约束)、`key_hash`(唯一)、`full_access`、`knowledge_base_ids`、`capabilities`、`expires_at`/`revoked_at` |
|
||||
| `user_kb_pins` | 用户级知识库置顶 | PK(`tenant_id`,`user_id`,`kb_id`)+ `pinned_at` |
|
||||
| `user_resource_favorites` | 用户收藏 | PK(`user_id`,`tenant_id`,`resource_type`,`resource_id`) |
|
||||
| `system_settings` | 系统级设置(000053) | `key`、`value`/`value_type`、`category`、`is_secret`、`requires_restart`、`last_modified_by` |
|
||||
| `audit_logs` | 审计日志(000044) | `tenant_id`、`actor_user_id`/`actor_role`、`action`、`target_type`/`target_id`/`target_user_id`、`request_path`/`request_method`、`outcome`(success/denied)、`scope_type`/`scope_id`、`details`(JSONB) |
|
||||
|
||||
v0.8.3 新增的 `model_catalog_configs` 保存部署级管理员覆盖(单行 id=1)、版本与历史;`chunk_images` 是 `chunks.image_info` 的可查询投影,触发器保持其与分块写入、删除和状态变化一致。附件保留由有效会话消息引用决定,`expires_at` 只清理已经不被引用的过期附件。
|
||||
|
||||
### 模型与知识库 {#_3-2-模型与知识库}
|
||||
|
||||
| 表 | 用途 | 关键字段 |
|
||||
| --- | --- | --- |
|
||||
| `models` | AI 模型配置(LLM/embedding/rerank 等) | `id`、`tenant_id`(FK→tenants,CASCADE)、`name`/`display_name`、`type`(`KnowledgeQA` / `Embedding` / `Rerank` / `VLLM` / `ASR`)、`source`、`parameters`(JSONB;v0.8.2 起可含可选的 `spec` 覆盖协议与能力,无需迁移)、`is_default`、`is_builtin`、`managed_by`、`status` |
|
||||
| `knowledge_bases` | 知识库 | `id`(UUID)、`tenant_id`、`name`、`type`(document/faq/wiki)、`chunking_config`/`image_processing_config`/`vlm_config`/`faq_config`/`asr_config`/`wiki_config`/`indexing_strategy`/`auto_tag_config`/`profile_config`/`generated_profile`(JSONB)、`embedding_model_id`/`summary_model_id`(FK→models)、`vector_store_id`(FK→vector_stores)、`storage_backend_id`(FK→storage_backends)、`creator_id`(FK→users)、`is_temporary`、`activity_scope` |
|
||||
| `knowledges` | 知识条目(文档/网页/FAQ 等) | `id`、`tenant_id`、`knowledge_base_id`(FK)、`type`、`title`、`source`(VARCHAR(2048))、`parse_status`(pending/processing/finalizing/completed/failed/cancelled/deleting)、`pending_subtasks_count`(000056,`finalizing` 阶段未完成的增强子任务数)、`enable_status`、`file_name`/`file_type`/`file_size`/`file_path`/`file_hash`、`metadata`(内部入库状态)、`custom_metadata`(JSONB,用户自填元数据,000078)、`folder_path`(目录树路径,000079)、`summary_status`、`profile`(JSONB,文档画像:gist/主题/类型/典型问题,000101)、`channel`、`processed_at`/`error_message`。**没有 `tag_id` 列**——000063 起标签走 `knowledge_tag_relations` 关联表 |
|
||||
| `chunks` | 分块(检索最小单元) | `id`、`tenant_id`、`knowledge_base_id`、`knowledge_id`(FK)、`content`、`source_content`(解析器原始输出,不可变)、`content_revision`、`index_status`(ready/processing/failed)、`last_editor_id`、`context_header`(索引用标题面包屑)、`chunk_index`、`start_at`/`end_at`、`pre_chunk_id`/`next_chunk_id`(链表)、`parent_chunk_id`(父子分块自引用)、`chunk_type`(text/image/…)、`image_info`/`video_info`、`relation_chunks`/`indirect_relation_chunks`(JSONB)、`source_locators`(JSONB,分块在原始文件中的位置,000114)、`is_enabled`、`flags`、`status`、`content_hash`、`seq_id`、`tag_id` |
|
||||
| `chunk_revisions` | 分块历史版本(000078) | `id`、`tenant_id`、`knowledge_base_id`、`knowledge_id`、`chunk_id`+`revision`(唯一索引)、`content`、`is_enabled`、`editor_id`、`edit_source`、`edited_at` |
|
||||
| `embeddings` | 向量 + BM25 索引(Postgres/ParadeDB 检索引擎专用,受 `app.skip_embedding` 门控) | `id`、`source_id`+`source_type`(唯一,chunk/wiki 页等来源)、`chunk_id`/`knowledge_id`/`knowledge_base_id`、`content`(BM25 全文)、`dimension`、`embedding`(halfvec,HNSW 索引按 768/1024/3584 维分建)、`is_enabled`、`tag_id` |
|
||||
| `knowledge_tags` | 知识标签(FAQ 分类等) | `id`、`tenant_id`、`knowledge_base_id`、`name`、`seq_id` |
|
||||
| `knowledge_tag_relations` | 文档 ↔ 标签多对多(000063) | 复合主键(`knowledge_id`,`tag_id`)+ `created_at`;两侧各建索引。**同时删掉了 `knowledges.tag_id` 列**(存量单标签数据已迁入本表)。FAQ 条目的标签不在这里,仍是 `chunks.tag_id` 单标签 |
|
||||
| `vector_stores` | 外接向量库连接配置(000032) | `id`、`tenant_id`、`name`(租户内唯一)、`engine_type`、`connection_config`/`index_config`(JSONB) |
|
||||
|
||||
### 会话与消息 {#_3-3-会话与消息}
|
||||
|
||||
| 表 | 用途 | 关键字段 |
|
||||
| --- | --- | --- |
|
||||
| `sessions` | 会话(对话上下文与检索参数快照) | `id`、`tenant_id`、`title`、`knowledge_base_id`、`agent_id`(FK→custom_agents)、`user_id`、`max_rounds`、`enable_rewrite`、`fallback_strategy`/`fallback_response`、`keyword_threshold`/`vector_threshold`、`embedding_top_k`/`rerank_top_k`/`rerank_threshold`、`rerank_model_id`/`summary_model_id`、`agent_config`/`context_config`(JSONB)、`sandbox_config_id`/`sandbox_config_tenant_id`(沙箱配置及其所属空间,0 表示会话自身空间,000108)、`parent_session_id`/`forked_from_message_id`/`fork_bootstrap`(会话分叉,000097;不设外键)、`host_workspace_dir`(Lite 桌面版项目目录,000109) |
|
||||
| `messages` | 消息 | `id`、`request_id`、`session_id`(FK)、`role`、`content`/`rendered_content`、`knowledge_references`(JSONB 引用)、`agent_steps`(JSONB,Agent 推理轨迹)、`mentioned_items`/`images`(JSONB)、`is_completed`/`is_fallback`、`channel`(web/IM 渠道)、`agent_id`+`agent_tenant_id`、`model_id`、`knowledge_id`、`agent_duration_ms`、`execution_context`、`attachments`、`used_memories`/`usage`(JSONB)、`sandbox_checkpoint`(分叉点的沙箱检查点,000097)、`context_checkpoint`(Agent 上下文压缩摘要,000105)。`artifacts` 列自 000103 起不再读写且已清空(仅为回滚与滚动升级保留),生成文件见 `message_artifacts` |
|
||||
| `message_artifacts` | 技能生成的文件,一行一个(000103) | `session_id`、`message_id`、`position`(消息内序号,即下载接口的 index;与 `message_id` 唯一)、`url`(存储或 resource:// 引用,不返回客户端)、`file_name`/`file_type`/`file_size`、`content_hash`、`source_path`(同会话同路径视为同一文件的多个版本)、`mod_time`(RFC 3339 文本,保留纳秒精度供采集器比对)、`created_at`、`deleted_at`(000107,用户删除文件后保留墓碑行,保持 `position` 稳定且不被重新采集)。消息被软删除时其文件一并隐藏 |
|
||||
| `message_suggestion_sets` | 建议问题集(000067) | `tenant_id`、`session_id`、`assistant_message_id`、`placement`(starter/follow_up)、`config_hash`+`locale`(缓存键,唯一)、`status`、`questions`(JSONB)、token/延迟统计、`lease_until` |
|
||||
| `message_suggestion_events` | 建议问题曝光/点击事件 | `suggestion_set_id`(FK,CASCADE)、`question_id`、`event_type`、`actor_id` |
|
||||
| `temporary_documents` | 会话内临时文档(000070) | `tenant_id`、`session_id`、`resource_ref`、`file_name`/`file_type`/`file_size`、`status`(uploaded/processing/ready/failed)、`content`、`chunks`(JSONB)、`expires_at` |
|
||||
|
||||
### Agent 与 MCP {#_3-4-agent-与-mcp}
|
||||
|
||||
| 表 | 用途 | 关键字段 |
|
||||
| --- | --- | --- |
|
||||
| `custom_agents` | 自定义 Agent | **复合主键 (`id`,`tenant_id`)**、`name`、`is_builtin`、`created_by`(FK→users)、`runnable_by_viewer`、`config`(JSONB:模式/模型/工具/知识范围) |
|
||||
| `mcp_services` | MCP 服务配置 | `id`、`tenant_id`、`name`、`enabled`、`transport_type`(stdio/sse/…)、`url`/`headers`/`auth_config`/`advanced_config`/`stdio_config`/`env_vars`(JSONB)、`is_builtin`、`usage_instructions`(本地维护的使用说明,000092) |
|
||||
| `mcp_metadata` | MCP 工具目录快照(000092) | PK(`tenant_id`,`service_id`,`principal`),静态认证时 `principal` 为空串、OAuth 服务按用户主体分行;`config_fingerprint`、`tools`(JSONB)、`instructions`、`server_name`/`server_version`/`server_description`、`synced_at`;随服务删除级联 |
|
||||
| `mcp_endpoints` | 空间对外发布的 MCP 端点(000102) | `tenant_id`、`name`/`description`、`enabled`、`token_hash`(Bearer token 的 SHA-256,未删除行唯一,明文只显示一次)/`token_hint`、`knowledge_base_ids`(JSONB,空数组表示全部知识库)、`tools`(JSONB 白名单)、`default_agent_id`、`rate_limit_per_minute`(默认 60)、`last_used_at` |
|
||||
| `mcp_tool_approvals` | MCP 工具审批策略(000042) | (`tenant_id`,`service_id`,`tool_name`) 唯一、`require_approval`、`enabled`(默认 true) |
|
||||
| `mcp_oauth_clients` | MCP OAuth 客户端(000062) | (`tenant_id`,`service_id`) 唯一、`client_id`/`client_secret`/`redirect_uri` |
|
||||
| `mcp_oauth_tokens` | MCP OAuth 令牌 | (`tenant_id`,`principal_type`,`principal_id`,`service_id`) 唯一(000064 起按主体,原按 `user_id`)、`access_token`/`refresh_token`、`expires_at`、`refresh_lease_id`/`refresh_lease_until`(000074,防并发刷新) |
|
||||
|
||||
### 浏览器连接
|
||||
|
||||
| 表 | 用途与关键字段 |
|
||||
| --- | --- |
|
||||
| `browser_devices` | 已授权的浏览器扩展设备(000093),每个空间内每个用户一台;label、token_hash/previous_hash(只存 SHA-256,令牌轮换有宽限期)、expires_at/renew_after、last_seen_at、revoked_at、在线租约 owner/lease_until |
|
||||
| `browser_pairings` | 一次性配对令牌哈希与过期时间 |
|
||||
| `browser_task_interruptions` | 需要用户显式恢复的中断任务(scope_key + session) |
|
||||
|
||||
### 沙箱与技能
|
||||
|
||||
| 表 | 用途与关键字段 |
|
||||
| --- | --- |
|
||||
| `tenant_sandbox_configs` | id、tenant_id、name、sandbox_type、config(JSONB)、cordoned_at;未删除配置在空间内名称唯一 |
|
||||
| `tenant_skill_catalog` | 空间技能定义;name/version/description/instructions、bundle_ref/bundle_sha256,空间内名称唯一 |
|
||||
| `tenant_skills` | catalog_id 与 sandbox_config_id 对应一次安装;enabled/status/error、installed_snapshot_id、installing_since、install_session_id/install_message_id、envs、served(新版本安装中或失败时仍在提供的版本,000104) |
|
||||
| `tenant_skill_snapshots` | sandbox_config_id、skill_id、snapshot_id/parent_snapshot_id、generation、trigger/state、planned_name、superseded_at |
|
||||
| `tenant_user_env_vars` | tenant_id、principal_type/principal_id、sandbox_config_id、skill_id、name、加密 value;空 skill_id 表示配置级变量 |
|
||||
| `fork_snapshot_leases` | snapshot_id(PK)、tenant_id、sandbox_config_id、created_at;会话分叉时先记下沙箱快照,分叉失败或进程中断后由后台回收(000098) |
|
||||
|
||||
目录定义与安装分开;禁用技能只改变可见性。个人变量使用完整 principal 身份,不能按 IM 共享的合成 user_id 合并。空间变量与个人值加密存储,响应不回传个人值明文。
|
||||
|
||||
### 长期记忆
|
||||
|
||||
| 表 | 用途与关键字段 |
|
||||
| --- | --- |
|
||||
| `memory_subjects` | (tenant_id,subject_id) 唯一;个人 enabled、常驻 block_text、item_count、extract_cursor/pending_sessions/extract_scheduled_at、extraction_state(000094)、整理时间 |
|
||||
| `memory_extraction_sessions` | PK(tenant_id,subject_id,session_id);按会话记录抽取游标、pending 标记与失败区间(000094) |
|
||||
| `memory_items` | kind/content/topic/normalized_key、importance/origin/status、来源会话/消息、valid_from/invalid_at/expires_at、superseded_by、replaces_id(待确认条目要替换的旧条目,000094) |
|
||||
| `memory_tombstones` | 删除/拒绝的主题与内容指纹,用于抑制重复抽取,不保存原正文 |
|
||||
| `memory_topic_stats` | topic/aliases、hits、last_seen_at/promoted_at |
|
||||
| `memory_doc_affinity` | knowledge_id/knowledge_base_id/title、hits/last_used_at |
|
||||
| `memory_item_embeddings` | item_id、model_id、dims、vector;PostgreSQL 装有 `vector` 扩展时另有 embedding(halfvec,000095)供库内检索,SQLite 在应用内排序;与条目分表存储 |
|
||||
|
||||
subject_id 使用 Principal.StorageID(),与 tenant_id 共同隔离身份。向量记录不放进条目列表,也不改变原知识库的访问权。
|
||||
|
||||
### 跨租户协作(组织) {#_3-5-跨租户协作-组织}
|
||||
|
||||
| 表 | 用途 | 关键字段 |
|
||||
| --- | --- | --- |
|
||||
| `organizations` | 组织(跨租户协作单元,000012) | `id`、`name`、`owner_id`(FK→users)、`owner_tenant_id`、`invite_code`(唯一)+ 过期控制、`require_approval`、`searchable`、`member_limit` |
|
||||
| `organization_members_pre_plan3` | 旧版组织用户成员表(000045 由 `organization_members` 改名归档,仅供回滚) | `organization_id`、`user_id`、`tenant_id`、`role`;成员关系已改由 `organization_tenant_members` 维护 |
|
||||
| `organization_tenant_members` | 组织的租户成员(000045) | (`organization_id`,`tenant_id`) 唯一、`role`(admin/editor/viewer)、`representative_user_id` |
|
||||
| `organization_join_requests` | 加入/升级申请 | `organization_id`、`user_id`、`status`(pending 唯一)、`requested_role`、`request_type`(join/upgrade)、审批字段 |
|
||||
| `kb_shares` | 知识库共享到组织 | (`knowledge_base_id`,`organization_id`) 软删除下唯一、`source_tenant_id`、`permission` |
|
||||
| `agent_shares` | Agent 共享到组织 | FK (`agent_id`,`source_tenant_id`)→custom_agents 复合主键、`organization_id`、`permission` |
|
||||
| `tenant_disabled_shared_agents` | 租户禁用某共享 Agent | PK(`tenant_id`,`agent_id`,`source_tenant_id`) |
|
||||
|
||||
### Wiki {#_3-6-wiki}
|
||||
|
||||
| 表 | 用途 | 关键字段 |
|
||||
| --- | --- | --- |
|
||||
| `wiki_pages` | AI 生成的 Wiki 页面(000037) | `id`、`tenant_id`、`knowledge_base_id`、`slug`(KB 内唯一)、`title`、`page_type`(summary/index/…)、`status`、`content`/`summary`、层级列(000061:`parent_slug`、`folder_id`、`category_path`、`wiki_path`、`depth`、`sort_order`)、`source_refs`/`chunk_refs`/`in_links`/`out_links`(JSONB)、`version`;全文 GIN/tsvector + trigram 索引 |
|
||||
| `wiki_folders` | Wiki 文件夹树 | `knowledge_base_id`、`parent_id`(邻接表)、`name`(同父下唯一)、`path`(物化路径)、`depth`、`sort_order` |
|
||||
| `wiki_page_issues` | 页面问题上报 | `knowledge_base_id`、`slug`、`issue_type`、`description`、`suspected_knowledge_ids`、`status`、`reported_by` |
|
||||
| `wiki_page_revisions` | Wiki 页面历史版本(000075) | `page_id`+`version`(唯一索引)、标题/正文/摘要/类型/状态/别名快照、`edit_source`(pipeline/agent/user/revert)、`editor_id`、`edited_at`;两级保留上限:软 50 版(只裁 pipeline 与空来源)/ 硬 200 版 |
|
||||
|
||||
### 数据源 / 渠道 / 搜索 {#_3-7-数据源-渠道-搜索}
|
||||
|
||||
| 表 | 用途 | 关键字段 |
|
||||
| --- | --- | --- |
|
||||
| `data_sources` | 外部数据源连接(飞书/Lark 知识库与云盘、Notion、Confluence、语雀、钉钉、IMA、RSS、GitLab,000029) | `id`、`tenant_id`、`knowledge_base_id`、`type`、`config`(JSONB 凭证)、`sync_schedule`(cron)、`sync_mode`(incremental/full)、`conflict_strategy`、`sync_deletions`、`last_sync_at`/`last_sync_cursor`/`last_sync_result` |
|
||||
| `sync_logs` | 每次同步的执行记录 | `data_source_id`(FK,CASCADE)、`status`、`started_at`/`finished_at`、`items_total/created/updated/deleted/skipped/failed`、`error_message` |
|
||||
| `im_channels` | IM 渠道接入配置(企业微信/飞书/Slack 等) | `tenant_id`、`platform`、`agent_id`、`knowledge_base_id`、`mode`(websocket/webhook;钉钉自 000096 起只用 websocket)、`output_mode`、`session_mode`、`bot_identity`、`credentials`、`locale`(固定回复语言,空串用部署默认值,000110) |
|
||||
| `im_channel_sessions` | IM 用户/线程 ↔ session 映射 | `im_channel_id`、`session_id`、`agent_id`、平台用户/会话标识 |
|
||||
| `embed_channels` | 网页嵌入聊天组件渠道(000060) | `tenant_id`、`agent_id`、公开 token/域名配置 |
|
||||
| `web_search_providers` | 联网搜索引擎配置(000030) | `id`、`tenant_id`、`name`、`provider`(bing/google/tavily/searxng…)、`parameters`(JSONB API key)、`is_default` |
|
||||
|
||||
### 存储 / 资源 / 任务 / 可观测 {#_3-8-存储-资源-任务-可观测}
|
||||
|
||||
| 表 | 用途 | 关键字段 |
|
||||
| --- | --- | --- |
|
||||
| `storage_backends` | 对象存储后端配置(000068) | `id`、`tenant_id`、`name`(租户内唯一)、`provider`(local/minio/cos/oss/s3/obs/tos/ks3)、`config`(JSONB)、`source`(user/system)、`legacy_alias` |
|
||||
| `resources` | 统一资源注册表(000069) | `id`、`handle`(22 位短句柄,唯一)、`tenant_id`、`storage_backend_id`、`provider`、`physical_path`、`location_hash`(租户内唯一)、`mime_type`/`original_name`/`size`/`content_hash`、`lifecycle`(persistent/temporary)+`expires_at`、`state` |
|
||||
| `resource_bindings` | 资源 ↔ 属主(消息/知识/会话)多态绑定 | (`resource_id`,`owner_type`,`owner_id`,`relation`) 唯一 |
|
||||
| `resource_access_grants` | 资源临时访问令牌 | `token_hash`(唯一)、`resource_id`、`access_scope`、`expires_at`/`revoked_at` |
|
||||
| `task_pending_ops` | 通用待处理任务队列(000041) | `tenant_id`、`task_type`、`scope`+`scope_id`、`op`、`dedup_key`、`payload`(JSONB)、`fail_count`、`enqueued_at`/`claimed_at`(并发领取) |
|
||||
| `task_dead_letters` | 失败任务死信归档 | `task_type`、`scope`/`scope_id`/`related_id`、`payload`、`last_error`、`fail_count`、`failed_at` |
|
||||
| `knowledge_processing_spans` | 文档处理管道 trace(000055) | (`knowledge_id`,`attempt`,`span_id`) 唯一、`parent_span_id`、`name`(DocReader/Chunking/Embedding…)、`kind`、`status`、`input`/`output`/`metadata`(JSONB)、`error_code`/`error_message`、`duration_ms` |
|
||||
| `schema_migrations` | golang-migrate 状态表(自动维护) | `version`、`dirty` |
|
||||
|
||||
## ER 图(核心表) {#_4-er-图-核心表}
|
||||
|
||||
```mermaid
|
||||
erDiagram
|
||||
tenants ||--o{ users : "tenant_id (SET NULL)"
|
||||
tenants ||--o{ tenant_members : "租户成员"
|
||||
users ||--o{ tenant_members : "user_id"
|
||||
users ||--o{ auth_tokens : "登录令牌"
|
||||
tenants ||--o{ models : "模型配置"
|
||||
tenants ||--o{ knowledge_bases : "知识库"
|
||||
tenants ||--o{ tenant_api_keys : "API Key"
|
||||
tenants ||--o{ audit_logs : "审计"
|
||||
users ||--o{ audit_logs : "actor_user_id"
|
||||
|
||||
knowledge_bases ||--o{ knowledges : "文档"
|
||||
knowledge_bases }o--|| models : "embedding_model_id"
|
||||
knowledge_bases }o--o| vector_stores : "vector_store_id"
|
||||
knowledge_bases }o--o| storage_backends : "storage_backend_id"
|
||||
knowledge_bases }o--o| users : "creator_id"
|
||||
knowledges ||--o{ chunks : "分块"
|
||||
chunks ||--o| chunks : "parent_chunk_id (父子分块)"
|
||||
chunks ||--o| embeddings : "source_id (向量/BM25)"
|
||||
knowledge_bases ||--o{ knowledge_tags : "标签"
|
||||
knowledge_tags ||--o{ knowledge_tag_relations : "多标签关联"
|
||||
knowledges ||--o{ knowledge_tag_relations : "knowledge_id"
|
||||
|
||||
tenants ||--o{ sessions : "会话"
|
||||
sessions ||--o{ messages : "消息"
|
||||
sessions ||--o{ sessions : "parent_session_id (分叉)"
|
||||
messages ||--o{ message_artifacts : "生成文件"
|
||||
sessions }o--o| custom_agents : "agent_id"
|
||||
sessions }o--o| knowledge_bases : "knowledge_base_id"
|
||||
messages }o--o| knowledges : "knowledge_id"
|
||||
messages ||--o{ message_suggestion_sets : "建议问题"
|
||||
message_suggestion_sets ||--o{ message_suggestion_events : "事件"
|
||||
sessions ||--o{ temporary_documents : "临时文档"
|
||||
|
||||
tenants ||--o{ custom_agents : "自定义 Agent"
|
||||
tenants ||--o{ mcp_services : "MCP 服务"
|
||||
mcp_services ||--o{ mcp_tool_approvals : "工具审批"
|
||||
mcp_services ||--o{ mcp_oauth_clients : "OAuth 客户端"
|
||||
mcp_services ||--o{ mcp_oauth_tokens : "OAuth 令牌"
|
||||
mcp_services ||--o{ mcp_metadata : "工具目录快照"
|
||||
tenants ||--o{ mcp_endpoints : "对外 MCP 端点"
|
||||
|
||||
users ||--o{ organizations : "owner_id"
|
||||
organizations ||--o{ organization_tenant_members : "租户成员"
|
||||
organizations ||--o{ kb_shares : "知识库共享"
|
||||
organizations ||--o{ agent_shares : "Agent 共享"
|
||||
organizations ||--o{ organization_join_requests : "加入申请"
|
||||
knowledge_bases ||--o{ kb_shares : "被共享"
|
||||
custom_agents ||--o{ agent_shares : "被共享 (id, tenant_id)"
|
||||
|
||||
knowledge_bases ||--o{ wiki_pages : "Wiki 页面"
|
||||
wiki_pages }o--o| wiki_folders : "folder_id"
|
||||
wiki_folders ||--o{ wiki_folders : "parent_id (树)"
|
||||
knowledge_bases ||--o{ wiki_page_issues : "问题上报"
|
||||
|
||||
knowledge_bases ||--o{ data_sources : "数据源"
|
||||
data_sources ||--o{ sync_logs : "同步日志"
|
||||
tenants ||--o{ web_search_providers : "联网搜索配置"
|
||||
tenants ||--o{ im_channels : "IM 渠道"
|
||||
im_channels ||--o{ im_channel_sessions : "渠道会话映射"
|
||||
im_channel_sessions }o--|| sessions : "session_id"
|
||||
tenants ||--o{ embed_channels : "嵌入渠道"
|
||||
|
||||
tenants ||--o{ storage_backends : "存储后端"
|
||||
tenants ||--o{ resources : "资源"
|
||||
resources }o--o| storage_backends : "storage_backend_id"
|
||||
resources ||--o{ resource_bindings : "多态绑定 (message/knowledge/session)"
|
||||
resources ||--o{ resource_access_grants : "访问授权"
|
||||
|
||||
tenants ||--o{ task_pending_ops : "任务队列"
|
||||
tenants ||--o{ task_dead_letters : "死信"
|
||||
knowledges ||--o{ knowledge_processing_spans : "处理 trace"
|
||||
```
|
||||
|
||||
## 迁移机制(golang-migrate) {#_5-迁移机制-golang-migrate}
|
||||
|
||||
迁移工具是 **golang-migrate/migrate v4**(`go.mod`:`github.com/golang-migrate/migrate/v4 v4.19.1`),状态记录在 `schema_migrations` 表(`version` + `dirty`)。有两条执行路径:
|
||||
|
||||
### 应用启动时自动迁移(默认) {#_5-1-应用启动时自动迁移-默认}
|
||||
|
||||
`internal/container/container.go` 的 `initDatabase()`:
|
||||
|
||||
- `AUTO_MIGRATE != "false"` 时(**默认开启**),调用 `database.RunMigrationsWithOptions(migrateDSN, opts)`;
|
||||
- `AUTO_RECOVER_DIRTY != "false"` 时(**默认开启**)设置 `MigrationOptions.AutoRecoverDirty = true`,遇到 dirty state 自动尝试恢复;
|
||||
- 迁移失败**只打 Warn 日志不阻断启动**(假设迁移可能由外部管理),排查问题时务必看启动日志;
|
||||
- postgres 的 migrate DSN 会拼上 `options=-c app.skip_embedding=<true|false>`(取决于 `RETRIEVE_DRIVER` 是否包含 `postgres`),控制 `embeddings` 相关迁移是否实际建表建索引。
|
||||
|
||||
`internal/database/migration.go` 中的路径选择逻辑:
|
||||
|
||||
```go
|
||||
// internal/database/migration.go
|
||||
migrationsPath := "file://migrations/versioned"
|
||||
if strings.HasPrefix(dsn, "sqlite3://") {
|
||||
migrationsPath = "file://migrations/sqlite"
|
||||
}
|
||||
```
|
||||
|
||||
即 postgres/ParadeDB 走 `migrations/versioned/`,SQLite 走 `migrations/sqlite/`。
|
||||
|
||||
### 手工执行:scripts/migrate.sh {#_5-2-手工执行-scripts-migrate-sh}
|
||||
|
||||
`scripts/migrate.sh` 是 `migrate` CLI 的包装(Makefile 的 `migrate-*` 目标调用它):
|
||||
|
||||
- 自动加载根目录 `.env`;
|
||||
- DSN 优先取 `DB_URL`(并把 `sslmode=require/prefer` 强制替换为 `disable`),否则由 `DB_HOST/DB_PORT/DB_USER/DB_PASSWORD/DB_NAME` 拼装(默认 `localhost:5432/postgres/Academy`),密码用 Python `urllib.parse.quote` URL 编码以兼容特殊字符;
|
||||
- 迁移目录默认 `MIGRATIONS_DIR=migrations/versioned`;
|
||||
- 未安装 `migrate` 时提示:`go install -tags 'postgres' github.com/golang-migrate/migrate/v4/cmd/migrate@latest`。
|
||||
|
||||
```bash
|
||||
make migrate-up # 应用全部待执行迁移
|
||||
make migrate-down # 回滚
|
||||
make migrate-version # 查看当前版本与 dirty 标志
|
||||
make migrate-create name=add_xxx # 创建下一个空闲版本的 add_xxx.up.sql / .down.sql
|
||||
make migrate-force version=74 # 强制标记版本(恢复 dirty)
|
||||
make migrate-goto version=60 # 迁移/回滚到指定版本
|
||||
```
|
||||
|
||||
## 如何新增一个迁移 {#_6-如何新增一个迁移}
|
||||
|
||||
1. **创建文件**:`make migrate-create name=add_my_feature`,在 `migrations/versioned/` 下生成下一个版本号(创建前检查目录,使用下一个空闲版本的 up/down 文件);
|
||||
2. **编写 up SQL**:注意 PostgreSQL 方言(JSONB、部分索引、`TIMESTAMP WITH TIME ZONE`);若涉及 `embeddings` 表,参考既有迁移用 `app.skip_embedding` GUC 做条件门控(`SELECT current_setting('app.skip_embedding', true)`),保证非 postgres 检索引擎部署也能通过迁移;
|
||||
3. **编写 down SQL**:必须可逆(drop column/table/index),否则回滚链会断;
|
||||
4. **同步 SQLite**:在 `migrations/sqlite/` 追加下一个空闲版本的增量迁移,镜像同一变更(注意方言转换:JSONB→TEXT、SERIAL→INTEGER AUTOINCREMENT、TIMESTAMPTZ→DATETIME 等)。已有 Lite 库不会重放 `000000_init`,只改基线会让老库缺列/缺表。同时更新 `internal/database/migration_sqlite_versioned_schema_test.go` 中的表/列清单与期望版本号;
|
||||
5. **同步 GORM 模型**:在 `internal/types/` 对应 struct 增加字段(GORM 只做 ORM 映射,生产库**不使用 AutoMigrate** 建表,schema 完全由 SQL 迁移驱动);
|
||||
6. **验证**:`make migrate-up` → `make migrate-down` → `make migrate-up` 三连确认可逆;SQLite 侧用 `DB_DRIVER=sqlite` 启动一次 Lite 版验证初始化脚本。
|
||||
|
||||
## 常见迁移问题排查 {#_7-常见迁移问题排查}
|
||||
|
||||
面向部署的诊断顺序、扩展检查与恢复边界见[数据库迁移排障](../01-getting-started/05-troubleshooting.md#database-migrations)。`force` 只修改版本标记,不撤销 SQL;先备份并核对实际 schema,不能假定失败迁移已完整回滚。
|
||||
|
||||
### dirty state(最常见) {#_7-1-dirty-state-最常见}
|
||||
|
||||
迁移中途失败/进程被杀后,`schema_migrations.dirty = true`,后续迁移拒绝执行。
|
||||
|
||||
```bash
|
||||
# 1. 确认状态
|
||||
make migrate-version # 输出形如 "74 (dirty)"
|
||||
# 或直接查表
|
||||
# SELECT version, dirty FROM schema_migrations;
|
||||
|
||||
# 2. 停止写入、备份,核对实际 schema 和失败 SQL 的执行位置
|
||||
|
||||
# 3. 仅在确认 schema 符合版本 73 且失败迁移可安全重跑后执行
|
||||
# 73 仅为示例,不能机械地用失败版本减一
|
||||
make migrate-force version=73
|
||||
make migrate-up
|
||||
```
|
||||
|
||||
应用默认 `AUTO_RECOVER_DIRTY` 开启(`container.go`),启动时会自动尝试恢复;若关闭(设为 `false`),日志会提示手工使用 force。
|
||||
|
||||
### 迁移"成功"但表没建出来 {#_7-2-迁移-成功-但表没建出来}
|
||||
|
||||
检查启动日志:自动迁移失败只是 Warn(`Database migration failed ... Continuing with application startup`),不会让进程退出。另外 `embeddings` 相关对象受 `app.skip_embedding` 门控——若 `RETRIEVE_DRIVER` 不含 `postgres`,不建 `embeddings` 索引属预期行为。
|
||||
|
||||
### 密码特殊字符导致连接失败 {#_7-3-密码特殊字符导致连接失败}
|
||||
|
||||
`migrate` CLI 要求 URL 形式 DSN,密码含 `@ # !` 等字符必须 URL 编码。`scripts/migrate.sh` 和 `container.go` 都已处理(分别用 Python `quote` 与 Go `url.QueryEscape`);自己手拼 `DB_URL` 时需自行编码。
|
||||
|
||||
### ParadeDB / 原生 Postgres 差异 {#_7-4-paradedb-原生-postgres-差异}
|
||||
|
||||
BM25 索引(`USING bm25`、Lindera 中文分词)只在 ParadeDB 可用;原生 Postgres 部署需保证相应迁移的条件分支生效或改用 Elasticsearch 等外部检索引擎。存量原生 Postgres 库切到 ParadeDB 可参考 `migrations/paradedb/01-migrate-to-paradedb.sql`。
|
||||
|
||||
官方镜像为 `paradedb/paradedb:v0.25.11-pg17`(v0.8.2 起曾为 `v0.22.6-pg17`)。迁移 000115 在服务器提供对应扩展包时,把已安装的 pg_search 0.22.0–0.25.10 升级到 0.25.11、pgvector 0.8.0–0.8.3 升级到 0.8.4;历史迁移 000099 仅在仍使用 `v0.22.6-pg17` 镜像时生效。其他版本线不会被自动升级或降级。扩展 catalog 必须与镜像版本一致,否则调用部分扩展函数会使数据库崩溃;手工升级见《ParadeDB 存量库升级》,在新镜像上不要执行 `ALTER EXTENSION pg_search UPDATE TO '0.22.6'`。
|
||||
|
||||
### 版本文件冲突 {#_7-5-版本文件冲突}
|
||||
|
||||
多个分支同时新增同一个版本号(如两个分支都生成同一数字前缀)会冲突:golang-migrate 按数字排序且版本号唯一,目录里出现重复版本时整个目录无法加载,所有部署都会迁移失败。合并时后合入者需要把自己的迁移改成下一个空闲版本号(up/down 两个文件都要改名)。`internal/database/migration_versions_test.go` 会加载 `versioned/` 与 `sqlite/` 两个目录,CI 中可发现这类冲突(000105 即因此从 000104 重编号)。
|
||||
@@ -0,0 +1,741 @@
|
||||
# 扩展点指南
|
||||
|
||||
Academy 的解析器、分块策略、检索引擎、模型厂商、搜索引擎、数据源、IM 适配器、Agent 工具和存储后端均通过接口接入。新增实现时,先实现对应接口,再在注册入口装配,并验证现有调用链。以下按扩展类型列出接口、已有实现和接入步骤。
|
||||
|
||||
## 扩展点总览 {#_0-扩展点总览}
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
subgraph DR["docreader (Python)"]
|
||||
P1["文档解析器<br/>(parser/registry.py)"]
|
||||
end
|
||||
subgraph APP["app (Go, internal/)"]
|
||||
P2["分块策略<br/>(infrastructure/chunker)"]
|
||||
P3["检索引擎<br/>(application/repository/retriever)"]
|
||||
P4["模型厂商<br/>(models/providers)"]
|
||||
P5["联网搜索引擎<br/>(infrastructure/web_search)"]
|
||||
P6["数据源连接器<br/>(datasource/connector)"]
|
||||
P7["IM 平台适配器<br/>(im/adapter.go)"]
|
||||
P8["Agent 工具<br/>(agent/tools)"]
|
||||
P9["存储后端<br/>(application/service/file)"]
|
||||
end
|
||||
DOC["原始文档"] --> P1
|
||||
P1 -->|"markdown + 图片"| P2
|
||||
P2 -->|"chunks"| P3
|
||||
P6 -->|"外部内容同步"| P1
|
||||
P7 -->|"IM 消息"| AG["Agent 引擎"]
|
||||
AG --> P8
|
||||
P8 --> P3
|
||||
P8 --> P5
|
||||
AG --> P4
|
||||
P1 -.->|"文件读写"| P9
|
||||
P2 -.-> P9
|
||||
CT["container.go<br/>(依赖注入 / 注册中枢)"] -.->|"注册"| P3
|
||||
CT -.->|"注册"| P5
|
||||
CT -.->|"注册"| P6
|
||||
CT -.->|"注册"| P7
|
||||
```
|
||||
|
||||
Go 侧绝大多数扩展点的**注册中枢**是 `internal/container/container.go`(依赖注入容器):检索引擎 `initRetrieveEngineRegistry()`、联网搜索 `registerWebSearchProviders()`、IM 适配器 `registerIMAdapterFactories()`、数据源连接器 `initConnectorRegistry()`。
|
||||
|
||||
---
|
||||
|
||||
## 新增文档解析器(docreader,Python) {#_1-新增文档解析器-docreader-python}
|
||||
|
||||
### 接口定义
|
||||
|
||||
基类在 `docreader/parser/base_parser.py`。轻量化重构后 BaseParser 只负责把文档转成 markdown 文本 + 原始图片引用(分块、图片存储、OCR、VLM caption 均在 Go 侧完成):
|
||||
|
||||
```python
|
||||
# docreader/parser/base_parser.py
|
||||
class BaseParser(ABC):
|
||||
"""Base parser interface."""
|
||||
|
||||
def __init__(self, file_name: str = "", file_type: Optional[str] = None, **kwargs):
|
||||
self.file_name = file_name
|
||||
self.file_type = file_type or os.path.splitext(file_name)[1].lstrip(".")
|
||||
|
||||
@abstractmethod
|
||||
def parse_into_text(self, content: bytes) -> Document:
|
||||
"""Parse document content into markdown text.
|
||||
|
||||
Returns:
|
||||
Document with ``content`` (markdown string) and optional
|
||||
``images`` dict mapping storage-relative paths to base64 data.
|
||||
"""
|
||||
```
|
||||
|
||||
返回值 `Document`(`docreader/models/document.py`,pydantic 模型)核心字段是 `content: str`(markdown)与 `images: Dict[str, str]`(路径 → base64)。
|
||||
|
||||
### 注册机制
|
||||
|
||||
`docreader/parser/registry.py` 的 `ParserEngineRegistry` 以"引擎名 → {文件扩展名 → Parser 类}"两级映射管理解析器;当请求的引擎不支持该文件类型时自动回落到 `builtin` 引擎。默认注册表由 `_build_default_registry()` 构建,模块级单例 `registry = _build_default_registry()`。
|
||||
|
||||
```python
|
||||
# docreader/parser/registry.py(节选)
|
||||
class ParserEngineRegistry:
|
||||
def register(self, name: str, file_types: Dict[str, Type[BaseParser]],
|
||||
description: str = "", check_available: Callable = None,
|
||||
unavailable_hint: str = ""): ...
|
||||
def get_parser_class(self, engine: str, file_type: str) -> Type[BaseParser]: ...
|
||||
```
|
||||
|
||||
### 现有实现
|
||||
|
||||
| 引擎 | Parser | 文件 |
|
||||
| --- | --- | --- |
|
||||
| `builtin` | `Docx2Parser` / `DocParser` / `PDFParser` / `MarkdownParser` / `ExcelParser` / `EPUBParser` / `HTMLParser` / `MHTMLParser` / `ImageParser`(jpg/png/gif/bmp/tiff/webp 等) | `docreader/parser/docx2_parser.py`、`doc_parser.py`、`pdf_parser.py`、`markdown_parser.py`、`excel_parser.py`、`epub_parser.py`、`html_parser.py`、`mhtml_parser.py`、`image_parser.py` |
|
||||
| `markitdown` | `MarkitdownParser`(微软 MarkItDown,多格式) | `docreader/parser/markitdown_parser.py` |
|
||||
| `opendataloader` | `OpenDataLoaderParser`(PDF 版面分析,需 Java 11+,带 `check_available` 探测) | `docreader/parser/opendataloader_parser.py` |
|
||||
|
||||
### 新增步骤
|
||||
|
||||
1. 在 `docreader/parser/` 新建 `my_parser.py`,继承 `BaseParser`,实现 `parse_into_text(content: bytes) -> Document`;
|
||||
2. **注册点:`docreader/parser/registry.py`** — 在 `_build_default_registry()` 中追加:
|
||||
|
||||
```python
|
||||
reg.register(
|
||||
"my_engine",
|
||||
{"myext": MyParser},
|
||||
description="我的解析引擎",
|
||||
check_available=lambda overrides: (True, ""), # 可选:依赖可用性探测
|
||||
unavailable_hint="缺依赖时给用户的提示", # 可选
|
||||
)
|
||||
```
|
||||
|
||||
3. 若是给已有扩展名换实现,也可只往 `builtin` 的映射里加一行 `"ext": MyParser`;
|
||||
4. 在 `docreader/tests/` 增加 unittest(参考 `test_parser_routing.py`),`uv run python -m unittest` 验证。
|
||||
|
||||
---
|
||||
|
||||
## 新增分块策略(internal/infrastructure/chunker) {#_2-新增分块策略-internal-infrastructure-chunker}
|
||||
|
||||
### 接口定义
|
||||
|
||||
分块没有 interface,而是**策略分层(tier)+ 包级函数变量覆盖**的模式。公共入口在 `internal/infrastructure/chunker/strategy.go`:
|
||||
|
||||
```go
|
||||
// internal/infrastructure/chunker/strategy.go
|
||||
// Strategy values for SplitterConfig.Strategy.
|
||||
const (
|
||||
StrategyAuto = "auto"
|
||||
StrategyHeading = "heading"
|
||||
StrategyHeuristic = "heuristic"
|
||||
StrategyRecursive = "recursive"
|
||||
StrategyLegacy = "legacy"
|
||||
)
|
||||
|
||||
func Split(text string, cfg SplitterConfig) []Chunk
|
||||
func SplitWithDiagnostics(text string, cfg SplitterConfig) ([]Chunk, *Diagnostics)
|
||||
func SplitParentChild(text string, parentCfg, childCfg SplitterConfig) ParentChildResult
|
||||
```
|
||||
|
||||
配置与结果类型在 `internal/infrastructure/chunker/splitter.go`:
|
||||
|
||||
```go
|
||||
// internal/infrastructure/chunker/splitter.go
|
||||
type Chunk struct {
|
||||
Content string
|
||||
ContextHeader string
|
||||
Seq int
|
||||
Start int
|
||||
End int
|
||||
}
|
||||
|
||||
type SplitterConfig struct {
|
||||
ChunkSize int
|
||||
ChunkOverlap int
|
||||
Separators []string
|
||||
Strategy string // 空 = legacy(向后兼容)
|
||||
TokenLimit int // 以近似 token 数限制块大小,0 = 用 ChunkSize 字符数
|
||||
Languages []string // 多语言启发式提示,空 = 自动检测
|
||||
}
|
||||
```
|
||||
|
||||
策略分发在 `runTier()`;heading / heuristic 两个实现通过包级函数变量在各自文件的 `init()` 中覆盖:
|
||||
|
||||
```go
|
||||
// internal/infrastructure/chunker/strategy.go
|
||||
func runTier(tier StrategyTier, text string, cfg SplitterConfig, profile *DocProfile) []Chunk {
|
||||
switch tier {
|
||||
case TierHeading:
|
||||
return splitByHeadings(text, cfg, profile)
|
||||
case TierHeuristic:
|
||||
return splitByHeuristics(text, cfg, profile)
|
||||
case TierLegacy:
|
||||
return SplitText(text, cfg)
|
||||
}
|
||||
return SplitText(text, cfg)
|
||||
}
|
||||
|
||||
var splitByHeadings = func(text string, cfg SplitterConfig, _ *DocProfile) []Chunk {
|
||||
return SplitText(text, cfg) // 被 heading_splitter.go 的 init() 覆盖
|
||||
}
|
||||
var splitByHeuristics = func(text string, cfg SplitterConfig, _ *DocProfile) []Chunk {
|
||||
return SplitText(text, cfg) // 被 heuristic_splitter.go 的 init() 覆盖
|
||||
}
|
||||
```
|
||||
|
||||
### 现有实现
|
||||
|
||||
| 策略 tier | 说明 | 文件 |
|
||||
| --- | --- | --- |
|
||||
| `TierHeading` | 按 Markdown 标题层级分块 | `internal/infrastructure/chunker/heading_hierarchy.go` 等 |
|
||||
| `TierHeuristic` | 多语言启发式分块 | `internal/infrastructure/chunker/heuristic_splitter.go` |
|
||||
| `TierLegacy`(=`recursive`) | 递归分隔符分块(原始实现) | `internal/infrastructure/chunker/splitter.go` 的 `SplitText()` |
|
||||
| 校验器 | 每个 tier 输出经 `ValidateChunks` 验收,失败则沿链回落 | `internal/infrastructure/chunker/validator.go` |
|
||||
|
||||
### 新增步骤
|
||||
|
||||
1. 在 `internal/infrastructure/chunker/` 新建 `my_splitter.go`,实现 `func(text string, cfg SplitterConfig, profile *DocProfile) []Chunk`;
|
||||
2. **注册点:`internal/infrastructure/chunker/strategy.go`** —
|
||||
- 增加策略常量(如 `StrategyMine = "mine"`)与新的 `StrategyTier`;
|
||||
- 在 `resolveChain`/`resolveChainWithProfile` 的 switch 中为新策略返回 tier 链(建议以 `TierLegacy` 兜底);
|
||||
- 在 `runTier()` 中新增 case;
|
||||
3. 调用方无需改动:知识库的 `chunking_config.strategy`(JSONB)经 `internal/application/service/knowledge_process.go` 的 `buildSplitterConfigFromChunking` 传入;
|
||||
4. 用 `SplitWithDiagnostics` 写单测验证 tier 选择与 `ValidateChunks` 验收行为。
|
||||
|
||||
---
|
||||
|
||||
## 新增检索引擎(Retriever Engine) {#_3-新增检索引擎-retriever-engine}
|
||||
|
||||
### 接口定义
|
||||
|
||||
接口在 `internal/types/interfaces/retriever.go`(三层:引擎 → 仓储 → 服务 + 注册表):
|
||||
|
||||
```go
|
||||
// internal/types/interfaces/retriever.go
|
||||
type RetrieveEngine interface {
|
||||
EngineType() types.RetrieverEngineType
|
||||
Retrieve(ctx context.Context, params types.RetrieveParams) ([]*types.RetrieveResult, error)
|
||||
Support() []types.RetrieverType // 支持的检索类型(向量/关键词)
|
||||
}
|
||||
|
||||
type RetrieveEngineRepository interface {
|
||||
Save(ctx context.Context, indexInfo *types.IndexInfo, params map[string]any) error
|
||||
BatchSave(ctx context.Context, indexInfoList []*types.IndexInfo, params map[string]any) error
|
||||
EstimateStorageSize(ctx context.Context, indexInfoList []*types.IndexInfo, params map[string]any) int64
|
||||
DeleteByChunkIDList(ctx context.Context, indexIDList []string, dimension int, knowledgeType string) error
|
||||
DeleteBySourceIDList(ctx context.Context, sourceIDList []string, dimension int, knowledgeType string) error
|
||||
CopyIndices(ctx context.Context, sourceKnowledgeBaseID string,
|
||||
sourceToTargetKBIDMap map[string]string,
|
||||
sourceToTargetChunkIDMap map[string]string,
|
||||
targetKnowledgeBaseID string, dimension int, knowledgeType string) error
|
||||
DeleteByKnowledgeIDList(ctx context.Context, knowledgeIDList []string, dimension int, knowledgeType string) error
|
||||
BatchUpdateChunkEnabledStatus(ctx context.Context, chunkStatusMap map[string]bool) error
|
||||
BatchUpdateChunkTagID(ctx context.Context, chunkTagMap map[string]string) error
|
||||
RetrieveEngine
|
||||
}
|
||||
|
||||
type RetrieveEngineRegistry interface {
|
||||
Register(indexService RetrieveEngineService) error
|
||||
GetRetrieveEngineService(engineType types.RetrieverEngineType) (RetrieveEngineService, error)
|
||||
GetAllRetrieveEngineServices() []RetrieveEngineService
|
||||
GetByStoreID(storeID string) (RetrieveEngineService, error)
|
||||
}
|
||||
```
|
||||
|
||||
引擎类型枚举在 `internal/types/retriever.go`:
|
||||
|
||||
```go
|
||||
// internal/types/retriever.go
|
||||
const (
|
||||
PostgresRetrieverEngineType RetrieverEngineType = "postgres"
|
||||
ElasticsearchRetrieverEngineType RetrieverEngineType = "elasticsearch"
|
||||
InfinityRetrieverEngineType RetrieverEngineType = "infinity"
|
||||
ElasticFaissRetrieverEngineType RetrieverEngineType = "elasticfaiss"
|
||||
QdrantRetrieverEngineType RetrieverEngineType = "qdrant"
|
||||
MilvusRetrieverEngineType RetrieverEngineType = "milvus"
|
||||
WeaviateRetrieverEngineType RetrieverEngineType = "weaviate"
|
||||
DorisRetrieverEngineType RetrieverEngineType = "doris"
|
||||
SQLiteRetrieverEngineType RetrieverEngineType = "sqlite"
|
||||
TencentVectorDBRetrieverEngineType RetrieverEngineType = "tencent_vectordb"
|
||||
OpenSearchRetrieverEngineType RetrieverEngineType = "opensearch"
|
||||
)
|
||||
```
|
||||
|
||||
### 现有实现
|
||||
|
||||
均在 `internal/application/repository/retriever/` 下:`postgres/`(pgvector + BM25/ParadeDB)、`elasticsearch/v7/`、`elasticsearch/v8/`、`qdrant/`、`milvus/`、`weaviate/`、`doris/`、`sqlite/`(sqlite-vec + FTS5)、`tencentvectordb/`、`opensearch/`。
|
||||
|
||||
### 新增步骤
|
||||
|
||||
1. 在 `internal/types/retriever.go` 增加 `RetrieverEngineType` 常量;
|
||||
2. 在 `internal/application/repository/retriever/myengine/` 新建包,实现 `RetrieveEngineRepository` 接口(可参考 `qdrant/` 或 `sqlite/`);
|
||||
3. **注册点:`internal/container/container.go` 的 `initRetrieveEngineRegistry()`** — 按 `RETRIEVE_DRIVER` 环境变量(逗号分隔)条件注册:
|
||||
|
||||
```go
|
||||
// internal/container/container.go(节选)
|
||||
retrieveDriver := strings.Split(os.Getenv("RETRIEVE_DRIVER"), ",")
|
||||
if slices.Contains(retrieveDriver, "postgres") {
|
||||
postgresRepo := postgresRepo.NewPostgresRetrieveEngineRepository(db)
|
||||
if err := registry.Register(
|
||||
retriever.NewKVHybridRetrieveEngine(postgresRepo, types.PostgresRetrieverEngineType),
|
||||
); err != nil { ... }
|
||||
}
|
||||
```
|
||||
|
||||
仿照上例为新引擎加分支,用 `retriever.NewKVHybridRetrieveEngine(repo, 引擎类型)` 包装后注册;
|
||||
如需支持知识库间移动文档时复用已有向量,再实现可选接口 `KnowledgeIndexMover`(`MoveKnowledgeIndices`:保留 chunk ID 与向量,只改所属知识库,且可安全重试);未实现时复用向量的移动会被拒绝,只能改用重新解析模式;
|
||||
4. 若引擎需要独立部署,在 `docker-compose.dev.yml` 加一个带 profile 的服务(参考 `qdrant`/`opensearch`),并在 `.env.example` 补连接变量。
|
||||
|
||||
---
|
||||
|
||||
## 新增模型厂商(internal/models/providers) {#_4-新增模型-provider-internal-models-provider}
|
||||
|
||||
模型接入分为协议、厂商、目录、运行时四层(概览见[模型管理](../03-features/06-models.md#分层结构))。大多数新厂商只需新增一份厂商定义并补充模型目录,复用已有协议即可。
|
||||
|
||||
### 接口定义
|
||||
|
||||
厂商定义是一个结构体,而不是接口实现,位于 `internal/models/providers/definition.go`:
|
||||
|
||||
```go
|
||||
// internal/models/providers/definition.go(节选)
|
||||
type Definition struct {
|
||||
ID string // 存入 models.parameters.provider 的稳定标识
|
||||
Name string
|
||||
Names map[string]string // 按语言的名称,如 "zh-CN"
|
||||
Website string
|
||||
Icon []byte // SVG
|
||||
API api.API // 默认对话协议
|
||||
RerankAPI api.RerankAPI // 未声明时默认 cohere-rerank
|
||||
EmbeddingAPI api.EmbeddingAPI // 未声明时默认 openai-embeddings
|
||||
TranscriptionAPI api.TranscriptionAPI // 未声明时默认 openai-transcriptions
|
||||
DefaultBaseURLs map[types.ModelType]string
|
||||
ModelTypes []types.ModelType
|
||||
RequiresAuth bool
|
||||
Auth AuthStyle // bearer / api-key / x-api-key / x-goog-api-key / none / signed
|
||||
URLPatterns []string // 旧行未填 provider 时按 URL 识别
|
||||
ExtraFields []ExtraField // 编辑器动态渲染的额外字段
|
||||
CredentialLabels []CredentialLabel // 重命名凭证输入框(签名类接口)
|
||||
Compat VendorCompat // 各协议的厂商级兼容默认值
|
||||
ThinkingLevels api.ThinkingLevelMap
|
||||
Order int // 厂商列表排序
|
||||
// 可选钩子
|
||||
Endpoint func(req EndpointRequest) (url string, query map[string]string)
|
||||
PreferAPI func(baseURL string, spec models.ModelSpec) api.API
|
||||
Signer func(creds api.Credentials) api.AuthFunc
|
||||
}
|
||||
```
|
||||
|
||||
协议层按能力各有一个最小接口,新协议实现它即可接入:
|
||||
|
||||
```go
|
||||
// internal/models/api/rerank.go
|
||||
type Reranker interface {
|
||||
Rerank(ctx context.Context, query string, documents []string) ([]RerankResult, error)
|
||||
}
|
||||
|
||||
// internal/models/api/embeddings.go
|
||||
type Embedder interface {
|
||||
Embed(ctx context.Context, texts []string, kind EmbedInputType) ([][]float32, error)
|
||||
}
|
||||
|
||||
// internal/models/api/transcriptions.go
|
||||
type Transcriber interface {
|
||||
Transcribe(ctx context.Context, req TranscriptionRequest) (*Transcription, error)
|
||||
}
|
||||
```
|
||||
|
||||
对话协议客户端实现 `internal/models/chat` 的 `Chat` 接口(`Chat` / `ChatStream` / `GetModelName` / `GetModelID`)。
|
||||
|
||||
### 现有实现
|
||||
|
||||
- **厂商**:`internal/models/providers/` 定义 30 个内置厂商,一个厂商一份(`aliyun.go`、`deepseek.go`、`generic.go`、`academycloud.go` 等),由 `builtin.go` 的 `Builtins()` 显式列出;图标在 `providers/assets/<id>.svg`。
|
||||
- **协议**:`internal/models/api/<protocol>`。对话 `openaicompletions`、`openairesponses`、`anthropicmessages`、`googlegenai`;向量 `openaiembeddings`、`dashscopeembeddings`、`arkembeddings`、`googleembeddings`;重排 `cohererank`、`dashscoperank`、`nimrerank`、`tencentlkeap`、`volcengineknowledge`、`teirank`、`pineconerank`;语音 `openaitranscriptions`、`openaichataudio`。
|
||||
- **模型目录**:`internal/models/catalog/data/seed.json`(模型元数据)+ `overrides.json`(协议、思考映射与 compat 修正)→ 由脚本生成 `models.generated.json`,编译时嵌入。
|
||||
- **运行时**:`internal/models/runtime` 组合厂商定义与目录(`New()`),应用部署叠加 `config/models.json`,并为每个模型行解析出协议、端点和兼容设置。
|
||||
|
||||
### 新增步骤
|
||||
|
||||
1. **新建厂商定义**:`internal/models/providers/<id>.go`,声明名称、支持的模型类型、各类型默认地址、鉴权方式、协议默认值及特殊端点钩子,并在包注释中写明官方文档依据;
|
||||
2. **注册点一:`internal/models/providers/builtin.go`** — 把 `new<Id>Provider()` 加进 `Builtins()`;图标放入 `providers/assets/<id>.svg`;
|
||||
3. **注册点二:模型目录** — 在 `internal/models/catalog/data/seed.json` 中为该厂商加一个条目(即使暂时没有模型也要有空列表,运行时按厂商 ID 读取目录),维护模型元数据;协议、思考映射与 compat 修正写在 `overrides.json`。模型键包含类型与 id / match,同名的对话和向量模型可以共存;
|
||||
4. **生成目录**:执行 `make model-catalog-generate`。生成文件不要手改;
|
||||
5. **新协议(可选)**:已有协议能覆盖时直接复用;确需新协议时新增 `internal/models/api/<protocol>` 包,并在对应工厂的协议分支中接入(对话 `internal/models/chat/chat.go` 的 `NewRemoteChat`、向量 `internal/models/embedding/protocol.go`、重排 `internal/models/rerank/reranker.go`、语音 `internal/models/asr/protocol.go`);
|
||||
6. **校验**:运行 `make model-catalog-check`。
|
||||
|
||||
`make model-catalog-check` 先检查生成数据是否过期,再运行 `internal/models/...` 的全部测试:`providers` 的注册与图标检查;`runtime` 的解析与叠加;`parity` 包的**不变量**(每个模型条目的字段合法性、compat 键名可解码、上下文与最大输出自洽)和**逐模型出站请求检查**(每个对话模型在思考开 / 关两种情况下只能出现一个输出上限字段;不支持采样参数的模型不得带 temperature;始终思考的模型不得收到关闭开关等)。新厂商和新模型违反这些规则时测试直接失败,无需单独写用例。
|
||||
|
||||
前端不需要改动:厂商下拉、图标、额外字段、模型目录都由 `GET /api/v1/models/providers` 动态渲染。开箱即用的内置模型行由运维在 `config/builtin_models.yaml` 中声明,与厂商定义无关。
|
||||
|
||||
### 维护已有厂商
|
||||
|
||||
**新增或调整模型元数据**(新模型 id、上下文窗口、价格):先生成差异报告,再对照厂商文档更新 `seed.json`,最后重新生成目录。
|
||||
|
||||
```bash
|
||||
make model-catalog-diff # 全部厂商
|
||||
make model-catalog-diff VENDOR=deepseek # 只看一家
|
||||
```
|
||||
|
||||
报告对比 [models.dev](https://models.dev/api.json) 的公开元数据:`+` 是上游有而目录没有的模型,`~` 是数值差异,`?` 是上游没收录的条目(国内厂商和别名经常如此,不代表错)。脚本只读不写,也从不在运行时调用。字段名、思考格式这类行为事实不会被自动同步,必须以厂商文档为准手工维护。
|
||||
|
||||
**厂商改了接口行为**(换了输出上限字段、新增 effort 取值、思考开关格式变化):改 `providers/<id>.go` 的 `Compat`,或 `overrides.json` 中对应模型的 `compat`,重新生成目录,并同步更新注释里的文档链接。`internal/models/api/openaicompletions/golden_test.go` 等快照测试会钉死出站 JSON,改动需先改测试预期。
|
||||
|
||||
**紧急修正**:不必等发版,可先用[部署叠加 `config/models.json`](../03-features/06-models.md#部署叠加-config-models-json)在部署侧修改,验证后再补回代码。
|
||||
|
||||
---
|
||||
|
||||
## 新增联网搜索引擎(internal/infrastructure/web_search) {#_5-新增联网搜索引擎-internal-infrastructure-web-search}
|
||||
|
||||
### 接口定义
|
||||
|
||||
```go
|
||||
// internal/types/interfaces/web_search.go
|
||||
type WebSearchProvider interface {
|
||||
// Name returns the name of the provider
|
||||
Name() string
|
||||
// Search performs a web search
|
||||
Search(ctx context.Context, query string, maxResults int, includeDate bool) ([]*types.WebSearchResult, error)
|
||||
}
|
||||
```
|
||||
|
||||
注册表是工厂映射(按需用租户参数实例化):
|
||||
|
||||
```go
|
||||
// internal/infrastructure/web_search/registry.go
|
||||
type ProviderFactory func(params types.WebSearchProviderParameters) (interfaces.WebSearchProvider, error)
|
||||
|
||||
type Registry struct {
|
||||
factories map[string]ProviderFactory
|
||||
mu sync.RWMutex
|
||||
}
|
||||
|
||||
func (r *Registry) Register(id string, factory ProviderFactory)
|
||||
func (r *Registry) CreateProvider(providerType string, params types.WebSearchProviderParameters) (interfaces.WebSearchProvider, error)
|
||||
```
|
||||
|
||||
支持按地区、时效过滤的引擎可额外实现可选接口 `FilteredWebSearchProvider`(`SearchWithFilters`);不支持过滤的引擎不得静默丢弃调用方请求的过滤条件。
|
||||
|
||||
### 现有实现
|
||||
|
||||
`internal/infrastructure/web_search/` 目录:`duckduckgo.go`、`google.go`、`bing.go`、`brave.go`、`tavily.go`、`ollama.go`、`baidu.go`、`searxng.go`、`keenable.go`、`zhipu.go`、`exa.go`、`metaso.go`、`bocha.go`、`serply.go`(另有 `proxy.go` 出站代理支持)。类型常量在 `internal/types/web_search_provider.go`(`WebSearchProviderTypeXxx`,与注册 ID 一一对应)。
|
||||
|
||||
### 新增步骤
|
||||
|
||||
1. 在 `internal/types/web_search_provider.go` 增加 `WebSearchProviderType` 常量;
|
||||
2. 在 `internal/infrastructure/web_search/` 新建 `mysearch.go`,实现 `WebSearchProvider` 并暴露工厂 `func NewMySearchProvider(params types.WebSearchProviderParameters) (interfaces.WebSearchProvider, error)`;
|
||||
3. **注册点:`internal/container/container.go` 的 `registerWebSearchProviders()`**:
|
||||
|
||||
```go
|
||||
func registerWebSearchProviders(registry *infra_web_search.Registry) {
|
||||
registry.Register("duckduckgo", infra_web_search.NewDuckDuckGoProvider)
|
||||
registry.Register("google", infra_web_search.NewGoogleProvider)
|
||||
// ... 在此追加:
|
||||
registry.Register("mysearch", infra_web_search.NewMySearchProvider)
|
||||
}
|
||||
```
|
||||
|
||||
4. 前端的 provider 下拉与参数表单如需展示新引擎,同步 `frontend/` 相应配置页组件;租户配置持久化在 `web_search_providers` 表。
|
||||
|
||||
---
|
||||
|
||||
## 新增数据源连接器(internal/datasource/connector) {#_6-新增数据源连接器-internal-datasource-connector}
|
||||
|
||||
> 目录内附有实现指南 `internal/datasource/CONNECTOR_IMPLEMENTATION_GUIDE.md`,可对照阅读。
|
||||
|
||||
### 接口定义
|
||||
|
||||
```go
|
||||
// internal/datasource/connector.go
|
||||
type Connector interface {
|
||||
// Type returns the connector type identifier (e.g., "feishu", "notion")
|
||||
Type() string
|
||||
|
||||
// Validate verifies that the provided configuration is valid by testing
|
||||
// connectivity and checking credentials.
|
||||
Validate(ctx context.Context, config *types.DataSourceConfig) error
|
||||
|
||||
// ListResources lists available resources that can be synced.
|
||||
// parentID 支持层级资源的懒加载:"" 返回顶层,非空返回该资源的直接子节点。
|
||||
ListResources(ctx context.Context, config *types.DataSourceConfig, parentID string) ([]types.Resource, error)
|
||||
|
||||
// ResolveResourceAncestors 为懒加载树的既有选中项解析祖先链(O(depth))。
|
||||
ResolveResourceAncestors(
|
||||
ctx context.Context, config *types.DataSourceConfig, resourceIDs []string,
|
||||
) ([]string, error)
|
||||
|
||||
// FetchAll performs a full sync of the specified resources.
|
||||
FetchAll(ctx context.Context, config *types.DataSourceConfig, resourceIDs []string) ([]types.FetchedItem, error)
|
||||
|
||||
// FetchIncremental performs an incremental sync based on the provided cursor.
|
||||
FetchIncremental(ctx context.Context, config *types.DataSourceConfig, cursor *types.SyncCursor) ([]types.FetchedItem, *types.SyncCursor, error)
|
||||
}
|
||||
```
|
||||
|
||||
可选的流式接口(大数据量分页 checkpoint,内存只驻留单条 item):
|
||||
|
||||
```go
|
||||
// internal/datasource/connector.go
|
||||
type StreamHandler interface {
|
||||
Emit(ctx context.Context, item types.FetchedItem) error
|
||||
Checkpoint(ctx context.Context, cursor *types.SyncCursor) error
|
||||
}
|
||||
|
||||
type StreamingConnector interface {
|
||||
Connector
|
||||
FetchStream(ctx context.Context, config *types.DataSourceConfig,
|
||||
cursor *types.SyncCursor, h StreamHandler) (*types.SyncCursor, error)
|
||||
}
|
||||
```
|
||||
|
||||
另有两个可选接口用于全量同步时仍能对账删除:`FullStreamingConnector`(`FetchFullStream`)与 `FullSyncWithCursor`(`FetchAllFromCursor`),在强制全量或 `sync_mode=full` 时重新拉取全部条目,同时保留上一次游标用于识别已删除的文档。未实现时,全量同步无法产生删除事件。
|
||||
|
||||
注册表同文件:`ConnectorRegistry`(`NewConnectorRegistry()` / `Register(connector)` / `Get(type)` / `List()`);连接器的 UI 元数据(名称、AuthType、capabilities)在同文件的 `ConnectorMetadataRegistry` map 中。
|
||||
|
||||
### 现有实现
|
||||
|
||||
| 类型 | 目录 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `feishu` / `lark` | `internal/datasource/connector/feishu/wiki/` | 飞书 / Lark 知识库,同一实现按区域区分 |
|
||||
| `feishu_drive` / `lark_drive` | `internal/datasource/connector/feishu/drive/` | 飞书 / Lark 云盘 |
|
||||
| `notion` | `internal/datasource/connector/notion/` | 页面与数据库 |
|
||||
| `confluence` | `internal/datasource/connector/confluence/` | Confluence |
|
||||
| `yuque` | `internal/datasource/connector/yuque/` | 语雀 |
|
||||
| `dingtalk` | `internal/datasource/connector/dingtalk/` | 钉钉文档 |
|
||||
| `ima` | `internal/datasource/connector/ima/` | 腾讯 ima 知识库 |
|
||||
| `rss` | `internal/datasource/connector/rss/` | RSS 订阅 |
|
||||
| `gitlab` | `internal/datasource/connector/gitlab/` | GitLab 仓库 |
|
||||
| `seafile` | `internal/datasource/connector/seafile/` | 资料库目录与文件 |
|
||||
|
||||
`internal/types/datasource.go` 中还有 `github`、`google_drive` 等尚未注册实现的类型常量。
|
||||
|
||||
### 新增步骤
|
||||
|
||||
1. 在 `internal/datasource/connector/mysource/` 新建包,实现 `Connector`(大数据量建议同时实现 `StreamingConnector`),提供 `NewConnector()`;
|
||||
2. **注册点一:`internal/container/container.go` 的 `initConnectorRegistry()`**:
|
||||
|
||||
```go
|
||||
if err := registry.Register(mysourceConnector.NewConnector()); err != nil {
|
||||
errs = errors.Join(errs, fmt.Errorf("register mysource connector: %w", err))
|
||||
}
|
||||
```
|
||||
|
||||
3. **注册点二:`internal/datasource/connector.go` 的 `ConnectorMetadataRegistry`** — 增加类型常量(`internal/types` 的 `ConnectorTypeXxx`)与元数据条目(Name/Description/AuthType/Capabilities);
|
||||
4. 同步配置结构:`types.DataSourceConfig` 若需新增凭证字段,注意加密存储约定;前端数据源接入页按元数据渲染;
|
||||
5. 复用 `internal/datasource` 的公共工具:用户可填写的 API 地址先经 `ValidateConnectorBaseURL` 做 SSRF 校验,HTTP 请求使用 `NewConnectorHTTPClient`(带重定向与拨号期 SSRF 防护),生成文件名使用 `SanitizeFileName`。
|
||||
|
||||
---
|
||||
|
||||
## 新增 IM 平台适配器(internal/im) {#_7-新增-im-平台适配器-internal-im}
|
||||
|
||||
### 接口定义
|
||||
|
||||
```go
|
||||
// internal/im/adapter.go
|
||||
type Platform string // "wecom" / "feishu" / "lark" / "slack" / "telegram" / "dingtalk" /
|
||||
// "mattermost" / "wechat" / "qqbot" / "yunzhijia"
|
||||
|
||||
// Adapter is the interface every IM platform must implement.
|
||||
type Adapter interface {
|
||||
// Platform returns the platform identifier.
|
||||
Platform() Platform
|
||||
|
||||
// VerifyCallback verifies the signature/token of an incoming callback request.
|
||||
VerifyCallback(c *gin.Context) error
|
||||
|
||||
// ParseCallback parses the raw IM callback request into a unified IncomingMessage.
|
||||
// Returns nil message for non-message events (e.g., URL verification).
|
||||
ParseCallback(c *gin.Context) (*IncomingMessage, error)
|
||||
|
||||
// SendReply sends a reply back to the IM platform.
|
||||
SendReply(ctx context.Context, incoming *IncomingMessage, reply *ReplyMessage) error
|
||||
|
||||
// HandleURLVerification handles the initial URL verification challenge.
|
||||
HandleURLVerification(c *gin.Context) bool
|
||||
}
|
||||
```
|
||||
|
||||
两个可选能力接口:
|
||||
|
||||
```go
|
||||
// internal/im/adapter.go
|
||||
// StreamSender:实现后 IM 服务将实时推送流式回答(如飞书流式卡片、Telegram 编辑消息)
|
||||
type StreamSender interface {
|
||||
StartStream(ctx context.Context, incoming *IncomingMessage) (string, error)
|
||||
UpdateStreamContent(ctx context.Context, incoming *IncomingMessage, streamID string, fullContent string) error
|
||||
FinalizeStream(ctx context.Context, incoming *IncomingMessage, streamID string, finalContent string) error
|
||||
EndStream(ctx context.Context, incoming *IncomingMessage, streamID string) error
|
||||
}
|
||||
|
||||
// FileDownloader:实现后,配置了 knowledge_base_id 的渠道会把文件消息入库
|
||||
type FileDownloader interface {
|
||||
DownloadFile(ctx context.Context, msg *IncomingMessage) (io.ReadCloser, string, error)
|
||||
}
|
||||
```
|
||||
|
||||
适配器由工厂按渠道实例化(`internal/im/service.go`):
|
||||
|
||||
```go
|
||||
// internal/im/service.go
|
||||
type AdapterFactory func(ctx context.Context, channel *IMChannel,
|
||||
msgHandler func(ctx context.Context, msg *IncomingMessage) error,
|
||||
) (Adapter, context.CancelFunc, error)
|
||||
|
||||
func (s *Service) RegisterAdapterFactory(platform string, factory AdapterFactory)
|
||||
```
|
||||
|
||||
### 现有实现
|
||||
|
||||
`internal/im/` 下每个平台一个子包:`wecom/`、`feishu/`(lark 复用,`feishu.NewFactory(RegionLark)`)、`slack/`、`telegram/`、`dingtalk/`、`mattermost/`、`wechat/`、`qqbot/`、`yunzhijia/`。
|
||||
|
||||
### 新增步骤
|
||||
|
||||
1. 在 `internal/im/adapter.go` 增加 `Platform` 常量;
|
||||
2. 新建 `internal/im/myplatform/`,实现 `Adapter`(按需加 `StreamSender`/`FileDownloader`)与 `NewFactory() im.AdapterFactory`;
|
||||
3. **注册点:`internal/container/container.go` 的 `registerIMAdapterFactories()`**:
|
||||
|
||||
```go
|
||||
func registerIMAdapterFactories(imService *imPkg.Service) {
|
||||
imService.RegisterAdapterFactory("wecom", wecom.NewFactory())
|
||||
// ... 在此追加:
|
||||
imService.RegisterAdapterFactory("myplatform", myplatform.NewFactory())
|
||||
if err := imService.LoadAndStartChannels(); err != nil { ... }
|
||||
}
|
||||
```
|
||||
|
||||
4. 渠道配置持久化在 `im_channels` 表,会话映射在 `im_channel_sessions`;前端渠道管理页需增加对应平台的配置表单。
|
||||
|
||||
---
|
||||
|
||||
## 新增 Agent 工具(internal/agent/tools) {#_8-新增-agent-工具-internal-agent-tools}
|
||||
|
||||
### 接口定义
|
||||
|
||||
工具接口定义在 `internal/types/agent.go`:
|
||||
|
||||
```go
|
||||
// internal/types/agent.go
|
||||
type Tool interface {
|
||||
// Name returns the unique identifier for this tool
|
||||
Name() string
|
||||
|
||||
// Description returns a human-readable description of what the tool does
|
||||
Description() string
|
||||
|
||||
// Parameters returns the JSON Schema for the tool's parameters
|
||||
Parameters() json.RawMessage
|
||||
|
||||
// Execute runs the tool with the given arguments
|
||||
Execute(ctx context.Context, args json.RawMessage) (*ToolResult, error)
|
||||
}
|
||||
```
|
||||
|
||||
运行时注册表在 `internal/agent/tools/registry.go`:
|
||||
|
||||
```go
|
||||
// internal/agent/tools/registry.go
|
||||
type ToolRegistry struct {
|
||||
tools map[string]types.Tool
|
||||
maxToolOutputSize int
|
||||
}
|
||||
|
||||
// RegisterTool adds a tool to the registry.
|
||||
// 同名工具 first-wins,防止名称碰撞劫持(GHSA-67q9-58vj-32qx)。
|
||||
func (r *ToolRegistry) RegisterTool(tool types.Tool)
|
||||
func (r *ToolRegistry) GetTool(name string) (types.Tool, error)
|
||||
func (r *ToolRegistry) ListTools() []string
|
||||
```
|
||||
|
||||
### 现有实现
|
||||
|
||||
工具名常量集中在 `internal/agent/tools/definitions.go`:`thinking`、`todo_write`、知识检索工具(`search_knowledge`、`read_document`、`list_documents`、`query_knowledge_graph`)、`database_query`、`data_analysis`、`data_schema`、`web_search`、`web_fetch`、MCP 按需调用工具(`discover_mcp_tools`、`call_mcp_tool`)、沙箱/技能工具(`shell_exec`、`read_file`、`list_sandbox_files`、`write_sandbox_file`、`edit_sandbox_file`、`write_skill_file`、`edit_skill_file`),记忆工具(`search_memory`、`search_conversations`)、wiki 工具(`wiki_read_page`、`wiki_write_page`、`wiki_replace_text`、`wiki_rename_page`、`wiki_delete_page`、`wiki_search`、`wiki_flag_issue`、`wiki_read_issue`、`wiki_update_issue`);本机浏览器工具 `local_browser` 实现在 `browserskill*.go`。实现文件多与工具同名(如 `search_knowledge.go`、`read_document.go`、`list_documents.go`、`data_analysis.go`;`mcp_tool.go` / `mcp_catalog.go` 负责把 MCP 服务的远程工具按需发现与调用)。
|
||||
|
||||
已退役的沙箱工具名(`execute_skill_script`、`read_skill`、`read_sandbox_file`)仅为解码历史记录保留,不再注册;已退役的检索工具名(`knowledge_search`、`grep_chunks`、`list_knowledge_chunks`、`get_document_info`、`wiki_read_source_doc`)仍以 `LegacyTool*` 常量保留:`legacyToolSuccessors` 把它们映射到 `search_knowledge` / `read_document`,`NormalizeAllowedTools` 在注册工具时自动改写已保存 Agent 配置里的旧名字,`SuccessorToolName` / `IsLegacyRetrievalTool` 供其他服务判定。重命名或合并工具时请沿用这一机制,而不是做数据迁移。
|
||||
|
||||
### 新增步骤
|
||||
|
||||
1. 在 `internal/agent/tools/` 新建 `my_tool.go`,实现 `types.Tool` 四个方法(`Parameters()` 返回 JSON Schema;注意工具名 ≤ 64 字符的 OpenAI 限制,见 `definitions.go` 的 `maxFunctionNameLength`);
|
||||
2. **注册点一:`internal/agent/tools/definitions.go`** — 增加 `ToolMyTool = "my_tool"` 常量,并把工具加进 `AvailableToolDefinitions()`(UI 的可选工具列表,注释明确要求与已注册工具保持同步);
|
||||
3. **注册点二:Agent 引擎的工具装配处** — 在构建 `ToolRegistry` 的服务逻辑(Agent 会话初始化,按 Agent 配置的允许工具列表实例化并 `RegisterTool`)中加入新工具的构造;带资源清理需求时实现 `Cleanup`(`types.Cleanable`);
|
||||
4. 输出体量大的工具注意 `ToolRegistry` 的 `maxToolOutputSize` 截断行为;为工具编写 `_test.go`(同目录有大量参考,如 `search_knowledge_test.go`、`scope_authorization_test.go`)。
|
||||
|
||||
---
|
||||
|
||||
## 新增存储后端(对象存储) {#_9-新增存储后端-对象存储}
|
||||
|
||||
### 接口定义
|
||||
|
||||
文件服务接口在 `internal/types/interfaces/file.go`:
|
||||
|
||||
```go
|
||||
// internal/types/interfaces/file.go
|
||||
type FileService interface {
|
||||
CheckConnectivity(ctx context.Context) error
|
||||
SaveFile(ctx context.Context, file *multipart.FileHeader, tenantID uint64, knowledgeID string) (string, error)
|
||||
SaveBytes(ctx context.Context, data []byte, tenantID uint64, fileName string, temp bool) (string, error)
|
||||
GetFile(ctx context.Context, filePath string) (io.ReadCloser, error)
|
||||
GetFileURL(ctx context.Context, filePath string) (string, error)
|
||||
DeleteFile(ctx context.Context, filePath string) error
|
||||
CopyFile(ctx context.Context, srcPath string, tenantID uint64, knowledgeID string) (string, error)
|
||||
}
|
||||
```
|
||||
|
||||
多后端解析(租户级 `storage_backends` 表配置 → FileService 实例)经 `internal/types/interfaces/storagebackend.go`:
|
||||
|
||||
```go
|
||||
// internal/types/interfaces/storagebackend.go
|
||||
type StorageBackendService interface {
|
||||
Create(ctx context.Context, backend *types.StorageBackend) error
|
||||
Update(ctx context.Context, backend *types.StorageBackend) error
|
||||
Delete(ctx context.Context, tenantID uint64, id string) error
|
||||
SetDefault(ctx context.Context, tenantID uint64, id string) error
|
||||
Test(ctx context.Context, backend *types.StorageBackend) error
|
||||
}
|
||||
|
||||
type StorageBackendResolver interface {
|
||||
ResolveFileService(ctx context.Context, tenant *types.Tenant, backendID, provider, localBaseDir string) (FileService, string, error)
|
||||
ResolveBackend(ctx context.Context, tenant *types.Tenant, backendID, provider string) (*types.StorageBackend, error)
|
||||
}
|
||||
```
|
||||
|
||||
### 现有实现
|
||||
|
||||
均在 `internal/application/service/file/`:
|
||||
|
||||
| provider | 文件 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `local` | `local.go` | 本地文件系统 |
|
||||
| `minio` | `minio.go` | MinIO / S3 兼容 |
|
||||
| `cos` | `cos.go` | 腾讯云 COS |
|
||||
| `tos` | `tos.go` | 火山引擎 TOS |
|
||||
| `s3` | `s3.go` | AWS S3 及兼容服务 |
|
||||
| `obs` | `obs.go` | 华为云 OBS |
|
||||
| `oss` | `oss.go` | 阿里云 OSS |
|
||||
| `ks3` | `ks3.go` | 金山云 KS3 |
|
||||
|
||||
### 新增步骤
|
||||
|
||||
1. 在 `internal/application/service/file/` 新建 `mystore.go`,实现 `FileService` 全部方法(`CheckConnectivity` 用于前端"测试连接"按钮,即 `StorageBackendService.Test`);
|
||||
2. **注册点:`internal/application/service/file/factory.go` 的 `NewFileServiceFromStorageConfig()`** — 在 provider switch 中加 case:
|
||||
|
||||
```go
|
||||
switch p {
|
||||
case "local": // NewLocalFileService(...)
|
||||
case "minio": // NewMinioFileService(...)
|
||||
// ... 在此追加:
|
||||
case "mystore":
|
||||
return NewMyStoreFileService(cfg), p, nil
|
||||
default:
|
||||
return nil, p, fmt.Errorf("unsupported storage provider: %s", p)
|
||||
}
|
||||
```
|
||||
|
||||
3. 若新 provider 需要新的配置字段(endpoint/bucket/region 等),扩展 `internal/types` 中的 `StorageEngineConfig` / `StorageBackend.config`(JSONB);
|
||||
4. 前端存储后端管理页增加对应 provider 的表单项;租户配置落在 `storage_backends` 表(`provider` 列即 switch 的 key)。
|
||||
|
||||
---
|
||||
|
||||
## 附:扩展点速查表
|
||||
|
||||
| 扩展点 | 核心接口 | 接口文件 | 注册点 |
|
||||
| --- | --- | --- | --- |
|
||||
| 文档解析器 | `BaseParser.parse_into_text` | `docreader/parser/base_parser.py` | `docreader/parser/registry.py` `_build_default_registry()` |
|
||||
| 分块策略 | tier 函数 `func(text, cfg, profile) []Chunk` | `internal/infrastructure/chunker/strategy.go` | 同文件 `runTier()` + 策略常量 |
|
||||
| 检索引擎 | `RetrieveEngineRepository` | `internal/types/interfaces/retriever.go` | `container.go` `initRetrieveEngineRegistry()`(`RETRIEVE_DRIVER` 门控) |
|
||||
| 模型厂商 | `providers.Definition`(+ 协议层 `Reranker` / `Embedder` / `Transcriber`、`chat.Chat`) | `internal/models/providers/definition.go` | `internal/models/providers/builtin.go` `Builtins()` + `internal/models/catalog/data/seed.json` |
|
||||
| 联网搜索 | `WebSearchProvider` | `internal/types/interfaces/web_search.go` | `container.go` `registerWebSearchProviders()` |
|
||||
| 数据源连接器 | `Connector` / `StreamingConnector` | `internal/datasource/connector.go` | `container.go` `initConnectorRegistry()` + `ConnectorMetadataRegistry` |
|
||||
| IM 适配器 | `Adapter`(+`StreamSender`/`FileDownloader`) | `internal/im/adapter.go` | `container.go` `registerIMAdapterFactories()` |
|
||||
| Agent 工具 | `types.Tool` | `internal/types/agent.go` | `internal/agent/tools/definitions.go` + `ToolRegistry.RegisterTool` |
|
||||
| 存储后端 | `FileService` | `internal/types/interfaces/file.go` | `internal/application/service/file/factory.go` switch |
|
||||
@@ -0,0 +1,131 @@
|
||||
# 沙箱部署与排障
|
||||
|
||||
技能使用流程见[技能目录与沙箱](../03-features/22-skills-sandbox.md),字段定义见[沙箱与技能 API](../04-api/02-api-sandbox-skills.md)。本文补充部署、模板、桌面和后端接入的运维要求。
|
||||
|
||||
## 后端与模板
|
||||
|
||||
空间命名配置可选择 Docker、CubeSandbox、E2B,本文说明这三类后端的部署。Lite 桌面客户端另有依赖操作系统隔离能力的 `host` 后端,不属于服务端命名配置,构建要求见下文 [Lite 本机沙箱](#lite-本机沙箱);旧 `local` 宿主机进程后端已移除。Docker 直接使用 Engine API;E2B 使用控制面 REST 与 envd 数据面;Cube 保留专用适配器处理模板和网络策略。
|
||||
|
||||
标准镜像由 `docker/Dockerfile.sandbox` 定义,包含 Python 3.12、Node.js 20、Bash、jq 与 `/workspace`。命令和文件操作默认使用沙箱内 root;保留 UID 1000 的 `user` 供显式按账号执行。跨会话隔离由容器或远端沙箱提供,不能把工作目录约定解释为 root 的文件权限限制。
|
||||
|
||||
| 构建 target | 镜像标签后缀 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| `sandbox` | 无 | Docker 会话镜像;E2B CLI 模板基础镜像 |
|
||||
| `cube` | `-cube` | Cube CLI 模板,含 envd |
|
||||
| `desktop` | `-desktop` | E2B 图形桌面模板基础镜像 |
|
||||
| `desktop-cube` | `-desktop-cube` | Cube 图形桌面模板,含 envd |
|
||||
|
||||
镜像名为 `wechatopenai/weknora-sandbox:<版本><后缀>`。模板 ID 属于具体集群或账号,不应把其他部署的 ID 直接复制过来。生产模板应对应已验证的应用版本;构建 target 和发布架构以仓库 Dockerfile、发布工作流为准。
|
||||
|
||||
## Docker 部署
|
||||
|
||||
Docker 后端默认关闭。系统管理员在「系统设置 → 网络安全」启用;尚未落库时可由 `ACADEMY_SANDBOX_DOCKER_ENABLED=true` 回退。关闭后仍可查看和删除已有配置,但不会新建会话容器。
|
||||
|
||||
一个配置连接一个 daemon,一个会话使用一个长驻容器。没有跨主机调度;不同 app 副本若连接各自独立的本机 daemon,不能假定会共享容器和技能快照。
|
||||
|
||||
| 配置 | 默认值或要求 |
|
||||
| --- | --- |
|
||||
| daemon 地址 | 留空时检测 `DOCKER_HOST` 或当前 Docker context;远端使用 `tcp://host:2376` |
|
||||
| TLS 证书目录 | 远端 TCP 必填,app 可读的目录中包含 `ca.pem`、`cert.pem`、`key.pem` |
|
||||
| CPU / 内存 / PID | 默认 2 核 / 2 GiB / 512 进程 |
|
||||
| 空闲 TTL | 默认 1800 秒 |
|
||||
| 网络模式 | 仅 `bridge` 或 `none`;不接受 `host`、`container:` 或自定义网络名 |
|
||||
| OCI runtime | 可选择 daemon 已安装的 runtime,如 `runsc` |
|
||||
|
||||
app 运行在容器里时,要挂载实际 Docker socket,或改连远端 daemon。socket 授予控制宿主机 Docker 的能力,只应交给可信 app。入口脚本在降权前根据 socket GID 配置 appuser 的组;不要通过 `chmod 666` 放开 socket。若 socket 为 `root:root` 且仅所有者可写,应先在宿主机配置合适的非 root 组权限。
|
||||
|
||||
优先使用标准镜像。自定义镜像需满足适配器的 root、Bash、GNU `find -printf`、coreutils `timeout` 和可写工作区要求;会话文件检查点与回退还依赖 Git。HTTP 请求取消本身不会终止容器进程,适配器通过容器内 `timeout` 执行命令超时控制。
|
||||
|
||||
空闲清扫由 Create/Connect 触发并在后台运行,按容器创建时记录的 TTL 判断;不是 daemon 自带的定时器。当前没有硬寿命上限,能执行命令的脚本可以持续更新活跃标记,部署方需单独监控长期存活容器。
|
||||
|
||||
### 技能快照与磁盘
|
||||
|
||||
技能安装通过 `docker commit` 生成 `academy-skill/` 本地镜像,后续会话从安装快照启动。它保存文件系统,不保存内存状态;当前不支持租户共享卷或 Docker 图形桌面。
|
||||
|
||||
增量快照继承旧镜像层,删除旧 tag 不一定释放磁盘;卸载技能会新增删除标记层,原文件仍可能留在父层。当前流程不自动压平镜像或跨 daemon 分发。监控层数和磁盘,清理前确认会话与快照引用;需要新底模时新建配置并重新安装技能。
|
||||
|
||||
## CubeSandbox / E2B 接入
|
||||
|
||||
1. 先准备可用的控制面、数据面网关和沙箱域名。在空间设置中填写 API、Proxy、domain 与凭据;私网/回环端点需要显式允许私网地址,仍不允许云元数据地址。
|
||||
2. 点击「连接并继续」,验证控制面后加载模板目录。连接通过只证明控制面可用。
|
||||
3. 缺少标准模板时显式创建;需要桌面时另行创建桌面模板。等待状态为 `READY` 再选择。Cube 应使用带 envd 的 `-cube` 变体;普通 Docker 镜像不提供 `:49983/health`。
|
||||
4. 执行「完整验证」,实际创建沙箱、执行探针并销毁,确认数据面和脚本环境也可用。
|
||||
5. 保存后在智能体选择该配置,并验证附件读取、命令状态保持和产物下载。
|
||||
|
||||
`proxy_url` 用于自托管数据面网关:连接网关时保留沙箱 Host 路由,适合没有泛域名 DNS 的环境。控制面可访问而执行失败时,重点核对 Proxy、sandbox domain、入站凭据和 app 到网关的可达性。
|
||||
|
||||
Cube guest DNS 属于模板配置。更改 DNS/镜像后需重建模板才会进入新环境。已经安装技能的配置不能更换或重建底模,也不能在 CLI/桌面间切换,应新建配置并安装技能,避免让快照与底模不一致。
|
||||
|
||||
多副本必须配置共享 Redis,保存 session→sandbox 绑定和桌面状态。仅单实例开发可使用内存存储。已有沙箱不会自动应用后端配置变更;技能更新的 `next_turn` / `new_session` 策略见[技能目录与沙箱](../03-features/22-skills-sandbox.md)。
|
||||
|
||||
| 现象 | 排查方向 |
|
||||
| --- | --- |
|
||||
| 连接验证失败 | API 是否误填 Dashboard 地址;凭据、TLS、私网开关是否正确 |
|
||||
| 连接成功但执行失败 | Proxy、sandbox domain、网关路由与入站 token |
|
||||
| 模板构建失败 | 查看集群返回的构建错误;镜像是否能拉取、架构是否匹配、Cube 镜像是否带 envd |
|
||||
| 沙箱无法出网 | 模板网络策略、guest DNS、集群出站代理;允许私网控制面不等于允许脚本出网 |
|
||||
| 安装依赖失败 | 默认拒绝出站时是否放行软件源;技能安装与会话使用同一网络策略 |
|
||||
| 重连后状态丢失 | Redis 是否共享、TTL 是否到期、技能更新是否触发重建 |
|
||||
|
||||
## 交互终端与图形桌面
|
||||
|
||||
对话侧栏的终端和桌面都通过 WebSocket 连接会话沙箱。终端支持 Cube、E2B 和 Docker;桌面仅 Cube/E2B 支持。浏览器不能在 WebSocket 握手里携带认证头,因此都先用已登录的 POST 换取两分钟有效的短期票据,再把票据放在握手 query 中:
|
||||
|
||||
| 能力 | 取票据 | WebSocket |
|
||||
| --- | --- | --- |
|
||||
| 终端 | `POST /api/v1/sessions/:session_id/sandbox/terminal-ticket` | `GET /api/v1/sessions/:id/sandbox/terminal?ticket=...` |
|
||||
| 桌面 | `POST /api/v1/sessions/:session_id/sandbox/desktop-ticket` | `GET /api/v1/sessions/:id/sandbox/desktop?ticket=...` |
|
||||
|
||||
入口代理必须为这两个路径转发 WebSocket Upgrade、放宽读超时,并避免在访问日志中记录 ticket query。标准 frontend Nginx 已为 `^/api/v1/sessions/[^/]+/sandbox/(terminal|desktop)$` 配置不含 query 的日志格式;自定义 Ingress 需自行处理。终端连上后,服务端大约每分钟复核一次登录状态、空间成员和会话归属,退出登录或被移出空间会断开终端。接口参数见[终端 API](../04-api/02-api-sandbox-skills.md#会话交互终端)与[桌面 API](../04-api/02-api-chat.md#sandbox-desktop)。
|
||||
|
||||
终端和桌面在无操作时按配置的 `terminal_idle_disconnect_sec` 断开(默认 900 秒,最短 60 秒,最长 24 小时),之后沙箱按提供商 TTL 暂停。终端以键盘输入和 PTY 输出计活动,桌面以键鼠计活动。
|
||||
|
||||
Docker 终端是一个 `TTY=true` 的 exec,Engine API 不支持重新附着,因此行为与 Cube/E2B 不同:
|
||||
|
||||
- 终端打开期间会定期刷新空闲回收用的活动标记,容器不会因 `DockerIdleTTL` 被回收;关闭后按 `DockerIdleTTL` 正常回收。
|
||||
- 终端断开(关闭面板、空闲断开、网络中断)时,Academy 会像关闭终端窗口一样向该 Shell 及其子进程发送 SIGHUP,前台任务随之结束,`nohup` 启动的后台任务保留。
|
||||
- 前端不会对 Docker 终端自动重连,用户点「重新连接」会得到一个新 Shell。
|
||||
- 沙箱未运行时(容器已停止或已被空闲回收)提示「可能已被回收」,启动后若容器已被删除会新建沙箱,之前的文件不会保留。
|
||||
|
||||
### 图形桌面
|
||||
|
||||
仅 Cube/E2B 桌面模板支持对话侧栏桌面。首次打开时由后端启动桌面进程;配置需选择桌面模板并设置 `desktop_enabled`。技能已安装后不能原地切换底模。
|
||||
|
||||
```text
|
||||
浏览器 noVNC → Academy 票据中继 → 提供商网关 → websockify :6080 → 本机 x11vnc :5900
|
||||
```
|
||||
|
||||
浏览器不持有沙箱 API Key、入站 token 或 websockify 密码。桌面票据仅可消费一次,完整定义见[会话 API](../04-api/02-api-chat.md#sandbox-desktop)。Cube 桌面模板的 `exposedPorts` 只暴露 envd 的 49983,**不要把 6080 加入宿主机 NAT**,桌面必须经过网关与 Academy 中继。
|
||||
|
||||
每个会话同时只允许一条桌面中继,多副本槽位由 Redis 协调。沙箱重建后以 `SANDBOX_REBUILT` 提醒断开,不能把新桌面当成保留了原临时文件的旧实例。空闲判断使用 RFB 键鼠活动,截图请求不算用户操作。
|
||||
|
||||
## Lite 本机沙箱
|
||||
|
||||
`host` 后端只编译进带 `desktop` 构建标签的 Lite 桌面程序(`cmd/desktop/wails.json` 的 `build:tags`),服务端和单二进制 Lite 不包含。它在未选沙箱配置的会话中运行命令,用法见[技能目录与沙箱](../03-features/22-skills-sandbox.md#lite-host)。
|
||||
|
||||
| 平台 | 状态 |
|
||||
| --- | --- |
|
||||
| macOS | 使用系统 `sandbox-exec`(Seatbelt)执行每条命令;启动时检测不可用则不启用 |
|
||||
| Windows | 尚未实现,报告不可用,不会退化为无隔离执行 |
|
||||
| Linux | 不支持 |
|
||||
|
||||
每条命令都是新的本机进程,没有会话级实例,因此不写入会话的沙箱绑定,也不做工作区检查点。用户通过系统目录选择框批准的项目目录保存在 `desktop-prefs.json` 的 `project_dirs`;会话只能绑定列表中的目录本身,不能绑定其子目录或手工输入的路径。`approval_mode` 当前只支持 `auto`(在工作区内自由读写、禁止联网),写入其他值会被拒绝。偏好文件位置见[桌面客户端](../05-clients/05-desktop.md#_5-偏好设置存储-cmd-desktop-prefs-go)。
|
||||
|
||||
## 开发验证
|
||||
|
||||
单元测试不需要真实 daemon:
|
||||
|
||||
```bash
|
||||
go test ./internal/sandbox -run 'TestDocker' -count=1
|
||||
```
|
||||
|
||||
真实 Docker 验证需要先构建标准镜像,会创建测试容器:
|
||||
|
||||
```bash
|
||||
docker build -f docker/Dockerfile.sandbox --target sandbox -t wechatopenai/weknora-sandbox:dev .
|
||||
DOCKER_INTEGRATION_IMAGE=wechatopenai/weknora-sandbox:dev \
|
||||
go test -tags=docker_integration ./internal/sandbox \
|
||||
-run '^TestDocker.*Integration' -count=1 -v -timeout=15m
|
||||
```
|
||||
|
||||
远端接入的一致性测试位于 `internal/sandbox/cube_integration_test.go` 与 `e2b_compatible_integration_test.go`,运行前按文件开头配置测试集群凭据。验证范围应包含会话状态保持、Shell 复用、附件暂存、产物收集和超时,而不能只测 Health。测试结束后确认测试实例已清理。
|
||||
@@ -0,0 +1,67 @@
|
||||
# 对话提示词拼装与可编辑范围
|
||||
|
||||
本文供维护提示词、智能体编辑器和模型消息链路的开发者使用。智能体配置与执行流程见[Agent 引擎](../03-features/07-agent.md)。
|
||||
|
||||
## 智能推理的系统段
|
||||
|
||||
唯一拼装入口是 `internal/agent/prompts.go` 中的 `BuildSystemPromptSections`,引擎和字符串兼容接口 `BuildSystemPromptWithOptions` 均使用它。以下按实际拼装顺序列出;空段在输出时省略。
|
||||
|
||||
| 段名 | 来源与职责 |
|
||||
| --- | --- |
|
||||
| `base` | 显式正文优先;否则无绑定知识库用 `pure` 默认模板,有知识库用 `rag` 默认模板 |
|
||||
| `steering` | 如何处理回答过程中用户追加的消息(补充、修改或取消),保留未完成任务;自定义正文同样带上 |
|
||||
| `runtime_contract` | 数据与指令边界、当前文档范围、完成条件;已知用户语言时追加默认回答语言 |
|
||||
| `sources` | 根据实际注册的工具集合选择来源规则;技能安装模式使用专门的安装验证说明 |
|
||||
| `tools` | 通用执行、文件和沙箱约定;具体参数仍在工具定义中 |
|
||||
| `output` | 公共输出格式、配图条件和完成检查 |
|
||||
| `skills` | 可用技能元数据;仅在非技能安装模式、具有 `read_file` 且存在元数据时追加 |
|
||||
| `memory` | 本轮召回的记忆 |
|
||||
| `protocol` | 来源句柄与输出引用协议 |
|
||||
|
||||
自定义正文只替换 `base`,不移除其他运行时段,也不增加工具权限。分段不是模型 API 的不同权限层级;可调用工具仍由后端注册与执行路径控制。浏览器操作契约保留在 `local_browser` 的工具描述中,接入与操作说明见[本机浏览器](../05-clients/09-local-browser.md)。
|
||||
|
||||
`base` 的占位符由 `renderPromptPlaceholdersWithStatus` 展开:
|
||||
|
||||
| 占位符 | 当前行为 |
|
||||
| --- | --- |
|
||||
| `{{knowledge_bases}}` | 指向用户消息中 `runtime_context` 的知识库目录,不展开全文 |
|
||||
| `{{web_search_status}}` | 根据实际 `web_search` 工具是否注册,展开为 `Enabled` / `Disabled` |
|
||||
| `{{current_time}}` | `YYYY-MM-DD` 日期 |
|
||||
| `{{language}}` | 用户语言名 |
|
||||
| `{{skills}}` | 清空;技能元数据由独立段提供 |
|
||||
|
||||
## 当前轮上下文与消息角色
|
||||
|
||||
`internal/agent/observe.go` 在当前用户消息中加入 `runtime_context`:日期、会话 ID、绑定知识库摘要、固定文档和问题来源等本轮信息;不把它持久化为历史指令。知识库名称与描述限长并转义,FAQ 答案和文档全文需要通过检索工具读取。
|
||||
|
||||
`@MCP` / `@Skill` 产生当前轮的 `must_use` 提示。MCP 提及只为已授权服务设置优先提示,不移除其他已配置服务;尚未暴露的服务通过 `discover_mcp_tools` 发现。技能提及提示先读取对应 `SKILL.md`。这些选择不能授权无关操作,仍受用户明确的来源限制和后端权限约束。
|
||||
|
||||
回答过程中用户追加并选择立即补充的消息,在下一轮迭代前作为 user 消息接到消息列表末尾:发给模型的内容以 `<steer_message>` 包裹并附 `<continue_task>` 说明(`types.SteerMessageContent`),会话历史和界面保留用户原文;`steering` 段约定模型如何对待这类消息。
|
||||
|
||||
正常工具结果保留 `tool` 角色与调用 ID;消息修复时无法配对的结果以转义后的 `untrusted_tool_result` 数据块保留,不能提升为系统指令。Agent、普通问答和模型兜底共用来源数据边界规则,但三者并不使用完全相同的提示词拼装流程。
|
||||
|
||||
达到迭代上限或错误收尾时,`internal/agent/finalize.go` 沿用当前消息列表,保留历史、图片及工具调用配对,再追加收尾请求。最后一次调用不提供工具,设置 `tool_choice=none` 并关闭 thinking。
|
||||
|
||||
## 编辑与保存
|
||||
|
||||
前端编辑器展示有效正文,`frontend/src/utils/agentPromptTemplates.ts` 在保存时区分模板引用与自定义内容:
|
||||
|
||||
- 正文与已知模板完全相同:保存 `system_prompt_id` / `context_template_id`,正文留空。
|
||||
- 正文被实际修改:保存正文,清除旧模板 ID。
|
||||
- 改写、兜底字段与当前默认模板一致:保存空值,继承默认值;意图提示词只保存偏离默认值的覆盖项。
|
||||
|
||||
例如未修改的 Wiki 模板保存为:
|
||||
|
||||
```json
|
||||
{"agent_mode":"smart-reasoning","system_prompt_id":"wiki_researcher","system_prompt":""}
|
||||
```
|
||||
|
||||
`internal/config/agent_prompts.go` 的 `ResolveCustomAgentPrompts` 在请求时解析引用,显式正文始终优先,引用仅在所属字段与模式的模板集合中查找。解析结果不会写回保存对象;未知引用返回空正文,由调用方使用默认路径。
|
||||
|
||||
默认模板更新不会覆盖已有自定义正文,也不会批量迁移历史默认副本。旧配置需要重新跟随模板时,在编辑器恢复默认后保存。
|
||||
|
||||
## 维护时检查什么
|
||||
|
||||
新增规则先确定归属:角色与领域方法放 `base`,来源选择放 `sources`,调用约定放工具定义或 `tools`,输出形态放 `output`,引用编码放 `protocol`。避免同一规则在多处重复维护。
|
||||
|
||||
`[Agent][Prompt] section=... bytes=...` 日志帮助定位各段体积;验证行为还需检查最终模型消息、实际工具注册表及执行权限,并用任务验证来源选择、失败恢复和输出格式。
|
||||
@@ -0,0 +1,205 @@
|
||||
# WeMM Transformers 部署
|
||||
|
||||
使用 [WeMM 官方 Transformers 推理代码](https://github.com/Tencent/WeMM-Embedding#transformers)加载模型,由仓库内的 `scripts/wemm-transformers/serve.py` 提供 HTTP Embedding 服务。服务可以与 Academy 部署在同一机器,也可以部署在独立 GPU 服务器上,通过 Base URL 接入。
|
||||
|
||||
CUDA、Apple MPS 和 CPU 是可选的计算设备,使用同一份脚本和请求协议。此 HTTP 适配层由 Academy 提供,支持文本和图片;模型本身支持的视频等能力尚未在此接口开放。官方 vLLM 部署方式见[模型配置](../03-features/06-models.md#wemm-embedding)。
|
||||
|
||||
## 安装依赖
|
||||
|
||||
以下命令在 Academy 仓库根目录执行,使用 Python 3.12。虚拟环境和模型文件放在仓库外:
|
||||
|
||||
```bash
|
||||
python3.12 -m venv "$HOME/.venvs/academy-wemm"
|
||||
source "$HOME/.venvs/academy-wemm/bin/activate"
|
||||
python -m pip install --upgrade pip
|
||||
```
|
||||
|
||||
按设备选择一组 PyTorch 安装命令。以下使用已验证的 PyTorch 2.10.0 / torchvision 0.25.0,CUDA wheel 须与驱动兼容;其他 CUDA 版本可参考 [PyTorch 安装说明](https://pytorch.org/get-started/previous-versions/#v2100)。
|
||||
|
||||
```bash
|
||||
# NVIDIA GPU:示例为 CUDA 12.8 wheel
|
||||
python -m pip install torch==2.10.0 torchvision==0.25.0 \
|
||||
--index-url https://download.pytorch.org/whl/cu128
|
||||
|
||||
# 或 Apple Silicon / MPS
|
||||
python -m pip install torch==2.10.0 torchvision==0.25.0
|
||||
|
||||
# 或 Linux / Windows CPU wheel
|
||||
python -m pip install torch==2.10.0 torchvision==0.25.0 \
|
||||
--index-url https://download.pytorch.org/whl/cpu
|
||||
```
|
||||
|
||||
安装其余依赖:
|
||||
|
||||
```bash
|
||||
python -m pip install -r scripts/wemm-transformers/requirements.txt
|
||||
```
|
||||
|
||||
Transformers 固定为官方推荐的 `5.2.0`,`qwen-vl-utils` 固定为 `0.0.14`。不要随意替换 Transformers 版本,避免预处理行为变化。脚本会启用 `trust_remote_code=True` 来加载 WeMM 的 `embedding()` 实现,应使用官方权重或已审查的模型目录。
|
||||
|
||||
## 启动服务
|
||||
|
||||
以 CUDA 上的 2B 为例:
|
||||
|
||||
```bash
|
||||
python scripts/wemm-transformers/serve.py \
|
||||
--model tencent/WeMM-Embedding-2B \
|
||||
--revision bbd6cd4bf52cfc6716f752a2df80b2706720bd95 \
|
||||
--device cuda \
|
||||
--host 127.0.0.1 \
|
||||
--port 18080
|
||||
```
|
||||
|
||||
首次启动会从 Hugging Face 下载模型到标准缓存,后续复用缓存。`--revision` 可固定模型代码与权重版本;示例 SHA 属于 2B,切换 4B、9B 时应选取对应仓库的版本,不能沿用此 SHA。未指定时使用该仓库默认版本。
|
||||
|
||||
已有模型目录时可以离线启动,并指定 Academy 调用时使用的模型名称:
|
||||
|
||||
```bash
|
||||
python scripts/wemm-transformers/serve.py \
|
||||
--model /srv/models/WeMM-Embedding-2B \
|
||||
--served-model-name tencent/WeMM-Embedding-2B \
|
||||
--local-files-only \
|
||||
--device cuda
|
||||
```
|
||||
|
||||
也可以提前下载并固定版本,例如:
|
||||
|
||||
```bash
|
||||
hf download tencent/WeMM-Embedding-2B \
|
||||
--revision bbd6cd4bf52cfc6716f752a2df80b2706720bd95 \
|
||||
--local-dir /srv/models/WeMM-Embedding-2B
|
||||
```
|
||||
|
||||
其他设备只需更换参数:
|
||||
|
||||
```bash
|
||||
# Apple Silicon,允许不支持的 MPS 算子回退到 CPU
|
||||
python scripts/wemm-transformers/serve.py \
|
||||
--model tencent/WeMM-Embedding-2B --device mps --mps-fallback
|
||||
|
||||
# CPU,默认使用 float32
|
||||
python scripts/wemm-transformers/serve.py \
|
||||
--model tencent/WeMM-Embedding-2B --device cpu
|
||||
```
|
||||
|
||||
4B、9B 将 `--model` 换成对应 ID 或路径。服务从模型配置读取原生维度及 Matryoshka 可选维度,不会将其他规格强制按 2048 维处理:
|
||||
|
||||
| 模型 ID | 原生维度 |
|
||||
| --- | --- |
|
||||
| `tencent/WeMM-Embedding-2B` | 2048 |
|
||||
| `tencent/WeMM-Embedding-4B` | 2560 |
|
||||
| `tencent/WeMM-Embedding-9B` | 4096 |
|
||||
|
||||
服务以前台方式运行,按 Ctrl+C 停止。常驻部署时由 systemd、容器或其他进程管理器托管同一命令。一个进程加载一份完整模型到一个设备,不提供多 GPU 切分;选择规格前应预留权重、视觉处理和推理激活所需的显存/内存。
|
||||
|
||||
### 独立服务器与鉴权
|
||||
|
||||
跨机器部署时使用 `--host 0.0.0.0`,并在服务进程环境中设置 `WEMM_API_KEY`。`/v1/models` 与 `/v1/embeddings` 会验证 `Authorization: Bearer <key>`;Academy 的 API Key 填写相同值。服务不直接终止 TLS,跨不可信网络时通过 HTTPS 反向代理访问。`/health` 仅提供运行状态和非敏感模型元数据,不要求 API Key。
|
||||
|
||||
默认监听回环地址、未设置 API Key。Academy 若运行在 Docker 中,`127.0.0.1` 指向 Academy 容器自身,应填写容器能够访问的推理服务地址,例如同一容器网络的服务名,或已配置的宿主机地址。私网地址还需符合 Academy 的 SSRF 访问策略,配置方法见[安全说明](../01-getting-started/04-configuration.md)。
|
||||
|
||||
## Academy 接入
|
||||
|
||||
在「设置 → 模型管理」添加:
|
||||
|
||||
| 字段 | 填写 |
|
||||
| --- | --- |
|
||||
| 类型 | Embedding |
|
||||
| 来源 / 服务商 | API / 自定义(OpenAI 兼容接口) |
|
||||
| 模型名称 | `/v1/models` 返回的 ID,推荐保留 `tencent/WeMM-Embedding-2B` 等官方名称 |
|
||||
| Base URL | `http://推理服务地址:18080/v1`,使用 HTTPS 代理时填写对应地址 |
|
||||
| API Key | 设置了 `WEMM_API_KEY` 时填写相同值 |
|
||||
| 图片输入 | 官方名称由预设识别;自定义别名需手动开启 |
|
||||
| 自定义输出维度 | 初次接入关闭,让连接检测识别原生维度;需要降维时再开启 |
|
||||
| 后台并发上限 | 建议从 1 开始 |
|
||||
|
||||
现有 WeMM 预设的 `messages` 格式同时适用于此服务。推荐在「高级 → 协议兼容覆盖」设置较小批量和较长超时:
|
||||
|
||||
```json
|
||||
{
|
||||
"api": "openai-embeddings",
|
||||
"image_format": "messages",
|
||||
"text_as_messages": true,
|
||||
"batch_messages": true,
|
||||
"accepts_truncate_prompt_tokens": false,
|
||||
"max_batch_size": 4,
|
||||
"max_image_batch_size": 2,
|
||||
"request_timeout_seconds": 180
|
||||
}
|
||||
```
|
||||
|
||||
完整配置也适用于尚未包含 WeMM 预设的旧版本或自定义模型别名;此时应手动打开图片输入。点击「测试连接」,确认实际维度后保存。知识库还需开启图片向量索引,配置方式见[模型配置](../03-features/06-models.md)。切换模型或输出维度需要重建已有索引。
|
||||
|
||||
## 请求格式与推理流程
|
||||
|
||||
接口为 `POST /v1/embeddings`。纯文本可以使用 `input`:
|
||||
|
||||
```json
|
||||
{
|
||||
"model": "tencent/WeMM-Embedding-2B",
|
||||
"input": ["第一段文本", "第二段文本"],
|
||||
"encoding_format": "float"
|
||||
}
|
||||
```
|
||||
|
||||
文本和图片也可使用 `messages`。以下二维数组包含两个独立输入,分别返回一个文本向量和一个图片向量:
|
||||
|
||||
```json
|
||||
{
|
||||
"model": "tencent/WeMM-Embedding-2B",
|
||||
"dimensions": 1024,
|
||||
"messages": [
|
||||
[{"role": "user", "content": [{"type": "text", "text": "白色背景上的红色方块"}]}],
|
||||
[{"role": "user", "content": [{"type": "image_url", "image_url": {"url": "data:image/png;base64,图片Base64"}}]}]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
`input` 和 `messages` 只能选一个。单条 conversation 可以使用一维消息数组;文字与图片放在同一 conversation 中会得到一个联合向量。返回值采用 OpenAI Embedding 的 `data[].embedding`、`data[].index` 和 `usage` 结构,编码支持 `float` 与 float32 小端字节的 `base64`。
|
||||
|
||||
服务会将文本包装成消息,把内联图片解码成 PIL 图片,使用官方 processor 的聊天模板,再转换为张量。Tokenizer 自动追加 `<embedding>`,调用方无需手动添加。推理调用 `model.embedding(..., use_cache=False)`,随后按请求维度截取并做 L2 归一化。这里使用 Transformers 自带的模型 tokenizer/processor;vLLM 的 `embedding_chat_template.jinja` 不作为本脚本的额外模板传入。
|
||||
|
||||
HTTP 支持批量输入,但模型逐条执行,并串行处理推理请求,以隔离模型内部的可变位置状态。`batch_messages: true` 表示合并 HTTP 请求,不代表 GPU 张量批处理,也不提供 vLLM 的连续批处理调度。
|
||||
|
||||
## 参数与限制
|
||||
|
||||
| 参数 | 默认值 | 说明 |
|
||||
| --- | --- | --- |
|
||||
| `--device` | `auto` | 自动按 CUDA → MPS → CPU 选择;可显式指定 `cuda:N`、`mps`、`cpu`,指定不可用设备会报错 |
|
||||
| `--dtype` | `auto` | CUDA 支持 BF16 时用 BF16,否则 FP16;MPS 用 BF16;CPU 用 FP32。可显式指定 `bfloat16`、`float16`、`float32` |
|
||||
| `--max-tokens` | 8192 | 每个输入经过模板和图片处理后的总 token 上限,超限拒绝,不静默截断 |
|
||||
| `--max-pixels` | 1048576 | 每张图片缩放后的像素上限,至少 65536;较小上限会影响高分辨率文档效果 |
|
||||
| `--max-batch-size` | 32 | 每个 HTTP 请求的独立输入数上限;Academy 的批量设置不应超过它 |
|
||||
| `--cpu-threads` | 8 | PyTorch CPU 线程数 |
|
||||
| `--mps-fallback` | 关闭 | 允许 PyTorch 将不支持的 MPS 算子放到 CPU 执行 |
|
||||
| `--local-files-only` | 关闭 | 仅使用本机文件或已有缓存,不下载权重 |
|
||||
| `--host` / `--port` | `127.0.0.1` / `18080` | 监听地址与端口 |
|
||||
|
||||
每个请求体最多 32 MiB,包含分块传输;每张图片的 data URI 最多 16 MiB,解码前原图最多 4000 万像素,每个 conversation 最多 5 张图片。图片只接受内联 Base64,不抓取远程 URL 或文件路径。`image_url.detail` 仅为格式兼容,实际分辨率由 `--max-pixels` 控制。所有上限都是此部署脚本的资源设置,不代表 WeMM 模型本身的上限。
|
||||
|
||||
## 验证与排障
|
||||
|
||||
运行无需下载权重的接口测试:
|
||||
|
||||
```bash
|
||||
python -m unittest discover -s scripts/wemm-transformers -v
|
||||
```
|
||||
|
||||
对运行中的服务做实际图文推理测试:
|
||||
|
||||
```bash
|
||||
python scripts/wemm-transformers/smoke_test.py \
|
||||
--base-url http://127.0.0.1:18080
|
||||
```
|
||||
|
||||
设置了鉴权时,测试进程同样读取 `WEMM_API_KEY`。测试覆盖批量图文、输出维度与归一化、图文匹配、图片后文本状态隔离及降维;输出耗时和结果到标准输出,不修改知识库。
|
||||
|
||||
当前在 Apple M4 Pro 上完成了 **WeMM 2B / MPS / BF16** 和 **WeMM 2B / CPU / FP32** 的完整图文推理测试。2B、4B、9B 的接口维度处理及 CUDA 精度选择有自动化覆盖;4B/9B 的完整权重推理和 CUDA 部署仍需在目标设备运行上述验证脚本。不要将接口测试视为这些设备和规格的性能验证。
|
||||
|
||||
常见问题:
|
||||
|
||||
- **CUDA/MPS 不可用**:检查 PyTorch wheel、驱动与设备,或显式改为 `--device cpu`;脚本不会将显式设备要求静默降级。
|
||||
- **MPS 算子不支持**:尝试 `--mps-fallback`;BF16 不可用时可使用 `--dtype float32`,同时检查内存余量。
|
||||
- **显存不足或超时**:减小模型规格、图片像素、输入长度和 Academy 批量。该服务为单 worker,增加 HTTP 并发不会自动增加推理吞吐。
|
||||
- **模型加载缓慢**:首次需要下载权重;先预下载并固定版本,离线启动时检查目录中同时包含权重、tokenizer、processor 和官方 Python 模型代码。
|
||||
- **模型名不匹配**:检查 `/v1/models`;使用自定义目录时建议显式设置 `--served-model-name`。
|
||||
Reference in new issue
Block a user