github-actions[bot] commited on
Commit
948f8ce
·
0 Parent(s):

GitHub deploy: 1b88d6aa4a804440ff59cd3b6ff5246b41aa8288

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .dockerignore +20 -0
  2. .env.example +22 -0
  3. .eslintignore +13 -0
  4. .eslintrc.cjs +31 -0
  5. .gitattributes +42 -0
  6. .github/FUNDING.yml +1 -0
  7. .github/ISSUE_TEMPLATE/bug_report.yaml +172 -0
  8. .github/ISSUE_TEMPLATE/config.yml +1 -0
  9. .github/ISSUE_TEMPLATE/feature_request.yaml +64 -0
  10. .github/dependabot.yml +20 -0
  11. .github/pull_request_template.md +77 -0
  12. .github/workflows/build-release.yml +72 -0
  13. .github/workflows/codespell.disabled +25 -0
  14. .github/workflows/deploy-to-hf-spaces.yml +63 -0
  15. .github/workflows/docker-build.yaml +800 -0
  16. .github/workflows/format-backend.yaml +49 -0
  17. .github/workflows/format-build-frontend.yaml +65 -0
  18. .github/workflows/integration-test.disabled +255 -0
  19. .github/workflows/lint-backend.disabled +27 -0
  20. .github/workflows/lint-frontend.disabled +21 -0
  21. .github/workflows/release-pypi.yml +36 -0
  22. .gitignore +314 -0
  23. .npmrc +1 -0
  24. .prettierignore +316 -0
  25. .prettierrc +10 -0
  26. CHANGELOG.md +0 -0
  27. CODE_OF_CONDUCT.md +99 -0
  28. CONTRIBUTOR_LICENSE_AGREEMENT +7 -0
  29. Dockerfile +191 -0
  30. INSTALLATION.md +35 -0
  31. LICENSE +33 -0
  32. LICENSE_HISTORY +53 -0
  33. LICENSE_NOTICE +11 -0
  34. Makefile +33 -0
  35. README.md +278 -0
  36. TROUBLESHOOTING.md +36 -0
  37. backend/.dockerignore +14 -0
  38. backend/.gitignore +12 -0
  39. backend/dev.sh +3 -0
  40. backend/open_webui/__init__.py +103 -0
  41. backend/open_webui/alembic.ini +114 -0
  42. backend/open_webui/config.py +0 -0
  43. backend/open_webui/constants.py +122 -0
  44. backend/open_webui/env.py +815 -0
  45. backend/open_webui/functions.py +353 -0
  46. backend/open_webui/internal/db.py +164 -0
  47. backend/open_webui/internal/migrations/001_initial_schema.py +254 -0
  48. backend/open_webui/internal/migrations/002_add_local_sharing.py +48 -0
  49. backend/open_webui/internal/migrations/003_add_auth_api_key.py +48 -0
  50. backend/open_webui/internal/migrations/004_add_archived.py +46 -0
.dockerignore ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .github
2
+ .DS_Store
3
+ docs
4
+ kubernetes
5
+ node_modules
6
+ /.svelte-kit
7
+ /package
8
+ .env
9
+ .env.*
10
+ vite.config.js.timestamp-*
11
+ vite.config.ts.timestamp-*
12
+ __pycache__
13
+ .idea
14
+ venv
15
+ _old
16
+ uploads
17
+ .ipynb_checkpoints
18
+ **/*.db
19
+ _test
20
+ backend/data/*
.env.example ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ollama URL for the backend to connect
2
+ # The path '/ollama' will be redirected to the specified backend URL
3
+ OLLAMA_BASE_URL='http://localhost:11434'
4
+
5
+ OPENAI_API_BASE_URL=''
6
+ OPENAI_API_KEY=''
7
+
8
+ # AUTOMATIC1111_BASE_URL="http://localhost:7860"
9
+
10
+ # For production, you should only need one host as
11
+ # fastapi serves the svelte-kit built frontend and backend from the same host and port.
12
+ # To test with CORS locally, you can set something like
13
+ # CORS_ALLOW_ORIGIN='http://localhost:5173;http://localhost:8080'
14
+ CORS_ALLOW_ORIGIN='*'
15
+
16
+ # For production you should set this to match the proxy configuration (127.0.0.1)
17
+ FORWARDED_ALLOW_IPS='*'
18
+
19
+ # DO NOT TRACK
20
+ SCARF_NO_ANALYTICS=true
21
+ DO_NOT_TRACK=true
22
+ ANONYMIZED_TELEMETRY=false
.eslintignore ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .DS_Store
2
+ node_modules
3
+ /build
4
+ /.svelte-kit
5
+ /package
6
+ .env
7
+ .env.*
8
+ !.env.example
9
+
10
+ # Ignore files for PNPM, NPM and YARN
11
+ pnpm-lock.yaml
12
+ package-lock.json
13
+ yarn.lock
.eslintrc.cjs ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ module.exports = {
2
+ root: true,
3
+ extends: [
4
+ 'eslint:recommended',
5
+ 'plugin:@typescript-eslint/recommended',
6
+ 'plugin:svelte/recommended',
7
+ 'plugin:cypress/recommended',
8
+ 'prettier'
9
+ ],
10
+ parser: '@typescript-eslint/parser',
11
+ plugins: ['@typescript-eslint'],
12
+ parserOptions: {
13
+ sourceType: 'module',
14
+ ecmaVersion: 2020,
15
+ extraFileExtensions: ['.svelte']
16
+ },
17
+ env: {
18
+ browser: true,
19
+ es2017: true,
20
+ node: true
21
+ },
22
+ overrides: [
23
+ {
24
+ files: ['*.svelte'],
25
+ parser: 'svelte-eslint-parser',
26
+ parserOptions: {
27
+ parser: '@typescript-eslint/parser'
28
+ }
29
+ }
30
+ ]
31
+ };
.gitattributes ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # TypeScript
2
+ *.ts text eol=lf
3
+ *.tsx text eol=lf
4
+ # JavaScript
5
+ *.js text eol=lf
6
+ *.jsx text eol=lf
7
+ *.mjs text eol=lf
8
+ *.cjs text eol=lf
9
+ # Svelte
10
+ *.svelte text eol=lf
11
+ # HTML/CSS
12
+ *.html text eol=lf
13
+ *.css text eol=lf
14
+ *.scss text eol=lf
15
+ *.less text eol=lf
16
+ # Config files and JSON
17
+ *.json text eol=lf
18
+ *.jsonc text eol=lf
19
+ *.yml text eol=lf
20
+ *.yaml text eol=lf
21
+ *.toml text eol=lf
22
+ # Shell scripts
23
+ *.sh text eol=lf
24
+ # Markdown & docs
25
+ *.md text eol=lf
26
+ *.mdx text eol=lf
27
+ *.txt text eol=lf
28
+ # Git-related
29
+ .gitattributes text eol=lf
30
+ .gitignore text eol=lf
31
+ # Prettier and other dotfiles
32
+ .prettierrc text eol=lf
33
+ .prettierignore text eol=lf
34
+ .eslintrc text eol=lf
35
+ .eslintignore text eol=lf
36
+ .stylelintrc text eol=lf
37
+ .editorconfig text eol=lf
38
+ # Misc
39
+ *.env text eol=lf
40
+ *.lock text eol=lf
41
+ *.ttf filter=lfs diff=lfs merge=lfs -text
42
+ *.jpg filter=lfs diff=lfs merge=lfs -text
.github/FUNDING.yml ADDED
@@ -0,0 +1 @@
 
 
1
+ github: tjbck
.github/ISSUE_TEMPLATE/bug_report.yaml ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Bug Report
2
+ description: Create a detailed bug report to help us improve Open WebUI.
3
+ title: 'issue: '
4
+ labels: ['bug', 'triage']
5
+ assignees: []
6
+ body:
7
+ - type: markdown
8
+ attributes:
9
+ value: |
10
+ # Bug Report
11
+
12
+ ## Important Notes
13
+
14
+ - **Before submitting a bug report**: Please check the [Issues](https://github.com/open-webui/open-webui/issues) and [Discussions](https://github.com/open-webui/open-webui/discussions) sections to see if a similar issue has already been reported. If unsure, start a discussion first, as this helps us efficiently focus on improving the project. Duplicates may be closed without notice. **Please search for existing issues and discussions.**
15
+
16
+ - Check for opened, **but also for (recently) CLOSED issues** as the issue you are trying to report **might already have been fixed!**
17
+
18
+ - **Respectful collaboration**: Open WebUI is a volunteer-driven project with a single maintainer and contributors who also have full-time jobs. Please be constructive and respectful in your communication.
19
+
20
+ - **Contributing**: If you encounter an issue, consider submitting a pull request or forking the project. We prioritize preventing contributor burnout to maintain Open WebUI's quality.
21
+
22
+ - **Bug Reproducibility**: If a bug cannot be reproduced using a `:main` or `:dev` Docker setup or with `pip install` on Python 3.11, community assistance may be required. In such cases, we will move it to the "[Issues](https://github.com/open-webui/open-webui/discussions/categories/issues)" Discussions section. Your help is appreciated!
23
+
24
+ - type: checkboxes
25
+ id: issue-check
26
+ attributes:
27
+ label: Check Existing Issues
28
+ description: Confirm that you’ve checked for existing reports before submitting a new one.
29
+ options:
30
+ - label: I have searched for any existing and/or related issues.
31
+ required: true
32
+ - label: I have searched for any existing and/or related discussions.
33
+ required: true
34
+ - label: I am using the latest version of Open WebUI.
35
+ required: true
36
+
37
+ - type: dropdown
38
+ id: installation-method
39
+ attributes:
40
+ label: Installation Method
41
+ description: How did you install Open WebUI?
42
+ options:
43
+ - Git Clone
44
+ - Pip Install
45
+ - Docker
46
+ - Other
47
+ validations:
48
+ required: true
49
+
50
+ - type: input
51
+ id: open-webui-version
52
+ attributes:
53
+ label: Open WebUI Version
54
+ description: Specify the version (e.g., v0.6.26)
55
+ validations:
56
+ required: true
57
+
58
+ - type: input
59
+ id: ollama-version
60
+ attributes:
61
+ label: Ollama Version (if applicable)
62
+ description: Specify the version (e.g., v0.2.0, or v0.1.32-rc1)
63
+ validations:
64
+ required: false
65
+
66
+ - type: input
67
+ id: operating-system
68
+ attributes:
69
+ label: Operating System
70
+ description: Specify the OS (e.g., Windows 10, macOS Sonoma, Ubuntu 22.04, Debian 12)
71
+ validations:
72
+ required: true
73
+
74
+ - type: input
75
+ id: browser
76
+ attributes:
77
+ label: Browser (if applicable)
78
+ description: Specify the browser/version (e.g., Chrome 100.0, Firefox 98.0)
79
+ validations:
80
+ required: false
81
+
82
+ - type: checkboxes
83
+ id: confirmation
84
+ attributes:
85
+ label: Confirmation
86
+ description: Ensure the following prerequisites have been met.
87
+ options:
88
+ - label: I have read and followed all instructions in `README.md`.
89
+ required: true
90
+ - label: I am using the latest version of **both** Open WebUI and Ollama.
91
+ required: true
92
+ - label: I have included the browser console logs.
93
+ required: true
94
+ - label: I have included the Docker container logs.
95
+ required: true
96
+ - label: I have **provided every relevant configuration, setting, and environment variable used in my setup.**
97
+ required: true
98
+ - label: I have clearly **listed every relevant configuration, custom setting, environment variable, and command-line option that influences my setup** (such as Docker Compose overrides, .env values, browser settings, authentication configurations, etc).
99
+ required: true
100
+ - label: |
101
+ I have documented **step-by-step reproduction instructions that are precise, sequential, and leave nothing to interpretation**. My steps:
102
+ - Start with the initial platform/version/OS and dependencies used,
103
+ - Specify exact install/launch/configure commands,
104
+ - List URLs visited, user input (incl. example values/emails/passwords if needed),
105
+ - Describe all options and toggles enabled or changed,
106
+ - Include any files or environmental changes,
107
+ - Identify the expected and actual result at each stage,
108
+ - Ensure any reasonably skilled user can follow and hit the same issue.
109
+ required: true
110
+ - type: textarea
111
+ id: expected-behavior
112
+ attributes:
113
+ label: Expected Behavior
114
+ description: Describe what should have happened.
115
+ validations:
116
+ required: true
117
+
118
+ - type: textarea
119
+ id: actual-behavior
120
+ attributes:
121
+ label: Actual Behavior
122
+ description: Describe what actually happened.
123
+ validations:
124
+ required: true
125
+
126
+ - type: textarea
127
+ id: reproduction-steps
128
+ attributes:
129
+ label: Steps to Reproduce
130
+ description: |
131
+ Please provide a **very detailed, step-by-step guide** to reproduce the issue. Your instructions should be so clear and precise that anyone can follow them without guesswork. Include every relevant detail—settings, configuration options, exact commands used, values entered, and any prerequisites or environment variables.
132
+ **If full reproduction steps and all relevant settings are not provided, your issue may not be addressed.**
133
+ **If your steps to reproduction are incomplete, lacking detail or not reproducible, your issue can not be addressed.**
134
+
135
+ placeholder: |
136
+ Example (include every detail):
137
+ 1. Start with a clean Ubuntu 22.04 install.
138
+ 2. Install Docker v24.0.5 and start the service.
139
+ 3. Clone the Open WebUI repo (git clone ...).
140
+ 4. Use the Docker Compose file without modifications.
141
+ 5. Open browser Chrome 115.0 in incognito mode.
142
+ 6. Go to http://localhost:8080 and log in with user "test@example.com".
143
+ 7. Set the language to "English" and theme to "Dark".
144
+ 8. Attempt to connect to Ollama at "http://localhost:11434".
145
+ 9. Observe that the error message "Connection refused" appears at the top right.
146
+
147
+ Please list each step carefully and include all relevant configuration, settings, and options.
148
+ validations:
149
+ required: true
150
+ - type: textarea
151
+ id: logs-screenshots
152
+ attributes:
153
+ label: Logs & Screenshots
154
+ description: Include relevant logs, errors, or screenshots to help diagnose the issue.
155
+ placeholder: 'Attach logs from the browser console, Docker logs, or error messages.'
156
+ validations:
157
+ required: true
158
+
159
+ - type: textarea
160
+ id: additional-info
161
+ attributes:
162
+ label: Additional Information
163
+ description: Provide any extra details that may assist in understanding the issue.
164
+ validations:
165
+ required: false
166
+
167
+ - type: markdown
168
+ attributes:
169
+ value: |
170
+ ## Note
171
+ **If the bug report is incomplete, does not follow instructions or is lacking details it may not be addressed.** Ensure that you've followed all the **README.md** and **troubleshooting.md** guidelines, and provide all necessary information for us to reproduce the issue.
172
+ Thank you for contributing to Open WebUI!
.github/ISSUE_TEMPLATE/config.yml ADDED
@@ -0,0 +1 @@
 
 
1
+ blank_issues_enabled: false
.github/ISSUE_TEMPLATE/feature_request.yaml ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Feature Request
2
+ description: Suggest an idea for this project
3
+ title: 'feat: '
4
+ labels: ['triage']
5
+ body:
6
+ - type: markdown
7
+ attributes:
8
+ value: |
9
+ ## Important Notes
10
+ ### Before submitting
11
+ Please check the [Issues](https://github.com/open-webui/open-webui/issues) or [Discussions](https://github.com/open-webui/open-webui/discussions) to see if a similar request has been posted.
12
+ It's likely we're already tracking it! If you’re unsure, start a discussion post first.
13
+ This will help us efficiently focus on improving the project.
14
+
15
+ ### Collaborate respectfully
16
+ We value a **constructive attitude**, so please be mindful of your communication. If negativity is part of your approach, our capacity to engage may be limited. We're here to help if you're **open to learning** and **communicating positively**.
17
+
18
+ Remember:
19
+ - Open WebUI is a **volunteer-driven project**
20
+ - It's managed by a **single maintainer**
21
+ - It's supported by contributors who also have **full-time jobs**
22
+
23
+ We appreciate your time and ask that you **respect ours**.
24
+
25
+
26
+ ### Contributing
27
+ If you encounter an issue, we highly encourage you to submit a pull request or fork the project. We actively work to prevent contributor burnout to maintain the quality and continuity of Open WebUI.
28
+
29
+ ### Bug reproducibility
30
+ If a bug cannot be reproduced with a `:main` or `:dev` Docker setup, or a `pip install` with Python 3.11, it may require additional help from the community. In such cases, we will move it to the "[issues](https://github.com/open-webui/open-webui/discussions/categories/issues)" Discussions section due to our limited resources. We encourage the community to assist with these issues. Remember, it’s not that the issue doesn’t exist; we need your help!
31
+
32
+ - type: checkboxes
33
+ id: existing-issue
34
+ attributes:
35
+ label: Check Existing Issues
36
+ description: Please confirm that you've checked for existing similar requests
37
+ options:
38
+ - label: I have searched the existing issues and discussions.
39
+ required: true
40
+ - type: textarea
41
+ id: problem-description
42
+ attributes:
43
+ label: Problem Description
44
+ description: Is your feature request related to a problem? Please provide a clear and concise description of what the problem is.
45
+ placeholder: "Ex. I'm always frustrated when..."
46
+ validations:
47
+ required: true
48
+ - type: textarea
49
+ id: solution-description
50
+ attributes:
51
+ label: Desired Solution you'd like
52
+ description: Clearly describe what you want to happen.
53
+ validations:
54
+ required: true
55
+ - type: textarea
56
+ id: alternatives-considered
57
+ attributes:
58
+ label: Alternatives Considered
59
+ description: A clear and concise description of any alternative solutions or features you've considered.
60
+ - type: textarea
61
+ id: additional-context
62
+ attributes:
63
+ label: Additional Context
64
+ description: Add any other context or screenshots about the feature request here.
.github/dependabot.yml ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ version: 2
2
+ updates:
3
+ - package-ecosystem: uv
4
+ directory: '/'
5
+ schedule:
6
+ interval: monthly
7
+ target-branch: 'dev'
8
+
9
+ - package-ecosystem: pip
10
+ directory: '/backend'
11
+ schedule:
12
+ interval: monthly
13
+ target-branch: 'dev'
14
+
15
+ - package-ecosystem: 'github-actions'
16
+ directory: '/'
17
+ schedule:
18
+ # Check for updates to GitHub Actions every week
19
+ interval: monthly
20
+ target-branch: 'dev'
.github/pull_request_template.md ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Pull Request Checklist
2
+
3
+ ### Note to first-time contributors: Please open a discussion post in [Discussions](https://github.com/open-webui/open-webui/discussions) and describe your changes before submitting a pull request.
4
+
5
+ **Before submitting, make sure you've checked the following:**
6
+
7
+ - [ ] **Target branch:** Verify that the pull request targets the `dev` branch. Not targeting the `dev` branch may lead to immediate closure of the PR.
8
+ - [ ] **Description:** Provide a concise description of the changes made in this pull request.
9
+ - [ ] **Changelog:** Ensure a changelog entry following the format of [Keep a Changelog](https://keepachangelog.com/) is added at the bottom of the PR description.
10
+ - [ ] **Documentation:** If necessary, update relevant documentation [Open WebUI Docs](https://github.com/open-webui/docs) like environment variables, the tutorials, or other documentation sources.
11
+ - [ ] **Dependencies:** Are there any new dependencies? Have you updated the dependency versions in the documentation?
12
+ - [ ] **Testing:** Perform manual tests to verify the implemented fix/feature works as intended AND does not break any other functionality. Take this as an opportunity to make screenshots of the feature/fix and include it in the PR description.
13
+ - [ ] **Agentic AI Code:**: Confirm this Pull Request is **not written by any AI Agent** or has at least gone through additional human review **and** manual testing. If any AI Agent is the co-author of this PR, it may lead to immediate closure of the PR.
14
+ - [ ] **Code review:** Have you performed a self-review of your code, addressing any coding standard issues and ensuring adherence to the project's coding standards?
15
+ - [ ] **Title Prefix:** To clearly categorize this pull request, prefix the pull request title using one of the following:
16
+ - **BREAKING CHANGE**: Significant changes that may affect compatibility
17
+ - **build**: Changes that affect the build system or external dependencies
18
+ - **ci**: Changes to our continuous integration processes or workflows
19
+ - **chore**: Refactor, cleanup, or other non-functional code changes
20
+ - **docs**: Documentation update or addition
21
+ - **feat**: Introduces a new feature or enhancement to the codebase
22
+ - **fix**: Bug fix or error correction
23
+ - **i18n**: Internationalization or localization changes
24
+ - **perf**: Performance improvement
25
+ - **refactor**: Code restructuring for better maintainability, readability, or scalability
26
+ - **style**: Changes that do not affect the meaning of the code (white space, formatting, missing semi-colons, etc.)
27
+ - **test**: Adding missing tests or correcting existing tests
28
+ - **WIP**: Work in progress, a temporary label for incomplete or ongoing work
29
+
30
+ # Changelog Entry
31
+
32
+ ### Description
33
+
34
+ - [Concisely describe the changes made in this pull request, including any relevant motivation and impact (e.g., fixing a bug, adding a feature, or improving performance)]
35
+
36
+ ### Added
37
+
38
+ - [List any new features, functionalities, or additions]
39
+
40
+ ### Changed
41
+
42
+ - [List any changes, updates, refactorings, or optimizations]
43
+
44
+ ### Deprecated
45
+
46
+ - [List any deprecated functionality or features that have been removed]
47
+
48
+ ### Removed
49
+
50
+ - [List any removed features, files, or functionalities]
51
+
52
+ ### Fixed
53
+
54
+ - [List any fixes, corrections, or bug fixes]
55
+
56
+ ### Security
57
+
58
+ - [List any new or updated security-related changes, including vulnerability fixes]
59
+
60
+ ### Breaking Changes
61
+
62
+ - **BREAKING CHANGE**: [List any breaking changes affecting compatibility or functionality]
63
+
64
+ ---
65
+
66
+ ### Additional Information
67
+
68
+ - [Insert any additional context, notes, or explanations for the changes]
69
+ - [Reference any related issues, commits, or other relevant information]
70
+
71
+ ### Screenshots or Videos
72
+
73
+ - [Attach any relevant screenshots or videos demonstrating the changes]
74
+
75
+ ### Contributor License Agreement
76
+
77
+ By submitting this pull request, I confirm that I have read and fully agree to the [Contributor License Agreement (CLA)](https://github.com/open-webui/open-webui/blob/main/CONTRIBUTOR_LICENSE_AGREEMENT), and I am providing my contributions under its terms.
.github/workflows/build-release.yml ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Release
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main # or whatever branch you want to use
7
+
8
+ jobs:
9
+ release:
10
+ runs-on: ubuntu-latest
11
+
12
+ steps:
13
+ - name: Checkout repository
14
+ uses: actions/checkout@v5
15
+
16
+ - name: Check for changes in package.json
17
+ run: |
18
+ git diff --cached --diff-filter=d package.json || {
19
+ echo "No changes to package.json"
20
+ exit 1
21
+ }
22
+
23
+ - name: Get version number from package.json
24
+ id: get_version
25
+ run: |
26
+ VERSION=$(jq -r '.version' package.json)
27
+ echo "::set-output name=version::$VERSION"
28
+
29
+ - name: Extract latest CHANGELOG entry
30
+ id: changelog
31
+ run: |
32
+ CHANGELOG_CONTENT=$(awk 'BEGIN {print_section=0;} /^## \[/ {if (print_section == 0) {print_section=1;} else {exit;}} print_section {print;}' CHANGELOG.md)
33
+ CHANGELOG_ESCAPED=$(echo "$CHANGELOG_CONTENT" | sed ':a;N;$!ba;s/\n/%0A/g')
34
+ echo "Extracted latest release notes from CHANGELOG.md:"
35
+ echo -e "$CHANGELOG_CONTENT"
36
+ echo "::set-output name=content::$CHANGELOG_ESCAPED"
37
+
38
+ - name: Create GitHub release
39
+ uses: actions/github-script@v8
40
+ with:
41
+ github-token: ${{ secrets.GITHUB_TOKEN }}
42
+ script: |
43
+ const changelog = `${{ steps.changelog.outputs.content }}`;
44
+ const release = await github.rest.repos.createRelease({
45
+ owner: context.repo.owner,
46
+ repo: context.repo.repo,
47
+ tag_name: `v${{ steps.get_version.outputs.version }}`,
48
+ name: `v${{ steps.get_version.outputs.version }}`,
49
+ body: changelog,
50
+ })
51
+ console.log(`Created release ${release.data.html_url}`)
52
+
53
+ - name: Upload package to GitHub release
54
+ uses: actions/upload-artifact@v4
55
+ with:
56
+ name: package
57
+ path: |
58
+ .
59
+ !.git
60
+ env:
61
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
62
+
63
+ - name: Trigger Docker build workflow
64
+ uses: actions/github-script@v8
65
+ with:
66
+ script: |
67
+ github.rest.actions.createWorkflowDispatch({
68
+ owner: context.repo.owner,
69
+ repo: context.repo.repo,
70
+ workflow_id: 'docker-build.yaml',
71
+ ref: 'v${{ steps.get_version.outputs.version }}',
72
+ })
.github/workflows/codespell.disabled ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Codespell configuration is within pyproject.toml
2
+ ---
3
+ name: Codespell
4
+
5
+ on:
6
+ push:
7
+ branches: [main]
8
+ pull_request:
9
+ branches: [main]
10
+
11
+ permissions:
12
+ contents: read
13
+
14
+ jobs:
15
+ codespell:
16
+ name: Check for spelling errors
17
+ runs-on: ubuntu-latest
18
+
19
+ steps:
20
+ - name: Checkout
21
+ uses: actions/checkout@v4
22
+ - name: Annotate locations with typos
23
+ uses: codespell-project/codespell-problem-matcher@v1
24
+ - name: Codespell
25
+ uses: codespell-project/actions-codespell@v2
.github/workflows/deploy-to-hf-spaces.yml ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Deploy to HuggingFace Spaces
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - dev
7
+ - main
8
+ workflow_dispatch:
9
+
10
+ jobs:
11
+ check-secret:
12
+ runs-on: ubuntu-latest
13
+ outputs:
14
+ token-set: ${{ steps.check-key.outputs.defined }}
15
+ steps:
16
+ - id: check-key
17
+ env:
18
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
19
+ if: "${{ env.HF_TOKEN != '' }}"
20
+ run: echo "defined=true" >> $GITHUB_OUTPUT
21
+
22
+ deploy:
23
+ runs-on: ubuntu-latest
24
+ needs: [check-secret]
25
+ if: needs.check-secret.outputs.token-set == 'true'
26
+ env:
27
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
28
+ steps:
29
+ - name: Checkout repository
30
+ uses: actions/checkout@v5
31
+ with:
32
+ lfs: true
33
+
34
+ - name: Remove git history
35
+ run: rm -rf .git
36
+
37
+ - name: Prepend YAML front matter to README.md
38
+ run: |
39
+ echo "---" > temp_readme.md
40
+ echo "title: Open WebUI" >> temp_readme.md
41
+ echo "emoji: 🐳" >> temp_readme.md
42
+ echo "colorFrom: purple" >> temp_readme.md
43
+ echo "colorTo: gray" >> temp_readme.md
44
+ echo "sdk: docker" >> temp_readme.md
45
+ echo "app_port: 8080" >> temp_readme.md
46
+ echo "---" >> temp_readme.md
47
+ cat README.md >> temp_readme.md
48
+ mv temp_readme.md README.md
49
+
50
+ - name: Configure git
51
+ run: |
52
+ git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com"
53
+ git config --global user.name "github-actions[bot]"
54
+ - name: Set up Git and push to Space
55
+ run: |
56
+ git init --initial-branch=main
57
+ git lfs install
58
+ git lfs track "*.ttf"
59
+ git lfs track "*.jpg"
60
+ rm demo.gif
61
+ git add .
62
+ git commit -m "GitHub deploy: ${{ github.sha }}"
63
+ git push --force https://arcticaurora:${HF_TOKEN}@huggingface.co/spaces/arcticaurora/ai main
.github/workflows/docker-build.yaml ADDED
@@ -0,0 +1,800 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Create and publish Docker images with specific build args
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ push:
6
+ branches:
7
+ - main
8
+ - dev
9
+ tags:
10
+ - v*
11
+
12
+ env:
13
+ REGISTRY: ghcr.io
14
+
15
+ jobs:
16
+ build-main-image:
17
+ runs-on: ${{ matrix.runner }}
18
+ permissions:
19
+ contents: read
20
+ packages: write
21
+ strategy:
22
+ fail-fast: false
23
+ matrix:
24
+ include:
25
+ - platform: linux/amd64
26
+ runner: ubuntu-latest
27
+ - platform: linux/arm64
28
+ runner: ubuntu-24.04-arm
29
+
30
+ steps:
31
+ # GitHub Packages requires the entire repository name to be in lowercase
32
+ # although the repository owner has a lowercase username, this prevents some people from running actions after forking
33
+ - name: Set repository and image name to lowercase
34
+ run: |
35
+ echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
36
+ echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
37
+ env:
38
+ IMAGE_NAME: '${{ github.repository }}'
39
+
40
+ - name: Prepare
41
+ run: |
42
+ platform=${{ matrix.platform }}
43
+ echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
44
+
45
+ - name: Checkout repository
46
+ uses: actions/checkout@v5
47
+
48
+ - name: Set up QEMU
49
+ uses: docker/setup-qemu-action@v3
50
+
51
+ - name: Set up Docker Buildx
52
+ uses: docker/setup-buildx-action@v3
53
+
54
+ - name: Log in to the Container registry
55
+ uses: docker/login-action@v3
56
+ with:
57
+ registry: ${{ env.REGISTRY }}
58
+ username: ${{ github.actor }}
59
+ password: ${{ secrets.GITHUB_TOKEN }}
60
+
61
+ - name: Extract metadata for Docker images (default latest tag)
62
+ id: meta
63
+ uses: docker/metadata-action@v5
64
+ with:
65
+ images: ${{ env.FULL_IMAGE_NAME }}
66
+ tags: |
67
+ type=ref,event=branch
68
+ type=ref,event=tag
69
+ type=sha,prefix=git-
70
+ type=semver,pattern={{version}}
71
+ type=semver,pattern={{major}}.{{minor}}
72
+ flavor: |
73
+ latest=${{ github.ref == 'refs/heads/main' }}
74
+
75
+ - name: Extract metadata for Docker cache
76
+ id: cache-meta
77
+ uses: docker/metadata-action@v5
78
+ with:
79
+ images: ${{ env.FULL_IMAGE_NAME }}
80
+ tags: |
81
+ type=ref,event=branch
82
+ ${{ github.ref_type == 'tag' && 'type=raw,value=main' || '' }}
83
+ flavor: |
84
+ prefix=cache-${{ matrix.platform }}-
85
+ latest=false
86
+
87
+ - name: Build Docker image (latest)
88
+ uses: docker/build-push-action@v5
89
+ id: build
90
+ with:
91
+ context: .
92
+ push: true
93
+ platforms: ${{ matrix.platform }}
94
+ labels: ${{ steps.meta.outputs.labels }}
95
+ outputs: type=image,name=${{ env.FULL_IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
96
+ cache-from: type=registry,ref=${{ steps.cache-meta.outputs.tags }}
97
+ cache-to: type=registry,ref=${{ steps.cache-meta.outputs.tags }},mode=max
98
+ build-args: |
99
+ BUILD_HASH=${{ github.sha }}
100
+
101
+ - name: Export digest
102
+ run: |
103
+ mkdir -p /tmp/digests
104
+ digest="${{ steps.build.outputs.digest }}"
105
+ touch "/tmp/digests/${digest#sha256:}"
106
+
107
+ - name: Upload digest
108
+ uses: actions/upload-artifact@v4
109
+ with:
110
+ name: digests-main-${{ env.PLATFORM_PAIR }}
111
+ path: /tmp/digests/*
112
+ if-no-files-found: error
113
+ retention-days: 1
114
+
115
+ build-cuda-image:
116
+ runs-on: ${{ matrix.runner }}
117
+ permissions:
118
+ contents: read
119
+ packages: write
120
+ strategy:
121
+ fail-fast: false
122
+ matrix:
123
+ include:
124
+ - platform: linux/amd64
125
+ runner: ubuntu-latest
126
+ - platform: linux/arm64
127
+ runner: ubuntu-24.04-arm
128
+
129
+ steps:
130
+ # GitHub Packages requires the entire repository name to be in lowercase
131
+ # although the repository owner has a lowercase username, this prevents some people from running actions after forking
132
+ - name: Set repository and image name to lowercase
133
+ run: |
134
+ echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
135
+ echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
136
+ env:
137
+ IMAGE_NAME: '${{ github.repository }}'
138
+
139
+ - name: Prepare
140
+ run: |
141
+ platform=${{ matrix.platform }}
142
+ echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
143
+
144
+ - name: Checkout repository
145
+ uses: actions/checkout@v5
146
+
147
+ - name: Set up QEMU
148
+ uses: docker/setup-qemu-action@v3
149
+
150
+ - name: Set up Docker Buildx
151
+ uses: docker/setup-buildx-action@v3
152
+
153
+ - name: Log in to the Container registry
154
+ uses: docker/login-action@v3
155
+ with:
156
+ registry: ${{ env.REGISTRY }}
157
+ username: ${{ github.actor }}
158
+ password: ${{ secrets.GITHUB_TOKEN }}
159
+
160
+ - name: Extract metadata for Docker images (cuda tag)
161
+ id: meta
162
+ uses: docker/metadata-action@v5
163
+ with:
164
+ images: ${{ env.FULL_IMAGE_NAME }}
165
+ tags: |
166
+ type=ref,event=branch
167
+ type=ref,event=tag
168
+ type=sha,prefix=git-
169
+ type=semver,pattern={{version}}
170
+ type=semver,pattern={{major}}.{{minor}}
171
+ type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=cuda
172
+ flavor: |
173
+ latest=${{ github.ref == 'refs/heads/main' }}
174
+ suffix=-cuda,onlatest=true
175
+
176
+ - name: Extract metadata for Docker cache
177
+ id: cache-meta
178
+ uses: docker/metadata-action@v5
179
+ with:
180
+ images: ${{ env.FULL_IMAGE_NAME }}
181
+ tags: |
182
+ type=ref,event=branch
183
+ ${{ github.ref_type == 'tag' && 'type=raw,value=main' || '' }}
184
+ flavor: |
185
+ prefix=cache-cuda-${{ matrix.platform }}-
186
+ latest=false
187
+
188
+ - name: Build Docker image (cuda)
189
+ uses: docker/build-push-action@v5
190
+ id: build
191
+ with:
192
+ context: .
193
+ push: true
194
+ platforms: ${{ matrix.platform }}
195
+ labels: ${{ steps.meta.outputs.labels }}
196
+ outputs: type=image,name=${{ env.FULL_IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
197
+ cache-from: type=registry,ref=${{ steps.cache-meta.outputs.tags }}
198
+ cache-to: type=registry,ref=${{ steps.cache-meta.outputs.tags }},mode=max
199
+ build-args: |
200
+ BUILD_HASH=${{ github.sha }}
201
+ USE_CUDA=true
202
+
203
+ - name: Export digest
204
+ run: |
205
+ mkdir -p /tmp/digests
206
+ digest="${{ steps.build.outputs.digest }}"
207
+ touch "/tmp/digests/${digest#sha256:}"
208
+
209
+ - name: Upload digest
210
+ uses: actions/upload-artifact@v4
211
+ with:
212
+ name: digests-cuda-${{ env.PLATFORM_PAIR }}
213
+ path: /tmp/digests/*
214
+ if-no-files-found: error
215
+ retention-days: 1
216
+
217
+ build-cuda126-image:
218
+ runs-on: ${{ matrix.runner }}
219
+ permissions:
220
+ contents: read
221
+ packages: write
222
+ strategy:
223
+ fail-fast: false
224
+ matrix:
225
+ include:
226
+ - platform: linux/amd64
227
+ runner: ubuntu-latest
228
+ - platform: linux/arm64
229
+ runner: ubuntu-24.04-arm
230
+
231
+ steps:
232
+ # GitHub Packages requires the entire repository name to be in lowercase
233
+ # although the repository owner has a lowercase username, this prevents some people from running actions after forking
234
+ - name: Set repository and image name to lowercase
235
+ run: |
236
+ echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
237
+ echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
238
+ env:
239
+ IMAGE_NAME: '${{ github.repository }}'
240
+
241
+ - name: Prepare
242
+ run: |
243
+ platform=${{ matrix.platform }}
244
+ echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
245
+
246
+ - name: Checkout repository
247
+ uses: actions/checkout@v5
248
+
249
+ - name: Set up QEMU
250
+ uses: docker/setup-qemu-action@v3
251
+
252
+ - name: Set up Docker Buildx
253
+ uses: docker/setup-buildx-action@v3
254
+
255
+ - name: Log in to the Container registry
256
+ uses: docker/login-action@v3
257
+ with:
258
+ registry: ${{ env.REGISTRY }}
259
+ username: ${{ github.actor }}
260
+ password: ${{ secrets.GITHUB_TOKEN }}
261
+
262
+ - name: Extract metadata for Docker images (cuda126 tag)
263
+ id: meta
264
+ uses: docker/metadata-action@v5
265
+ with:
266
+ images: ${{ env.FULL_IMAGE_NAME }}
267
+ tags: |
268
+ type=ref,event=branch
269
+ type=ref,event=tag
270
+ type=sha,prefix=git-
271
+ type=semver,pattern={{version}}
272
+ type=semver,pattern={{major}}.{{minor}}
273
+ type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=cuda126
274
+ flavor: |
275
+ latest=${{ github.ref == 'refs/heads/main' }}
276
+ suffix=-cuda126,onlatest=true
277
+
278
+ - name: Extract metadata for Docker cache
279
+ id: cache-meta
280
+ uses: docker/metadata-action@v5
281
+ with:
282
+ images: ${{ env.FULL_IMAGE_NAME }}
283
+ tags: |
284
+ type=ref,event=branch
285
+ ${{ github.ref_type == 'tag' && 'type=raw,value=main' || '' }}
286
+ flavor: |
287
+ prefix=cache-cuda126-${{ matrix.platform }}-
288
+ latest=false
289
+
290
+ - name: Build Docker image (cuda126)
291
+ uses: docker/build-push-action@v5
292
+ id: build
293
+ with:
294
+ context: .
295
+ push: true
296
+ platforms: ${{ matrix.platform }}
297
+ labels: ${{ steps.meta.outputs.labels }}
298
+ outputs: type=image,name=${{ env.FULL_IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
299
+ cache-from: type=registry,ref=${{ steps.cache-meta.outputs.tags }}
300
+ cache-to: type=registry,ref=${{ steps.cache-meta.outputs.tags }},mode=max
301
+ build-args: |
302
+ BUILD_HASH=${{ github.sha }}
303
+ USE_CUDA=true
304
+ USE_CUDA_VER=cu126
305
+
306
+ - name: Export digest
307
+ run: |
308
+ mkdir -p /tmp/digests
309
+ digest="${{ steps.build.outputs.digest }}"
310
+ touch "/tmp/digests/${digest#sha256:}"
311
+
312
+ - name: Upload digest
313
+ uses: actions/upload-artifact@v4
314
+ with:
315
+ name: digests-cuda126-${{ env.PLATFORM_PAIR }}
316
+ path: /tmp/digests/*
317
+ if-no-files-found: error
318
+ retention-days: 1
319
+
320
+ build-ollama-image:
321
+ runs-on: ${{ matrix.runner }}
322
+ permissions:
323
+ contents: read
324
+ packages: write
325
+ strategy:
326
+ fail-fast: false
327
+ matrix:
328
+ include:
329
+ - platform: linux/amd64
330
+ runner: ubuntu-latest
331
+ - platform: linux/arm64
332
+ runner: ubuntu-24.04-arm
333
+
334
+ steps:
335
+ # GitHub Packages requires the entire repository name to be in lowercase
336
+ # although the repository owner has a lowercase username, this prevents some people from running actions after forking
337
+ - name: Set repository and image name to lowercase
338
+ run: |
339
+ echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
340
+ echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
341
+ env:
342
+ IMAGE_NAME: '${{ github.repository }}'
343
+
344
+ - name: Prepare
345
+ run: |
346
+ platform=${{ matrix.platform }}
347
+ echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
348
+
349
+ - name: Checkout repository
350
+ uses: actions/checkout@v5
351
+
352
+ - name: Set up QEMU
353
+ uses: docker/setup-qemu-action@v3
354
+
355
+ - name: Set up Docker Buildx
356
+ uses: docker/setup-buildx-action@v3
357
+
358
+ - name: Log in to the Container registry
359
+ uses: docker/login-action@v3
360
+ with:
361
+ registry: ${{ env.REGISTRY }}
362
+ username: ${{ github.actor }}
363
+ password: ${{ secrets.GITHUB_TOKEN }}
364
+
365
+ - name: Extract metadata for Docker images (ollama tag)
366
+ id: meta
367
+ uses: docker/metadata-action@v5
368
+ with:
369
+ images: ${{ env.FULL_IMAGE_NAME }}
370
+ tags: |
371
+ type=ref,event=branch
372
+ type=ref,event=tag
373
+ type=sha,prefix=git-
374
+ type=semver,pattern={{version}}
375
+ type=semver,pattern={{major}}.{{minor}}
376
+ type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=ollama
377
+ flavor: |
378
+ latest=${{ github.ref == 'refs/heads/main' }}
379
+ suffix=-ollama,onlatest=true
380
+
381
+ - name: Extract metadata for Docker cache
382
+ id: cache-meta
383
+ uses: docker/metadata-action@v5
384
+ with:
385
+ images: ${{ env.FULL_IMAGE_NAME }}
386
+ tags: |
387
+ type=ref,event=branch
388
+ ${{ github.ref_type == 'tag' && 'type=raw,value=main' || '' }}
389
+ flavor: |
390
+ prefix=cache-ollama-${{ matrix.platform }}-
391
+ latest=false
392
+
393
+ - name: Build Docker image (ollama)
394
+ uses: docker/build-push-action@v5
395
+ id: build
396
+ with:
397
+ context: .
398
+ push: true
399
+ platforms: ${{ matrix.platform }}
400
+ labels: ${{ steps.meta.outputs.labels }}
401
+ outputs: type=image,name=${{ env.FULL_IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
402
+ cache-from: type=registry,ref=${{ steps.cache-meta.outputs.tags }}
403
+ cache-to: type=registry,ref=${{ steps.cache-meta.outputs.tags }},mode=max
404
+ build-args: |
405
+ BUILD_HASH=${{ github.sha }}
406
+ USE_OLLAMA=true
407
+
408
+ - name: Export digest
409
+ run: |
410
+ mkdir -p /tmp/digests
411
+ digest="${{ steps.build.outputs.digest }}"
412
+ touch "/tmp/digests/${digest#sha256:}"
413
+
414
+ - name: Upload digest
415
+ uses: actions/upload-artifact@v4
416
+ with:
417
+ name: digests-ollama-${{ env.PLATFORM_PAIR }}
418
+ path: /tmp/digests/*
419
+ if-no-files-found: error
420
+ retention-days: 1
421
+
422
+ build-slim-image:
423
+ runs-on: ${{ matrix.runner }}
424
+ permissions:
425
+ contents: read
426
+ packages: write
427
+ strategy:
428
+ fail-fast: false
429
+ matrix:
430
+ include:
431
+ - platform: linux/amd64
432
+ runner: ubuntu-latest
433
+ - platform: linux/arm64
434
+ runner: ubuntu-24.04-arm
435
+
436
+ steps:
437
+ # GitHub Packages requires the entire repository name to be in lowercase
438
+ # although the repository owner has a lowercase username, this prevents some people from running actions after forking
439
+ - name: Set repository and image name to lowercase
440
+ run: |
441
+ echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
442
+ echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
443
+ env:
444
+ IMAGE_NAME: '${{ github.repository }}'
445
+
446
+ - name: Prepare
447
+ run: |
448
+ platform=${{ matrix.platform }}
449
+ echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
450
+
451
+ - name: Checkout repository
452
+ uses: actions/checkout@v5
453
+
454
+ - name: Set up QEMU
455
+ uses: docker/setup-qemu-action@v3
456
+
457
+ - name: Set up Docker Buildx
458
+ uses: docker/setup-buildx-action@v3
459
+
460
+ - name: Log in to the Container registry
461
+ uses: docker/login-action@v3
462
+ with:
463
+ registry: ${{ env.REGISTRY }}
464
+ username: ${{ github.actor }}
465
+ password: ${{ secrets.GITHUB_TOKEN }}
466
+
467
+ - name: Extract metadata for Docker images (slim tag)
468
+ id: meta
469
+ uses: docker/metadata-action@v5
470
+ with:
471
+ images: ${{ env.FULL_IMAGE_NAME }}
472
+ tags: |
473
+ type=ref,event=branch
474
+ type=ref,event=tag
475
+ type=sha,prefix=git-
476
+ type=semver,pattern={{version}}
477
+ type=semver,pattern={{major}}.{{minor}}
478
+ type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=slim
479
+ flavor: |
480
+ latest=${{ github.ref == 'refs/heads/main' }}
481
+ suffix=-slim,onlatest=true
482
+
483
+ - name: Extract metadata for Docker cache
484
+ id: cache-meta
485
+ uses: docker/metadata-action@v5
486
+ with:
487
+ images: ${{ env.FULL_IMAGE_NAME }}
488
+ tags: |
489
+ type=ref,event=branch
490
+ ${{ github.ref_type == 'tag' && 'type=raw,value=main' || '' }}
491
+ flavor: |
492
+ prefix=cache-slim-${{ matrix.platform }}-
493
+ latest=false
494
+
495
+ - name: Build Docker image (slim)
496
+ uses: docker/build-push-action@v5
497
+ id: build
498
+ with:
499
+ context: .
500
+ push: true
501
+ platforms: ${{ matrix.platform }}
502
+ labels: ${{ steps.meta.outputs.labels }}
503
+ outputs: type=image,name=${{ env.FULL_IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
504
+ cache-from: type=registry,ref=${{ steps.cache-meta.outputs.tags }}
505
+ cache-to: type=registry,ref=${{ steps.cache-meta.outputs.tags }},mode=max
506
+ build-args: |
507
+ BUILD_HASH=${{ github.sha }}
508
+ USE_SLIM=true
509
+
510
+ - name: Export digest
511
+ run: |
512
+ mkdir -p /tmp/digests
513
+ digest="${{ steps.build.outputs.digest }}"
514
+ touch "/tmp/digests/${digest#sha256:}"
515
+
516
+ - name: Upload digest
517
+ uses: actions/upload-artifact@v4
518
+ with:
519
+ name: digests-slim-${{ env.PLATFORM_PAIR }}
520
+ path: /tmp/digests/*
521
+ if-no-files-found: error
522
+ retention-days: 1
523
+
524
+ merge-main-images:
525
+ runs-on: ubuntu-latest
526
+ needs: [build-main-image]
527
+ steps:
528
+ # GitHub Packages requires the entire repository name to be in lowercase
529
+ # although the repository owner has a lowercase username, this prevents some people from running actions after forking
530
+ - name: Set repository and image name to lowercase
531
+ run: |
532
+ echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
533
+ echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
534
+ env:
535
+ IMAGE_NAME: '${{ github.repository }}'
536
+
537
+ - name: Download digests
538
+ uses: actions/download-artifact@v5
539
+ with:
540
+ pattern: digests-main-*
541
+ path: /tmp/digests
542
+ merge-multiple: true
543
+
544
+ - name: Set up Docker Buildx
545
+ uses: docker/setup-buildx-action@v3
546
+
547
+ - name: Log in to the Container registry
548
+ uses: docker/login-action@v3
549
+ with:
550
+ registry: ${{ env.REGISTRY }}
551
+ username: ${{ github.actor }}
552
+ password: ${{ secrets.GITHUB_TOKEN }}
553
+
554
+ - name: Extract metadata for Docker images (default latest tag)
555
+ id: meta
556
+ uses: docker/metadata-action@v5
557
+ with:
558
+ images: ${{ env.FULL_IMAGE_NAME }}
559
+ tags: |
560
+ type=ref,event=branch
561
+ type=ref,event=tag
562
+ type=sha,prefix=git-
563
+ type=semver,pattern={{version}}
564
+ type=semver,pattern={{major}}.{{minor}}
565
+ flavor: |
566
+ latest=${{ github.ref == 'refs/heads/main' }}
567
+
568
+ - name: Create manifest list and push
569
+ working-directory: /tmp/digests
570
+ run: |
571
+ docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
572
+ $(printf '${{ env.FULL_IMAGE_NAME }}@sha256:%s ' *)
573
+
574
+ - name: Inspect image
575
+ run: |
576
+ docker buildx imagetools inspect ${{ env.FULL_IMAGE_NAME }}:${{ steps.meta.outputs.version }}
577
+
578
+ merge-cuda-images:
579
+ runs-on: ubuntu-latest
580
+ needs: [build-cuda-image]
581
+ steps:
582
+ # GitHub Packages requires the entire repository name to be in lowercase
583
+ # although the repository owner has a lowercase username, this prevents some people from running actions after forking
584
+ - name: Set repository and image name to lowercase
585
+ run: |
586
+ echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
587
+ echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
588
+ env:
589
+ IMAGE_NAME: '${{ github.repository }}'
590
+
591
+ - name: Download digests
592
+ uses: actions/download-artifact@v5
593
+ with:
594
+ pattern: digests-cuda-*
595
+ path: /tmp/digests
596
+ merge-multiple: true
597
+
598
+ - name: Set up Docker Buildx
599
+ uses: docker/setup-buildx-action@v3
600
+
601
+ - name: Log in to the Container registry
602
+ uses: docker/login-action@v3
603
+ with:
604
+ registry: ${{ env.REGISTRY }}
605
+ username: ${{ github.actor }}
606
+ password: ${{ secrets.GITHUB_TOKEN }}
607
+
608
+ - name: Extract metadata for Docker images (default latest tag)
609
+ id: meta
610
+ uses: docker/metadata-action@v5
611
+ with:
612
+ images: ${{ env.FULL_IMAGE_NAME }}
613
+ tags: |
614
+ type=ref,event=branch
615
+ type=ref,event=tag
616
+ type=sha,prefix=git-
617
+ type=semver,pattern={{version}}
618
+ type=semver,pattern={{major}}.{{minor}}
619
+ type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=cuda
620
+ flavor: |
621
+ latest=${{ github.ref == 'refs/heads/main' }}
622
+ suffix=-cuda,onlatest=true
623
+
624
+ - name: Create manifest list and push
625
+ working-directory: /tmp/digests
626
+ run: |
627
+ docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
628
+ $(printf '${{ env.FULL_IMAGE_NAME }}@sha256:%s ' *)
629
+
630
+ - name: Inspect image
631
+ run: |
632
+ docker buildx imagetools inspect ${{ env.FULL_IMAGE_NAME }}:${{ steps.meta.outputs.version }}
633
+
634
+ merge-cuda126-images:
635
+ runs-on: ubuntu-latest
636
+ needs: [build-cuda126-image]
637
+ steps:
638
+ # GitHub Packages requires the entire repository name to be in lowercase
639
+ # although the repository owner has a lowercase username, this prevents some people from running actions after forking
640
+ - name: Set repository and image name to lowercase
641
+ run: |
642
+ echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
643
+ echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
644
+ env:
645
+ IMAGE_NAME: '${{ github.repository }}'
646
+
647
+ - name: Download digests
648
+ uses: actions/download-artifact@v5
649
+ with:
650
+ pattern: digests-cuda126-*
651
+ path: /tmp/digests
652
+ merge-multiple: true
653
+
654
+ - name: Set up Docker Buildx
655
+ uses: docker/setup-buildx-action@v3
656
+
657
+ - name: Log in to the Container registry
658
+ uses: docker/login-action@v3
659
+ with:
660
+ registry: ${{ env.REGISTRY }}
661
+ username: ${{ github.actor }}
662
+ password: ${{ secrets.GITHUB_TOKEN }}
663
+
664
+ - name: Extract metadata for Docker images (default latest tag)
665
+ id: meta
666
+ uses: docker/metadata-action@v5
667
+ with:
668
+ images: ${{ env.FULL_IMAGE_NAME }}
669
+ tags: |
670
+ type=ref,event=branch
671
+ type=ref,event=tag
672
+ type=sha,prefix=git-
673
+ type=semver,pattern={{version}}
674
+ type=semver,pattern={{major}}.{{minor}}
675
+ type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=cuda126
676
+ flavor: |
677
+ latest=${{ github.ref == 'refs/heads/main' }}
678
+ suffix=-cuda126,onlatest=true
679
+
680
+ - name: Create manifest list and push
681
+ working-directory: /tmp/digests
682
+ run: |
683
+ docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
684
+ $(printf '${{ env.FULL_IMAGE_NAME }}@sha256:%s ' *)
685
+
686
+ - name: Inspect image
687
+ run: |
688
+ docker buildx imagetools inspect ${{ env.FULL_IMAGE_NAME }}:${{ steps.meta.outputs.version }}
689
+
690
+ merge-ollama-images:
691
+ runs-on: ubuntu-latest
692
+ needs: [build-ollama-image]
693
+ steps:
694
+ # GitHub Packages requires the entire repository name to be in lowercase
695
+ # although the repository owner has a lowercase username, this prevents some people from running actions after forking
696
+ - name: Set repository and image name to lowercase
697
+ run: |
698
+ echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
699
+ echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
700
+ env:
701
+ IMAGE_NAME: '${{ github.repository }}'
702
+
703
+ - name: Download digests
704
+ uses: actions/download-artifact@v5
705
+ with:
706
+ pattern: digests-ollama-*
707
+ path: /tmp/digests
708
+ merge-multiple: true
709
+
710
+ - name: Set up Docker Buildx
711
+ uses: docker/setup-buildx-action@v3
712
+
713
+ - name: Log in to the Container registry
714
+ uses: docker/login-action@v3
715
+ with:
716
+ registry: ${{ env.REGISTRY }}
717
+ username: ${{ github.actor }}
718
+ password: ${{ secrets.GITHUB_TOKEN }}
719
+
720
+ - name: Extract metadata for Docker images (default ollama tag)
721
+ id: meta
722
+ uses: docker/metadata-action@v5
723
+ with:
724
+ images: ${{ env.FULL_IMAGE_NAME }}
725
+ tags: |
726
+ type=ref,event=branch
727
+ type=ref,event=tag
728
+ type=sha,prefix=git-
729
+ type=semver,pattern={{version}}
730
+ type=semver,pattern={{major}}.{{minor}}
731
+ type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=ollama
732
+ flavor: |
733
+ latest=${{ github.ref == 'refs/heads/main' }}
734
+ suffix=-ollama,onlatest=true
735
+
736
+ - name: Create manifest list and push
737
+ working-directory: /tmp/digests
738
+ run: |
739
+ docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
740
+ $(printf '${{ env.FULL_IMAGE_NAME }}@sha256:%s ' *)
741
+
742
+ - name: Inspect image
743
+ run: |
744
+ docker buildx imagetools inspect ${{ env.FULL_IMAGE_NAME }}:${{ steps.meta.outputs.version }}
745
+
746
+ merge-slim-images:
747
+ runs-on: ubuntu-latest
748
+ needs: [build-slim-image]
749
+ steps:
750
+ # GitHub Packages requires the entire repository name to be in lowercase
751
+ # although the repository owner has a lowercase username, this prevents some people from running actions after forking
752
+ - name: Set repository and image name to lowercase
753
+ run: |
754
+ echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
755
+ echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
756
+ env:
757
+ IMAGE_NAME: '${{ github.repository }}'
758
+
759
+ - name: Download digests
760
+ uses: actions/download-artifact@v5
761
+ with:
762
+ pattern: digests-slim-*
763
+ path: /tmp/digests
764
+ merge-multiple: true
765
+
766
+ - name: Set up Docker Buildx
767
+ uses: docker/setup-buildx-action@v3
768
+
769
+ - name: Log in to the Container registry
770
+ uses: docker/login-action@v3
771
+ with:
772
+ registry: ${{ env.REGISTRY }}
773
+ username: ${{ github.actor }}
774
+ password: ${{ secrets.GITHUB_TOKEN }}
775
+
776
+ - name: Extract metadata for Docker images (default slim tag)
777
+ id: meta
778
+ uses: docker/metadata-action@v5
779
+ with:
780
+ images: ${{ env.FULL_IMAGE_NAME }}
781
+ tags: |
782
+ type=ref,event=branch
783
+ type=ref,event=tag
784
+ type=sha,prefix=git-
785
+ type=semver,pattern={{version}}
786
+ type=semver,pattern={{major}}.{{minor}}
787
+ type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=slim
788
+ flavor: |
789
+ latest=${{ github.ref == 'refs/heads/main' }}
790
+ suffix=-slim,onlatest=true
791
+
792
+ - name: Create manifest list and push
793
+ working-directory: /tmp/digests
794
+ run: |
795
+ docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
796
+ $(printf '${{ env.FULL_IMAGE_NAME }}@sha256:%s ' *)
797
+
798
+ - name: Inspect image
799
+ run: |
800
+ docker buildx imagetools inspect ${{ env.FULL_IMAGE_NAME }}:${{ steps.meta.outputs.version }}
.github/workflows/format-backend.yaml ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Python CI
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ - dev
8
+ paths:
9
+ - 'backend/**'
10
+ - 'pyproject.toml'
11
+ - 'uv.lock'
12
+ pull_request:
13
+ branches:
14
+ - main
15
+ - dev
16
+ paths:
17
+ - 'backend/**'
18
+ - 'pyproject.toml'
19
+ - 'uv.lock'
20
+
21
+ jobs:
22
+ build:
23
+ name: 'Format Backend'
24
+ runs-on: ubuntu-latest
25
+
26
+ strategy:
27
+ matrix:
28
+ python-version:
29
+ - 3.11.x
30
+ - 3.12.x
31
+
32
+ steps:
33
+ - uses: actions/checkout@v5
34
+
35
+ - name: Set up Python
36
+ uses: actions/setup-python@v6
37
+ with:
38
+ python-version: '${{ matrix.python-version }}'
39
+
40
+ - name: Install dependencies
41
+ run: |
42
+ python -m pip install --upgrade pip
43
+ pip install black
44
+
45
+ - name: Format backend
46
+ run: npm run format:backend
47
+
48
+ - name: Check for changes after format
49
+ run: git diff --exit-code
.github/workflows/format-build-frontend.yaml ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Frontend Build
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ - dev
8
+ paths-ignore:
9
+ - 'backend/**'
10
+ - 'pyproject.toml'
11
+ - 'uv.lock'
12
+ pull_request:
13
+ branches:
14
+ - main
15
+ - dev
16
+ paths-ignore:
17
+ - 'backend/**'
18
+ - 'pyproject.toml'
19
+ - 'uv.lock'
20
+
21
+ jobs:
22
+ build:
23
+ name: 'Format & Build Frontend'
24
+ runs-on: ubuntu-latest
25
+ steps:
26
+ - name: Checkout Repository
27
+ uses: actions/checkout@v5
28
+
29
+ - name: Setup Node.js
30
+ uses: actions/setup-node@v5
31
+ with:
32
+ node-version: '22'
33
+
34
+ - name: Install Dependencies
35
+ run: npm install --force
36
+
37
+ - name: Format Frontend
38
+ run: npm run format
39
+
40
+ - name: Run i18next
41
+ run: npm run i18n:parse
42
+
43
+ - name: Check for Changes After Format
44
+ run: git diff --exit-code
45
+
46
+ - name: Build Frontend
47
+ run: npm run build
48
+
49
+ test-frontend:
50
+ name: 'Frontend Unit Tests'
51
+ runs-on: ubuntu-latest
52
+ steps:
53
+ - name: Checkout Repository
54
+ uses: actions/checkout@v5
55
+
56
+ - name: Setup Node.js
57
+ uses: actions/setup-node@v5
58
+ with:
59
+ node-version: '22'
60
+
61
+ - name: Install Dependencies
62
+ run: npm ci --force
63
+
64
+ - name: Run vitest
65
+ run: npm run test:frontend
.github/workflows/integration-test.disabled ADDED
@@ -0,0 +1,255 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Integration Test
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main
7
+ - dev
8
+ pull_request:
9
+ branches:
10
+ - main
11
+ - dev
12
+
13
+ jobs:
14
+ cypress-run:
15
+ name: Run Cypress Integration Tests
16
+ runs-on: ubuntu-latest
17
+ steps:
18
+ - name: Maximize build space
19
+ uses: AdityaGarg8/remove-unwanted-software@v4.1
20
+ with:
21
+ remove-android: 'true'
22
+ remove-haskell: 'true'
23
+ remove-codeql: 'true'
24
+
25
+ - name: Checkout Repository
26
+ uses: actions/checkout@v4
27
+
28
+ - name: Build and run Compose Stack
29
+ run: |
30
+ docker compose \
31
+ --file docker-compose.yaml \
32
+ --file docker-compose.api.yaml \
33
+ --file docker-compose.a1111-test.yaml \
34
+ up --detach --build
35
+
36
+ - name: Delete Docker build cache
37
+ run: |
38
+ docker builder prune --all --force
39
+
40
+ - name: Wait for Ollama to be up
41
+ timeout-minutes: 5
42
+ run: |
43
+ until curl --output /dev/null --silent --fail http://localhost:11434; do
44
+ printf '.'
45
+ sleep 1
46
+ done
47
+ echo "Service is up!"
48
+
49
+ - name: Preload Ollama model
50
+ run: |
51
+ docker exec ollama ollama pull qwen:0.5b-chat-v1.5-q2_K
52
+
53
+ - name: Cypress run
54
+ uses: cypress-io/github-action@v6
55
+ env:
56
+ LIBGL_ALWAYS_SOFTWARE: 1
57
+ with:
58
+ browser: chrome
59
+ wait-on: 'http://localhost:3000'
60
+ config: baseUrl=http://localhost:3000
61
+
62
+ - uses: actions/upload-artifact@v4
63
+ if: always()
64
+ name: Upload Cypress videos
65
+ with:
66
+ name: cypress-videos
67
+ path: cypress/videos
68
+ if-no-files-found: ignore
69
+
70
+ - name: Extract Compose logs
71
+ if: always()
72
+ run: |
73
+ docker compose logs > compose-logs.txt
74
+
75
+ - uses: actions/upload-artifact@v4
76
+ if: always()
77
+ name: Upload Compose logs
78
+ with:
79
+ name: compose-logs
80
+ path: compose-logs.txt
81
+ if-no-files-found: ignore
82
+
83
+ # pytest:
84
+ # name: Run Backend Tests
85
+ # runs-on: ubuntu-latest
86
+ # steps:
87
+ # - uses: actions/checkout@v4
88
+
89
+ # - name: Set up Python
90
+ # uses: actions/setup-python@v5
91
+ # with:
92
+ # python-version: ${{ matrix.python-version }}
93
+
94
+ # - name: Install dependencies
95
+ # run: |
96
+ # python -m pip install --upgrade pip
97
+ # pip install -r backend/requirements.txt
98
+
99
+ # - name: pytest run
100
+ # run: |
101
+ # ls -al
102
+ # cd backend
103
+ # PYTHONPATH=. pytest . -o log_cli=true -o log_cli_level=INFO
104
+
105
+ migration_test:
106
+ name: Run Migration Tests
107
+ runs-on: ubuntu-latest
108
+ services:
109
+ postgres:
110
+ image: postgres
111
+ env:
112
+ POSTGRES_PASSWORD: postgres
113
+ options: >-
114
+ --health-cmd pg_isready
115
+ --health-interval 10s
116
+ --health-timeout 5s
117
+ --health-retries 5
118
+ ports:
119
+ - 5432:5432
120
+ # mysql:
121
+ # image: mysql
122
+ # env:
123
+ # MYSQL_ROOT_PASSWORD: mysql
124
+ # MYSQL_DATABASE: mysql
125
+ # options: >-
126
+ # --health-cmd "mysqladmin ping -h localhost"
127
+ # --health-interval 10s
128
+ # --health-timeout 5s
129
+ # --health-retries 5
130
+ # ports:
131
+ # - 3306:3306
132
+ steps:
133
+ - name: Checkout Repository
134
+ uses: actions/checkout@v4
135
+
136
+ - name: Set up Python
137
+ uses: actions/setup-python@v5
138
+ with:
139
+ python-version: ${{ matrix.python-version }}
140
+
141
+ - name: Set up uv
142
+ uses: yezz123/setup-uv@v4
143
+ with:
144
+ uv-venv: venv
145
+
146
+ - name: Activate virtualenv
147
+ run: |
148
+ . venv/bin/activate
149
+ echo PATH=$PATH >> $GITHUB_ENV
150
+
151
+ - name: Install dependencies
152
+ run: |
153
+ uv pip install -r backend/requirements.txt
154
+
155
+ - name: Test backend with SQLite
156
+ id: sqlite
157
+ env:
158
+ WEBUI_SECRET_KEY: secret-key
159
+ GLOBAL_LOG_LEVEL: debug
160
+ run: |
161
+ cd backend
162
+ uvicorn open_webui.main:app --port "8080" --forwarded-allow-ips '*' &
163
+ UVICORN_PID=$!
164
+ # Wait up to 40 seconds for the server to start
165
+ for i in {1..40}; do
166
+ curl -s http://localhost:8080/api/config > /dev/null && break
167
+ sleep 1
168
+ if [ $i -eq 40 ]; then
169
+ echo "Server failed to start"
170
+ kill -9 $UVICORN_PID
171
+ exit 1
172
+ fi
173
+ done
174
+ # Check that the server is still running after 5 seconds
175
+ sleep 5
176
+ if ! kill -0 $UVICORN_PID; then
177
+ echo "Server has stopped"
178
+ exit 1
179
+ fi
180
+
181
+ - name: Test backend with Postgres
182
+ if: success() || steps.sqlite.conclusion == 'failure'
183
+ env:
184
+ WEBUI_SECRET_KEY: secret-key
185
+ GLOBAL_LOG_LEVEL: debug
186
+ DATABASE_URL: postgresql://postgres:postgres@localhost:5432/postgres
187
+ DATABASE_POOL_SIZE: 10
188
+ DATABASE_POOL_MAX_OVERFLOW: 10
189
+ DATABASE_POOL_TIMEOUT: 30
190
+ run: |
191
+ cd backend
192
+ uvicorn open_webui.main:app --port "8081" --forwarded-allow-ips '*' &
193
+ UVICORN_PID=$!
194
+ # Wait up to 20 seconds for the server to start
195
+ for i in {1..20}; do
196
+ curl -s http://localhost:8081/api/config > /dev/null && break
197
+ sleep 1
198
+ if [ $i -eq 20 ]; then
199
+ echo "Server failed to start"
200
+ kill -9 $UVICORN_PID
201
+ exit 1
202
+ fi
203
+ done
204
+ # Check that the server is still running after 5 seconds
205
+ sleep 5
206
+ if ! kill -0 $UVICORN_PID; then
207
+ echo "Server has stopped"
208
+ exit 1
209
+ fi
210
+
211
+ # Check that service will reconnect to postgres when connection will be closed
212
+ status_code=$(curl --write-out %{http_code} -s --output /dev/null http://localhost:8081/health/db)
213
+ if [[ "$status_code" -ne 200 ]] ; then
214
+ echo "Server has failed before postgres reconnect check"
215
+ exit 1
216
+ fi
217
+
218
+ echo "Terminating all connections to postgres..."
219
+ python -c "import os, psycopg2 as pg2; \
220
+ conn = pg2.connect(dsn=os.environ['DATABASE_URL'].replace('+pool', '')); \
221
+ cur = conn.cursor(); \
222
+ cur.execute('SELECT pg_terminate_backend(psa.pid) FROM pg_stat_activity psa WHERE datname = current_database() AND pid <> pg_backend_pid();')"
223
+
224
+ status_code=$(curl --write-out %{http_code} -s --output /dev/null http://localhost:8081/health/db)
225
+ if [[ "$status_code" -ne 200 ]] ; then
226
+ echo "Server has not reconnected to postgres after connection was closed: returned status $status_code"
227
+ exit 1
228
+ fi
229
+
230
+ # - name: Test backend with MySQL
231
+ # if: success() || steps.sqlite.conclusion == 'failure' || steps.postgres.conclusion == 'failure'
232
+ # env:
233
+ # WEBUI_SECRET_KEY: secret-key
234
+ # GLOBAL_LOG_LEVEL: debug
235
+ # DATABASE_URL: mysql://root:mysql@localhost:3306/mysql
236
+ # run: |
237
+ # cd backend
238
+ # uvicorn open_webui.main:app --port "8083" --forwarded-allow-ips '*' &
239
+ # UVICORN_PID=$!
240
+ # # Wait up to 20 seconds for the server to start
241
+ # for i in {1..20}; do
242
+ # curl -s http://localhost:8083/api/config > /dev/null && break
243
+ # sleep 1
244
+ # if [ $i -eq 20 ]; then
245
+ # echo "Server failed to start"
246
+ # kill -9 $UVICORN_PID
247
+ # exit 1
248
+ # fi
249
+ # done
250
+ # # Check that the server is still running after 5 seconds
251
+ # sleep 5
252
+ # if ! kill -0 $UVICORN_PID; then
253
+ # echo "Server has stopped"
254
+ # exit 1
255
+ # fi
.github/workflows/lint-backend.disabled ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Python CI
2
+ on:
3
+ push:
4
+ branches: ['main']
5
+ pull_request:
6
+ jobs:
7
+ build:
8
+ name: 'Lint Backend'
9
+ env:
10
+ PUBLIC_API_BASE_URL: ''
11
+ runs-on: ubuntu-latest
12
+ strategy:
13
+ matrix:
14
+ node-version:
15
+ - latest
16
+ steps:
17
+ - uses: actions/checkout@v4
18
+ - name: Use Python
19
+ uses: actions/setup-python@v5
20
+ - name: Use Bun
21
+ uses: oven-sh/setup-bun@v1
22
+ - name: Install dependencies
23
+ run: |
24
+ python -m pip install --upgrade pip
25
+ pip install pylint
26
+ - name: Lint backend
27
+ run: bun run lint:backend
.github/workflows/lint-frontend.disabled ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Bun CI
2
+ on:
3
+ push:
4
+ branches: ['main']
5
+ pull_request:
6
+ jobs:
7
+ build:
8
+ name: 'Lint Frontend'
9
+ env:
10
+ PUBLIC_API_BASE_URL: ''
11
+ runs-on: ubuntu-latest
12
+ steps:
13
+ - uses: actions/checkout@v4
14
+ - name: Use Bun
15
+ uses: oven-sh/setup-bun@v1
16
+ - run: bun --version
17
+ - name: Install frontend dependencies
18
+ run: bun install --frozen-lockfile
19
+ - run: bun run lint:frontend
20
+ - run: bun run lint:types
21
+ if: success() || failure()
.github/workflows/release-pypi.yml ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Release to PyPI
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - main # or whatever branch you want to use
7
+ - pypi-release
8
+
9
+ jobs:
10
+ release:
11
+ runs-on: ubuntu-latest
12
+ environment:
13
+ name: pypi
14
+ url: https://pypi.org/p/open-webui
15
+ permissions:
16
+ id-token: write
17
+ steps:
18
+ - name: Checkout repository
19
+ uses: actions/checkout@v5
20
+ with:
21
+ fetch-depth: 0
22
+ - name: Install Git
23
+ run: sudo apt-get update && sudo apt-get install -y git
24
+ - uses: actions/setup-node@v5
25
+ with:
26
+ node-version: 22
27
+ - uses: actions/setup-python@v6
28
+ with:
29
+ python-version: 3.11
30
+ - name: Build
31
+ run: |
32
+ python -m pip install --upgrade pip
33
+ pip install build
34
+ python -m build .
35
+ - name: Publish package distributions to PyPI
36
+ uses: pypa/gh-action-pypi-publish@release/v1
.gitignore ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ x.py
2
+ yarn.lock
3
+ .DS_Store
4
+ node_modules
5
+ /build
6
+ /.svelte-kit
7
+ /package
8
+ .myenv/
9
+ .env
10
+ .webui_secret_key
11
+ .env.*
12
+ !.env.example
13
+ vite.config.js.timestamp-*
14
+ vite.config.ts.timestamp-*
15
+ # Byte-compiled / optimized / DLL files
16
+ __pycache__/
17
+ *.py[cod]
18
+ *$py.class
19
+ .nvmrc
20
+ CLAUDE.md
21
+ # C extensions
22
+ *.so
23
+
24
+ # Pyodide distribution
25
+ static/pyodide/*
26
+ !static/pyodide/pyodide-lock.json
27
+
28
+ # Distribution / packaging
29
+ .Python
30
+ build/
31
+ develop-eggs/
32
+ dist/
33
+ downloads/
34
+ eggs/
35
+ .eggs/
36
+ lib64/
37
+ parts/
38
+ sdist/
39
+ var/
40
+ wheels/
41
+ share/python-wheels/
42
+ *.egg-info/
43
+ .installed.cfg
44
+ *.egg
45
+ MANIFEST
46
+
47
+ # PyInstaller
48
+ # Usually these files are written by a python script from a template
49
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
50
+ *.manifest
51
+ *.spec
52
+
53
+ # Installer logs
54
+ pip-log.txt
55
+ pip-delete-this-directory.txt
56
+
57
+ # Unit test / coverage reports
58
+ htmlcov/
59
+ .tox/
60
+ .nox/
61
+ .coverage
62
+ .coverage.*
63
+ .cache
64
+ nosetests.xml
65
+ coverage.xml
66
+ *.cover
67
+ *.py,cover
68
+ .hypothesis/
69
+ .pytest_cache/
70
+ cover/
71
+
72
+ # Translations
73
+ *.mo
74
+ *.pot
75
+
76
+ # Django stuff:
77
+ *.log
78
+ local_settings.py
79
+ db.sqlite3
80
+ db.sqlite3-journal
81
+
82
+ # Flask stuff:
83
+ instance/
84
+ .webassets-cache
85
+
86
+ # Scrapy stuff:
87
+ .scrapy
88
+
89
+ # Sphinx documentation
90
+ docs/_build/
91
+
92
+ # PyBuilder
93
+ .pybuilder/
94
+ target/
95
+
96
+ # Jupyter Notebook
97
+ .ipynb_checkpoints
98
+
99
+ # IPython
100
+ profile_default/
101
+ ipython_config.py
102
+
103
+ # pyenv
104
+ # For a library or package, you might want to ignore these files since the code is
105
+ # intended to run in multiple environments; otherwise, check them in:
106
+ # .python-version
107
+
108
+ # pipenv
109
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
110
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
111
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
112
+ # install all needed dependencies.
113
+ #Pipfile.lock
114
+
115
+ # poetry
116
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
117
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
118
+ # commonly ignored for libraries.
119
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
120
+ #poetry.lock
121
+
122
+ # pdm
123
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
124
+ #pdm.lock
125
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
126
+ # in version control.
127
+ # https://pdm.fming.dev/#use-with-ide
128
+ .pdm.toml
129
+
130
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
131
+ __pypackages__/
132
+
133
+ # Celery stuff
134
+ celerybeat-schedule
135
+ celerybeat.pid
136
+
137
+ # SageMath parsed files
138
+ *.sage.py
139
+
140
+ # Environments
141
+ .env
142
+ .venv
143
+ env/
144
+ venv/
145
+ ENV/
146
+ env.bak/
147
+ venv.bak/
148
+
149
+ # Spyder project settings
150
+ .spyderproject
151
+ .spyproject
152
+
153
+ # Rope project settings
154
+ .ropeproject
155
+
156
+ # mkdocs documentation
157
+ /site
158
+
159
+ # mypy
160
+ .mypy_cache/
161
+ .dmypy.json
162
+ dmypy.json
163
+
164
+ # Pyre type checker
165
+ .pyre/
166
+
167
+ # pytype static type analyzer
168
+ .pytype/
169
+
170
+ # Cython debug symbols
171
+ cython_debug/
172
+
173
+ # PyCharm
174
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
175
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
176
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
177
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
178
+ .idea/
179
+
180
+ # Logs
181
+ logs
182
+ *.log
183
+ npm-debug.log*
184
+ yarn-debug.log*
185
+ yarn-error.log*
186
+ lerna-debug.log*
187
+ .pnpm-debug.log*
188
+
189
+ # Diagnostic reports (https://nodejs.org/api/report.html)
190
+ report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
191
+
192
+ # Runtime data
193
+ pids
194
+ *.pid
195
+ *.seed
196
+ *.pid.lock
197
+
198
+ # Directory for instrumented libs generated by jscoverage/JSCover
199
+ lib-cov
200
+
201
+ # Coverage directory used by tools like istanbul
202
+ coverage
203
+ *.lcov
204
+
205
+ # nyc test coverage
206
+ .nyc_output
207
+
208
+ # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
209
+ .grunt
210
+
211
+ # Bower dependency directory (https://bower.io/)
212
+ bower_components
213
+
214
+ # node-waf configuration
215
+ .lock-wscript
216
+
217
+ # Compiled binary addons (https://nodejs.org/api/addons.html)
218
+ build/Release
219
+
220
+ # Dependency directories
221
+ node_modules/
222
+ jspm_packages/
223
+
224
+ # Snowpack dependency directory (https://snowpack.dev/)
225
+ web_modules/
226
+
227
+ # TypeScript cache
228
+ *.tsbuildinfo
229
+
230
+ # Optional npm cache directory
231
+ .npm
232
+
233
+ # Optional eslint cache
234
+ .eslintcache
235
+
236
+ # Optional stylelint cache
237
+ .stylelintcache
238
+
239
+ # Microbundle cache
240
+ .rpt2_cache/
241
+ .rts2_cache_cjs/
242
+ .rts2_cache_es/
243
+ .rts2_cache_umd/
244
+
245
+ # Optional REPL history
246
+ .node_repl_history
247
+
248
+ # Output of 'npm pack'
249
+ *.tgz
250
+
251
+ # Yarn Integrity file
252
+ .yarn-integrity
253
+
254
+ # dotenv environment variable files
255
+ .env
256
+ .env.development.local
257
+ .env.test.local
258
+ .env.production.local
259
+ .env.local
260
+
261
+ # parcel-bundler cache (https://parceljs.org/)
262
+ .cache
263
+ .parcel-cache
264
+
265
+ # Next.js build output
266
+ .next
267
+ out
268
+
269
+ # Nuxt.js build / generate output
270
+ .nuxt
271
+ dist
272
+
273
+ # Gatsby files
274
+ .cache/
275
+ # Comment in the public line in if your project uses Gatsby and not Next.js
276
+ # https://nextjs.org/blog/next-9-1#public-directory-support
277
+ # public
278
+
279
+ # vuepress build output
280
+ .vuepress/dist
281
+
282
+ # vuepress v2.x temp and cache directory
283
+ .temp
284
+ .cache
285
+
286
+ # Docusaurus cache and generated files
287
+ .docusaurus
288
+
289
+ # Serverless directories
290
+ .serverless/
291
+
292
+ # FuseBox cache
293
+ .fusebox/
294
+
295
+ # DynamoDB Local files
296
+ .dynamodb/
297
+
298
+ # TernJS port file
299
+ .tern-port
300
+
301
+ # Stores VSCode versions used for testing VSCode extensions
302
+ .vscode-test
303
+
304
+ # yarn v2
305
+ .yarn/cache
306
+ .yarn/unplugged
307
+ .yarn/build-state.yml
308
+ .yarn/install-state.gz
309
+ .pnp.*
310
+
311
+ # cypress artifacts
312
+ cypress/videos
313
+ cypress/screenshots
314
+ .vscode/settings.json
.npmrc ADDED
@@ -0,0 +1 @@
 
 
1
+ engine-strict=true
.prettierignore ADDED
@@ -0,0 +1,316 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Ignore files for PNPM, NPM and YARN
2
+ pnpm-lock.yaml
3
+ package-lock.json
4
+ yarn.lock
5
+
6
+ kubernetes/
7
+
8
+ # Copy of .gitignore
9
+ .DS_Store
10
+ node_modules
11
+ /build
12
+ /.svelte-kit
13
+ /package
14
+ .env
15
+ .env.*
16
+ !.env.example
17
+ vite.config.js.timestamp-*
18
+ vite.config.ts.timestamp-*
19
+ # Byte-compiled / optimized / DLL files
20
+ __pycache__/
21
+ *.py[cod]
22
+ *$py.class
23
+
24
+ # C extensions
25
+ *.so
26
+
27
+ # Distribution / packaging
28
+ .Python
29
+ build/
30
+ develop-eggs/
31
+ dist/
32
+ downloads/
33
+ eggs/
34
+ .eggs/
35
+ lib64/
36
+ parts/
37
+ sdist/
38
+ var/
39
+ wheels/
40
+ share/python-wheels/
41
+ *.egg-info/
42
+ .installed.cfg
43
+ *.egg
44
+ MANIFEST
45
+
46
+ # PyInstaller
47
+ # Usually these files are written by a python script from a template
48
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
49
+ *.manifest
50
+ *.spec
51
+
52
+ # Installer logs
53
+ pip-log.txt
54
+ pip-delete-this-directory.txt
55
+
56
+ # Unit test / coverage reports
57
+ htmlcov/
58
+ .tox/
59
+ .nox/
60
+ .coverage
61
+ .coverage.*
62
+ .cache
63
+ nosetests.xml
64
+ coverage.xml
65
+ *.cover
66
+ *.py,cover
67
+ .hypothesis/
68
+ .pytest_cache/
69
+ cover/
70
+
71
+ # Translations
72
+ *.mo
73
+ *.pot
74
+
75
+ # Django stuff:
76
+ *.log
77
+ local_settings.py
78
+ db.sqlite3
79
+ db.sqlite3-journal
80
+
81
+ # Flask stuff:
82
+ instance/
83
+ .webassets-cache
84
+
85
+ # Scrapy stuff:
86
+ .scrapy
87
+
88
+ # Sphinx documentation
89
+ docs/_build/
90
+
91
+ # PyBuilder
92
+ .pybuilder/
93
+ target/
94
+
95
+ # Jupyter Notebook
96
+ .ipynb_checkpoints
97
+
98
+ # IPython
99
+ profile_default/
100
+ ipython_config.py
101
+
102
+ # pyenv
103
+ # For a library or package, you might want to ignore these files since the code is
104
+ # intended to run in multiple environments; otherwise, check them in:
105
+ # .python-version
106
+
107
+ # pipenv
108
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
109
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
110
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
111
+ # install all needed dependencies.
112
+ #Pipfile.lock
113
+
114
+ # poetry
115
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
116
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
117
+ # commonly ignored for libraries.
118
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
119
+ #poetry.lock
120
+
121
+ # pdm
122
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
123
+ #pdm.lock
124
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
125
+ # in version control.
126
+ # https://pdm.fming.dev/#use-with-ide
127
+ .pdm.toml
128
+
129
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
130
+ __pypackages__/
131
+
132
+ # Celery stuff
133
+ celerybeat-schedule
134
+ celerybeat.pid
135
+
136
+ # SageMath parsed files
137
+ *.sage.py
138
+
139
+ # Environments
140
+ .env
141
+ .venv
142
+ env/
143
+ venv/
144
+ ENV/
145
+ env.bak/
146
+ venv.bak/
147
+
148
+ # Spyder project settings
149
+ .spyderproject
150
+ .spyproject
151
+
152
+ # Rope project settings
153
+ .ropeproject
154
+
155
+ # mkdocs documentation
156
+ /site
157
+
158
+ # mypy
159
+ .mypy_cache/
160
+ .dmypy.json
161
+ dmypy.json
162
+
163
+ # Pyre type checker
164
+ .pyre/
165
+
166
+ # pytype static type analyzer
167
+ .pytype/
168
+
169
+ # Cython debug symbols
170
+ cython_debug/
171
+
172
+ # PyCharm
173
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
174
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
175
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
176
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
177
+ .idea/
178
+
179
+ # Logs
180
+ logs
181
+ *.log
182
+ npm-debug.log*
183
+ yarn-debug.log*
184
+ yarn-error.log*
185
+ lerna-debug.log*
186
+ .pnpm-debug.log*
187
+
188
+ # Diagnostic reports (https://nodejs.org/api/report.html)
189
+ report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
190
+
191
+ # Runtime data
192
+ pids
193
+ *.pid
194
+ *.seed
195
+ *.pid.lock
196
+
197
+ # Directory for instrumented libs generated by jscoverage/JSCover
198
+ lib-cov
199
+
200
+ # Coverage directory used by tools like istanbul
201
+ coverage
202
+ *.lcov
203
+
204
+ # nyc test coverage
205
+ .nyc_output
206
+
207
+ # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
208
+ .grunt
209
+
210
+ # Bower dependency directory (https://bower.io/)
211
+ bower_components
212
+
213
+ # node-waf configuration
214
+ .lock-wscript
215
+
216
+ # Compiled binary addons (https://nodejs.org/api/addons.html)
217
+ build/Release
218
+
219
+ # Dependency directories
220
+ node_modules/
221
+ jspm_packages/
222
+
223
+ # Snowpack dependency directory (https://snowpack.dev/)
224
+ web_modules/
225
+
226
+ # TypeScript cache
227
+ *.tsbuildinfo
228
+
229
+ # Optional npm cache directory
230
+ .npm
231
+
232
+ # Optional eslint cache
233
+ .eslintcache
234
+
235
+ # Optional stylelint cache
236
+ .stylelintcache
237
+
238
+ # Microbundle cache
239
+ .rpt2_cache/
240
+ .rts2_cache_cjs/
241
+ .rts2_cache_es/
242
+ .rts2_cache_umd/
243
+
244
+ # Optional REPL history
245
+ .node_repl_history
246
+
247
+ # Output of 'npm pack'
248
+ *.tgz
249
+
250
+ # Yarn Integrity file
251
+ .yarn-integrity
252
+
253
+ # dotenv environment variable files
254
+ .env
255
+ .env.development.local
256
+ .env.test.local
257
+ .env.production.local
258
+ .env.local
259
+
260
+ # parcel-bundler cache (https://parceljs.org/)
261
+ .cache
262
+ .parcel-cache
263
+
264
+ # Next.js build output
265
+ .next
266
+ out
267
+
268
+ # Nuxt.js build / generate output
269
+ .nuxt
270
+ dist
271
+
272
+ # Gatsby files
273
+ .cache/
274
+ # Comment in the public line in if your project uses Gatsby and not Next.js
275
+ # https://nextjs.org/blog/next-9-1#public-directory-support
276
+ # public
277
+
278
+ # vuepress build output
279
+ .vuepress/dist
280
+
281
+ # vuepress v2.x temp and cache directory
282
+ .temp
283
+ .cache
284
+
285
+ # Docusaurus cache and generated files
286
+ .docusaurus
287
+
288
+ # Serverless directories
289
+ .serverless/
290
+
291
+ # FuseBox cache
292
+ .fusebox/
293
+
294
+ # DynamoDB Local files
295
+ .dynamodb/
296
+
297
+ # TernJS port file
298
+ .tern-port
299
+
300
+ # Stores VSCode versions used for testing VSCode extensions
301
+ .vscode-test
302
+
303
+ # yarn v2
304
+ .yarn/cache
305
+ .yarn/unplugged
306
+ .yarn/build-state.yml
307
+ .yarn/install-state.gz
308
+ .pnp.*
309
+
310
+ # cypress artifacts
311
+ cypress/videos
312
+ cypress/screenshots
313
+
314
+
315
+
316
+ /static/*
.prettierrc ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "useTabs": true,
3
+ "singleQuote": true,
4
+ "trailingComma": "none",
5
+ "printWidth": 100,
6
+ "plugins": ["prettier-plugin-svelte"],
7
+ "pluginSearchDirs": ["."],
8
+ "overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }],
9
+ "endOfLine": "lf"
10
+ }
CHANGELOG.md ADDED
The diff for this file is too large to render. See raw diff
 
CODE_OF_CONDUCT.md ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ As members, contributors, and leaders of this community, we pledge to make participation in our project a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socioeconomic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We are committed to creating and maintaining an open, respectful, and professional environment where positive contributions and meaningful discussions can flourish. By participating in this project, you agree to uphold these values and align your behavior to the standards outlined in this Code of Conduct.
8
+
9
+ ## Why These Standards Are Important
10
+
11
+ Projects rely on a community of volunteers dedicating their time, expertise, and effort toward a shared goal. These projects are inherently collaborative but also fragile, as the success of the project depends on the goodwill, energy, and productivity of those involved.
12
+
13
+ Maintaining a positive and respectful environment is essential to safeguarding the integrity of this project and protecting contributors' efforts. Behavior that disrupts this atmosphere—whether through hostility, entitlement, or unprofessional conduct—can severely harm the morale and productivity of the community. **Strict enforcement of these standards ensures a safe and supportive space for meaningful collaboration.**
14
+
15
+ This is a community where **respect and professionalism are mandatory.** Violations of these standards will result in **zero tolerance** and immediate enforcement to prevent disruption and ensure the well-being of all participants.
16
+
17
+ ## Our Standards
18
+
19
+ Examples of behavior that contribute to a positive and professional community include:
20
+
21
+ - **Respecting others.** Be considerate, listen actively, and engage with empathy toward others' viewpoints and experiences.
22
+ - **Constructive feedback.** Provide actionable, thoughtful, and respectful feedback that helps improve the project and encourages collaboration. Avoid unproductive negativity or hypercriticism.
23
+ - **Recognizing volunteer contributions.** Appreciate that contributors dedicate their free time and resources selflessly. Approach them with gratitude and patience.
24
+ - **Focusing on shared goals.** Collaborate in ways that prioritize the health, success, and sustainability of the community over individual agendas.
25
+
26
+ Examples of unacceptable behavior include:
27
+
28
+ - The use of discriminatory, demeaning, or sexualized language or behavior.
29
+ - Personal attacks, derogatory comments, trolling, or inflammatory political or ideological arguments.
30
+ - Harassment, intimidation, or any behavior intended to create a hostile, uncomfortable, or unsafe environment.
31
+ - Publishing others' private information (e.g., physical or email addresses) without explicit permission.
32
+ - **Entitlement, demand, or aggression toward contributors.** Volunteers are under no obligation to provide immediate or personalized support. Rude or dismissive behavior will not be tolerated.
33
+ - **Unproductive or destructive behavior.** This includes venting frustration as hostility ("tantrums"), hypercriticism, attention-seeking negativity, or anything that distracts from the project's goals.
34
+ - **Spamming and promotional exploitation.** Sharing irrelevant product promotions or self-promotion in the community is not allowed unless it directly contributes value to the discussion.
35
+
36
+ ### Feedback and Community Engagement
37
+
38
+ - **Constructive feedback is encouraged, but hostile or entitled behavior will result in immediate action.** If you disagree with elements of the project, we encourage you to offer meaningful improvements or fork the project if necessary. Healthy discussions and technical disagreements are welcome only when handled with professionalism.
39
+ - **Respect contributors' time and efforts.** No one is entitled to personalized or on-demand assistance. This is a community built on collaboration and shared effort; demanding or demeaning behavior undermines that trust and will not be allowed.
40
+
41
+ ### Zero Tolerance: No Warnings, Immediate Action
42
+
43
+ This community operates under a **zero-tolerance policy.** Any behavior deemed unacceptable under this Code of Conduct will result in **immediate enforcement, without prior warning.**
44
+
45
+ We employ this approach to ensure that unproductive or disruptive behavior does not escalate further or cause unnecessary harm to other contributors. The standards are clear, and violations of any kind—whether mild or severe—will be addressed decisively to protect the community.
46
+
47
+ ## Enforcement Responsibilities
48
+
49
+ Community leaders are responsible for upholding and enforcing these standards. They are empowered to take **immediate and appropriate action** to address any behaviors they deem unacceptable under this Code of Conduct. These actions are taken with the goal of protecting the community and preserving its safe, positive, and productive environment.
50
+
51
+ ## Scope
52
+
53
+ This Code of Conduct applies to all community spaces, including forums, repositories, social media accounts, and in-person events. It also applies when an individual represents the community in public settings, such as conferences or official communications.
54
+
55
+ Additionally, any behavior outside of these defined spaces that negatively impacts the community or its members may fall within the scope of this Code of Conduct.
56
+
57
+ ## Reporting Violations
58
+
59
+ Instances of unacceptable behavior can be reported to the leadership team at **hello@openwebui.com**. Reports will be handled promptly, confidentially, and with consideration for the safety and well-being of the reporter.
60
+
61
+ All community leaders are required to uphold confidentiality and impartiality when addressing reports of violations.
62
+
63
+ ## Enforcement Guidelines
64
+
65
+ ### Ban
66
+
67
+ **Community Impact**: Community leaders will issue a ban to any participant whose behavior is deemed unacceptable according to this Code of Conduct. Bans are enforced immediately and without prior notice.
68
+
69
+ A ban may be temporary or permanent, depending on the severity of the violation. This includes—but is not limited to—behavior such as:
70
+
71
+ - Harassment or abusive behavior toward contributors.
72
+ - Persistent negativity or hostility that disrupts the collaborative environment.
73
+ - Disrespectful, demanding, or aggressive interactions with others.
74
+ - Attempts to cause harm or sabotage the community.
75
+
76
+ **Consequence**: A banned individual is immediately removed from access to all community spaces, communication channels, and events. Community leaders reserve the right to enforce either a time-limited suspension or a permanent ban based on the specific circumstances of the violation.
77
+
78
+ This approach ensures that disruptive behaviors are addressed swiftly and decisively in order to maintain the integrity and productivity of the community.
79
+
80
+ ## Why Zero Tolerance Is Necessary
81
+
82
+ Projects thrive on collaboration, goodwill, and mutual respect. Toxic behaviors—such as entitlement, hostility, or persistent negativity—threaten not just individual contributors but the health of the project as a whole. Allowing such behaviors to persist robs contributors of their time, energy, and enthusiasm for the work they do.
83
+
84
+ By enforcing a zero-tolerance policy, we ensure that the community remains a safe, welcoming space for all participants. These measures are not about harshness—they are about protecting contributors and fostering a productive environment where innovation can thrive.
85
+
86
+ Our expectations are clear, and our enforcement reflects our commitment to this project's long-term success.
87
+
88
+ ## Attribution
89
+
90
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0, available at
91
+ https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
92
+
93
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
94
+
95
+ [homepage]: https://www.contributor-covenant.org
96
+
97
+ For answers to common questions about this code of conduct, see the FAQ at
98
+ https://www.contributor-covenant.org/faq. Translations are available at
99
+ https://www.contributor-covenant.org/translations.
CONTRIBUTOR_LICENSE_AGREEMENT ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Open WebUI Contributor License Agreement
2
+
3
+ By submitting my contributions to Open WebUI, I grant Open WebUI full freedom to use my work in any way they choose, under any terms they like, both now and in the future. This approach helps ensure the project remains unified, flexible, and easy to maintain, while empowering Open WebUI to respond quickly to the needs of its users and the wider community.
4
+
5
+ Taking part in this process means my work can be seamlessly integrated and combined with others, ensuring longevity and adaptability for everyone who benefits from the Open WebUI project. This collaborative approach strengthens the project’s future and helps guarantee that improvements can always be shared and distributed in the most effective way possible.
6
+
7
+ **_To the fullest extent permitted by law, my contributions are provided on an “as is” basis, with no warranties or guarantees of any kind, and I disclaim any liability for any issues or damages arising from their use or incorporation into the project, regardless of the type of legal claim._**
Dockerfile ADDED
@@ -0,0 +1,191 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # syntax=docker/dockerfile:1
2
+ # Initialize device type args
3
+ # use build args in the docker build command with --build-arg="BUILDARG=true"
4
+ ARG USE_CUDA=false
5
+ ARG USE_OLLAMA=false
6
+ ARG USE_SLIM=false
7
+ ARG USE_PERMISSION_HARDENING=false
8
+ # Tested with cu117 for CUDA 11 and cu121 for CUDA 12 (default)
9
+ ARG USE_CUDA_VER=cu128
10
+ # any sentence transformer model; models to use can be found at https://huggingface.co/models?library=sentence-transformers
11
+ # Leaderboard: https://huggingface.co/spaces/mteb/leaderboard
12
+ # for better performance and multilangauge support use "intfloat/multilingual-e5-large" (~2.5GB) or "intfloat/multilingual-e5-base" (~1.5GB)
13
+ # IMPORTANT: If you change the embedding model (sentence-transformers/all-MiniLM-L6-v2) and vice versa, you aren't able to use RAG Chat with your previous documents loaded in the WebUI! You need to re-embed them.
14
+ ARG USE_EMBEDDING_MODEL=sentence-transformers/all-MiniLM-L6-v2
15
+ ARG USE_RERANKING_MODEL=""
16
+
17
+ # Tiktoken encoding name; models to use can be found at https://huggingface.co/models?library=tiktoken
18
+ ARG USE_TIKTOKEN_ENCODING_NAME="cl100k_base"
19
+
20
+ ARG BUILD_HASH=dev-build
21
+ # Override at your own risk - non-root configurations are untested
22
+ ARG UID=0
23
+ ARG GID=0
24
+
25
+ ######## WebUI frontend ########
26
+ FROM --platform=$BUILDPLATFORM node:22-alpine3.20 AS build
27
+ ARG BUILD_HASH
28
+
29
+ # Set Node.js options (heap limit Allocation failed - JavaScript heap out of memory)
30
+ # ENV NODE_OPTIONS="--max-old-space-size=4096"
31
+
32
+ WORKDIR /app
33
+
34
+ # to store git revision in build
35
+ RUN apk add --no-cache git
36
+
37
+ COPY package.json package-lock.json ./
38
+ RUN npm install --force
39
+
40
+ COPY . .
41
+ ENV APP_BUILD_HASH=${BUILD_HASH}
42
+ RUN npm run build
43
+
44
+ ######## WebUI backend ########
45
+ FROM python:3.11-slim-bookworm AS base
46
+
47
+ # Use args
48
+ ARG USE_CUDA
49
+ ARG USE_OLLAMA
50
+ ARG USE_CUDA_VER
51
+ ARG USE_SLIM
52
+ ARG USE_PERMISSION_HARDENING
53
+ ARG USE_EMBEDDING_MODEL
54
+ ARG USE_RERANKING_MODEL
55
+ ARG UID
56
+ ARG GID
57
+
58
+ ## Basis ##
59
+ ENV ENV=prod \
60
+ PORT=8080 \
61
+ # pass build args to the build
62
+ USE_OLLAMA_DOCKER=${USE_OLLAMA} \
63
+ USE_CUDA_DOCKER=${USE_CUDA} \
64
+ USE_SLIM_DOCKER=${USE_SLIM} \
65
+ USE_CUDA_DOCKER_VER=${USE_CUDA_VER} \
66
+ USE_EMBEDDING_MODEL_DOCKER=${USE_EMBEDDING_MODEL} \
67
+ USE_RERANKING_MODEL_DOCKER=${USE_RERANKING_MODEL}
68
+
69
+ ## Basis URL Config ##
70
+ ENV OLLAMA_BASE_URL="/ollama" \
71
+ OPENAI_API_BASE_URL=""
72
+
73
+ ## API Key and Security Config ##
74
+ ENV OPENAI_API_KEY="" \
75
+ WEBUI_SECRET_KEY="" \
76
+ SCARF_NO_ANALYTICS=true \
77
+ DO_NOT_TRACK=true \
78
+ ANONYMIZED_TELEMETRY=false
79
+
80
+ #### Other models #########################################################
81
+ ## whisper TTS model settings ##
82
+ ENV WHISPER_MODEL="base" \
83
+ WHISPER_MODEL_DIR="/app/backend/data/cache/whisper/models"
84
+
85
+ ## RAG Embedding model settings ##
86
+ ENV RAG_EMBEDDING_MODEL="$USE_EMBEDDING_MODEL_DOCKER" \
87
+ RAG_RERANKING_MODEL="$USE_RERANKING_MODEL_DOCKER" \
88
+ SENTENCE_TRANSFORMERS_HOME="/app/backend/data/cache/embedding/models"
89
+
90
+ ## Tiktoken model settings ##
91
+ ENV TIKTOKEN_ENCODING_NAME="cl100k_base" \
92
+ TIKTOKEN_CACHE_DIR="/app/backend/data/cache/tiktoken"
93
+
94
+ ## Hugging Face download cache ##
95
+ ENV HF_HOME="/app/backend/data/cache/embedding/models"
96
+
97
+ ## Torch Extensions ##
98
+ # ENV TORCH_EXTENSIONS_DIR="/.cache/torch_extensions"
99
+
100
+ #### Other models ##########################################################
101
+
102
+ WORKDIR /app/backend
103
+
104
+ ENV HOME=/root
105
+ # Create user and group if not root
106
+ RUN if [ $UID -ne 0 ]; then \
107
+ if [ $GID -ne 0 ]; then \
108
+ addgroup --gid $GID app; \
109
+ fi; \
110
+ adduser --uid $UID --gid $GID --home $HOME --disabled-password --no-create-home app; \
111
+ fi
112
+
113
+ RUN mkdir -p $HOME/.cache/chroma
114
+ RUN echo -n 00000000-0000-0000-0000-000000000000 > $HOME/.cache/chroma/telemetry_user_id
115
+
116
+ # Make sure the user has access to the app and root directory
117
+ RUN chown -R $UID:$GID /app $HOME
118
+
119
+ # Install common system dependencies
120
+ RUN apt-get update && \
121
+ apt-get install -y --no-install-recommends \
122
+ git build-essential pandoc gcc netcat-openbsd curl jq \
123
+ python3-dev \
124
+ ffmpeg libsm6 libxext6 \
125
+ && rm -rf /var/lib/apt/lists/*
126
+
127
+ # install python dependencies
128
+ COPY --chown=$UID:$GID ./backend/requirements.txt ./requirements.txt
129
+
130
+ RUN pip3 install --no-cache-dir uv && \
131
+ if [ "$USE_CUDA" = "true" ]; then \
132
+ # If you use CUDA the whisper and embedding model will be downloaded on first use
133
+ pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/$USE_CUDA_DOCKER_VER --no-cache-dir && \
134
+ uv pip install --system -r requirements.txt --no-cache-dir && \
135
+ python -c "import os; from sentence_transformers import SentenceTransformer; SentenceTransformer(os.environ['RAG_EMBEDDING_MODEL'], device='cpu')" && \
136
+ python -c "import os; from faster_whisper import WhisperModel; WhisperModel(os.environ['WHISPER_MODEL'], device='cpu', compute_type='int8', download_root=os.environ['WHISPER_MODEL_DIR'])"; \
137
+ python -c "import os; import tiktoken; tiktoken.get_encoding(os.environ['TIKTOKEN_ENCODING_NAME'])"; \
138
+ else \
139
+ pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu --no-cache-dir && \
140
+ uv pip install --system -r requirements.txt --no-cache-dir && \
141
+ if [ "$USE_SLIM" != "true" ]; then \
142
+ python -c "import os; from sentence_transformers import SentenceTransformer; SentenceTransformer(os.environ['RAG_EMBEDDING_MODEL'], device='cpu')" && \
143
+ python -c "import os; from faster_whisper import WhisperModel; WhisperModel(os.environ['WHISPER_MODEL'], device='cpu', compute_type='int8', download_root=os.environ['WHISPER_MODEL_DIR'])"; \
144
+ python -c "import os; import tiktoken; tiktoken.get_encoding(os.environ['TIKTOKEN_ENCODING_NAME'])"; \
145
+ fi; \
146
+ fi; \
147
+ mkdir -p /app/backend/data && chown -R $UID:$GID /app/backend/data/ && \
148
+ rm -rf /var/lib/apt/lists/*;
149
+
150
+ # Install Ollama if requested
151
+ RUN if [ "$USE_OLLAMA" = "true" ]; then \
152
+ date +%s > /tmp/ollama_build_hash && \
153
+ echo "Cache broken at timestamp: `cat /tmp/ollama_build_hash`" && \
154
+ curl -fsSL https://ollama.com/install.sh | sh && \
155
+ rm -rf /var/lib/apt/lists/*; \
156
+ fi
157
+
158
+ # copy embedding weight from build
159
+ # RUN mkdir -p /root/.cache/chroma/onnx_models/all-MiniLM-L6-v2
160
+ # COPY --from=build /app/onnx /root/.cache/chroma/onnx_models/all-MiniLM-L6-v2/onnx
161
+
162
+ # copy built frontend files
163
+ COPY --chown=$UID:$GID --from=build /app/build /app/build
164
+ COPY --chown=$UID:$GID --from=build /app/CHANGELOG.md /app/CHANGELOG.md
165
+ COPY --chown=$UID:$GID --from=build /app/package.json /app/package.json
166
+
167
+ # copy backend files
168
+ COPY --chown=$UID:$GID ./backend .
169
+
170
+ EXPOSE 8080
171
+
172
+ HEALTHCHECK CMD curl --silent --fail http://localhost:${PORT:-8080}/health | jq -ne 'input.status == true' || exit 1
173
+
174
+ # Minimal, atomic permission hardening for OpenShift (arbitrary UID):
175
+ # - Group 0 owns /app and /root
176
+ # - Directories are group-writable and have SGID so new files inherit GID 0
177
+ RUN if [ "$USE_PERMISSION_HARDENING" = "true" ]; then \
178
+ set -eux; \
179
+ chgrp -R 0 /app /root || true; \
180
+ chmod -R g+rwX /app /root || true; \
181
+ find /app -type d -exec chmod g+s {} + || true; \
182
+ find /root -type d -exec chmod g+s {} + || true; \
183
+ fi
184
+
185
+ USER $UID:$GID
186
+
187
+ ARG BUILD_HASH
188
+ ENV WEBUI_BUILD_VERSION=${BUILD_HASH}
189
+ ENV DOCKER=true
190
+
191
+ CMD [ "bash", "start.sh"]
INSTALLATION.md ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### Installing Both Ollama and Open WebUI Using Kustomize
2
+
3
+ For cpu-only pod
4
+
5
+ ```bash
6
+ kubectl apply -f ./kubernetes/manifest/base
7
+ ```
8
+
9
+ For gpu-enabled pod
10
+
11
+ ```bash
12
+ kubectl apply -k ./kubernetes/manifest
13
+ ```
14
+
15
+ ### Installing Both Ollama and Open WebUI Using Helm
16
+
17
+ Package Helm file first
18
+
19
+ ```bash
20
+ helm package ./kubernetes/helm/
21
+ ```
22
+
23
+ For cpu-only pod
24
+
25
+ ```bash
26
+ helm install ollama-webui ./ollama-webui-*.tgz
27
+ ```
28
+
29
+ For gpu-enabled pod
30
+
31
+ ```bash
32
+ helm install ollama-webui ./ollama-webui-*.tgz --set ollama.resources.limits.nvidia.com/gpu="1"
33
+ ```
34
+
35
+ Check the `kubernetes/helm/values.yaml` file to know which parameters are available for customization
LICENSE ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2023-2025 Timothy Jaeryang Baek (Open WebUI)
2
+ All rights reserved.
3
+
4
+ Redistribution and use in source and binary forms, with or without
5
+ modification, are permitted provided that the following conditions are met:
6
+
7
+ 1. Redistributions of source code must retain the above copyright notice, this
8
+ list of conditions and the following disclaimer.
9
+
10
+ 2. Redistributions in binary form must reproduce the above copyright notice,
11
+ this list of conditions and the following disclaimer in the documentation
12
+ and/or other materials provided with the distribution.
13
+
14
+ 3. Neither the name of the copyright holder nor the names of its
15
+ contributors may be used to endorse or promote products derived from
16
+ this software without specific prior written permission.
17
+
18
+ 4. Notwithstanding any other provision of this License, and as a material condition of the rights granted herein, licensees are strictly prohibited from altering, removing, obscuring, or replacing any "Open WebUI" branding, including but not limited to the name, logo, or any visual, textual, or symbolic identifiers that distinguish the software and its interfaces, in any deployment or distribution, regardless of the number of users, except as explicitly set forth in Clauses 5 and 6 below.
19
+
20
+ 5. The branding restriction enumerated in Clause 4 shall not apply in the following limited circumstances: (i) deployments or distributions where the total number of end users (defined as individual natural persons with direct access to the application) does not exceed fifty (50) within any rolling thirty (30) day period; (ii) cases in which the licensee is an official contributor to the codebase—with a substantive code change successfully merged into the main branch of the official codebase maintained by the copyright holder—who has obtained specific prior written permission for branding adjustment from the copyright holder; or (iii) where the licensee has obtained a duly executed enterprise license expressly permitting such modification. For all other cases, any removal or alteration of the "Open WebUI" branding shall constitute a material breach of license.
21
+
22
+ 6. All code, modifications, or derivative works incorporated into this project prior to the incorporation of this branding clause remain licensed under the BSD 3-Clause License, and prior contributors retain all BSD-3 rights therein; if any such contributor requests the removal of their BSD-3-licensed code, the copyright holder will do so, and any replacement code will be licensed under the project's primary license then in effect. By contributing after this clause's adoption, you agree to the project's Contributor License Agreement (CLA) and to these updated terms for all new contributions.
23
+
24
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
25
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
27
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
28
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
30
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
31
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
32
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
33
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
LICENSE_HISTORY ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ All code and materials created before commit `60d84a3aae9802339705826e9095e272e3c83623` are subject to the following copyright and license:
2
+
3
+ Copyright (c) 2023-2025 Timothy Jaeryang Baek
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ 1. Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ 2. Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ 3. Neither the name of the copyright holder nor the names of its
17
+ contributors may be used to endorse or promote products derived from
18
+ this software without specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30
+
31
+ All code and materials created before commit `a76068d69cd59568b920dfab85dc573dbbb8f131` are subject to the following copyright and license:
32
+
33
+ MIT License
34
+
35
+ Copyright (c) 2023 Timothy Jaeryang Baek
36
+
37
+ Permission is hereby granted, free of charge, to any person obtaining a copy
38
+ of this software and associated documentation files (the "Software"), to deal
39
+ in the Software without restriction, including without limitation the rights
40
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
41
+ copies of the Software, and to permit persons to whom the Software is
42
+ furnished to do so, subject to the following conditions:
43
+
44
+ The above copyright notice and this permission notice shall be included in all
45
+ copies or substantial portions of the Software.
46
+
47
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
48
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
49
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
50
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
51
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
52
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
53
+ SOFTWARE.
LICENSE_NOTICE ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Open WebUI Multi-License Notice
2
+
3
+ This repository contains code governed by multiple licenses based on the date and origin of contribution:
4
+
5
+ 1. All code committed prior to commit a76068d69cd59568b920dfab85dc573dbbb8f131 is licensed under the MIT License (see LICENSE_HISTORY).
6
+
7
+ 2. All code committed from commit a76068d69cd59568b920dfab85dc573dbbb8f131 up to and including commit 60d84a3aae9802339705826e9095e272e3c83623 is licensed under the BSD 3-Clause License (see LICENSE_HISTORY).
8
+
9
+ 3. All code contributed or modified after commit 60d84a3aae9802339705826e9095e272e3c83623 is licensed under the Open WebUI License (see LICENSE).
10
+
11
+ For details on which commits are covered by which license, refer to LICENSE_HISTORY.
Makefile ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ ifneq ($(shell which docker-compose 2>/dev/null),)
3
+ DOCKER_COMPOSE := docker-compose
4
+ else
5
+ DOCKER_COMPOSE := docker compose
6
+ endif
7
+
8
+ install:
9
+ $(DOCKER_COMPOSE) up -d
10
+
11
+ remove:
12
+ @chmod +x confirm_remove.sh
13
+ @./confirm_remove.sh
14
+
15
+ start:
16
+ $(DOCKER_COMPOSE) start
17
+ startAndBuild:
18
+ $(DOCKER_COMPOSE) up -d --build
19
+
20
+ stop:
21
+ $(DOCKER_COMPOSE) stop
22
+
23
+ update:
24
+ # Calls the LLM update script
25
+ chmod +x update_ollama_models.sh
26
+ @./update_ollama_models.sh
27
+ @git pull
28
+ $(DOCKER_COMPOSE) down
29
+ # Make sure the ollama-webui container is stopped before rebuilding
30
+ @docker stop open-webui || true
31
+ $(DOCKER_COMPOSE) up --build -d
32
+ $(DOCKER_COMPOSE) start
33
+
README.md ADDED
@@ -0,0 +1,278 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Open WebUI
3
+ emoji: 🐳
4
+ colorFrom: purple
5
+ colorTo: gray
6
+ sdk: docker
7
+ app_port: 8080
8
+ ---
9
+ # Open WebUI 👋
10
+
11
+ ![GitHub stars](https://img.shields.io/github/stars/open-webui/open-webui?style=social)
12
+ ![GitHub forks](https://img.shields.io/github/forks/open-webui/open-webui?style=social)
13
+ ![GitHub watchers](https://img.shields.io/github/watchers/open-webui/open-webui?style=social)
14
+ ![GitHub repo size](https://img.shields.io/github/repo-size/open-webui/open-webui)
15
+ ![GitHub language count](https://img.shields.io/github/languages/count/open-webui/open-webui)
16
+ ![GitHub top language](https://img.shields.io/github/languages/top/open-webui/open-webui)
17
+ ![GitHub last commit](https://img.shields.io/github/last-commit/open-webui/open-webui?color=red)
18
+ [![Discord](https://img.shields.io/badge/Discord-Open_WebUI-blue?logo=discord&logoColor=white)](https://discord.gg/5rJgQTnV4s)
19
+ [![](https://img.shields.io/static/v1?label=Sponsor&message=%E2%9D%A4&logo=GitHub&color=%23fe8e86)](https://github.com/sponsors/tjbck)
20
+
21
+ **Open WebUI is an [extensible](https://docs.openwebui.com/features/plugin/), feature-rich, and user-friendly self-hosted AI platform designed to operate entirely offline.** It supports various LLM runners like **Ollama** and **OpenAI-compatible APIs**, with **built-in inference engine** for RAG, making it a **powerful AI deployment solution**.
22
+
23
+ Passionate about open-source AI? [Join our team →](https://careers.openwebui.com/)
24
+
25
+ ![Open WebUI Demo](./demo.gif)
26
+
27
+ > [!TIP]
28
+ > **Looking for an [Enterprise Plan](https://docs.openwebui.com/enterprise)?** – **[Speak with Our Sales Team Today!](mailto:sales@openwebui.com)**
29
+ >
30
+ > Get **enhanced capabilities**, including **custom theming and branding**, **Service Level Agreement (SLA) support**, **Long-Term Support (LTS) versions**, and **more!**
31
+
32
+ For more information, be sure to check out our [Open WebUI Documentation](https://docs.openwebui.com/).
33
+
34
+ ## Key Features of Open WebUI ⭐
35
+
36
+ - 🚀 **Effortless Setup**: Install seamlessly using Docker or Kubernetes (kubectl, kustomize or helm) for a hassle-free experience with support for both `:ollama` and `:cuda` tagged images.
37
+
38
+ - 🤝 **Ollama/OpenAI API Integration**: Effortlessly integrate OpenAI-compatible APIs for versatile conversations alongside Ollama models. Customize the OpenAI API URL to link with **LMStudio, GroqCloud, Mistral, OpenRouter, and more**.
39
+
40
+ - 🛡️ **Granular Permissions and User Groups**: By allowing administrators to create detailed user roles and permissions, we ensure a secure user environment. This granularity not only enhances security but also allows for customized user experiences, fostering a sense of ownership and responsibility amongst users.
41
+
42
+ - 🔄 **SCIM 2.0 Support**: Enterprise-grade user and group provisioning through SCIM 2.0 protocol, enabling seamless integration with identity providers like Okta, Azure AD, and Google Workspace for automated user lifecycle management.
43
+
44
+ - 📱 **Responsive Design**: Enjoy a seamless experience across Desktop PC, Laptop, and Mobile devices.
45
+
46
+ - 📱 **Progressive Web App (PWA) for Mobile**: Enjoy a native app-like experience on your mobile device with our PWA, providing offline access on localhost and a seamless user interface.
47
+
48
+ - ✒️🔢 **Full Markdown and LaTeX Support**: Elevate your LLM experience with comprehensive Markdown and LaTeX capabilities for enriched interaction.
49
+
50
+ - 🎤📹 **Hands-Free Voice/Video Call**: Experience seamless communication with integrated hands-free voice and video call features, allowing for a more dynamic and interactive chat environment.
51
+
52
+ - 🛠️ **Model Builder**: Easily create Ollama models via the Web UI. Create and add custom characters/agents, customize chat elements, and import models effortlessly through [Open WebUI Community](https://openwebui.com/) integration.
53
+
54
+ - 🐍 **Native Python Function Calling Tool**: Enhance your LLMs with built-in code editor support in the tools workspace. Bring Your Own Function (BYOF) by simply adding your pure Python functions, enabling seamless integration with LLMs.
55
+
56
+ - 📚 **Local RAG Integration**: Dive into the future of chat interactions with groundbreaking Retrieval Augmented Generation (RAG) support. This feature seamlessly integrates document interactions into your chat experience. You can load documents directly into the chat or add files to your document library, effortlessly accessing them using the `#` command before a query.
57
+
58
+ - 🔍 **Web Search for RAG**: Perform web searches using providers like `SearXNG`, `Google PSE`, `Brave Search`, `serpstack`, `serper`, `Serply`, `DuckDuckGo`, `TavilySearch`, `SearchApi` and `Bing` and inject the results directly into your chat experience.
59
+
60
+ - 🌐 **Web Browsing Capability**: Seamlessly integrate websites into your chat experience using the `#` command followed by a URL. This feature allows you to incorporate web content directly into your conversations, enhancing the richness and depth of your interactions.
61
+
62
+ - 🎨 **Image Generation Integration**: Seamlessly incorporate image generation capabilities using options such as AUTOMATIC1111 API or ComfyUI (local), and OpenAI's DALL-E (external), enriching your chat experience with dynamic visual content.
63
+
64
+ - ⚙️ **Many Models Conversations**: Effortlessly engage with various models simultaneously, harnessing their unique strengths for optimal responses. Enhance your experience by leveraging a diverse set of models in parallel.
65
+
66
+ - 🔐 **Role-Based Access Control (RBAC)**: Ensure secure access with restricted permissions; only authorized individuals can access your Ollama, and exclusive model creation/pulling rights are reserved for administrators.
67
+
68
+ - 🌐🌍 **Multilingual Support**: Experience Open WebUI in your preferred language with our internationalization (i18n) support. Join us in expanding our supported languages! We're actively seeking contributors!
69
+
70
+ - 🧩 **Pipelines, Open WebUI Plugin Support**: Seamlessly integrate custom logic and Python libraries into Open WebUI using [Pipelines Plugin Framework](https://github.com/open-webui/pipelines). Launch your Pipelines instance, set the OpenAI URL to the Pipelines URL, and explore endless possibilities. [Examples](https://github.com/open-webui/pipelines/tree/main/examples) include **Function Calling**, User **Rate Limiting** to control access, **Usage Monitoring** with tools like Langfuse, **Live Translation with LibreTranslate** for multilingual support, **Toxic Message Filtering** and much more.
71
+
72
+ - 🌟 **Continuous Updates**: We are committed to improving Open WebUI with regular updates, fixes, and new features.
73
+
74
+ Want to learn more about Open WebUI's features? Check out our [Open WebUI documentation](https://docs.openwebui.com/features) for a comprehensive overview!
75
+
76
+ ## Sponsors 🙌
77
+
78
+ #### Emerald
79
+
80
+ <table>
81
+ <!-- <tr>
82
+ <td>
83
+ <a href="https://n8n.io/" target="_blank">
84
+ <img src="https://docs.openwebui.com/sponsors/logos/n8n.png" alt="n8n" style="width: 8rem; height: 8rem; border-radius: .75rem;" />
85
+ </a>
86
+ </td>
87
+ <td>
88
+ <a href="https://n8n.io/">n8n</a> • Does your interface have a backend yet?<br>Try <a href="https://n8n.io/">n8n</a>
89
+ </td>
90
+ </tr> -->
91
+ <tr>
92
+ <td>
93
+ <a href="https://tailscale.com/blog/self-host-a-local-ai-stack/?utm_source=OpenWebUI&utm_medium=paid-ad-placement&utm_campaign=OpenWebUI-Docs" target="_blank">
94
+ <img src="https://docs.openwebui.com/sponsors/logos/tailscale.png" alt="Tailscale" style="width: 8rem; height: 8rem; border-radius: .75rem;" />
95
+ </a>
96
+ </td>
97
+ <td>
98
+ <a href="https://tailscale.com/blog/self-host-a-local-ai-stack/?utm_source=OpenWebUI&utm_medium=paid-ad-placement&utm_campaign=OpenWebUI-Docs">Tailscale</a> • Connect self-hosted AI to any device with Tailscale
99
+ </td>
100
+ </tr>
101
+ <tr>
102
+ <td>
103
+ <a href="https://warp.dev/open-webui" target="_blank">
104
+ <img src="https://docs.openwebui.com/sponsors/logos/warp.png" alt="Warp" style="width: 8rem; height: 8rem; border-radius: .75rem;" />
105
+ </a>
106
+ </td>
107
+ <td>
108
+ <a href="https://warp.dev/open-webui">Warp</a> • The intelligent terminal for developers
109
+ </td>
110
+ </tr>
111
+ </table>
112
+
113
+ ---
114
+
115
+ We are incredibly grateful for the generous support of our sponsors. Their contributions help us to maintain and improve our project, ensuring we can continue to deliver quality work to our community. Thank you!
116
+
117
+ ## How to Install 🚀
118
+
119
+ ### Installation via Python pip 🐍
120
+
121
+ Open WebUI can be installed using pip, the Python package installer. Before proceeding, ensure you're using **Python 3.11** to avoid compatibility issues.
122
+
123
+ 1. **Install Open WebUI**:
124
+ Open your terminal and run the following command to install Open WebUI:
125
+
126
+ ```bash
127
+ pip install open-webui
128
+ ```
129
+
130
+ 2. **Running Open WebUI**:
131
+ After installation, you can start Open WebUI by executing:
132
+
133
+ ```bash
134
+ open-webui serve
135
+ ```
136
+
137
+ This will start the Open WebUI server, which you can access at [http://localhost:8080](http://localhost:8080)
138
+
139
+ ### Quick Start with Docker 🐳
140
+
141
+ > [!NOTE]
142
+ > Please note that for certain Docker environments, additional configurations might be needed. If you encounter any connection issues, our detailed guide on [Open WebUI Documentation](https://docs.openwebui.com/) is ready to assist you.
143
+
144
+ > [!WARNING]
145
+ > When using Docker to install Open WebUI, make sure to include the `-v open-webui:/app/backend/data` in your Docker command. This step is crucial as it ensures your database is properly mounted and prevents any loss of data.
146
+
147
+ > [!TIP]
148
+ > If you wish to utilize Open WebUI with Ollama included or CUDA acceleration, we recommend utilizing our official images tagged with either `:cuda` or `:ollama`. To enable CUDA, you must install the [Nvidia CUDA container toolkit](https://docs.nvidia.com/dgx/nvidia-container-runtime-upgrade/) on your Linux/WSL system.
149
+
150
+ ### Installation with Default Configuration
151
+
152
+ - **If Ollama is on your computer**, use this command:
153
+
154
+ ```bash
155
+ docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
156
+ ```
157
+
158
+ - **If Ollama is on a Different Server**, use this command:
159
+
160
+ To connect to Ollama on another server, change the `OLLAMA_BASE_URL` to the server's URL:
161
+
162
+ ```bash
163
+ 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
164
+ ```
165
+
166
+ - **To run Open WebUI with Nvidia GPU support**, use this command:
167
+
168
+ ```bash
169
+ docker run -d -p 3000:8080 --gpus all --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:cuda
170
+ ```
171
+
172
+ ### Installation for OpenAI API Usage Only
173
+
174
+ - **If you're only using OpenAI API**, use this command:
175
+
176
+ ```bash
177
+ docker run -d -p 3000:8080 -e OPENAI_API_KEY=your_secret_key -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
178
+ ```
179
+
180
+ ### Installing Open WebUI with Bundled Ollama Support
181
+
182
+ This installation method uses a single container image that bundles Open WebUI with Ollama, allowing for a streamlined setup via a single command. Choose the appropriate command based on your hardware setup:
183
+
184
+ - **With GPU Support**:
185
+ Utilize GPU resources by running the following command:
186
+
187
+ ```bash
188
+ docker run -d -p 3000:8080 --gpus=all -v ollama:/root/.ollama -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:ollama
189
+ ```
190
+
191
+ - **For CPU Only**:
192
+ If you're not using a GPU, use this command instead:
193
+
194
+ ```bash
195
+ docker run -d -p 3000:8080 -v ollama:/root/.ollama -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:ollama
196
+ ```
197
+
198
+ Both commands facilitate a built-in, hassle-free installation of both Open WebUI and Ollama, ensuring that you can get everything up and running swiftly.
199
+
200
+ After installation, you can access Open WebUI at [http://localhost:3000](http://localhost:3000). Enjoy! 😄
201
+
202
+ ### Other Installation Methods
203
+
204
+ We offer various installation alternatives, including non-Docker native installation methods, Docker Compose, Kustomize, and Helm. Visit our [Open WebUI Documentation](https://docs.openwebui.com/getting-started/) or join our [Discord community](https://discord.gg/5rJgQTnV4s) for comprehensive guidance.
205
+
206
+ Look at the [Local Development Guide](https://docs.openwebui.com/getting-started/advanced-topics/development) for instructions on setting up a local development environment.
207
+
208
+ ### Troubleshooting
209
+
210
+ Encountering connection issues? Our [Open WebUI Documentation](https://docs.openwebui.com/troubleshooting/) has got you covered. For further assistance and to join our vibrant community, visit the [Open WebUI Discord](https://discord.gg/5rJgQTnV4s).
211
+
212
+ #### Open WebUI: Server Connection Error
213
+
214
+ If you're experiencing connection issues, it’s often due to the WebUI docker container not being able to reach the Ollama server at 127.0.0.1:11434 (host.docker.internal:11434) inside the container . Use the `--network=host` flag in your docker command to resolve this. Note that the port changes from 3000 to 8080, resulting in the link: `http://localhost:8080`.
215
+
216
+ **Example Docker Command**:
217
+
218
+ ```bash
219
+ docker run -d --network=host -v open-webui:/app/backend/data -e OLLAMA_BASE_URL=http://127.0.0.1:11434 --name open-webui --restart always ghcr.io/open-webui/open-webui:main
220
+ ```
221
+
222
+ ### Keeping Your Docker Installation Up-to-Date
223
+
224
+ In case you want to update your local Docker installation to the latest version, you can do it with [Watchtower](https://containrrr.dev/watchtower/):
225
+
226
+ ```bash
227
+ docker run --rm --volume /var/run/docker.sock:/var/run/docker.sock containrrr/watchtower --run-once open-webui
228
+ ```
229
+
230
+ In the last part of the command, replace `open-webui` with your container name if it is different.
231
+
232
+ Check our Updating Guide available in our [Open WebUI Documentation](https://docs.openwebui.com/getting-started/updating).
233
+
234
+ ### Using the Dev Branch 🌙
235
+
236
+ > [!WARNING]
237
+ > The `:dev` branch contains the latest unstable features and changes. Use it at your own risk as it may have bugs or incomplete features.
238
+
239
+ If you want to try out the latest bleeding-edge features and are okay with occasional instability, you can use the `:dev` tag like this:
240
+
241
+ ```bash
242
+ docker run -d -p 3000:8080 -v open-webui:/app/backend/data --name open-webui --add-host=host.docker.internal:host-gateway --restart always ghcr.io/open-webui/open-webui:dev
243
+ ```
244
+
245
+ ### Offline Mode
246
+
247
+ If you are running Open WebUI in an offline environment, you can set the `HF_HUB_OFFLINE` environment variable to `1` to prevent attempts to download models from the internet.
248
+
249
+ ```bash
250
+ export HF_HUB_OFFLINE=1
251
+ ```
252
+
253
+ ## What's Next? 🌟
254
+
255
+ Discover upcoming features on our roadmap in the [Open WebUI Documentation](https://docs.openwebui.com/roadmap/).
256
+
257
+ ## License 📜
258
+
259
+ This project contains code under multiple licenses. The current codebase includes components licensed under the Open WebUI License with an additional requirement to preserve the "Open WebUI" branding, as well as prior contributions under their respective original licenses. For a detailed record of license changes and the applicable terms for each section of the code, please refer to [LICENSE_HISTORY](./LICENSE_HISTORY). For complete and updated licensing details, please see the [LICENSE](./LICENSE) and [LICENSE_HISTORY](./LICENSE_HISTORY) files.
260
+
261
+ ## Support 💬
262
+
263
+ If you have any questions, suggestions, or need assistance, please open an issue or join our
264
+ [Open WebUI Discord community](https://discord.gg/5rJgQTnV4s) to connect with us! 🤝
265
+
266
+ ## Star History
267
+
268
+ <a href="https://star-history.com/#open-webui/open-webui&Date">
269
+ <picture>
270
+ <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date&theme=dark" />
271
+ <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
272
+ <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
273
+ </picture>
274
+ </a>
275
+
276
+ ---
277
+
278
+ Created by [Timothy Jaeryang Baek](https://github.com/tjbck) - Let's make Open WebUI even more amazing together! 💪
TROUBLESHOOTING.md ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Open WebUI Troubleshooting Guide
2
+
3
+ ## Understanding the Open WebUI Architecture
4
+
5
+ The Open WebUI system is designed to streamline interactions between the client (your browser) and the Ollama API. At the heart of this design is a backend reverse proxy, enhancing security and resolving CORS issues.
6
+
7
+ - **How it Works**: The Open WebUI is designed to interact with the Ollama API through a specific route. When a request is made from the WebUI to Ollama, it is not directly sent to the Ollama API. Initially, the request is sent to the Open WebUI backend via `/ollama` route. From there, the backend is responsible for forwarding the request to the Ollama API. This forwarding is accomplished by using the route specified in the `OLLAMA_BASE_URL` environment variable. Therefore, a request made to `/ollama` in the WebUI is effectively the same as making a request to `OLLAMA_BASE_URL` in the backend. For instance, a request to `/ollama/api/tags` in the WebUI is equivalent to `OLLAMA_BASE_URL/api/tags` in the backend.
8
+
9
+ - **Security Benefits**: This design prevents direct exposure of the Ollama API to the frontend, safeguarding against potential CORS (Cross-Origin Resource Sharing) issues and unauthorized access. Requiring authentication to access the Ollama API further enhances this security layer.
10
+
11
+ ## Open WebUI: Server Connection Error
12
+
13
+ If you're experiencing connection issues, it’s often due to the WebUI docker container not being able to reach the Ollama server at 127.0.0.1:11434 (host.docker.internal:11434) inside the container . Use the `--network=host` flag in your docker command to resolve this. Note that the port changes from 3000 to 8080, resulting in the link: `http://localhost:8080`.
14
+
15
+ **Example Docker Command**:
16
+
17
+ ```bash
18
+ docker run -d --network=host -v open-webui:/app/backend/data -e OLLAMA_BASE_URL=http://127.0.0.1:11434 --name open-webui --restart always ghcr.io/open-webui/open-webui:main
19
+ ```
20
+
21
+ ### Error on Slow Responses for Ollama
22
+
23
+ Open WebUI has a default timeout of 5 minutes for Ollama to finish generating the response. If needed, this can be adjusted via the environment variable AIOHTTP_CLIENT_TIMEOUT, which sets the timeout in seconds.
24
+
25
+ ### General Connection Errors
26
+
27
+ **Ensure Ollama Version is Up-to-Date**: Always start by checking that you have the latest version of Ollama. Visit [Ollama's official site](https://ollama.com/) for the latest updates.
28
+
29
+ **Troubleshooting Steps**:
30
+
31
+ 1. **Verify Ollama URL Format**:
32
+ - When running the Web UI container, ensure the `OLLAMA_BASE_URL` is correctly set. (e.g., `http://192.168.1.1:11434` for different host setups).
33
+ - In the Open WebUI, navigate to "Settings" > "General".
34
+ - Confirm that the Ollama Server URL is correctly set to `[OLLAMA URL]` (e.g., `http://localhost:11434`).
35
+
36
+ By following these enhanced troubleshooting steps, connection issues should be effectively resolved. For further assistance or queries, feel free to reach out to us on our community Discord.
backend/.dockerignore ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__
2
+ .env
3
+ _old
4
+ uploads
5
+ .ipynb_checkpoints
6
+ *.db
7
+ _test
8
+ !/data
9
+ /data/*
10
+ !/data/litellm
11
+ /data/litellm/*
12
+ !data/litellm/config.yaml
13
+
14
+ !data/config.json
backend/.gitignore ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__
2
+ .env
3
+ _old
4
+ uploads
5
+ .ipynb_checkpoints
6
+ *.db
7
+ _test
8
+ Pipfile
9
+ !/data
10
+ /data/*
11
+ /open_webui/data/*
12
+ .webui_secret_key
backend/dev.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ export CORS_ALLOW_ORIGIN="http://localhost:5173;http://localhost:8080"
2
+ PORT="${PORT:-8080}"
3
+ uvicorn open_webui.main:app --port $PORT --host 0.0.0.0 --forwarded-allow-ips '*' --reload
backend/open_webui/__init__.py ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import os
3
+ import random
4
+ from pathlib import Path
5
+
6
+ import typer
7
+ import uvicorn
8
+ from typing import Optional
9
+ from typing_extensions import Annotated
10
+
11
+ app = typer.Typer()
12
+
13
+ KEY_FILE = Path.cwd() / ".webui_secret_key"
14
+
15
+
16
+ def version_callback(value: bool):
17
+ if value:
18
+ from open_webui.env import VERSION
19
+
20
+ typer.echo(f"Open WebUI version: {VERSION}")
21
+ raise typer.Exit()
22
+
23
+
24
+ @app.command()
25
+ def main(
26
+ version: Annotated[
27
+ Optional[bool], typer.Option("--version", callback=version_callback)
28
+ ] = None,
29
+ ):
30
+ pass
31
+
32
+
33
+ @app.command()
34
+ def serve(
35
+ host: str = "0.0.0.0",
36
+ port: int = 8080,
37
+ ):
38
+ os.environ["FROM_INIT_PY"] = "true"
39
+ if os.getenv("WEBUI_SECRET_KEY") is None:
40
+ typer.echo(
41
+ "Loading WEBUI_SECRET_KEY from file, not provided as an environment variable."
42
+ )
43
+ if not KEY_FILE.exists():
44
+ typer.echo(f"Generating a new secret key and saving it to {KEY_FILE}")
45
+ KEY_FILE.write_bytes(base64.b64encode(random.randbytes(12)))
46
+ typer.echo(f"Loading WEBUI_SECRET_KEY from {KEY_FILE}")
47
+ os.environ["WEBUI_SECRET_KEY"] = KEY_FILE.read_text()
48
+
49
+ if os.getenv("USE_CUDA_DOCKER", "false") == "true":
50
+ typer.echo(
51
+ "CUDA is enabled, appending LD_LIBRARY_PATH to include torch/cudnn & cublas libraries."
52
+ )
53
+ LD_LIBRARY_PATH = os.getenv("LD_LIBRARY_PATH", "").split(":")
54
+ os.environ["LD_LIBRARY_PATH"] = ":".join(
55
+ LD_LIBRARY_PATH
56
+ + [
57
+ "/usr/local/lib/python3.11/site-packages/torch/lib",
58
+ "/usr/local/lib/python3.11/site-packages/nvidia/cudnn/lib",
59
+ ]
60
+ )
61
+ try:
62
+ import torch
63
+
64
+ assert torch.cuda.is_available(), "CUDA not available"
65
+ typer.echo("CUDA seems to be working")
66
+ except Exception as e:
67
+ typer.echo(
68
+ "Error when testing CUDA but USE_CUDA_DOCKER is true. "
69
+ "Resetting USE_CUDA_DOCKER to false and removing "
70
+ f"LD_LIBRARY_PATH modifications: {e}"
71
+ )
72
+ os.environ["USE_CUDA_DOCKER"] = "false"
73
+ os.environ["LD_LIBRARY_PATH"] = ":".join(LD_LIBRARY_PATH)
74
+
75
+ import open_webui.main # we need set environment variables before importing main
76
+ from open_webui.env import UVICORN_WORKERS # Import the workers setting
77
+
78
+ uvicorn.run(
79
+ "open_webui.main:app",
80
+ host=host,
81
+ port=port,
82
+ forwarded_allow_ips="*",
83
+ workers=UVICORN_WORKERS,
84
+ )
85
+
86
+
87
+ @app.command()
88
+ def dev(
89
+ host: str = "0.0.0.0",
90
+ port: int = 8080,
91
+ reload: bool = True,
92
+ ):
93
+ uvicorn.run(
94
+ "open_webui.main:app",
95
+ host=host,
96
+ port=port,
97
+ reload=reload,
98
+ forwarded_allow_ips="*",
99
+ )
100
+
101
+
102
+ if __name__ == "__main__":
103
+ app()
backend/open_webui/alembic.ini ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # A generic, single database configuration.
2
+
3
+ [alembic]
4
+ # path to migration scripts
5
+ script_location = migrations
6
+
7
+ # template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
8
+ # Uncomment the line below if you want the files to be prepended with date and time
9
+ # file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
10
+
11
+ # sys.path path, will be prepended to sys.path if present.
12
+ # defaults to the current working directory.
13
+ prepend_sys_path = ..
14
+
15
+ # timezone to use when rendering the date within the migration file
16
+ # as well as the filename.
17
+ # If specified, requires the python>=3.9 or backports.zoneinfo library.
18
+ # Any required deps can installed by adding `alembic[tz]` to the pip requirements
19
+ # string value is passed to ZoneInfo()
20
+ # leave blank for localtime
21
+ # timezone =
22
+
23
+ # max length of characters to apply to the
24
+ # "slug" field
25
+ # truncate_slug_length = 40
26
+
27
+ # set to 'true' to run the environment during
28
+ # the 'revision' command, regardless of autogenerate
29
+ # revision_environment = false
30
+
31
+ # set to 'true' to allow .pyc and .pyo files without
32
+ # a source .py file to be detected as revisions in the
33
+ # versions/ directory
34
+ # sourceless = false
35
+
36
+ # version location specification; This defaults
37
+ # to migrations/versions. When using multiple version
38
+ # directories, initial revisions must be specified with --version-path.
39
+ # The path separator used here should be the separator specified by "version_path_separator" below.
40
+ # version_locations = %(here)s/bar:%(here)s/bat:migrations/versions
41
+
42
+ # version path separator; As mentioned above, this is the character used to split
43
+ # version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
44
+ # If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
45
+ # Valid values for version_path_separator are:
46
+ #
47
+ # version_path_separator = :
48
+ # version_path_separator = ;
49
+ # version_path_separator = space
50
+ version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
51
+
52
+ # set to 'true' to search source files recursively
53
+ # in each "version_locations" directory
54
+ # new in Alembic version 1.10
55
+ # recursive_version_locations = false
56
+
57
+ # the output encoding used when revision files
58
+ # are written from script.py.mako
59
+ # output_encoding = utf-8
60
+
61
+ # sqlalchemy.url = REPLACE_WITH_DATABASE_URL
62
+
63
+
64
+ [post_write_hooks]
65
+ # post_write_hooks defines scripts or Python functions that are run
66
+ # on newly generated revision scripts. See the documentation for further
67
+ # detail and examples
68
+
69
+ # format using "black" - use the console_scripts runner, against the "black" entrypoint
70
+ # hooks = black
71
+ # black.type = console_scripts
72
+ # black.entrypoint = black
73
+ # black.options = -l 79 REVISION_SCRIPT_FILENAME
74
+
75
+ # lint with attempts to fix using "ruff" - use the exec runner, execute a binary
76
+ # hooks = ruff
77
+ # ruff.type = exec
78
+ # ruff.executable = %(here)s/.venv/bin/ruff
79
+ # ruff.options = --fix REVISION_SCRIPT_FILENAME
80
+
81
+ # Logging configuration
82
+ [loggers]
83
+ keys = root,sqlalchemy,alembic
84
+
85
+ [handlers]
86
+ keys = console
87
+
88
+ [formatters]
89
+ keys = generic
90
+
91
+ [logger_root]
92
+ level = WARN
93
+ handlers = console
94
+ qualname =
95
+
96
+ [logger_sqlalchemy]
97
+ level = WARN
98
+ handlers =
99
+ qualname = sqlalchemy.engine
100
+
101
+ [logger_alembic]
102
+ level = INFO
103
+ handlers =
104
+ qualname = alembic
105
+
106
+ [handler_console]
107
+ class = StreamHandler
108
+ args = (sys.stderr,)
109
+ level = NOTSET
110
+ formatter = generic
111
+
112
+ [formatter_generic]
113
+ format = %(levelname)-5.5s [%(name)s] %(message)s
114
+ datefmt = %H:%M:%S
backend/open_webui/config.py ADDED
The diff for this file is too large to render. See raw diff
 
backend/open_webui/constants.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from enum import Enum
2
+
3
+
4
+ class MESSAGES(str, Enum):
5
+ DEFAULT = lambda msg="": f"{msg if msg else ''}"
6
+ MODEL_ADDED = lambda model="": f"The model '{model}' has been added successfully."
7
+ MODEL_DELETED = (
8
+ lambda model="": f"The model '{model}' has been deleted successfully."
9
+ )
10
+
11
+
12
+ class WEBHOOK_MESSAGES(str, Enum):
13
+ DEFAULT = lambda msg="": f"{msg if msg else ''}"
14
+ USER_SIGNUP = lambda username="": (
15
+ f"New user signed up: {username}" if username else "New user signed up"
16
+ )
17
+
18
+
19
+ class ERROR_MESSAGES(str, Enum):
20
+ def __str__(self) -> str:
21
+ return super().__str__()
22
+
23
+ DEFAULT = (
24
+ lambda err="": f'{"Something went wrong :/" if err == "" else "[ERROR: " + str(err) + "]"}'
25
+ )
26
+ ENV_VAR_NOT_FOUND = "Required environment variable not found. Terminating now."
27
+ CREATE_USER_ERROR = "Oops! Something went wrong while creating your account. Please try again later. If the issue persists, contact support for assistance."
28
+ DELETE_USER_ERROR = "Oops! Something went wrong. We encountered an issue while trying to delete the user. Please give it another shot."
29
+ EMAIL_MISMATCH = "Uh-oh! This email does not match the email your provider is registered with. Please check your email and try again."
30
+ EMAIL_TAKEN = "Uh-oh! This email is already registered. Sign in with your existing account or choose another email to start anew."
31
+ USERNAME_TAKEN = (
32
+ "Uh-oh! This username is already registered. Please choose another username."
33
+ )
34
+ PASSWORD_TOO_LONG = "Uh-oh! The password you entered is too long. Please make sure your password is less than 72 bytes long."
35
+ COMMAND_TAKEN = "Uh-oh! This command is already registered. Please choose another command string."
36
+ FILE_EXISTS = "Uh-oh! This file is already registered. Please choose another file."
37
+
38
+ ID_TAKEN = "Uh-oh! This id is already registered. Please choose another id string."
39
+ MODEL_ID_TAKEN = "Uh-oh! This model id is already registered. Please choose another model id string."
40
+ NAME_TAG_TAKEN = "Uh-oh! This name tag is already registered. Please choose another name tag string."
41
+ MODEL_ID_TOO_LONG = "The model id is too long. Please make sure your model id is less than 256 characters long."
42
+
43
+ INVALID_TOKEN = (
44
+ "Your session has expired or the token is invalid. Please sign in again."
45
+ )
46
+ INVALID_CRED = "The email or password provided is incorrect. Please check for typos and try logging in again."
47
+ INVALID_EMAIL_FORMAT = "The email format you entered is invalid. Please double-check and make sure you're using a valid email address (e.g., yourname@example.com)."
48
+ INVALID_PASSWORD = (
49
+ "The password provided is incorrect. Please check for typos and try again."
50
+ )
51
+ INVALID_TRUSTED_HEADER = "Your provider has not provided a trusted header. Please contact your administrator for assistance."
52
+
53
+ EXISTING_USERS = "You can't turn off authentication because there are existing users. If you want to disable WEBUI_AUTH, make sure your web interface doesn't have any existing users and is a fresh installation."
54
+
55
+ UNAUTHORIZED = "401 Unauthorized"
56
+ ACCESS_PROHIBITED = "You do not have permission to access this resource. Please contact your administrator for assistance."
57
+ ACTION_PROHIBITED = (
58
+ "The requested action has been restricted as a security measure."
59
+ )
60
+
61
+ FILE_NOT_SENT = "FILE_NOT_SENT"
62
+ FILE_NOT_SUPPORTED = "Oops! It seems like the file format you're trying to upload is not supported. Please upload a file with a supported format and try again."
63
+
64
+ NOT_FOUND = "We could not find what you're looking for :/"
65
+ USER_NOT_FOUND = "We could not find what you're looking for :/"
66
+ API_KEY_NOT_FOUND = "Oops! It looks like there's a hiccup. The API key is missing. Please make sure to provide a valid API key to access this feature."
67
+ API_KEY_NOT_ALLOWED = "Use of API key is not enabled in the environment."
68
+
69
+ MALICIOUS = "Unusual activities detected, please try again in a few minutes."
70
+
71
+ PANDOC_NOT_INSTALLED = "Pandoc is not installed on the server. Please contact your administrator for assistance."
72
+ INCORRECT_FORMAT = (
73
+ lambda err="": f"Invalid format. Please use the correct format{err}"
74
+ )
75
+ RATE_LIMIT_EXCEEDED = "API rate limit exceeded"
76
+
77
+ MODEL_NOT_FOUND = lambda name="": f"Model '{name}' was not found"
78
+ OPENAI_NOT_FOUND = lambda name="": "OpenAI API was not found"
79
+ OLLAMA_NOT_FOUND = "WebUI could not connect to Ollama"
80
+ CREATE_API_KEY_ERROR = "Oops! Something went wrong while creating your API key. Please try again later. If the issue persists, contact support for assistance."
81
+ API_KEY_CREATION_NOT_ALLOWED = "API key creation is not allowed in the environment."
82
+
83
+ EMPTY_CONTENT = "The content provided is empty. Please ensure that there is text or data present before proceeding."
84
+
85
+ DB_NOT_SQLITE = "This feature is only available when running with SQLite databases."
86
+
87
+ INVALID_URL = (
88
+ "Oops! The URL you provided is invalid. Please double-check and try again."
89
+ )
90
+
91
+ WEB_SEARCH_ERROR = (
92
+ lambda err="": f"{err if err else 'Oops! Something went wrong while searching the web.'}"
93
+ )
94
+
95
+ OLLAMA_API_DISABLED = (
96
+ "The Ollama API is disabled. Please enable it to use this feature."
97
+ )
98
+
99
+ FILE_TOO_LARGE = (
100
+ lambda size="": f"Oops! The file you're trying to upload is too large. Please upload a file that is less than {size}."
101
+ )
102
+
103
+ DUPLICATE_CONTENT = (
104
+ "Duplicate content detected. Please provide unique content to proceed."
105
+ )
106
+ FILE_NOT_PROCESSED = "Extracted content is not available for this file. Please ensure that the file is processed before proceeding."
107
+
108
+
109
+ class TASKS(str, Enum):
110
+ def __str__(self) -> str:
111
+ return super().__str__()
112
+
113
+ DEFAULT = lambda task="": f"{task if task else 'generation'}"
114
+ TITLE_GENERATION = "title_generation"
115
+ FOLLOW_UP_GENERATION = "follow_up_generation"
116
+ TAGS_GENERATION = "tags_generation"
117
+ EMOJI_GENERATION = "emoji_generation"
118
+ QUERY_GENERATION = "query_generation"
119
+ IMAGE_PROMPT_GENERATION = "image_prompt_generation"
120
+ AUTOCOMPLETE_GENERATION = "autocomplete_generation"
121
+ FUNCTION_CALLING = "function_calling"
122
+ MOA_RESPONSE_GENERATION = "moa_response_generation"
backend/open_webui/env.py ADDED
@@ -0,0 +1,815 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.metadata
2
+ import json
3
+ import logging
4
+ import os
5
+ import pkgutil
6
+ import sys
7
+ import shutil
8
+ from uuid import uuid4
9
+ from pathlib import Path
10
+ from cryptography.hazmat.primitives import serialization
11
+
12
+ import markdown
13
+ from bs4 import BeautifulSoup
14
+ from open_webui.constants import ERROR_MESSAGES
15
+
16
+ ####################################
17
+ # Load .env file
18
+ ####################################
19
+
20
+ # Use .resolve() to get the canonical path, removing any '..' or '.' components
21
+ ENV_FILE_PATH = Path(__file__).resolve()
22
+
23
+ # OPEN_WEBUI_DIR should be the directory where env.py resides (open_webui/)
24
+ OPEN_WEBUI_DIR = ENV_FILE_PATH.parent
25
+
26
+ # BACKEND_DIR is the parent of OPEN_WEBUI_DIR (backend/)
27
+ BACKEND_DIR = OPEN_WEBUI_DIR.parent
28
+
29
+ # BASE_DIR is the parent of BACKEND_DIR (open-webui-dev/)
30
+ BASE_DIR = BACKEND_DIR.parent
31
+
32
+ try:
33
+ from dotenv import find_dotenv, load_dotenv
34
+
35
+ load_dotenv(find_dotenv(str(BASE_DIR / ".env")))
36
+ except ImportError:
37
+ print("dotenv not installed, skipping...")
38
+
39
+ DOCKER = os.environ.get("DOCKER", "False").lower() == "true"
40
+
41
+ # device type embedding models - "cpu" (default), "cuda" (nvidia gpu required) or "mps" (apple silicon) - choosing this right can lead to better performance
42
+ USE_CUDA = os.environ.get("USE_CUDA_DOCKER", "false")
43
+
44
+ if USE_CUDA.lower() == "true":
45
+ try:
46
+ import torch
47
+
48
+ assert torch.cuda.is_available(), "CUDA not available"
49
+ DEVICE_TYPE = "cuda"
50
+ except Exception as e:
51
+ cuda_error = (
52
+ "Error when testing CUDA but USE_CUDA_DOCKER is true. "
53
+ f"Resetting USE_CUDA_DOCKER to false: {e}"
54
+ )
55
+ os.environ["USE_CUDA_DOCKER"] = "false"
56
+ USE_CUDA = "false"
57
+ DEVICE_TYPE = "cpu"
58
+ else:
59
+ DEVICE_TYPE = "cpu"
60
+
61
+ try:
62
+ import torch
63
+
64
+ if torch.backends.mps.is_available() and torch.backends.mps.is_built():
65
+ DEVICE_TYPE = "mps"
66
+ except Exception:
67
+ pass
68
+
69
+ ####################################
70
+ # LOGGING
71
+ ####################################
72
+
73
+ GLOBAL_LOG_LEVEL = os.environ.get("GLOBAL_LOG_LEVEL", "").upper()
74
+ if GLOBAL_LOG_LEVEL in logging.getLevelNamesMapping():
75
+ logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL, force=True)
76
+ else:
77
+ GLOBAL_LOG_LEVEL = "INFO"
78
+
79
+ log = logging.getLogger(__name__)
80
+ log.info(f"GLOBAL_LOG_LEVEL: {GLOBAL_LOG_LEVEL}")
81
+
82
+ if "cuda_error" in locals():
83
+ log.exception(cuda_error)
84
+ del cuda_error
85
+
86
+ log_sources = [
87
+ "AUDIO",
88
+ "COMFYUI",
89
+ "CONFIG",
90
+ "DB",
91
+ "IMAGES",
92
+ "MAIN",
93
+ "MODELS",
94
+ "OLLAMA",
95
+ "OPENAI",
96
+ "RAG",
97
+ "WEBHOOK",
98
+ "SOCKET",
99
+ "OAUTH",
100
+ ]
101
+
102
+ SRC_LOG_LEVELS = {}
103
+
104
+ for source in log_sources:
105
+ log_env_var = source + "_LOG_LEVEL"
106
+ SRC_LOG_LEVELS[source] = os.environ.get(log_env_var, "").upper()
107
+ if SRC_LOG_LEVELS[source] not in logging.getLevelNamesMapping():
108
+ SRC_LOG_LEVELS[source] = GLOBAL_LOG_LEVEL
109
+ log.info(f"{log_env_var}: {SRC_LOG_LEVELS[source]}")
110
+
111
+ log.setLevel(SRC_LOG_LEVELS["CONFIG"])
112
+
113
+ WEBUI_NAME = os.environ.get("WEBUI_NAME", "Open WebUI")
114
+ # if WEBUI_NAME != "Open WebUI":
115
+ # WEBUI_NAME += " (Open WebUI)"
116
+
117
+ WEBUI_FAVICON_URL = "https://openwebui.com/favicon.png"
118
+
119
+ TRUSTED_SIGNATURE_KEY = os.environ.get("TRUSTED_SIGNATURE_KEY", "")
120
+
121
+ ####################################
122
+ # ENV (dev,test,prod)
123
+ ####################################
124
+
125
+ ENV = os.environ.get("ENV", "dev")
126
+
127
+ FROM_INIT_PY = os.environ.get("FROM_INIT_PY", "False").lower() == "true"
128
+
129
+ if FROM_INIT_PY:
130
+ PACKAGE_DATA = {"version": importlib.metadata.version("open-webui")}
131
+ else:
132
+ try:
133
+ PACKAGE_DATA = json.loads((BASE_DIR / "package.json").read_text())
134
+ except Exception:
135
+ PACKAGE_DATA = {"version": "0.0.0"}
136
+
137
+ VERSION = PACKAGE_DATA["version"]
138
+ INSTANCE_ID = os.environ.get("INSTANCE_ID", str(uuid4()))
139
+
140
+
141
+ # Function to parse each section
142
+ def parse_section(section):
143
+ items = []
144
+ for li in section.find_all("li"):
145
+ # Extract raw HTML string
146
+ raw_html = str(li)
147
+
148
+ # Extract text without HTML tags
149
+ text = li.get_text(separator=" ", strip=True)
150
+
151
+ # Split into title and content
152
+ parts = text.split(": ", 1)
153
+ title = parts[0].strip() if len(parts) > 1 else ""
154
+ content = parts[1].strip() if len(parts) > 1 else text
155
+
156
+ items.append({"title": title, "content": content, "raw": raw_html})
157
+ return items
158
+
159
+
160
+ try:
161
+ changelog_path = BASE_DIR / "CHANGELOG.md"
162
+ with open(str(changelog_path.absolute()), "r", encoding="utf8") as file:
163
+ changelog_content = file.read()
164
+
165
+ except Exception:
166
+ changelog_content = (pkgutil.get_data("open_webui", "CHANGELOG.md") or b"").decode()
167
+
168
+ # Convert markdown content to HTML
169
+ html_content = markdown.markdown(changelog_content)
170
+
171
+ # Parse the HTML content
172
+ soup = BeautifulSoup(html_content, "html.parser")
173
+
174
+ # Initialize JSON structure
175
+ changelog_json = {}
176
+
177
+ # Iterate over each version
178
+ for version in soup.find_all("h2"):
179
+ version_number = version.get_text().strip().split(" - ")[0][1:-1] # Remove brackets
180
+ date = version.get_text().strip().split(" - ")[1]
181
+
182
+ version_data = {"date": date}
183
+
184
+ # Find the next sibling that is a h3 tag (section title)
185
+ current = version.find_next_sibling()
186
+
187
+ while current and current.name != "h2":
188
+ if current.name == "h3":
189
+ section_title = current.get_text().lower() # e.g., "added", "fixed"
190
+ section_items = parse_section(current.find_next_sibling("ul"))
191
+ version_data[section_title] = section_items
192
+
193
+ # Move to the next element
194
+ current = current.find_next_sibling()
195
+
196
+ changelog_json[version_number] = version_data
197
+
198
+ CHANGELOG = changelog_json
199
+
200
+ ####################################
201
+ # SAFE_MODE
202
+ ####################################
203
+
204
+ SAFE_MODE = os.environ.get("SAFE_MODE", "false").lower() == "true"
205
+
206
+
207
+ ####################################
208
+ # ENABLE_FORWARD_USER_INFO_HEADERS
209
+ ####################################
210
+
211
+ ENABLE_FORWARD_USER_INFO_HEADERS = (
212
+ os.environ.get("ENABLE_FORWARD_USER_INFO_HEADERS", "False").lower() == "true"
213
+ )
214
+
215
+ # Experimental feature, may be removed in future
216
+ ENABLE_STAR_SESSIONS_MIDDLEWARE = (
217
+ os.environ.get("ENABLE_STAR_SESSIONS_MIDDLEWARE", "False").lower() == "true"
218
+ )
219
+
220
+ ####################################
221
+ # WEBUI_BUILD_HASH
222
+ ####################################
223
+
224
+ WEBUI_BUILD_HASH = os.environ.get("WEBUI_BUILD_HASH", "dev-build")
225
+
226
+ ####################################
227
+ # DATA/FRONTEND BUILD DIR
228
+ ####################################
229
+
230
+ DATA_DIR = Path(os.getenv("DATA_DIR", BACKEND_DIR / "data")).resolve()
231
+
232
+ if FROM_INIT_PY:
233
+ NEW_DATA_DIR = Path(os.getenv("DATA_DIR", OPEN_WEBUI_DIR / "data")).resolve()
234
+ NEW_DATA_DIR.mkdir(parents=True, exist_ok=True)
235
+
236
+ # Check if the data directory exists in the package directory
237
+ if DATA_DIR.exists() and DATA_DIR != NEW_DATA_DIR:
238
+ log.info(f"Moving {DATA_DIR} to {NEW_DATA_DIR}")
239
+ for item in DATA_DIR.iterdir():
240
+ dest = NEW_DATA_DIR / item.name
241
+ if item.is_dir():
242
+ shutil.copytree(item, dest, dirs_exist_ok=True)
243
+ else:
244
+ shutil.copy2(item, dest)
245
+
246
+ # Zip the data directory
247
+ shutil.make_archive(DATA_DIR.parent / "open_webui_data", "zip", DATA_DIR)
248
+
249
+ # Remove the old data directory
250
+ shutil.rmtree(DATA_DIR)
251
+
252
+ DATA_DIR = Path(os.getenv("DATA_DIR", OPEN_WEBUI_DIR / "data"))
253
+
254
+ STATIC_DIR = Path(os.getenv("STATIC_DIR", OPEN_WEBUI_DIR / "static"))
255
+
256
+ FONTS_DIR = Path(os.getenv("FONTS_DIR", OPEN_WEBUI_DIR / "static" / "fonts"))
257
+
258
+ FRONTEND_BUILD_DIR = Path(os.getenv("FRONTEND_BUILD_DIR", BASE_DIR / "build")).resolve()
259
+
260
+ if FROM_INIT_PY:
261
+ FRONTEND_BUILD_DIR = Path(
262
+ os.getenv("FRONTEND_BUILD_DIR", OPEN_WEBUI_DIR / "frontend")
263
+ ).resolve()
264
+
265
+ ####################################
266
+ # Database
267
+ ####################################
268
+
269
+ # Check if the file exists
270
+ if os.path.exists(f"{DATA_DIR}/ollama.db"):
271
+ # Rename the file
272
+ os.rename(f"{DATA_DIR}/ollama.db", f"{DATA_DIR}/webui.db")
273
+ log.info("Database migrated from Ollama-WebUI successfully.")
274
+ else:
275
+ pass
276
+
277
+ DATABASE_URL = os.environ.get("DATABASE_URL", f"sqlite:///{DATA_DIR}/webui.db")
278
+
279
+ DATABASE_TYPE = os.environ.get("DATABASE_TYPE")
280
+ DATABASE_USER = os.environ.get("DATABASE_USER")
281
+ DATABASE_PASSWORD = os.environ.get("DATABASE_PASSWORD")
282
+
283
+ DATABASE_CRED = ""
284
+ if DATABASE_USER:
285
+ DATABASE_CRED += f"{DATABASE_USER}"
286
+ if DATABASE_PASSWORD:
287
+ DATABASE_CRED += f":{DATABASE_PASSWORD}"
288
+
289
+ DB_VARS = {
290
+ "db_type": DATABASE_TYPE,
291
+ "db_cred": DATABASE_CRED,
292
+ "db_host": os.environ.get("DATABASE_HOST"),
293
+ "db_port": os.environ.get("DATABASE_PORT"),
294
+ "db_name": os.environ.get("DATABASE_NAME"),
295
+ }
296
+
297
+ if all(DB_VARS.values()):
298
+ DATABASE_URL = f"{DB_VARS['db_type']}://{DB_VARS['db_cred']}@{DB_VARS['db_host']}:{DB_VARS['db_port']}/{DB_VARS['db_name']}"
299
+ elif DATABASE_TYPE == "sqlite+sqlcipher" and not os.environ.get("DATABASE_URL"):
300
+ # Handle SQLCipher with local file when DATABASE_URL wasn't explicitly set
301
+ DATABASE_URL = f"sqlite+sqlcipher:///{DATA_DIR}/webui.db"
302
+
303
+ # Replace the postgres:// with postgresql://
304
+ if "postgres://" in DATABASE_URL:
305
+ DATABASE_URL = DATABASE_URL.replace("postgres://", "postgresql://")
306
+
307
+ DATABASE_SCHEMA = os.environ.get("DATABASE_SCHEMA", None)
308
+
309
+ DATABASE_POOL_SIZE = os.environ.get("DATABASE_POOL_SIZE", None)
310
+
311
+ if DATABASE_POOL_SIZE != None:
312
+ try:
313
+ DATABASE_POOL_SIZE = int(DATABASE_POOL_SIZE)
314
+ except Exception:
315
+ DATABASE_POOL_SIZE = None
316
+
317
+ DATABASE_POOL_MAX_OVERFLOW = os.environ.get("DATABASE_POOL_MAX_OVERFLOW", 0)
318
+
319
+ if DATABASE_POOL_MAX_OVERFLOW == "":
320
+ DATABASE_POOL_MAX_OVERFLOW = 0
321
+ else:
322
+ try:
323
+ DATABASE_POOL_MAX_OVERFLOW = int(DATABASE_POOL_MAX_OVERFLOW)
324
+ except Exception:
325
+ DATABASE_POOL_MAX_OVERFLOW = 0
326
+
327
+ DATABASE_POOL_TIMEOUT = os.environ.get("DATABASE_POOL_TIMEOUT", 30)
328
+
329
+ if DATABASE_POOL_TIMEOUT == "":
330
+ DATABASE_POOL_TIMEOUT = 30
331
+ else:
332
+ try:
333
+ DATABASE_POOL_TIMEOUT = int(DATABASE_POOL_TIMEOUT)
334
+ except Exception:
335
+ DATABASE_POOL_TIMEOUT = 30
336
+
337
+ DATABASE_POOL_RECYCLE = os.environ.get("DATABASE_POOL_RECYCLE", 3600)
338
+
339
+ if DATABASE_POOL_RECYCLE == "":
340
+ DATABASE_POOL_RECYCLE = 3600
341
+ else:
342
+ try:
343
+ DATABASE_POOL_RECYCLE = int(DATABASE_POOL_RECYCLE)
344
+ except Exception:
345
+ DATABASE_POOL_RECYCLE = 3600
346
+
347
+ DATABASE_ENABLE_SQLITE_WAL = (
348
+ os.environ.get("DATABASE_ENABLE_SQLITE_WAL", "False").lower() == "true"
349
+ )
350
+
351
+ DATABASE_USER_ACTIVE_STATUS_UPDATE_INTERVAL = os.environ.get(
352
+ "DATABASE_USER_ACTIVE_STATUS_UPDATE_INTERVAL", None
353
+ )
354
+ if DATABASE_USER_ACTIVE_STATUS_UPDATE_INTERVAL is not None:
355
+ try:
356
+ DATABASE_USER_ACTIVE_STATUS_UPDATE_INTERVAL = float(
357
+ DATABASE_USER_ACTIVE_STATUS_UPDATE_INTERVAL
358
+ )
359
+ except Exception:
360
+ DATABASE_USER_ACTIVE_STATUS_UPDATE_INTERVAL = 0.0
361
+
362
+ RESET_CONFIG_ON_START = (
363
+ os.environ.get("RESET_CONFIG_ON_START", "False").lower() == "true"
364
+ )
365
+
366
+ ENABLE_REALTIME_CHAT_SAVE = (
367
+ os.environ.get("ENABLE_REALTIME_CHAT_SAVE", "False").lower() == "true"
368
+ )
369
+
370
+ ENABLE_QUERIES_CACHE = os.environ.get("ENABLE_QUERIES_CACHE", "False").lower() == "true"
371
+
372
+ ####################################
373
+ # REDIS
374
+ ####################################
375
+
376
+ REDIS_URL = os.environ.get("REDIS_URL", "")
377
+ REDIS_CLUSTER = os.environ.get("REDIS_CLUSTER", "False").lower() == "true"
378
+
379
+ REDIS_KEY_PREFIX = os.environ.get("REDIS_KEY_PREFIX", "open-webui")
380
+
381
+ REDIS_SENTINEL_HOSTS = os.environ.get("REDIS_SENTINEL_HOSTS", "")
382
+ REDIS_SENTINEL_PORT = os.environ.get("REDIS_SENTINEL_PORT", "26379")
383
+
384
+ # Maximum number of retries for Redis operations when using Sentinel fail-over
385
+ REDIS_SENTINEL_MAX_RETRY_COUNT = os.environ.get("REDIS_SENTINEL_MAX_RETRY_COUNT", "2")
386
+ try:
387
+ REDIS_SENTINEL_MAX_RETRY_COUNT = int(REDIS_SENTINEL_MAX_RETRY_COUNT)
388
+ if REDIS_SENTINEL_MAX_RETRY_COUNT < 1:
389
+ REDIS_SENTINEL_MAX_RETRY_COUNT = 2
390
+ except ValueError:
391
+ REDIS_SENTINEL_MAX_RETRY_COUNT = 2
392
+
393
+ ####################################
394
+ # UVICORN WORKERS
395
+ ####################################
396
+
397
+ # Number of uvicorn worker processes for handling requests
398
+ UVICORN_WORKERS = os.environ.get("UVICORN_WORKERS", "1")
399
+ try:
400
+ UVICORN_WORKERS = int(UVICORN_WORKERS)
401
+ if UVICORN_WORKERS < 1:
402
+ UVICORN_WORKERS = 1
403
+ except ValueError:
404
+ UVICORN_WORKERS = 1
405
+ log.info(f"Invalid UVICORN_WORKERS value, defaulting to {UVICORN_WORKERS}")
406
+
407
+ ####################################
408
+ # WEBUI_AUTH (Required for security)
409
+ ####################################
410
+
411
+ WEBUI_AUTH = os.environ.get("WEBUI_AUTH", "True").lower() == "true"
412
+
413
+ ENABLE_INITIAL_ADMIN_SIGNUP = (
414
+ os.environ.get("ENABLE_INITIAL_ADMIN_SIGNUP", "False").lower() == "true"
415
+ )
416
+ ENABLE_SIGNUP_PASSWORD_CONFIRMATION = (
417
+ os.environ.get("ENABLE_SIGNUP_PASSWORD_CONFIRMATION", "False").lower() == "true"
418
+ )
419
+
420
+ WEBUI_AUTH_TRUSTED_EMAIL_HEADER = os.environ.get(
421
+ "WEBUI_AUTH_TRUSTED_EMAIL_HEADER", None
422
+ )
423
+ WEBUI_AUTH_TRUSTED_NAME_HEADER = os.environ.get("WEBUI_AUTH_TRUSTED_NAME_HEADER", None)
424
+ WEBUI_AUTH_TRUSTED_GROUPS_HEADER = os.environ.get(
425
+ "WEBUI_AUTH_TRUSTED_GROUPS_HEADER", None
426
+ )
427
+
428
+
429
+ BYPASS_MODEL_ACCESS_CONTROL = (
430
+ os.environ.get("BYPASS_MODEL_ACCESS_CONTROL", "False").lower() == "true"
431
+ )
432
+
433
+ WEBUI_AUTH_SIGNOUT_REDIRECT_URL = os.environ.get(
434
+ "WEBUI_AUTH_SIGNOUT_REDIRECT_URL", None
435
+ )
436
+
437
+ ####################################
438
+ # WEBUI_SECRET_KEY
439
+ ####################################
440
+
441
+ WEBUI_SECRET_KEY = os.environ.get(
442
+ "WEBUI_SECRET_KEY",
443
+ os.environ.get(
444
+ "WEBUI_JWT_SECRET_KEY", "t0p-s3cr3t"
445
+ ), # DEPRECATED: remove at next major version
446
+ )
447
+
448
+ WEBUI_SESSION_COOKIE_SAME_SITE = os.environ.get("WEBUI_SESSION_COOKIE_SAME_SITE", "lax")
449
+
450
+ WEBUI_SESSION_COOKIE_SECURE = (
451
+ os.environ.get("WEBUI_SESSION_COOKIE_SECURE", "false").lower() == "true"
452
+ )
453
+
454
+ WEBUI_AUTH_COOKIE_SAME_SITE = os.environ.get(
455
+ "WEBUI_AUTH_COOKIE_SAME_SITE", WEBUI_SESSION_COOKIE_SAME_SITE
456
+ )
457
+
458
+ WEBUI_AUTH_COOKIE_SECURE = (
459
+ os.environ.get(
460
+ "WEBUI_AUTH_COOKIE_SECURE",
461
+ os.environ.get("WEBUI_SESSION_COOKIE_SECURE", "false"),
462
+ ).lower()
463
+ == "true"
464
+ )
465
+
466
+ if WEBUI_AUTH and WEBUI_SECRET_KEY == "":
467
+ raise ValueError(ERROR_MESSAGES.ENV_VAR_NOT_FOUND)
468
+
469
+ ENABLE_COMPRESSION_MIDDLEWARE = (
470
+ os.environ.get("ENABLE_COMPRESSION_MIDDLEWARE", "True").lower() == "true"
471
+ )
472
+
473
+ ####################################
474
+ # OAUTH Configuration
475
+ ####################################
476
+ ENABLE_OAUTH_EMAIL_FALLBACK = (
477
+ os.environ.get("ENABLE_OAUTH_EMAIL_FALLBACK", "False").lower() == "true"
478
+ )
479
+
480
+ ENABLE_OAUTH_ID_TOKEN_COOKIE = (
481
+ os.environ.get("ENABLE_OAUTH_ID_TOKEN_COOKIE", "True").lower() == "true"
482
+ )
483
+
484
+ OAUTH_CLIENT_INFO_ENCRYPTION_KEY = os.environ.get(
485
+ "OAUTH_CLIENT_INFO_ENCRYPTION_KEY", WEBUI_SECRET_KEY
486
+ )
487
+
488
+ OAUTH_SESSION_TOKEN_ENCRYPTION_KEY = os.environ.get(
489
+ "OAUTH_SESSION_TOKEN_ENCRYPTION_KEY", WEBUI_SECRET_KEY
490
+ )
491
+
492
+ ####################################
493
+ # SCIM Configuration
494
+ ####################################
495
+
496
+ SCIM_ENABLED = os.environ.get("SCIM_ENABLED", "False").lower() == "true"
497
+ SCIM_TOKEN = os.environ.get("SCIM_TOKEN", "")
498
+
499
+ ####################################
500
+ # LICENSE_KEY
501
+ ####################################
502
+
503
+ LICENSE_KEY = os.environ.get("LICENSE_KEY", "")
504
+
505
+ LICENSE_BLOB = None
506
+ LICENSE_BLOB_PATH = os.environ.get("LICENSE_BLOB_PATH", DATA_DIR / "l.data")
507
+ if LICENSE_BLOB_PATH and os.path.exists(LICENSE_BLOB_PATH):
508
+ with open(LICENSE_BLOB_PATH, "rb") as f:
509
+ LICENSE_BLOB = f.read()
510
+
511
+ LICENSE_PUBLIC_KEY = os.environ.get("LICENSE_PUBLIC_KEY", "")
512
+
513
+ pk = None
514
+ if LICENSE_PUBLIC_KEY:
515
+ pk = serialization.load_pem_public_key(
516
+ f"""
517
+ -----BEGIN PUBLIC KEY-----
518
+ {LICENSE_PUBLIC_KEY}
519
+ -----END PUBLIC KEY-----
520
+ """.encode(
521
+ "utf-8"
522
+ )
523
+ )
524
+
525
+
526
+ ####################################
527
+ # MODELS
528
+ ####################################
529
+
530
+ MODELS_CACHE_TTL = os.environ.get("MODELS_CACHE_TTL", "1")
531
+ if MODELS_CACHE_TTL == "":
532
+ MODELS_CACHE_TTL = None
533
+ else:
534
+ try:
535
+ MODELS_CACHE_TTL = int(MODELS_CACHE_TTL)
536
+ except Exception:
537
+ MODELS_CACHE_TTL = 1
538
+
539
+
540
+ ####################################
541
+ # CHAT
542
+ ####################################
543
+
544
+ CHAT_RESPONSE_STREAM_DELTA_CHUNK_SIZE = os.environ.get(
545
+ "CHAT_RESPONSE_STREAM_DELTA_CHUNK_SIZE", "1"
546
+ )
547
+
548
+ if CHAT_RESPONSE_STREAM_DELTA_CHUNK_SIZE == "":
549
+ CHAT_RESPONSE_STREAM_DELTA_CHUNK_SIZE = 1
550
+ else:
551
+ try:
552
+ CHAT_RESPONSE_STREAM_DELTA_CHUNK_SIZE = int(
553
+ CHAT_RESPONSE_STREAM_DELTA_CHUNK_SIZE
554
+ )
555
+ except Exception:
556
+ CHAT_RESPONSE_STREAM_DELTA_CHUNK_SIZE = 1
557
+
558
+
559
+ CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES = os.environ.get(
560
+ "CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES", "30"
561
+ )
562
+
563
+ if CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES == "":
564
+ CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES = 30
565
+ else:
566
+ try:
567
+ CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES = int(CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES)
568
+ except Exception:
569
+ CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES = 30
570
+
571
+
572
+ ####################################
573
+ # WEBSOCKET SUPPORT
574
+ ####################################
575
+
576
+ ENABLE_WEBSOCKET_SUPPORT = (
577
+ os.environ.get("ENABLE_WEBSOCKET_SUPPORT", "True").lower() == "true"
578
+ )
579
+
580
+
581
+ WEBSOCKET_MANAGER = os.environ.get("WEBSOCKET_MANAGER", "")
582
+
583
+ WEBSOCKET_REDIS_URL = os.environ.get("WEBSOCKET_REDIS_URL", REDIS_URL)
584
+ WEBSOCKET_REDIS_CLUSTER = (
585
+ os.environ.get("WEBSOCKET_REDIS_CLUSTER", str(REDIS_CLUSTER)).lower() == "true"
586
+ )
587
+
588
+ websocket_redis_lock_timeout = os.environ.get("WEBSOCKET_REDIS_LOCK_TIMEOUT", "60")
589
+
590
+ try:
591
+ WEBSOCKET_REDIS_LOCK_TIMEOUT = int(websocket_redis_lock_timeout)
592
+ except ValueError:
593
+ WEBSOCKET_REDIS_LOCK_TIMEOUT = 60
594
+
595
+ WEBSOCKET_SENTINEL_HOSTS = os.environ.get("WEBSOCKET_SENTINEL_HOSTS", "")
596
+ WEBSOCKET_SENTINEL_PORT = os.environ.get("WEBSOCKET_SENTINEL_PORT", "26379")
597
+
598
+
599
+ AIOHTTP_CLIENT_TIMEOUT = os.environ.get("AIOHTTP_CLIENT_TIMEOUT", "")
600
+
601
+ if AIOHTTP_CLIENT_TIMEOUT == "":
602
+ AIOHTTP_CLIENT_TIMEOUT = None
603
+ else:
604
+ try:
605
+ AIOHTTP_CLIENT_TIMEOUT = int(AIOHTTP_CLIENT_TIMEOUT)
606
+ except Exception:
607
+ AIOHTTP_CLIENT_TIMEOUT = 300
608
+
609
+
610
+ AIOHTTP_CLIENT_SESSION_SSL = (
611
+ os.environ.get("AIOHTTP_CLIENT_SESSION_SSL", "True").lower() == "true"
612
+ )
613
+
614
+ AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST = os.environ.get(
615
+ "AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST",
616
+ os.environ.get("AIOHTTP_CLIENT_TIMEOUT_OPENAI_MODEL_LIST", "10"),
617
+ )
618
+
619
+ if AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST == "":
620
+ AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST = None
621
+ else:
622
+ try:
623
+ AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST = int(AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST)
624
+ except Exception:
625
+ AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST = 10
626
+
627
+
628
+ AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER_DATA = os.environ.get(
629
+ "AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER_DATA", "10"
630
+ )
631
+
632
+ if AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER_DATA == "":
633
+ AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER_DATA = None
634
+ else:
635
+ try:
636
+ AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER_DATA = int(
637
+ AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER_DATA
638
+ )
639
+ except Exception:
640
+ AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER_DATA = 10
641
+
642
+
643
+ AIOHTTP_CLIENT_SESSION_TOOL_SERVER_SSL = (
644
+ os.environ.get("AIOHTTP_CLIENT_SESSION_TOOL_SERVER_SSL", "True").lower() == "true"
645
+ )
646
+
647
+
648
+ ####################################
649
+ # SENTENCE TRANSFORMERS
650
+ ####################################
651
+
652
+
653
+ SENTENCE_TRANSFORMERS_BACKEND = os.environ.get("SENTENCE_TRANSFORMERS_BACKEND", "")
654
+ if SENTENCE_TRANSFORMERS_BACKEND == "":
655
+ SENTENCE_TRANSFORMERS_BACKEND = "torch"
656
+
657
+
658
+ SENTENCE_TRANSFORMERS_MODEL_KWARGS = os.environ.get(
659
+ "SENTENCE_TRANSFORMERS_MODEL_KWARGS", ""
660
+ )
661
+ if SENTENCE_TRANSFORMERS_MODEL_KWARGS == "":
662
+ SENTENCE_TRANSFORMERS_MODEL_KWARGS = None
663
+ else:
664
+ try:
665
+ SENTENCE_TRANSFORMERS_MODEL_KWARGS = json.loads(
666
+ SENTENCE_TRANSFORMERS_MODEL_KWARGS
667
+ )
668
+ except Exception:
669
+ SENTENCE_TRANSFORMERS_MODEL_KWARGS = None
670
+
671
+
672
+ SENTENCE_TRANSFORMERS_CROSS_ENCODER_BACKEND = os.environ.get(
673
+ "SENTENCE_TRANSFORMERS_CROSS_ENCODER_BACKEND", ""
674
+ )
675
+ if SENTENCE_TRANSFORMERS_CROSS_ENCODER_BACKEND == "":
676
+ SENTENCE_TRANSFORMERS_CROSS_ENCODER_BACKEND = "torch"
677
+
678
+
679
+ SENTENCE_TRANSFORMERS_CROSS_ENCODER_MODEL_KWARGS = os.environ.get(
680
+ "SENTENCE_TRANSFORMERS_CROSS_ENCODER_MODEL_KWARGS", ""
681
+ )
682
+ if SENTENCE_TRANSFORMERS_CROSS_ENCODER_MODEL_KWARGS == "":
683
+ SENTENCE_TRANSFORMERS_CROSS_ENCODER_MODEL_KWARGS = None
684
+ else:
685
+ try:
686
+ SENTENCE_TRANSFORMERS_CROSS_ENCODER_MODEL_KWARGS = json.loads(
687
+ SENTENCE_TRANSFORMERS_CROSS_ENCODER_MODEL_KWARGS
688
+ )
689
+ except Exception:
690
+ SENTENCE_TRANSFORMERS_CROSS_ENCODER_MODEL_KWARGS = None
691
+
692
+ ####################################
693
+ # OFFLINE_MODE
694
+ ####################################
695
+
696
+ ENABLE_VERSION_UPDATE_CHECK = (
697
+ os.environ.get("ENABLE_VERSION_UPDATE_CHECK", "true").lower() == "true"
698
+ )
699
+ OFFLINE_MODE = os.environ.get("OFFLINE_MODE", "false").lower() == "true"
700
+
701
+ if OFFLINE_MODE:
702
+ os.environ["HF_HUB_OFFLINE"] = "1"
703
+ ENABLE_VERSION_UPDATE_CHECK = False
704
+
705
+ ####################################
706
+ # AUDIT LOGGING
707
+ ####################################
708
+ # Where to store log file
709
+ AUDIT_LOGS_FILE_PATH = f"{DATA_DIR}/audit.log"
710
+ # Maximum size of a file before rotating into a new log file
711
+ AUDIT_LOG_FILE_ROTATION_SIZE = os.getenv("AUDIT_LOG_FILE_ROTATION_SIZE", "10MB")
712
+
713
+ # Comma separated list of logger names to use for audit logging
714
+ # Default is "uvicorn.access" which is the access log for Uvicorn
715
+ # You can add more logger names to this list if you want to capture more logs
716
+ AUDIT_UVICORN_LOGGER_NAMES = os.getenv(
717
+ "AUDIT_UVICORN_LOGGER_NAMES", "uvicorn.access"
718
+ ).split(",")
719
+
720
+ # METADATA | REQUEST | REQUEST_RESPONSE
721
+ AUDIT_LOG_LEVEL = os.getenv("AUDIT_LOG_LEVEL", "NONE").upper()
722
+ try:
723
+ MAX_BODY_LOG_SIZE = int(os.environ.get("MAX_BODY_LOG_SIZE") or 2048)
724
+ except ValueError:
725
+ MAX_BODY_LOG_SIZE = 2048
726
+
727
+ # Comma separated list for urls to exclude from audit
728
+ AUDIT_EXCLUDED_PATHS = os.getenv("AUDIT_EXCLUDED_PATHS", "/chats,/chat,/folders").split(
729
+ ","
730
+ )
731
+ AUDIT_EXCLUDED_PATHS = [path.strip() for path in AUDIT_EXCLUDED_PATHS]
732
+ AUDIT_EXCLUDED_PATHS = [path.lstrip("/") for path in AUDIT_EXCLUDED_PATHS]
733
+
734
+
735
+ ####################################
736
+ # OPENTELEMETRY
737
+ ####################################
738
+
739
+ ENABLE_OTEL = os.environ.get("ENABLE_OTEL", "False").lower() == "true"
740
+ ENABLE_OTEL_TRACES = os.environ.get("ENABLE_OTEL_TRACES", "False").lower() == "true"
741
+ ENABLE_OTEL_METRICS = os.environ.get("ENABLE_OTEL_METRICS", "False").lower() == "true"
742
+ ENABLE_OTEL_LOGS = os.environ.get("ENABLE_OTEL_LOGS", "False").lower() == "true"
743
+
744
+ OTEL_EXPORTER_OTLP_ENDPOINT = os.environ.get(
745
+ "OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4317"
746
+ )
747
+ OTEL_METRICS_EXPORTER_OTLP_ENDPOINT = os.environ.get(
748
+ "OTEL_METRICS_EXPORTER_OTLP_ENDPOINT", OTEL_EXPORTER_OTLP_ENDPOINT
749
+ )
750
+ OTEL_LOGS_EXPORTER_OTLP_ENDPOINT = os.environ.get(
751
+ "OTEL_LOGS_EXPORTER_OTLP_ENDPOINT", OTEL_EXPORTER_OTLP_ENDPOINT
752
+ )
753
+ OTEL_EXPORTER_OTLP_INSECURE = (
754
+ os.environ.get("OTEL_EXPORTER_OTLP_INSECURE", "False").lower() == "true"
755
+ )
756
+ OTEL_METRICS_EXPORTER_OTLP_INSECURE = (
757
+ os.environ.get(
758
+ "OTEL_METRICS_EXPORTER_OTLP_INSECURE", str(OTEL_EXPORTER_OTLP_INSECURE)
759
+ ).lower()
760
+ == "true"
761
+ )
762
+ OTEL_LOGS_EXPORTER_OTLP_INSECURE = (
763
+ os.environ.get(
764
+ "OTEL_LOGS_EXPORTER_OTLP_INSECURE", str(OTEL_EXPORTER_OTLP_INSECURE)
765
+ ).lower()
766
+ == "true"
767
+ )
768
+ OTEL_SERVICE_NAME = os.environ.get("OTEL_SERVICE_NAME", "open-webui")
769
+ OTEL_RESOURCE_ATTRIBUTES = os.environ.get(
770
+ "OTEL_RESOURCE_ATTRIBUTES", ""
771
+ ) # e.g. key1=val1,key2=val2
772
+ OTEL_TRACES_SAMPLER = os.environ.get(
773
+ "OTEL_TRACES_SAMPLER", "parentbased_always_on"
774
+ ).lower()
775
+ OTEL_BASIC_AUTH_USERNAME = os.environ.get("OTEL_BASIC_AUTH_USERNAME", "")
776
+ OTEL_BASIC_AUTH_PASSWORD = os.environ.get("OTEL_BASIC_AUTH_PASSWORD", "")
777
+
778
+ OTEL_METRICS_BASIC_AUTH_USERNAME = os.environ.get(
779
+ "OTEL_METRICS_BASIC_AUTH_USERNAME", OTEL_BASIC_AUTH_USERNAME
780
+ )
781
+ OTEL_METRICS_BASIC_AUTH_PASSWORD = os.environ.get(
782
+ "OTEL_METRICS_BASIC_AUTH_PASSWORD", OTEL_BASIC_AUTH_PASSWORD
783
+ )
784
+ OTEL_LOGS_BASIC_AUTH_USERNAME = os.environ.get(
785
+ "OTEL_LOGS_BASIC_AUTH_USERNAME", OTEL_BASIC_AUTH_USERNAME
786
+ )
787
+ OTEL_LOGS_BASIC_AUTH_PASSWORD = os.environ.get(
788
+ "OTEL_LOGS_BASIC_AUTH_PASSWORD", OTEL_BASIC_AUTH_PASSWORD
789
+ )
790
+
791
+ OTEL_OTLP_SPAN_EXPORTER = os.environ.get(
792
+ "OTEL_OTLP_SPAN_EXPORTER", "grpc"
793
+ ).lower() # grpc or http
794
+
795
+ OTEL_METRICS_OTLP_SPAN_EXPORTER = os.environ.get(
796
+ "OTEL_METRICS_OTLP_SPAN_EXPORTER", OTEL_OTLP_SPAN_EXPORTER
797
+ ).lower() # grpc or http
798
+
799
+ OTEL_LOGS_OTLP_SPAN_EXPORTER = os.environ.get(
800
+ "OTEL_LOGS_OTLP_SPAN_EXPORTER", OTEL_OTLP_SPAN_EXPORTER
801
+ ).lower() # grpc or http
802
+
803
+ ####################################
804
+ # TOOLS/FUNCTIONS PIP OPTIONS
805
+ ####################################
806
+
807
+ PIP_OPTIONS = os.getenv("PIP_OPTIONS", "").split()
808
+ PIP_PACKAGE_INDEX_OPTIONS = os.getenv("PIP_PACKAGE_INDEX_OPTIONS", "").split()
809
+
810
+
811
+ ####################################
812
+ # PROGRESSIVE WEB APP OPTIONS
813
+ ####################################
814
+
815
+ EXTERNAL_PWA_MANIFEST_URL = os.environ.get("EXTERNAL_PWA_MANIFEST_URL")
backend/open_webui/functions.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import sys
3
+ import inspect
4
+ import json
5
+ import asyncio
6
+
7
+ from pydantic import BaseModel
8
+ from typing import AsyncGenerator, Generator, Iterator
9
+ from fastapi import (
10
+ Depends,
11
+ FastAPI,
12
+ File,
13
+ Form,
14
+ HTTPException,
15
+ Request,
16
+ UploadFile,
17
+ status,
18
+ )
19
+ from starlette.responses import Response, StreamingResponse
20
+
21
+
22
+ from open_webui.constants import ERROR_MESSAGES
23
+ from open_webui.socket.main import (
24
+ get_event_call,
25
+ get_event_emitter,
26
+ )
27
+
28
+
29
+ from open_webui.models.users import UserModel
30
+ from open_webui.models.functions import Functions
31
+ from open_webui.models.models import Models
32
+
33
+ from open_webui.utils.plugin import (
34
+ load_function_module_by_id,
35
+ get_function_module_from_cache,
36
+ )
37
+ from open_webui.utils.tools import get_tools
38
+ from open_webui.utils.access_control import has_access
39
+
40
+ from open_webui.env import SRC_LOG_LEVELS, GLOBAL_LOG_LEVEL
41
+
42
+ from open_webui.utils.misc import (
43
+ add_or_update_system_message,
44
+ get_last_user_message,
45
+ prepend_to_first_user_message_content,
46
+ openai_chat_chunk_message_template,
47
+ openai_chat_completion_message_template,
48
+ )
49
+ from open_webui.utils.payload import (
50
+ apply_model_params_to_body_openai,
51
+ apply_system_prompt_to_body,
52
+ )
53
+
54
+
55
+ logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
56
+ log = logging.getLogger(__name__)
57
+ log.setLevel(SRC_LOG_LEVELS["MAIN"])
58
+
59
+
60
+ def get_function_module_by_id(request: Request, pipe_id: str):
61
+ function_module, _, _ = get_function_module_from_cache(request, pipe_id)
62
+
63
+ if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
64
+ Valves = function_module.Valves
65
+ valves = Functions.get_function_valves_by_id(pipe_id)
66
+
67
+ if valves:
68
+ try:
69
+ function_module.valves = Valves(
70
+ **{k: v for k, v in valves.items() if v is not None}
71
+ )
72
+ except Exception as e:
73
+ log.exception(f"Error loading valves for function {pipe_id}: {e}")
74
+ raise e
75
+ else:
76
+ function_module.valves = Valves()
77
+
78
+ return function_module
79
+
80
+
81
+ async def get_function_models(request):
82
+ pipes = Functions.get_functions_by_type("pipe", active_only=True)
83
+ pipe_models = []
84
+
85
+ for pipe in pipes:
86
+ try:
87
+ function_module = get_function_module_by_id(request, pipe.id)
88
+
89
+ has_user_valves = False
90
+ if hasattr(function_module, "UserValves"):
91
+ has_user_valves = True
92
+
93
+ # Check if function is a manifold
94
+ if hasattr(function_module, "pipes"):
95
+ sub_pipes = []
96
+
97
+ # Handle pipes being a list, sync function, or async function
98
+ try:
99
+ if callable(function_module.pipes):
100
+ if asyncio.iscoroutinefunction(function_module.pipes):
101
+ sub_pipes = await function_module.pipes()
102
+ else:
103
+ sub_pipes = function_module.pipes()
104
+ else:
105
+ sub_pipes = function_module.pipes
106
+ except Exception as e:
107
+ log.exception(e)
108
+ sub_pipes = []
109
+
110
+ log.debug(
111
+ f"get_function_models: function '{pipe.id}' is a manifold of {sub_pipes}"
112
+ )
113
+
114
+ for p in sub_pipes:
115
+ sub_pipe_id = f'{pipe.id}.{p["id"]}'
116
+ sub_pipe_name = p["name"]
117
+
118
+ if hasattr(function_module, "name"):
119
+ sub_pipe_name = f"{function_module.name}{sub_pipe_name}"
120
+
121
+ pipe_flag = {"type": pipe.type}
122
+
123
+ pipe_models.append(
124
+ {
125
+ "id": sub_pipe_id,
126
+ "name": sub_pipe_name,
127
+ "object": "model",
128
+ "created": pipe.created_at,
129
+ "owned_by": "openai",
130
+ "pipe": pipe_flag,
131
+ "has_user_valves": has_user_valves,
132
+ }
133
+ )
134
+ else:
135
+ pipe_flag = {"type": "pipe"}
136
+
137
+ log.debug(
138
+ f"get_function_models: function '{pipe.id}' is a single pipe {{ 'id': {pipe.id}, 'name': {pipe.name} }}"
139
+ )
140
+
141
+ pipe_models.append(
142
+ {
143
+ "id": pipe.id,
144
+ "name": pipe.name,
145
+ "object": "model",
146
+ "created": pipe.created_at,
147
+ "owned_by": "openai",
148
+ "pipe": pipe_flag,
149
+ "has_user_valves": has_user_valves,
150
+ }
151
+ )
152
+ except Exception as e:
153
+ log.exception(e)
154
+ continue
155
+
156
+ return pipe_models
157
+
158
+
159
+ async def generate_function_chat_completion(
160
+ request, form_data, user, models: dict = {}
161
+ ):
162
+ async def execute_pipe(pipe, params):
163
+ if inspect.iscoroutinefunction(pipe):
164
+ return await pipe(**params)
165
+ else:
166
+ return pipe(**params)
167
+
168
+ async def get_message_content(res: str | Generator | AsyncGenerator) -> str:
169
+ if isinstance(res, str):
170
+ return res
171
+ if isinstance(res, Generator):
172
+ return "".join(map(str, res))
173
+ if isinstance(res, AsyncGenerator):
174
+ return "".join([str(stream) async for stream in res])
175
+
176
+ def process_line(form_data: dict, line):
177
+ if isinstance(line, BaseModel):
178
+ line = line.model_dump_json()
179
+ line = f"data: {line}"
180
+ if isinstance(line, dict):
181
+ line = f"data: {json.dumps(line)}"
182
+
183
+ try:
184
+ line = line.decode("utf-8")
185
+ except Exception:
186
+ pass
187
+
188
+ if line.startswith("data:"):
189
+ return f"{line}\n\n"
190
+ else:
191
+ line = openai_chat_chunk_message_template(form_data["model"], line)
192
+ return f"data: {json.dumps(line)}\n\n"
193
+
194
+ def get_pipe_id(form_data: dict) -> str:
195
+ pipe_id = form_data["model"]
196
+ if "." in pipe_id:
197
+ pipe_id, _ = pipe_id.split(".", 1)
198
+ return pipe_id
199
+
200
+ def get_function_params(function_module, form_data, user, extra_params=None):
201
+ if extra_params is None:
202
+ extra_params = {}
203
+
204
+ pipe_id = get_pipe_id(form_data)
205
+
206
+ # Get the signature of the function
207
+ sig = inspect.signature(function_module.pipe)
208
+ params = {"body": form_data} | {
209
+ k: v for k, v in extra_params.items() if k in sig.parameters
210
+ }
211
+
212
+ if "__user__" in params and hasattr(function_module, "UserValves"):
213
+ user_valves = Functions.get_user_valves_by_id_and_user_id(pipe_id, user.id)
214
+ try:
215
+ params["__user__"]["valves"] = function_module.UserValves(**user_valves)
216
+ except Exception as e:
217
+ log.exception(e)
218
+ params["__user__"]["valves"] = function_module.UserValves()
219
+
220
+ return params
221
+
222
+ model_id = form_data.get("model")
223
+ model_info = Models.get_model_by_id(model_id)
224
+
225
+ metadata = form_data.pop("metadata", {})
226
+
227
+ files = metadata.get("files", [])
228
+ tool_ids = metadata.get("tool_ids", [])
229
+ # Check if tool_ids is None
230
+ if tool_ids is None:
231
+ tool_ids = []
232
+
233
+ __event_emitter__ = None
234
+ __event_call__ = None
235
+ __task__ = None
236
+ __task_body__ = None
237
+
238
+ if metadata:
239
+ if all(k in metadata for k in ("session_id", "chat_id", "message_id")):
240
+ __event_emitter__ = get_event_emitter(metadata)
241
+ __event_call__ = get_event_call(metadata)
242
+ __task__ = metadata.get("task", None)
243
+ __task_body__ = metadata.get("task_body", None)
244
+
245
+ oauth_token = None
246
+ try:
247
+ if request.cookies.get("oauth_session_id", None):
248
+ oauth_token = await request.app.state.oauth_manager.get_oauth_token(
249
+ user.id,
250
+ request.cookies.get("oauth_session_id", None),
251
+ )
252
+ except Exception as e:
253
+ log.error(f"Error getting OAuth token: {e}")
254
+
255
+ extra_params = {
256
+ "__event_emitter__": __event_emitter__,
257
+ "__event_call__": __event_call__,
258
+ "__chat_id__": metadata.get("chat_id", None),
259
+ "__session_id__": metadata.get("session_id", None),
260
+ "__message_id__": metadata.get("message_id", None),
261
+ "__task__": __task__,
262
+ "__task_body__": __task_body__,
263
+ "__files__": files,
264
+ "__user__": user.model_dump() if isinstance(user, UserModel) else {},
265
+ "__metadata__": metadata,
266
+ "__oauth_token__": oauth_token,
267
+ "__request__": request,
268
+ }
269
+ extra_params["__tools__"] = await get_tools(
270
+ request,
271
+ tool_ids,
272
+ user,
273
+ {
274
+ **extra_params,
275
+ "__model__": models.get(form_data["model"], None),
276
+ "__messages__": form_data["messages"],
277
+ "__files__": files,
278
+ },
279
+ )
280
+
281
+ if model_info:
282
+ if model_info.base_model_id:
283
+ form_data["model"] = model_info.base_model_id
284
+
285
+ params = model_info.params.model_dump()
286
+
287
+ if params:
288
+ system = params.pop("system", None)
289
+ form_data = apply_model_params_to_body_openai(params, form_data)
290
+ form_data = apply_system_prompt_to_body(system, form_data, metadata, user)
291
+
292
+ pipe_id = get_pipe_id(form_data)
293
+ function_module = get_function_module_by_id(request, pipe_id)
294
+
295
+ pipe = function_module.pipe
296
+ params = get_function_params(function_module, form_data, user, extra_params)
297
+
298
+ if form_data.get("stream", False):
299
+
300
+ async def stream_content():
301
+ try:
302
+ res = await execute_pipe(pipe, params)
303
+
304
+ # Directly return if the response is a StreamingResponse
305
+ if isinstance(res, StreamingResponse):
306
+ async for data in res.body_iterator:
307
+ yield data
308
+ return
309
+ if isinstance(res, dict):
310
+ yield f"data: {json.dumps(res)}\n\n"
311
+ return
312
+
313
+ except Exception as e:
314
+ log.error(f"Error: {e}")
315
+ yield f"data: {json.dumps({'error': {'detail':str(e)}})}\n\n"
316
+ return
317
+
318
+ if isinstance(res, str):
319
+ message = openai_chat_chunk_message_template(form_data["model"], res)
320
+ yield f"data: {json.dumps(message)}\n\n"
321
+
322
+ if isinstance(res, Iterator):
323
+ for line in res:
324
+ yield process_line(form_data, line)
325
+
326
+ if isinstance(res, AsyncGenerator):
327
+ async for line in res:
328
+ yield process_line(form_data, line)
329
+
330
+ if isinstance(res, str) or isinstance(res, Generator):
331
+ finish_message = openai_chat_chunk_message_template(
332
+ form_data["model"], ""
333
+ )
334
+ finish_message["choices"][0]["finish_reason"] = "stop"
335
+ yield f"data: {json.dumps(finish_message)}\n\n"
336
+ yield "data: [DONE]"
337
+
338
+ return StreamingResponse(stream_content(), media_type="text/event-stream")
339
+ else:
340
+ try:
341
+ res = await execute_pipe(pipe, params)
342
+
343
+ except Exception as e:
344
+ log.error(f"Error: {e}")
345
+ return {"error": {"detail": str(e)}}
346
+
347
+ if isinstance(res, StreamingResponse) or isinstance(res, dict):
348
+ return res
349
+ if isinstance(res, BaseModel):
350
+ return res.model_dump()
351
+
352
+ message = await get_message_content(res)
353
+ return openai_chat_completion_message_template(form_data["model"], message)
backend/open_webui/internal/db.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ import logging
4
+ from contextlib import contextmanager
5
+ from typing import Any, Optional
6
+
7
+ from open_webui.internal.wrappers import register_connection
8
+ from open_webui.env import (
9
+ OPEN_WEBUI_DIR,
10
+ DATABASE_URL,
11
+ DATABASE_SCHEMA,
12
+ SRC_LOG_LEVELS,
13
+ DATABASE_POOL_MAX_OVERFLOW,
14
+ DATABASE_POOL_RECYCLE,
15
+ DATABASE_POOL_SIZE,
16
+ DATABASE_POOL_TIMEOUT,
17
+ DATABASE_ENABLE_SQLITE_WAL,
18
+ )
19
+ from peewee_migrate import Router
20
+ from sqlalchemy import Dialect, create_engine, MetaData, event, types
21
+ from sqlalchemy.ext.declarative import declarative_base
22
+ from sqlalchemy.orm import scoped_session, sessionmaker
23
+ from sqlalchemy.pool import QueuePool, NullPool
24
+ from sqlalchemy.sql.type_api import _T
25
+ from typing_extensions import Self
26
+
27
+ log = logging.getLogger(__name__)
28
+ log.setLevel(SRC_LOG_LEVELS["DB"])
29
+
30
+
31
+ class JSONField(types.TypeDecorator):
32
+ impl = types.Text
33
+ cache_ok = True
34
+
35
+ def process_bind_param(self, value: Optional[_T], dialect: Dialect) -> Any:
36
+ return json.dumps(value)
37
+
38
+ def process_result_value(self, value: Optional[_T], dialect: Dialect) -> Any:
39
+ if value is not None:
40
+ return json.loads(value)
41
+
42
+ def copy(self, **kw: Any) -> Self:
43
+ return JSONField(self.impl.length)
44
+
45
+ def db_value(self, value):
46
+ return json.dumps(value)
47
+
48
+ def python_value(self, value):
49
+ if value is not None:
50
+ return json.loads(value)
51
+
52
+
53
+ # Workaround to handle the peewee migration
54
+ # This is required to ensure the peewee migration is handled before the alembic migration
55
+ def handle_peewee_migration(DATABASE_URL):
56
+ # db = None
57
+ try:
58
+ # Replace the postgresql:// with postgres:// to handle the peewee migration
59
+ db = register_connection(DATABASE_URL.replace("postgresql://", "postgres://"))
60
+ migrate_dir = OPEN_WEBUI_DIR / "internal" / "migrations"
61
+ router = Router(db, logger=log, migrate_dir=migrate_dir)
62
+ router.run()
63
+ db.close()
64
+
65
+ except Exception as e:
66
+ log.error(f"Failed to initialize the database connection: {e}")
67
+ log.warning(
68
+ "Hint: If your database password contains special characters, you may need to URL-encode it."
69
+ )
70
+ raise
71
+ finally:
72
+ # Properly closing the database connection
73
+ if db and not db.is_closed():
74
+ db.close()
75
+
76
+ # Assert if db connection has been closed
77
+ assert db.is_closed(), "Database connection is still open."
78
+
79
+
80
+ handle_peewee_migration(DATABASE_URL)
81
+
82
+
83
+ SQLALCHEMY_DATABASE_URL = DATABASE_URL
84
+
85
+ # Handle SQLCipher URLs
86
+ if SQLALCHEMY_DATABASE_URL.startswith("sqlite+sqlcipher://"):
87
+ database_password = os.environ.get("DATABASE_PASSWORD")
88
+ if not database_password or database_password.strip() == "":
89
+ raise ValueError(
90
+ "DATABASE_PASSWORD is required when using sqlite+sqlcipher:// URLs"
91
+ )
92
+
93
+ # Extract database path from SQLCipher URL
94
+ db_path = SQLALCHEMY_DATABASE_URL.replace("sqlite+sqlcipher://", "")
95
+ if db_path.startswith("/"):
96
+ db_path = db_path[1:] # Remove leading slash for relative paths
97
+
98
+ # Create a custom creator function that uses sqlcipher3
99
+ def create_sqlcipher_connection():
100
+ import sqlcipher3
101
+
102
+ conn = sqlcipher3.connect(db_path, check_same_thread=False)
103
+ conn.execute(f"PRAGMA key = '{database_password}'")
104
+ return conn
105
+
106
+ engine = create_engine(
107
+ "sqlite://", # Dummy URL since we're using creator
108
+ creator=create_sqlcipher_connection,
109
+ echo=False,
110
+ )
111
+
112
+ log.info("Connected to encrypted SQLite database using SQLCipher")
113
+
114
+ elif "sqlite" in SQLALCHEMY_DATABASE_URL:
115
+ engine = create_engine(
116
+ SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
117
+ )
118
+
119
+ def on_connect(dbapi_connection, connection_record):
120
+ cursor = dbapi_connection.cursor()
121
+ if DATABASE_ENABLE_SQLITE_WAL:
122
+ cursor.execute("PRAGMA journal_mode=WAL")
123
+ else:
124
+ cursor.execute("PRAGMA journal_mode=DELETE")
125
+ cursor.close()
126
+
127
+ event.listen(engine, "connect", on_connect)
128
+ else:
129
+ if isinstance(DATABASE_POOL_SIZE, int):
130
+ if DATABASE_POOL_SIZE > 0:
131
+ engine = create_engine(
132
+ SQLALCHEMY_DATABASE_URL,
133
+ pool_size=DATABASE_POOL_SIZE,
134
+ max_overflow=DATABASE_POOL_MAX_OVERFLOW,
135
+ pool_timeout=DATABASE_POOL_TIMEOUT,
136
+ pool_recycle=DATABASE_POOL_RECYCLE,
137
+ pool_pre_ping=True,
138
+ poolclass=QueuePool,
139
+ )
140
+ else:
141
+ engine = create_engine(
142
+ SQLALCHEMY_DATABASE_URL, pool_pre_ping=True, poolclass=NullPool
143
+ )
144
+ else:
145
+ engine = create_engine(SQLALCHEMY_DATABASE_URL, pool_pre_ping=True)
146
+
147
+
148
+ SessionLocal = sessionmaker(
149
+ autocommit=False, autoflush=False, bind=engine, expire_on_commit=False
150
+ )
151
+ metadata_obj = MetaData(schema=DATABASE_SCHEMA)
152
+ Base = declarative_base(metadata=metadata_obj)
153
+ Session = scoped_session(SessionLocal)
154
+
155
+
156
+ def get_session():
157
+ db = SessionLocal()
158
+ try:
159
+ yield db
160
+ finally:
161
+ db.close()
162
+
163
+
164
+ get_db = contextmanager(get_session)
backend/open_webui/internal/migrations/001_initial_schema.py ADDED
@@ -0,0 +1,254 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Peewee migrations -- 001_initial_schema.py.
2
+
3
+ Some examples (model - class or model name)::
4
+
5
+ > Model = migrator.orm['table_name'] # Return model in current state by name
6
+ > Model = migrator.ModelClass # Return model in current state by name
7
+
8
+ > migrator.sql(sql) # Run custom SQL
9
+ > migrator.run(func, *args, **kwargs) # Run python function with the given args
10
+ > migrator.create_model(Model) # Create a model (could be used as decorator)
11
+ > migrator.remove_model(model, cascade=True) # Remove a model
12
+ > migrator.add_fields(model, **fields) # Add fields to a model
13
+ > migrator.change_fields(model, **fields) # Change fields
14
+ > migrator.remove_fields(model, *field_names, cascade=True)
15
+ > migrator.rename_field(model, old_field_name, new_field_name)
16
+ > migrator.rename_table(model, new_table_name)
17
+ > migrator.add_index(model, *col_names, unique=False)
18
+ > migrator.add_not_null(model, *field_names)
19
+ > migrator.add_default(model, field_name, default)
20
+ > migrator.add_constraint(model, name, sql)
21
+ > migrator.drop_index(model, *col_names)
22
+ > migrator.drop_not_null(model, *field_names)
23
+ > migrator.drop_constraints(model, *constraints)
24
+
25
+ """
26
+
27
+ from contextlib import suppress
28
+
29
+ import peewee as pw
30
+ from peewee_migrate import Migrator
31
+
32
+
33
+ with suppress(ImportError):
34
+ import playhouse.postgres_ext as pw_pext
35
+
36
+
37
+ def migrate(migrator: Migrator, database: pw.Database, *, fake=False):
38
+ """Write your migrations here."""
39
+
40
+ # We perform different migrations for SQLite and other databases
41
+ # This is because SQLite is very loose with enforcing its schema, and trying to migrate other databases like SQLite
42
+ # will require per-database SQL queries.
43
+ # Instead, we assume that because external DB support was added at a later date, it is safe to assume a newer base
44
+ # schema instead of trying to migrate from an older schema.
45
+ if isinstance(database, pw.SqliteDatabase):
46
+ migrate_sqlite(migrator, database, fake=fake)
47
+ else:
48
+ migrate_external(migrator, database, fake=fake)
49
+
50
+
51
+ def migrate_sqlite(migrator: Migrator, database: pw.Database, *, fake=False):
52
+ @migrator.create_model
53
+ class Auth(pw.Model):
54
+ id = pw.CharField(max_length=255, unique=True)
55
+ email = pw.CharField(max_length=255)
56
+ password = pw.CharField(max_length=255)
57
+ active = pw.BooleanField()
58
+
59
+ class Meta:
60
+ table_name = "auth"
61
+
62
+ @migrator.create_model
63
+ class Chat(pw.Model):
64
+ id = pw.CharField(max_length=255, unique=True)
65
+ user_id = pw.CharField(max_length=255)
66
+ title = pw.CharField()
67
+ chat = pw.TextField()
68
+ timestamp = pw.BigIntegerField()
69
+
70
+ class Meta:
71
+ table_name = "chat"
72
+
73
+ @migrator.create_model
74
+ class ChatIdTag(pw.Model):
75
+ id = pw.CharField(max_length=255, unique=True)
76
+ tag_name = pw.CharField(max_length=255)
77
+ chat_id = pw.CharField(max_length=255)
78
+ user_id = pw.CharField(max_length=255)
79
+ timestamp = pw.BigIntegerField()
80
+
81
+ class Meta:
82
+ table_name = "chatidtag"
83
+
84
+ @migrator.create_model
85
+ class Document(pw.Model):
86
+ id = pw.AutoField()
87
+ collection_name = pw.CharField(max_length=255, unique=True)
88
+ name = pw.CharField(max_length=255, unique=True)
89
+ title = pw.CharField()
90
+ filename = pw.CharField()
91
+ content = pw.TextField(null=True)
92
+ user_id = pw.CharField(max_length=255)
93
+ timestamp = pw.BigIntegerField()
94
+
95
+ class Meta:
96
+ table_name = "document"
97
+
98
+ @migrator.create_model
99
+ class Modelfile(pw.Model):
100
+ id = pw.AutoField()
101
+ tag_name = pw.CharField(max_length=255, unique=True)
102
+ user_id = pw.CharField(max_length=255)
103
+ modelfile = pw.TextField()
104
+ timestamp = pw.BigIntegerField()
105
+
106
+ class Meta:
107
+ table_name = "modelfile"
108
+
109
+ @migrator.create_model
110
+ class Prompt(pw.Model):
111
+ id = pw.AutoField()
112
+ command = pw.CharField(max_length=255, unique=True)
113
+ user_id = pw.CharField(max_length=255)
114
+ title = pw.CharField()
115
+ content = pw.TextField()
116
+ timestamp = pw.BigIntegerField()
117
+
118
+ class Meta:
119
+ table_name = "prompt"
120
+
121
+ @migrator.create_model
122
+ class Tag(pw.Model):
123
+ id = pw.CharField(max_length=255, unique=True)
124
+ name = pw.CharField(max_length=255)
125
+ user_id = pw.CharField(max_length=255)
126
+ data = pw.TextField(null=True)
127
+
128
+ class Meta:
129
+ table_name = "tag"
130
+
131
+ @migrator.create_model
132
+ class User(pw.Model):
133
+ id = pw.CharField(max_length=255, unique=True)
134
+ name = pw.CharField(max_length=255)
135
+ email = pw.CharField(max_length=255)
136
+ role = pw.CharField(max_length=255)
137
+ profile_image_url = pw.CharField(max_length=255)
138
+ timestamp = pw.BigIntegerField()
139
+
140
+ class Meta:
141
+ table_name = "user"
142
+
143
+
144
+ def migrate_external(migrator: Migrator, database: pw.Database, *, fake=False):
145
+ @migrator.create_model
146
+ class Auth(pw.Model):
147
+ id = pw.CharField(max_length=255, unique=True)
148
+ email = pw.CharField(max_length=255)
149
+ password = pw.TextField()
150
+ active = pw.BooleanField()
151
+
152
+ class Meta:
153
+ table_name = "auth"
154
+
155
+ @migrator.create_model
156
+ class Chat(pw.Model):
157
+ id = pw.CharField(max_length=255, unique=True)
158
+ user_id = pw.CharField(max_length=255)
159
+ title = pw.TextField()
160
+ chat = pw.TextField()
161
+ timestamp = pw.BigIntegerField()
162
+
163
+ class Meta:
164
+ table_name = "chat"
165
+
166
+ @migrator.create_model
167
+ class ChatIdTag(pw.Model):
168
+ id = pw.CharField(max_length=255, unique=True)
169
+ tag_name = pw.CharField(max_length=255)
170
+ chat_id = pw.CharField(max_length=255)
171
+ user_id = pw.CharField(max_length=255)
172
+ timestamp = pw.BigIntegerField()
173
+
174
+ class Meta:
175
+ table_name = "chatidtag"
176
+
177
+ @migrator.create_model
178
+ class Document(pw.Model):
179
+ id = pw.AutoField()
180
+ collection_name = pw.CharField(max_length=255, unique=True)
181
+ name = pw.CharField(max_length=255, unique=True)
182
+ title = pw.TextField()
183
+ filename = pw.TextField()
184
+ content = pw.TextField(null=True)
185
+ user_id = pw.CharField(max_length=255)
186
+ timestamp = pw.BigIntegerField()
187
+
188
+ class Meta:
189
+ table_name = "document"
190
+
191
+ @migrator.create_model
192
+ class Modelfile(pw.Model):
193
+ id = pw.AutoField()
194
+ tag_name = pw.CharField(max_length=255, unique=True)
195
+ user_id = pw.CharField(max_length=255)
196
+ modelfile = pw.TextField()
197
+ timestamp = pw.BigIntegerField()
198
+
199
+ class Meta:
200
+ table_name = "modelfile"
201
+
202
+ @migrator.create_model
203
+ class Prompt(pw.Model):
204
+ id = pw.AutoField()
205
+ command = pw.CharField(max_length=255, unique=True)
206
+ user_id = pw.CharField(max_length=255)
207
+ title = pw.TextField()
208
+ content = pw.TextField()
209
+ timestamp = pw.BigIntegerField()
210
+
211
+ class Meta:
212
+ table_name = "prompt"
213
+
214
+ @migrator.create_model
215
+ class Tag(pw.Model):
216
+ id = pw.CharField(max_length=255, unique=True)
217
+ name = pw.CharField(max_length=255)
218
+ user_id = pw.CharField(max_length=255)
219
+ data = pw.TextField(null=True)
220
+
221
+ class Meta:
222
+ table_name = "tag"
223
+
224
+ @migrator.create_model
225
+ class User(pw.Model):
226
+ id = pw.CharField(max_length=255, unique=True)
227
+ name = pw.CharField(max_length=255)
228
+ email = pw.CharField(max_length=255)
229
+ role = pw.CharField(max_length=255)
230
+ profile_image_url = pw.TextField()
231
+ timestamp = pw.BigIntegerField()
232
+
233
+ class Meta:
234
+ table_name = "user"
235
+
236
+
237
+ def rollback(migrator: Migrator, database: pw.Database, *, fake=False):
238
+ """Write your rollback migrations here."""
239
+
240
+ migrator.remove_model("user")
241
+
242
+ migrator.remove_model("tag")
243
+
244
+ migrator.remove_model("prompt")
245
+
246
+ migrator.remove_model("modelfile")
247
+
248
+ migrator.remove_model("document")
249
+
250
+ migrator.remove_model("chatidtag")
251
+
252
+ migrator.remove_model("chat")
253
+
254
+ migrator.remove_model("auth")
backend/open_webui/internal/migrations/002_add_local_sharing.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Peewee migrations -- 002_add_local_sharing.py.
2
+
3
+ Some examples (model - class or model name)::
4
+
5
+ > Model = migrator.orm['table_name'] # Return model in current state by name
6
+ > Model = migrator.ModelClass # Return model in current state by name
7
+
8
+ > migrator.sql(sql) # Run custom SQL
9
+ > migrator.run(func, *args, **kwargs) # Run python function with the given args
10
+ > migrator.create_model(Model) # Create a model (could be used as decorator)
11
+ > migrator.remove_model(model, cascade=True) # Remove a model
12
+ > migrator.add_fields(model, **fields) # Add fields to a model
13
+ > migrator.change_fields(model, **fields) # Change fields
14
+ > migrator.remove_fields(model, *field_names, cascade=True)
15
+ > migrator.rename_field(model, old_field_name, new_field_name)
16
+ > migrator.rename_table(model, new_table_name)
17
+ > migrator.add_index(model, *col_names, unique=False)
18
+ > migrator.add_not_null(model, *field_names)
19
+ > migrator.add_default(model, field_name, default)
20
+ > migrator.add_constraint(model, name, sql)
21
+ > migrator.drop_index(model, *col_names)
22
+ > migrator.drop_not_null(model, *field_names)
23
+ > migrator.drop_constraints(model, *constraints)
24
+
25
+ """
26
+
27
+ from contextlib import suppress
28
+
29
+ import peewee as pw
30
+ from peewee_migrate import Migrator
31
+
32
+
33
+ with suppress(ImportError):
34
+ import playhouse.postgres_ext as pw_pext
35
+
36
+
37
+ def migrate(migrator: Migrator, database: pw.Database, *, fake=False):
38
+ """Write your migrations here."""
39
+
40
+ migrator.add_fields(
41
+ "chat", share_id=pw.CharField(max_length=255, null=True, unique=True)
42
+ )
43
+
44
+
45
+ def rollback(migrator: Migrator, database: pw.Database, *, fake=False):
46
+ """Write your rollback migrations here."""
47
+
48
+ migrator.remove_fields("chat", "share_id")
backend/open_webui/internal/migrations/003_add_auth_api_key.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Peewee migrations -- 002_add_local_sharing.py.
2
+
3
+ Some examples (model - class or model name)::
4
+
5
+ > Model = migrator.orm['table_name'] # Return model in current state by name
6
+ > Model = migrator.ModelClass # Return model in current state by name
7
+
8
+ > migrator.sql(sql) # Run custom SQL
9
+ > migrator.run(func, *args, **kwargs) # Run python function with the given args
10
+ > migrator.create_model(Model) # Create a model (could be used as decorator)
11
+ > migrator.remove_model(model, cascade=True) # Remove a model
12
+ > migrator.add_fields(model, **fields) # Add fields to a model
13
+ > migrator.change_fields(model, **fields) # Change fields
14
+ > migrator.remove_fields(model, *field_names, cascade=True)
15
+ > migrator.rename_field(model, old_field_name, new_field_name)
16
+ > migrator.rename_table(model, new_table_name)
17
+ > migrator.add_index(model, *col_names, unique=False)
18
+ > migrator.add_not_null(model, *field_names)
19
+ > migrator.add_default(model, field_name, default)
20
+ > migrator.add_constraint(model, name, sql)
21
+ > migrator.drop_index(model, *col_names)
22
+ > migrator.drop_not_null(model, *field_names)
23
+ > migrator.drop_constraints(model, *constraints)
24
+
25
+ """
26
+
27
+ from contextlib import suppress
28
+
29
+ import peewee as pw
30
+ from peewee_migrate import Migrator
31
+
32
+
33
+ with suppress(ImportError):
34
+ import playhouse.postgres_ext as pw_pext
35
+
36
+
37
+ def migrate(migrator: Migrator, database: pw.Database, *, fake=False):
38
+ """Write your migrations here."""
39
+
40
+ migrator.add_fields(
41
+ "user", api_key=pw.CharField(max_length=255, null=True, unique=True)
42
+ )
43
+
44
+
45
+ def rollback(migrator: Migrator, database: pw.Database, *, fake=False):
46
+ """Write your rollback migrations here."""
47
+
48
+ migrator.remove_fields("user", "api_key")
backend/open_webui/internal/migrations/004_add_archived.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Peewee migrations -- 002_add_local_sharing.py.
2
+
3
+ Some examples (model - class or model name)::
4
+
5
+ > Model = migrator.orm['table_name'] # Return model in current state by name
6
+ > Model = migrator.ModelClass # Return model in current state by name
7
+
8
+ > migrator.sql(sql) # Run custom SQL
9
+ > migrator.run(func, *args, **kwargs) # Run python function with the given args
10
+ > migrator.create_model(Model) # Create a model (could be used as decorator)
11
+ > migrator.remove_model(model, cascade=True) # Remove a model
12
+ > migrator.add_fields(model, **fields) # Add fields to a model
13
+ > migrator.change_fields(model, **fields) # Change fields
14
+ > migrator.remove_fields(model, *field_names, cascade=True)
15
+ > migrator.rename_field(model, old_field_name, new_field_name)
16
+ > migrator.rename_table(model, new_table_name)
17
+ > migrator.add_index(model, *col_names, unique=False)
18
+ > migrator.add_not_null(model, *field_names)
19
+ > migrator.add_default(model, field_name, default)
20
+ > migrator.add_constraint(model, name, sql)
21
+ > migrator.drop_index(model, *col_names)
22
+ > migrator.drop_not_null(model, *field_names)
23
+ > migrator.drop_constraints(model, *constraints)
24
+
25
+ """
26
+
27
+ from contextlib import suppress
28
+
29
+ import peewee as pw
30
+ from peewee_migrate import Migrator
31
+
32
+
33
+ with suppress(ImportError):
34
+ import playhouse.postgres_ext as pw_pext
35
+
36
+
37
+ def migrate(migrator: Migrator, database: pw.Database, *, fake=False):
38
+ """Write your migrations here."""
39
+
40
+ migrator.add_fields("chat", archived=pw.BooleanField(default=False))
41
+
42
+
43
+ def rollback(migrator: Migrator, database: pw.Database, *, fake=False):
44
+ """Write your rollback migrations here."""
45
+
46
+ migrator.remove_fields("chat", "archived")