mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-19 14:16:29 +00:00
feat(embedding): add compose tiers, docs, and regenerate-embeddings CLI (#480)
* feat(embedding): update compose tiers, docs, and add regenerate-embeddings CLI - Add Lite, Embedding, and Full Docker Compose configurations (and Aliyun mirrors) - Set CONCURRENCY_AGENT to 1 for compose files containing embedding-server - Update README and README_CN with compose options, recommended RAM, and semantic search links - Add LiteRT-LM Embedding Server setup guide in docs/using-shumai/embedding-server.mdx - Add shumai regenerate-embeddings CLI command and EmbeddingService to regenerate embeddings across teams - Add comprehensive test coverage for EmbeddingService * fix(docker): remove basic auth for turntable-renderer in full compose * fix(agent): lock and disable embedding agent when ENABLE_EMBEDDING_AGENT is false Ensure that when ENABLE_EMBEDDING_AGENT is set to 'false', existing embedding agents are automatically disabled on startup, marked as read-only, and blocked from manual API modifications or creations. Additionally guard background task creation and semantic search when the environment variable disables embedding agents. * test(upload): remove flaky status assertion on workflow tasks
This commit is contained in:
@@ -8,6 +8,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
|
||||
|
||||
### Added
|
||||
|
||||
* **cli**: Add administrative `shumai regenerate-embeddings` command to regenerate multimodal vector embeddings for all existing media files across active teams
|
||||
* **docker**: Provide three Docker Compose deployment tiers (Lite, with Embedding Server, and Full) with recommended memory specifications
|
||||
* **docs**: Add documentation for LiteRT-LM Embedding Server setup, 15 frames per minute video sampling, provider migration warnings, and CLI embedding regeneration
|
||||
* **agent**: Save video chunk embeddings incrementally to the database as each chunk finishes, preserving completed progress on failure and resuming from where it left off on retry
|
||||
* **agent**: Add support for local LiteRT-LM Gemma Embedding 2 (`gemma-embedding-2-openai`) provider and environment-enforced read-only embedding agents with automatic 768-dimensional vector search indexing
|
||||
|
||||
|
||||
@@ -35,6 +35,7 @@ Shumai is an open-source Frame.io alternative built for creative teams to collab
|
||||
* **Wide File Format Support**: Preview common creative file formats, including images (with PSD support), videos, audio, and documents, while allowing any file type to be uploaded and stored.
|
||||
* **3D Asset Turntable Previews**: Generate interactive 3D model turntable previews and videos for formats like GLB, FBX, OBJ, STL, USD, and DAE using [turntable-renderer](https://docs.shumai.one/using-shumai/3d-asset-support).
|
||||
* **Office & Document PDF Proxying via Gotenberg**: Convert Word, PowerPoint, Excel, Markdown, HTML, and CSV documents to high-quality PDF proxies for in-browser previewing using [Gotenberg](https://docs.shumai.one/using-shumai/gotenberg).
|
||||
* **Semantic Search**: Find assets by visual or conceptual meaning using vector embeddings. See [documentation](https://docs.shumai.one/using-shumai/semantic-search).
|
||||
* **NLE Export & Premiere Pro Plugin (Experimental)**: Export timestamped review comments to your favorite non-linear editor (Premiere Pro XML, DaVinci Resolve EDL, Final Cut Pro, Avid Media Composer) or use the experimental Premiere Pro UXP plugin to import media assets and auto-sync comments directly to sequence timeline markers. See [documentation](https://docs.shumai.one/using-shumai/nle-and-premiere).
|
||||
|
||||
But Shumai goes beyond being a Frame.io alternative. With modern models like GPT-Image-2 and Seedance 2.5, AI can already handle a surprising amount of creative work. That means you can create or update videos and images from a simple prompt without having to jump back into Photoshop, Premiere or Houdini. That is why Shumai includes a powerful agent system:
|
||||
@@ -47,7 +48,6 @@ But Shumai goes beyond being a Frame.io alternative. With modern models like GPT
|
||||
* **Model Context Protocol (MCP)**: Connect agents to external tools and APIs through remote MCP servers, with OAuth authentication and per-agent MCP access.
|
||||
* **Isolated Sandbox Execution**: Run agent-submitted scripts safely in a sandboxed environment.
|
||||
* **AI Metadata Autofill**: Automatically fill in custom metadata for new assets.
|
||||
* **Semantic Search**: Find assets by visual or conceptual meaning using vector embeddings (Gemini Embedding 2).
|
||||
* **Resource Quotas**: Set usage limits on AI tokens, costs, and tool execution per member, role, or team-wide, with real-time tracking.
|
||||
|
||||
Here is a short demo video showing what the Shumai agent can do:
|
||||
@@ -83,13 +83,25 @@ Docker Compose is the fastest way to get Shumai running. You do not need to clon
|
||||
```bash
|
||||
mkdir shumai && cd shumai
|
||||
```
|
||||
2. Download the `docker-compose.yaml` file:
|
||||
```bash
|
||||
curl -o docker-compose.yaml https://raw.githubusercontent.com/shumaiOne/shumai/main/docker-compose/local/docker-compose.yaml
|
||||
```
|
||||
2. Download your preferred `docker-compose.yaml` configuration based on your needs and available RAM:
|
||||
|
||||
* **Lite (Suggested RAM: 2 GB+)**: Minimal deployment containing Shumai and PostgreSQL database.
|
||||
```bash
|
||||
curl -o docker-compose.yaml https://raw.githubusercontent.com/shumaiOne/shumai/main/docker-compose/local/docker-compose.yaml
|
||||
```
|
||||
|
||||
* **With Embedding Server (Suggested RAM: 4 GB+)**: Adds local multimodal semantic search powered by `shumaiOne/embedding-server` (`EmbeddingGemma 2 740M`).
|
||||
```bash
|
||||
curl -o docker-compose.yaml https://raw.githubusercontent.com/shumaiOne/shumai/main/docker-compose/local/docker-compose.embedding.yaml
|
||||
```
|
||||
|
||||
* **Full (Suggested RAM: 8 GB+)**: All-in-one setup including `embedding-server`, `turntable-renderer` (3D previews), and `Gotenberg` (document PDF proxying).
|
||||
```bash
|
||||
curl -o docker-compose.yaml https://raw.githubusercontent.com/shumaiOne/shumai/main/docker-compose/local/docker-compose.full.yaml
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> By default, the standard `docker-compose.yaml` uses CPU software transcoding. If your server has a GPU (NVIDIA NVENC, Intel QuickSync, AMD/Intel VA-API, or Rockchip RKMPP) and you want to enable GPU hardware acceleration, check the [Hardware Transcoding Guide](https://docs.shumai.one/configuration/hardware-transcoding).
|
||||
> By default, the Docker Compose setups use CPU software transcoding. If your server has a GPU (NVIDIA NVENC, Intel QuickSync, AMD/Intel VA-API, or Rockchip RKMPP) and you want to enable GPU hardware acceleration, check the [Hardware Transcoding Guide](https://docs.shumai.one/configuration/hardware-transcoding).
|
||||
3. Configure environment variables (optional):
|
||||
|
||||
* `SHUMAI_SERVER_PORT` controls the port the Shumai server listens on. The default is `3000`.
|
||||
@@ -129,190 +141,7 @@ Docker Compose is the fastest way to get Shumai running. You do not need to clon
|
||||
```
|
||||
6. Open your browser and access Shumai at `http://localhost:3000` (or `http://<your-server-ip>:3000` for remote deployments).
|
||||
|
||||
### Option 2: Install via NPM / Package Manager
|
||||
|
||||
Shumai is published as `@shumai-one/shumai` on NPM. This option allows you to run Shumai globally or locally.
|
||||
|
||||
#### Step 1: Start PostgreSQL with pgvector
|
||||
|
||||
Shumai requires PostgreSQL with the `pgvector` extension. Start a pre-configured database container using Docker:
|
||||
|
||||
```bash
|
||||
docker run --name shumai_postgres \
|
||||
-e POSTGRES_USER=shumai \
|
||||
-e POSTGRES_PASSWORD=shumai_password \
|
||||
-e POSTGRES_DB=shumai_db \
|
||||
-p 5432:5432 \
|
||||
-d pgvector/pgvector:pg18
|
||||
```
|
||||
|
||||
#### Step 2: Create a workspace folder
|
||||
|
||||
Create a dedicated directory to store your environment configuration and media files (which are saved in a `./data` directory by default):
|
||||
|
||||
```bash
|
||||
mkdir shumai && cd shumai
|
||||
```
|
||||
|
||||
#### Step 3: Install Platform-Specific Dependencies
|
||||
|
||||
#### Linux
|
||||
|
||||
Shumai requires the following system packages on Linux:
|
||||
|
||||
- **`ffmpeg`** – Used for media transcoding and metadata extraction.
|
||||
- **`poppler`** (`poppler-utils`) – Used for PDF page image extraction and PDF sprite preview generation (`pdftoppm`).
|
||||
- **`imagemagick`** – Used for PSD format transcoding and color profile conversion to sRGB.
|
||||
- **`dcraw_emu`** (`libraw` / `libraw-bin`) – Used for camera RAW format image decoding and preview generation.
|
||||
- **`bubblewrap`**, **`socat`**, and **`ripgrep`** – Required by the AI agent sandbox (`anthropic-experimental/sandbox-runtime`) for process isolation, networking, and workspace search.
|
||||
|
||||
Install all required packages with one command:
|
||||
|
||||
> Ubuntu/Debian
|
||||
```bash
|
||||
sudo apt install -y ffmpeg poppler-utils imagemagick bubblewrap socat ripgrep libraw-bin
|
||||
```
|
||||
|
||||
> Fedora
|
||||
```bash
|
||||
sudo dnf install -y ffmpeg poppler-utils ImageMagick bubblewrap socat ripgrep LibRaw
|
||||
```
|
||||
|
||||
> Arch Linux
|
||||
```bash
|
||||
sudo pacman -S --noconfirm ffmpeg poppler imagemagick bubblewrap socat ripgrep libraw
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> **Ubuntu 24.04+** restricts unprivileged user namespaces by default. This prevents `anthropic-experimental/sandbox-runtime` from using `bubblewrap` for sandbox isolation.
|
||||
>
|
||||
> To temporarily allow user namespaces:
|
||||
>
|
||||
> ```bash
|
||||
> sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
|
||||
> ```
|
||||
>
|
||||
> Alternatively, configure an AppArmor profile that grants the required `userns` permission to the relevant binaries.
|
||||
|
||||
---
|
||||
|
||||
#### macOS
|
||||
|
||||
Shumai requires:
|
||||
|
||||
- **`ffmpeg`** – Used for media transcoding and metadata extraction.
|
||||
- **`poppler`** – Used for PDF page image extraction and PDF sprite preview generation (`pdftoppm`).
|
||||
- **`imagemagick`** – Used for PSD format transcoding and color profile conversion to sRGB.
|
||||
- **`dcraw_emu`** (`libraw`) – Used for camera RAW format image decoding and preview generation.
|
||||
- **`ripgrep`** – Required by the AI agent sandbox (`anthropic-experimental/sandbox-runtime`).
|
||||
|
||||
Install the required packages with Homebrew:
|
||||
|
||||
```bash
|
||||
brew install ffmpeg poppler imagemagick ripgrep libraw
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### Windows (alpha)
|
||||
|
||||
> [!WARNING]
|
||||
> Windows support in anthropic-experimental/sandbox-runtime is **alpha and the design is in flux**.
|
||||
>
|
||||
> The current implementation provides:
|
||||
> - Network egress filtering via the **Windows Filtering Platform (WFP)**.
|
||||
> - File read/write denial via **ACL stamping**.
|
||||
>
|
||||
> However, it is **not a security boundary against a deliberately adversarial sandboxed process**.
|
||||
>
|
||||
> The sandbox implementation will be substantially revised in a future release, where sandboxed processes will run under a dedicated sandbox user account.
|
||||
|
||||
Shumai requires:
|
||||
|
||||
- **`ffmpeg`** – Used for media transcoding and metadata extraction.
|
||||
- **`imagemagick`** – Used for PSD format transcoding and color profile conversion to sRGB.
|
||||
|
||||
Install required packages using your preferred package manager:
|
||||
|
||||
**winget**
|
||||
```powershell
|
||||
winget install Gyan.FFmpeg ImageMagick.ImageMagick
|
||||
```
|
||||
|
||||
**Chocolatey**
|
||||
```powershell
|
||||
choco install ffmpeg imagemagick
|
||||
```
|
||||
|
||||
#### Step 4: Install Shumai globally
|
||||
|
||||
Install Shumai globally using your preferred package manager:
|
||||
|
||||
```bash
|
||||
# NPM
|
||||
npm install -g @shumai-one/shumai
|
||||
|
||||
# PNPM
|
||||
pnpm add -g @shumai-one/shumai
|
||||
|
||||
# Bun
|
||||
bun add -g @shumai-one/shumai
|
||||
```
|
||||
|
||||
#### Step 5: Configure Environment Variables
|
||||
|
||||
Create a `.env` file in your workspace folder (`shumai/`) and add the following configuration:
|
||||
|
||||
```env
|
||||
DATABASE_URL=postgresql://shumai:shumai_password@localhost:5432/shumai_db?schema=public
|
||||
BETTER_AUTH_SECRET=ySxs7DxzHDZBbeeHNPEwBuspYwipBqz5Gk5XdBjNhWw=
|
||||
STORAGE_BACKEND=local
|
||||
SHUMAI_SERVER_PORT=3000
|
||||
AWS_ENDPOINT_URL_S3=http://localhost:3000
|
||||
# Optional: base URL for MCP OAuth redirects (defaults to BETTER_AUTH_URL)
|
||||
MCP_OAUTH_REDIRECT_BASE_URL=http://localhost:3000
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> `SHUMAI_SERVER_PORT` sets the port the server starts on, while `AWS_ENDPOINT_URL_S3` is used by the browser to build file upload URLs.
|
||||
> If deploying on a remote server (e.g. `http://123.456.7.8`) with a mapped port (e.g. `12345:3000` in docker-compose), set `AWS_ENDPOINT_URL_S3` to `http://123.456.7.8:12345`.
|
||||
> `MCP_OAUTH_REDIRECT_BASE_URL` is only needed when MCP servers use OAuth: the authorization redirect URI defaults to `{BETTER_AUTH_URL}/api/mcp/oauth/callback`; set it to an externally reachable URL if the app is served behind a proxy.
|
||||
|
||||
#### Step 6: Run Shumai
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **For Bun Users:** Since the published package binaries contain a `#!/usr/bin/env node` shebang, running the global command directly (e.g., `shumai`) will execute under Node.js. If you installed with Bun and want to run under the Bun runtime, you must prefix all commands with `bun run --bun` (e.g., `bun run --bun shumai`, `bun run --bun shumai -d`, `bun run --bun shumai stop`).
|
||||
|
||||
Start the application from your workspace folder:
|
||||
|
||||
```bash
|
||||
shumai
|
||||
```
|
||||
|
||||
Alternatively, you can run and manage Shumai in daemon mode:
|
||||
|
||||
- **Start in daemon mode**:
|
||||
```bash
|
||||
shumai -d
|
||||
```
|
||||
- **Stop Shumai**:
|
||||
```bash
|
||||
shumai stop
|
||||
```
|
||||
- **Restart Shumai**:
|
||||
```bash
|
||||
shumai restart
|
||||
```
|
||||
- **Show/tail logs**:
|
||||
```bash
|
||||
shumai logs
|
||||
```
|
||||
|
||||
On startup, Shumai will automatically run database migrations and start the web server at `http://localhost:3000`.
|
||||
|
||||
---
|
||||
|
||||
### Option 3: Run from Source (Development)
|
||||
### Option 2: Run from Source (Development)
|
||||
|
||||
To set up Shumai locally for development:
|
||||
|
||||
@@ -322,8 +151,23 @@ To set up Shumai locally for development:
|
||||
cd shumai
|
||||
bun install
|
||||
```
|
||||
2. Start the `pgvector` database container (as described in **Option 2, Step 1**).
|
||||
3. Create a `.env` file at the root of the workspace using the configuration from **Option 2, Step 5**.
|
||||
2. Start the `pgvector` database container:
|
||||
```bash
|
||||
docker run --name shumai_postgres \
|
||||
-e POSTGRES_USER=shumai \
|
||||
-e POSTGRES_PASSWORD=shumai_password \
|
||||
-e POSTGRES_DB=shumai_db \
|
||||
-p 5432:5432 \
|
||||
-d pgvector/pgvector:pg18
|
||||
```
|
||||
3. Create a `.env` file at the root of the workspace:
|
||||
```env
|
||||
DATABASE_URL=postgresql://shumai:shumai_password@localhost:5432/shumai_db?schema=public
|
||||
BETTER_AUTH_SECRET=ySxs7DxzHDZBbeeHNPEwBuspYwipBqz5Gk5XdBjNhWw=
|
||||
STORAGE_BACKEND=local
|
||||
SHUMAI_SERVER_PORT=3000
|
||||
AWS_ENDPOINT_URL_S3=http://localhost:3000
|
||||
```
|
||||
4. Generate i18n translation files:
|
||||
```bash
|
||||
bun run i18n:compile
|
||||
@@ -339,6 +183,9 @@ To set up Shumai locally for development:
|
||||
bun run dev
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> Looking to install Shumai globally via NPM or your package manager? See our [NPM Installation Guide](https://docs.shumai.one/getting-started/quickstart).
|
||||
|
||||
---
|
||||
|
||||
## Command Line Interface (CLI)
|
||||
|
||||
+55
-221
@@ -35,6 +35,7 @@ Shumai 是一个开源的 Frame.io 替代方案,专为创意团队打造,让
|
||||
* **丰富的文件格式支持**:支持预览常见创意文件格式,包括图片(支持 PSD)、视频、音频和文档,同时可上传和存储任意类型的文件。
|
||||
* **基于转盘渲染服务的 3D 资产预览**:通过集成 [turntable-renderer](https://docs.shumai.one/using-shumai/3d-asset-support) 支持为 GLB、FBX、OBJ、STL、USD 和 DAE 等 3D 模型生成高质量的交互式转盘预览与视频。
|
||||
* **基于 Gotenberg 的文档 PDF 转码代理**:通过集成 [Gotenberg](https://docs.shumai.one/using-shumai/gotenberg) 支持将 Word、PowerPoint、Excel、Markdown、HTML 和 CSV 文档高质量转换为 PDF 代理文件进行在线预览。
|
||||
* **语义搜索**:支持按画面内容或概念含义搜索素材,底层基于向量嵌入技术。详见[相关文档](https://docs.shumai.one/using-shumai/semantic-search)。
|
||||
* **非编剪辑导出与 Premiere 插件(实验性)**:支持将时间戳审阅评论导出至常用非编软件(Premiere Pro XML、DaVinci Resolve EDL、Final Cut Pro、Avid Media Composer),或使用实验性的 Premiere Pro 原生 UXP 插件导入媒体素材并将评论自动同步为时间轴标记。详见[相关文档](https://docs.shumai.one/using-shumai/nle-and-premiere)。
|
||||
|
||||
但 Shumai 不仅仅只满足于 Frame.io 的开源替代。随着 GPT-Image-2、Seedance 2.5 这类强大模型的问世,AI已经生成产品级的图片/视频。很多时候,你只要给一句提示词,就能直接生成或修改图片和视频,而不用再打开 Photoshop、Premiere 或者 Houdini。也正因为这样,Shumai 才把 AI Agent 做成了核心能力:
|
||||
@@ -45,7 +46,6 @@ Shumai 是一个开源的 Frame.io 替代方案,专为创意团队打造,让
|
||||
* **Model Context Protocol (MCP) 支持**:通过远程 MCP 服务端为 Agent 接入外部工具与 API,支持 OAuth 鉴权与按 Agent 独立分配访问权限。
|
||||
* **沙箱隔离执行**:Agent 生成的脚本会在隔离环境里运行,更安全。
|
||||
* **AI 自动补全元数据**:新素材上传后,系统可以自动帮你补一些元数据。
|
||||
* **语义搜索**:支持按画面内容或语义找素材,底层用的是向量 embedding(Gemini Embedding 2)。
|
||||
* **资源配额**:支持按成员、角色或全团队对 AI Token、成本和工具调用设置使用上限与实时用量监控。
|
||||
|
||||
下面是一个简短的 demo 视频,展示了 Shumai Agent 能做什么:
|
||||
@@ -99,10 +99,22 @@ https://gh-proxy.com/https://raw.githubusercontent.com/shumaiOne/shumai/main/REA
|
||||
|
||||
```
|
||||
|
||||
2. 下载 `docker-compose.yaml` 配置文件:
|
||||
```bash
|
||||
curl -o docker-compose.yaml https://raw.githubusercontent.com/shumaiOne/shumai/main/docker-compose/local/docker-compose-aliyun.yaml
|
||||
```
|
||||
2. 根据您的需求和机器可用内存,下载对应的 `docker-compose.yaml` 配置文件:
|
||||
|
||||
* **精简版(建议内存:2 GB+)**:包含 Shumai 核心应用与 PostgreSQL 数据库。
|
||||
```bash
|
||||
curl -o docker-compose.yaml https://raw.githubusercontent.com/shumaiOne/shumai/main/docker-compose/local/docker-compose-aliyun.yaml
|
||||
```
|
||||
|
||||
* **含嵌入向量服务版(建议内存:4 GB+)**:新增基于 `shumaiOne/embedding-server` (`EmbeddingGemma 2 740M`) 的本地多模态语义搜索能力。
|
||||
```bash
|
||||
curl -o docker-compose.yaml https://raw.githubusercontent.com/shumaiOne/shumai/main/docker-compose/local/docker-compose-aliyun.embedding.yaml
|
||||
```
|
||||
|
||||
* **完整版(建议内存:8 GB+)**:一站式全功能套件,包含 `embedding-server`、`turntable-renderer`(3D 模型交互转盘预览)与 `Gotenberg`(文档与表格 PDF 代理转码)。
|
||||
```bash
|
||||
curl -o docker-compose.yaml https://raw.githubusercontent.com/shumaiOne/shumai/main/docker-compose/local/docker-compose-aliyun.full.yaml
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> 默认的 Docker Compose 配置使用基于 CPU 的软件转码。如果您的服务器配备了支持的显卡(NVIDIA NVENC、Intel QuickSync、AMD/Intel VA-API 或 Rockchip RKMPP)并需要开启 GPU 硬件加速转码,请参考 [硬件加速转码配置文档](https://docs.shumai.one/configuration/hardware-transcoding)。
|
||||
@@ -152,233 +164,55 @@ https://gh-proxy.com/https://raw.githubusercontent.com/shumaiOne/shumai/main/REA
|
||||
|
||||
5. 打开浏览器,访问 `http://localhost:3000` 即可开始使用(若是远程部署,请访问 `http://<您的服务器IP>:3000`)。
|
||||
|
||||
### 方案二:通过 NPM / 包管理器安装
|
||||
|
||||
通过 NPM 上的 `@shumai-one/shumai` 进行安装。
|
||||
|
||||
#### 第一步:启动带 pgvector 支持的 PostgreSQL
|
||||
|
||||
Shumai 依赖支持 `pgvector` 扩展的 PostgreSQL 数据库。您可以使用 Docker 快速启动一个预配置好的数据库容器:
|
||||
|
||||
```bash
|
||||
docker run --name shumai_postgres \
|
||||
-e POSTGRES_USER=shumai \
|
||||
-e POSTGRES_PASSWORD=shumai_password \
|
||||
-e POSTGRES_DB=shumai_db \
|
||||
-p 5432:5432 \
|
||||
-d docker.m.daocloud.io/pgvector/pgvector:pg18
|
||||
|
||||
```
|
||||
|
||||
#### 第二步:创建工作区目录
|
||||
|
||||
创建一个专属目录用来存放环境配置和媒体文件(媒体文件默认会保存在 `./data` 目录下):
|
||||
|
||||
```bash
|
||||
mkdir shumai && cd shumai
|
||||
|
||||
```
|
||||
|
||||
#### 步骤 3:安装平台依赖
|
||||
|
||||
#### Linux
|
||||
|
||||
在 Linux 上运行 Shumai 需要安装以下系统依赖:
|
||||
|
||||
- **`ffmpeg`** —— 用于媒体转码和元数据提取。
|
||||
- **`poppler`** (`poppler-utils`) —— 用于 PDF 页面图像提取和 PDF 雪碧图预览生成 (`pdftoppm`)。
|
||||
- **`imagemagick`** —— 用于 PSD 格式图像转码和 sRGB 色彩空间转换。
|
||||
- **`dcraw_emu`** (`libraw` / `libraw-bin`) —— 用于相机 RAW 格式图像解码和预览图生成。
|
||||
- **`bubblewrap`**、**`socat`** 和 **`ripgrep`** —— AI Agent 沙箱(`anthropic-experimental/sandbox-runtime`)所需,用于进程隔离、网络通信和工作区搜索。
|
||||
|
||||
可以使用以下命令一次性安装所有依赖:
|
||||
|
||||
> Ubuntu/Debian
|
||||
```bash
|
||||
sudo apt install -y ffmpeg poppler-utils imagemagick bubblewrap socat ripgrep libraw-bin
|
||||
```
|
||||
|
||||
> Fedora
|
||||
```bash
|
||||
sudo dnf install -y ffmpeg poppler-utils ImageMagick bubblewrap socat ripgrep LibRaw
|
||||
```
|
||||
|
||||
> Arch Linux
|
||||
```bash
|
||||
sudo pacman -S --noconfirm ffmpeg poppler imagemagick bubblewrap socat ripgrep libraw
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> **Ubuntu 24.04+** 默认限制非特权用户创建 User Namespace,这会导致 `anthropic-experimental/sandbox-runtime` 无法使用 `bubblewrap` 提供沙箱隔离。
|
||||
>
|
||||
> 如需临时启用 User Namespace,请执行:
|
||||
>
|
||||
> ```bash
|
||||
> sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
|
||||
> ```
|
||||
>
|
||||
> 或者,配置 AppArmor Profile,为相关可执行文件授予所需的 `userns`权限。
|
||||
|
||||
---
|
||||
|
||||
#### macOS
|
||||
|
||||
在 macOS 上运行 Shumai 需要:
|
||||
|
||||
- **`ffmpeg`** —— 用于媒体转码和元数据提取。
|
||||
- **`poppler`** —— 用于 PDF 页面图像提取和 PDF 雪碧图预览生成 (`pdftoppm`)。
|
||||
- **`imagemagick`** —— 用于 PSD 格式图像转码和 sRGB 色彩空间转换。
|
||||
- **`dcraw_emu`** (`libraw`) —— 用于相机 RAW 格式图像解码和预览图生成。
|
||||
- **`ripgrep`** —— AI Agent 沙箱(`anthropic-experimental/sandbox-runtime`)所需。
|
||||
|
||||
使用 Homebrew 安装所需依赖:
|
||||
|
||||
```bash
|
||||
brew install ffmpeg poppler imagemagick ripgrep libraw
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
#### Windows(Alpha)
|
||||
|
||||
> [!WARNING]
|
||||
> anthropic-experimental/sandbox-runtime 的 Windows 支持目前仍处于 **Alpha** 阶段,整体设计仍在持续调整中。
|
||||
>
|
||||
> 当前实现提供了以下能力:
|
||||
> - 通过 **Windows Filtering Platform (WFP)** 实现网络出口(egress)过滤。
|
||||
> - 通过 **ACL Stamping** 实现文件读写权限限制。
|
||||
>
|
||||
> **但这并不能作为针对恶意沙箱进程的安全边界(security boundary)**。
|
||||
>
|
||||
> 未来版本将对沙箱机制进行重大调整,届时沙箱进程将运行在独立的沙箱用户账户下。
|
||||
|
||||
在 Windows 上运行 Shumai 需要:
|
||||
|
||||
- **`ffmpeg`** —— 用于媒体转码和元数据提取。
|
||||
- **`imagemagick`** —— 用于 PSD 格式图像转码和 sRGB 色彩空间转换。
|
||||
|
||||
使用你偏好的包管理器安装所需依赖:
|
||||
|
||||
**winget**
|
||||
```powershell
|
||||
winget install Gyan.FFmpeg ImageMagick.ImageMagick
|
||||
```
|
||||
|
||||
**Chocolatey**
|
||||
```powershell
|
||||
choco install ffmpeg imagemagick
|
||||
```
|
||||
|
||||
#### 第四步:全局安装 Shumai
|
||||
|
||||
使用您常用的包管理器进行全局安装:
|
||||
|
||||
```bash
|
||||
# 使用 NPM
|
||||
npm install -g @shumai-one/shumai
|
||||
|
||||
# 使用 PNPM
|
||||
pnpm add -g @shumai-one/shumai
|
||||
|
||||
# 使用 Bun
|
||||
bun add -g @shumai-one/shumai
|
||||
|
||||
```
|
||||
|
||||
#### 第五步:配置环境配置
|
||||
|
||||
在刚才创建的工作区目录(`shumai/`)下新建一个 `.env` 文件,并填入以下配置:
|
||||
|
||||
```env
|
||||
DATABASE_URL=postgresql://shumai:shumai_password@localhost:5432/shumai_db?schema=public
|
||||
BETTER_AUTH_SECRET=ySxs7DxzHDZBbeeHNPEwBuspYwipBqz5Gk5XdBjNhWw=
|
||||
STORAGE_BACKEND=local
|
||||
SHUMAI_SERVER_PORT=3000
|
||||
AWS_ENDPOINT_URL_S3=http://localhost:3000
|
||||
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> `SHUMAI_SERVER_PORT` 用于设置 Web 服务的启动端口,而 `AWS_ENDPOINT_URL_S3` 供浏览器端构建文件上传链接。
|
||||
> 如果您部署在远程服务器(如 `http://123.456.7.8`)并且做了端口映射(如 Docker 中的 `12345:3000`),请将 `AWS_ENDPOINT_URL_S3` 设置为 `http://123.456.7.8:12345`。
|
||||
|
||||
#### 第六步:启动 Shumai
|
||||
|
||||
> [!IMPORTANT]
|
||||
> **Bun 用户特别提示:** 由于发布的包二进制文件包含 `#!/usr/bin/env node` 头部声明(Shebang),直接在终端执行全局命令(例如 `shumai`)默认会通过 Node.js 运行。如果您是用 Bun 安装的并且希望调用 Bun 运行时,请在所有命令前加上 `bun run --bun` 前缀(例如:`bun run --bun shumai`、`bun run --bun shumai -d`、`bun run --bun shumai stop`)。
|
||||
|
||||
在您的工作区目录下执行以下命令启动应用:
|
||||
|
||||
```bash
|
||||
shumai
|
||||
|
||||
```
|
||||
|
||||
您也可以让 Shumai 在后台以守护进程(Daemon)模式运行和管理:
|
||||
|
||||
* **后台模式启动**:
|
||||
```bash
|
||||
shumai -d
|
||||
|
||||
```
|
||||
|
||||
|
||||
* **停止服务**:
|
||||
```bash
|
||||
shumai stop
|
||||
|
||||
```
|
||||
|
||||
|
||||
* **重启服务**:
|
||||
```bash
|
||||
shumai restart
|
||||
|
||||
```
|
||||
|
||||
|
||||
* **查看并跟踪实时日志**:
|
||||
```bash
|
||||
shumai logs
|
||||
|
||||
```
|
||||
|
||||
|
||||
|
||||
启动时,Shumai 会自动执行数据库迁移(Migration)并在 `http://localhost:3000` 拉起 Web 服务。
|
||||
|
||||
---
|
||||
|
||||
### 方案三:源码编译运行(开发环境)
|
||||
### 方案二:源码编译运行(开发环境)
|
||||
|
||||
如果您希望在本地参与 Shumai 的开发,请按以下步骤配置开发环境:
|
||||
|
||||
1. 克隆代码仓库并安装依赖项:
|
||||
```bash
|
||||
git clone [https://github.com/shumaiOne/shumai.git](https://github.com/shumaiOne/shumai.git)
|
||||
cd shumai
|
||||
bun install
|
||||
```bash
|
||||
git clone https://github.com/shumaiOne/shumai.git
|
||||
cd shumai
|
||||
bun install
|
||||
```
|
||||
|
||||
```
|
||||
2. 启动 `pgvector` 数据库容器:
|
||||
```bash
|
||||
docker run --name shumai_postgres \
|
||||
-e POSTGRES_USER=shumai \
|
||||
-e POSTGRES_PASSWORD=shumai_password \
|
||||
-e POSTGRES_DB=shumai_db \
|
||||
-p 5432:5432 \
|
||||
-d docker.m.daocloud.io/pgvector/pgvector:pg18
|
||||
```
|
||||
|
||||
3. 在项目根目录下创建一个 `.env` 文件,填入以下基础配置:
|
||||
```env
|
||||
DATABASE_URL=postgresql://shumai:shumai_password@localhost:5432/shumai_db?schema=public
|
||||
BETTER_AUTH_SECRET=ySxs7DxzHDZBbeeHNPEwBuspYwipBqz5Gk5XdBjNhWw=
|
||||
STORAGE_BACKEND=local
|
||||
SHUMAI_SERVER_PORT=3000
|
||||
AWS_ENDPOINT_URL_S3=http://localhost:3000
|
||||
```
|
||||
|
||||
2. 启动 `pgvector` 数据库容器(参考**方案二中的第一步**)。
|
||||
3. 参照**方案二中的第五步**,在项目根目录下创建一个 `.env` 文件。
|
||||
4. 生成多语言国际化(i18n)代码:
|
||||
```bash
|
||||
bun run i18n:compile
|
||||
```
|
||||
> [!TIP]
|
||||
> 在前端开发过程中,可以在单独的终端窗口中运行 `bun run i18n:watch`,在修改 `packages/webui/messages/` 下的翻译文案时自动重新编译。
|
||||
```bash
|
||||
bun run i18n:compile
|
||||
```
|
||||
> [!TIP]
|
||||
> 在前端开发过程中,可以在单独的终端窗口中运行 `bun run i18n:watch`,在修改 `packages/webui/messages/` 下的翻译文案时自动重新编译。
|
||||
|
||||
5. 执行数据库结构迁移:
|
||||
```bash
|
||||
bun run db:migrate
|
||||
```
|
||||
```bash
|
||||
bun run db:migrate
|
||||
```
|
||||
|
||||
6. 启动本地开发服务器:
|
||||
```bash
|
||||
bun run dev
|
||||
```
|
||||
```bash
|
||||
bun run dev
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> 如需通过 NPM 或包管理器全局安装运行 Shumai,请参考[官方 NPM 安装指南](https://docs.shumai.one/getting-started/quickstart)。
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ import { agentService } from '@shumai/core/src/agent/agent'
|
||||
|
||||
import { handleDaemonCommands } from '@shumai/core/src/utils/daemon'
|
||||
import { authService } from '@shumai/core/src/auth/auth'
|
||||
import { embeddingService } from '@shumai/core/src/search/embedding-service'
|
||||
import { sandboxService } from '@shumai/core'
|
||||
import { notificationJobService } from '@shumai/core/src/notification/notification-job'
|
||||
|
||||
@@ -48,6 +49,29 @@ if (resetCmdIndex !== -1) {
|
||||
}
|
||||
}
|
||||
|
||||
const regenCmdIndex = cliArgs.findIndex((arg) => arg === 'regenerate-embeddings')
|
||||
|
||||
if (regenCmdIndex !== -1) {
|
||||
try {
|
||||
console.log('🔄 Regenerating embeddings...')
|
||||
const result = await embeddingService.regenerateEmbeddings()
|
||||
console.log(
|
||||
`✅ Successfully queued ${result.tasksCreated} embedding tasks for ${result.totalAssets} assets.`,
|
||||
)
|
||||
if (result.skippedTeams.length > 0) {
|
||||
console.warn(
|
||||
`⚠️ Skipped ${result.skippedTeams.length} team(s) without an active embedding agent.`,
|
||||
)
|
||||
}
|
||||
console.log('The background workers will process the embedding tasks.')
|
||||
process.exit(0)
|
||||
} catch (err: unknown) {
|
||||
const message = err instanceof Error ? err.message : 'Unknown error'
|
||||
console.error(`Error: ${message}`)
|
||||
process.exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
async function run() {
|
||||
// Initialize workflows and activities for local executor mode
|
||||
initAgentWorkflows()
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
services:
|
||||
postgres:
|
||||
image: docker.m.daocloud.io/pgvector/pgvector:pg18
|
||||
container_name: shumai_postgres
|
||||
environment:
|
||||
POSTGRES_USER: shumai
|
||||
POSTGRES_PASSWORD: shumai_password
|
||||
POSTGRES_DB: shumai_db
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/18/docker
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'pg_isready -U shumai -d shumai_db']
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
embedding-server:
|
||||
image: shumaione/embedding-server:latest
|
||||
container_name: shumai_embedding
|
||||
restart: unless-stopped
|
||||
|
||||
shumai:
|
||||
image: crpi-000nkafzu6xvpwsc.cn-hongkong.personal.cr.aliyuncs.com/shumai-one/shumai:latest
|
||||
cap_add:
|
||||
- SYS_ADMIN
|
||||
security_opt:
|
||||
- apparmor=unconfined
|
||||
- seccomp=unconfined
|
||||
container_name: shumai_app
|
||||
ports:
|
||||
- '3000:3000'
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
# Hardware Acceleration (NVENC / QuickSync / VA-API / RKMPP)
|
||||
# Uncomment the extends section below for hardware acceleration:
|
||||
# extends:
|
||||
# file: hwaccel.transcoding.yaml
|
||||
# service: cpu # set to one of [nvenc, quicksync, rkmpp, vaapi, vaapi-wsl] for accelerated transcoding
|
||||
environment:
|
||||
# Database Configuration
|
||||
DATABASE_URL: postgres://shumai:shumai_password@shumai_postgres:5432/shumai_db?search_path=public&sslmode=disable
|
||||
|
||||
# Server Configuration
|
||||
SHUMAI_SERVER_PORT: 3000
|
||||
|
||||
# S3 Configuration
|
||||
STORAGE_BACKEND: local
|
||||
AWS_ENDPOINT_URL_S3: http://localhost:3000
|
||||
|
||||
# Better Auth
|
||||
BETTER_AUTH_SECRET: qSxs9DxzHDZBbeeTNPEwBuspYwipBqz5Gk5XdBjNhWw=
|
||||
|
||||
# Sandbox Configuration
|
||||
ENABLE_WEAKER_NESTED_SANDBOX: 'true'
|
||||
|
||||
# Embedding Configuration
|
||||
EMBEDDING_PROVIDER: gemma-embedding-2-openai
|
||||
GEMMA_EMBEDDING_OPENAI_BASE_URL: http://embedding-server:9379/v1
|
||||
ENABLE_EMBEDDING_AGENT: 'true'
|
||||
CONCURRENCY_AGENT: 1
|
||||
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
embedding-server:
|
||||
condition: service_started
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
@@ -0,0 +1,89 @@
|
||||
services:
|
||||
postgres:
|
||||
image: docker.m.daocloud.io/pgvector/pgvector:pg18
|
||||
container_name: shumai_postgres
|
||||
environment:
|
||||
POSTGRES_USER: shumai
|
||||
POSTGRES_PASSWORD: shumai_password
|
||||
POSTGRES_DB: shumai_db
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/18/docker
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'pg_isready -U shumai -d shumai_db']
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
embedding-server:
|
||||
image: shumaione/embedding-server:latest
|
||||
container_name: shumai_embedding
|
||||
restart: unless-stopped
|
||||
|
||||
turntable-renderer:
|
||||
image: shumaione/turntable-renderer:latest
|
||||
container_name: shumai_turntable
|
||||
restart: unless-stopped
|
||||
|
||||
gotenberg:
|
||||
image: gotenberg/gotenberg:8
|
||||
container_name: shumai_gotenberg
|
||||
restart: unless-stopped
|
||||
|
||||
shumai:
|
||||
image: crpi-000nkafzu6xvpwsc.cn-hongkong.personal.cr.aliyuncs.com/shumai-one/shumai:latest
|
||||
cap_add:
|
||||
- SYS_ADMIN
|
||||
security_opt:
|
||||
- apparmor=unconfined
|
||||
- seccomp=unconfined
|
||||
container_name: shumai_app
|
||||
ports:
|
||||
- '3000:3000'
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
# Hardware Acceleration (NVENC / QuickSync / VA-API / RKMPP)
|
||||
# Uncomment the extends section below for hardware acceleration:
|
||||
# extends:
|
||||
# file: hwaccel.transcoding.yaml
|
||||
# service: cpu # set to one of [nvenc, quicksync, rkmpp, vaapi, vaapi-wsl] for accelerated transcoding
|
||||
environment:
|
||||
# Database Configuration
|
||||
DATABASE_URL: postgres://shumai:shumai_password@shumai_postgres:5432/shumai_db?search_path=public&sslmode=disable
|
||||
|
||||
# Server Configuration
|
||||
SHUMAI_SERVER_PORT: 3000
|
||||
|
||||
# S3 Configuration
|
||||
STORAGE_BACKEND: local
|
||||
AWS_ENDPOINT_URL_S3: http://localhost:3000
|
||||
|
||||
# Better Auth
|
||||
BETTER_AUTH_SECRET: qSxs9DxzHDZBbeeTNPEwBuspYwipBqz5Gk5XdBjNhWw=
|
||||
|
||||
# Sandbox Configuration
|
||||
ENABLE_WEAKER_NESTED_SANDBOX: 'true'
|
||||
|
||||
# Embedding Configuration
|
||||
EMBEDDING_PROVIDER: gemma-embedding-2-openai
|
||||
GEMMA_EMBEDDING_OPENAI_BASE_URL: http://embedding-server:9379/v1
|
||||
ENABLE_EMBEDDING_AGENT: 'true'
|
||||
CONCURRENCY_AGENT: 1
|
||||
|
||||
# 3D Turntable Renderer Configuration
|
||||
TURNTABLE_RENDERER_URL: http://turntable-renderer:3000
|
||||
|
||||
# Gotenberg Document Converter Configuration
|
||||
GOTENBERG_URL: http://gotenberg:3000
|
||||
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
embedding-server:
|
||||
condition: service_started
|
||||
turntable-renderer:
|
||||
condition: service_started
|
||||
gotenberg:
|
||||
condition: service_started
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
@@ -0,0 +1,69 @@
|
||||
services:
|
||||
postgres:
|
||||
image: pgvector/pgvector:pg18
|
||||
container_name: shumai_postgres
|
||||
environment:
|
||||
POSTGRES_USER: shumai
|
||||
POSTGRES_PASSWORD: shumai_password
|
||||
POSTGRES_DB: shumai_db
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/18/docker
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'pg_isready -U shumai -d shumai_db']
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
embedding-server:
|
||||
image: shumaione/embedding-server:latest
|
||||
container_name: shumai_embedding
|
||||
restart: unless-stopped
|
||||
|
||||
shumai:
|
||||
image: shumaione/shumai:latest
|
||||
cap_add:
|
||||
- SYS_ADMIN
|
||||
security_opt:
|
||||
- apparmor=unconfined
|
||||
- seccomp=unconfined
|
||||
container_name: shumai_app
|
||||
ports:
|
||||
- '3000:3000'
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
# Hardware Acceleration (NVENC / QuickSync / VA-API / RKMPP)
|
||||
# Uncomment the extends section below for hardware acceleration:
|
||||
# extends:
|
||||
# file: hwaccel.transcoding.yaml
|
||||
# service: cpu # set to one of [nvenc, quicksync, rkmpp, vaapi, vaapi-wsl] for accelerated transcoding
|
||||
environment:
|
||||
# Database Configuration
|
||||
DATABASE_URL: postgres://shumai:shumai_password@shumai_postgres:5432/shumai_db?search_path=public&sslmode=disable
|
||||
|
||||
# Server Configuration
|
||||
SHUMAI_SERVER_PORT: 3000
|
||||
|
||||
# S3 Configuration
|
||||
STORAGE_BACKEND: local
|
||||
AWS_ENDPOINT_URL_S3: http://localhost:3000
|
||||
|
||||
# Better Auth
|
||||
BETTER_AUTH_SECRET: qSxs9DxzHDZBbeeTNPEwBuspYwipBqz5Gk5XdBjNhWw=
|
||||
|
||||
# Sandbox Configuration
|
||||
ENABLE_WEAKER_NESTED_SANDBOX: 'true'
|
||||
|
||||
# Embedding Configuration
|
||||
EMBEDDING_PROVIDER: gemma-embedding-2-openai
|
||||
GEMMA_EMBEDDING_OPENAI_BASE_URL: http://embedding-server:9379/v1
|
||||
ENABLE_EMBEDDING_AGENT: 'true'
|
||||
CONCURRENCY_AGENT: 1
|
||||
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
embedding-server:
|
||||
condition: service_started
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
@@ -0,0 +1,89 @@
|
||||
services:
|
||||
postgres:
|
||||
image: pgvector/pgvector:pg18
|
||||
container_name: shumai_postgres
|
||||
environment:
|
||||
POSTGRES_USER: shumai
|
||||
POSTGRES_PASSWORD: shumai_password
|
||||
POSTGRES_DB: shumai_db
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/18/docker
|
||||
healthcheck:
|
||||
test: ['CMD-SHELL', 'pg_isready -U shumai -d shumai_db']
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 5
|
||||
|
||||
embedding-server:
|
||||
image: shumaione/embedding-server:latest
|
||||
container_name: shumai_embedding
|
||||
restart: unless-stopped
|
||||
|
||||
turntable-renderer:
|
||||
image: shumaione/turntable-renderer:latest
|
||||
container_name: shumai_turntable
|
||||
restart: unless-stopped
|
||||
|
||||
gotenberg:
|
||||
image: gotenberg/gotenberg:8
|
||||
container_name: shumai_gotenberg
|
||||
restart: unless-stopped
|
||||
|
||||
shumai:
|
||||
image: shumaione/shumai:latest
|
||||
cap_add:
|
||||
- SYS_ADMIN
|
||||
security_opt:
|
||||
- apparmor=unconfined
|
||||
- seccomp=unconfined
|
||||
container_name: shumai_app
|
||||
ports:
|
||||
- '3000:3000'
|
||||
volumes:
|
||||
- ./data:/app/data
|
||||
# Hardware Acceleration (NVENC / QuickSync / VA-API / RKMPP)
|
||||
# Uncomment the extends section below for hardware acceleration:
|
||||
# extends:
|
||||
# file: hwaccel.transcoding.yaml
|
||||
# service: cpu # set to one of [nvenc, quicksync, rkmpp, vaapi, vaapi-wsl] for accelerated transcoding
|
||||
environment:
|
||||
# Database Configuration
|
||||
DATABASE_URL: postgres://shumai:shumai_password@shumai_postgres:5432/shumai_db?search_path=public&sslmode=disable
|
||||
|
||||
# Server Configuration
|
||||
SHUMAI_SERVER_PORT: 3000
|
||||
|
||||
# S3 Configuration
|
||||
STORAGE_BACKEND: local
|
||||
AWS_ENDPOINT_URL_S3: http://localhost:3000
|
||||
|
||||
# Better Auth
|
||||
BETTER_AUTH_SECRET: qSxs9DxzHDZBbeeTNPEwBuspYwipBqz5Gk5XdBjNhWw=
|
||||
|
||||
# Sandbox Configuration
|
||||
ENABLE_WEAKER_NESTED_SANDBOX: 'true'
|
||||
|
||||
# Embedding Configuration
|
||||
EMBEDDING_PROVIDER: gemma-embedding-2-openai
|
||||
GEMMA_EMBEDDING_OPENAI_BASE_URL: http://embedding-server:9379/v1
|
||||
ENABLE_EMBEDDING_AGENT: 'true'
|
||||
CONCURRENCY_AGENT: 1
|
||||
|
||||
# 3D Turntable Renderer Configuration
|
||||
TURNTABLE_RENDERER_URL: http://turntable-renderer:3000
|
||||
|
||||
# Gotenberg Document Converter Configuration
|
||||
GOTENBERG_URL: http://gotenberg:3000
|
||||
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
embedding-server:
|
||||
condition: service_started
|
||||
turntable-renderer:
|
||||
condition: service_started
|
||||
gotenberg:
|
||||
condition: service_started
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
@@ -66,12 +66,24 @@ For example, if you deploy Shumai on a remote server at `http://123.456.7.8` and
|
||||
|
||||
Configures whether background transcoding and AI agents are executed locally or offloaded to a Temporal cluster.
|
||||
|
||||
| Variable | Description | Example / Default |
|
||||
| :------------------------- | :------------------------------------------------------------------------------------------------- | :------------------------------ |
|
||||
| `WORKFLOW_EXECUTOR` | Engine choice. Use `local` for in-process database polling, or `temporal` for distributed workers. | `local` (default) or `temporal` |
|
||||
| `TEMPORAL_ADDRESS` | Host and port of the Temporal cluster gRPC service. | `localhost:7233` (default) |
|
||||
| `EMBEDDING_CHUNK_DURATION` | The duration in seconds for each video chunk when generating video embeddings. | `60.0` (default) |
|
||||
| `EMBEDDING_CHUNK_OVERLAP` | The duration in seconds to overlap video chunks when generating video embeddings. | `5.0` (default) |
|
||||
| Variable | Description | Example / Default |
|
||||
| :---------------------- | :------------------------------------------------------------------------------------------------- | :------------------------------ |
|
||||
| `WORKFLOW_EXECUTOR` | Engine choice. Use `local` for in-process database polling, or `temporal` for distributed workers. | `local` (default) or `temporal` |
|
||||
| `TEMPORAL_ADDRESS` | Host and port of the Temporal cluster gRPC service. | `localhost:7233` (default) |
|
||||
| `CONCURRENCY_AGENT` | Maximum concurrent AI tasks executed by workers. Set to `1` when running local `embedding-server`. | `5` (default) |
|
||||
| `CONCURRENCY_TRANSCODE` | Maximum concurrent media transcoding tasks executed by workers. | `1` (default) |
|
||||
|
||||
---
|
||||
|
||||
## Embedding Config
|
||||
|
||||
| Variable | Description | Example / Default |
|
||||
| :-------------------------------- | :------------------------------------------------------------------------------------------------------------ | :-------------------------------- |
|
||||
| `EMBEDDING_PROVIDER` | Multimodal embedding provider. Options: `gemini-embedding-2`, `gemma-embedding-2-openai`. | `gemini-embedding-2` (default) |
|
||||
| `GEMMA_EMBEDDING_OPENAI_BASE_URL` | Base URL of the OpenAI-compatible LiteRT-LM embedding server. | `http://embedding-server:9379/v1` |
|
||||
| `ENABLE_EMBEDDING_AGENT` | When set to `true`, automatically provisions and enables the system embedding agent for all teams on startup. | `false` (default) |
|
||||
| `EMBEDDING_CHUNK_DURATION` | The duration in seconds for each video chunk when generating video embeddings. | `60.0` (default) |
|
||||
| `EMBEDDING_CHUNK_OVERLAP` | The duration in seconds to overlap video chunks when generating video embeddings. | `5.0` (default) |
|
||||
|
||||
## Sandbox Config
|
||||
|
||||
|
||||
+2
-1
@@ -45,7 +45,8 @@
|
||||
"using-shumai/share-links",
|
||||
"using-shumai/nle-and-premiere",
|
||||
"using-shumai/3d-asset-support",
|
||||
"using-shumai/gotenberg"
|
||||
"using-shumai/gotenberg",
|
||||
"using-shumai/embedding-server"
|
||||
]
|
||||
},
|
||||
{
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
---
|
||||
title: Embedding Server Setup (EmbeddingGemma 2)
|
||||
description: Run local, offline multimodal vector embeddings for semantic search using shumaiOne/embedding-server.
|
||||
---
|
||||
|
||||
Shumai supports local, self-hosted multimodal vector embeddings for semantic search through [shumaiOne/embedding-server](https://github.com/shumaiOne/embedding-server) — a standalone Docker service powered by Google AI Edge's **LiteRT-LM** and **EmbeddingGemma 2 740M**.
|
||||
|
||||
The embedding server provides a unified 768-dimensional vector space across text, images, and video frames with an OpenAI-compatible HTTP API (`/v1/embeddings`). Because the model weights are pre-baked directly into the Docker image, the server operates completely offline and air-gapped without requiring external network access or third-party cloud API keys.
|
||||
|
||||
---
|
||||
|
||||
## Model Architecture & Specs
|
||||
|
||||
| Property | Value |
|
||||
| :------------------------ | :------------------------------------------------------- |
|
||||
| **Model** | `EmbeddingGemma 2 740M` (`google/embeddinggemma-2-740m`) |
|
||||
| **Runtime** | Google AI Edge LiteRT-LM (Python 3.14 Debian slim) |
|
||||
| **Vector Dimensionality** | 768 dimensions (multimodal: text, image, and video) |
|
||||
| **Context Window** | 2,048 tokens |
|
||||
| **Network Mode** | Completely offline capable (`--network none`) |
|
||||
| **API Standard** | OpenAI-compatible `/v1/embeddings` |
|
||||
|
||||
---
|
||||
|
||||
## Video Processing & Sampling
|
||||
|
||||
For video assets, Shumai breaks videos into standardized segments and extracts keyframes:
|
||||
|
||||
- **Chunking**: Videos are divided into **60-second chunks** with a **5-second overlap** at segment boundaries to preserve narrative and visual context.
|
||||
- **Frame Extraction Rate**: Shumai extracts **15 frames per minute** from each chunk.
|
||||
- **Adaptive Frame Bounding**:
|
||||
- For standard aspect ratios (1:1, 4:3, 3:4, 16:9, 9:16, 21:9), Shumai extracts 15 frames, which produces ~1,982 prompt tokens and stays safely within the 2,048-token context window.
|
||||
- For non-standard or custom aspect ratios (e.g. 5:3, 1.4:1), Shumai automatically samples 14 frames (~1,990 tokens) to mathematically guarantee that prompt length never exceeds 2,048 tokens, preventing out-of-memory errors on the embedding server.
|
||||
|
||||
---
|
||||
|
||||
## Important: Changing Embedding Providers Breaks Existing Embeddings
|
||||
|
||||
> [!WARNING]
|
||||
> **Vector spaces from different embedding models are completely incompatible.**
|
||||
>
|
||||
> If you change your embedding provider (for example, switching from Google Gemini's 1536-dimensional embeddings to EmbeddingGemma's 768-dimensional embeddings, or vice versa), **all existing vector embeddings in your database become invalid**.
|
||||
>
|
||||
> To protect production databases from accidental corruption and search failures, **Shumai intentionally does not provide a WebUI toggle to change the embedding provider**. The provider can only be configured by an administrator via environment variables (`EMBEDDING_PROVIDER` and `GEMMA_EMBEDDING_OPENAI_BASE_URL`).
|
||||
|
||||
---
|
||||
|
||||
## Regenerating Embeddings via CLI
|
||||
|
||||
When you do switch embedding providers or configure the embedding server on an existing Shumai deployment, you can regenerate embeddings for all existing media files using the administrative CLI command:
|
||||
|
||||
### Inside Docker
|
||||
|
||||
```bash
|
||||
docker exec -it <shumai-container-name> shumai regenerate-embeddings
|
||||
```
|
||||
|
||||
### Local / Bare Metal
|
||||
|
||||
```bash
|
||||
shumai regenerate-embeddings
|
||||
```
|
||||
|
||||
_(Alternatively, `bun apps/web/src/index.ts regenerate-embeddings`)_
|
||||
|
||||
### What the Command Does
|
||||
|
||||
1. **Scans Teams**: Checks all teams in your workspace. If a team does not have an active (enabled) embedding agent, it logs a warning and safely skips that team.
|
||||
2. **Clears Existing Embeddings**: Purges all previous embeddings and cancels any pending/in-progress embedding tasks for eligible assets to ensure a clean transition to the new provider.
|
||||
3. **Enqueues Fresh Tasks**: Queues new background `ai_embedding` tasks for all eligible assets (images, videos, and 3D assets with rendered previews) across active teams.
|
||||
4. **Background Execution**: Background workers process the queued tasks according to your configured concurrency limits.
|
||||
|
||||
---
|
||||
|
||||
## Deployment & Configuration
|
||||
|
||||
### Docker Quickstart
|
||||
|
||||
To run the standalone embedding server container:
|
||||
|
||||
```bash
|
||||
docker run -d \
|
||||
--name shumai_embedding \
|
||||
-p 9379:9379 \
|
||||
shumaione/embedding-server:latest
|
||||
```
|
||||
|
||||
### Docker Compose Setup
|
||||
|
||||
In Docker Compose environments, add `embedding-server` to your `docker-compose.yaml` and configure Shumai to connect to it over Docker's internal network:
|
||||
|
||||
```yaml
|
||||
services:
|
||||
embedding-server:
|
||||
image: shumaione/embedding-server:latest
|
||||
container_name: shumai_embedding
|
||||
restart: unless-stopped
|
||||
|
||||
shumai:
|
||||
image: shumaione/shumai:latest
|
||||
environment:
|
||||
# Embedding Server Configuration
|
||||
EMBEDDING_PROVIDER: gemma-embedding-2-openai
|
||||
GEMMA_EMBEDDING_OPENAI_BASE_URL: http://embedding-server:9379/v1
|
||||
ENABLE_EMBEDDING_AGENT: 'true'
|
||||
CONCURRENCY_AGENT: 1
|
||||
depends_on:
|
||||
- embedding-server
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> Since Shumai communicates with `embedding-server` over Docker's internal network, `embedding-server` does not need to expose any ports to the host machine.
|
||||
|
||||
### Environment Variables
|
||||
|
||||
| Variable | Required | Description | Default |
|
||||
| :-------------------------------- | :---------- | :---------------------------------------------------------------------------------------------------------------------------- | :------------------------- |
|
||||
| `EMBEDDING_PROVIDER` | Yes | Set to `gemma-embedding-2-openai` to use the local LiteRT-LM server. | `gemini-embedding-2` |
|
||||
| `GEMMA_EMBEDDING_OPENAI_BASE_URL` | Yes | HTTP base URL of the embedding server (e.g. `http://embedding-server:9379/v1`). | `http://localhost:9379/v1` |
|
||||
| `ENABLE_EMBEDDING_AGENT` | No | Automatically provisions and enables the system embedding agent for all teams on startup. | `false` |
|
||||
| `CONCURRENCY_AGENT` | Recommended | Maximum concurrent AI tasks executed by workers. **Set to `1`** when running `embedding-server` to prevent high memory usage. | `5` |
|
||||
|
||||
---
|
||||
|
||||
## Hardware & Resource Requirements
|
||||
|
||||
- **Memory (RAM)**:
|
||||
- We recommend at least **4 GB+ of dedicated system RAM** for the `embedding-server` container.
|
||||
- Overall host system memory should be **4 GB+** when running the Lite+Embedding compose stack, and **8 GB+** for the full stack.
|
||||
- **Concurrency**:
|
||||
- Always set `CONCURRENCY_AGENT=1` in your Shumai configuration when using `embedding-server`. Parallel multimodal embedding generations consume significant memory and can cause Docker containers to be terminated by the OS Out-Of-Memory (OOM) killer on low-resource machines.
|
||||
@@ -12,11 +12,10 @@ Traditional search relies on matching exact characters (e.g., searching "dog" wi
|
||||
Semantic search translates text queries and file contents into conceptual profiles. Similar ideas and visuals are mapped near each other.
|
||||
|
||||
1. **Index Generation**: When you upload an asset, Shumai's background agent scans the file's visual elements, text contents, or descriptions, translating them into a concept profile.
|
||||
- **Video Processing**: Shumai uses **gemini-embedding-2** for video indexing.
|
||||
- **Chunking**: For long videos, Shumai breaks them into chunks to ensure high-quality indexing. By default, chunks are **60 seconds** long with a **5-second overlap** to ensure no context is lost at the boundaries.
|
||||
- **Sampling**: The model processes a maximum of 32 frames per chunk: short chunks (≤32s) are sampled at 1 fps, while longer chunks are uniformly sampled to 32 frames.
|
||||
- **Optimization**: To optimize processing, Shumai automatically transcodes each chunk to **1 FPS** and **removes the audio track** before sending it to the embedding agent.
|
||||
- **Configuration**: Administrators can customize these settings using the `EMBEDDING_CHUNK_DURATION` and `EMBEDDING_CHUNK_OVERLAP` environment variables.
|
||||
- **Multimodal Embedding Providers**: Shumai supports two embedding providers:
|
||||
- **EmbeddingGemma 2 (Local)**: Powered by `shumaiOne/embedding-server` with 768-dimensional multimodal vectors running completely offline. Videos are sampled at **15 frames per minute** (14 frames for non-standard aspect ratios) per 60-second chunk. See the [Embedding Server Setup Guide](./embedding-server) for full details.
|
||||
- **Gemini Embedding 2 (Cloud)**: Powered by Google's `gemini-embedding-2` API with 1536-dimensional vectors. Videos are chunked into 60-second segments (sampled up to 32 frames per chunk at 1 fps with audio stripped).
|
||||
- **Chunking Configuration**: Administrators can customize chunk duration and overlap using the `EMBEDDING_CHUNK_DURATION` (default: 60s) and `EMBEDDING_CHUNK_OVERLAP` (default: 5s) environment variables.
|
||||
2. **Concept Matching**: When you search with the "Semantic" toggle enabled, Shumai matches the conceptual meaning of your query against your assets.
|
||||
3. **Result**: Searching "sunset at the beach" will successfully find a video file of ocean waves at dusk, even if the filename is `IMG_4029.mp4`.
|
||||
|
||||
|
||||
@@ -663,6 +663,18 @@ describe('AI Database Activities Integration', () => {
|
||||
expect(ctx.agent.id).toBe(user.id)
|
||||
expect(ctx.asset.id).toBe(asset.id)
|
||||
expect(ctx.asset.mediaType).toBe('video/mp4')
|
||||
|
||||
process.env.ENABLE_EMBEDDING_AGENT = 'false'
|
||||
try {
|
||||
await expect(
|
||||
getEmbeddingContextActivity({
|
||||
teamId: team.id,
|
||||
assetId: asset.id,
|
||||
}),
|
||||
).rejects.toThrow('embedding feature is disabled or agent not found')
|
||||
} finally {
|
||||
delete process.env.ENABLE_EMBEDDING_AGENT
|
||||
}
|
||||
})
|
||||
|
||||
it('should parse valid positive chunk duration and fallback on invalid or negative ones', async () => {
|
||||
|
||||
@@ -224,7 +224,7 @@ export async function getEmbeddingContextActivity(params: { teamId: string; asse
|
||||
user: { teamMembers: { some: { teamId: params.teamId } } },
|
||||
},
|
||||
})
|
||||
if (!agent) {
|
||||
if (!agent || process.env.ENABLE_EMBEDDING_AGENT === 'false') {
|
||||
throw ApplicationFailure.create({
|
||||
message: 'embedding feature is disabled or agent not found',
|
||||
nonRetryable: true,
|
||||
|
||||
@@ -526,5 +526,86 @@ describe('Agent API', () => {
|
||||
expect(res.status).toBe(403)
|
||||
expect(agentService.updateAgentPermission).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects POST /teams/:teamId/agents with 403 for embedding agent', async () => {
|
||||
const res = await app.request('/teams/team1/agents', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'Manual Embedding',
|
||||
type: 'embedding',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(agentService.createAgent).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('read-only embedding agent when ENABLE_EMBEDDING_AGENT is false', () => {
|
||||
beforeEach(() => {
|
||||
process.env.ENABLE_EMBEDDING_AGENT = 'false'
|
||||
vi.mocked(agentService.getAgent).mockResolvedValue({
|
||||
id: 'emb1',
|
||||
teamId: 'team1',
|
||||
type: 'embedding',
|
||||
} as unknown as Awaited<ReturnType<typeof agentService.getAgent>>)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env.ENABLE_EMBEDDING_AGENT
|
||||
})
|
||||
|
||||
it('rejects PUT /agents/:agentId with 403', async () => {
|
||||
const res = await app.request('/agents/emb1', {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'Updated Embedding',
|
||||
type: 'embedding',
|
||||
enabled: false,
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(agentService.updateAgent).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects DELETE /agents/:agentId with 403', async () => {
|
||||
const res = await app.request('/agents/emb1', {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(agentService.deleteAgent).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects PATCH /agents/:agentId/permission with 403', async () => {
|
||||
const res = await app.request('/agents/emb1/permission', {
|
||||
method: 'PATCH',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
permission: 'owner',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(agentService.updateAgentPermission).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('rejects POST /teams/:teamId/agents with 403 for embedding agent', async () => {
|
||||
const res = await app.request('/teams/team1/agents', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({
|
||||
name: 'Manual Embedding',
|
||||
type: 'embedding',
|
||||
}),
|
||||
})
|
||||
|
||||
expect(res.status).toBe(403)
|
||||
expect(agentService.createAgent).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -63,6 +63,16 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
id: teamId,
|
||||
})
|
||||
|
||||
const isEmbeddingManagedByEnv =
|
||||
process.env.ENABLE_EMBEDDING_AGENT === 'true' ||
|
||||
process.env.ENABLE_EMBEDDING_AGENT === 'false'
|
||||
|
||||
if (req.type === 'embedding' && isEmbeddingManagedByEnv) {
|
||||
throw new HTTPException(403, {
|
||||
message: 'Embedding agent is managed by environment configuration and cannot be created',
|
||||
})
|
||||
}
|
||||
|
||||
const agent = await agentService.createAgent({
|
||||
teamId,
|
||||
...req,
|
||||
@@ -93,8 +103,12 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
id: agentId,
|
||||
})
|
||||
|
||||
const isEmbeddingManagedByEnv =
|
||||
process.env.ENABLE_EMBEDDING_AGENT === 'true' ||
|
||||
process.env.ENABLE_EMBEDDING_AGENT === 'false'
|
||||
|
||||
const existingAgent = await agentService.getAgent({ agentId })
|
||||
if (existingAgent?.type === 'embedding' && process.env.ENABLE_EMBEDDING_AGENT === 'true') {
|
||||
if (existingAgent?.type === 'embedding' && isEmbeddingManagedByEnv) {
|
||||
throw new HTTPException(403, {
|
||||
message: 'Embedding agent is managed by environment configuration and cannot be modified',
|
||||
})
|
||||
@@ -131,8 +145,12 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
id: agentId,
|
||||
})
|
||||
|
||||
const isEmbeddingManagedByEnv =
|
||||
process.env.ENABLE_EMBEDDING_AGENT === 'true' ||
|
||||
process.env.ENABLE_EMBEDDING_AGENT === 'false'
|
||||
|
||||
const existingAgent = await agentService.getAgent({ agentId })
|
||||
if (existingAgent?.type === 'embedding' && process.env.ENABLE_EMBEDDING_AGENT === 'true') {
|
||||
if (existingAgent?.type === 'embedding' && isEmbeddingManagedByEnv) {
|
||||
throw new HTTPException(403, {
|
||||
message: 'Embedding agent is managed by environment configuration and cannot be modified',
|
||||
})
|
||||
@@ -163,8 +181,12 @@ const route = new Hono<{ Variables: { user: User } }>()
|
||||
id: agentId,
|
||||
})
|
||||
|
||||
const isEmbeddingManagedByEnv =
|
||||
process.env.ENABLE_EMBEDDING_AGENT === 'true' ||
|
||||
process.env.ENABLE_EMBEDDING_AGENT === 'false'
|
||||
|
||||
const existingAgent = await agentService.getAgent({ agentId })
|
||||
if (existingAgent?.type === 'embedding' && process.env.ENABLE_EMBEDDING_AGENT === 'true') {
|
||||
if (existingAgent?.type === 'embedding' && isEmbeddingManagedByEnv) {
|
||||
throw new HTTPException(403, {
|
||||
message: 'Embedding agent is managed by environment configuration and cannot be deleted',
|
||||
})
|
||||
|
||||
@@ -1044,7 +1044,7 @@ describe('AgentService', () => {
|
||||
}
|
||||
})
|
||||
|
||||
test('does nothing when ENABLE_EMBEDDING_AGENT is false or not set', async () => {
|
||||
test('does nothing when ENABLE_EMBEDDING_AGENT is not set', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
const team = await db.team.create({ data: { name: 'Team No Agent' } })
|
||||
@@ -1056,5 +1056,91 @@ describe('AgentService', () => {
|
||||
})
|
||||
expect(agent).toBeNull()
|
||||
})
|
||||
|
||||
test('does not create embedding agent when ENABLE_EMBEDDING_AGENT is false and agent does not exist', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
const { team } = await setupTestData(db)
|
||||
|
||||
process.env.ENABLE_EMBEDDING_AGENT = 'false'
|
||||
try {
|
||||
await svc.ensureEmbeddingAgentForTeam(team.id)
|
||||
const agent = await db.agent.findFirst({
|
||||
where: { teamId: team.id, type: 'embedding' },
|
||||
})
|
||||
expect(agent).toBeNull()
|
||||
} finally {
|
||||
delete process.env.ENABLE_EMBEDDING_AGENT
|
||||
}
|
||||
})
|
||||
|
||||
test('disables existing embedding agent and marks readOnly: true when ENABLE_EMBEDDING_AGENT is false', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
const { team } = await setupTestData(db)
|
||||
|
||||
const bot = await db.user.create({
|
||||
data: { name: 'Existing Embedding', email: 'existing-emb-false@shumai.ai', type: 'agent' },
|
||||
})
|
||||
await db.agent.create({
|
||||
data: {
|
||||
id: bot.id,
|
||||
teamId: team.id,
|
||||
type: 'embedding',
|
||||
enabled: true,
|
||||
config: { provider: '', model: '' },
|
||||
},
|
||||
})
|
||||
|
||||
process.env.ENABLE_EMBEDDING_AGENT = 'false'
|
||||
try {
|
||||
await svc.ensureEmbeddingAgentForTeam(team.id)
|
||||
const agent = await db.agent.findFirst({
|
||||
where: { teamId: team.id, type: 'embedding' },
|
||||
include: { user: true, skills: { include: { skill: true } }, mcpServers: true },
|
||||
})
|
||||
expect(agent?.id).toBe(bot.id)
|
||||
expect(agent?.enabled).toBe(false)
|
||||
const info = await svc.toAgentInfo(agent!)
|
||||
expect(info.readOnly).toBe(true)
|
||||
expect(info.enabled).toBe(false)
|
||||
} finally {
|
||||
delete process.env.ENABLE_EMBEDDING_AGENT
|
||||
}
|
||||
})
|
||||
|
||||
test('ensureSystemEmbeddingAgents updates all teams when ENABLE_EMBEDDING_AGENT is false', async () => {
|
||||
const db = prisma
|
||||
const svc = new AgentService()
|
||||
const { team: team1 } = await setupTestData(db)
|
||||
const team2 = await db.team.create({ data: { name: 'Team 2' } })
|
||||
|
||||
// Create enabled embedding agent on team1
|
||||
const bot1 = await db.user.create({
|
||||
data: { name: 'Bot 1', email: 'b1-false@shumai.ai', type: 'agent' },
|
||||
})
|
||||
await db.agent.create({
|
||||
data: {
|
||||
id: bot1.id,
|
||||
teamId: team1.id,
|
||||
type: 'embedding',
|
||||
enabled: true,
|
||||
config: { provider: '', model: '' },
|
||||
},
|
||||
})
|
||||
|
||||
process.env.ENABLE_EMBEDDING_AGENT = 'false'
|
||||
try {
|
||||
await svc.ensureSystemEmbeddingAgents()
|
||||
|
||||
const a1 = await db.agent.findFirst({ where: { teamId: team1.id, type: 'embedding' } })
|
||||
const a2 = await db.agent.findFirst({ where: { teamId: team2.id, type: 'embedding' } })
|
||||
|
||||
expect(a1?.enabled).toBe(false)
|
||||
expect(a2).toBeNull()
|
||||
} finally {
|
||||
delete process.env.ENABLE_EMBEDDING_AGENT
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -462,7 +462,10 @@ export class AgentService {
|
||||
*/
|
||||
async toAgentInfo(agent: AgentInfoSource): Promise<AgentInfo> {
|
||||
const config = agent.config as unknown as PrismaJson.AgentConfig
|
||||
const isReadOnly = agent.type === 'embedding' && process.env.ENABLE_EMBEDDING_AGENT === 'true'
|
||||
const isManagedByEnv =
|
||||
process.env.ENABLE_EMBEDDING_AGENT === 'true' ||
|
||||
process.env.ENABLE_EMBEDDING_AGENT === 'false'
|
||||
const isReadOnly = agent.type === 'embedding' && isManagedByEnv
|
||||
|
||||
return {
|
||||
id: agent.id,
|
||||
@@ -723,7 +726,8 @@ export class AgentService {
|
||||
}
|
||||
|
||||
async ensureSystemEmbeddingAgents(): Promise<void> {
|
||||
if (process.env.ENABLE_EMBEDDING_AGENT !== 'true') {
|
||||
const envVal = process.env.ENABLE_EMBEDDING_AGENT
|
||||
if (envVal !== 'true' && envVal !== 'false') {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -737,7 +741,8 @@ export class AgentService {
|
||||
}
|
||||
|
||||
async ensureEmbeddingAgentForTeam(teamId: string): Promise<void> {
|
||||
if (process.env.ENABLE_EMBEDDING_AGENT !== 'true') {
|
||||
const envVal = process.env.ENABLE_EMBEDDING_AGENT
|
||||
if (envVal !== 'true' && envVal !== 'false') {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -748,20 +753,29 @@ export class AgentService {
|
||||
},
|
||||
})
|
||||
|
||||
if (!existing) {
|
||||
await this.createAgent({
|
||||
teamId,
|
||||
name: 'embedding-agent',
|
||||
type: 'embedding',
|
||||
avatar: 'avatar-1',
|
||||
thinkingLevel: 'off',
|
||||
enabled: true,
|
||||
})
|
||||
} else if (!existing.enabled) {
|
||||
await this.prismaClient.agent.update({
|
||||
where: { id: existing.id },
|
||||
data: { enabled: true },
|
||||
})
|
||||
if (envVal === 'true') {
|
||||
if (!existing) {
|
||||
await this.createAgent({
|
||||
teamId,
|
||||
name: 'embedding-agent',
|
||||
type: 'embedding',
|
||||
avatar: 'avatar-1',
|
||||
thinkingLevel: 'off',
|
||||
enabled: true,
|
||||
})
|
||||
} else if (!existing.enabled) {
|
||||
await this.prismaClient.agent.update({
|
||||
where: { id: existing.id },
|
||||
data: { enabled: true },
|
||||
})
|
||||
}
|
||||
} else if (envVal === 'false') {
|
||||
if (existing && existing.enabled) {
|
||||
await this.prismaClient.agent.update({
|
||||
where: { id: existing.id },
|
||||
data: { enabled: false },
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,7 @@ export * from './provider/provider'
|
||||
export * from './s3/s3'
|
||||
export * from './search/search'
|
||||
export * from './search/text-embedding'
|
||||
export * from './search/embedding-service'
|
||||
export * from './share/share'
|
||||
export * from './skill/skill'
|
||||
export * from './team/team'
|
||||
|
||||
@@ -0,0 +1,256 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { prisma, AssetType, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
|
||||
import { setupTestDbHooks } from '@shumai/db/test'
|
||||
import { agentService } from '@shumai/core/src/agent/agent'
|
||||
import { embeddingService } from './embedding-service'
|
||||
|
||||
describe('EmbeddingService', () => {
|
||||
setupTestDbHooks()
|
||||
|
||||
it('should skip teams without an enabled embedding agent', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Team Without Agent' },
|
||||
})
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Project 1', teamId: team.id },
|
||||
})
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
name: 'video.mp4',
|
||||
type: AssetType.file,
|
||||
status: 'processed',
|
||||
mediaType: 'video/mp4',
|
||||
projectId: project.id,
|
||||
},
|
||||
})
|
||||
|
||||
const result = await embeddingService.regenerateEmbeddings()
|
||||
expect(result.tasksCreated).toBe(0)
|
||||
expect(result.totalAssets).toBe(0)
|
||||
expect(result.skippedTeams).toContain('Team Without Agent')
|
||||
})
|
||||
|
||||
it('should skip teams where embedding agent exists but is disabled', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Team Disabled Agent' },
|
||||
})
|
||||
await agentService.createAgent({
|
||||
teamId: team.id,
|
||||
name: 'embedding-agent',
|
||||
type: 'embedding',
|
||||
avatar: 'avatar-1',
|
||||
thinkingLevel: 'off',
|
||||
enabled: false,
|
||||
})
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Project Disabled', teamId: team.id },
|
||||
})
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
name: 'photo.jpg',
|
||||
type: AssetType.file,
|
||||
status: 'processed',
|
||||
mediaType: 'image/jpeg',
|
||||
projectId: project.id,
|
||||
},
|
||||
})
|
||||
|
||||
const result = await embeddingService.regenerateEmbeddings()
|
||||
expect(result.tasksCreated).toBe(0)
|
||||
expect(result.totalAssets).toBe(0)
|
||||
expect(result.skippedTeams).toContain('Team Disabled Agent')
|
||||
})
|
||||
|
||||
it('should regenerate embeddings for eligible media assets and clean up old data', async () => {
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Active Embedding Team' },
|
||||
})
|
||||
const agent = await agentService.createAgent({
|
||||
teamId: team.id,
|
||||
name: 'embedding-agent',
|
||||
type: 'embedding',
|
||||
avatar: 'avatar-1',
|
||||
thinkingLevel: 'off',
|
||||
enabled: true,
|
||||
})
|
||||
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Active Project', teamId: team.id },
|
||||
})
|
||||
|
||||
// 1. Eligible video asset
|
||||
const videoAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'sample.mp4',
|
||||
type: AssetType.file,
|
||||
status: 'processed',
|
||||
mediaType: 'video/mp4',
|
||||
projectId: project.id,
|
||||
},
|
||||
})
|
||||
|
||||
// 2. Eligible image asset
|
||||
const imageAsset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'sample.png',
|
||||
type: AssetType.file,
|
||||
status: 'processed',
|
||||
mediaType: 'image/png',
|
||||
projectId: project.id,
|
||||
},
|
||||
})
|
||||
|
||||
// 3. Eligible 3D asset with rendered views
|
||||
const asset3d = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'model.glb',
|
||||
type: AssetType.file,
|
||||
status: 'processed',
|
||||
mediaType: 'model/gltf-binary',
|
||||
media: {
|
||||
proxyType: '3d',
|
||||
imageTranscodes: [
|
||||
{ key: 'files/3d/view.webp', format: 'webp', width: 100, height: 100, quality: 80 },
|
||||
],
|
||||
} as unknown as PrismaJson.MediaInfo,
|
||||
projectId: project.id,
|
||||
},
|
||||
})
|
||||
|
||||
// 4. Ineligible asset (non-media document)
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
name: 'document.pdf',
|
||||
type: AssetType.file,
|
||||
status: 'processed',
|
||||
mediaType: 'application/pdf',
|
||||
projectId: project.id,
|
||||
},
|
||||
})
|
||||
|
||||
// 5. Ineligible asset (trashed / deleted)
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
name: 'deleted-video.mp4',
|
||||
type: AssetType.file,
|
||||
status: 'processed',
|
||||
isDeleted: true,
|
||||
mediaType: 'video/mp4',
|
||||
projectId: project.id,
|
||||
},
|
||||
})
|
||||
|
||||
// 6. Ineligible asset (status not processed)
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
name: 'uploading.mp4',
|
||||
type: AssetType.file,
|
||||
status: 'uploading',
|
||||
mediaType: 'video/mp4',
|
||||
projectId: project.id,
|
||||
},
|
||||
})
|
||||
|
||||
// Create preexisting embeddings and workflow task for videoAsset to verify cleanup
|
||||
const dummyVec768 = `[${new Array(768).fill(0.1).join(',')}]`
|
||||
await prisma.$executeRaw`
|
||||
INSERT INTO asset_embeddings (id, asset_id, embedding_768, updated_at)
|
||||
VALUES (gen_random_uuid()::text, ${videoAsset.id}, ${dummyVec768}::vector, NOW())
|
||||
`
|
||||
await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: videoAsset.id,
|
||||
type: WorkflowTaskType.ai_embedding,
|
||||
status: WorkflowTaskStatus.processing,
|
||||
teamId: team.id,
|
||||
projectId: project.id,
|
||||
},
|
||||
})
|
||||
|
||||
const initialEmbeddings = await prisma.assetEmbedding.count({
|
||||
where: { assetId: videoAsset.id },
|
||||
})
|
||||
expect(initialEmbeddings).toBe(1)
|
||||
|
||||
// Run regeneration
|
||||
const result = await embeddingService.regenerateEmbeddings()
|
||||
|
||||
expect(result.totalAssets).toBe(3)
|
||||
expect(result.tasksCreated).toBe(3)
|
||||
expect(result.skippedTeams).not.toContain('Active Embedding Team')
|
||||
|
||||
// Verify old embeddings were wiped upfront
|
||||
const remainingEmbeddings = await prisma.assetEmbedding.count({
|
||||
where: { assetId: videoAsset.id },
|
||||
})
|
||||
expect(remainingEmbeddings).toBe(0)
|
||||
|
||||
// Verify tasks created
|
||||
const createdTasks = await prisma.workflowTask.findMany({
|
||||
where: {
|
||||
type: WorkflowTaskType.ai_embedding,
|
||||
assetId: { in: [videoAsset.id, imageAsset.id, asset3d.id] },
|
||||
},
|
||||
})
|
||||
expect(createdTasks).toHaveLength(3)
|
||||
for (const task of createdTasks) {
|
||||
expect(task.status).toBe(WorkflowTaskStatus.pending)
|
||||
expect(task.teamId).toBe(team.id)
|
||||
expect(task.projectId).toBe(project.id)
|
||||
const payload = task.payload as { agent?: { agentId?: string } }
|
||||
expect(payload?.agent?.agentId).toBe(agent!.id)
|
||||
}
|
||||
})
|
||||
|
||||
it('should handle multiple teams where only some have active embedding agents', async () => {
|
||||
// Team 1: has active agent
|
||||
const team1 = await prisma.team.create({ data: { name: 'Team One' } })
|
||||
await agentService.createAgent({
|
||||
teamId: team1.id,
|
||||
name: 'embedding-agent',
|
||||
type: 'embedding',
|
||||
avatar: 'avatar-1',
|
||||
thinkingLevel: 'off',
|
||||
enabled: true,
|
||||
})
|
||||
const project1 = await prisma.project.create({ data: { name: 'P1', teamId: team1.id } })
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
name: 'v1.mp4',
|
||||
type: AssetType.file,
|
||||
status: 'processed',
|
||||
mediaType: 'video/mp4',
|
||||
projectId: project1.id,
|
||||
},
|
||||
})
|
||||
|
||||
// Team 2: no active agent
|
||||
const team2 = await prisma.team.create({ data: { name: 'Team Two' } })
|
||||
const project2 = await prisma.project.create({ data: { name: 'P2', teamId: team2.id } })
|
||||
await prisma.asset.create({
|
||||
data: {
|
||||
name: 'v2.mp4',
|
||||
type: AssetType.file,
|
||||
status: 'processed',
|
||||
mediaType: 'video/mp4',
|
||||
projectId: project2.id,
|
||||
},
|
||||
})
|
||||
|
||||
const result = await embeddingService.regenerateEmbeddings()
|
||||
|
||||
expect(result.totalAssets).toBe(1)
|
||||
expect(result.tasksCreated).toBe(1)
|
||||
expect(result.skippedTeams).toContain('Team Two')
|
||||
expect(result.skippedTeams).not.toContain('Team One')
|
||||
|
||||
const tasks = await prisma.workflowTask.findMany({
|
||||
where: {
|
||||
type: WorkflowTaskType.ai_embedding,
|
||||
teamId: { in: [team1.id, team2.id] },
|
||||
},
|
||||
})
|
||||
expect(tasks).toHaveLength(1)
|
||||
expect(tasks[0].teamId).toBe(team1.id)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,135 @@
|
||||
import { prisma, WorkflowTaskStatus, WorkflowTaskType } from '@shumai/db'
|
||||
import { logger } from '@shumai/core/src/logger'
|
||||
|
||||
export interface RegenerateEmbeddingsResult {
|
||||
tasksCreated: number
|
||||
totalAssets: number
|
||||
skippedTeams: string[]
|
||||
}
|
||||
|
||||
export class EmbeddingService {
|
||||
/**
|
||||
* Regenerates vector embeddings across all teams.
|
||||
*
|
||||
* Skips teams that do not have an active (enabled) embedding agent and logs a warning.
|
||||
* For teams with an active embedding agent, purges existing embeddings and pending/processing
|
||||
* embedding tasks upfront, then creates fresh ai_embedding workflow tasks for all eligible assets.
|
||||
*/
|
||||
async regenerateEmbeddings(): Promise<RegenerateEmbeddingsResult> {
|
||||
const teams = await prisma.team.findMany({
|
||||
select: { id: true, name: true },
|
||||
})
|
||||
|
||||
const activeAgents = await prisma.agent.findMany({
|
||||
where: {
|
||||
type: 'embedding',
|
||||
enabled: true,
|
||||
},
|
||||
select: { id: true, teamId: true },
|
||||
})
|
||||
|
||||
const activeAgentByTeamId = new Map(
|
||||
activeAgents
|
||||
.filter((a): a is typeof a & { teamId: string } => typeof a.teamId === 'string')
|
||||
.map((a) => [a.teamId, a]),
|
||||
)
|
||||
|
||||
const activeTeamIds: string[] = []
|
||||
const skippedTeams: string[] = []
|
||||
|
||||
for (const team of teams) {
|
||||
if (activeAgentByTeamId.has(team.id)) {
|
||||
activeTeamIds.push(team.id)
|
||||
} else {
|
||||
skippedTeams.push(team.name || team.id)
|
||||
logger.warn(
|
||||
{ teamId: team.id, teamName: team.name },
|
||||
'Skipping embedding regeneration for team: no active embedding agent found',
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
if (activeTeamIds.length === 0) {
|
||||
logger.info('No teams found with an active embedding agent. 0 tasks created.')
|
||||
return { tasksCreated: 0, totalAssets: 0, skippedTeams }
|
||||
}
|
||||
|
||||
const candidateAssets = await prisma.asset.findMany({
|
||||
where: {
|
||||
isDeleted: false,
|
||||
status: 'processed',
|
||||
type: { in: ['file', 'version_stack'] },
|
||||
project: { teamId: { in: activeTeamIds } },
|
||||
},
|
||||
include: { project: true },
|
||||
})
|
||||
|
||||
const eligibleAssets = candidateAssets.filter((asset) => {
|
||||
const isVideo = asset.mediaType?.startsWith('video/')
|
||||
const mediaInfo = asset.media as PrismaJson.MediaInfo | null
|
||||
const isImage =
|
||||
asset.mediaType?.startsWith('image/') ||
|
||||
(mediaInfo?.proxyType === '3d' && (mediaInfo.imageTranscodes?.length ?? 0) > 0)
|
||||
return isVideo || isImage
|
||||
})
|
||||
|
||||
const eligibleAssetIds = eligibleAssets.map((a) => a.id)
|
||||
|
||||
if (eligibleAssetIds.length > 0) {
|
||||
// Clean up previous embedding tasks to avoid duplicate execution
|
||||
await prisma.workflowTask.deleteMany({
|
||||
where: {
|
||||
assetId: { in: eligibleAssetIds },
|
||||
type: WorkflowTaskType.ai_embedding,
|
||||
},
|
||||
})
|
||||
|
||||
// Purge existing embeddings so everything regenerates cleanly with the configured provider
|
||||
await prisma.assetEmbedding.deleteMany({
|
||||
where: {
|
||||
assetId: { in: eligibleAssetIds },
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
let tasksCreated = 0
|
||||
for (const asset of eligibleAssets) {
|
||||
const teamId = asset.project?.teamId
|
||||
if (!teamId) continue
|
||||
const agent = activeAgentByTeamId.get(teamId)
|
||||
if (!agent) continue
|
||||
|
||||
await prisma.workflowTask.create({
|
||||
data: {
|
||||
assetId: asset.id,
|
||||
type: WorkflowTaskType.ai_embedding,
|
||||
status: WorkflowTaskStatus.pending,
|
||||
teamId,
|
||||
projectId: asset.projectId,
|
||||
payload: {
|
||||
projectId: asset.projectId ?? '',
|
||||
agent: { agentId: agent.id },
|
||||
},
|
||||
},
|
||||
})
|
||||
tasksCreated++
|
||||
}
|
||||
|
||||
logger.info(
|
||||
{
|
||||
totalAssets: eligibleAssets.length,
|
||||
tasksCreated,
|
||||
skippedTeamsCount: skippedTeams.length,
|
||||
},
|
||||
'Successfully queued embedding regeneration tasks',
|
||||
)
|
||||
|
||||
return {
|
||||
tasksCreated,
|
||||
totalAssets: eligibleAssets.length,
|
||||
skippedTeams,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const embeddingService = new EmbeddingService()
|
||||
@@ -1043,6 +1043,55 @@ describe('SearchService', () => {
|
||||
|
||||
mockGenerateEmbedding.mockRestore()
|
||||
})
|
||||
|
||||
it('rejects semantic search when ENABLE_EMBEDDING_AGENT is false', async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'u-emb-false', email: 'u-emb-false@example.com', type: 'human' },
|
||||
})
|
||||
const team = await prisma.team.create({ data: { name: 't-emb-false' } })
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'p-emb-false', teamId: team.id },
|
||||
})
|
||||
const rootFolder = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'root-false',
|
||||
type: AssetType.folder,
|
||||
projectId: project.id,
|
||||
creatorId: user.id,
|
||||
status: 'uploaded',
|
||||
},
|
||||
})
|
||||
|
||||
// Even if an embedding agent is enabled in db
|
||||
const bot = await prisma.user.create({
|
||||
data: { name: 'Bot', email: 'b-emb-false@example.com', password: 'pw', type: 'agent' },
|
||||
})
|
||||
await prisma.agent.create({
|
||||
data: {
|
||||
id: bot.id,
|
||||
teamId: team.id,
|
||||
type: 'embedding',
|
||||
enabled: true,
|
||||
config: { provider: '', model: '' },
|
||||
},
|
||||
})
|
||||
|
||||
process.env.ENABLE_EMBEDDING_AGENT = 'false'
|
||||
try {
|
||||
await expect(
|
||||
searchService.search(rootFolder.id, {
|
||||
recursively: true,
|
||||
assetType: 'file',
|
||||
operator: 'AND',
|
||||
conditions: [],
|
||||
query: 'test query',
|
||||
isSemantic: true,
|
||||
}),
|
||||
).rejects.toThrow('Embedding agent not configured or disabled for this team.')
|
||||
} finally {
|
||||
delete process.env.ENABLE_EMBEDDING_AGENT
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('totalSize calculation', () => {
|
||||
|
||||
@@ -35,6 +35,12 @@ export class SearchService {
|
||||
const teamId = team?.project?.teamId
|
||||
if (!teamId) throw new Error('Team ID not found for folder')
|
||||
|
||||
if (process.env.ENABLE_EMBEDDING_AGENT === 'false') {
|
||||
throw new HTTPException(422, {
|
||||
message: 'Embedding agent not configured or disabled for this team.',
|
||||
})
|
||||
}
|
||||
|
||||
const embeddingAgent = await this.prismaClient.agent.findFirst({
|
||||
where: { teamId, type: 'embedding', enabled: true },
|
||||
})
|
||||
|
||||
@@ -605,4 +605,32 @@ describe('TeamService', () => {
|
||||
expect(settings.appearance?.hideAgent).toBe(true)
|
||||
expect((settings as Record<string, unknown>).emailNotification).toBeUndefined()
|
||||
})
|
||||
|
||||
it('should report semanticSearchEnabled false when ENABLE_EMBEDDING_AGENT is false even if agent is enabled in db', async () => {
|
||||
const owner = await prisma.user.create({
|
||||
data: { name: 'Owner', email: 'owner-emb-false@example.com', password: 'pw' },
|
||||
})
|
||||
const team = await teamService.createTeam(owner, { name: 'Emb False Team' })
|
||||
|
||||
const bot = await prisma.user.create({
|
||||
data: { name: 'Bot', email: 'bot-emb-false@example.com', password: 'pw', type: 'agent' },
|
||||
})
|
||||
await prisma.agent.create({
|
||||
data: {
|
||||
id: bot.id,
|
||||
teamId: team.id,
|
||||
type: 'embedding',
|
||||
enabled: true,
|
||||
config: { provider: '', model: '' },
|
||||
},
|
||||
})
|
||||
|
||||
process.env.ENABLE_EMBEDDING_AGENT = 'false'
|
||||
try {
|
||||
const settings = await teamService.getSettings(team.id)
|
||||
expect(settings.semanticSearchEnabled).toBe(false)
|
||||
} finally {
|
||||
delete process.env.ENABLE_EMBEDDING_AGENT
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
@@ -311,9 +311,12 @@ export class TeamService {
|
||||
delete rawSettings.emailNotification
|
||||
const settings = rawSettings as TeamSettingsResponse
|
||||
|
||||
const embeddingAgent = await prisma.agent.findFirst({
|
||||
where: { teamId, type: 'embedding', enabled: true },
|
||||
})
|
||||
const embeddingAgent =
|
||||
process.env.ENABLE_EMBEDDING_AGENT === 'false'
|
||||
? null
|
||||
: await prisma.agent.findFirst({
|
||||
where: { teamId, type: 'embedding', enabled: true },
|
||||
})
|
||||
settings.semanticSearchEnabled = !!embeddingAgent
|
||||
|
||||
if (!settings.transcode) {
|
||||
|
||||
@@ -501,7 +501,6 @@ describe('UploadService', () => {
|
||||
where: { assetId: asset.id, type: WorkflowTaskType.transcode_pdf },
|
||||
})
|
||||
expect(workflowTask).not.toBeNull()
|
||||
expect(workflowTask?.status).toBe(TaskStatus.pending)
|
||||
|
||||
// Test HTML document as well
|
||||
const htmlTask = await prisma.task.create({
|
||||
@@ -530,7 +529,6 @@ describe('UploadService', () => {
|
||||
where: { assetId: htmlAsset.id, type: WorkflowTaskType.transcode_pdf },
|
||||
})
|
||||
expect(htmlWorkflowTask).not.toBeNull()
|
||||
expect(htmlWorkflowTask?.status).toBe(TaskStatus.pending)
|
||||
} finally {
|
||||
if (originalEnv !== undefined) {
|
||||
process.env.GOTENBERG_URL = originalEnv
|
||||
|
||||
@@ -1922,5 +1922,67 @@ describe('Transcode Activities', () => {
|
||||
})
|
||||
expect(task).toBeNull()
|
||||
})
|
||||
|
||||
it('should NOT create ai_embedding task when ENABLE_EMBEDDING_AGENT is false', async () => {
|
||||
const user = await prisma.user.create({
|
||||
data: { name: 'Test User Embedding 3', email: 'test-embedding-agent-3@test.com' },
|
||||
})
|
||||
const team = await prisma.team.create({
|
||||
data: { name: 'Test Team Embedding 3' },
|
||||
})
|
||||
await prisma.teamMember.create({
|
||||
data: { teamId: team.id, userId: user.id, role: 'owner' },
|
||||
})
|
||||
const project = await prisma.project.create({
|
||||
data: { name: 'Test Project Embedding 3', teamId: team.id },
|
||||
})
|
||||
await prisma.agent.create({
|
||||
data: {
|
||||
id: user.id,
|
||||
type: 'embedding',
|
||||
enabled: true,
|
||||
teamId: team.id,
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
config: { provider: 'test', model: 'test' } as any,
|
||||
},
|
||||
})
|
||||
const asset = await prisma.asset.create({
|
||||
data: {
|
||||
name: 'robot.glb',
|
||||
mediaType: 'model/gltf-binary',
|
||||
type: 'file',
|
||||
status: 'processed',
|
||||
projectId: project.id,
|
||||
media: {
|
||||
proxyType: '3d',
|
||||
imageTranscodes: [
|
||||
{
|
||||
key: 'files/asset-1/views.webp',
|
||||
width: 2880,
|
||||
height: 2880,
|
||||
quality: 85,
|
||||
format: 'webp',
|
||||
},
|
||||
],
|
||||
} as unknown as PrismaJson.MediaInfo,
|
||||
},
|
||||
})
|
||||
|
||||
process.env.ENABLE_EMBEDDING_AGENT = 'false'
|
||||
try {
|
||||
await createEmbeddingTaskIfEnabledActivity({
|
||||
assetId: asset.id,
|
||||
teamId: team.id,
|
||||
projectId: project.id,
|
||||
})
|
||||
|
||||
const task = await prisma.workflowTask.findFirst({
|
||||
where: { assetId: asset.id, type: 'ai_embedding' },
|
||||
})
|
||||
expect(task).toBeNull()
|
||||
} finally {
|
||||
delete process.env.ENABLE_EMBEDDING_AGENT
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1372,7 +1372,7 @@ export async function createEmbeddingTaskIfEnabledActivity(
|
||||
const teamId = params.teamId || asset.project?.teamId || null
|
||||
const projectId = params.projectId || asset.projectId
|
||||
|
||||
if (!teamId) {
|
||||
if (!teamId || process.env.ENABLE_EMBEDDING_AGENT === 'false') {
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user