agentic_huge_data_base / wiki
页面 Open WebUI · 2.3 后端架构·DeepWiki 中文全文译文

2.3 · 后端架构(Backend Architecture)

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

项目Open WebUI 章节2.3 状态全文译文 模块接口与服务契约、工具、记忆与模型调用、检索、召回与知识系统、认证、权限与安全
源码线索
  • backend/open_webui/config.py
  • backend/open_webui/env.py
  • backend/open_webui/functions.py
  • backend/open_webui/main.py
  • backend/open_webui/migrations/versions/c1d2e3f4a5b6_add_shared_chat_table.py
  • backend/open_webui/models/shared_chats.py
  • backend/open_webui/routers/auths.py
  • backend/open_webui/tools/builtin.py
  • backend/open_webui/utils/access_control/__init__.py
  • backend/open_webui/utils/access_control/files.py
模块标签
  • 接口与服务契约
  • 工具、记忆与模型调用
  • 检索、召回与知识系统
  • 认证、权限与安全
  • 系统架构

中文译文

后端架构(中文译文)

原始 DeepWiki 页面:https://deepwiki.com/open-webui/open-webui/2.3-backend-architecture
翻译时间:2026-06-09T16:07:32.142Z
翻译模型:deepseek-chat
原文字符数:16180
项目:Open WebUI (open-webui)

---

后端架构

相关源文件

以下文件用于生成此 wiki 页面:

  • backend/open_webui/config.py
  • backend/open_webui/env.py
  • backend/open_webui/functions.py
  • backend/open_webui/main.py
  • backend/open_webui/migrations/versions/c1d2e3f4a5b6_add_shared_chat_table.py
  • backend/open_webui/models/shared_chats.py
  • backend/open_webui/routers/auths.py
  • backend/open_webui/tools/builtin.py
  • backend/open_webui/utils/access_control/__init__.py
  • backend/open_webui/utils/access_control/files.py
  • backend/open_webui/utils/auth.py
  • backend/open_webui/utils/chat.py
  • backend/open_webui/utils/filter.py
  • backend/open_webui/utils/middleware.py
  • backend/open_webui/utils/models.py
  • backend/open_webui/utils/oauth.py
  • backend/open_webui/utils/plugin.py
  • backend/open_webui/utils/tools.py
  • src/lib/components/workspace/Models/BuiltinTools.svelte

目的与范围

本文档记录了 Open WebUI 基于 FastAPI 的后端架构,包括应用初始化、路由组织、中间件管道和配置管理系统。关于数据持久化层的信息,请参见数据与存储层。关于实时通信基础设施,请参见实时通信架构。关于前端架构详情,请参见前端架构

---

FastAPI 应用核心

后端基于 FastAPI 构建,在 backend/open_webui/main.py 中完成初始化。应用采用模块化路由架构,并集中管理生命周期。

应用初始化
graph TB
    subgraph "生命周期上下文管理器"
        StartLogger["start_logger()"]
        InstallDeps["install_tool_and_function_dependencies()"]
        RedisConn["get_redis_connection()"]
        TaskListener["redis_task_command_listener()"]
        SocketCleanup["periodic_usage_pool_cleanup()"]
        ModelCache["get_all_models() - 若 ENABLE_BASE_MODELS_CACHE"]
    end

    subgraph "FastAPI 应用创建"
        AppInit["FastAPI(lifespan=lifespan)"]
        OAuthMgr["oauth_manager = OAuthManager(app)"]
        OAuthClient["oauth_client_manager = OAuthClientManager(app)"]
        AppConfig["app.state.config = AppConfig()"]
    end

    subgraph "中间件栈"
        SecurityHeaders["SecurityHeadersMiddleware"]
        AuditLogging["AuditLoggingMiddleware"]
        SessionMW["StarSessionsMiddleware / SessionMiddleware"]
        CORS["CORSMiddleware"]
        Compress["CompressMiddleware"]
    end

    subgraph "路由注册"
        APIRouters["register_routers()"]
        Analytics["/api/v1/analytics"]
        Audio["/api/v1/audio"]
        Images["/api/v1/images"]
        Ollama["/api/ollama"]
        OpenAI["/api/openai"]
        Retrieval["/api/v1/retrieval"]
        Pipelines["/api/v1/pipelines"]
        Tasks["/api/v1/tasks"]
        Auths["/api/v1/auths"]
        Channels["/api/v1/channels"]
        Chats["/api/v1/chats"]
        Notes["/api/v1/notes"]
        Folders["/api/v1/folders"]
        Configs["/api/v1/configs"]
        Groups["/api/v1/groups"]
        Files["/api/v1/files"]
        Functions["/api/v1/functions"]
        Memories["/api/v1/memories"]
        Models["/api/v1/models"]
        Knowledge["/api/v1/knowledge"]
        Prompts["/api/v1/prompts"]
        Evaluations["/api/v1/evaluations"]
        Skills["/api/v1/skills"]
        Tools["/api/v1/tools"]
        Users["/api/v1/users"]
        Utils["/api/v1/utils"]
        SCIM["/api/v1/scim"]
        Automations["/api/v1/automations"]
        Calendar["/api/v1/calendar"]
    end

    StartLogger --> InstallDeps
    InstallDeps --> RedisConn
    RedisConn --> TaskListener
    TaskListener --> SocketCleanup
    SocketCleanup --> ModelCache

    AppInit --> OAuthMgr
    OAuthMgr --> OAuthClient
    OAuthClient --> AppConfig

    AppConfig --> SecurityHeaders
    SecurityHeaders --> AuditLogging
    AuditLogging --> SessionMW
    SessionMW --> CORS
    CORS --> Compress

    Compress --> APIRouters
    APIRouters --> Analytics
    APIRouters --> Audio
    APIRouters --> Images
    APIRouters --> Ollama
    APIRouters --> OpenAI
    APIRouters --> Retrieval
    APIRouters --> Pipelines
    APIRouters --> Tasks
    APIRouters --> Auths
    APIRouters --> Channels
    APIRouters --> Chats
    APIRouters --> Notes
    APIRouters --> Folders
    APIRouters --> Configs
    APIRouters --> Groups
    APIRouters --> Files
    APIRouters --> Functions
    APIRouters --> Memories
    APIRouters --> Models
    APIRouters --> Knowledge
    APIRouters --> Prompts
    APIRouters --> Evaluations
    APIRouters --> Skills
    APIRouters --> Tools
    APIRouters --> Users
    APIRouters --> Utils
    APIRouters --> SCIM
    APIRouters --> Automations
    APIRouters --> Calendar

来源: backend/open_webui/main.py:28-109backend/open_webui/main.py:592-665

lifespan 异步上下文管理器负责处理应用的启动和关闭:

生命周期阶段操作代码引用
启动初始化日志记录器backend/open_webui/main.py:67
启动连接 Redisbackend/open_webui/utils/redis.py:40
启动启动任务监听器backend/open_webui/main.py:612
启动启动使用池清理backend/open_webui/socket/main.py:72
启动缓存基础模型backend/open_webui/socket/main.py:70

来源: backend/open_webui/main.py:592-663backend/open_webui/socket/main.py:69-77

---

路由组织

后端使用 FastAPI 的 APIRouter 将端点组织到逻辑模块中。每个路由在 backend/open_webui/main.py 中注册时带有特定的路径前缀。

核心路由
graph LR
    subgraph "AI 模型集成"
        OpenAI["/api/openai<br/>openai.py"]
        Ollama["/api/ollama<br/>ollama.py"]
        Pipelines["/api/v1/pipelines<br/>pipelines.py"]
        Models["/api/v1/models<br/>models.py"]
    end

    subgraph "RAG 与知识库"
        Retrieval["/api/v1/retrieval<br/>retrieval.py"]
        Knowledge["/api/v1/knowledge<br/>knowledge.py"]
        Files["/api/v1/files<br/>files.py"]
        Memories["/api/v1/memories<br/>memories.py"]
    end

    subgraph "内容管理"
        Chats["/api/v1/chats<br/>chats.py"]
        Notes["/api/v1/notes<br/>notes.py"]
        Channels["/api/v1/channels<br/>channels.py"]
        Folders["/api/v1/folders<br/>folders.py"]
        Automations["/api/v1/automations<br/>automations.py"]
        Calendar["/api/v1/calendar<br/>calendar.py"]
    end

    subgraph "用户与认证"
        Auths["/api/v1/auths<br/>auths.py"]
        Users["/api/v1/users<br/>users.py"]
        Groups["/api/v1/groups<br/>groups.py"]
        SCIM["/api/v1/scim<br/>scim.py"]
    end

    subgraph "扩展"
        Functions["/api/v1/functions<br/>functions.py"]
        Tools["/api/v1/tools<br/>tools.py"]
        Skills["/api/v1/skills<br/>skills.py"]
        Prompts["/api/v1/prompts<br/>prompts.py"]
    end

来源: backend/open_webui/main.py:78-109

---

中间件管道

中间件管道在处理请求到达路由处理程序之前,会经过多个层次进行处理。

聊天请求处理管道

backend/open_webui/utils/chat.py:158-164 中的 generate_chat_completion 函数是 AI 请求的主要编排器,负责应用过滤器并检查模型访问权限。

graph TB
    Request["传入聊天请求<br/>(POST /api/chat/completions)"]

    AuditLog["AuditLoggingMiddleware<br/>记录请求/响应"]
    Session["SessionMiddleware<br/>管理用户会话"]
    AuthToken["AuthTokenMiddleware<br/>令牌验证"]

    AuthCheck["get_verified_user()<br/>JWT/API 密钥验证"]

    subgraph "process_chat_payload 流程"
        InletFilter["process_pipeline_inlet_filter()<br/>预处理过滤器"]
        ApplySystem["apply_system_prompt_to_body()"]
        ToolCheck["检查 tool_ids"]
        RAGCheck["检查 file_ids"]
    end

    subgraph "工具执行"
        GetTools["get_tools()<br/>加载工具规格与可调用对象"]
        ExecuteTools["执行工具函数"]
        FormatResults["格式化工具结果"]
    end

    subgraph "RAG 处理"
        GetFiles["检索文件内容"]
        GenerateEmbedding["get_ef()<br/>生成查询嵌入"]
        VectorSearch["query_collection()<br/>查询向量数据库"]
        Rerank["get_rf()<br/>重排序结果"]
    end

    Request --> AuditLog
    AuditLog --> Session
    Session --> AuthToken
    AuthToken --> AuthCheck
    AuthCheck --> InletFilter
    InletFilter --> ApplySystem
    ApplySystem --> ToolCheck
    ToolCheck --> GetTools
    GetTools --> ExecuteTools
    ExecuteTools --> FormatResults
    RAGCheck --> GetFiles
    GetFiles --> GenerateEmbedding
    GenerateEmbedding --> VectorSearch
    VectorSearch --> Rerank

来源: backend/open_webui/main.py:60-66backend/open_webui/utils/middleware.py:1-223backend/open_webui/utils/chat.py:158-216

中间件函数
函数用途关键操作
get_citation_source_from_tool_result()解析工具结果供 UI 使用将结果解析为源字典,用于引用显示 backend/open_webui/utils/middleware.py:221-223
_split_tool_calls()处理多 JSON 参数展开参数中包含多个连续 JSON 对象的工具调用 backend/open_webui/utils/middleware.py:172-183
apply_system_prompt_to_body()注入系统指令将配置的系统提示词前置到消息列表中 backend/open_webui/utils/payload.py:115
AuthTokenMiddleware令牌管理处理认证令牌的提取和验证 backend/open_webui/main.py:61
process_filter_functions()执行自定义过滤器遍历 inletoutletstream 过滤器,支持阀门配置 backend/open_webui/utils/filter.py:66-126

来源: backend/open_webui/utils/middleware.py:172-223backend/open_webui/utils/payload.py:115backend/open_webui/utils/filter.py:66-134

---

配置管理系统

Open WebUI 使用 PersistentConfig 系统,同时支持数据库持久化和环境变量覆盖。

PersistentConfig 架构

该系统使用存储在 SQL 数据库中的中央 Config 模型 backend/open_webui/config.py:78-86,以在重启之间维护状态。

graph TB
    subgraph "配置来源"
        EnvVars["环境变量<br/>os.environ"]
        DBConfig["数据库配置表<br/>Config 模型"]
        DefaultVals["默认值"]
    end

    subgraph "PersistentConfig 类"
        Init["__init__(env_name, config_path, env_value)"]
        GetValue["get_config_value(config_path)<br/>从数据库读取"]
        Update["update()<br/>从数据库刷新"]
    end

    subgraph "配置注册表"
        Registry["PERSISTENT_CONFIG_REGISTRY"]
        BroadcastUpdate["async_save_config(config)<br/>触发 update()"]
    end

    EnvVars --> Init
    DefaultVals --> Init
    Init --> GetValue
    Init --> Registry
    Registry --> BroadcastUpdate
    BroadcastUpdate --> Update

来源: backend/open_webui/config.py:78-231

PersistentConfig 使用模式

backend/open_webui/config.py:214-231 中的 PersistentConfig 类封装了配置值。当 ENABLE_PERSISTENT_CONFIG 为 True 时,它优先使用数据库值而非环境变量 backend/open_webui/config.py:211-229

class PersistentConfig(Generic[T]):
    def __init__(self, env_name: str, config_path: str, env_value: T):
        self.env_name = env_name
        self.config_path = config_path
        self.env_value = env_value
        self.config_value = get_config_value(config_path)
        # 优先级:数据库值 > 环境变量值

来源: backend/open_webui/config.py:214-231

---

服务层设计

后端采用分层架构,将路由、工具函数和数据模型分离。

服务层结构
graph TB
    subgraph "表示层(路由)"
        AuthRouter["auths.py<br/>认证"]
        RetrievalRouter["retrieval.py<br/>RAG 与搜索"]
        ToolRouter["tools.py<br/>工具管理"]
    end

    subgraph "业务逻辑层(工具函数)"
        AuthUtils["utils/auth.py<br/>JWT 与密码"]
        RetrievalUtils["retrieval/utils.py<br/>get_content_from_url()"]
        ToolUtils["utils/tools.py<br/>get_tools()"]
    end

    subgraph "数据访问层(模型)"
        UsersModel["models/users.py<br/>用户"]
        FilesModel["models/files.py<br/>文件"]
        ToolsModel["models/tools.py<br/>工具"]
    end

    AuthRouter --> AuthUtils
    AuthUtils --> UsersModel
    RetrievalRouter --> RetrievalUtils
    RetrievalUtils --> FilesModel
    ToolRouter --> ToolUtils
    ToolUtils --> ToolsModel

来源: backend/open_webui/routers/auths.py:11-29backend/open_webui/utils/tools.py:38-43backend/open_webui/utils/auth.py:23-26

依赖注入模式

FastAPI 的依赖注入用于认证和数据库会话:

  • get_verified_user():验证 JWT 或 API 密钥 backend/open_webui/utils/auth.py:69
  • get_admin_user():确保用户具有管理员权限 backend/open_webui/utils/auth.py:68
  • get_async_session():提供异步 SQLAlchemy 会话 backend/open_webui/internal/db.py:120
  • get_current_user():从令牌中检索当前用户的依赖项 backend/open_webui/utils/auth.py:70

来源: backend/open_webui/utils/auth.py:61-73backend/open_webui/internal/db.py:120

---

请求处理流程

RAG 与文档导入

文档处理由 retrieval 路由和工具函数处理:

  1. 提取get_content_from_url() 验证 URL 并使用导入管道提取文本 backend/open_webui/retrieval/utils.py:19
  2. 嵌入get_ef()(嵌入函数)和 get_rf()(重排序函数)提供语义搜索能力 backend/open_webui/main.py:111-116
  3. 模型发现get_all_models() 聚合来自 Ollama、OpenAI 和自定义函数的模型 backend/open_webui/utils/models.py:80-92

来源: backend/open_webui/utils/models.py:80-92backend/open_webui/main.py:111-116backend/open_webui/tools/builtin.py:19

内置工具执行

内置工具定义在 builtin.py 中,通过 tools 工具函数执行:

  • 网页搜索search_web() 使用配置的搜索引擎获取摘要 backend/open_webui/tools/builtin.py:184-197
  • 时间工具get_current_timestamp()calculate_timestamp() 为 LLM 提供时间上下文 backend/open_webui/tools/builtin.py:52-176
  • 工具加载get_tools() 处理工具的访问控制和模块加载 backend/open_webui/utils/tools.py:164-210

来源: backend/open_webui/tools/builtin.py:52-197backend/open_webui/utils/tools.py:164-210