Open WebUI with Ollama 应用搭建

854 阅读7分钟

Open WebUI

文档地址: 🏡 Home | Open WebUI Github 地址:GitHub - open-webui/open-webui: User-friendly WebUI for LLMs (Formerly Ollama WebUI) Open WebUI 是一个基于 LLM 模型处理多类任务的软件。并且其可扩展,功能丰富,且可以完全离线部署操作。支持多中 LLM model 的运行,包括Ollama 和 类OpenAI APIs 。

安装

基于 conda 安装

⏱️ Quick Start | Open WebUI

手动安装,需要安装必须的依赖,python 版本要求 3.11, 服务启动方式更简单和高效,启动后访问地址:http://localhost:8080

  1. Create a Conda Environment: conda create -n open-webui python=3.11
  2. Activate the Environment: conda activate open-webui
  3. Install Open WebUI: pip install open-webui
  4. Start the Server: open-webui serve

To update your locally installed Open-WebUI package to the latest version using pip, follow these simple steps:

pip install -U open-webui

The -U (or --upgrade) flag ensures that pip upgrades the package to the latest available version.

That's it! Your Open-WebUI package is now updated and ready to use.

After installing, visit:

You are now ready to start using OpenWebUI!

基于 Docker 安装

⏱️ Quick Start | Open WebUI

  1. 拉取 docker 镜像 ghcr.io/open-webui/open-webui:main
docker pull ghcr.io/open-webui/open-webui:main

2. 使用默认配置运行 dockcer 实例,工作目录映射 open-webui:/app/backend/data

docker run -d -p 3000:8080 -v open-webui:/app/backend/data --name open-webui ghcr.io/open-webui/open-webui:main

Important Flags

  • Volume Mapping (-v open-webui:/app/backend/data) : Ensures persistent storage of your data. This prevents data loss between container restarts.
  • Port Mapping (-p 3000:8080) : Exposes the WebUI on port 3000 of your local machine.
  • Using GPU Support For Nvidia GPU support, add --gpus all to the docker run command:
docker run -d -p 3000:8080 --gpus all -v open-webui:/app/backend/data --name open-webui ghcr.io/open-webui/open-webui:cuda
  • Single-User Mode (Disabling Login) To bypass the login page for a single-user setup, set the WEBUI_AUTH environment variable to False:
docker run -d -p 3000:8080 -e WEBUI_AUTH=False -v open-webui:/app/backend/data --name open-webui ghcr.io/open-webui/open-webui:main
  • Advanced Configuration: Connecting to Ollama on a Different Server To connect Open WebUI to an Ollama server located on another host, add the OLLAMA_BASE_URL environment variable:
docker run -d -p 3000:8080 -e OLLAMA_BASE_URL=https://example.com -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
  • Docker Compose 配置
# yaml 配置
version: '3'
services:
  open-webui:
    image: ghcr.io/open-webui/open-webui:main
    ports:
      - "3000:8080"
    volumes:
      - ./data:/app/backend/data
    environment:
      - WEBUI_AUTH=False

Access the WebUI After the container is running, access Open WebUI at: http://localhost:3000 For detailed help on each Docker flag, see Docker's documentation.

使用

🦙 Starting With Ollama | Open WebUI

管理员配置

  • 外部连接 第一个用户则是管理员,在管理员面板,选中外部连接,其中可以配置 OpenAI 和 ollama 的连接地址

image.png

点击 ollama 右边的小扳手,弹出一个管理 ollama 模型界面,可以下载,删除,导入模型。 image.png

  • 模型 可以查看到 ollama 下载完成的模型 image.png

  • 文档 LLM 模型会存缺少某些领域知识,导致回答不够精准,所以出现一个 RAG 技术,通过附加领域相关的信息,增强 LLM 模型在某领域回答的准确性。

如何将领域相关知识传入 LLM 模型?通常是将领域知识文档进行分割,生成 Embedding 格式的向量数据,那么则同样需要一个 LLM 模型进行 embedding 。在配置的文档项中可以配置使用的 LLM 模型。

image.png

Chat

下面进入对话界面,左上角选择使用的模型,底部有输入框,支持文本与语音。 image.png

点击工作空间,可以增加知识库文档,提示词模板,以及可调用的工具。

  • 知识库:在这里可以上传各种格式的文档,之后则可以在输入框中使用 # 调起这些文档。 image.png

image.png

  • 提示词:在这里创建 prompt 提示词模版,并且取一个英文名。之后则可以在输入框中使用 / + 模版名,则会自动输入模版。 image.png

image.png

  • 工具: 在这里可以创建工具,使用 python 编写特定功能,由 LLM 进行调用,可以获取 LLM 之外的信息和功能,特别是实时信息。 image.png

高级 Chat 指令

⚙️ Chat Parameters | Open WebUI

LLM 输出的高级特性

🏺 Artifacts | Open WebUI

反馈机制

📝 Evaluation | Open WebUI

Web Search

SearXNG

  1. SearXNG 基于 docker 的安装比较简单,直接 clone github.com/searxng/sea… 仓库,然后执行 docker-compose up 则可,另外其中的 settings.yml 文件需要有两处修改:1. 设置开启 json 格式结果;2. 禁用限制访问

doc.tryfastgpt.ai/docs/guide/…
docs.searxng.org/admin/setti…

image.png

# see https://docs.searxng.org/admin/settings/settings.html#settings-use-default-settings
use_default_settings: true
server:
  # base_url is defined in the SEARXNG_BASE_URL environment variable, see .env and docker-compose.yml
  secret_key: "c7fd14aaf57df6155eebc352219702547b93d064cc92acbb0501bca9fec14167"  # change this!
  limiter: false  # can be disabled for a private instance
  image_proxy: true
search:
  formats:
    - html
    - json
ui:
  static_use_hash: true
redis:
  url: redis://redis:6379/0

3. Open WebUI 进入到管理员设置面板,联网搜索一栏,开启联网搜索,搜索引擎选择 searxng : docs.openwebui.com/tutorials/i…

Searxng Query URL 中填写下面示例之一:

  • http://searxng:8080/search?q=<query> (using the container name and exposed port, suitable for Docker-based setups)
  • http://host.docker.internal:8080/search?q=<query> (using the host.docker.internal DNS name and the host port, suitable for Docker-based setups)
  • http://<searxng.local>/search?q=<query> (using a local domain name, suitable for local network access)
  • https://<search.domain.com>/search?q=<query> (using a custom domain name for a self-hosted SearXNG instance, suitable for public or private access)

特别注意 /search?q=<query> 是固定的.  

image.png

Develop

Tool

⚙️ Tools | Open WebUI Tool 扩展了 LLM 模型的能力,使其可以具有真实世界,实时的信息。设想一个场景,你希望 LLM 回答今天的天气或者股票信息,但由于 LLM 模型是预先训练的,它并没有当前真实世界的实时信息。此时如果提供一个可以获取天气或在股票信息的 Tool , LLM 先调用 Tool 获取相应信息,再进行摘要总结,输出预期的格式的结果。

可以从社区找到需要的 Tool 下载安装。 Tools | Open WebUI Community The Tools import process is quite simple. You will have two options:

image.png

下载并手动导入

  1. 点击需要的 Tool
  2. 点击蓝色的 Get 按钮
  3. 再点击 “Download as JSON export”
  4. 然后再 OpenWebUI 中的工作区 =》工具 中点击导入工具按钮

image.png

Tool 的实现

Tool 是一个 python 编写的一段代码,开头是一段描述信息

"""
title: String Inverse
author: Your Name
author_url: https://website.com
git_url: https://github.com/username/string-reverse.git
description: This tool calculates the inverse of a string
required_open_webui_version: 0.4.0
requirements: langchain-openai, langgraph, ollama, langchain_ollama
version: 0.4.0
licence: MIT
"""

接着定义一个 class Tools, 可选定义两个嵌套类 Valves 和 UserValves, 这两个类主要提供可以配置的信息,比如请求地址, api key 等。

class Tools:
    def __init__(self):
        """Initialize the Tool."""
        self.valves = self.Valves()

    class Valves(BaseModel):
        api_key: str = Field("", description="Your API key here")

    def reverse_string(self, string: str) -> str:
        """
        Reverses the input string.
        :param string: The string to reverse
        """
        # example usage of valves
        if self.valves.api_key != "42":
            return "Wrong API key"
        return string[::-1] 

下面是可以使用到特殊变量:

  • __event_emitter__: Emit events 可以在 LLM Chat 响应的任意阶段,将额外信息添加在结果中。
  • __event_call__: Same as event emitter but can be used for user interactions
  • __user__: A dictionary with user information
  • __metadata__: Dictionary with chat metadata
  • __messages__: List of previous messages
  • __files__: Attached files
  • __model__: Model name

__event_emitter__ 可以传递多种类型: type: status; type: message; 等。

class EventEmitter:
    def __init__(self, event_emitter: Callable[[dict], Any] = None):
        self.event_emitter = event_emitter

    async def emit(self, description="Unknown State", status="in_progress", done=False):
        if self.event_emitter:
            await self.event_emitter(
                {
                    "type": "status",
                    "data": {
                        "status": status,
                        "description": description,
                        "done": done,
                    },
                }
            )

Function

🧰 Functions | Open WebUI Function 扩展了 Open WebUI 的能力,增加新的 Model 模型,增加新的功能按钮等。

分为三类 Function:

  1. Pipe Function: 构建自定义 Agent 和 Model 的复杂处理逻辑,类似 Tools
  2. Filter Function: 对输入与输出进行改造处理。
  3. Action Function: 支持在 Chat 交互界面增加按钮扩展功能。

Pipe Function

Open WebUI 的数据流会按照配置,通过自定义的 Pipe Function , Pipe Function 则可以在数据流过时,将自定义逻辑注入到处理逻辑中。

from pydantic import BaseModel, Field

class Pipe:
    class Valves(BaseModel):
        MODEL_ID: str = Field(default="")

    def __init__(self):
        self.valves = self.Valves()

    def pipe(self, body: dict):
        # Logic goes here
        print(self.valves, body)  # This will print the configuration options and the input body
        return "Hello, World!"
  • 定义了 Pipe 类,其中的 pipe 方法则是主要逻辑入口。
  • 定义嵌套类 Valves , 这个类主要提供可以配置的信息,比如请求地址, api key 等,与 Tools 的 Values 类似。

支持 model 的 Pipe Function,增加 pipes 方法,返回 Dict , 每一组 id 和 name 表示一个 LLM 模型

class Valves(BaseModel):  
...
    def pipes(self):  
        return [  
            {"id": "model_id_1", "name": "model_1"},  
            {"id": "model_id_2", "name": "model_2"},  
            {"id": "model_id_3", "name": "model_3"},  
        ]
...

API

API docs available at: http://localhost:8080/docs.