Skip to content

Checking your reading list…

Retry verification

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Open WebUI Architecture: How Web AI Chat Handles RAG, Tools & Real-time Streaming

Open WebUI Architecture: How Web AI Chat Handles RAG, Tools & Real-time Streaming

This article dissects Open WebUI's architecture, tracing a knowledge-base Q&A flow from file upload and vector indexing through model routing, RAG retrieval, tool calling, and streaming response delivery via Socket.IO, asyncio, and Redis for multi-instance coordination and disconnection recovery.

1. What Is Open WebUI?

Open WebUI provides a unified web interface for chat, multi-user management, model integration, file and knowledge-base handling, tools, and extensions. It is not a large language model itself and does not need to run on the same machine as the model inference service. The overall architecture separates the application layer (Open WebUI) from model services.

1.1 Model, Model Service, and Application

These are three distinct layers. Choosing Open WebUI does not mean any chat model is installed; model visibility, permission, and service connectivity are separate concerns.

1.2 Message, Chat, and Message Tree

A Chat is a conversation container; a Message represents a user, assistant, or tool interaction. Chat history is not a simple array: regenerating, editing historical messages, and multi-model replies can create branches. Both frontend ( Chat.svelte) and backend reconstruct the current branch using message ID , parent message ID , and current message ID .

1.3 Token, Context Window, and Streaming Output

Model input includes system prompt, history, current question, retrieved chunks, and tool results — all consuming the context window. More retrieved content is not always better ; it can increase cost, latency, noise, and evict important history. Streaming output means the server returns increments in batches so users need not wait for the full answer. Upstream model to backend typically uses HTTP streaming ; backend to browser uses Socket.IO events — two separate connections that should not be conflated.

1.4 RAG, Embedding, Vector Store, and Reranking

RAG (Retrieval-Augmented Generation) has two phases: build phase — documents are converted to text, split, embedded, and indexed; query phase — the question retrieves relevant text, and selected evidence is passed to the model for answering.

1.5 Tool, Function, Pipe, Filter, MCP, Pipeline

The following terms define the extension mechanisms:

Tool — exposes callable capabilities to the model (e.g., query or execute operations).

Function — platform's Python extension mechanism including Pipe, Filter, Action, Event.

Pipe — wraps custom logic as a selectable model or processing path.

Filter — processes content at request/response stages.

Action — UI-triggered extensions.

MCP — protocol for connecting external tool services.

Pipeline — processing services integrated via corresponding adapters.

2. Project Structure and Core Code

Repository: https://github.com/open-webui/open-webui (commit b0e6098e9, 2026-11-09). Key directories:

open-webui/├── src/                 # SvelteKit frontend│   ├── routes/          # pages & routing│   └── lib/             # APIs, components, stores, i18n├── backend/│   ├── start.sh         # container startup│   ├── dev.sh           # dev startup│   ├── requirements.txt # Python deps│   └── open_webui/      # main backend package│       ├── main.py      # FastAPI assembly & chat entry│       ├── env.py       # env vars & boot config│       ├── config.py    # feature config & persistence│       ├── routers/     # API routes (users, chat, files, knowledge, models, tools)│       ├── models/      # data models & persistence│       ├── internal/    # DB & internal infra│       ├── utils/       # chat orchestration, auth, tools│       ├── retrieval/   # document retrieval, loading, vector adapters│       ├── storage/     # file storage abstraction│       ├── socket/      # Socket.IO & realtime│       ├── migrations/  # DB migrations│       ├── functions.py # Function execution logic│       └── tasks.py     # in-process & cross-instance task coordination├── static/              # static assets├── scripts/             # build & resource scripts├── test/                # frontend tests├── Dockerfile├── docker-compose.yaml├── package.json         # frontend deps & scripts└── pyproject.toml       # Python project & deps

Note: The critical chat entry point is backend/open_webui/main.py; core orchestration lives in backend/open_webui/utils/middleware.py; model routing is in backend/open_webui/utils/chat.py.

3. Complete Flow of a Knowledge-Base Q&A

Scenario: user uploads an employee handbook, selects a model, asks: "According to the employee handbook, how long is the probation period? Please provide evidence."

3.1 Upload File

Uploading a file does not send the raw file to the LLM. Frontend calls uploadFile (in src/lib/apis/files/index.ts); backend handles via upload_file, upload_file_handler, process_uploaded_file ( backend/open_webui/routers/files.py). Different file types follow different branches: documents may be extracted and indexed; some audio is transcribed; images/video may go through multimodal processing or be limited by extraction capabilities. Three data categories emerge:

Raw content — stored in local or configured object storage.

File record & metadata — file ID, ownership, status, storage path for permission checks and business linking.

Retrievable content & vectors — parsed, chunked, embedded, written to vector store.

These have independent lifecycles; a DB record does not guarantee the object exists, and raw file existence does not guarantee indexing is complete or uses the current embedding model.

3.2 Document Parsing and Indexing

Handled in routers/retrieval.py via index_file, process_file, save_docs_to_vector_db. save_docs_to_vector_db selects splitting strategy (character, token, etc.) per config; embedding and vector store are determined by config and adapter layer. Chunks can retain source metadata so retrieval can link fragments back to documents. Warning: Configuration may be persisted in DB; changing chunking rules or embedding model does not automatically update old indexes — they must be rebuilt and validated. Different embeddings have incompatible dimensions and semantic spaces; mixing them causes errors or recall degradation.

3.3 Frontend Organizes Request

Main UI component Chat.svelte uses paths submitPrompt → sendMessage / sendMessageSocket. Frontend assembles user message and assistant placeholder, selects model, files, tools, feature flags, and attaches session_id, chat and message identifiers. Finally calls generateOpenAIChatCompletion in src/lib/apis/openai/index.ts to hit the completions endpoint. Key identifiers: chat_id — identifies chat or temporary session. message_id / id — locates assistant message. parent_id — identifies parent node of message branch. session_id — links active Socket.IO session. task_id — identifies a running generation task.

Although function names contain Socket, chat initiation uses HTTP; real-time results are handled via Socket.IO events. Frontend may place multiple model message_ids in one request; backend fans out per model rather than frontend sending duplicate requests.

3.4 Backend Receives and Processes Request

Request enters main.py; Open WebUI verifies user identity, checks model access permission, assembles model parameters and chat messages. Two processing modes:

Create background task — if request contains required session_id and chat_id, a chat task is created for the target model and executed in the current process. If Redis is configured, partial task state is recorded. HTTP returns chat_id and task_ids immediately; frontend then receives model-generated content via events. Getting a task ID does not mean the answer is complete.

Direct result return — if background task conditions aren't met, request is processed directly and returned via HTTP (single or streaming response). Browser chat and other API clients may receive different response forms. Stop clicks, timeouts, model failures, or process kills trigger different cleanup behaviors; cannot assume tasks always clean up normally.

3.5 Prepare Model Context

Core chat task flow resides in main.py 's internal process_chat function: three steps — process_chat_payload prepares request, hands to chat model, then process_chat_response handles model output. process_chat_payload does more than concatenate text; it processes model parameters, chat history, filters, memory, web search, images, tools, files, and source context per request and config.

3.6 Select and Call Model

Model routing in utils/chat.py 's generate_chat_completion checks current model and access rights, then dispatches by model type. Unified interface hides format differences across providers, but interface compatibility does not guarantee identical tool calling, multimodal support, parameters, error formats, or streaming protocols . When a model-specific issue arises, examine the vendor's raw response alongside adapter logs.

3.7 Retrieve Knowledge Base

After indexing, the user query is transformed into a retrievable representation; candidate chunks are fetched from one or more collections. Code supports standard query and hybrid retrieval; reranking depends on config. chat_completion_files_handler manages file context on chat side; retrieval routing and adapters in retrieval/ handle low-level queries.

3.8 Call External Tools

Tool calling is not the model executing code directly. When the model requests a tool call (name + arguments), Open WebUI or the execution environment validates, executes allowed tools, and returns results to the model for continued generation. Depending on model, tool type, and config, different invocation paths exist; some require user approval before execution. Relevant code in utils/middleware.py: execute_tool_call, pause_for_tool_approval, resume_tool_calls.

3.9 Push and Save Response

After model returns, middleware.py 's process_chat_response chooses normal or streaming handling. Streaming parses upstream increments, organizes output, handles tool results and sources, and updates messages per chat type, config, and event state. Frontend Chat.svelte event handlers consume chat:completion, chat:message:delta, error, and status events. Persistence is not a simple "write to DB on every token" rule ; current version uses response stream snapshots, in-memory or Redis state, and multiple update paths. Temporary vs. saved chats differ; after disconnection, verify the target version's actual recovery behavior and business requirements — cannot guarantee all content is replayable after process failure.

4. Recovering Answers After Disconnection

If network is unstable or user refreshes, how does the browser know which chat to return to? Four identifiers recap: chat_id — locates session. message_id — locates message. task_id — locates running task. session_id — links current Socket.IO connection; after reconnection session_id may change, so it should not be used as a long-term session ID.

Recovery flow: browser reconnects → app re-queries chat, active tasks, and available snapshots to restore UI state. Redis Pub/Sub does not guarantee replay of all events during offline period; if the executing process crashes, Redis snapshots alone cannot guarantee the model resumes inference from the interruption point.

5. How Real-Time Chat Is Implemented

Three global concepts:

Socket.IO — Core question: How does user receive real-time events? Typical role: Manages connections, events, rooms; pushes content & state to browser.

asyncio — Core question: How does server handle concurrent waiting tasks? Typical role: Schedules chat generation, Redis listening, other async tasks within Python process.

Redis — Core question: How do multiple instances exchange events & share transient state? Typical role: Pub/Sub, active task registry, response stream snapshots, locks, coordination state.

Relational DB — Core question: How are users & saved chats persisted? Typical role: Persists normal chats, users, config.

5.1 Socket.IO: Real-Time Message Push

Unlike HTTP request-response, Socket.IO provides a persistent event channel where browser can emit events and server can push events during generation. It offers connection management, events, rooms, and acknowledgments. Socket.IO is not raw WebSocket ; it has its own event protocol over Engine.IO, commonly using WebSocket and HTTP long-polling transports. Current version selects transport via ENABLE_WEBSOCKET_SUPPORT: enabled → WebSocket; disabled → polling. Cannot assume automatic fallback on WebSocket failure. Browser connection established in src/routes/layout.svelte with config:

const _socket = io(`${WEBUI_BASE_URL}` || undefined, {  reconnection: true,  reconnectionDelay: 1000,  reconnectionDelayMax: 5000,  randomizationFactor: 0.5,  path: '/ws/socket.io',  transports: enableWebsocket ? ['websocket'] : ['polling', 'websocket'],  auth: (cb) => cb({ token: localStorage.token })});

Key details: path is Socket.IO service path; reverse proxy must forward it correctly.

Client enables reconnection with backoff, but connection rebuild does not equal server automatically replaying all events during disconnection. auth supplies current token to connection auth logic; token handling still subject to server validation and permission rules.

Client transport list must be viewed with server config; server uses

transports=(['websocket'] if ENABLE_WEBSOCKET_SUPPORT else ['polling'])

.

Server creates socketio.AsyncServer in socket/main.py. On successful auth, connection saves user info and joins user:{user_id} room; for saved chats, also joins chat:{chat_id} room after verifying user access. Rooms are server-side delivery groups, not DB tables, and do not replace permission checks.

5.2 asyncio: Asynchronous Task Execution

Core of asyncio is event loop and coroutines . When a coroutine hits an await on async I/O, the event loop runs other ready tasks; resumes when model response or Redis data arrives. Key concepts: async def — defines coroutine function. await — waits for awaitable; yields execution meanwhile.

Event loop — schedules and runs async tasks. asyncio.create_task() — schedules coroutine as a Task. asyncio.CancelledError — exception raised when task is cancelled.

Simplified example (not from repo):

import asyncioasync def generate_reply():    # simulate waiting for model service; event loop can run other tasks during wait    await asyncio.sleep(1)    return 'reply content'async def main():    task = asyncio.create_task(generate_reply())    print('generation task started')    reply = await task    print(reply)asyncio.run(main())

Suitable for many wait-for-network-or-I/O scenarios, but async def does not automatically move CPU-intensive work to other cores. If a coroutine runs blocking sync calls, it still blocks the event loop, slowing other tasks and real-time events; choose thread pool, process, or separate service based on workload. Critical code in tasks.py ( backend/open_webui/tasks.py), core create_task():

async def create_task(redis, coroutine, id=None, task_id=None):    task_id = task_id or str(uuid4())    task = asyncio.create_task(coroutine)    task.add_done_callback(        lambda t: asyncio.create_task(cleanup_task(redis, task_id, id))    )    tasks[task_id] = task    # omitted item_tasks registration by chat ID    if redis:        await redis_save_task(redis, task_id, id)    return task_id, task
task

is an asyncio.Task in the current Python process; tasks dict is also process-local memory. Redis stores cross-instance accessible task registry info — not executable or migratable Python coroutine objects.

5.3 Redis: Cross-Instance Coordination

Redis provides both key-value transient data structures and Pub/Sub — distinct responsibilities:

Keys, hashes, sets — record task activity, task-chat associations, partial response stream state. Task activity markers have TTL, renewed by heartbeat during run; expired entries cleaned on query.

Pub/Sub — publishers send messages to channels; subscribed instances receive them. Project uses it to propagate Socket.IO events and task stop commands across instances.

Locks & other state — coordinates online status and cleanup; lock timeouts and actual service availability affect behavior.

Redis Pub/Sub is for real-time notification, not a persistent work queue: messages published while a subscriber is offline cannot be guaranteed delivered later via Pub/Sub alone. Project has snapshots and DB mechanisms, but these also do not guarantee precise resumption of model calls after process failure. Two Redis configurations exist: one for WebSocket room channels ( WEBSOCKET_REDIS_ROOM_CHANNELS), another for general coordination. In socket/main.py, manager selection:

manager_class = (    AsyncRedisRoomChannelManager    if WEBSOCKET_REDIS_ROOM_CHANNELS    else socketio.AsyncRedisManager)redis_manager = manager_class(    ws_redis_url,    redis_options=ws_redis_options,    json=SOCKETIO_JSON)sio = socketio.AsyncServer(    # omitted CORS, transports, heartbeat, etc.    client_manager=redis_manager)
AsyncRedisRoomChannelManager

(implemented in redis_room_channels.py) is a room-channel manager . When WEBSOCKET_REDIS_ROOM_CHANNELS=true, events directed to a room can be published to its channel, reducing irrelevant event handling on instances without local members; control messages may still use shared channel.

5.4 Tying It Together: Generation, Stop, and Recovery

Assuming multi-replica deployment with Redis and required shared services:

Generation & Push : Browser submits question via HTTP; replica B creates in-process asyncio Task, awaits model output. Generated content organized into Socket.IO events, forwarded across instances via Redis Pub/Sub , finally pushed to browser by replica A. Redis simultaneously registers task and saves partial response snapshots; application DB persists normal chat history.

Stop Task : Receiving instance publishes stop command with task_id via Redis; replica holding the task calls task.cancel() in its process. Cancellation is a request — does not imply remote task has finished cleanup or external operations are rolled back.

Disconnection Recovery : Browser reconnects; app re-queries chat, active tasks, and available snapshots to restore UI state. Redis Pub/Sub cannot guarantee replay of all offline events; if executing process crashes, Redis snapshots alone cannot guarantee model resumes inference from interruption point.

6. Summary

Through analysis of Open WebUI, we followed a knowledge-base Q&A to understand the complete flow from document parsing, knowledge retrieval, model invocation to answer generation, and saw how task execution, real-time push, state persistence, and disconnection recovery coordinate. A seemingly simple browser conversation involves not just model answering, but application-level organization and management of models, knowledge, tools, and chat state. Whether learning Web AI application implementation or planning an internal team AI platform, Open WebUI is a valuable open-source project to study and reference.

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

RAGRedisFastAPISocket.IOasyncioOpen WebUISvelteKitAI Chat Architecture

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion