agentic_huge_data_base / wiki
页面 Open WebUI · 2.1 系统组件与数据流·DeepWiki 中文全文译文

2.1 · 系统组件与数据流(System Components and Data Flow)

多模型对话工作台与知识应用入口 · 本章是 Open WebUI DeepWiki 中文译文的独立章节页,保留原始链接、源码锚点、模块标签和章节层级。

项目Open WebUI 章节2.1 状态全文译文 模块接口与服务契约、工具、记忆与模型调用、认证、权限与安全、系统架构
源码线索
  • backend/open_webui/config.py
  • backend/open_webui/env.py
  • backend/open_webui/main.py
  • backend/open_webui/routers/auths.py
  • backend/open_webui/tools/builtin.py
  • backend/open_webui/utils/auth.py
  • backend/open_webui/utils/middleware.py
  • backend/open_webui/utils/oauth.py
  • backend/open_webui/utils/tools.py
  • src/lib/apis/index.ts
模块标签
  • 接口与服务契约
  • 工具、记忆与模型调用
  • 认证、权限与安全
  • 系统架构
  • 界面与交互

中文译文

系统组件与数据流(中文译文)

原始 DeepWiki 页面:https://deepwiki.com/open-webui/open-webui/2.1-system-components-and-data-flow
翻译时间:2026-06-09T16:07:28.612Z
翻译模型:deepseek-chat
原文字符数:13531
项目:Open WebUI (open-webui)

---

系统组件与数据流

相关源文件

以下文件被用作生成此 wiki 页面的上下文:

  • backend/open_webui/config.py
  • backend/open_webui/env.py
  • backend/open_webui/main.py
  • backend/open_webui/routers/auths.py
  • backend/open_webui/tools/builtin.py
  • backend/open_webui/utils/auth.py
  • backend/open_webui/utils/middleware.py
  • backend/open_webui/utils/oauth.py
  • backend/open_webui/utils/tools.py
  • src/lib/apis/index.ts
  • src/lib/components/workspace/Models/BuiltinTools.svelte
  • src/lib/stores/index.ts
  • src/routes/+layout.svelte

本文档描述 Open WebUI 的主要架构组件及它们之间的数据流。涵盖前端(SvelteKit)、后端(FastAPI)、外部服务集成和存储层。

---

架构概览

Open WebUI 采用三层架构,清晰分离了表示层、应用逻辑层和数据存储层。系统使用消息驱动架构,通过 WebSocket 事件实现实时更新。

高层组件图
graph TB
    subgraph Frontend["前端 - SvelteKit 应用"]
        ChatSvelte["Chat.svelte<br/>submitPrompt()<br/>chatEventHandler()"]
        MessageInputSvelte["MessageInput.svelte<br/>uploadFileHandler()<br/>setText()"]
        MessagesSvelte["Messages.svelte<br/>showPreviousMessage()<br/>showNextMessage()"]
        StoresLib["$lib/stores/index.ts<br/>$user, $config, $models<br/>$socket, $chatId"]
    end

    subgraph Backend["后端 - FastAPI 应用"]
        MainPy["main.py<br/>app = FastAPI()<br/>lifespan()"]
        MiddlewarePy["utils/middleware.py<br/>process_chat_payload()<br/>build_chat_response_context()"]
        OpenaiRouter["routers/openai.py<br/>/api/chat/completions"]
        ChatsRouter["routers/chats.py<br/>/api/chats/*"]
        RetrievalRouter["routers/retrieval.py<br/>/api/retrieval/*"]
    end

    subgraph Storage["存储层"]
        ChatsModel["open_webui.models.chats.Chats<br/>SQLAlchemy / ScopedSession"]
        FilesModel["open_webui.models.files.Files"]
        VectorDBClient["VECTOR_DB_CLIENT<br/>retrieval/vector/factory.py"]
        StorageProvider["open_webui.storage.provider.Storage<br/>Local/S3/Azure/GCS"]
    end

    subgraph External["外部服务"]
        OllamaAPI["Ollama API<br/>generate_chat_completion()"]
        OpenAIAPI["OpenAI API<br/>/v1/chat/completions"]
        VectorDBs["向量数据库<br/>ChromaDB/Qdrant/Milvus"]
    end

    ChatSvelte -->|"POST /api/chat/completions"| OpenaiRouter
    ChatSvelte -->|"socket.on('events')"| MainPy
    MessageInputSvelte -->|"uploadFile()"| ChatsRouter
    StoresLib -->|"getChatList()"| ChatsRouter

    OpenaiRouter --> MiddlewarePy
    MiddlewarePy --> OllamaAPI
    MiddlewarePy --> OpenAIAPI

    RetrievalRouter --> VectorDBClient
    VectorDBClient --> VectorDBs

    ChatsRouter --> ChatsModel
    ChatsRouter --> FilesModel
    ChatsRouter --> StorageProvider

来源: backend/open_webui/main.py:28-109, backend/open_webui/utils/middleware.py:78-102, backend/open_webui/internal/db.py:120-121, src/lib/stores/index.ts:13-85

---

前端组件

前端是一个 SvelteKit 应用,使用响应式 store 进行状态管理,并通过 HTTP 和 WebSocket 与后端通信。

前端状态管理

Open WebUI 使用 Svelte stores 作为主要状态管理模式。关键 store 在整个应用中导入以管理全局状态:

Store用途关键数据
user当前用户信息SessionUser 对象、角色、权限 src/lib/stores/index.ts:19
config后端配置功能开关、API 设置 src/lib/stores/index.ts:18
models可用 LLM 模型模型列表、能力 src/lib/stores/index.ts:69
socketWebSocket 连接Socket 实例 src/lib/stores/index.ts:31
chatId当前聊天 ID活跃聊天标识符 src/lib/stores/index.ts:55
pyodideWorker代码执行环境Pyodide web worker src/lib/stores/index.ts:80

来源: src/lib/stores/index.ts:13-115, src/routes/+layout.svelte:12-41

前后端通信模式
sequenceDiagram
    participant User
    participant LayoutSvelte["+layout.svelte"]
    participant Store["$lib/stores/index.ts"]
    participant API["src/lib/apis/index.ts"]
    participant Socket["socket.io-client"]

    Note over User,Socket: 初始化流程
    User->>LayoutSvelte: 加载应用
    LayoutSvelte->>API: getModels(token)
    API-->>LayoutSvelte: 模型列表 [src/lib/apis/index.ts:9]
    LayoutSvelte->>Socket: setupSocket(enableWebsocket) [src/routes/+layout.svelte:115]
    Socket->>LayoutSvelte: _socket.on('connect') [src/routes/+layout.svelte:133]

    Note over User,Socket: 消息提交流程
    User->>LayoutSvelte: 提交消息
    LayoutSvelte->>Store: 更新 $chatId
    LayoutSvelte->>API: chatCompletion(token, body)

    Note over User,Socket: 实时更新
    LayoutSvelte->>Socket: emit('heartbeat') [src/routes/+layout.svelte:162]
    Socket-->>LayoutSvelte: _socket.on('disconnect') [src/routes/+layout.svelte:193]

来源: src/routes/+layout.svelte:115-207, src/lib/apis/index.ts:9-160, src/lib/stores/index.ts:31-32

---

后端架构

后端基于 FastAPI 构建,采用模块化路由架构。

应用初始化与配置

FastAPI 应用在 main.py 中初始化 backend/open_webui/main.py:28-39。它管理复杂的生命周期,包括数据库迁移 backend/open_webui/config.py:57-75 和服务初始化。

配置模式:PersistentConfig 与 AppConfig

Open WebUI 使用一种将环境变量与数据库持久化值合并的配置系统:

graph LR
    EnvVars["环境变量<br/>open_webui/env.py"]
    Database["open_webui.config.Config 表<br/>SQLAlchemy 模型"]
    Redis["Redis 缓存<br/>get_redis_connection()"]

    PersistentConfig["PersistentConfig[T]<br/>env_value, config_value"]
    AppConfig["request.app.state.config"]

    EnvVars -->|"初始加载"| PersistentConfig
    Database -->|"覆盖"| PersistentConfig
    PersistentConfig --> AppConfig

    AppConfig -->|"async_save_config"| Database
    AppConfig -->|"同步"| Redis

    Redis -->|"多节点同步"| AppConfig

模式细节:

  1. PersistentConfig backend/open_webui/config.py:214-231:通用包装器,同时存储环境值和数据库值,数据库可用时优先使用。
  2. AppConfig 持久化:运行时变更通过 async_save_config backend/open_webui/config.py:192-206 持久化,该函数更新数据库中的 Config 模型。
  3. PERSISTENT_CONFIG_REGISTRY backend/open_webui/config.py:172-189:所有配置的注册表,当数据库发生变化时更新。

来源: backend/open_webui/config.py:78-231, backend/open_webui/env.py:22-38

API 路由结构

后端将功能组织为模块化路由 backend/open_webui/main.py:78-109

路由端点用途
chats.py/api/chats/*聊天的 CRUD、历史管理
retrieval.py/api/retrieval/*文档上传、RAG 查询、网络搜索
audio.py/api/audio/*STT 转录、TTS 生成
images.py/api/images/*图像生成、编辑
tasks.py/api/tasks/*后台任务(标题、跟进)
auths.py/api/v1/auths/*会话和 JWT 管理 backend/open_webui/routers/auths.py:91

来源: backend/open_webui/main.py:78-109, backend/open_webui/routers/auths.py:91

---

数据流:聊天补全

聊天补全流程涉及 middleware.py 管道中的多个处理层。

完整的请求-响应数据流
sequenceDiagram
    participant User
    participant ChatSvelte["Chat.svelte"]
    participant OpenAIRouter["open_webui/routers/openai.py"]
    participant MiddlewarePy["open_webui/utils/middleware.py<br/>process_chat_payload()"]
    participant RetrievalRouter["open_webui/routers/retrieval.py<br/>process_web_search()"]
    participant ChatCompletion["open_webui/utils/chat.py<br/>generate_chat_completion()"]
    participant LLMProvider["Ollama/OpenAI API"]
    participant SocketIO["open_webui/socket/main.py<br/>get_event_emitter()"]

    User->>ChatSvelte: 提交消息
    ChatSvelte->>OpenAIRouter: POST /api/chat/completions

    OpenAIRouter->>MiddlewarePy: process_chat_payload(request, body, user)

    alt webSearchEnabled
        MiddlewarePy->>RetrievalRouter: process_web_search(request, SearchForm) [backend/open_webui/utils/middleware.py:45]
        RetrievalRouter-->>MiddlewarePy: 搜索结果
    end

    alt tool_ids in payload
        MiddlewarePy->>ToolsUtil["utils/tools.py"]: get_tools(request, tool_ids, user, ...) [backend/open_webui/utils/tools.py:164]
        ToolsUtil-->>MiddlewarePy: 工具定义与阀门
    end

    MiddlewarePy->>ChatCompletion: generate_chat_completion(request, form_data, user) [backend/open_webui/utils/middleware.py:78]
    ChatCompletion->>LLMProvider: 流式请求

    loop 流式数据块
        LLMProvider-->>SocketIO: emit('chat', {type: 'content', content: '...'})
        SocketIO-->>ChatSvelte: 更新 UI
    end

来源: backend/open_webui/utils/middleware.py:1-220, backend/open_webui/utils/tools.py:164-216, backend/open_webui/utils/chat.py:78

中间件处理管道

process_chat_payload 函数编排以下步骤:

  1. 记忆注入:通过 query_memory 查询用户记忆 backend/open_webui/utils/middleware.py:59
  2. 网络搜索:通过 process_web_search 执行搜索 backend/open_webui/utils/middleware.py:45
  3. 工具执行:通过 get_tools 准备工具 backend/open_webui/utils/tools.py:164-216
  4. 代码执行:如果触发代码解释器,通过 execute_code_jupyter 运行 Python 代码片段 backend/open_webui/utils/middleware.py:114

来源: backend/open_webui/utils/middleware.py:37-67, backend/open_webui/utils/tools.py:164-216

---

认证与会话流程

Open WebUI 使用 JWT 令牌进行会话管理,支持多种认证提供者。

认证数据流
graph TD
    subgraph AuthRequest["认证请求"]
        SigninForm["routers/auths.py<br/>signin(SigninForm)"]
        LdapAuth["routers/auths.py<br/>ldap_auth(LdapForm)"]
        OAuthRedirect["utils/oauth.py<br/>RedirectResponse"]
    end

    subgraph TokenCreation["会话生成"]
        CreateToken["utils/auth.py<br/>create_token(data, expires_delta)"]
        SessionResponse["routers/auths.py<br/>create_session_response()"]
    end

    subgraph ClientStorage["客户端持久化"]
        Cookie["Set-Cookie: token"]
        LocalStorage["localStorage.token"]
    end

    SigninForm --> SessionResponse
    LdapAuth --> SessionResponse
    SessionResponse --> CreateToken
    CreateToken --> SessionResponse
    SessionResponse --> Cookie
    SessionResponse --> LocalStorage

关键实现细节:

  • 令牌创建create_token 使用 HS256 算法和 WEBUI_SECRET_KEY backend/open_webui/utils/auth.py:200-211
  • 会话响应create_session_response 构建包含用户权限的最终载荷 backend/open_webui/routers/auths.py:100-149
  • 撤销:可通过 Redis 使用 jti(JWT ID)撤销令牌 backend/open_webui/utils/auth.py:222-236

来源: backend/open_webui/routers/auths.py:100-149, backend/open_webui/utils/auth.py:200-236, backend/open_webui/utils/oauth.py:27

---

存储层

Open WebUI 针对不同数据类型使用多种存储后端。

存储架构
graph TB
    subgraph "应用层"
        Models["SQLAlchemy 模型<br/>open_webui.models.chats.Chats<br/>open_webui.models.users.Users"]
    end

    subgraph "存储抽象层"
        VectorFactory["VECTOR_DB_CLIENT<br/>open_webui/retrieval/vector/factory.py"]
        StorageProvider["Storage<br/>open_webui/storage/provider.py"]
    end

    subgraph "物理存储"
        Database["SQLite/Postgres<br/>SQLAlchemy 引擎"]
        ChromaDB["向量数据库<br/>Chroma/Qdrant/Milvus/pgvector"]
        LocalFS["本地文件系统/S3<br/>DATA_DIR/uploads"]
    end

    Models --> Database
    VectorFactory --> ChromaDB
    StorageProvider --> LocalFS

来源: backend/open_webui/internal/db.py:120-121, backend/open_webui/retrieval/vector/factory.py:47-48, backend/open_webui/storage/provider.py:42