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

GitHub deploy: b2af6313f1dff7fdd5d51fdcac99a86f9ffecebc

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 +13 -0
  3. .eslintignore +13 -0
  4. .eslintrc.cjs +31 -0
  5. .gitattributes +3 -0
  6. .github/FUNDING.yml +1 -0
  7. .github/ISSUE_TEMPLATE/bug_report.yaml +146 -0
  8. .github/ISSUE_TEMPLATE/config.yml +1 -0
  9. .github/ISSUE_TEMPLATE/feature_request.yaml +64 -0
  10. .github/dependabot.yml +26 -0
  11. .github/pull_request_template.md +76 -0
  12. .github/workflows/build-release.yml +72 -0
  13. .github/workflows/codespell.disabled +25 -0
  14. .github/workflows/deploy-to-hf-spaces.yml +78 -0
  15. .github/workflows/docker-build.yaml +496 -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 +32 -0
  22. .github/workflows/sync-hf-spaces-with-dev.yml +30 -0
  23. .gitignore +309 -0
  24. .npmrc +1 -0
  25. .prettierignore +316 -0
  26. .prettierrc +9 -0
  27. CHANGELOG.md +0 -0
  28. CODE_OF_CONDUCT.md +99 -0
  29. CONTRIBUTOR_LICENSE_AGREEMENT +7 -0
  30. Caddyfile.localhost +64 -0
  31. Dockerfile +3 -0
  32. INSTALLATION.md +35 -0
  33. LICENSE +33 -0
  34. Makefile +33 -0
  35. README.md +247 -0
  36. TROUBLESHOOTING.md +36 -0
  37. backend/.dockerignore +14 -0
  38. backend/.gitignore +12 -0
  39. backend/dev.sh +2 -0
  40. backend/open_webui/__init__.py +103 -0
  41. backend/open_webui/alembic.ini +114 -0
  42. backend/open_webui/config.py +2762 -0
  43. backend/open_webui/constants.py +120 -0
  44. backend/open_webui/env.py +559 -0
  45. backend/open_webui/functions.py +322 -0
  46. backend/open_webui/internal/db.py +116 -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,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # DO NOT TRACK
11
+ SCARF_NO_ANALYTICS=true
12
+ DO_NOT_TRACK=true
13
+ 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,3 @@
 
 
 
 
1
+ *.sh text eol=lf
2
+ *.ttf filter=lfs diff=lfs merge=lfs -text
3
+ *.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,146 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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) or [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.
15
+
16
+ - **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.
17
+
18
+ - **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.
19
+
20
+ - **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!
21
+
22
+ - type: checkboxes
23
+ id: issue-check
24
+ attributes:
25
+ label: Check Existing Issues
26
+ description: Confirm that you’ve checked for existing reports before submitting a new one.
27
+ options:
28
+ - label: I have searched the existing issues and discussions.
29
+ required: true
30
+ - label: I am using the latest version of Open WebUI.
31
+ required: true
32
+
33
+ - type: dropdown
34
+ id: installation-method
35
+ attributes:
36
+ label: Installation Method
37
+ description: How did you install Open WebUI?
38
+ options:
39
+ - Git Clone
40
+ - Pip Install
41
+ - Docker
42
+ - Other
43
+ validations:
44
+ required: true
45
+
46
+ - type: input
47
+ id: open-webui-version
48
+ attributes:
49
+ label: Open WebUI Version
50
+ description: Specify the version (e.g., v0.3.11)
51
+ validations:
52
+ required: true
53
+
54
+ - type: input
55
+ id: ollama-version
56
+ attributes:
57
+ label: Ollama Version (if applicable)
58
+ description: Specify the version (e.g., v0.2.0, or v0.1.32-rc1)
59
+ validations:
60
+ required: false
61
+
62
+ - type: input
63
+ id: operating-system
64
+ attributes:
65
+ label: Operating System
66
+ description: Specify the OS (e.g., Windows 10, macOS Sonoma, Ubuntu 22.04)
67
+ validations:
68
+ required: true
69
+
70
+ - type: input
71
+ id: browser
72
+ attributes:
73
+ label: Browser (if applicable)
74
+ description: Specify the browser/version (e.g., Chrome 100.0, Firefox 98.0)
75
+ validations:
76
+ required: false
77
+
78
+ - type: checkboxes
79
+ id: confirmation
80
+ attributes:
81
+ label: Confirmation
82
+ description: Ensure the following prerequisites have been met.
83
+ options:
84
+ - label: I have read and followed all instructions in `README.md`.
85
+ required: true
86
+ - label: I am using the latest version of **both** Open WebUI and Ollama.
87
+ required: true
88
+ - label: I have included the browser console logs.
89
+ required: true
90
+ - label: I have included the Docker container logs.
91
+ required: true
92
+ - label: I have listed steps to reproduce the bug in detail.
93
+ required: true
94
+
95
+ - type: textarea
96
+ id: expected-behavior
97
+ attributes:
98
+ label: Expected Behavior
99
+ description: Describe what should have happened.
100
+ validations:
101
+ required: true
102
+
103
+ - type: textarea
104
+ id: actual-behavior
105
+ attributes:
106
+ label: Actual Behavior
107
+ description: Describe what actually happened.
108
+ validations:
109
+ required: true
110
+
111
+ - type: textarea
112
+ id: reproduction-steps
113
+ attributes:
114
+ label: Steps to Reproduce
115
+ description: Providing clear, step-by-step instructions helps us reproduce and fix the issue faster. If we can't reproduce it, we can't fix it.
116
+ placeholder: |
117
+ 1. Go to '...'
118
+ 2. Click on '...'
119
+ 3. Scroll down to '...'
120
+ 4. See the error message '...'
121
+ validations:
122
+ required: true
123
+
124
+ - type: textarea
125
+ id: logs-screenshots
126
+ attributes:
127
+ label: Logs & Screenshots
128
+ description: Include relevant logs, errors, or screenshots to help diagnose the issue.
129
+ placeholder: 'Attach logs from the browser console, Docker logs, or error messages.'
130
+ validations:
131
+ required: true
132
+
133
+ - type: textarea
134
+ id: additional-info
135
+ attributes:
136
+ label: Additional Information
137
+ description: Provide any extra details that may assist in understanding the issue.
138
+ validations:
139
+ required: false
140
+
141
+ - type: markdown
142
+ attributes:
143
+ value: |
144
+ ## Note
145
+ If the bug report is incomplete or does not follow instructions, 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.
146
+ 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,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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: npm
16
+ directory: '/'
17
+ schedule:
18
+ interval: monthly
19
+ target-branch: 'dev'
20
+
21
+ - package-ecosystem: 'github-actions'
22
+ directory: '/'
23
+ schedule:
24
+ # Check for updates to GitHub Actions every week
25
+ interval: monthly
26
+ target-branch: 'dev'
.github/pull_request_template.md ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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:** Please verify that the pull request targets the `dev` branch.
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:** Have you updated relevant documentation [Open WebUI Docs](https://github.com/open-webui/docs), or other documentation sources?
11
+ - [ ] **Dependencies:** Are there any new dependencies? Have you updated the dependency versions in the documentation?
12
+ - [ ] **Testing:** Have you written and run sufficient tests to validate the changes?
13
+ - [ ] **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?
14
+ - [ ] **Prefix:** To clearly categorize this pull request, prefix the pull request title using one of the following:
15
+ - **BREAKING CHANGE**: Significant changes that may affect compatibility
16
+ - **build**: Changes that affect the build system or external dependencies
17
+ - **ci**: Changes to our continuous integration processes or workflows
18
+ - **chore**: Refactor, cleanup, or other non-functional code changes
19
+ - **docs**: Documentation update or addition
20
+ - **feat**: Introduces a new feature or enhancement to the codebase
21
+ - **fix**: Bug fix or error correction
22
+ - **i18n**: Internationalization or localization changes
23
+ - **perf**: Performance improvement
24
+ - **refactor**: Code restructuring for better maintainability, readability, or scalability
25
+ - **style**: Changes that do not affect the meaning of the code (white space, formatting, missing semi-colons, etc.)
26
+ - **test**: Adding missing tests or correcting existing tests
27
+ - **WIP**: Work in progress, a temporary label for incomplete or ongoing work
28
+
29
+ # Changelog Entry
30
+
31
+ ### Description
32
+
33
+ - [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)]
34
+
35
+ ### Added
36
+
37
+ - [List any new features, functionalities, or additions]
38
+
39
+ ### Changed
40
+
41
+ - [List any changes, updates, refactorings, or optimizations]
42
+
43
+ ### Deprecated
44
+
45
+ - [List any deprecated functionality or features that have been removed]
46
+
47
+ ### Removed
48
+
49
+ - [List any removed features, files, or functionalities]
50
+
51
+ ### Fixed
52
+
53
+ - [List any fixes, corrections, or bug fixes]
54
+
55
+ ### Security
56
+
57
+ - [List any new or updated security-related changes, including vulnerability fixes]
58
+
59
+ ### Breaking Changes
60
+
61
+ - **BREAKING CHANGE**: [List any breaking changes affecting compatibility or functionality]
62
+
63
+ ---
64
+
65
+ ### Additional Information
66
+
67
+ - [Insert any additional context, notes, or explanations for the changes]
68
+ - [Reference any related issues, commits, or other relevant information]
69
+
70
+ ### Screenshots or Videos
71
+
72
+ - [Attach any relevant screenshots or videos demonstrating the changes]
73
+
74
+ ### Contributor License Agreement
75
+
76
+ By submitting this pull request, I confirm that I have read and fully agree to the [Contributor License Agreement (CLA)](/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@v4
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@v7
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@v7
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,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Deploy to HuggingFace Spaces
2
+
3
+ on:
4
+ # Spaces doesn't have the RAM to build the image anymore
5
+ # We wait for docker-build.yaml to be done first
6
+ workflow_call:
7
+ inputs:
8
+ image-name:
9
+ required: true
10
+ type: string
11
+
12
+ jobs:
13
+ check-secret:
14
+ runs-on: ubuntu-latest
15
+ outputs:
16
+ token-set: ${{ steps.check-key.outputs.defined }}
17
+ steps:
18
+ - id: check-key
19
+ env:
20
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
21
+ if: "${{ env.HF_TOKEN != '' }}"
22
+ run: echo "defined=true" >> $GITHUB_OUTPUT
23
+
24
+ deploy:
25
+ runs-on: ubuntu-latest
26
+ needs: [check-secret]
27
+ if: needs.check-secret.outputs.token-set == 'true'
28
+ env:
29
+ HF_TOKEN: ${{ secrets.HF_TOKEN }}
30
+ HF_USERNAME: ${{ secrets.HF_USERNAME }}
31
+ HF_SPACE_NAME: ${{ secrets.HF_SPACE_NAME }}
32
+ steps:
33
+ - name: Checkout repository
34
+ uses: actions/checkout@v4
35
+ with:
36
+ lfs: true
37
+
38
+ - name: Remove git history
39
+ run: rm -rf .git
40
+
41
+ - name: Prepend YAML front matter to README.md
42
+ run: |
43
+ cat <<EOF >README.md
44
+ ---
45
+ title: Open WebUI
46
+ emoji: 🐳
47
+ colorFrom: purple
48
+ colorTo: gray
49
+ sdk: docker
50
+ app_port: 8080
51
+ hf_oauth: true
52
+ hf_oauth_scopes:
53
+ - email
54
+ ---
55
+ $(cat README.md)
56
+ EOF
57
+
58
+ - name: Write new Dockerfile
59
+ run: |
60
+ echo "FROM ${{ inputs.image-name }}" > Dockerfile
61
+ echo "# This file is automatically generated by the deploy-to-hf-spaces.yml workflow" >> Dockerfile
62
+ echo "# HF Spaces doesn't have the RAM to build the image, so we use the pre-built image from the docker-build.yml workflow" >> Dockerfile
63
+
64
+ - name: Configure git
65
+ run: |
66
+ git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com"
67
+ git config --global user.name "github-actions[bot]"
68
+
69
+ - name: Set up Git and push to Space
70
+ run: |
71
+ git init --initial-branch=main
72
+ git lfs install
73
+ git lfs track "*.ttf"
74
+ git lfs track "*.jpg"
75
+ rm demo.gif
76
+ git add .
77
+ git commit -m "GitHub deploy: ${{ github.sha }}"
78
+ git push --force https://${HF_USERNAME}:${HF_TOKEN}@huggingface.co/spaces/${HF_USERNAME}/${HF_SPACE_NAME} main
.github/workflows/docker-build.yaml ADDED
@@ -0,0 +1,496 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ - hf-space
10
+ tags:
11
+ - v*
12
+
13
+ env:
14
+ REGISTRY: ghcr.io
15
+
16
+ jobs:
17
+ build-main-image:
18
+ runs-on: ${{ matrix.platform == 'linux/arm64' && 'ubuntu-24.04-arm' || 'ubuntu-latest' }}
19
+ permissions:
20
+ contents: read
21
+ packages: write
22
+ strategy:
23
+ fail-fast: false
24
+ matrix:
25
+ platform:
26
+ - linux/amd64
27
+ - linux/arm64
28
+
29
+ steps:
30
+ # GitHub Packages requires the entire repository name to be in lowercase
31
+ # although the repository owner has a lowercase username, this prevents some people from running actions after forking
32
+ - name: Set repository and image name to lowercase
33
+ run: |
34
+ echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
35
+ echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
36
+ env:
37
+ IMAGE_NAME: '${{ github.repository }}'
38
+
39
+ - name: Prepare
40
+ run: |
41
+ platform=${{ matrix.platform }}
42
+ echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
43
+
44
+ - name: Checkout repository
45
+ uses: actions/checkout@v4
46
+
47
+ - name: Set up QEMU
48
+ uses: docker/setup-qemu-action@v3
49
+
50
+ - name: Set up Docker Buildx
51
+ uses: docker/setup-buildx-action@v3
52
+
53
+ - name: Log in to the Container registry
54
+ uses: docker/login-action@v3
55
+ with:
56
+ registry: ${{ env.REGISTRY }}
57
+ username: ${{ github.actor }}
58
+ password: ${{ secrets.GITHUB_TOKEN }}
59
+
60
+ - name: Extract metadata for Docker images (default latest tag)
61
+ id: meta
62
+ uses: docker/metadata-action@v5
63
+ with:
64
+ images: ${{ env.FULL_IMAGE_NAME }}
65
+ tags: |
66
+ type=ref,event=branch
67
+ type=ref,event=tag
68
+ type=sha,prefix=git-
69
+ type=semver,pattern={{version}}
70
+ type=semver,pattern={{major}}.{{minor}}
71
+ flavor: |
72
+ latest=${{ github.ref == 'refs/heads/main' }}
73
+
74
+ - name: Extract metadata for Docker cache
75
+ id: cache-meta
76
+ uses: docker/metadata-action@v5
77
+ with:
78
+ images: ${{ env.FULL_IMAGE_NAME }}
79
+ tags: |
80
+ type=ref,event=branch
81
+ ${{ github.ref_type == 'tag' && 'type=raw,value=main' || '' }}
82
+ flavor: |
83
+ prefix=cache-${{ matrix.platform }}-
84
+ latest=false
85
+
86
+ - name: Build Docker image (latest)
87
+ uses: docker/build-push-action@v5
88
+ id: build
89
+ with:
90
+ context: .
91
+ push: true
92
+ platforms: ${{ matrix.platform }}
93
+ labels: ${{ steps.meta.outputs.labels }}
94
+ outputs: type=image,name=${{ env.FULL_IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
95
+ cache-from: type=registry,ref=${{ steps.cache-meta.outputs.tags }}
96
+ cache-to: type=registry,ref=${{ steps.cache-meta.outputs.tags }},mode=max
97
+ build-args: |
98
+ BUILD_HASH=${{ github.sha }}
99
+ UID=1000
100
+ GID=1000
101
+
102
+ - name: Export digest
103
+ run: |
104
+ mkdir -p /tmp/digests
105
+ digest="${{ steps.build.outputs.digest }}"
106
+ touch "/tmp/digests/${digest#sha256:}"
107
+
108
+ - name: Upload digest
109
+ uses: actions/upload-artifact@v4
110
+ with:
111
+ name: digests-main-${{ env.PLATFORM_PAIR }}
112
+ path: /tmp/digests/*
113
+ if-no-files-found: error
114
+ retention-days: 1
115
+
116
+ build-cuda-image:
117
+ runs-on: ${{ matrix.platform == 'linux/arm64' && 'ubuntu-24.04-arm' || 'ubuntu-latest' }}
118
+ permissions:
119
+ contents: read
120
+ packages: write
121
+ strategy:
122
+ fail-fast: false
123
+ matrix:
124
+ platform:
125
+ - linux/amd64
126
+ - linux/arm64
127
+
128
+ steps:
129
+ # GitHub Packages requires the entire repository name to be in lowercase
130
+ # although the repository owner has a lowercase username, this prevents some people from running actions after forking
131
+ - name: Set repository and image name to lowercase
132
+ run: |
133
+ echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
134
+ echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
135
+ env:
136
+ IMAGE_NAME: '${{ github.repository }}'
137
+
138
+ - name: Prepare
139
+ run: |
140
+ platform=${{ matrix.platform }}
141
+ echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
142
+
143
+ - name: Checkout repository
144
+ uses: actions/checkout@v4
145
+
146
+ - name: Set up QEMU
147
+ uses: docker/setup-qemu-action@v3
148
+
149
+ - name: Set up Docker Buildx
150
+ uses: docker/setup-buildx-action@v3
151
+
152
+ - name: Log in to the Container registry
153
+ uses: docker/login-action@v3
154
+ with:
155
+ registry: ${{ env.REGISTRY }}
156
+ username: ${{ github.actor }}
157
+ password: ${{ secrets.GITHUB_TOKEN }}
158
+
159
+ - name: Extract metadata for Docker images (cuda tag)
160
+ id: meta
161
+ uses: docker/metadata-action@v5
162
+ with:
163
+ images: ${{ env.FULL_IMAGE_NAME }}
164
+ tags: |
165
+ type=ref,event=branch
166
+ type=ref,event=tag
167
+ type=sha,prefix=git-
168
+ type=semver,pattern={{version}}
169
+ type=semver,pattern={{major}}.{{minor}}
170
+ type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=cuda
171
+ flavor: |
172
+ latest=${{ github.ref == 'refs/heads/main' }}
173
+ suffix=-cuda,onlatest=true
174
+
175
+ - name: Extract metadata for Docker cache
176
+ id: cache-meta
177
+ uses: docker/metadata-action@v5
178
+ with:
179
+ images: ${{ env.FULL_IMAGE_NAME }}
180
+ tags: |
181
+ type=ref,event=branch
182
+ ${{ github.ref_type == 'tag' && 'type=raw,value=main' || '' }}
183
+ flavor: |
184
+ prefix=cache-cuda-${{ matrix.platform }}-
185
+ latest=false
186
+
187
+ - name: Build Docker image (cuda)
188
+ uses: docker/build-push-action@v5
189
+ id: build
190
+ with:
191
+ context: .
192
+ push: true
193
+ platforms: ${{ matrix.platform }}
194
+ labels: ${{ steps.meta.outputs.labels }}
195
+ outputs: type=image,name=${{ env.FULL_IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
196
+ cache-from: type=registry,ref=${{ steps.cache-meta.outputs.tags }}
197
+ cache-to: type=registry,ref=${{ steps.cache-meta.outputs.tags }},mode=max
198
+ build-args: |
199
+ BUILD_HASH=${{ github.sha }}
200
+ USE_CUDA=true
201
+
202
+ - name: Export digest
203
+ run: |
204
+ mkdir -p /tmp/digests
205
+ digest="${{ steps.build.outputs.digest }}"
206
+ touch "/tmp/digests/${digest#sha256:}"
207
+
208
+ - name: Upload digest
209
+ uses: actions/upload-artifact@v4
210
+ with:
211
+ name: digests-cuda-${{ env.PLATFORM_PAIR }}
212
+ path: /tmp/digests/*
213
+ if-no-files-found: error
214
+ retention-days: 1
215
+
216
+ build-ollama-image:
217
+ runs-on: ${{ matrix.platform == 'linux/arm64' && 'ubuntu-24.04-arm' || 'ubuntu-latest' }}
218
+ permissions:
219
+ contents: read
220
+ packages: write
221
+ strategy:
222
+ fail-fast: false
223
+ matrix:
224
+ platform:
225
+ - linux/amd64
226
+ - linux/arm64
227
+
228
+ steps:
229
+ # GitHub Packages requires the entire repository name to be in lowercase
230
+ # although the repository owner has a lowercase username, this prevents some people from running actions after forking
231
+ - name: Set repository and image name to lowercase
232
+ run: |
233
+ echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
234
+ echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
235
+ env:
236
+ IMAGE_NAME: '${{ github.repository }}'
237
+
238
+ - name: Prepare
239
+ run: |
240
+ platform=${{ matrix.platform }}
241
+ echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
242
+
243
+ - name: Checkout repository
244
+ uses: actions/checkout@v4
245
+
246
+ - name: Set up QEMU
247
+ uses: docker/setup-qemu-action@v3
248
+
249
+ - name: Set up Docker Buildx
250
+ uses: docker/setup-buildx-action@v3
251
+
252
+ - name: Log in to the Container registry
253
+ uses: docker/login-action@v3
254
+ with:
255
+ registry: ${{ env.REGISTRY }}
256
+ username: ${{ github.actor }}
257
+ password: ${{ secrets.GITHUB_TOKEN }}
258
+
259
+ - name: Extract metadata for Docker images (ollama tag)
260
+ id: meta
261
+ uses: docker/metadata-action@v5
262
+ with:
263
+ images: ${{ env.FULL_IMAGE_NAME }}
264
+ tags: |
265
+ type=ref,event=branch
266
+ type=ref,event=tag
267
+ type=sha,prefix=git-
268
+ type=semver,pattern={{version}}
269
+ type=semver,pattern={{major}}.{{minor}}
270
+ type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=ollama
271
+ flavor: |
272
+ latest=${{ github.ref == 'refs/heads/main' }}
273
+ suffix=-ollama,onlatest=true
274
+
275
+ - name: Extract metadata for Docker cache
276
+ id: cache-meta
277
+ uses: docker/metadata-action@v5
278
+ with:
279
+ images: ${{ env.FULL_IMAGE_NAME }}
280
+ tags: |
281
+ type=ref,event=branch
282
+ ${{ github.ref_type == 'tag' && 'type=raw,value=main' || '' }}
283
+ flavor: |
284
+ prefix=cache-ollama-${{ matrix.platform }}-
285
+ latest=false
286
+
287
+ - name: Build Docker image (ollama)
288
+ uses: docker/build-push-action@v5
289
+ id: build
290
+ with:
291
+ context: .
292
+ push: true
293
+ platforms: ${{ matrix.platform }}
294
+ labels: ${{ steps.meta.outputs.labels }}
295
+ outputs: type=image,name=${{ env.FULL_IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
296
+ cache-from: type=registry,ref=${{ steps.cache-meta.outputs.tags }}
297
+ cache-to: type=registry,ref=${{ steps.cache-meta.outputs.tags }},mode=max
298
+ build-args: |
299
+ BUILD_HASH=${{ github.sha }}
300
+ USE_OLLAMA=true
301
+
302
+ - name: Export digest
303
+ run: |
304
+ mkdir -p /tmp/digests
305
+ digest="${{ steps.build.outputs.digest }}"
306
+ touch "/tmp/digests/${digest#sha256:}"
307
+
308
+ - name: Upload digest
309
+ uses: actions/upload-artifact@v4
310
+ with:
311
+ name: digests-ollama-${{ env.PLATFORM_PAIR }}
312
+ path: /tmp/digests/*
313
+ if-no-files-found: error
314
+ retention-days: 1
315
+
316
+ merge-main-images:
317
+ runs-on: ubuntu-latest
318
+ needs: [build-main-image]
319
+ outputs:
320
+ image_tag: ${{ steps.output-image-name.outputs.image_tag }}
321
+ steps:
322
+ # GitHub Packages requires the entire repository name to be in lowercase
323
+ # although the repository owner has a lowercase username, this prevents some people from running actions after forking
324
+ - name: Set repository and image name to lowercase
325
+ run: |
326
+ echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
327
+ echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
328
+ env:
329
+ IMAGE_NAME: '${{ github.repository }}'
330
+
331
+ - name: Download digests
332
+ uses: actions/download-artifact@v4
333
+ with:
334
+ pattern: digests-main-*
335
+ path: /tmp/digests
336
+ merge-multiple: true
337
+
338
+ - name: Set up Docker Buildx
339
+ uses: docker/setup-buildx-action@v3
340
+
341
+ - name: Log in to the Container registry
342
+ uses: docker/login-action@v3
343
+ with:
344
+ registry: ${{ env.REGISTRY }}
345
+ username: ${{ github.actor }}
346
+ password: ${{ secrets.GITHUB_TOKEN }}
347
+
348
+ - name: Extract metadata for Docker images (default latest tag)
349
+ id: meta
350
+ uses: docker/metadata-action@v5
351
+ with:
352
+ images: ${{ env.FULL_IMAGE_NAME }}
353
+ tags: |
354
+ type=ref,event=branch
355
+ type=ref,event=tag
356
+ type=sha,prefix=git-
357
+ type=semver,pattern={{version}}
358
+ type=semver,pattern={{major}}.{{minor}}
359
+ flavor: |
360
+ latest=${{ github.ref == 'refs/heads/main' }}
361
+
362
+ - name: Create manifest list and push
363
+ working-directory: /tmp/digests
364
+ run: |
365
+ docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
366
+ $(printf '${{ env.FULL_IMAGE_NAME }}@sha256:%s ' *)
367
+
368
+ - name: Inspect image
369
+ run: |
370
+ docker buildx imagetools inspect ${{ env.FULL_IMAGE_NAME }}:${{ steps.meta.outputs.version }}
371
+
372
+ - name: Output image name
373
+ id: output-image-name
374
+ run: |
375
+ export IMAGE_SHA=$(docker buildx imagetools inspect "${{ env.FULL_IMAGE_NAME }}:${{ steps.meta.outputs.version }}" --format "{{json .}}" | jq -r '.manifest.digest')
376
+ export IMAGE_TAG="${{ env.FULL_IMAGE_NAME }}@$IMAGE_SHA"
377
+ echo "image_tag=$IMAGE_TAG" >> $GITHUB_OUTPUT
378
+
379
+ trigger-hf-space-deploy:
380
+ needs: [merge-main-images]
381
+ uses: ./.github/workflows/deploy-to-hf-spaces.yml
382
+ with:
383
+ image-name: ${{ needs.merge-main-images.outputs.image_tag }}
384
+ secrets: inherit
385
+
386
+ merge-cuda-images:
387
+ runs-on: ubuntu-latest
388
+ needs: [build-cuda-image]
389
+ steps:
390
+ # GitHub Packages requires the entire repository name to be in lowercase
391
+ # although the repository owner has a lowercase username, this prevents some people from running actions after forking
392
+ - name: Set repository and image name to lowercase
393
+ run: |
394
+ echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
395
+ echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
396
+ env:
397
+ IMAGE_NAME: '${{ github.repository }}'
398
+
399
+ - name: Download digests
400
+ uses: actions/download-artifact@v4
401
+ with:
402
+ pattern: digests-cuda-*
403
+ path: /tmp/digests
404
+ merge-multiple: true
405
+
406
+ - name: Set up Docker Buildx
407
+ uses: docker/setup-buildx-action@v3
408
+
409
+ - name: Log in to the Container registry
410
+ uses: docker/login-action@v3
411
+ with:
412
+ registry: ${{ env.REGISTRY }}
413
+ username: ${{ github.actor }}
414
+ password: ${{ secrets.GITHUB_TOKEN }}
415
+
416
+ - name: Extract metadata for Docker images (default latest tag)
417
+ id: meta
418
+ uses: docker/metadata-action@v5
419
+ with:
420
+ images: ${{ env.FULL_IMAGE_NAME }}
421
+ tags: |
422
+ type=ref,event=branch
423
+ type=ref,event=tag
424
+ type=sha,prefix=git-
425
+ type=semver,pattern={{version}}
426
+ type=semver,pattern={{major}}.{{minor}}
427
+ type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=cuda
428
+ flavor: |
429
+ latest=${{ github.ref == 'refs/heads/main' }}
430
+ suffix=-cuda,onlatest=true
431
+
432
+ - name: Create manifest list and push
433
+ working-directory: /tmp/digests
434
+ run: |
435
+ docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
436
+ $(printf '${{ env.FULL_IMAGE_NAME }}@sha256:%s ' *)
437
+
438
+ - name: Inspect image
439
+ run: |
440
+ docker buildx imagetools inspect ${{ env.FULL_IMAGE_NAME }}:${{ steps.meta.outputs.version }}
441
+
442
+ merge-ollama-images:
443
+ runs-on: ubuntu-latest
444
+ needs: [build-ollama-image]
445
+ steps:
446
+ # GitHub Packages requires the entire repository name to be in lowercase
447
+ # although the repository owner has a lowercase username, this prevents some people from running actions after forking
448
+ - name: Set repository and image name to lowercase
449
+ run: |
450
+ echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
451
+ echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
452
+ env:
453
+ IMAGE_NAME: '${{ github.repository }}'
454
+
455
+ - name: Download digests
456
+ uses: actions/download-artifact@v4
457
+ with:
458
+ pattern: digests-ollama-*
459
+ path: /tmp/digests
460
+ merge-multiple: true
461
+
462
+ - name: Set up Docker Buildx
463
+ uses: docker/setup-buildx-action@v3
464
+
465
+ - name: Log in to the Container registry
466
+ uses: docker/login-action@v3
467
+ with:
468
+ registry: ${{ env.REGISTRY }}
469
+ username: ${{ github.actor }}
470
+ password: ${{ secrets.GITHUB_TOKEN }}
471
+
472
+ - name: Extract metadata for Docker images (default ollama tag)
473
+ id: meta
474
+ uses: docker/metadata-action@v5
475
+ with:
476
+ images: ${{ env.FULL_IMAGE_NAME }}
477
+ tags: |
478
+ type=ref,event=branch
479
+ type=ref,event=tag
480
+ type=sha,prefix=git-
481
+ type=semver,pattern={{version}}
482
+ type=semver,pattern={{major}}.{{minor}}
483
+ type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=ollama
484
+ flavor: |
485
+ latest=${{ github.ref == 'refs/heads/main' }}
486
+ suffix=-ollama,onlatest=true
487
+
488
+ - name: Create manifest list and push
489
+ working-directory: /tmp/digests
490
+ run: |
491
+ docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
492
+ $(printf '${{ env.FULL_IMAGE_NAME }}@sha256:%s ' *)
493
+
494
+ - name: Inspect image
495
+ run: |
496
+ 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@v4
34
+
35
+ - name: Set up Python
36
+ uses: actions/setup-python@v5
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@v4
28
+
29
+ - name: Setup Node.js
30
+ uses: actions/setup-node@v4
31
+ with:
32
+ node-version: '22'
33
+
34
+ - name: Install Dependencies
35
+ run: npm install
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@v4
55
+
56
+ - name: Setup Node.js
57
+ uses: actions/setup-node@v4
58
+ with:
59
+ node-version: '22'
60
+
61
+ - name: Install Dependencies
62
+ run: npm ci
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,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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@v4
20
+ - uses: actions/setup-node@v4
21
+ with:
22
+ node-version: 22
23
+ - uses: actions/setup-python@v5
24
+ with:
25
+ python-version: 3.11
26
+ - name: Build
27
+ run: |
28
+ python -m pip install --upgrade pip
29
+ pip install build
30
+ python -m build .
31
+ - name: Publish package distributions to PyPI
32
+ uses: pypa/gh-action-pypi-publish@release/v1
.github/workflows/sync-hf-spaces-with-dev.yml ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Sync hf-spaces with dev
2
+
3
+ on:
4
+ push:
5
+ branches:
6
+ - dev
7
+ - hf-spaces
8
+ schedule:
9
+ - cron: '0 0 * * *'
10
+ workflow_dispatch:
11
+
12
+ jobs:
13
+ sync:
14
+ runs-on: ubuntu-latest
15
+ permissions:
16
+ contents: write
17
+ steps:
18
+ - name: Checkout repository
19
+ uses: actions/checkout@v4
20
+ with:
21
+ fetch-depth: 0
22
+
23
+ - name: Sync with dev
24
+ run: |
25
+ git checkout dev
26
+ git fetch origin
27
+ git checkout hf-space
28
+ git pull
29
+ git merge origin/dev
30
+ git push origin hf-space
.gitignore ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .DS_Store
2
+ node_modules
3
+ /build
4
+ /.svelte-kit
5
+ /package
6
+ .env
7
+ .env.*
8
+ !.env.example
9
+ vite.config.js.timestamp-*
10
+ vite.config.ts.timestamp-*
11
+ # Byte-compiled / optimized / DLL files
12
+ __pycache__/
13
+ *.py[cod]
14
+ *$py.class
15
+
16
+ # C extensions
17
+ *.so
18
+
19
+ # Pyodide distribution
20
+ static/pyodide/*
21
+ !static/pyodide/pyodide-lock.json
22
+
23
+ # Distribution / packaging
24
+ .Python
25
+ build/
26
+ develop-eggs/
27
+ dist/
28
+ downloads/
29
+ eggs/
30
+ .eggs/
31
+ lib64/
32
+ parts/
33
+ sdist/
34
+ var/
35
+ wheels/
36
+ share/python-wheels/
37
+ *.egg-info/
38
+ .installed.cfg
39
+ *.egg
40
+ MANIFEST
41
+
42
+ # PyInstaller
43
+ # Usually these files are written by a python script from a template
44
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
45
+ *.manifest
46
+ *.spec
47
+
48
+ # Installer logs
49
+ pip-log.txt
50
+ pip-delete-this-directory.txt
51
+
52
+ # Unit test / coverage reports
53
+ htmlcov/
54
+ .tox/
55
+ .nox/
56
+ .coverage
57
+ .coverage.*
58
+ .cache
59
+ nosetests.xml
60
+ coverage.xml
61
+ *.cover
62
+ *.py,cover
63
+ .hypothesis/
64
+ .pytest_cache/
65
+ cover/
66
+
67
+ # Translations
68
+ *.mo
69
+ *.pot
70
+
71
+ # Django stuff:
72
+ *.log
73
+ local_settings.py
74
+ db.sqlite3
75
+ db.sqlite3-journal
76
+
77
+ # Flask stuff:
78
+ instance/
79
+ .webassets-cache
80
+
81
+ # Scrapy stuff:
82
+ .scrapy
83
+
84
+ # Sphinx documentation
85
+ docs/_build/
86
+
87
+ # PyBuilder
88
+ .pybuilder/
89
+ target/
90
+
91
+ # Jupyter Notebook
92
+ .ipynb_checkpoints
93
+
94
+ # IPython
95
+ profile_default/
96
+ ipython_config.py
97
+
98
+ # pyenv
99
+ # For a library or package, you might want to ignore these files since the code is
100
+ # intended to run in multiple environments; otherwise, check them in:
101
+ # .python-version
102
+
103
+ # pipenv
104
+ # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
105
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
106
+ # having no cross-platform support, pipenv may install dependencies that don't work, or not
107
+ # install all needed dependencies.
108
+ #Pipfile.lock
109
+
110
+ # poetry
111
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
112
+ # This is especially recommended for binary packages to ensure reproducibility, and is more
113
+ # commonly ignored for libraries.
114
+ # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
115
+ #poetry.lock
116
+
117
+ # pdm
118
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
119
+ #pdm.lock
120
+ # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
121
+ # in version control.
122
+ # https://pdm.fming.dev/#use-with-ide
123
+ .pdm.toml
124
+
125
+ # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
126
+ __pypackages__/
127
+
128
+ # Celery stuff
129
+ celerybeat-schedule
130
+ celerybeat.pid
131
+
132
+ # SageMath parsed files
133
+ *.sage.py
134
+
135
+ # Environments
136
+ .env
137
+ .venv
138
+ env/
139
+ venv/
140
+ ENV/
141
+ env.bak/
142
+ venv.bak/
143
+
144
+ # Spyder project settings
145
+ .spyderproject
146
+ .spyproject
147
+
148
+ # Rope project settings
149
+ .ropeproject
150
+
151
+ # mkdocs documentation
152
+ /site
153
+
154
+ # mypy
155
+ .mypy_cache/
156
+ .dmypy.json
157
+ dmypy.json
158
+
159
+ # Pyre type checker
160
+ .pyre/
161
+
162
+ # pytype static type analyzer
163
+ .pytype/
164
+
165
+ # Cython debug symbols
166
+ cython_debug/
167
+
168
+ # PyCharm
169
+ # JetBrains specific template is maintained in a separate JetBrains.gitignore that can
170
+ # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
171
+ # and can be added to the global gitignore or merged into this file. For a more nuclear
172
+ # option (not recommended) you can uncomment the following to ignore the entire idea folder.
173
+ .idea/
174
+
175
+ # Logs
176
+ logs
177
+ *.log
178
+ npm-debug.log*
179
+ yarn-debug.log*
180
+ yarn-error.log*
181
+ lerna-debug.log*
182
+ .pnpm-debug.log*
183
+
184
+ # Diagnostic reports (https://nodejs.org/api/report.html)
185
+ report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
186
+
187
+ # Runtime data
188
+ pids
189
+ *.pid
190
+ *.seed
191
+ *.pid.lock
192
+
193
+ # Directory for instrumented libs generated by jscoverage/JSCover
194
+ lib-cov
195
+
196
+ # Coverage directory used by tools like istanbul
197
+ coverage
198
+ *.lcov
199
+
200
+ # nyc test coverage
201
+ .nyc_output
202
+
203
+ # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
204
+ .grunt
205
+
206
+ # Bower dependency directory (https://bower.io/)
207
+ bower_components
208
+
209
+ # node-waf configuration
210
+ .lock-wscript
211
+
212
+ # Compiled binary addons (https://nodejs.org/api/addons.html)
213
+ build/Release
214
+
215
+ # Dependency directories
216
+ node_modules/
217
+ jspm_packages/
218
+
219
+ # Snowpack dependency directory (https://snowpack.dev/)
220
+ web_modules/
221
+
222
+ # TypeScript cache
223
+ *.tsbuildinfo
224
+
225
+ # Optional npm cache directory
226
+ .npm
227
+
228
+ # Optional eslint cache
229
+ .eslintcache
230
+
231
+ # Optional stylelint cache
232
+ .stylelintcache
233
+
234
+ # Microbundle cache
235
+ .rpt2_cache/
236
+ .rts2_cache_cjs/
237
+ .rts2_cache_es/
238
+ .rts2_cache_umd/
239
+
240
+ # Optional REPL history
241
+ .node_repl_history
242
+
243
+ # Output of 'npm pack'
244
+ *.tgz
245
+
246
+ # Yarn Integrity file
247
+ .yarn-integrity
248
+
249
+ # dotenv environment variable files
250
+ .env
251
+ .env.development.local
252
+ .env.test.local
253
+ .env.production.local
254
+ .env.local
255
+
256
+ # parcel-bundler cache (https://parceljs.org/)
257
+ .cache
258
+ .parcel-cache
259
+
260
+ # Next.js build output
261
+ .next
262
+ out
263
+
264
+ # Nuxt.js build / generate output
265
+ .nuxt
266
+ dist
267
+
268
+ # Gatsby files
269
+ .cache/
270
+ # Comment in the public line in if your project uses Gatsby and not Next.js
271
+ # https://nextjs.org/blog/next-9-1#public-directory-support
272
+ # public
273
+
274
+ # vuepress build output
275
+ .vuepress/dist
276
+
277
+ # vuepress v2.x temp and cache directory
278
+ .temp
279
+ .cache
280
+
281
+ # Docusaurus cache and generated files
282
+ .docusaurus
283
+
284
+ # Serverless directories
285
+ .serverless/
286
+
287
+ # FuseBox cache
288
+ .fusebox/
289
+
290
+ # DynamoDB Local files
291
+ .dynamodb/
292
+
293
+ # TernJS port file
294
+ .tern-port
295
+
296
+ # Stores VSCode versions used for testing VSCode extensions
297
+ .vscode-test
298
+
299
+ # yarn v2
300
+ .yarn/cache
301
+ .yarn/unplugged
302
+ .yarn/build-state.yml
303
+ .yarn/install-state.gz
304
+ .pnp.*
305
+
306
+ # cypress artifacts
307
+ cypress/videos
308
+ cypress/screenshots
309
+ .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,9 @@
 
 
 
 
 
 
 
 
 
 
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
+ }
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 open-source 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
+ Open-source 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
+ Open-source 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._**
Caddyfile.localhost ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Run with
2
+ # caddy run --envfile ./example.env --config ./Caddyfile.localhost
3
+ #
4
+ # This is configured for
5
+ # - Automatic HTTPS (even for localhost)
6
+ # - Reverse Proxying to Ollama API Base URL (http://localhost:11434/api)
7
+ # - CORS
8
+ # - HTTP Basic Auth API Tokens (uncomment basicauth section)
9
+
10
+
11
+ # CORS Preflight (OPTIONS) + Request (GET, POST, PATCH, PUT, DELETE)
12
+ (cors-api) {
13
+ @match-cors-api-preflight method OPTIONS
14
+ handle @match-cors-api-preflight {
15
+ header {
16
+ Access-Control-Allow-Origin "{http.request.header.origin}"
17
+ Access-Control-Allow-Methods "GET, POST, PUT, PATCH, DELETE, OPTIONS"
18
+ Access-Control-Allow-Headers "Origin, Accept, Authorization, Content-Type, X-Requested-With"
19
+ Access-Control-Allow-Credentials "true"
20
+ Access-Control-Max-Age "3600"
21
+ defer
22
+ }
23
+ respond "" 204
24
+ }
25
+
26
+ @match-cors-api-request {
27
+ not {
28
+ header Origin "{http.request.scheme}://{http.request.host}"
29
+ }
30
+ header Origin "{http.request.header.origin}"
31
+ }
32
+ handle @match-cors-api-request {
33
+ header {
34
+ Access-Control-Allow-Origin "{http.request.header.origin}"
35
+ Access-Control-Allow-Methods "GET, POST, PUT, PATCH, DELETE, OPTIONS"
36
+ Access-Control-Allow-Headers "Origin, Accept, Authorization, Content-Type, X-Requested-With"
37
+ Access-Control-Allow-Credentials "true"
38
+ Access-Control-Max-Age "3600"
39
+ defer
40
+ }
41
+ }
42
+ }
43
+
44
+ # replace localhost with example.com or whatever
45
+ localhost {
46
+ ## HTTP Basic Auth
47
+ ## (uncomment to enable)
48
+ # basicauth {
49
+ # # see .example.env for how to generate tokens
50
+ # {env.OLLAMA_API_ID} {env.OLLAMA_API_TOKEN_DIGEST}
51
+ # }
52
+
53
+ handle /api/* {
54
+ # Comment to disable CORS
55
+ import cors-api
56
+
57
+ reverse_proxy localhost:11434
58
+ }
59
+
60
+ # Same-Origin Static Web Server
61
+ file_server {
62
+ root ./build/
63
+ }
64
+ }
Dockerfile ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ FROM ghcr.io/cheahjs/open-webui-fork@sha256:0cfc250b8a6bd9d41977255e479486df7fd98bd876a023bbd94d7c1fa3c56670
2
+ # This file is automatically generated by the deploy-to-hf-spaces.yml workflow
3
+ # HF Spaces doesn't have the RAM to build the image, so we use the pre-built image from the docker-build.yml workflow
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.
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,247 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Open WebUI
3
+ emoji: 🐳
4
+ colorFrom: purple
5
+ colorTo: gray
6
+ sdk: docker
7
+ app_port: 8080
8
+ hf_oauth: true
9
+ hf_oauth_scopes:
10
+ - email
11
+ ---
12
+ ---
13
+ title: Open WebUI
14
+ emoji: 🐳
15
+ colorFrom: purple
16
+ colorTo: gray
17
+ sdk: docker
18
+ app_port: 8080
19
+ ---
20
+
21
+ # Open WebUI 👋
22
+
23
+ ![GitHub stars](https://img.shields.io/github/stars/open-webui/open-webui?style=social)
24
+ ![GitHub forks](https://img.shields.io/github/forks/open-webui/open-webui?style=social)
25
+ ![GitHub watchers](https://img.shields.io/github/watchers/open-webui/open-webui?style=social)
26
+ ![GitHub repo size](https://img.shields.io/github/repo-size/open-webui/open-webui)
27
+ ![GitHub language count](https://img.shields.io/github/languages/count/open-webui/open-webui)
28
+ ![GitHub top language](https://img.shields.io/github/languages/top/open-webui/open-webui)
29
+ ![GitHub last commit](https://img.shields.io/github/last-commit/open-webui/open-webui?color=red)
30
+ [![Discord](https://img.shields.io/badge/Discord-Open_WebUI-blue?logo=discord&logoColor=white)](https://discord.gg/5rJgQTnV4s)
31
+ [![](https://img.shields.io/static/v1?label=Sponsor&message=%E2%9D%A4&logo=GitHub&color=%23fe8e86)](https://github.com/sponsors/tjbck)
32
+
33
+ **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**.
34
+
35
+ ![Open WebUI Demo](./demo.gif)
36
+
37
+ > [!TIP]
38
+ > **Looking for an [Enterprise Plan](https://docs.openwebui.com/enterprise)?** – **[Speak with Our Sales Team Today!](mailto:sales@openwebui.com)**
39
+ >
40
+ > Get **enhanced capabilities**, including **custom theming and branding**, **Service Level Agreement (SLA) support**, **Long-Term Support (LTS) versions**, and **more!**
41
+
42
+ For more information, be sure to check out our [Open WebUI Documentation](https://docs.openwebui.com/).
43
+
44
+ ## Key Features of Open WebUI ⭐
45
+
46
+ - 🚀 **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.
47
+
48
+ - 🤝 **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**.
49
+
50
+ - 🛡️ **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.
51
+
52
+ - 📱 **Responsive Design**: Enjoy a seamless experience across Desktop PC, Laptop, and Mobile devices.
53
+
54
+ - 📱 **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.
55
+
56
+ - ✒️🔢 **Full Markdown and LaTeX Support**: Elevate your LLM experience with comprehensive Markdown and LaTeX capabilities for enriched interaction.
57
+
58
+ - 🎤📹 **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.
59
+
60
+ - 🛠️ **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.
61
+
62
+ - 🐍 **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.
63
+
64
+ - 📚 **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.
65
+
66
+ - 🔍 **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.
67
+
68
+ - 🌐 **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.
69
+
70
+ - 🎨 **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.
71
+
72
+ - ⚙️ **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.
73
+
74
+ - 🔐 **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.
75
+
76
+ - 🌐🌍 **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!
77
+
78
+ - 🧩 **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.
79
+
80
+ - 🌟 **Continuous Updates**: We are committed to improving Open WebUI with regular updates, fixes, and new features.
81
+
82
+ Want to learn more about Open WebUI's features? Check out our [Open WebUI documentation](https://docs.openwebui.com/features) for a comprehensive overview!
83
+
84
+ ## 🔗 Also Check Out Open WebUI Community!
85
+
86
+ Don't forget to explore our sibling project, [Open WebUI Community](https://openwebui.com/), where you can discover, download, and explore customized Modelfiles. Open WebUI Community offers a wide range of exciting possibilities for enhancing your chat interactions with Open WebUI! 🚀
87
+
88
+ ## How to Install 🚀
89
+
90
+ ### Installation via Python pip 🐍
91
+
92
+ Open WebUI can be installed using pip, the Python package installer. Before proceeding, ensure you're using **Python 3.11** to avoid compatibility issues.
93
+
94
+ 1. **Install Open WebUI**:
95
+ Open your terminal and run the following command to install Open WebUI:
96
+
97
+ ```bash
98
+ pip install open-webui
99
+ ```
100
+
101
+ 2. **Running Open WebUI**:
102
+ After installation, you can start Open WebUI by executing:
103
+
104
+ ```bash
105
+ open-webui serve
106
+ ```
107
+
108
+ This will start the Open WebUI server, which you can access at [http://localhost:8080](http://localhost:8080)
109
+
110
+ ### Quick Start with Docker 🐳
111
+
112
+ > [!NOTE]
113
+ > 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.
114
+
115
+ > [!WARNING]
116
+ > 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.
117
+
118
+ > [!TIP]
119
+ > 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.
120
+
121
+ ### Installation with Default Configuration
122
+
123
+ - **If Ollama is on your computer**, use this command:
124
+
125
+ ```bash
126
+ 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
127
+ ```
128
+
129
+ - **If Ollama is on a Different Server**, use this command:
130
+
131
+ To connect to Ollama on another server, change the `OLLAMA_BASE_URL` to the server's URL:
132
+
133
+ ```bash
134
+ 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
135
+ ```
136
+
137
+ - **To run Open WebUI with Nvidia GPU support**, use this command:
138
+
139
+ ```bash
140
+ 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
141
+ ```
142
+
143
+ ### Installation for OpenAI API Usage Only
144
+
145
+ - **If you're only using OpenAI API**, use this command:
146
+
147
+ ```bash
148
+ 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
149
+ ```
150
+
151
+ ### Installing Open WebUI with Bundled Ollama Support
152
+
153
+ 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:
154
+
155
+ - **With GPU Support**:
156
+ Utilize GPU resources by running the following command:
157
+
158
+ ```bash
159
+ 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
160
+ ```
161
+
162
+ - **For CPU Only**:
163
+ If you're not using a GPU, use this command instead:
164
+
165
+ ```bash
166
+ 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
167
+ ```
168
+
169
+ 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.
170
+
171
+ After installation, you can access Open WebUI at [http://localhost:3000](http://localhost:3000). Enjoy! 😄
172
+
173
+ ### Other Installation Methods
174
+
175
+ 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.
176
+
177
+ ### Troubleshooting
178
+
179
+ 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).
180
+
181
+ #### Open WebUI: Server Connection Error
182
+
183
+ 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`.
184
+
185
+ **Example Docker Command**:
186
+
187
+ ```bash
188
+ 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
189
+ ```
190
+
191
+ ### Keeping Your Docker Installation Up-to-Date
192
+
193
+ In case you want to update your local Docker installation to the latest version, you can do it with [Watchtower](https://containrrr.dev/watchtower/):
194
+
195
+ ```bash
196
+ docker run --rm --volume /var/run/docker.sock:/var/run/docker.sock containrrr/watchtower --run-once open-webui
197
+ ```
198
+
199
+ In the last part of the command, replace `open-webui` with your container name if it is different.
200
+
201
+ Check our Updating Guide available in our [Open WebUI Documentation](https://docs.openwebui.com/getting-started/updating).
202
+
203
+ ### Using the Dev Branch 🌙
204
+
205
+ > [!WARNING]
206
+ > The `:dev` branch contains the latest unstable features and changes. Use it at your own risk as it may have bugs or incomplete features.
207
+
208
+ 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:
209
+
210
+ ```bash
211
+ 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
212
+ ```
213
+
214
+ ### Offline Mode
215
+
216
+ 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.
217
+
218
+ ```bash
219
+ export HF_HUB_OFFLINE=1
220
+ ```
221
+
222
+ ## What's Next? 🌟
223
+
224
+ Discover upcoming features on our roadmap in the [Open WebUI Documentation](https://docs.openwebui.com/roadmap/).
225
+
226
+ ## License 📜
227
+
228
+ This project is licensed under the [Open WebUI License](LICENSE), a revised BSD-3-Clause license. You receive all the same rights as the classic BSD-3 license: you can use, modify, and distribute the software, including in proprietary and commercial products, with minimal restrictions. The only additional requirement is to preserve the "Open WebUI" branding, as detailed in the LICENSE file. For full terms, see the [LICENSE](LICENSE) document. 📄
229
+
230
+ ## Support 💬
231
+
232
+ If you have any questions, suggestions, or need assistance, please open an issue or join our
233
+ [Open WebUI Discord community](https://discord.gg/5rJgQTnV4s) to connect with us! 🤝
234
+
235
+ ## Star History
236
+
237
+ <a href="https://star-history.com/#open-webui/open-webui&Date">
238
+ <picture>
239
+ <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date&theme=dark" />
240
+ <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
241
+ <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
242
+ </picture>
243
+ </a>
244
+
245
+ ---
246
+
247
+ 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,2 @@
 
 
 
1
+ PORT="${PORT:-8080}"
2
+ 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
@@ -0,0 +1,2762 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ import os
4
+ import shutil
5
+ import base64
6
+ import redis
7
+
8
+ from datetime import datetime
9
+ from pathlib import Path
10
+ from typing import Generic, Optional, TypeVar
11
+ from urllib.parse import urlparse
12
+
13
+ import requests
14
+ from pydantic import BaseModel
15
+ from sqlalchemy import JSON, Column, DateTime, Integer, func
16
+
17
+ from open_webui.env import (
18
+ DATA_DIR,
19
+ DATABASE_URL,
20
+ ENV,
21
+ REDIS_URL,
22
+ REDIS_SENTINEL_HOSTS,
23
+ REDIS_SENTINEL_PORT,
24
+ FRONTEND_BUILD_DIR,
25
+ OFFLINE_MODE,
26
+ OPEN_WEBUI_DIR,
27
+ WEBUI_AUTH,
28
+ WEBUI_FAVICON_URL,
29
+ WEBUI_NAME,
30
+ log,
31
+ )
32
+ from open_webui.internal.db import Base, get_db
33
+ from open_webui.utils.redis import get_redis_connection
34
+
35
+
36
+ class EndpointFilter(logging.Filter):
37
+ def filter(self, record: logging.LogRecord) -> bool:
38
+ return record.getMessage().find("/health") == -1
39
+
40
+
41
+ # Filter out /endpoint
42
+ logging.getLogger("uvicorn.access").addFilter(EndpointFilter())
43
+
44
+ ####################################
45
+ # Config helpers
46
+ ####################################
47
+
48
+
49
+ # Function to run the alembic migrations
50
+ def run_migrations():
51
+ log.info("Running migrations")
52
+ try:
53
+ from alembic import command
54
+ from alembic.config import Config
55
+
56
+ alembic_cfg = Config(OPEN_WEBUI_DIR / "alembic.ini")
57
+
58
+ # Set the script location dynamically
59
+ migrations_path = OPEN_WEBUI_DIR / "migrations"
60
+ alembic_cfg.set_main_option("script_location", str(migrations_path))
61
+
62
+ command.upgrade(alembic_cfg, "head")
63
+ except Exception as e:
64
+ log.exception(f"Error running migrations: {e}")
65
+
66
+
67
+ run_migrations()
68
+
69
+
70
+ class Config(Base):
71
+ __tablename__ = "config"
72
+
73
+ id = Column(Integer, primary_key=True)
74
+ data = Column(JSON, nullable=False)
75
+ version = Column(Integer, nullable=False, default=0)
76
+ created_at = Column(DateTime, nullable=False, server_default=func.now())
77
+ updated_at = Column(DateTime, nullable=True, onupdate=func.now())
78
+
79
+
80
+ def load_json_config():
81
+ with open(f"{DATA_DIR}/config.json", "r") as file:
82
+ return json.load(file)
83
+
84
+
85
+ def save_to_db(data):
86
+ with get_db() as db:
87
+ existing_config = db.query(Config).first()
88
+ if not existing_config:
89
+ new_config = Config(data=data, version=0)
90
+ db.add(new_config)
91
+ else:
92
+ existing_config.data = data
93
+ existing_config.updated_at = datetime.now()
94
+ db.add(existing_config)
95
+ db.commit()
96
+
97
+
98
+ def reset_config():
99
+ with get_db() as db:
100
+ db.query(Config).delete()
101
+ db.commit()
102
+
103
+
104
+ # When initializing, check if config.json exists and migrate it to the database
105
+ if os.path.exists(f"{DATA_DIR}/config.json"):
106
+ data = load_json_config()
107
+ save_to_db(data)
108
+ os.rename(f"{DATA_DIR}/config.json", f"{DATA_DIR}/old_config.json")
109
+
110
+ DEFAULT_CONFIG = {
111
+ "version": 0,
112
+ "ui": {
113
+ "default_locale": "",
114
+ "prompt_suggestions": [
115
+ {
116
+ "title": [
117
+ "Help me study",
118
+ "vocabulary for a college entrance exam",
119
+ ],
120
+ "content": "Help me study vocabulary: write a sentence for me to fill in the blank, and I'll try to pick the correct option.",
121
+ },
122
+ {
123
+ "title": [
124
+ "Give me ideas",
125
+ "for what to do with my kids' art",
126
+ ],
127
+ "content": "What are 5 creative things I could do with my kids' art? I don't want to throw them away, but it's also so much clutter.",
128
+ },
129
+ {
130
+ "title": ["Tell me a fun fact", "about the Roman Empire"],
131
+ "content": "Tell me a random fun fact about the Roman Empire",
132
+ },
133
+ {
134
+ "title": [
135
+ "Show me a code snippet",
136
+ "of a website's sticky header",
137
+ ],
138
+ "content": "Show me a code snippet of a website's sticky header in CSS and JavaScript.",
139
+ },
140
+ {
141
+ "title": [
142
+ "Explain options trading",
143
+ "if I'm familiar with buying and selling stocks",
144
+ ],
145
+ "content": "Explain options trading in simple terms if I'm familiar with buying and selling stocks.",
146
+ },
147
+ {
148
+ "title": ["Overcome procrastination", "give me tips"],
149
+ "content": "Could you start by asking me about instances when I procrastinate the most and then give me some suggestions to overcome it?",
150
+ },
151
+ {
152
+ "title": [
153
+ "Grammar check",
154
+ "rewrite it for better readability ",
155
+ ],
156
+ "content": 'Check the following sentence for grammar and clarity: "[sentence]". Rewrite it for better readability while maintaining its original meaning.',
157
+ },
158
+ ],
159
+ },
160
+ }
161
+
162
+
163
+ def get_config():
164
+ with get_db() as db:
165
+ config_entry = db.query(Config).order_by(Config.id.desc()).first()
166
+ return config_entry.data if config_entry else DEFAULT_CONFIG
167
+
168
+
169
+ CONFIG_DATA = get_config()
170
+
171
+
172
+ def get_config_value(config_path: str):
173
+ path_parts = config_path.split(".")
174
+ cur_config = CONFIG_DATA
175
+ for key in path_parts:
176
+ if key in cur_config:
177
+ cur_config = cur_config[key]
178
+ else:
179
+ return None
180
+ return cur_config
181
+
182
+
183
+ PERSISTENT_CONFIG_REGISTRY = []
184
+
185
+
186
+ def save_config(config):
187
+ global CONFIG_DATA
188
+ global PERSISTENT_CONFIG_REGISTRY
189
+ try:
190
+ save_to_db(config)
191
+ CONFIG_DATA = config
192
+
193
+ # Trigger updates on all registered PersistentConfig entries
194
+ for config_item in PERSISTENT_CONFIG_REGISTRY:
195
+ config_item.update()
196
+ except Exception as e:
197
+ log.exception(e)
198
+ return False
199
+ return True
200
+
201
+
202
+ T = TypeVar("T")
203
+
204
+ ENABLE_PERSISTENT_CONFIG = (
205
+ os.environ.get("ENABLE_PERSISTENT_CONFIG", "True").lower() == "true"
206
+ )
207
+
208
+
209
+ class PersistentConfig(Generic[T]):
210
+ def __init__(self, env_name: str, config_path: str, env_value: T):
211
+ self.env_name = env_name
212
+ self.config_path = config_path
213
+ self.env_value = env_value
214
+ self.config_value = get_config_value(config_path)
215
+ if self.config_value is not None and ENABLE_PERSISTENT_CONFIG:
216
+ log.info(f"'{env_name}' loaded from the latest database entry")
217
+ self.value = self.config_value
218
+ else:
219
+ self.value = env_value
220
+
221
+ PERSISTENT_CONFIG_REGISTRY.append(self)
222
+
223
+ def __str__(self):
224
+ return str(self.value)
225
+
226
+ @property
227
+ def __dict__(self):
228
+ raise TypeError(
229
+ "PersistentConfig object cannot be converted to dict, use config_get or .value instead."
230
+ )
231
+
232
+ def __getattribute__(self, item):
233
+ if item == "__dict__":
234
+ raise TypeError(
235
+ "PersistentConfig object cannot be converted to dict, use config_get or .value instead."
236
+ )
237
+ return super().__getattribute__(item)
238
+
239
+ def update(self):
240
+ new_value = get_config_value(self.config_path)
241
+ if new_value is not None:
242
+ self.value = new_value
243
+ log.info(f"Updated {self.env_name} to new value {self.value}")
244
+
245
+ def save(self):
246
+ log.info(f"Saving '{self.env_name}' to the database")
247
+ path_parts = self.config_path.split(".")
248
+ sub_config = CONFIG_DATA
249
+ for key in path_parts[:-1]:
250
+ if key not in sub_config:
251
+ sub_config[key] = {}
252
+ sub_config = sub_config[key]
253
+ sub_config[path_parts[-1]] = self.value
254
+ save_to_db(CONFIG_DATA)
255
+ self.config_value = self.value
256
+
257
+
258
+ class AppConfig:
259
+ _state: dict[str, PersistentConfig]
260
+ _redis: Optional[redis.Redis] = None
261
+
262
+ def __init__(
263
+ self, redis_url: Optional[str] = None, redis_sentinels: Optional[list] = []
264
+ ):
265
+ super().__setattr__("_state", {})
266
+ if redis_url:
267
+ super().__setattr__(
268
+ "_redis",
269
+ get_redis_connection(redis_url, redis_sentinels, decode_responses=True),
270
+ )
271
+
272
+ def __setattr__(self, key, value):
273
+ if isinstance(value, PersistentConfig):
274
+ self._state[key] = value
275
+ else:
276
+ self._state[key].value = value
277
+ self._state[key].save()
278
+
279
+ if self._redis:
280
+ redis_key = f"open-webui:config:{key}"
281
+ self._redis.set(redis_key, json.dumps(self._state[key].value))
282
+
283
+ def __getattr__(self, key):
284
+ if key not in self._state:
285
+ raise AttributeError(f"Config key '{key}' not found")
286
+
287
+ # If Redis is available, check for an updated value
288
+ if self._redis:
289
+ redis_key = f"open-webui:config:{key}"
290
+ redis_value = self._redis.get(redis_key)
291
+
292
+ if redis_value is not None:
293
+ try:
294
+ decoded_value = json.loads(redis_value)
295
+
296
+ # Update the in-memory value if different
297
+ if self._state[key].value != decoded_value:
298
+ self._state[key].value = decoded_value
299
+ log.info(f"Updated {key} from Redis: {decoded_value}")
300
+
301
+ except json.JSONDecodeError:
302
+ log.error(f"Invalid JSON format in Redis for {key}: {redis_value}")
303
+
304
+ return self._state[key].value
305
+
306
+
307
+ ####################################
308
+ # WEBUI_AUTH (Required for security)
309
+ ####################################
310
+
311
+ ENABLE_API_KEY = PersistentConfig(
312
+ "ENABLE_API_KEY",
313
+ "auth.api_key.enable",
314
+ os.environ.get("ENABLE_API_KEY", "True").lower() == "true",
315
+ )
316
+
317
+ ENABLE_API_KEY_ENDPOINT_RESTRICTIONS = PersistentConfig(
318
+ "ENABLE_API_KEY_ENDPOINT_RESTRICTIONS",
319
+ "auth.api_key.endpoint_restrictions",
320
+ os.environ.get("ENABLE_API_KEY_ENDPOINT_RESTRICTIONS", "False").lower() == "true",
321
+ )
322
+
323
+ API_KEY_ALLOWED_ENDPOINTS = PersistentConfig(
324
+ "API_KEY_ALLOWED_ENDPOINTS",
325
+ "auth.api_key.allowed_endpoints",
326
+ os.environ.get("API_KEY_ALLOWED_ENDPOINTS", ""),
327
+ )
328
+
329
+
330
+ JWT_EXPIRES_IN = PersistentConfig(
331
+ "JWT_EXPIRES_IN", "auth.jwt_expiry", os.environ.get("JWT_EXPIRES_IN", "-1")
332
+ )
333
+
334
+ ####################################
335
+ # OAuth config
336
+ ####################################
337
+
338
+
339
+ ENABLE_OAUTH_SIGNUP = PersistentConfig(
340
+ "ENABLE_OAUTH_SIGNUP",
341
+ "oauth.enable_signup",
342
+ os.environ.get("ENABLE_OAUTH_SIGNUP", "False").lower() == "true",
343
+ )
344
+
345
+
346
+ OAUTH_MERGE_ACCOUNTS_BY_EMAIL = PersistentConfig(
347
+ "OAUTH_MERGE_ACCOUNTS_BY_EMAIL",
348
+ "oauth.merge_accounts_by_email",
349
+ os.environ.get("OAUTH_MERGE_ACCOUNTS_BY_EMAIL", "False").lower() == "true",
350
+ )
351
+
352
+ OAUTH_PROVIDERS = {}
353
+
354
+ GOOGLE_CLIENT_ID = PersistentConfig(
355
+ "GOOGLE_CLIENT_ID",
356
+ "oauth.google.client_id",
357
+ os.environ.get("GOOGLE_CLIENT_ID", ""),
358
+ )
359
+
360
+ GOOGLE_CLIENT_SECRET = PersistentConfig(
361
+ "GOOGLE_CLIENT_SECRET",
362
+ "oauth.google.client_secret",
363
+ os.environ.get("GOOGLE_CLIENT_SECRET", ""),
364
+ )
365
+
366
+
367
+ GOOGLE_OAUTH_SCOPE = PersistentConfig(
368
+ "GOOGLE_OAUTH_SCOPE",
369
+ "oauth.google.scope",
370
+ os.environ.get("GOOGLE_OAUTH_SCOPE", "openid email profile"),
371
+ )
372
+
373
+ GOOGLE_REDIRECT_URI = PersistentConfig(
374
+ "GOOGLE_REDIRECT_URI",
375
+ "oauth.google.redirect_uri",
376
+ os.environ.get("GOOGLE_REDIRECT_URI", ""),
377
+ )
378
+
379
+ MICROSOFT_CLIENT_ID = PersistentConfig(
380
+ "MICROSOFT_CLIENT_ID",
381
+ "oauth.microsoft.client_id",
382
+ os.environ.get("MICROSOFT_CLIENT_ID", ""),
383
+ )
384
+
385
+ MICROSOFT_CLIENT_SECRET = PersistentConfig(
386
+ "MICROSOFT_CLIENT_SECRET",
387
+ "oauth.microsoft.client_secret",
388
+ os.environ.get("MICROSOFT_CLIENT_SECRET", ""),
389
+ )
390
+
391
+ MICROSOFT_CLIENT_TENANT_ID = PersistentConfig(
392
+ "MICROSOFT_CLIENT_TENANT_ID",
393
+ "oauth.microsoft.tenant_id",
394
+ os.environ.get("MICROSOFT_CLIENT_TENANT_ID", ""),
395
+ )
396
+
397
+ MICROSOFT_OAUTH_SCOPE = PersistentConfig(
398
+ "MICROSOFT_OAUTH_SCOPE",
399
+ "oauth.microsoft.scope",
400
+ os.environ.get("MICROSOFT_OAUTH_SCOPE", "openid email profile"),
401
+ )
402
+
403
+ MICROSOFT_REDIRECT_URI = PersistentConfig(
404
+ "MICROSOFT_REDIRECT_URI",
405
+ "oauth.microsoft.redirect_uri",
406
+ os.environ.get("MICROSOFT_REDIRECT_URI", ""),
407
+ )
408
+
409
+ GITHUB_CLIENT_ID = PersistentConfig(
410
+ "GITHUB_CLIENT_ID",
411
+ "oauth.github.client_id",
412
+ os.environ.get("GITHUB_CLIENT_ID", ""),
413
+ )
414
+
415
+ GITHUB_CLIENT_SECRET = PersistentConfig(
416
+ "GITHUB_CLIENT_SECRET",
417
+ "oauth.github.client_secret",
418
+ os.environ.get("GITHUB_CLIENT_SECRET", ""),
419
+ )
420
+
421
+ GITHUB_CLIENT_SCOPE = PersistentConfig(
422
+ "GITHUB_CLIENT_SCOPE",
423
+ "oauth.github.scope",
424
+ os.environ.get("GITHUB_CLIENT_SCOPE", "user:email"),
425
+ )
426
+
427
+ GITHUB_CLIENT_REDIRECT_URI = PersistentConfig(
428
+ "GITHUB_CLIENT_REDIRECT_URI",
429
+ "oauth.github.redirect_uri",
430
+ os.environ.get("GITHUB_CLIENT_REDIRECT_URI", ""),
431
+ )
432
+
433
+ OAUTH_CLIENT_ID = PersistentConfig(
434
+ "OAUTH_CLIENT_ID",
435
+ "oauth.oidc.client_id",
436
+ os.environ.get("OAUTH_CLIENT_ID", ""),
437
+ )
438
+
439
+ OAUTH_CLIENT_SECRET = PersistentConfig(
440
+ "OAUTH_CLIENT_SECRET",
441
+ "oauth.oidc.client_secret",
442
+ os.environ.get("OAUTH_CLIENT_SECRET", ""),
443
+ )
444
+
445
+ OPENID_PROVIDER_URL = PersistentConfig(
446
+ "OPENID_PROVIDER_URL",
447
+ "oauth.oidc.provider_url",
448
+ os.environ.get("OPENID_PROVIDER_URL", ""),
449
+ )
450
+
451
+ OPENID_REDIRECT_URI = PersistentConfig(
452
+ "OPENID_REDIRECT_URI",
453
+ "oauth.oidc.redirect_uri",
454
+ os.environ.get("OPENID_REDIRECT_URI", ""),
455
+ )
456
+
457
+ OAUTH_SCOPES = PersistentConfig(
458
+ "OAUTH_SCOPES",
459
+ "oauth.oidc.scopes",
460
+ os.environ.get("OAUTH_SCOPES", "openid email profile"),
461
+ )
462
+
463
+ OAUTH_CODE_CHALLENGE_METHOD = PersistentConfig(
464
+ "OAUTH_CODE_CHALLENGE_METHOD",
465
+ "oauth.oidc.code_challenge_method",
466
+ os.environ.get("OAUTH_CODE_CHALLENGE_METHOD", None),
467
+ )
468
+
469
+ OAUTH_PROVIDER_NAME = PersistentConfig(
470
+ "OAUTH_PROVIDER_NAME",
471
+ "oauth.oidc.provider_name",
472
+ os.environ.get("OAUTH_PROVIDER_NAME", "SSO"),
473
+ )
474
+
475
+ OAUTH_USERNAME_CLAIM = PersistentConfig(
476
+ "OAUTH_USERNAME_CLAIM",
477
+ "oauth.oidc.username_claim",
478
+ os.environ.get("OAUTH_USERNAME_CLAIM", "name"),
479
+ )
480
+
481
+
482
+ OAUTH_PICTURE_CLAIM = PersistentConfig(
483
+ "OAUTH_PICTURE_CLAIM",
484
+ "oauth.oidc.avatar_claim",
485
+ os.environ.get("OAUTH_PICTURE_CLAIM", "picture"),
486
+ )
487
+
488
+ OAUTH_EMAIL_CLAIM = PersistentConfig(
489
+ "OAUTH_EMAIL_CLAIM",
490
+ "oauth.oidc.email_claim",
491
+ os.environ.get("OAUTH_EMAIL_CLAIM", "email"),
492
+ )
493
+
494
+ OAUTH_GROUPS_CLAIM = PersistentConfig(
495
+ "OAUTH_GROUPS_CLAIM",
496
+ "oauth.oidc.group_claim",
497
+ os.environ.get("OAUTH_GROUP_CLAIM", "groups"),
498
+ )
499
+
500
+ ENABLE_OAUTH_ROLE_MANAGEMENT = PersistentConfig(
501
+ "ENABLE_OAUTH_ROLE_MANAGEMENT",
502
+ "oauth.enable_role_mapping",
503
+ os.environ.get("ENABLE_OAUTH_ROLE_MANAGEMENT", "False").lower() == "true",
504
+ )
505
+
506
+ ENABLE_OAUTH_GROUP_MANAGEMENT = PersistentConfig(
507
+ "ENABLE_OAUTH_GROUP_MANAGEMENT",
508
+ "oauth.enable_group_mapping",
509
+ os.environ.get("ENABLE_OAUTH_GROUP_MANAGEMENT", "False").lower() == "true",
510
+ )
511
+
512
+ ENABLE_OAUTH_GROUP_CREATION = PersistentConfig(
513
+ "ENABLE_OAUTH_GROUP_CREATION",
514
+ "oauth.enable_group_creation",
515
+ os.environ.get("ENABLE_OAUTH_GROUP_CREATION", "False").lower() == "true",
516
+ )
517
+
518
+ OAUTH_ROLES_CLAIM = PersistentConfig(
519
+ "OAUTH_ROLES_CLAIM",
520
+ "oauth.roles_claim",
521
+ os.environ.get("OAUTH_ROLES_CLAIM", "roles"),
522
+ )
523
+
524
+ OAUTH_ALLOWED_ROLES = PersistentConfig(
525
+ "OAUTH_ALLOWED_ROLES",
526
+ "oauth.allowed_roles",
527
+ [
528
+ role.strip()
529
+ for role in os.environ.get("OAUTH_ALLOWED_ROLES", "user,admin").split(",")
530
+ ],
531
+ )
532
+
533
+ OAUTH_ADMIN_ROLES = PersistentConfig(
534
+ "OAUTH_ADMIN_ROLES",
535
+ "oauth.admin_roles",
536
+ [role.strip() for role in os.environ.get("OAUTH_ADMIN_ROLES", "admin").split(",")],
537
+ )
538
+
539
+ OAUTH_ALLOWED_DOMAINS = PersistentConfig(
540
+ "OAUTH_ALLOWED_DOMAINS",
541
+ "oauth.allowed_domains",
542
+ [
543
+ domain.strip()
544
+ for domain in os.environ.get("OAUTH_ALLOWED_DOMAINS", "*").split(",")
545
+ ],
546
+ )
547
+
548
+
549
+ def load_oauth_providers():
550
+ OAUTH_PROVIDERS.clear()
551
+ if GOOGLE_CLIENT_ID.value and GOOGLE_CLIENT_SECRET.value:
552
+
553
+ def google_oauth_register(client):
554
+ client.register(
555
+ name="google",
556
+ client_id=GOOGLE_CLIENT_ID.value,
557
+ client_secret=GOOGLE_CLIENT_SECRET.value,
558
+ server_metadata_url="https://accounts.google.com/.well-known/openid-configuration",
559
+ client_kwargs={"scope": GOOGLE_OAUTH_SCOPE.value},
560
+ redirect_uri=GOOGLE_REDIRECT_URI.value,
561
+ )
562
+
563
+ OAUTH_PROVIDERS["google"] = {
564
+ "redirect_uri": GOOGLE_REDIRECT_URI.value,
565
+ "register": google_oauth_register,
566
+ }
567
+
568
+ if (
569
+ MICROSOFT_CLIENT_ID.value
570
+ and MICROSOFT_CLIENT_SECRET.value
571
+ and MICROSOFT_CLIENT_TENANT_ID.value
572
+ ):
573
+
574
+ def microsoft_oauth_register(client):
575
+ client.register(
576
+ name="microsoft",
577
+ client_id=MICROSOFT_CLIENT_ID.value,
578
+ client_secret=MICROSOFT_CLIENT_SECRET.value,
579
+ server_metadata_url=f"https://login.microsoftonline.com/{MICROSOFT_CLIENT_TENANT_ID.value}/v2.0/.well-known/openid-configuration?appid={MICROSOFT_CLIENT_ID.value}",
580
+ client_kwargs={
581
+ "scope": MICROSOFT_OAUTH_SCOPE.value,
582
+ },
583
+ redirect_uri=MICROSOFT_REDIRECT_URI.value,
584
+ )
585
+
586
+ OAUTH_PROVIDERS["microsoft"] = {
587
+ "redirect_uri": MICROSOFT_REDIRECT_URI.value,
588
+ "picture_url": "https://graph.microsoft.com/v1.0/me/photo/$value",
589
+ "register": microsoft_oauth_register,
590
+ }
591
+
592
+ if GITHUB_CLIENT_ID.value and GITHUB_CLIENT_SECRET.value:
593
+
594
+ def github_oauth_register(client):
595
+ client.register(
596
+ name="github",
597
+ client_id=GITHUB_CLIENT_ID.value,
598
+ client_secret=GITHUB_CLIENT_SECRET.value,
599
+ access_token_url="https://github.com/login/oauth/access_token",
600
+ authorize_url="https://github.com/login/oauth/authorize",
601
+ api_base_url="https://api.github.com",
602
+ userinfo_endpoint="https://api.github.com/user",
603
+ client_kwargs={"scope": GITHUB_CLIENT_SCOPE.value},
604
+ redirect_uri=GITHUB_CLIENT_REDIRECT_URI.value,
605
+ )
606
+
607
+ OAUTH_PROVIDERS["github"] = {
608
+ "redirect_uri": GITHUB_CLIENT_REDIRECT_URI.value,
609
+ "register": github_oauth_register,
610
+ "sub_claim": "id",
611
+ }
612
+
613
+ if (
614
+ OAUTH_CLIENT_ID.value
615
+ and OAUTH_CLIENT_SECRET.value
616
+ and OPENID_PROVIDER_URL.value
617
+ ):
618
+
619
+ def oidc_oauth_register(client):
620
+ client_kwargs = {
621
+ "scope": OAUTH_SCOPES.value,
622
+ }
623
+
624
+ if (
625
+ OAUTH_CODE_CHALLENGE_METHOD.value
626
+ and OAUTH_CODE_CHALLENGE_METHOD.value == "S256"
627
+ ):
628
+ client_kwargs["code_challenge_method"] = "S256"
629
+ elif OAUTH_CODE_CHALLENGE_METHOD.value:
630
+ raise Exception(
631
+ 'Code challenge methods other than "%s" not supported. Given: "%s"'
632
+ % ("S256", OAUTH_CODE_CHALLENGE_METHOD.value)
633
+ )
634
+
635
+ client.register(
636
+ name="oidc",
637
+ client_id=OAUTH_CLIENT_ID.value,
638
+ client_secret=OAUTH_CLIENT_SECRET.value,
639
+ server_metadata_url=OPENID_PROVIDER_URL.value,
640
+ client_kwargs=client_kwargs,
641
+ redirect_uri=OPENID_REDIRECT_URI.value,
642
+ )
643
+
644
+ OAUTH_PROVIDERS["oidc"] = {
645
+ "name": OAUTH_PROVIDER_NAME.value,
646
+ "redirect_uri": OPENID_REDIRECT_URI.value,
647
+ "register": oidc_oauth_register,
648
+ }
649
+
650
+
651
+ load_oauth_providers()
652
+
653
+ ####################################
654
+ # Static DIR
655
+ ####################################
656
+
657
+ STATIC_DIR = Path(os.getenv("STATIC_DIR", OPEN_WEBUI_DIR / "static")).resolve()
658
+
659
+ for file_path in (FRONTEND_BUILD_DIR / "static").glob("**/*"):
660
+ if file_path.is_file():
661
+ target_path = STATIC_DIR / file_path.relative_to(
662
+ (FRONTEND_BUILD_DIR / "static")
663
+ )
664
+ target_path.parent.mkdir(parents=True, exist_ok=True)
665
+ try:
666
+ shutil.copyfile(file_path, target_path)
667
+ except Exception as e:
668
+ logging.error(f"An error occurred: {e}")
669
+
670
+ frontend_favicon = FRONTEND_BUILD_DIR / "static" / "favicon.png"
671
+
672
+ if frontend_favicon.exists():
673
+ try:
674
+ shutil.copyfile(frontend_favicon, STATIC_DIR / "favicon.png")
675
+ except Exception as e:
676
+ logging.error(f"An error occurred: {e}")
677
+
678
+ frontend_splash = FRONTEND_BUILD_DIR / "static" / "splash.png"
679
+
680
+ if frontend_splash.exists():
681
+ try:
682
+ shutil.copyfile(frontend_splash, STATIC_DIR / "splash.png")
683
+ except Exception as e:
684
+ logging.error(f"An error occurred: {e}")
685
+
686
+ frontend_loader = FRONTEND_BUILD_DIR / "static" / "loader.js"
687
+
688
+ if frontend_loader.exists():
689
+ try:
690
+ shutil.copyfile(frontend_loader, STATIC_DIR / "loader.js")
691
+ except Exception as e:
692
+ logging.error(f"An error occurred: {e}")
693
+
694
+
695
+ ####################################
696
+ # CUSTOM_NAME (Legacy)
697
+ ####################################
698
+
699
+ CUSTOM_NAME = os.environ.get("CUSTOM_NAME", "")
700
+
701
+ if CUSTOM_NAME:
702
+ try:
703
+ r = requests.get(f"https://api.openwebui.com/api/v1/custom/{CUSTOM_NAME}")
704
+ data = r.json()
705
+ if r.ok:
706
+ if "logo" in data:
707
+ WEBUI_FAVICON_URL = url = (
708
+ f"https://api.openwebui.com{data['logo']}"
709
+ if data["logo"][0] == "/"
710
+ else data["logo"]
711
+ )
712
+
713
+ r = requests.get(url, stream=True)
714
+ if r.status_code == 200:
715
+ with open(f"{STATIC_DIR}/favicon.png", "wb") as f:
716
+ r.raw.decode_content = True
717
+ shutil.copyfileobj(r.raw, f)
718
+
719
+ if "splash" in data:
720
+ url = (
721
+ f"https://api.openwebui.com{data['splash']}"
722
+ if data["splash"][0] == "/"
723
+ else data["splash"]
724
+ )
725
+
726
+ r = requests.get(url, stream=True)
727
+ if r.status_code == 200:
728
+ with open(f"{STATIC_DIR}/splash.png", "wb") as f:
729
+ r.raw.decode_content = True
730
+ shutil.copyfileobj(r.raw, f)
731
+
732
+ WEBUI_NAME = data["name"]
733
+ except Exception as e:
734
+ log.exception(e)
735
+ pass
736
+
737
+
738
+ ####################################
739
+ # LICENSE_KEY
740
+ ####################################
741
+
742
+ LICENSE_KEY = os.environ.get("LICENSE_KEY", "")
743
+
744
+ ####################################
745
+ # STORAGE PROVIDER
746
+ ####################################
747
+
748
+ STORAGE_PROVIDER = os.environ.get("STORAGE_PROVIDER", "local") # defaults to local, s3
749
+
750
+ S3_ACCESS_KEY_ID = os.environ.get("S3_ACCESS_KEY_ID", None)
751
+ S3_SECRET_ACCESS_KEY = os.environ.get("S3_SECRET_ACCESS_KEY", None)
752
+ S3_REGION_NAME = os.environ.get("S3_REGION_NAME", None)
753
+ S3_BUCKET_NAME = os.environ.get("S3_BUCKET_NAME", None)
754
+ S3_KEY_PREFIX = os.environ.get("S3_KEY_PREFIX", None)
755
+ S3_ENDPOINT_URL = os.environ.get("S3_ENDPOINT_URL", None)
756
+ S3_USE_ACCELERATE_ENDPOINT = (
757
+ os.environ.get("S3_USE_ACCELERATE_ENDPOINT", "False").lower() == "true"
758
+ )
759
+ S3_ADDRESSING_STYLE = os.environ.get("S3_ADDRESSING_STYLE", None)
760
+
761
+ GCS_BUCKET_NAME = os.environ.get("GCS_BUCKET_NAME", None)
762
+ GOOGLE_APPLICATION_CREDENTIALS_JSON = os.environ.get(
763
+ "GOOGLE_APPLICATION_CREDENTIALS_JSON", None
764
+ )
765
+
766
+ AZURE_STORAGE_ENDPOINT = os.environ.get("AZURE_STORAGE_ENDPOINT", None)
767
+ AZURE_STORAGE_CONTAINER_NAME = os.environ.get("AZURE_STORAGE_CONTAINER_NAME", None)
768
+ AZURE_STORAGE_KEY = os.environ.get("AZURE_STORAGE_KEY", None)
769
+
770
+ ####################################
771
+ # File Upload DIR
772
+ ####################################
773
+
774
+ UPLOAD_DIR = DATA_DIR / "uploads"
775
+ UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
776
+
777
+
778
+ ####################################
779
+ # Cache DIR
780
+ ####################################
781
+
782
+ CACHE_DIR = DATA_DIR / "cache"
783
+ CACHE_DIR.mkdir(parents=True, exist_ok=True)
784
+
785
+
786
+ ####################################
787
+ # DIRECT CONNECTIONS
788
+ ####################################
789
+
790
+ ENABLE_DIRECT_CONNECTIONS = PersistentConfig(
791
+ "ENABLE_DIRECT_CONNECTIONS",
792
+ "direct.enable",
793
+ os.environ.get("ENABLE_DIRECT_CONNECTIONS", "True").lower() == "true",
794
+ )
795
+
796
+ ####################################
797
+ # OLLAMA_BASE_URL
798
+ ####################################
799
+
800
+ ENABLE_OLLAMA_API = PersistentConfig(
801
+ "ENABLE_OLLAMA_API",
802
+ "ollama.enable",
803
+ os.environ.get("ENABLE_OLLAMA_API", "True").lower() == "true",
804
+ )
805
+
806
+ OLLAMA_API_BASE_URL = os.environ.get(
807
+ "OLLAMA_API_BASE_URL", "http://localhost:11434/api"
808
+ )
809
+
810
+ OLLAMA_BASE_URL = os.environ.get("OLLAMA_BASE_URL", "")
811
+ if OLLAMA_BASE_URL:
812
+ # Remove trailing slash
813
+ OLLAMA_BASE_URL = (
814
+ OLLAMA_BASE_URL[:-1] if OLLAMA_BASE_URL.endswith("/") else OLLAMA_BASE_URL
815
+ )
816
+
817
+
818
+ K8S_FLAG = os.environ.get("K8S_FLAG", "")
819
+ USE_OLLAMA_DOCKER = os.environ.get("USE_OLLAMA_DOCKER", "false")
820
+
821
+ if OLLAMA_BASE_URL == "" and OLLAMA_API_BASE_URL != "":
822
+ OLLAMA_BASE_URL = (
823
+ OLLAMA_API_BASE_URL[:-4]
824
+ if OLLAMA_API_BASE_URL.endswith("/api")
825
+ else OLLAMA_API_BASE_URL
826
+ )
827
+
828
+ if ENV == "prod":
829
+ if OLLAMA_BASE_URL == "/ollama" and not K8S_FLAG:
830
+ if USE_OLLAMA_DOCKER.lower() == "true":
831
+ # if you use all-in-one docker container (Open WebUI + Ollama)
832
+ # with the docker build arg USE_OLLAMA=true (--build-arg="USE_OLLAMA=true") this only works with http://localhost:11434
833
+ OLLAMA_BASE_URL = "http://localhost:11434"
834
+ else:
835
+ OLLAMA_BASE_URL = "http://host.docker.internal:11434"
836
+ elif K8S_FLAG:
837
+ OLLAMA_BASE_URL = "http://ollama-service.open-webui.svc.cluster.local:11434"
838
+
839
+
840
+ OLLAMA_BASE_URLS = os.environ.get("OLLAMA_BASE_URLS", "")
841
+ OLLAMA_BASE_URLS = OLLAMA_BASE_URLS if OLLAMA_BASE_URLS != "" else OLLAMA_BASE_URL
842
+
843
+ OLLAMA_BASE_URLS = [url.strip() for url in OLLAMA_BASE_URLS.split(";")]
844
+ OLLAMA_BASE_URLS = PersistentConfig(
845
+ "OLLAMA_BASE_URLS", "ollama.base_urls", OLLAMA_BASE_URLS
846
+ )
847
+
848
+ OLLAMA_API_CONFIGS = PersistentConfig(
849
+ "OLLAMA_API_CONFIGS",
850
+ "ollama.api_configs",
851
+ {},
852
+ )
853
+
854
+ ####################################
855
+ # OPENAI_API
856
+ ####################################
857
+
858
+
859
+ ENABLE_OPENAI_API = PersistentConfig(
860
+ "ENABLE_OPENAI_API",
861
+ "openai.enable",
862
+ os.environ.get("ENABLE_OPENAI_API", "True").lower() == "true",
863
+ )
864
+
865
+
866
+ OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "")
867
+ OPENAI_API_BASE_URL = os.environ.get("OPENAI_API_BASE_URL", "")
868
+
869
+ GEMINI_API_KEY = os.environ.get("GEMINI_API_KEY", "")
870
+ GEMINI_API_BASE_URL = os.environ.get("GEMINI_API_BASE_URL", "")
871
+
872
+
873
+ if OPENAI_API_BASE_URL == "":
874
+ OPENAI_API_BASE_URL = "https://api.openai.com/v1"
875
+
876
+ OPENAI_API_KEYS = os.environ.get("OPENAI_API_KEYS", "")
877
+ OPENAI_API_KEYS = OPENAI_API_KEYS if OPENAI_API_KEYS != "" else OPENAI_API_KEY
878
+
879
+ OPENAI_API_KEYS = [url.strip() for url in OPENAI_API_KEYS.split(";")]
880
+ OPENAI_API_KEYS = PersistentConfig(
881
+ "OPENAI_API_KEYS", "openai.api_keys", OPENAI_API_KEYS
882
+ )
883
+
884
+ OPENAI_API_BASE_URLS = os.environ.get("OPENAI_API_BASE_URLS", "")
885
+ OPENAI_API_BASE_URLS = (
886
+ OPENAI_API_BASE_URLS if OPENAI_API_BASE_URLS != "" else OPENAI_API_BASE_URL
887
+ )
888
+
889
+ OPENAI_API_BASE_URLS = [
890
+ url.strip() if url != "" else "https://api.openai.com/v1"
891
+ for url in OPENAI_API_BASE_URLS.split(";")
892
+ ]
893
+ OPENAI_API_BASE_URLS = PersistentConfig(
894
+ "OPENAI_API_BASE_URLS", "openai.api_base_urls", OPENAI_API_BASE_URLS
895
+ )
896
+
897
+ OPENAI_API_CONFIGS = PersistentConfig(
898
+ "OPENAI_API_CONFIGS",
899
+ "openai.api_configs",
900
+ {},
901
+ )
902
+
903
+ # Get the actual OpenAI API key based on the base URL
904
+ OPENAI_API_KEY = ""
905
+ try:
906
+ OPENAI_API_KEY = OPENAI_API_KEYS.value[
907
+ OPENAI_API_BASE_URLS.value.index("https://api.openai.com/v1")
908
+ ]
909
+ except Exception:
910
+ pass
911
+ OPENAI_API_BASE_URL = "https://api.openai.com/v1"
912
+
913
+ ####################################
914
+ # TOOL_SERVERS
915
+ ####################################
916
+
917
+
918
+ TOOL_SERVER_CONNECTIONS = PersistentConfig(
919
+ "TOOL_SERVER_CONNECTIONS",
920
+ "tool_server.connections",
921
+ [],
922
+ )
923
+
924
+ ####################################
925
+ # WEBUI
926
+ ####################################
927
+
928
+
929
+ WEBUI_URL = PersistentConfig(
930
+ "WEBUI_URL", "webui.url", os.environ.get("WEBUI_URL", "http://localhost:3000")
931
+ )
932
+
933
+
934
+ ENABLE_SIGNUP = PersistentConfig(
935
+ "ENABLE_SIGNUP",
936
+ "ui.enable_signup",
937
+ (
938
+ False
939
+ if not WEBUI_AUTH
940
+ else os.environ.get("ENABLE_SIGNUP", "True").lower() == "true"
941
+ ),
942
+ )
943
+
944
+ ENABLE_LOGIN_FORM = PersistentConfig(
945
+ "ENABLE_LOGIN_FORM",
946
+ "ui.ENABLE_LOGIN_FORM",
947
+ os.environ.get("ENABLE_LOGIN_FORM", "True").lower() == "true",
948
+ )
949
+
950
+
951
+ DEFAULT_LOCALE = PersistentConfig(
952
+ "DEFAULT_LOCALE",
953
+ "ui.default_locale",
954
+ os.environ.get("DEFAULT_LOCALE", ""),
955
+ )
956
+
957
+ DEFAULT_MODELS = PersistentConfig(
958
+ "DEFAULT_MODELS", "ui.default_models", os.environ.get("DEFAULT_MODELS", None)
959
+ )
960
+
961
+ try:
962
+ default_prompt_suggestions = json.loads(os.environ.get("DEFAULT_PROMPT_SUGGESTIONS", "[]"))
963
+ except Exception as e:
964
+ log.exception(f"Error loading DEFAULT_PROMPT_SUGGESTIONS: {e}")
965
+ default_prompt_suggestions = []
966
+ if default_prompt_suggestions == []:
967
+ default_prompt_suggestions = [
968
+ {
969
+ "title": ["Help me study", "vocabulary for a college entrance exam"],
970
+ "content": "Help me study vocabulary: write a sentence for me to fill in the blank, and I'll try to pick the correct option.",
971
+ },
972
+ {
973
+ "title": ["Give me ideas", "for what to do with my kids' art"],
974
+ "content": "What are 5 creative things I could do with my kids' art? I don't want to throw them away, but it's also so much clutter.",
975
+ },
976
+ {
977
+ "title": ["Tell me a fun fact", "about the Roman Empire"],
978
+ "content": "Tell me a random fun fact about the Roman Empire",
979
+ },
980
+ {
981
+ "title": ["Show me a code snippet", "of a website's sticky header"],
982
+ "content": "Show me a code snippet of a website's sticky header in CSS and JavaScript.",
983
+ },
984
+ {
985
+ "title": [
986
+ "Explain options trading",
987
+ "if I'm familiar with buying and selling stocks",
988
+ ],
989
+ "content": "Explain options trading in simple terms if I'm familiar with buying and selling stocks.",
990
+ },
991
+ {
992
+ "title": ["Overcome procrastination", "give me tips"],
993
+ "content": "Could you start by asking me about instances when I procrastinate the most and then give me some suggestions to overcome it?",
994
+ },
995
+ ]
996
+ DEFAULT_PROMPT_SUGGESTIONS = PersistentConfig(
997
+ "DEFAULT_PROMPT_SUGGESTIONS",
998
+ "ui.prompt_suggestions",
999
+ default_prompt_suggestions,
1000
+ )
1001
+
1002
+ MODEL_ORDER_LIST = PersistentConfig(
1003
+ "MODEL_ORDER_LIST",
1004
+ "ui.model_order_list",
1005
+ [],
1006
+ )
1007
+
1008
+ DEFAULT_USER_ROLE = PersistentConfig(
1009
+ "DEFAULT_USER_ROLE",
1010
+ "ui.default_user_role",
1011
+ os.getenv("DEFAULT_USER_ROLE", "pending"),
1012
+ )
1013
+
1014
+ USER_PERMISSIONS_WORKSPACE_MODELS_ACCESS = (
1015
+ os.environ.get("USER_PERMISSIONS_WORKSPACE_MODELS_ACCESS", "False").lower()
1016
+ == "true"
1017
+ )
1018
+
1019
+ USER_PERMISSIONS_WORKSPACE_KNOWLEDGE_ACCESS = (
1020
+ os.environ.get("USER_PERMISSIONS_WORKSPACE_KNOWLEDGE_ACCESS", "False").lower()
1021
+ == "true"
1022
+ )
1023
+
1024
+ USER_PERMISSIONS_WORKSPACE_PROMPTS_ACCESS = (
1025
+ os.environ.get("USER_PERMISSIONS_WORKSPACE_PROMPTS_ACCESS", "False").lower()
1026
+ == "true"
1027
+ )
1028
+
1029
+ USER_PERMISSIONS_WORKSPACE_TOOLS_ACCESS = (
1030
+ os.environ.get("USER_PERMISSIONS_WORKSPACE_TOOLS_ACCESS", "False").lower() == "true"
1031
+ )
1032
+
1033
+ USER_PERMISSIONS_WORKSPACE_MODELS_ALLOW_PUBLIC_SHARING = (
1034
+ os.environ.get(
1035
+ "USER_PERMISSIONS_WORKSPACE_MODELS_ALLOW_PUBLIC_SHARING", "False"
1036
+ ).lower()
1037
+ == "true"
1038
+ )
1039
+
1040
+ USER_PERMISSIONS_WORKSPACE_KNOWLEDGE_ALLOW_PUBLIC_SHARING = (
1041
+ os.environ.get(
1042
+ "USER_PERMISSIONS_WORKSPACE_KNOWLEDGE_ALLOW_PUBLIC_SHARING", "False"
1043
+ ).lower()
1044
+ == "true"
1045
+ )
1046
+
1047
+ USER_PERMISSIONS_WORKSPACE_PROMPTS_ALLOW_PUBLIC_SHARING = (
1048
+ os.environ.get(
1049
+ "USER_PERMISSIONS_WORKSPACE_PROMPTS_ALLOW_PUBLIC_SHARING", "False"
1050
+ ).lower()
1051
+ == "true"
1052
+ )
1053
+
1054
+ USER_PERMISSIONS_WORKSPACE_TOOLS_ALLOW_PUBLIC_SHARING = (
1055
+ os.environ.get(
1056
+ "USER_PERMISSIONS_WORKSPACE_TOOLS_ALLOW_PUBLIC_SHARING", "False"
1057
+ ).lower()
1058
+ == "true"
1059
+ )
1060
+
1061
+
1062
+ USER_PERMISSIONS_CHAT_CONTROLS = (
1063
+ os.environ.get("USER_PERMISSIONS_CHAT_CONTROLS", "True").lower() == "true"
1064
+ )
1065
+
1066
+ USER_PERMISSIONS_CHAT_FILE_UPLOAD = (
1067
+ os.environ.get("USER_PERMISSIONS_CHAT_FILE_UPLOAD", "True").lower() == "true"
1068
+ )
1069
+
1070
+ USER_PERMISSIONS_CHAT_DELETE = (
1071
+ os.environ.get("USER_PERMISSIONS_CHAT_DELETE", "True").lower() == "true"
1072
+ )
1073
+
1074
+ USER_PERMISSIONS_CHAT_EDIT = (
1075
+ os.environ.get("USER_PERMISSIONS_CHAT_EDIT", "True").lower() == "true"
1076
+ )
1077
+
1078
+ USER_PERMISSIONS_CHAT_SHARE = (
1079
+ os.environ.get("USER_PERMISSIONS_CHAT_SHARE", "True").lower() == "true"
1080
+ )
1081
+
1082
+ USER_PERMISSIONS_CHAT_EXPORT = (
1083
+ os.environ.get("USER_PERMISSIONS_CHAT_EXPORT", "True").lower() == "true"
1084
+ )
1085
+
1086
+ USER_PERMISSIONS_CHAT_STT = (
1087
+ os.environ.get("USER_PERMISSIONS_CHAT_STT", "True").lower() == "true"
1088
+ )
1089
+
1090
+ USER_PERMISSIONS_CHAT_TTS = (
1091
+ os.environ.get("USER_PERMISSIONS_CHAT_TTS", "True").lower() == "true"
1092
+ )
1093
+
1094
+ USER_PERMISSIONS_CHAT_CALL = (
1095
+ os.environ.get("USER_PERMISSIONS_CHAT_CALL", "True").lower() == "true"
1096
+ )
1097
+
1098
+ USER_PERMISSIONS_CHAT_MULTIPLE_MODELS = (
1099
+ os.environ.get("USER_PERMISSIONS_CHAT_MULTIPLE_MODELS", "True").lower() == "true"
1100
+ )
1101
+
1102
+ USER_PERMISSIONS_CHAT_TEMPORARY = (
1103
+ os.environ.get("USER_PERMISSIONS_CHAT_TEMPORARY", "True").lower() == "true"
1104
+ )
1105
+
1106
+ USER_PERMISSIONS_CHAT_TEMPORARY_ENFORCED = (
1107
+ os.environ.get("USER_PERMISSIONS_CHAT_TEMPORARY_ENFORCED", "False").lower()
1108
+ == "true"
1109
+ )
1110
+
1111
+
1112
+ USER_PERMISSIONS_FEATURES_DIRECT_TOOL_SERVERS = (
1113
+ os.environ.get("USER_PERMISSIONS_FEATURES_DIRECT_TOOL_SERVERS", "False").lower()
1114
+ == "true"
1115
+ )
1116
+
1117
+ USER_PERMISSIONS_FEATURES_WEB_SEARCH = (
1118
+ os.environ.get("USER_PERMISSIONS_FEATURES_WEB_SEARCH", "True").lower() == "true"
1119
+ )
1120
+
1121
+ USER_PERMISSIONS_FEATURES_IMAGE_GENERATION = (
1122
+ os.environ.get("USER_PERMISSIONS_FEATURES_IMAGE_GENERATION", "True").lower()
1123
+ == "true"
1124
+ )
1125
+
1126
+ USER_PERMISSIONS_FEATURES_CODE_INTERPRETER = (
1127
+ os.environ.get("USER_PERMISSIONS_FEATURES_CODE_INTERPRETER", "True").lower()
1128
+ == "true"
1129
+ )
1130
+
1131
+
1132
+ DEFAULT_USER_PERMISSIONS = {
1133
+ "workspace": {
1134
+ "models": USER_PERMISSIONS_WORKSPACE_MODELS_ACCESS,
1135
+ "knowledge": USER_PERMISSIONS_WORKSPACE_KNOWLEDGE_ACCESS,
1136
+ "prompts": USER_PERMISSIONS_WORKSPACE_PROMPTS_ACCESS,
1137
+ "tools": USER_PERMISSIONS_WORKSPACE_TOOLS_ACCESS,
1138
+ },
1139
+ "sharing": {
1140
+ "public_models": USER_PERMISSIONS_WORKSPACE_MODELS_ALLOW_PUBLIC_SHARING,
1141
+ "public_knowledge": USER_PERMISSIONS_WORKSPACE_KNOWLEDGE_ALLOW_PUBLIC_SHARING,
1142
+ "public_prompts": USER_PERMISSIONS_WORKSPACE_PROMPTS_ALLOW_PUBLIC_SHARING,
1143
+ "public_tools": USER_PERMISSIONS_WORKSPACE_TOOLS_ALLOW_PUBLIC_SHARING,
1144
+ },
1145
+ "chat": {
1146
+ "controls": USER_PERMISSIONS_CHAT_CONTROLS,
1147
+ "file_upload": USER_PERMISSIONS_CHAT_FILE_UPLOAD,
1148
+ "delete": USER_PERMISSIONS_CHAT_DELETE,
1149
+ "edit": USER_PERMISSIONS_CHAT_EDIT,
1150
+ "share": USER_PERMISSIONS_CHAT_SHARE,
1151
+ "export": USER_PERMISSIONS_CHAT_EXPORT,
1152
+ "stt": USER_PERMISSIONS_CHAT_STT,
1153
+ "tts": USER_PERMISSIONS_CHAT_TTS,
1154
+ "call": USER_PERMISSIONS_CHAT_CALL,
1155
+ "multiple_models": USER_PERMISSIONS_CHAT_MULTIPLE_MODELS,
1156
+ "temporary": USER_PERMISSIONS_CHAT_TEMPORARY,
1157
+ "temporary_enforced": USER_PERMISSIONS_CHAT_TEMPORARY_ENFORCED,
1158
+ },
1159
+ "features": {
1160
+ "direct_tool_servers": USER_PERMISSIONS_FEATURES_DIRECT_TOOL_SERVERS,
1161
+ "web_search": USER_PERMISSIONS_FEATURES_WEB_SEARCH,
1162
+ "image_generation": USER_PERMISSIONS_FEATURES_IMAGE_GENERATION,
1163
+ "code_interpreter": USER_PERMISSIONS_FEATURES_CODE_INTERPRETER,
1164
+ },
1165
+ }
1166
+
1167
+ USER_PERMISSIONS = PersistentConfig(
1168
+ "USER_PERMISSIONS",
1169
+ "user.permissions",
1170
+ DEFAULT_USER_PERMISSIONS,
1171
+ )
1172
+
1173
+ ENABLE_CHANNELS = PersistentConfig(
1174
+ "ENABLE_CHANNELS",
1175
+ "channels.enable",
1176
+ os.environ.get("ENABLE_CHANNELS", "False").lower() == "true",
1177
+ )
1178
+
1179
+
1180
+ ENABLE_EVALUATION_ARENA_MODELS = PersistentConfig(
1181
+ "ENABLE_EVALUATION_ARENA_MODELS",
1182
+ "evaluation.arena.enable",
1183
+ os.environ.get("ENABLE_EVALUATION_ARENA_MODELS", "True").lower() == "true",
1184
+ )
1185
+ EVALUATION_ARENA_MODELS = PersistentConfig(
1186
+ "EVALUATION_ARENA_MODELS",
1187
+ "evaluation.arena.models",
1188
+ [],
1189
+ )
1190
+
1191
+ DEFAULT_ARENA_MODEL = {
1192
+ "id": "arena-model",
1193
+ "name": "Arena Model",
1194
+ "meta": {
1195
+ "profile_image_url": "/favicon.png",
1196
+ "description": "Submit your questions to anonymous AI chatbots and vote on the best response.",
1197
+ "model_ids": None,
1198
+ },
1199
+ }
1200
+
1201
+ WEBHOOK_URL = PersistentConfig(
1202
+ "WEBHOOK_URL", "webhook_url", os.environ.get("WEBHOOK_URL", "")
1203
+ )
1204
+
1205
+ ENABLE_ADMIN_EXPORT = os.environ.get("ENABLE_ADMIN_EXPORT", "True").lower() == "true"
1206
+
1207
+ ENABLE_ADMIN_CHAT_ACCESS = (
1208
+ os.environ.get("ENABLE_ADMIN_CHAT_ACCESS", "True").lower() == "true"
1209
+ )
1210
+
1211
+ ENABLE_COMMUNITY_SHARING = PersistentConfig(
1212
+ "ENABLE_COMMUNITY_SHARING",
1213
+ "ui.enable_community_sharing",
1214
+ os.environ.get("ENABLE_COMMUNITY_SHARING", "True").lower() == "true",
1215
+ )
1216
+
1217
+ ENABLE_MESSAGE_RATING = PersistentConfig(
1218
+ "ENABLE_MESSAGE_RATING",
1219
+ "ui.enable_message_rating",
1220
+ os.environ.get("ENABLE_MESSAGE_RATING", "True").lower() == "true",
1221
+ )
1222
+
1223
+ ENABLE_USER_WEBHOOKS = PersistentConfig(
1224
+ "ENABLE_USER_WEBHOOKS",
1225
+ "ui.enable_user_webhooks",
1226
+ os.environ.get("ENABLE_USER_WEBHOOKS", "True").lower() == "true",
1227
+ )
1228
+
1229
+ # FastAPI / AnyIO settings
1230
+ THREAD_POOL_SIZE = int(os.getenv("THREAD_POOL_SIZE", "0"))
1231
+
1232
+
1233
+ def validate_cors_origins(origins):
1234
+ for origin in origins:
1235
+ if origin != "*":
1236
+ validate_cors_origin(origin)
1237
+
1238
+
1239
+ def validate_cors_origin(origin):
1240
+ parsed_url = urlparse(origin)
1241
+
1242
+ # Check if the scheme is either http or https
1243
+ if parsed_url.scheme not in ["http", "https"]:
1244
+ raise ValueError(
1245
+ f"Invalid scheme in CORS_ALLOW_ORIGIN: '{origin}'. Only 'http' and 'https' are allowed."
1246
+ )
1247
+
1248
+ # Ensure that the netloc (domain + port) is present, indicating it's a valid URL
1249
+ if not parsed_url.netloc:
1250
+ raise ValueError(f"Invalid URL structure in CORS_ALLOW_ORIGIN: '{origin}'.")
1251
+
1252
+
1253
+ # For production, you should only need one host as
1254
+ # fastapi serves the svelte-kit built frontend and backend from the same host and port.
1255
+ # To test CORS_ALLOW_ORIGIN locally, you can set something like
1256
+ # CORS_ALLOW_ORIGIN=http://localhost:5173;http://localhost:8080
1257
+ # in your .env file depending on your frontend port, 5173 in this case.
1258
+ CORS_ALLOW_ORIGIN = os.environ.get("CORS_ALLOW_ORIGIN", "*").split(";")
1259
+
1260
+ if "*" in CORS_ALLOW_ORIGIN:
1261
+ log.warning(
1262
+ "\n\nWARNING: CORS_ALLOW_ORIGIN IS SET TO '*' - NOT RECOMMENDED FOR PRODUCTION DEPLOYMENTS.\n"
1263
+ )
1264
+
1265
+ validate_cors_origins(CORS_ALLOW_ORIGIN)
1266
+
1267
+
1268
+ class BannerModel(BaseModel):
1269
+ id: str
1270
+ type: str
1271
+ title: Optional[str] = None
1272
+ content: str
1273
+ dismissible: bool
1274
+ timestamp: int
1275
+
1276
+
1277
+ try:
1278
+ banners = json.loads(os.environ.get("WEBUI_BANNERS", "[]"))
1279
+ banners = [BannerModel(**banner) for banner in banners]
1280
+ except Exception as e:
1281
+ log.exception(f"Error loading WEBUI_BANNERS: {e}")
1282
+ banners = []
1283
+
1284
+ WEBUI_BANNERS = PersistentConfig("WEBUI_BANNERS", "ui.banners", banners)
1285
+
1286
+
1287
+ SHOW_ADMIN_DETAILS = PersistentConfig(
1288
+ "SHOW_ADMIN_DETAILS",
1289
+ "auth.admin.show",
1290
+ os.environ.get("SHOW_ADMIN_DETAILS", "true").lower() == "true",
1291
+ )
1292
+
1293
+ ADMIN_EMAIL = PersistentConfig(
1294
+ "ADMIN_EMAIL",
1295
+ "auth.admin.email",
1296
+ os.environ.get("ADMIN_EMAIL", None),
1297
+ )
1298
+
1299
+
1300
+ ####################################
1301
+ # TASKS
1302
+ ####################################
1303
+
1304
+
1305
+ TASK_MODEL = PersistentConfig(
1306
+ "TASK_MODEL",
1307
+ "task.model.default",
1308
+ os.environ.get("TASK_MODEL", ""),
1309
+ )
1310
+
1311
+ TASK_MODEL_EXTERNAL = PersistentConfig(
1312
+ "TASK_MODEL_EXTERNAL",
1313
+ "task.model.external",
1314
+ os.environ.get("TASK_MODEL_EXTERNAL", ""),
1315
+ )
1316
+
1317
+ TITLE_GENERATION_PROMPT_TEMPLATE = PersistentConfig(
1318
+ "TITLE_GENERATION_PROMPT_TEMPLATE",
1319
+ "task.title.prompt_template",
1320
+ os.environ.get("TITLE_GENERATION_PROMPT_TEMPLATE", ""),
1321
+ )
1322
+
1323
+ DEFAULT_TITLE_GENERATION_PROMPT_TEMPLATE = """### Task:
1324
+ Generate a concise, 3-5 word title with an emoji summarizing the chat history.
1325
+ ### Guidelines:
1326
+ - The title should clearly represent the main theme or subject of the conversation.
1327
+ - Use emojis that enhance understanding of the topic, but avoid quotation marks or special formatting.
1328
+ - Write the title in the chat's primary language; default to English if multilingual.
1329
+ - Prioritize accuracy over excessive creativity; keep it clear and simple.
1330
+ ### Output:
1331
+ JSON format: { "title": "your concise title here" }
1332
+ ### Examples:
1333
+ - { "title": "📉 Stock Market Trends" },
1334
+ - { "title": "🍪 Perfect Chocolate Chip Recipe" },
1335
+ - { "title": "Evolution of Music Streaming" },
1336
+ - { "title": "Remote Work Productivity Tips" },
1337
+ - { "title": "Artificial Intelligence in Healthcare" },
1338
+ - { "title": "🎮 Video Game Development Insights" }
1339
+ ### Chat History:
1340
+ <chat_history>
1341
+ {{MESSAGES:END:2}}
1342
+ </chat_history>"""
1343
+
1344
+ TAGS_GENERATION_PROMPT_TEMPLATE = PersistentConfig(
1345
+ "TAGS_GENERATION_PROMPT_TEMPLATE",
1346
+ "task.tags.prompt_template",
1347
+ os.environ.get("TAGS_GENERATION_PROMPT_TEMPLATE", ""),
1348
+ )
1349
+
1350
+ DEFAULT_TAGS_GENERATION_PROMPT_TEMPLATE = """### Task:
1351
+ Generate 1-3 broad tags categorizing the main themes of the chat history, along with 1-3 more specific subtopic tags.
1352
+
1353
+ ### Guidelines:
1354
+ - Start with high-level domains (e.g. Science, Technology, Philosophy, Arts, Politics, Business, Health, Sports, Entertainment, Education)
1355
+ - Consider including relevant subfields/subdomains if they are strongly represented throughout the conversation
1356
+ - If content is too short (less than 3 messages) or too diverse, use only ["General"]
1357
+ - Use the chat's primary language; default to English if multilingual
1358
+ - Prioritize accuracy over specificity
1359
+
1360
+ ### Output:
1361
+ JSON format: { "tags": ["tag1", "tag2", "tag3"] }
1362
+
1363
+ ### Chat History:
1364
+ <chat_history>
1365
+ {{MESSAGES:END:6}}
1366
+ </chat_history>"""
1367
+
1368
+ IMAGE_PROMPT_GENERATION_PROMPT_TEMPLATE = PersistentConfig(
1369
+ "IMAGE_PROMPT_GENERATION_PROMPT_TEMPLATE",
1370
+ "task.image.prompt_template",
1371
+ os.environ.get("IMAGE_PROMPT_GENERATION_PROMPT_TEMPLATE", ""),
1372
+ )
1373
+
1374
+ DEFAULT_IMAGE_PROMPT_GENERATION_PROMPT_TEMPLATE = """### Task:
1375
+ Generate a detailed prompt for am image generation task based on the given language and context. Describe the image as if you were explaining it to someone who cannot see it. Include relevant details, colors, shapes, and any other important elements.
1376
+
1377
+ ### Guidelines:
1378
+ - Be descriptive and detailed, focusing on the most important aspects of the image.
1379
+ - Avoid making assumptions or adding information not present in the image.
1380
+ - Use the chat's primary language; default to English if multilingual.
1381
+ - If the image is too complex, focus on the most prominent elements.
1382
+
1383
+ ### Output:
1384
+ Strictly return in JSON format:
1385
+ {
1386
+ "prompt": "Your detailed description here."
1387
+ }
1388
+
1389
+ ### Chat History:
1390
+ <chat_history>
1391
+ {{MESSAGES:END:6}}
1392
+ </chat_history>"""
1393
+
1394
+ ENABLE_TAGS_GENERATION = PersistentConfig(
1395
+ "ENABLE_TAGS_GENERATION",
1396
+ "task.tags.enable",
1397
+ os.environ.get("ENABLE_TAGS_GENERATION", "True").lower() == "true",
1398
+ )
1399
+
1400
+ ENABLE_TITLE_GENERATION = PersistentConfig(
1401
+ "ENABLE_TITLE_GENERATION",
1402
+ "task.title.enable",
1403
+ os.environ.get("ENABLE_TITLE_GENERATION", "True").lower() == "true",
1404
+ )
1405
+
1406
+
1407
+ ENABLE_SEARCH_QUERY_GENERATION = PersistentConfig(
1408
+ "ENABLE_SEARCH_QUERY_GENERATION",
1409
+ "task.query.search.enable",
1410
+ os.environ.get("ENABLE_SEARCH_QUERY_GENERATION", "True").lower() == "true",
1411
+ )
1412
+
1413
+ ENABLE_RETRIEVAL_QUERY_GENERATION = PersistentConfig(
1414
+ "ENABLE_RETRIEVAL_QUERY_GENERATION",
1415
+ "task.query.retrieval.enable",
1416
+ os.environ.get("ENABLE_RETRIEVAL_QUERY_GENERATION", "True").lower() == "true",
1417
+ )
1418
+
1419
+
1420
+ QUERY_GENERATION_PROMPT_TEMPLATE = PersistentConfig(
1421
+ "QUERY_GENERATION_PROMPT_TEMPLATE",
1422
+ "task.query.prompt_template",
1423
+ os.environ.get("QUERY_GENERATION_PROMPT_TEMPLATE", ""),
1424
+ )
1425
+
1426
+ DEFAULT_QUERY_GENERATION_PROMPT_TEMPLATE = """### Task:
1427
+ Analyze the chat history to determine the necessity of generating search queries, in the given language. By default, **prioritize generating 1-3 broad and relevant search queries** unless it is absolutely certain that no additional information is required. The aim is to retrieve comprehensive, updated, and valuable information even with minimal uncertainty. If no search is unequivocally needed, return an empty list.
1428
+
1429
+ ### Guidelines:
1430
+ - Respond **EXCLUSIVELY** with a JSON object. Any form of extra commentary, explanation, or additional text is strictly prohibited.
1431
+ - When generating search queries, respond in the format: { "queries": ["query1", "query2"] }, ensuring each query is distinct, concise, and relevant to the topic.
1432
+ - If and only if it is entirely certain that no useful results can be retrieved by a search, return: { "queries": [] }.
1433
+ - Err on the side of suggesting search queries if there is **any chance** they might provide useful or updated information.
1434
+ - Be concise and focused on composing high-quality search queries, avoiding unnecessary elaboration, commentary, or assumptions.
1435
+ - Today's date is: {{CURRENT_DATE}}.
1436
+ - Always prioritize providing actionable and broad queries that maximize informational coverage.
1437
+
1438
+ ### Output:
1439
+ Strictly return in JSON format:
1440
+ {
1441
+ "queries": ["query1", "query2"]
1442
+ }
1443
+
1444
+ ### Chat History:
1445
+ <chat_history>
1446
+ {{MESSAGES:END:6}}
1447
+ </chat_history>
1448
+ """
1449
+
1450
+ ENABLE_AUTOCOMPLETE_GENERATION = PersistentConfig(
1451
+ "ENABLE_AUTOCOMPLETE_GENERATION",
1452
+ "task.autocomplete.enable",
1453
+ os.environ.get("ENABLE_AUTOCOMPLETE_GENERATION", "False").lower() == "true",
1454
+ )
1455
+
1456
+ AUTOCOMPLETE_GENERATION_INPUT_MAX_LENGTH = PersistentConfig(
1457
+ "AUTOCOMPLETE_GENERATION_INPUT_MAX_LENGTH",
1458
+ "task.autocomplete.input_max_length",
1459
+ int(os.environ.get("AUTOCOMPLETE_GENERATION_INPUT_MAX_LENGTH", "-1")),
1460
+ )
1461
+
1462
+ AUTOCOMPLETE_GENERATION_PROMPT_TEMPLATE = PersistentConfig(
1463
+ "AUTOCOMPLETE_GENERATION_PROMPT_TEMPLATE",
1464
+ "task.autocomplete.prompt_template",
1465
+ os.environ.get("AUTOCOMPLETE_GENERATION_PROMPT_TEMPLATE", ""),
1466
+ )
1467
+
1468
+
1469
+ DEFAULT_AUTOCOMPLETE_GENERATION_PROMPT_TEMPLATE = """### Task:
1470
+ You are an autocompletion system. Continue the text in `<text>` based on the **completion type** in `<type>` and the given language.
1471
+
1472
+ ### **Instructions**:
1473
+ 1. Analyze `<text>` for context and meaning.
1474
+ 2. Use `<type>` to guide your output:
1475
+ - **General**: Provide a natural, concise continuation.
1476
+ - **Search Query**: Complete as if generating a realistic search query.
1477
+ 3. Start as if you are directly continuing `<text>`. Do **not** repeat, paraphrase, or respond as a model. Simply complete the text.
1478
+ 4. Ensure the continuation:
1479
+ - Flows naturally from `<text>`.
1480
+ - Avoids repetition, overexplaining, or unrelated ideas.
1481
+ 5. If unsure, return: `{ "text": "" }`.
1482
+
1483
+ ### **Output Rules**:
1484
+ - Respond only in JSON format: `{ "text": "<your_completion>" }`.
1485
+
1486
+ ### **Examples**:
1487
+ #### Example 1:
1488
+ Input:
1489
+ <type>General</type>
1490
+ <text>The sun was setting over the horizon, painting the sky</text>
1491
+ Output:
1492
+ { "text": "with vibrant shades of orange and pink." }
1493
+
1494
+ #### Example 2:
1495
+ Input:
1496
+ <type>Search Query</type>
1497
+ <text>Top-rated restaurants in</text>
1498
+ Output:
1499
+ { "text": "New York City for Italian cuisine." }
1500
+
1501
+ ---
1502
+ ### Context:
1503
+ <chat_history>
1504
+ {{MESSAGES:END:6}}
1505
+ </chat_history>
1506
+ <type>{{TYPE}}</type>
1507
+ <text>{{PROMPT}}</text>
1508
+ #### Output:
1509
+ """
1510
+
1511
+ TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = PersistentConfig(
1512
+ "TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE",
1513
+ "task.tools.prompt_template",
1514
+ os.environ.get("TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE", ""),
1515
+ )
1516
+
1517
+
1518
+ DEFAULT_TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE = """Available Tools: {{TOOLS}}
1519
+
1520
+ Your task is to choose and return the correct tool(s) from the list of available tools based on the query. Follow these guidelines:
1521
+
1522
+ - Return only the JSON object, without any additional text or explanation.
1523
+
1524
+ - If no tools match the query, return an empty array:
1525
+ {
1526
+ "tool_calls": []
1527
+ }
1528
+
1529
+ - If one or more tools match the query, construct a JSON response containing a "tool_calls" array with objects that include:
1530
+ - "name": The tool's name.
1531
+ - "parameters": A dictionary of required parameters and their corresponding values.
1532
+
1533
+ The format for the JSON response is strictly:
1534
+ {
1535
+ "tool_calls": [
1536
+ {"name": "toolName1", "parameters": {"key1": "value1"}},
1537
+ {"name": "toolName2", "parameters": {"key2": "value2"}}
1538
+ ]
1539
+ }"""
1540
+
1541
+
1542
+ DEFAULT_EMOJI_GENERATION_PROMPT_TEMPLATE = """Your task is to reflect the speaker's likely facial expression through a fitting emoji. Interpret emotions from the message and reflect their facial expression using fitting, diverse emojis (e.g., 😊, 😢, 😡, 😱).
1543
+
1544
+ Message: ```{{prompt}}```"""
1545
+
1546
+ DEFAULT_MOA_GENERATION_PROMPT_TEMPLATE = """You have been provided with a set of responses from various models to the latest user query: "{{prompt}}"
1547
+
1548
+ Your task is to synthesize these responses into a single, high-quality response. It is crucial to critically evaluate the information provided in these responses, recognizing that some of it may be biased or incorrect. Your response should not simply replicate the given answers but should offer a refined, accurate, and comprehensive reply to the instruction. Ensure your response is well-structured, coherent, and adheres to the highest standards of accuracy and reliability.
1549
+
1550
+ Responses from models: {{responses}}"""
1551
+
1552
+
1553
+ ####################################
1554
+ # Code Interpreter
1555
+ ####################################
1556
+
1557
+ ENABLE_CODE_EXECUTION = PersistentConfig(
1558
+ "ENABLE_CODE_EXECUTION",
1559
+ "code_execution.enable",
1560
+ os.environ.get("ENABLE_CODE_EXECUTION", "True").lower() == "true",
1561
+ )
1562
+
1563
+ CODE_EXECUTION_ENGINE = PersistentConfig(
1564
+ "CODE_EXECUTION_ENGINE",
1565
+ "code_execution.engine",
1566
+ os.environ.get("CODE_EXECUTION_ENGINE", "pyodide"),
1567
+ )
1568
+
1569
+ CODE_EXECUTION_JUPYTER_URL = PersistentConfig(
1570
+ "CODE_EXECUTION_JUPYTER_URL",
1571
+ "code_execution.jupyter.url",
1572
+ os.environ.get("CODE_EXECUTION_JUPYTER_URL", ""),
1573
+ )
1574
+
1575
+ CODE_EXECUTION_JUPYTER_AUTH = PersistentConfig(
1576
+ "CODE_EXECUTION_JUPYTER_AUTH",
1577
+ "code_execution.jupyter.auth",
1578
+ os.environ.get("CODE_EXECUTION_JUPYTER_AUTH", ""),
1579
+ )
1580
+
1581
+ CODE_EXECUTION_JUPYTER_AUTH_TOKEN = PersistentConfig(
1582
+ "CODE_EXECUTION_JUPYTER_AUTH_TOKEN",
1583
+ "code_execution.jupyter.auth_token",
1584
+ os.environ.get("CODE_EXECUTION_JUPYTER_AUTH_TOKEN", ""),
1585
+ )
1586
+
1587
+
1588
+ CODE_EXECUTION_JUPYTER_AUTH_PASSWORD = PersistentConfig(
1589
+ "CODE_EXECUTION_JUPYTER_AUTH_PASSWORD",
1590
+ "code_execution.jupyter.auth_password",
1591
+ os.environ.get("CODE_EXECUTION_JUPYTER_AUTH_PASSWORD", ""),
1592
+ )
1593
+
1594
+ CODE_EXECUTION_JUPYTER_TIMEOUT = PersistentConfig(
1595
+ "CODE_EXECUTION_JUPYTER_TIMEOUT",
1596
+ "code_execution.jupyter.timeout",
1597
+ int(os.environ.get("CODE_EXECUTION_JUPYTER_TIMEOUT", "60")),
1598
+ )
1599
+
1600
+ ENABLE_CODE_INTERPRETER = PersistentConfig(
1601
+ "ENABLE_CODE_INTERPRETER",
1602
+ "code_interpreter.enable",
1603
+ os.environ.get("ENABLE_CODE_INTERPRETER", "True").lower() == "true",
1604
+ )
1605
+
1606
+ CODE_INTERPRETER_ENGINE = PersistentConfig(
1607
+ "CODE_INTERPRETER_ENGINE",
1608
+ "code_interpreter.engine",
1609
+ os.environ.get("CODE_INTERPRETER_ENGINE", "pyodide"),
1610
+ )
1611
+
1612
+ CODE_INTERPRETER_PROMPT_TEMPLATE = PersistentConfig(
1613
+ "CODE_INTERPRETER_PROMPT_TEMPLATE",
1614
+ "code_interpreter.prompt_template",
1615
+ os.environ.get("CODE_INTERPRETER_PROMPT_TEMPLATE", ""),
1616
+ )
1617
+
1618
+ CODE_INTERPRETER_JUPYTER_URL = PersistentConfig(
1619
+ "CODE_INTERPRETER_JUPYTER_URL",
1620
+ "code_interpreter.jupyter.url",
1621
+ os.environ.get(
1622
+ "CODE_INTERPRETER_JUPYTER_URL", os.environ.get("CODE_EXECUTION_JUPYTER_URL", "")
1623
+ ),
1624
+ )
1625
+
1626
+ CODE_INTERPRETER_JUPYTER_AUTH = PersistentConfig(
1627
+ "CODE_INTERPRETER_JUPYTER_AUTH",
1628
+ "code_interpreter.jupyter.auth",
1629
+ os.environ.get(
1630
+ "CODE_INTERPRETER_JUPYTER_AUTH",
1631
+ os.environ.get("CODE_EXECUTION_JUPYTER_AUTH", ""),
1632
+ ),
1633
+ )
1634
+
1635
+ CODE_INTERPRETER_JUPYTER_AUTH_TOKEN = PersistentConfig(
1636
+ "CODE_INTERPRETER_JUPYTER_AUTH_TOKEN",
1637
+ "code_interpreter.jupyter.auth_token",
1638
+ os.environ.get(
1639
+ "CODE_INTERPRETER_JUPYTER_AUTH_TOKEN",
1640
+ os.environ.get("CODE_EXECUTION_JUPYTER_AUTH_TOKEN", ""),
1641
+ ),
1642
+ )
1643
+
1644
+
1645
+ CODE_INTERPRETER_JUPYTER_AUTH_PASSWORD = PersistentConfig(
1646
+ "CODE_INTERPRETER_JUPYTER_AUTH_PASSWORD",
1647
+ "code_interpreter.jupyter.auth_password",
1648
+ os.environ.get(
1649
+ "CODE_INTERPRETER_JUPYTER_AUTH_PASSWORD",
1650
+ os.environ.get("CODE_EXECUTION_JUPYTER_AUTH_PASSWORD", ""),
1651
+ ),
1652
+ )
1653
+
1654
+ CODE_INTERPRETER_JUPYTER_TIMEOUT = PersistentConfig(
1655
+ "CODE_INTERPRETER_JUPYTER_TIMEOUT",
1656
+ "code_interpreter.jupyter.timeout",
1657
+ int(
1658
+ os.environ.get(
1659
+ "CODE_INTERPRETER_JUPYTER_TIMEOUT",
1660
+ os.environ.get("CODE_EXECUTION_JUPYTER_TIMEOUT", "60"),
1661
+ )
1662
+ ),
1663
+ )
1664
+
1665
+
1666
+ DEFAULT_CODE_INTERPRETER_PROMPT = """
1667
+ #### Tools Available
1668
+
1669
+ 1. **Code Interpreter**: `<code_interpreter type="code" lang="python"></code_interpreter>`
1670
+ - You have access to a Python shell that runs directly in the user's browser, enabling fast execution of code for analysis, calculations, or problem-solving. Use it in this response.
1671
+ - The Python code you write can incorporate a wide array of libraries, handle data manipulation or visualization, perform API calls for web-related tasks, or tackle virtually any computational challenge. Use this flexibility to **think outside the box, craft elegant solutions, and harness Python's full potential**.
1672
+ - To use it, **you must enclose your code within `<code_interpreter type="code" lang="python">` XML tags** and stop right away. If you don't, the code won't execute. Do NOT use triple backticks.
1673
+ - When coding, **always aim to print meaningful outputs** (e.g., results, tables, summaries, or visuals) to better interpret and verify the findings. Avoid relying on implicit outputs; prioritize explicit and clear print statements so the results are effectively communicated to the user.
1674
+ - After obtaining the printed output, **always provide a concise analysis, interpretation, or next steps to help the user understand the findings or refine the outcome further.**
1675
+ - If the results are unclear, unexpected, or require validation, refine the code and execute it again as needed. Always aim to deliver meaningful insights from the results, iterating if necessary.
1676
+ - **If a link to an image, audio, or any file is provided in markdown format in the output, ALWAYS regurgitate word for word, explicitly display it as part of the response to ensure the user can access it easily, do NOT change the link.**
1677
+ - All responses should be communicated in the chat's primary language, ensuring seamless understanding. If the chat is multilingual, default to English for clarity.
1678
+
1679
+ Ensure that the tools are effectively utilized to achieve the highest-quality analysis for the user."""
1680
+
1681
+
1682
+ ####################################
1683
+ # Vector Database
1684
+ ####################################
1685
+
1686
+ VECTOR_DB = os.environ.get("VECTOR_DB", "chroma")
1687
+
1688
+ # Chroma
1689
+ CHROMA_DATA_PATH = f"{DATA_DIR}/vector_db"
1690
+
1691
+ if VECTOR_DB == "chroma":
1692
+ import chromadb
1693
+
1694
+ CHROMA_TENANT = os.environ.get("CHROMA_TENANT", chromadb.DEFAULT_TENANT)
1695
+ CHROMA_DATABASE = os.environ.get("CHROMA_DATABASE", chromadb.DEFAULT_DATABASE)
1696
+ CHROMA_HTTP_HOST = os.environ.get("CHROMA_HTTP_HOST", "")
1697
+ CHROMA_HTTP_PORT = int(os.environ.get("CHROMA_HTTP_PORT", "8000"))
1698
+ CHROMA_CLIENT_AUTH_PROVIDER = os.environ.get("CHROMA_CLIENT_AUTH_PROVIDER", "")
1699
+ CHROMA_CLIENT_AUTH_CREDENTIALS = os.environ.get(
1700
+ "CHROMA_CLIENT_AUTH_CREDENTIALS", ""
1701
+ )
1702
+ # Comma-separated list of header=value pairs
1703
+ CHROMA_HTTP_HEADERS = os.environ.get("CHROMA_HTTP_HEADERS", "")
1704
+ if CHROMA_HTTP_HEADERS:
1705
+ CHROMA_HTTP_HEADERS = dict(
1706
+ [pair.split("=") for pair in CHROMA_HTTP_HEADERS.split(",")]
1707
+ )
1708
+ else:
1709
+ CHROMA_HTTP_HEADERS = None
1710
+ CHROMA_HTTP_SSL = os.environ.get("CHROMA_HTTP_SSL", "false").lower() == "true"
1711
+ # this uses the model defined in the Dockerfile ENV variable. If you dont use docker or docker based deployments such as k8s, the default embedding model will be used (sentence-transformers/all-MiniLM-L6-v2)
1712
+
1713
+ # Milvus
1714
+
1715
+ MILVUS_URI = os.environ.get("MILVUS_URI", f"{DATA_DIR}/vector_db/milvus.db")
1716
+ MILVUS_DB = os.environ.get("MILVUS_DB", "default")
1717
+ MILVUS_TOKEN = os.environ.get("MILVUS_TOKEN", None)
1718
+
1719
+ # Qdrant
1720
+ QDRANT_URI = os.environ.get("QDRANT_URI", None)
1721
+ QDRANT_API_KEY = os.environ.get("QDRANT_API_KEY", None)
1722
+ QDRANT_ON_DISK = os.environ.get("QDRANT_ON_DISK", "false").lower() == "true"
1723
+ QDRANT_PREFER_GRPC = os.environ.get("QDRANT_PREFER_GRPC", "False").lower() == "true"
1724
+ QDRANT_GRPC_PORT = int(os.environ.get("QDRANT_GRPC_PORT", "6334"))
1725
+
1726
+ # OpenSearch
1727
+ OPENSEARCH_URI = os.environ.get("OPENSEARCH_URI", "https://localhost:9200")
1728
+ OPENSEARCH_SSL = os.environ.get("OPENSEARCH_SSL", "true").lower() == "true"
1729
+ OPENSEARCH_CERT_VERIFY = (
1730
+ os.environ.get("OPENSEARCH_CERT_VERIFY", "false").lower() == "true"
1731
+ )
1732
+ OPENSEARCH_USERNAME = os.environ.get("OPENSEARCH_USERNAME", None)
1733
+ OPENSEARCH_PASSWORD = os.environ.get("OPENSEARCH_PASSWORD", None)
1734
+
1735
+ # ElasticSearch
1736
+ ELASTICSEARCH_URL = os.environ.get("ELASTICSEARCH_URL", "https://localhost:9200")
1737
+ ELASTICSEARCH_CA_CERTS = os.environ.get("ELASTICSEARCH_CA_CERTS", None)
1738
+ ELASTICSEARCH_API_KEY = os.environ.get("ELASTICSEARCH_API_KEY", None)
1739
+ ELASTICSEARCH_USERNAME = os.environ.get("ELASTICSEARCH_USERNAME", None)
1740
+ ELASTICSEARCH_PASSWORD = os.environ.get("ELASTICSEARCH_PASSWORD", None)
1741
+ ELASTICSEARCH_CLOUD_ID = os.environ.get("ELASTICSEARCH_CLOUD_ID", None)
1742
+ SSL_ASSERT_FINGERPRINT = os.environ.get("SSL_ASSERT_FINGERPRINT", None)
1743
+ ELASTICSEARCH_INDEX_PREFIX = os.environ.get(
1744
+ "ELASTICSEARCH_INDEX_PREFIX", "open_webui_collections"
1745
+ )
1746
+ # Pgvector
1747
+ PGVECTOR_DB_URL = os.environ.get("PGVECTOR_DB_URL", DATABASE_URL)
1748
+ if VECTOR_DB == "pgvector" and not PGVECTOR_DB_URL.startswith("postgres"):
1749
+ raise ValueError(
1750
+ "Pgvector requires setting PGVECTOR_DB_URL or using Postgres with vector extension as the primary database."
1751
+ )
1752
+ PGVECTOR_INITIALIZE_MAX_VECTOR_LENGTH = int(
1753
+ os.environ.get("PGVECTOR_INITIALIZE_MAX_VECTOR_LENGTH", "1536")
1754
+ )
1755
+
1756
+ # Pinecone
1757
+ PINECONE_API_KEY = os.environ.get("PINECONE_API_KEY", None)
1758
+ PINECONE_ENVIRONMENT = os.environ.get("PINECONE_ENVIRONMENT", None)
1759
+ PINECONE_INDEX_NAME = os.getenv("PINECONE_INDEX_NAME", "open-webui-index")
1760
+ PINECONE_DIMENSION = int(os.getenv("PINECONE_DIMENSION", 1536)) # or 3072, 1024, 768
1761
+ PINECONE_METRIC = os.getenv("PINECONE_METRIC", "cosine")
1762
+ PINECONE_CLOUD = os.getenv("PINECONE_CLOUD", "aws") # or "gcp" or "azure"
1763
+
1764
+ ####################################
1765
+ # Information Retrieval (RAG)
1766
+ ####################################
1767
+
1768
+
1769
+ # If configured, Google Drive will be available as an upload option.
1770
+ ENABLE_GOOGLE_DRIVE_INTEGRATION = PersistentConfig(
1771
+ "ENABLE_GOOGLE_DRIVE_INTEGRATION",
1772
+ "google_drive.enable",
1773
+ os.getenv("ENABLE_GOOGLE_DRIVE_INTEGRATION", "False").lower() == "true",
1774
+ )
1775
+
1776
+ GOOGLE_DRIVE_CLIENT_ID = PersistentConfig(
1777
+ "GOOGLE_DRIVE_CLIENT_ID",
1778
+ "google_drive.client_id",
1779
+ os.environ.get("GOOGLE_DRIVE_CLIENT_ID", ""),
1780
+ )
1781
+
1782
+ GOOGLE_DRIVE_API_KEY = PersistentConfig(
1783
+ "GOOGLE_DRIVE_API_KEY",
1784
+ "google_drive.api_key",
1785
+ os.environ.get("GOOGLE_DRIVE_API_KEY", ""),
1786
+ )
1787
+
1788
+ ENABLE_ONEDRIVE_INTEGRATION = PersistentConfig(
1789
+ "ENABLE_ONEDRIVE_INTEGRATION",
1790
+ "onedrive.enable",
1791
+ os.getenv("ENABLE_ONEDRIVE_INTEGRATION", "False").lower() == "true",
1792
+ )
1793
+
1794
+ ONEDRIVE_CLIENT_ID = PersistentConfig(
1795
+ "ONEDRIVE_CLIENT_ID",
1796
+ "onedrive.client_id",
1797
+ os.environ.get("ONEDRIVE_CLIENT_ID", ""),
1798
+ )
1799
+
1800
+ ONEDRIVE_SHAREPOINT_URL = PersistentConfig(
1801
+ "ONEDRIVE_SHAREPOINT_URL",
1802
+ "onedrive.sharepoint_url",
1803
+ os.environ.get("ONEDRIVE_SHAREPOINT_URL", ""),
1804
+ )
1805
+
1806
+
1807
+ # RAG Content Extraction
1808
+ CONTENT_EXTRACTION_ENGINE = PersistentConfig(
1809
+ "CONTENT_EXTRACTION_ENGINE",
1810
+ "rag.CONTENT_EXTRACTION_ENGINE",
1811
+ os.environ.get("CONTENT_EXTRACTION_ENGINE", "").lower(),
1812
+ )
1813
+
1814
+ TIKA_SERVER_URL = PersistentConfig(
1815
+ "TIKA_SERVER_URL",
1816
+ "rag.tika_server_url",
1817
+ os.getenv("TIKA_SERVER_URL", "http://tika:9998"), # Default for sidecar deployment
1818
+ )
1819
+
1820
+ DOCLING_SERVER_URL = PersistentConfig(
1821
+ "DOCLING_SERVER_URL",
1822
+ "rag.docling_server_url",
1823
+ os.getenv("DOCLING_SERVER_URL", "http://docling:5001"),
1824
+ )
1825
+
1826
+ DOCUMENT_INTELLIGENCE_ENDPOINT = PersistentConfig(
1827
+ "DOCUMENT_INTELLIGENCE_ENDPOINT",
1828
+ "rag.document_intelligence_endpoint",
1829
+ os.getenv("DOCUMENT_INTELLIGENCE_ENDPOINT", ""),
1830
+ )
1831
+
1832
+ DOCUMENT_INTELLIGENCE_KEY = PersistentConfig(
1833
+ "DOCUMENT_INTELLIGENCE_KEY",
1834
+ "rag.document_intelligence_key",
1835
+ os.getenv("DOCUMENT_INTELLIGENCE_KEY", ""),
1836
+ )
1837
+
1838
+ MISTRAL_OCR_API_KEY = PersistentConfig(
1839
+ "MISTRAL_OCR_API_KEY",
1840
+ "rag.mistral_ocr_api_key",
1841
+ os.getenv("MISTRAL_OCR_API_KEY", ""),
1842
+ )
1843
+
1844
+ BYPASS_EMBEDDING_AND_RETRIEVAL = PersistentConfig(
1845
+ "BYPASS_EMBEDDING_AND_RETRIEVAL",
1846
+ "rag.bypass_embedding_and_retrieval",
1847
+ os.environ.get("BYPASS_EMBEDDING_AND_RETRIEVAL", "False").lower() == "true",
1848
+ )
1849
+
1850
+
1851
+ RAG_TOP_K = PersistentConfig(
1852
+ "RAG_TOP_K", "rag.top_k", int(os.environ.get("RAG_TOP_K", "3"))
1853
+ )
1854
+ RAG_TOP_K_RERANKER = PersistentConfig(
1855
+ "RAG_TOP_K_RERANKER",
1856
+ "rag.top_k_reranker",
1857
+ int(os.environ.get("RAG_TOP_K_RERANKER", "3")),
1858
+ )
1859
+ RAG_RELEVANCE_THRESHOLD = PersistentConfig(
1860
+ "RAG_RELEVANCE_THRESHOLD",
1861
+ "rag.relevance_threshold",
1862
+ float(os.environ.get("RAG_RELEVANCE_THRESHOLD", "0.0")),
1863
+ )
1864
+
1865
+ ENABLE_RAG_HYBRID_SEARCH = PersistentConfig(
1866
+ "ENABLE_RAG_HYBRID_SEARCH",
1867
+ "rag.enable_hybrid_search",
1868
+ os.environ.get("ENABLE_RAG_HYBRID_SEARCH", "").lower() == "true",
1869
+ )
1870
+
1871
+ RAG_FULL_CONTEXT = PersistentConfig(
1872
+ "RAG_FULL_CONTEXT",
1873
+ "rag.full_context",
1874
+ os.getenv("RAG_FULL_CONTEXT", "False").lower() == "true",
1875
+ )
1876
+
1877
+ RAG_FILE_MAX_COUNT = PersistentConfig(
1878
+ "RAG_FILE_MAX_COUNT",
1879
+ "rag.file.max_count",
1880
+ (
1881
+ int(os.environ.get("RAG_FILE_MAX_COUNT"))
1882
+ if os.environ.get("RAG_FILE_MAX_COUNT")
1883
+ else None
1884
+ ),
1885
+ )
1886
+
1887
+ RAG_FILE_MAX_SIZE = PersistentConfig(
1888
+ "RAG_FILE_MAX_SIZE",
1889
+ "rag.file.max_size",
1890
+ (
1891
+ int(os.environ.get("RAG_FILE_MAX_SIZE"))
1892
+ if os.environ.get("RAG_FILE_MAX_SIZE")
1893
+ else None
1894
+ ),
1895
+ )
1896
+
1897
+ RAG_EMBEDDING_ENGINE = PersistentConfig(
1898
+ "RAG_EMBEDDING_ENGINE",
1899
+ "rag.embedding_engine",
1900
+ os.environ.get("RAG_EMBEDDING_ENGINE", ""),
1901
+ )
1902
+
1903
+ PDF_EXTRACT_IMAGES = PersistentConfig(
1904
+ "PDF_EXTRACT_IMAGES",
1905
+ "rag.pdf_extract_images",
1906
+ os.environ.get("PDF_EXTRACT_IMAGES", "False").lower() == "true",
1907
+ )
1908
+
1909
+ RAG_EMBEDDING_MODEL = PersistentConfig(
1910
+ "RAG_EMBEDDING_MODEL",
1911
+ "rag.embedding_model",
1912
+ os.environ.get("RAG_EMBEDDING_MODEL", "sentence-transformers/all-MiniLM-L6-v2"),
1913
+ )
1914
+ log.info(f"Embedding model set: {RAG_EMBEDDING_MODEL.value}")
1915
+
1916
+ RAG_EMBEDDING_MODEL_AUTO_UPDATE = (
1917
+ not OFFLINE_MODE
1918
+ and os.environ.get("RAG_EMBEDDING_MODEL_AUTO_UPDATE", "True").lower() == "true"
1919
+ )
1920
+
1921
+ RAG_EMBEDDING_MODEL_TRUST_REMOTE_CODE = (
1922
+ os.environ.get("RAG_EMBEDDING_MODEL_TRUST_REMOTE_CODE", "True").lower() == "true"
1923
+ )
1924
+
1925
+ RAG_EMBEDDING_BATCH_SIZE = PersistentConfig(
1926
+ "RAG_EMBEDDING_BATCH_SIZE",
1927
+ "rag.embedding_batch_size",
1928
+ int(
1929
+ os.environ.get("RAG_EMBEDDING_BATCH_SIZE")
1930
+ or os.environ.get("RAG_EMBEDDING_OPENAI_BATCH_SIZE", "1")
1931
+ ),
1932
+ )
1933
+
1934
+ RAG_EMBEDDING_QUERY_PREFIX = os.environ.get("RAG_EMBEDDING_QUERY_PREFIX", None)
1935
+
1936
+ RAG_EMBEDDING_CONTENT_PREFIX = os.environ.get("RAG_EMBEDDING_CONTENT_PREFIX", None)
1937
+
1938
+ RAG_EMBEDDING_PREFIX_FIELD_NAME = os.environ.get(
1939
+ "RAG_EMBEDDING_PREFIX_FIELD_NAME", None
1940
+ )
1941
+
1942
+ RAG_RERANKING_MODEL = PersistentConfig(
1943
+ "RAG_RERANKING_MODEL",
1944
+ "rag.reranking_model",
1945
+ os.environ.get("RAG_RERANKING_MODEL", ""),
1946
+ )
1947
+ if RAG_RERANKING_MODEL.value != "":
1948
+ log.info(f"Reranking model set: {RAG_RERANKING_MODEL.value}")
1949
+
1950
+ RAG_RERANKING_MODEL_AUTO_UPDATE = (
1951
+ not OFFLINE_MODE
1952
+ and os.environ.get("RAG_RERANKING_MODEL_AUTO_UPDATE", "True").lower() == "true"
1953
+ )
1954
+
1955
+ RAG_RERANKING_MODEL_TRUST_REMOTE_CODE = (
1956
+ os.environ.get("RAG_RERANKING_MODEL_TRUST_REMOTE_CODE", "True").lower() == "true"
1957
+ )
1958
+
1959
+
1960
+ RAG_TEXT_SPLITTER = PersistentConfig(
1961
+ "RAG_TEXT_SPLITTER",
1962
+ "rag.text_splitter",
1963
+ os.environ.get("RAG_TEXT_SPLITTER", ""),
1964
+ )
1965
+
1966
+
1967
+ TIKTOKEN_CACHE_DIR = os.environ.get("TIKTOKEN_CACHE_DIR", f"{CACHE_DIR}/tiktoken")
1968
+ TIKTOKEN_ENCODING_NAME = PersistentConfig(
1969
+ "TIKTOKEN_ENCODING_NAME",
1970
+ "rag.tiktoken_encoding_name",
1971
+ os.environ.get("TIKTOKEN_ENCODING_NAME", "cl100k_base"),
1972
+ )
1973
+
1974
+
1975
+ CHUNK_SIZE = PersistentConfig(
1976
+ "CHUNK_SIZE", "rag.chunk_size", int(os.environ.get("CHUNK_SIZE", "1000"))
1977
+ )
1978
+ CHUNK_OVERLAP = PersistentConfig(
1979
+ "CHUNK_OVERLAP",
1980
+ "rag.chunk_overlap",
1981
+ int(os.environ.get("CHUNK_OVERLAP", "100")),
1982
+ )
1983
+
1984
+ DEFAULT_RAG_TEMPLATE = """### Task:
1985
+ Respond to the user query using the provided context, incorporating inline citations in the format [id] **only when the <source> tag includes an explicit id attribute** (e.g., <source id="1">).
1986
+
1987
+ ### Guidelines:
1988
+ - If you don't know the answer, clearly state that.
1989
+ - If uncertain, ask the user for clarification.
1990
+ - Respond in the same language as the user's query.
1991
+ - If the context is unreadable or of poor quality, inform the user and provide the best possible answer.
1992
+ - If the answer isn't present in the context but you possess the knowledge, explain this to the user and provide the answer using your own understanding.
1993
+ - **Only include inline citations using [id] (e.g., [1], [2]) when the <source> tag includes an id attribute.**
1994
+ - Do not cite if the <source> tag does not contain an id attribute.
1995
+ - Do not use XML tags in your response.
1996
+ - Ensure citations are concise and directly related to the information provided.
1997
+
1998
+ ### Example of Citation:
1999
+ If the user asks about a specific topic and the information is found in a source with a provided id attribute, the response should include the citation like in the following example:
2000
+ * "According to the study, the proposed method increases efficiency by 20% [1]."
2001
+
2002
+ ### Output:
2003
+ Provide a clear and direct response to the user's query, including inline citations in the format [id] only when the <source> tag with id attribute is present in the context.
2004
+
2005
+ <context>
2006
+ {{CONTEXT}}
2007
+ </context>
2008
+
2009
+ <user_query>
2010
+ {{QUERY}}
2011
+ </user_query>
2012
+ """
2013
+
2014
+ RAG_TEMPLATE = PersistentConfig(
2015
+ "RAG_TEMPLATE",
2016
+ "rag.template",
2017
+ os.environ.get("RAG_TEMPLATE", DEFAULT_RAG_TEMPLATE),
2018
+ )
2019
+
2020
+ RAG_OPENAI_API_BASE_URL = PersistentConfig(
2021
+ "RAG_OPENAI_API_BASE_URL",
2022
+ "rag.openai_api_base_url",
2023
+ os.getenv("RAG_OPENAI_API_BASE_URL", OPENAI_API_BASE_URL),
2024
+ )
2025
+ RAG_OPENAI_API_KEY = PersistentConfig(
2026
+ "RAG_OPENAI_API_KEY",
2027
+ "rag.openai_api_key",
2028
+ os.getenv("RAG_OPENAI_API_KEY", OPENAI_API_KEY),
2029
+ )
2030
+
2031
+ RAG_OLLAMA_BASE_URL = PersistentConfig(
2032
+ "RAG_OLLAMA_BASE_URL",
2033
+ "rag.ollama.url",
2034
+ os.getenv("RAG_OLLAMA_BASE_URL", OLLAMA_BASE_URL),
2035
+ )
2036
+
2037
+ RAG_OLLAMA_API_KEY = PersistentConfig(
2038
+ "RAG_OLLAMA_API_KEY",
2039
+ "rag.ollama.key",
2040
+ os.getenv("RAG_OLLAMA_API_KEY", ""),
2041
+ )
2042
+
2043
+
2044
+ ENABLE_RAG_LOCAL_WEB_FETCH = (
2045
+ os.getenv("ENABLE_RAG_LOCAL_WEB_FETCH", "False").lower() == "true"
2046
+ )
2047
+
2048
+ YOUTUBE_LOADER_LANGUAGE = PersistentConfig(
2049
+ "YOUTUBE_LOADER_LANGUAGE",
2050
+ "rag.youtube_loader_language",
2051
+ os.getenv("YOUTUBE_LOADER_LANGUAGE", "en").split(","),
2052
+ )
2053
+
2054
+ YOUTUBE_LOADER_PROXY_URL = PersistentConfig(
2055
+ "YOUTUBE_LOADER_PROXY_URL",
2056
+ "rag.youtube_loader_proxy_url",
2057
+ os.getenv("YOUTUBE_LOADER_PROXY_URL", ""),
2058
+ )
2059
+
2060
+
2061
+ ####################################
2062
+ # Web Search (RAG)
2063
+ ####################################
2064
+
2065
+ ENABLE_WEB_SEARCH = PersistentConfig(
2066
+ "ENABLE_WEB_SEARCH",
2067
+ "rag.web.search.enable",
2068
+ os.getenv("ENABLE_WEB_SEARCH", "False").lower() == "true",
2069
+ )
2070
+
2071
+ WEB_SEARCH_ENGINE = PersistentConfig(
2072
+ "WEB_SEARCH_ENGINE",
2073
+ "rag.web.search.engine",
2074
+ os.getenv("WEB_SEARCH_ENGINE", ""),
2075
+ )
2076
+
2077
+ BYPASS_WEB_SEARCH_EMBEDDING_AND_RETRIEVAL = PersistentConfig(
2078
+ "BYPASS_WEB_SEARCH_EMBEDDING_AND_RETRIEVAL",
2079
+ "rag.web.search.bypass_embedding_and_retrieval",
2080
+ os.getenv("BYPASS_WEB_SEARCH_EMBEDDING_AND_RETRIEVAL", "False").lower() == "true",
2081
+ )
2082
+
2083
+
2084
+ WEB_SEARCH_RESULT_COUNT = PersistentConfig(
2085
+ "WEB_SEARCH_RESULT_COUNT",
2086
+ "rag.web.search.result_count",
2087
+ int(os.getenv("WEB_SEARCH_RESULT_COUNT", "3")),
2088
+ )
2089
+
2090
+
2091
+ # You can provide a list of your own websites to filter after performing a web search.
2092
+ # This ensures the highest level of safety and reliability of the information sources.
2093
+ WEB_SEARCH_DOMAIN_FILTER_LIST = PersistentConfig(
2094
+ "WEB_SEARCH_DOMAIN_FILTER_LIST",
2095
+ "rag.web.search.domain.filter_list",
2096
+ [
2097
+ # "wikipedia.com",
2098
+ # "wikimedia.org",
2099
+ # "wikidata.org",
2100
+ ],
2101
+ )
2102
+
2103
+ WEB_SEARCH_CONCURRENT_REQUESTS = PersistentConfig(
2104
+ "WEB_SEARCH_CONCURRENT_REQUESTS",
2105
+ "rag.web.search.concurrent_requests",
2106
+ int(os.getenv("WEB_SEARCH_CONCURRENT_REQUESTS", "10")),
2107
+ )
2108
+
2109
+ WEB_LOADER_ENGINE = PersistentConfig(
2110
+ "WEB_LOADER_ENGINE",
2111
+ "rag.web.loader.engine",
2112
+ os.environ.get("WEB_LOADER_ENGINE", ""),
2113
+ )
2114
+
2115
+ ENABLE_WEB_LOADER_SSL_VERIFICATION = PersistentConfig(
2116
+ "ENABLE_WEB_LOADER_SSL_VERIFICATION",
2117
+ "rag.web.loader.ssl_verification",
2118
+ os.environ.get("ENABLE_WEB_LOADER_SSL_VERIFICATION", "True").lower() == "true",
2119
+ )
2120
+
2121
+ WEB_SEARCH_TRUST_ENV = PersistentConfig(
2122
+ "WEB_SEARCH_TRUST_ENV",
2123
+ "rag.web.search.trust_env",
2124
+ os.getenv("WEB_SEARCH_TRUST_ENV", "False").lower() == "true",
2125
+ )
2126
+
2127
+
2128
+ SEARXNG_QUERY_URL = PersistentConfig(
2129
+ "SEARXNG_QUERY_URL",
2130
+ "rag.web.search.searxng_query_url",
2131
+ os.getenv("SEARXNG_QUERY_URL", ""),
2132
+ )
2133
+
2134
+ GOOGLE_PSE_API_KEY = PersistentConfig(
2135
+ "GOOGLE_PSE_API_KEY",
2136
+ "rag.web.search.google_pse_api_key",
2137
+ os.getenv("GOOGLE_PSE_API_KEY", ""),
2138
+ )
2139
+
2140
+ GOOGLE_PSE_ENGINE_ID = PersistentConfig(
2141
+ "GOOGLE_PSE_ENGINE_ID",
2142
+ "rag.web.search.google_pse_engine_id",
2143
+ os.getenv("GOOGLE_PSE_ENGINE_ID", ""),
2144
+ )
2145
+
2146
+ BRAVE_SEARCH_API_KEY = PersistentConfig(
2147
+ "BRAVE_SEARCH_API_KEY",
2148
+ "rag.web.search.brave_search_api_key",
2149
+ os.getenv("BRAVE_SEARCH_API_KEY", ""),
2150
+ )
2151
+
2152
+ KAGI_SEARCH_API_KEY = PersistentConfig(
2153
+ "KAGI_SEARCH_API_KEY",
2154
+ "rag.web.search.kagi_search_api_key",
2155
+ os.getenv("KAGI_SEARCH_API_KEY", ""),
2156
+ )
2157
+
2158
+ MOJEEK_SEARCH_API_KEY = PersistentConfig(
2159
+ "MOJEEK_SEARCH_API_KEY",
2160
+ "rag.web.search.mojeek_search_api_key",
2161
+ os.getenv("MOJEEK_SEARCH_API_KEY", ""),
2162
+ )
2163
+
2164
+ BOCHA_SEARCH_API_KEY = PersistentConfig(
2165
+ "BOCHA_SEARCH_API_KEY",
2166
+ "rag.web.search.bocha_search_api_key",
2167
+ os.getenv("BOCHA_SEARCH_API_KEY", ""),
2168
+ )
2169
+
2170
+ SERPSTACK_API_KEY = PersistentConfig(
2171
+ "SERPSTACK_API_KEY",
2172
+ "rag.web.search.serpstack_api_key",
2173
+ os.getenv("SERPSTACK_API_KEY", ""),
2174
+ )
2175
+
2176
+ SERPSTACK_HTTPS = PersistentConfig(
2177
+ "SERPSTACK_HTTPS",
2178
+ "rag.web.search.serpstack_https",
2179
+ os.getenv("SERPSTACK_HTTPS", "True").lower() == "true",
2180
+ )
2181
+
2182
+ SERPER_API_KEY = PersistentConfig(
2183
+ "SERPER_API_KEY",
2184
+ "rag.web.search.serper_api_key",
2185
+ os.getenv("SERPER_API_KEY", ""),
2186
+ )
2187
+
2188
+ SERPLY_API_KEY = PersistentConfig(
2189
+ "SERPLY_API_KEY",
2190
+ "rag.web.search.serply_api_key",
2191
+ os.getenv("SERPLY_API_KEY", ""),
2192
+ )
2193
+
2194
+ JINA_API_KEY = PersistentConfig(
2195
+ "JINA_API_KEY",
2196
+ "rag.web.search.jina_api_key",
2197
+ os.getenv("JINA_API_KEY", ""),
2198
+ )
2199
+
2200
+ SEARCHAPI_API_KEY = PersistentConfig(
2201
+ "SEARCHAPI_API_KEY",
2202
+ "rag.web.search.searchapi_api_key",
2203
+ os.getenv("SEARCHAPI_API_KEY", ""),
2204
+ )
2205
+
2206
+ SEARCHAPI_ENGINE = PersistentConfig(
2207
+ "SEARCHAPI_ENGINE",
2208
+ "rag.web.search.searchapi_engine",
2209
+ os.getenv("SEARCHAPI_ENGINE", ""),
2210
+ )
2211
+
2212
+ SERPAPI_API_KEY = PersistentConfig(
2213
+ "SERPAPI_API_KEY",
2214
+ "rag.web.search.serpapi_api_key",
2215
+ os.getenv("SERPAPI_API_KEY", ""),
2216
+ )
2217
+
2218
+ SERPAPI_ENGINE = PersistentConfig(
2219
+ "SERPAPI_ENGINE",
2220
+ "rag.web.search.serpapi_engine",
2221
+ os.getenv("SERPAPI_ENGINE", ""),
2222
+ )
2223
+
2224
+ BING_SEARCH_V7_ENDPOINT = PersistentConfig(
2225
+ "BING_SEARCH_V7_ENDPOINT",
2226
+ "rag.web.search.bing_search_v7_endpoint",
2227
+ os.environ.get(
2228
+ "BING_SEARCH_V7_ENDPOINT", "https://api.bing.microsoft.com/v7.0/search"
2229
+ ),
2230
+ )
2231
+
2232
+ BING_SEARCH_V7_SUBSCRIPTION_KEY = PersistentConfig(
2233
+ "BING_SEARCH_V7_SUBSCRIPTION_KEY",
2234
+ "rag.web.search.bing_search_v7_subscription_key",
2235
+ os.environ.get("BING_SEARCH_V7_SUBSCRIPTION_KEY", ""),
2236
+ )
2237
+
2238
+ EXA_API_KEY = PersistentConfig(
2239
+ "EXA_API_KEY",
2240
+ "rag.web.search.exa_api_key",
2241
+ os.getenv("EXA_API_KEY", ""),
2242
+ )
2243
+
2244
+ PERPLEXITY_API_KEY = PersistentConfig(
2245
+ "PERPLEXITY_API_KEY",
2246
+ "rag.web.search.perplexity_api_key",
2247
+ os.getenv("PERPLEXITY_API_KEY", ""),
2248
+ )
2249
+
2250
+ SOUGOU_API_SID = PersistentConfig(
2251
+ "SOUGOU_API_SID",
2252
+ "rag.web.search.sougou_api_sid",
2253
+ os.getenv("SOUGOU_API_SID", ""),
2254
+ )
2255
+
2256
+ SOUGOU_API_SK = PersistentConfig(
2257
+ "SOUGOU_API_SK",
2258
+ "rag.web.search.sougou_api_sk",
2259
+ os.getenv("SOUGOU_API_SK", ""),
2260
+ )
2261
+
2262
+ TAVILY_API_KEY = PersistentConfig(
2263
+ "TAVILY_API_KEY",
2264
+ "rag.web.search.tavily_api_key",
2265
+ os.getenv("TAVILY_API_KEY", ""),
2266
+ )
2267
+
2268
+ TAVILY_EXTRACT_DEPTH = PersistentConfig(
2269
+ "TAVILY_EXTRACT_DEPTH",
2270
+ "rag.web.search.tavily_extract_depth",
2271
+ os.getenv("TAVILY_EXTRACT_DEPTH", "basic"),
2272
+ )
2273
+
2274
+ PLAYWRIGHT_WS_URL = PersistentConfig(
2275
+ "PLAYWRIGHT_WS_URL",
2276
+ "rag.web.loader.playwright_ws_url",
2277
+ os.environ.get("PLAYWRIGHT_WS_URL", ""),
2278
+ )
2279
+
2280
+ PLAYWRIGHT_TIMEOUT = PersistentConfig(
2281
+ "PLAYWRIGHT_TIMEOUT",
2282
+ "rag.web.loader.playwright_timeout",
2283
+ int(os.environ.get("PLAYWRIGHT_TIMEOUT", "10000")),
2284
+ )
2285
+
2286
+ FIRECRAWL_API_KEY = PersistentConfig(
2287
+ "FIRECRAWL_API_KEY",
2288
+ "rag.web.loader.firecrawl_api_key",
2289
+ os.environ.get("FIRECRAWL_API_KEY", ""),
2290
+ )
2291
+
2292
+ FIRECRAWL_API_BASE_URL = PersistentConfig(
2293
+ "FIRECRAWL_API_BASE_URL",
2294
+ "rag.web.loader.firecrawl_api_url",
2295
+ os.environ.get("FIRECRAWL_API_BASE_URL", "https://api.firecrawl.dev"),
2296
+ )
2297
+
2298
+ EXTERNAL_WEB_SEARCH_URL = PersistentConfig(
2299
+ "EXTERNAL_WEB_SEARCH_URL",
2300
+ "rag.web.search.external_web_search_url",
2301
+ os.environ.get("EXTERNAL_WEB_SEARCH_URL", ""),
2302
+ )
2303
+
2304
+ EXTERNAL_WEB_SEARCH_API_KEY = PersistentConfig(
2305
+ "EXTERNAL_WEB_SEARCH_API_KEY",
2306
+ "rag.web.search.external_web_search_api_key",
2307
+ os.environ.get("EXTERNAL_WEB_SEARCH_API_KEY", ""),
2308
+ )
2309
+
2310
+ EXTERNAL_WEB_LOADER_URL = PersistentConfig(
2311
+ "EXTERNAL_WEB_LOADER_URL",
2312
+ "rag.web.loader.external_web_loader_url",
2313
+ os.environ.get("EXTERNAL_WEB_LOADER_URL", ""),
2314
+ )
2315
+
2316
+ EXTERNAL_WEB_LOADER_API_KEY = PersistentConfig(
2317
+ "EXTERNAL_WEB_LOADER_API_KEY",
2318
+ "rag.web.loader.external_web_loader_api_key",
2319
+ os.environ.get("EXTERNAL_WEB_LOADER_API_KEY", ""),
2320
+ )
2321
+
2322
+ ####################################
2323
+ # Images
2324
+ ####################################
2325
+
2326
+ IMAGE_GENERATION_ENGINE = PersistentConfig(
2327
+ "IMAGE_GENERATION_ENGINE",
2328
+ "image_generation.engine",
2329
+ os.getenv("IMAGE_GENERATION_ENGINE", "openai"),
2330
+ )
2331
+
2332
+ ENABLE_IMAGE_GENERATION = PersistentConfig(
2333
+ "ENABLE_IMAGE_GENERATION",
2334
+ "image_generation.enable",
2335
+ os.environ.get("ENABLE_IMAGE_GENERATION", "").lower() == "true",
2336
+ )
2337
+
2338
+ ENABLE_IMAGE_PROMPT_GENERATION = PersistentConfig(
2339
+ "ENABLE_IMAGE_PROMPT_GENERATION",
2340
+ "image_generation.prompt.enable",
2341
+ os.environ.get("ENABLE_IMAGE_PROMPT_GENERATION", "true").lower() == "true",
2342
+ )
2343
+
2344
+ AUTOMATIC1111_BASE_URL = PersistentConfig(
2345
+ "AUTOMATIC1111_BASE_URL",
2346
+ "image_generation.automatic1111.base_url",
2347
+ os.getenv("AUTOMATIC1111_BASE_URL", ""),
2348
+ )
2349
+ AUTOMATIC1111_API_AUTH = PersistentConfig(
2350
+ "AUTOMATIC1111_API_AUTH",
2351
+ "image_generation.automatic1111.api_auth",
2352
+ os.getenv("AUTOMATIC1111_API_AUTH", ""),
2353
+ )
2354
+
2355
+ AUTOMATIC1111_CFG_SCALE = PersistentConfig(
2356
+ "AUTOMATIC1111_CFG_SCALE",
2357
+ "image_generation.automatic1111.cfg_scale",
2358
+ (
2359
+ float(os.environ.get("AUTOMATIC1111_CFG_SCALE"))
2360
+ if os.environ.get("AUTOMATIC1111_CFG_SCALE")
2361
+ else None
2362
+ ),
2363
+ )
2364
+
2365
+
2366
+ AUTOMATIC1111_SAMPLER = PersistentConfig(
2367
+ "AUTOMATIC1111_SAMPLER",
2368
+ "image_generation.automatic1111.sampler",
2369
+ (
2370
+ os.environ.get("AUTOMATIC1111_SAMPLER")
2371
+ if os.environ.get("AUTOMATIC1111_SAMPLER")
2372
+ else None
2373
+ ),
2374
+ )
2375
+
2376
+ AUTOMATIC1111_SCHEDULER = PersistentConfig(
2377
+ "AUTOMATIC1111_SCHEDULER",
2378
+ "image_generation.automatic1111.scheduler",
2379
+ (
2380
+ os.environ.get("AUTOMATIC1111_SCHEDULER")
2381
+ if os.environ.get("AUTOMATIC1111_SCHEDULER")
2382
+ else None
2383
+ ),
2384
+ )
2385
+
2386
+ COMFYUI_BASE_URL = PersistentConfig(
2387
+ "COMFYUI_BASE_URL",
2388
+ "image_generation.comfyui.base_url",
2389
+ os.getenv("COMFYUI_BASE_URL", ""),
2390
+ )
2391
+
2392
+ COMFYUI_API_KEY = PersistentConfig(
2393
+ "COMFYUI_API_KEY",
2394
+ "image_generation.comfyui.api_key",
2395
+ os.getenv("COMFYUI_API_KEY", ""),
2396
+ )
2397
+
2398
+ COMFYUI_DEFAULT_WORKFLOW = """
2399
+ {
2400
+ "3": {
2401
+ "inputs": {
2402
+ "seed": 0,
2403
+ "steps": 20,
2404
+ "cfg": 8,
2405
+ "sampler_name": "euler",
2406
+ "scheduler": "normal",
2407
+ "denoise": 1,
2408
+ "model": [
2409
+ "4",
2410
+ 0
2411
+ ],
2412
+ "positive": [
2413
+ "6",
2414
+ 0
2415
+ ],
2416
+ "negative": [
2417
+ "7",
2418
+ 0
2419
+ ],
2420
+ "latent_image": [
2421
+ "5",
2422
+ 0
2423
+ ]
2424
+ },
2425
+ "class_type": "KSampler",
2426
+ "_meta": {
2427
+ "title": "KSampler"
2428
+ }
2429
+ },
2430
+ "4": {
2431
+ "inputs": {
2432
+ "ckpt_name": "model.safetensors"
2433
+ },
2434
+ "class_type": "CheckpointLoaderSimple",
2435
+ "_meta": {
2436
+ "title": "Load Checkpoint"
2437
+ }
2438
+ },
2439
+ "5": {
2440
+ "inputs": {
2441
+ "width": 512,
2442
+ "height": 512,
2443
+ "batch_size": 1
2444
+ },
2445
+ "class_type": "EmptyLatentImage",
2446
+ "_meta": {
2447
+ "title": "Empty Latent Image"
2448
+ }
2449
+ },
2450
+ "6": {
2451
+ "inputs": {
2452
+ "text": "Prompt",
2453
+ "clip": [
2454
+ "4",
2455
+ 1
2456
+ ]
2457
+ },
2458
+ "class_type": "CLIPTextEncode",
2459
+ "_meta": {
2460
+ "title": "CLIP Text Encode (Prompt)"
2461
+ }
2462
+ },
2463
+ "7": {
2464
+ "inputs": {
2465
+ "text": "",
2466
+ "clip": [
2467
+ "4",
2468
+ 1
2469
+ ]
2470
+ },
2471
+ "class_type": "CLIPTextEncode",
2472
+ "_meta": {
2473
+ "title": "CLIP Text Encode (Prompt)"
2474
+ }
2475
+ },
2476
+ "8": {
2477
+ "inputs": {
2478
+ "samples": [
2479
+ "3",
2480
+ 0
2481
+ ],
2482
+ "vae": [
2483
+ "4",
2484
+ 2
2485
+ ]
2486
+ },
2487
+ "class_type": "VAEDecode",
2488
+ "_meta": {
2489
+ "title": "VAE Decode"
2490
+ }
2491
+ },
2492
+ "9": {
2493
+ "inputs": {
2494
+ "filename_prefix": "ComfyUI",
2495
+ "images": [
2496
+ "8",
2497
+ 0
2498
+ ]
2499
+ },
2500
+ "class_type": "SaveImage",
2501
+ "_meta": {
2502
+ "title": "Save Image"
2503
+ }
2504
+ }
2505
+ }
2506
+ """
2507
+
2508
+
2509
+ COMFYUI_WORKFLOW = PersistentConfig(
2510
+ "COMFYUI_WORKFLOW",
2511
+ "image_generation.comfyui.workflow",
2512
+ os.getenv("COMFYUI_WORKFLOW", COMFYUI_DEFAULT_WORKFLOW),
2513
+ )
2514
+
2515
+ COMFYUI_WORKFLOW_NODES = PersistentConfig(
2516
+ "COMFYUI_WORKFLOW",
2517
+ "image_generation.comfyui.nodes",
2518
+ [],
2519
+ )
2520
+
2521
+ IMAGES_OPENAI_API_BASE_URL = PersistentConfig(
2522
+ "IMAGES_OPENAI_API_BASE_URL",
2523
+ "image_generation.openai.api_base_url",
2524
+ os.getenv("IMAGES_OPENAI_API_BASE_URL", OPENAI_API_BASE_URL),
2525
+ )
2526
+ IMAGES_OPENAI_API_KEY = PersistentConfig(
2527
+ "IMAGES_OPENAI_API_KEY",
2528
+ "image_generation.openai.api_key",
2529
+ os.getenv("IMAGES_OPENAI_API_KEY", OPENAI_API_KEY),
2530
+ )
2531
+
2532
+ IMAGES_GEMINI_API_BASE_URL = PersistentConfig(
2533
+ "IMAGES_GEMINI_API_BASE_URL",
2534
+ "image_generation.gemini.api_base_url",
2535
+ os.getenv("IMAGES_GEMINI_API_BASE_URL", GEMINI_API_BASE_URL),
2536
+ )
2537
+ IMAGES_GEMINI_API_KEY = PersistentConfig(
2538
+ "IMAGES_GEMINI_API_KEY",
2539
+ "image_generation.gemini.api_key",
2540
+ os.getenv("IMAGES_GEMINI_API_KEY", GEMINI_API_KEY),
2541
+ )
2542
+
2543
+ IMAGE_SIZE = PersistentConfig(
2544
+ "IMAGE_SIZE", "image_generation.size", os.getenv("IMAGE_SIZE", "512x512")
2545
+ )
2546
+
2547
+ IMAGE_STEPS = PersistentConfig(
2548
+ "IMAGE_STEPS", "image_generation.steps", int(os.getenv("IMAGE_STEPS", 50))
2549
+ )
2550
+
2551
+ IMAGE_GENERATION_MODEL = PersistentConfig(
2552
+ "IMAGE_GENERATION_MODEL",
2553
+ "image_generation.model",
2554
+ os.getenv("IMAGE_GENERATION_MODEL", ""),
2555
+ )
2556
+
2557
+ ####################################
2558
+ # Audio
2559
+ ####################################
2560
+
2561
+ # Transcription
2562
+ WHISPER_MODEL = PersistentConfig(
2563
+ "WHISPER_MODEL",
2564
+ "audio.stt.whisper_model",
2565
+ os.getenv("WHISPER_MODEL", "base"),
2566
+ )
2567
+
2568
+ WHISPER_MODEL_DIR = os.getenv("WHISPER_MODEL_DIR", f"{CACHE_DIR}/whisper/models")
2569
+ WHISPER_MODEL_AUTO_UPDATE = (
2570
+ not OFFLINE_MODE
2571
+ and os.environ.get("WHISPER_MODEL_AUTO_UPDATE", "").lower() == "true"
2572
+ )
2573
+
2574
+ WHISPER_VAD_FILTER = PersistentConfig(
2575
+ "WHISPER_VAD_FILTER",
2576
+ "audio.stt.whisper_vad_filter",
2577
+ os.getenv("WHISPER_VAD_FILTER", "False").lower() == "true",
2578
+ )
2579
+
2580
+
2581
+ # Add Deepgram configuration
2582
+ DEEPGRAM_API_KEY = PersistentConfig(
2583
+ "DEEPGRAM_API_KEY",
2584
+ "audio.stt.deepgram.api_key",
2585
+ os.getenv("DEEPGRAM_API_KEY", ""),
2586
+ )
2587
+
2588
+
2589
+ AUDIO_STT_OPENAI_API_BASE_URL = PersistentConfig(
2590
+ "AUDIO_STT_OPENAI_API_BASE_URL",
2591
+ "audio.stt.openai.api_base_url",
2592
+ os.getenv("AUDIO_STT_OPENAI_API_BASE_URL", OPENAI_API_BASE_URL),
2593
+ )
2594
+
2595
+ AUDIO_STT_OPENAI_API_KEY = PersistentConfig(
2596
+ "AUDIO_STT_OPENAI_API_KEY",
2597
+ "audio.stt.openai.api_key",
2598
+ os.getenv("AUDIO_STT_OPENAI_API_KEY", OPENAI_API_KEY),
2599
+ )
2600
+
2601
+ AUDIO_STT_ENGINE = PersistentConfig(
2602
+ "AUDIO_STT_ENGINE",
2603
+ "audio.stt.engine",
2604
+ os.getenv("AUDIO_STT_ENGINE", ""),
2605
+ )
2606
+
2607
+ AUDIO_STT_MODEL = PersistentConfig(
2608
+ "AUDIO_STT_MODEL",
2609
+ "audio.stt.model",
2610
+ os.getenv("AUDIO_STT_MODEL", ""),
2611
+ )
2612
+
2613
+ AUDIO_STT_AZURE_API_KEY = PersistentConfig(
2614
+ "AUDIO_STT_AZURE_API_KEY",
2615
+ "audio.stt.azure.api_key",
2616
+ os.getenv("AUDIO_STT_AZURE_API_KEY", ""),
2617
+ )
2618
+
2619
+ AUDIO_STT_AZURE_REGION = PersistentConfig(
2620
+ "AUDIO_STT_AZURE_REGION",
2621
+ "audio.stt.azure.region",
2622
+ os.getenv("AUDIO_STT_AZURE_REGION", ""),
2623
+ )
2624
+
2625
+ AUDIO_STT_AZURE_LOCALES = PersistentConfig(
2626
+ "AUDIO_STT_AZURE_LOCALES",
2627
+ "audio.stt.azure.locales",
2628
+ os.getenv("AUDIO_STT_AZURE_LOCALES", ""),
2629
+ )
2630
+
2631
+ AUDIO_TTS_OPENAI_API_BASE_URL = PersistentConfig(
2632
+ "AUDIO_TTS_OPENAI_API_BASE_URL",
2633
+ "audio.tts.openai.api_base_url",
2634
+ os.getenv("AUDIO_TTS_OPENAI_API_BASE_URL", OPENAI_API_BASE_URL),
2635
+ )
2636
+ AUDIO_TTS_OPENAI_API_KEY = PersistentConfig(
2637
+ "AUDIO_TTS_OPENAI_API_KEY",
2638
+ "audio.tts.openai.api_key",
2639
+ os.getenv("AUDIO_TTS_OPENAI_API_KEY", OPENAI_API_KEY),
2640
+ )
2641
+
2642
+ AUDIO_TTS_API_KEY = PersistentConfig(
2643
+ "AUDIO_TTS_API_KEY",
2644
+ "audio.tts.api_key",
2645
+ os.getenv("AUDIO_TTS_API_KEY", ""),
2646
+ )
2647
+
2648
+ AUDIO_TTS_ENGINE = PersistentConfig(
2649
+ "AUDIO_TTS_ENGINE",
2650
+ "audio.tts.engine",
2651
+ os.getenv("AUDIO_TTS_ENGINE", ""),
2652
+ )
2653
+
2654
+
2655
+ AUDIO_TTS_MODEL = PersistentConfig(
2656
+ "AUDIO_TTS_MODEL",
2657
+ "audio.tts.model",
2658
+ os.getenv("AUDIO_TTS_MODEL", "tts-1"), # OpenAI default model
2659
+ )
2660
+
2661
+ AUDIO_TTS_VOICE = PersistentConfig(
2662
+ "AUDIO_TTS_VOICE",
2663
+ "audio.tts.voice",
2664
+ os.getenv("AUDIO_TTS_VOICE", "alloy"), # OpenAI default voice
2665
+ )
2666
+
2667
+ AUDIO_TTS_SPLIT_ON = PersistentConfig(
2668
+ "AUDIO_TTS_SPLIT_ON",
2669
+ "audio.tts.split_on",
2670
+ os.getenv("AUDIO_TTS_SPLIT_ON", "punctuation"),
2671
+ )
2672
+
2673
+ AUDIO_TTS_AZURE_SPEECH_REGION = PersistentConfig(
2674
+ "AUDIO_TTS_AZURE_SPEECH_REGION",
2675
+ "audio.tts.azure.speech_region",
2676
+ os.getenv("AUDIO_TTS_AZURE_SPEECH_REGION", "eastus"),
2677
+ )
2678
+
2679
+ AUDIO_TTS_AZURE_SPEECH_OUTPUT_FORMAT = PersistentConfig(
2680
+ "AUDIO_TTS_AZURE_SPEECH_OUTPUT_FORMAT",
2681
+ "audio.tts.azure.speech_output_format",
2682
+ os.getenv(
2683
+ "AUDIO_TTS_AZURE_SPEECH_OUTPUT_FORMAT", "audio-24khz-160kbitrate-mono-mp3"
2684
+ ),
2685
+ )
2686
+
2687
+
2688
+ ####################################
2689
+ # LDAP
2690
+ ####################################
2691
+
2692
+ ENABLE_LDAP = PersistentConfig(
2693
+ "ENABLE_LDAP",
2694
+ "ldap.enable",
2695
+ os.environ.get("ENABLE_LDAP", "false").lower() == "true",
2696
+ )
2697
+
2698
+ LDAP_SERVER_LABEL = PersistentConfig(
2699
+ "LDAP_SERVER_LABEL",
2700
+ "ldap.server.label",
2701
+ os.environ.get("LDAP_SERVER_LABEL", "LDAP Server"),
2702
+ )
2703
+
2704
+ LDAP_SERVER_HOST = PersistentConfig(
2705
+ "LDAP_SERVER_HOST",
2706
+ "ldap.server.host",
2707
+ os.environ.get("LDAP_SERVER_HOST", "localhost"),
2708
+ )
2709
+
2710
+ LDAP_SERVER_PORT = PersistentConfig(
2711
+ "LDAP_SERVER_PORT",
2712
+ "ldap.server.port",
2713
+ int(os.environ.get("LDAP_SERVER_PORT", "389")),
2714
+ )
2715
+
2716
+ LDAP_ATTRIBUTE_FOR_MAIL = PersistentConfig(
2717
+ "LDAP_ATTRIBUTE_FOR_MAIL",
2718
+ "ldap.server.attribute_for_mail",
2719
+ os.environ.get("LDAP_ATTRIBUTE_FOR_MAIL", "mail"),
2720
+ )
2721
+
2722
+ LDAP_ATTRIBUTE_FOR_USERNAME = PersistentConfig(
2723
+ "LDAP_ATTRIBUTE_FOR_USERNAME",
2724
+ "ldap.server.attribute_for_username",
2725
+ os.environ.get("LDAP_ATTRIBUTE_FOR_USERNAME", "uid"),
2726
+ )
2727
+
2728
+ LDAP_APP_DN = PersistentConfig(
2729
+ "LDAP_APP_DN", "ldap.server.app_dn", os.environ.get("LDAP_APP_DN", "")
2730
+ )
2731
+
2732
+ LDAP_APP_PASSWORD = PersistentConfig(
2733
+ "LDAP_APP_PASSWORD",
2734
+ "ldap.server.app_password",
2735
+ os.environ.get("LDAP_APP_PASSWORD", ""),
2736
+ )
2737
+
2738
+ LDAP_SEARCH_BASE = PersistentConfig(
2739
+ "LDAP_SEARCH_BASE", "ldap.server.users_dn", os.environ.get("LDAP_SEARCH_BASE", "")
2740
+ )
2741
+
2742
+ LDAP_SEARCH_FILTERS = PersistentConfig(
2743
+ "LDAP_SEARCH_FILTER",
2744
+ "ldap.server.search_filter",
2745
+ os.environ.get("LDAP_SEARCH_FILTER", os.environ.get("LDAP_SEARCH_FILTERS", "")),
2746
+ )
2747
+
2748
+ LDAP_USE_TLS = PersistentConfig(
2749
+ "LDAP_USE_TLS",
2750
+ "ldap.server.use_tls",
2751
+ os.environ.get("LDAP_USE_TLS", "True").lower() == "true",
2752
+ )
2753
+
2754
+ LDAP_CA_CERT_FILE = PersistentConfig(
2755
+ "LDAP_CA_CERT_FILE",
2756
+ "ldap.server.ca_cert_file",
2757
+ os.environ.get("LDAP_CA_CERT_FILE", ""),
2758
+ )
2759
+
2760
+ LDAP_CIPHERS = PersistentConfig(
2761
+ "LDAP_CIPHERS", "ldap.server.ciphers", os.environ.get("LDAP_CIPHERS", "ALL")
2762
+ )
backend/open_webui/constants.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
42
+ INVALID_TOKEN = (
43
+ "Your session has expired or the token is invalid. Please sign in again."
44
+ )
45
+ INVALID_CRED = "The email or password provided is incorrect. Please check for typos and try logging in again."
46
+ 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)."
47
+ INVALID_PASSWORD = (
48
+ "The password provided is incorrect. Please check for typos and try again."
49
+ )
50
+ INVALID_TRUSTED_HEADER = "Your provider has not provided a trusted header. Please contact your administrator for assistance."
51
+
52
+ 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."
53
+
54
+ UNAUTHORIZED = "401 Unauthorized"
55
+ ACCESS_PROHIBITED = "You do not have permission to access this resource. Please contact your administrator for assistance."
56
+ ACTION_PROHIBITED = (
57
+ "The requested action has been restricted as a security measure."
58
+ )
59
+
60
+ FILE_NOT_SENT = "FILE_NOT_SENT"
61
+ 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."
62
+
63
+ NOT_FOUND = "We could not find what you're looking for :/"
64
+ USER_NOT_FOUND = "We could not find what you're looking for :/"
65
+ 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."
66
+ API_KEY_NOT_ALLOWED = "Use of API key is not enabled in the environment."
67
+
68
+ MALICIOUS = "Unusual activities detected, please try again in a few minutes."
69
+
70
+ PANDOC_NOT_INSTALLED = "Pandoc is not installed on the server. Please contact your administrator for assistance."
71
+ INCORRECT_FORMAT = (
72
+ lambda err="": f"Invalid format. Please use the correct format{err}"
73
+ )
74
+ RATE_LIMIT_EXCEEDED = "API rate limit exceeded"
75
+
76
+ MODEL_NOT_FOUND = lambda name="": f"Model '{name}' was not found"
77
+ OPENAI_NOT_FOUND = lambda name="": "OpenAI API was not found"
78
+ OLLAMA_NOT_FOUND = "WebUI could not connect to Ollama"
79
+ 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."
80
+ API_KEY_CREATION_NOT_ALLOWED = "API key creation is not allowed in the environment."
81
+
82
+ EMPTY_CONTENT = "The content provided is empty. Please ensure that there is text or data present before proceeding."
83
+
84
+ DB_NOT_SQLITE = "This feature is only available when running with SQLite databases."
85
+
86
+ INVALID_URL = (
87
+ "Oops! The URL you provided is invalid. Please double-check and try again."
88
+ )
89
+
90
+ WEB_SEARCH_ERROR = (
91
+ lambda err="": f"{err if err else 'Oops! Something went wrong while searching the web.'}"
92
+ )
93
+
94
+ OLLAMA_API_DISABLED = (
95
+ "The Ollama API is disabled. Please enable it to use this feature."
96
+ )
97
+
98
+ FILE_TOO_LARGE = (
99
+ lambda size="": f"Oops! The file you're trying to upload is too large. Please upload a file that is less than {size}."
100
+ )
101
+
102
+ DUPLICATE_CONTENT = (
103
+ "Duplicate content detected. Please provide unique content to proceed."
104
+ )
105
+ FILE_NOT_PROCESSED = "Extracted content is not available for this file. Please ensure that the file is processed before proceeding."
106
+
107
+
108
+ class TASKS(str, Enum):
109
+ def __str__(self) -> str:
110
+ return super().__str__()
111
+
112
+ DEFAULT = lambda task="": f"{task if task else 'generation'}"
113
+ TITLE_GENERATION = "title_generation"
114
+ TAGS_GENERATION = "tags_generation"
115
+ EMOJI_GENERATION = "emoji_generation"
116
+ QUERY_GENERATION = "query_generation"
117
+ IMAGE_PROMPT_GENERATION = "image_prompt_generation"
118
+ AUTOCOMPLETE_GENERATION = "autocomplete_generation"
119
+ FUNCTION_CALLING = "function_calling"
120
+ MOA_RESPONSE_GENERATION = "moa_response_generation"
backend/open_webui/env.py ADDED
@@ -0,0 +1,559 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib.metadata
2
+ import json
3
+ import logging
4
+ import os
5
+ import pkgutil
6
+ import sys
7
+ import shutil
8
+ from pathlib import Path
9
+
10
+ import markdown
11
+ from bs4 import BeautifulSoup
12
+ from open_webui.constants import ERROR_MESSAGES
13
+
14
+ ####################################
15
+ # Load .env file
16
+ ####################################
17
+
18
+ OPEN_WEBUI_DIR = Path(__file__).parent # the path containing this file
19
+ print(OPEN_WEBUI_DIR)
20
+
21
+ BACKEND_DIR = OPEN_WEBUI_DIR.parent # the path containing this file
22
+ BASE_DIR = BACKEND_DIR.parent # the path containing the backend/
23
+
24
+ print(BACKEND_DIR)
25
+ print(BASE_DIR)
26
+
27
+ try:
28
+ from dotenv import find_dotenv, load_dotenv
29
+
30
+ load_dotenv(find_dotenv(str(BASE_DIR / ".env")))
31
+ except ImportError:
32
+ print("dotenv not installed, skipping...")
33
+
34
+ DOCKER = os.environ.get("DOCKER", "False").lower() == "true"
35
+
36
+ # device type embedding models - "cpu" (default), "cuda" (nvidia gpu required) or "mps" (apple silicon) - choosing this right can lead to better performance
37
+ USE_CUDA = os.environ.get("USE_CUDA_DOCKER", "false")
38
+
39
+ if USE_CUDA.lower() == "true":
40
+ try:
41
+ import torch
42
+
43
+ assert torch.cuda.is_available(), "CUDA not available"
44
+ DEVICE_TYPE = "cuda"
45
+ except Exception as e:
46
+ cuda_error = (
47
+ "Error when testing CUDA but USE_CUDA_DOCKER is true. "
48
+ f"Resetting USE_CUDA_DOCKER to false: {e}"
49
+ )
50
+ os.environ["USE_CUDA_DOCKER"] = "false"
51
+ USE_CUDA = "false"
52
+ DEVICE_TYPE = "cpu"
53
+ else:
54
+ DEVICE_TYPE = "cpu"
55
+
56
+ try:
57
+ import torch
58
+
59
+ if torch.backends.mps.is_available() and torch.backends.mps.is_built():
60
+ DEVICE_TYPE = "mps"
61
+ except Exception:
62
+ pass
63
+
64
+ ####################################
65
+ # LOGGING
66
+ ####################################
67
+
68
+ GLOBAL_LOG_LEVEL = os.environ.get("GLOBAL_LOG_LEVEL", "").upper()
69
+ if GLOBAL_LOG_LEVEL in logging.getLevelNamesMapping():
70
+ logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL, force=True)
71
+ else:
72
+ GLOBAL_LOG_LEVEL = "INFO"
73
+
74
+ log = logging.getLogger(__name__)
75
+ log.info(f"GLOBAL_LOG_LEVEL: {GLOBAL_LOG_LEVEL}")
76
+
77
+ if "cuda_error" in locals():
78
+ log.exception(cuda_error)
79
+ del cuda_error
80
+
81
+ log_sources = [
82
+ "AUDIO",
83
+ "COMFYUI",
84
+ "CONFIG",
85
+ "DB",
86
+ "IMAGES",
87
+ "MAIN",
88
+ "MODELS",
89
+ "OLLAMA",
90
+ "OPENAI",
91
+ "RAG",
92
+ "WEBHOOK",
93
+ "SOCKET",
94
+ "OAUTH",
95
+ ]
96
+
97
+ SRC_LOG_LEVELS = {}
98
+
99
+ for source in log_sources:
100
+ log_env_var = source + "_LOG_LEVEL"
101
+ SRC_LOG_LEVELS[source] = os.environ.get(log_env_var, "").upper()
102
+ if SRC_LOG_LEVELS[source] not in logging.getLevelNamesMapping():
103
+ SRC_LOG_LEVELS[source] = GLOBAL_LOG_LEVEL
104
+ log.info(f"{log_env_var}: {SRC_LOG_LEVELS[source]}")
105
+
106
+ log.setLevel(SRC_LOG_LEVELS["CONFIG"])
107
+
108
+ WEBUI_NAME = os.environ.get("WEBUI_NAME", "Open WebUI")
109
+ if WEBUI_NAME != "Open WebUI":
110
+ WEBUI_NAME += " (Open WebUI)"
111
+
112
+ WEBUI_FAVICON_URL = "https://openwebui.com/favicon.png"
113
+
114
+ TRUSTED_SIGNATURE_KEY = os.environ.get("TRUSTED_SIGNATURE_KEY", "")
115
+
116
+ ####################################
117
+ # ENV (dev,test,prod)
118
+ ####################################
119
+
120
+ ENV = os.environ.get("ENV", "dev")
121
+
122
+ FROM_INIT_PY = os.environ.get("FROM_INIT_PY", "False").lower() == "true"
123
+
124
+ if FROM_INIT_PY:
125
+ PACKAGE_DATA = {"version": importlib.metadata.version("open-webui")}
126
+ else:
127
+ try:
128
+ PACKAGE_DATA = json.loads((BASE_DIR / "package.json").read_text())
129
+ except Exception:
130
+ PACKAGE_DATA = {"version": "0.0.0"}
131
+
132
+ VERSION = PACKAGE_DATA["version"]
133
+
134
+
135
+ # Function to parse each section
136
+ def parse_section(section):
137
+ items = []
138
+ for li in section.find_all("li"):
139
+ # Extract raw HTML string
140
+ raw_html = str(li)
141
+
142
+ # Extract text without HTML tags
143
+ text = li.get_text(separator=" ", strip=True)
144
+
145
+ # Split into title and content
146
+ parts = text.split(": ", 1)
147
+ title = parts[0].strip() if len(parts) > 1 else ""
148
+ content = parts[1].strip() if len(parts) > 1 else text
149
+
150
+ items.append({"title": title, "content": content, "raw": raw_html})
151
+ return items
152
+
153
+
154
+ try:
155
+ changelog_path = BASE_DIR / "CHANGELOG.md"
156
+ with open(str(changelog_path.absolute()), "r", encoding="utf8") as file:
157
+ changelog_content = file.read()
158
+
159
+ except Exception:
160
+ changelog_content = (pkgutil.get_data("open_webui", "CHANGELOG.md") or b"").decode()
161
+
162
+ # Convert markdown content to HTML
163
+ html_content = markdown.markdown(changelog_content)
164
+
165
+ # Parse the HTML content
166
+ soup = BeautifulSoup(html_content, "html.parser")
167
+
168
+ # Initialize JSON structure
169
+ changelog_json = {}
170
+
171
+ # Iterate over each version
172
+ for version in soup.find_all("h2"):
173
+ version_number = version.get_text().strip().split(" - ")[0][1:-1] # Remove brackets
174
+ date = version.get_text().strip().split(" - ")[1]
175
+
176
+ version_data = {"date": date}
177
+
178
+ # Find the next sibling that is a h3 tag (section title)
179
+ current = version.find_next_sibling()
180
+
181
+ while current and current.name != "h2":
182
+ if current.name == "h3":
183
+ section_title = current.get_text().lower() # e.g., "added", "fixed"
184
+ section_items = parse_section(current.find_next_sibling("ul"))
185
+ version_data[section_title] = section_items
186
+
187
+ # Move to the next element
188
+ current = current.find_next_sibling()
189
+
190
+ changelog_json[version_number] = version_data
191
+
192
+ CHANGELOG = changelog_json
193
+
194
+ ####################################
195
+ # SAFE_MODE
196
+ ####################################
197
+
198
+ SAFE_MODE = os.environ.get("SAFE_MODE", "false").lower() == "true"
199
+
200
+ ####################################
201
+ # ENABLE_FORWARD_USER_INFO_HEADERS
202
+ ####################################
203
+
204
+ ENABLE_FORWARD_USER_INFO_HEADERS = (
205
+ os.environ.get("ENABLE_FORWARD_USER_INFO_HEADERS", "False").lower() == "true"
206
+ )
207
+
208
+ ####################################
209
+ # WEBUI_BUILD_HASH
210
+ ####################################
211
+
212
+ WEBUI_BUILD_HASH = os.environ.get("WEBUI_BUILD_HASH", "dev-build")
213
+
214
+ ####################################
215
+ # DATA/FRONTEND BUILD DIR
216
+ ####################################
217
+
218
+ DATA_DIR = Path(os.getenv("DATA_DIR", BACKEND_DIR / "data")).resolve()
219
+
220
+ if FROM_INIT_PY:
221
+ NEW_DATA_DIR = Path(os.getenv("DATA_DIR", OPEN_WEBUI_DIR / "data")).resolve()
222
+ NEW_DATA_DIR.mkdir(parents=True, exist_ok=True)
223
+
224
+ # Check if the data directory exists in the package directory
225
+ if DATA_DIR.exists() and DATA_DIR != NEW_DATA_DIR:
226
+ log.info(f"Moving {DATA_DIR} to {NEW_DATA_DIR}")
227
+ for item in DATA_DIR.iterdir():
228
+ dest = NEW_DATA_DIR / item.name
229
+ if item.is_dir():
230
+ shutil.copytree(item, dest, dirs_exist_ok=True)
231
+ else:
232
+ shutil.copy2(item, dest)
233
+
234
+ # Zip the data directory
235
+ shutil.make_archive(DATA_DIR.parent / "open_webui_data", "zip", DATA_DIR)
236
+
237
+ # Remove the old data directory
238
+ shutil.rmtree(DATA_DIR)
239
+
240
+ DATA_DIR = Path(os.getenv("DATA_DIR", OPEN_WEBUI_DIR / "data"))
241
+
242
+ STATIC_DIR = Path(os.getenv("STATIC_DIR", OPEN_WEBUI_DIR / "static"))
243
+
244
+ FONTS_DIR = Path(os.getenv("FONTS_DIR", OPEN_WEBUI_DIR / "static" / "fonts"))
245
+
246
+ FRONTEND_BUILD_DIR = Path(os.getenv("FRONTEND_BUILD_DIR", BASE_DIR / "build")).resolve()
247
+
248
+ if FROM_INIT_PY:
249
+ FRONTEND_BUILD_DIR = Path(
250
+ os.getenv("FRONTEND_BUILD_DIR", OPEN_WEBUI_DIR / "frontend")
251
+ ).resolve()
252
+
253
+ ####################################
254
+ # Database
255
+ ####################################
256
+
257
+ # Check if the file exists
258
+ if os.path.exists(f"{DATA_DIR}/ollama.db"):
259
+ # Rename the file
260
+ os.rename(f"{DATA_DIR}/ollama.db", f"{DATA_DIR}/webui.db")
261
+ log.info("Database migrated from Ollama-WebUI successfully.")
262
+ else:
263
+ pass
264
+
265
+ DATABASE_URL = os.environ.get("DATABASE_URL", f"sqlite:///{DATA_DIR}/webui.db")
266
+
267
+ # Replace the postgres:// with postgresql://
268
+ if "postgres://" in DATABASE_URL:
269
+ DATABASE_URL = DATABASE_URL.replace("postgres://", "postgresql://")
270
+
271
+ DATABASE_SCHEMA = os.environ.get("DATABASE_SCHEMA", None)
272
+
273
+ DATABASE_POOL_SIZE = os.environ.get("DATABASE_POOL_SIZE", 0)
274
+
275
+ if DATABASE_POOL_SIZE == "":
276
+ DATABASE_POOL_SIZE = 0
277
+ else:
278
+ try:
279
+ DATABASE_POOL_SIZE = int(DATABASE_POOL_SIZE)
280
+ except Exception:
281
+ DATABASE_POOL_SIZE = 0
282
+
283
+ DATABASE_POOL_MAX_OVERFLOW = os.environ.get("DATABASE_POOL_MAX_OVERFLOW", 0)
284
+
285
+ if DATABASE_POOL_MAX_OVERFLOW == "":
286
+ DATABASE_POOL_MAX_OVERFLOW = 0
287
+ else:
288
+ try:
289
+ DATABASE_POOL_MAX_OVERFLOW = int(DATABASE_POOL_MAX_OVERFLOW)
290
+ except Exception:
291
+ DATABASE_POOL_MAX_OVERFLOW = 0
292
+
293
+ DATABASE_POOL_TIMEOUT = os.environ.get("DATABASE_POOL_TIMEOUT", 30)
294
+
295
+ if DATABASE_POOL_TIMEOUT == "":
296
+ DATABASE_POOL_TIMEOUT = 30
297
+ else:
298
+ try:
299
+ DATABASE_POOL_TIMEOUT = int(DATABASE_POOL_TIMEOUT)
300
+ except Exception:
301
+ DATABASE_POOL_TIMEOUT = 30
302
+
303
+ DATABASE_POOL_RECYCLE = os.environ.get("DATABASE_POOL_RECYCLE", 3600)
304
+
305
+ if DATABASE_POOL_RECYCLE == "":
306
+ DATABASE_POOL_RECYCLE = 3600
307
+ else:
308
+ try:
309
+ DATABASE_POOL_RECYCLE = int(DATABASE_POOL_RECYCLE)
310
+ except Exception:
311
+ DATABASE_POOL_RECYCLE = 3600
312
+
313
+ RESET_CONFIG_ON_START = (
314
+ os.environ.get("RESET_CONFIG_ON_START", "False").lower() == "true"
315
+ )
316
+
317
+ ENABLE_REALTIME_CHAT_SAVE = (
318
+ os.environ.get("ENABLE_REALTIME_CHAT_SAVE", "False").lower() == "true"
319
+ )
320
+
321
+ ####################################
322
+ # REDIS
323
+ ####################################
324
+
325
+ REDIS_URL = os.environ.get("REDIS_URL", "")
326
+ REDIS_SENTINEL_HOSTS = os.environ.get("REDIS_SENTINEL_HOSTS", "")
327
+ REDIS_SENTINEL_PORT = os.environ.get("REDIS_SENTINEL_PORT", "26379")
328
+
329
+ ####################################
330
+ # UVICORN WORKERS
331
+ ####################################
332
+
333
+ # Number of uvicorn worker processes for handling requests
334
+ UVICORN_WORKERS = os.environ.get("UVICORN_WORKERS", "1")
335
+ try:
336
+ UVICORN_WORKERS = int(UVICORN_WORKERS)
337
+ if UVICORN_WORKERS < 1:
338
+ UVICORN_WORKERS = 1
339
+ except ValueError:
340
+ UVICORN_WORKERS = 1
341
+ log.info(f"Invalid UVICORN_WORKERS value, defaulting to {UVICORN_WORKERS}")
342
+
343
+ ####################################
344
+ # WEBUI_AUTH (Required for security)
345
+ ####################################
346
+
347
+ WEBUI_AUTH = os.environ.get("WEBUI_AUTH", "True").lower() == "true"
348
+ WEBUI_AUTH_TRUSTED_EMAIL_HEADER = os.environ.get(
349
+ "WEBUI_AUTH_TRUSTED_EMAIL_HEADER", None
350
+ )
351
+ WEBUI_AUTH_TRUSTED_NAME_HEADER = os.environ.get("WEBUI_AUTH_TRUSTED_NAME_HEADER", None)
352
+
353
+ BYPASS_MODEL_ACCESS_CONTROL = (
354
+ os.environ.get("BYPASS_MODEL_ACCESS_CONTROL", "False").lower() == "true"
355
+ )
356
+
357
+ WEBUI_AUTH_SIGNOUT_REDIRECT_URL = os.environ.get(
358
+ "WEBUI_AUTH_SIGNOUT_REDIRECT_URL", None
359
+ )
360
+
361
+ ####################################
362
+ # WEBUI_SECRET_KEY
363
+ ####################################
364
+
365
+ WEBUI_SECRET_KEY = os.environ.get(
366
+ "WEBUI_SECRET_KEY",
367
+ os.environ.get(
368
+ "WEBUI_JWT_SECRET_KEY", "t0p-s3cr3t"
369
+ ), # DEPRECATED: remove at next major version
370
+ )
371
+
372
+ WEBUI_SESSION_COOKIE_SAME_SITE = os.environ.get("WEBUI_SESSION_COOKIE_SAME_SITE", "lax")
373
+
374
+ WEBUI_SESSION_COOKIE_SECURE = (
375
+ os.environ.get("WEBUI_SESSION_COOKIE_SECURE", "false").lower() == "true"
376
+ )
377
+
378
+ WEBUI_AUTH_COOKIE_SAME_SITE = os.environ.get(
379
+ "WEBUI_AUTH_COOKIE_SAME_SITE", WEBUI_SESSION_COOKIE_SAME_SITE
380
+ )
381
+
382
+ WEBUI_AUTH_COOKIE_SECURE = (
383
+ os.environ.get(
384
+ "WEBUI_AUTH_COOKIE_SECURE",
385
+ os.environ.get("WEBUI_SESSION_COOKIE_SECURE", "false"),
386
+ ).lower()
387
+ == "true"
388
+ )
389
+
390
+ if WEBUI_AUTH and WEBUI_SECRET_KEY == "":
391
+ raise ValueError(ERROR_MESSAGES.ENV_VAR_NOT_FOUND)
392
+
393
+ ENABLE_WEBSOCKET_SUPPORT = (
394
+ os.environ.get("ENABLE_WEBSOCKET_SUPPORT", "True").lower() == "true"
395
+ )
396
+
397
+ WEBSOCKET_MANAGER = os.environ.get("WEBSOCKET_MANAGER", "")
398
+
399
+ WEBSOCKET_REDIS_URL = os.environ.get("WEBSOCKET_REDIS_URL", REDIS_URL)
400
+ WEBSOCKET_REDIS_LOCK_TIMEOUT = os.environ.get("WEBSOCKET_REDIS_LOCK_TIMEOUT", 60)
401
+
402
+ WEBSOCKET_SENTINEL_HOSTS = os.environ.get("WEBSOCKET_SENTINEL_HOSTS", "")
403
+
404
+ WEBSOCKET_SENTINEL_PORT = os.environ.get("WEBSOCKET_SENTINEL_PORT", "26379")
405
+
406
+ AIOHTTP_CLIENT_TIMEOUT = os.environ.get("AIOHTTP_CLIENT_TIMEOUT", "")
407
+
408
+ if AIOHTTP_CLIENT_TIMEOUT == "":
409
+ AIOHTTP_CLIENT_TIMEOUT = None
410
+ else:
411
+ try:
412
+ AIOHTTP_CLIENT_TIMEOUT = int(AIOHTTP_CLIENT_TIMEOUT)
413
+ except Exception:
414
+ AIOHTTP_CLIENT_TIMEOUT = 300
415
+
416
+
417
+ AIOHTTP_CLIENT_SESSION_SSL = (
418
+ os.environ.get("AIOHTTP_CLIENT_SESSION_SSL", "True").lower() == "true"
419
+ )
420
+
421
+ AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST = os.environ.get(
422
+ "AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST",
423
+ os.environ.get("AIOHTTP_CLIENT_TIMEOUT_OPENAI_MODEL_LIST", "10"),
424
+ )
425
+
426
+ if AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST == "":
427
+ AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST = None
428
+ else:
429
+ try:
430
+ AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST = int(AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST)
431
+ except Exception:
432
+ AIOHTTP_CLIENT_TIMEOUT_MODEL_LIST = 10
433
+
434
+
435
+ AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER_DATA = os.environ.get(
436
+ "AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER_DATA", "10"
437
+ )
438
+
439
+ if AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER_DATA == "":
440
+ AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER_DATA = None
441
+ else:
442
+ try:
443
+ AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER_DATA = int(
444
+ AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER_DATA
445
+ )
446
+ except Exception:
447
+ AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER_DATA = 10
448
+
449
+
450
+ AIOHTTP_CLIENT_SESSION_TOOL_SERVER_SSL = (
451
+ os.environ.get("AIOHTTP_CLIENT_SESSION_TOOL_SERVER_SSL", "True").lower() == "true"
452
+ )
453
+
454
+
455
+ ####################################
456
+ # SENTENCE TRANSFORMERS
457
+ ####################################
458
+
459
+
460
+ SENTENCE_TRANSFORMERS_BACKEND = os.environ.get("SENTENCE_TRANSFORMERS_BACKEND", "")
461
+ if SENTENCE_TRANSFORMERS_BACKEND == "":
462
+ SENTENCE_TRANSFORMERS_BACKEND = "torch"
463
+
464
+
465
+ SENTENCE_TRANSFORMERS_MODEL_KWARGS = os.environ.get(
466
+ "SENTENCE_TRANSFORMERS_MODEL_KWARGS", ""
467
+ )
468
+ if SENTENCE_TRANSFORMERS_MODEL_KWARGS == "":
469
+ SENTENCE_TRANSFORMERS_MODEL_KWARGS = None
470
+ else:
471
+ try:
472
+ SENTENCE_TRANSFORMERS_MODEL_KWARGS = json.loads(
473
+ SENTENCE_TRANSFORMERS_MODEL_KWARGS
474
+ )
475
+ except Exception:
476
+ SENTENCE_TRANSFORMERS_MODEL_KWARGS = None
477
+
478
+
479
+ SENTENCE_TRANSFORMERS_CROSS_ENCODER_BACKEND = os.environ.get(
480
+ "SENTENCE_TRANSFORMERS_CROSS_ENCODER_BACKEND", ""
481
+ )
482
+ if SENTENCE_TRANSFORMERS_CROSS_ENCODER_BACKEND == "":
483
+ SENTENCE_TRANSFORMERS_CROSS_ENCODER_BACKEND = "torch"
484
+
485
+
486
+ SENTENCE_TRANSFORMERS_CROSS_ENCODER_MODEL_KWARGS = os.environ.get(
487
+ "SENTENCE_TRANSFORMERS_CROSS_ENCODER_MODEL_KWARGS", ""
488
+ )
489
+ if SENTENCE_TRANSFORMERS_CROSS_ENCODER_MODEL_KWARGS == "":
490
+ SENTENCE_TRANSFORMERS_CROSS_ENCODER_MODEL_KWARGS = None
491
+ else:
492
+ try:
493
+ SENTENCE_TRANSFORMERS_CROSS_ENCODER_MODEL_KWARGS = json.loads(
494
+ SENTENCE_TRANSFORMERS_CROSS_ENCODER_MODEL_KWARGS
495
+ )
496
+ except Exception:
497
+ SENTENCE_TRANSFORMERS_CROSS_ENCODER_MODEL_KWARGS = None
498
+
499
+ ####################################
500
+ # OFFLINE_MODE
501
+ ####################################
502
+
503
+ OFFLINE_MODE = os.environ.get("OFFLINE_MODE", "false").lower() == "true"
504
+
505
+ if OFFLINE_MODE:
506
+ os.environ["HF_HUB_OFFLINE"] = "1"
507
+
508
+
509
+ ####################################
510
+ # AUDIT LOGGING
511
+ ####################################
512
+ # Where to store log file
513
+ AUDIT_LOGS_FILE_PATH = f"{DATA_DIR}/audit.log"
514
+ # Maximum size of a file before rotating into a new log file
515
+ AUDIT_LOG_FILE_ROTATION_SIZE = os.getenv("AUDIT_LOG_FILE_ROTATION_SIZE", "10MB")
516
+ # METADATA | REQUEST | REQUEST_RESPONSE
517
+ AUDIT_LOG_LEVEL = os.getenv("AUDIT_LOG_LEVEL", "NONE").upper()
518
+ try:
519
+ MAX_BODY_LOG_SIZE = int(os.environ.get("MAX_BODY_LOG_SIZE") or 2048)
520
+ except ValueError:
521
+ MAX_BODY_LOG_SIZE = 2048
522
+
523
+ # Comma separated list for urls to exclude from audit
524
+ AUDIT_EXCLUDED_PATHS = os.getenv("AUDIT_EXCLUDED_PATHS", "/chats,/chat,/folders").split(
525
+ ","
526
+ )
527
+ AUDIT_EXCLUDED_PATHS = [path.strip() for path in AUDIT_EXCLUDED_PATHS]
528
+ AUDIT_EXCLUDED_PATHS = [path.lstrip("/") for path in AUDIT_EXCLUDED_PATHS]
529
+
530
+
531
+ ####################################
532
+ # OPENTELEMETRY
533
+ ####################################
534
+
535
+ ENABLE_OTEL = os.environ.get("ENABLE_OTEL", "False").lower() == "true"
536
+ OTEL_EXPORTER_OTLP_ENDPOINT = os.environ.get(
537
+ "OTEL_EXPORTER_OTLP_ENDPOINT", "http://localhost:4317"
538
+ )
539
+ OTEL_SERVICE_NAME = os.environ.get("OTEL_SERVICE_NAME", "open-webui")
540
+ OTEL_RESOURCE_ATTRIBUTES = os.environ.get(
541
+ "OTEL_RESOURCE_ATTRIBUTES", ""
542
+ ) # e.g. key1=val1,key2=val2
543
+ OTEL_TRACES_SAMPLER = os.environ.get(
544
+ "OTEL_TRACES_SAMPLER", "parentbased_always_on"
545
+ ).lower()
546
+
547
+ ####################################
548
+ # TOOLS/FUNCTIONS PIP OPTIONS
549
+ ####################################
550
+
551
+ PIP_OPTIONS = os.getenv("PIP_OPTIONS", "").split()
552
+ PIP_PACKAGE_INDEX_OPTIONS = os.getenv("PIP_PACKAGE_INDEX_OPTIONS", "").split()
553
+
554
+
555
+ ####################################
556
+ # PROGRESSIVE WEB APP OPTIONS
557
+ ####################################
558
+
559
+ EXTERNAL_PWA_MANIFEST_URL = os.environ.get("EXTERNAL_PWA_MANIFEST_URL")
backend/open_webui/functions.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.socket.main import (
23
+ get_event_call,
24
+ get_event_emitter,
25
+ )
26
+
27
+
28
+ from open_webui.models.functions import Functions
29
+ from open_webui.models.models import Models
30
+
31
+ from open_webui.utils.plugin import load_function_module_by_id
32
+ from open_webui.utils.tools import get_tools
33
+ from open_webui.utils.access_control import has_access
34
+
35
+ from open_webui.env import SRC_LOG_LEVELS, GLOBAL_LOG_LEVEL
36
+
37
+ from open_webui.utils.misc import (
38
+ add_or_update_system_message,
39
+ get_last_user_message,
40
+ prepend_to_first_user_message_content,
41
+ openai_chat_chunk_message_template,
42
+ openai_chat_completion_message_template,
43
+ )
44
+ from open_webui.utils.payload import (
45
+ apply_model_params_to_body_openai,
46
+ apply_model_system_prompt_to_body,
47
+ )
48
+
49
+
50
+ logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
51
+ log = logging.getLogger(__name__)
52
+ log.setLevel(SRC_LOG_LEVELS["MAIN"])
53
+
54
+
55
+ def get_function_module_by_id(request: Request, pipe_id: str):
56
+ # Check if function is already loaded
57
+ if pipe_id not in request.app.state.FUNCTIONS:
58
+ function_module, _, _ = load_function_module_by_id(pipe_id)
59
+ request.app.state.FUNCTIONS[pipe_id] = function_module
60
+ else:
61
+ function_module = request.app.state.FUNCTIONS[pipe_id]
62
+
63
+ if hasattr(function_module, "valves") and hasattr(function_module, "Valves"):
64
+ valves = Functions.get_function_valves_by_id(pipe_id)
65
+ function_module.valves = function_module.Valves(**(valves if valves else {}))
66
+ return function_module
67
+
68
+
69
+ async def get_function_models(request):
70
+ pipes = Functions.get_functions_by_type("pipe", active_only=True)
71
+ pipe_models = []
72
+
73
+ for pipe in pipes:
74
+ function_module = get_function_module_by_id(request, pipe.id)
75
+
76
+ # Check if function is a manifold
77
+ if hasattr(function_module, "pipes"):
78
+ sub_pipes = []
79
+
80
+ # Handle pipes being a list, sync function, or async function
81
+ try:
82
+ if callable(function_module.pipes):
83
+ if asyncio.iscoroutinefunction(function_module.pipes):
84
+ sub_pipes = await function_module.pipes()
85
+ else:
86
+ sub_pipes = function_module.pipes()
87
+ else:
88
+ sub_pipes = function_module.pipes
89
+ except Exception as e:
90
+ log.exception(e)
91
+ sub_pipes = []
92
+
93
+ log.debug(
94
+ f"get_function_models: function '{pipe.id}' is a manifold of {sub_pipes}"
95
+ )
96
+
97
+ for p in sub_pipes:
98
+ sub_pipe_id = f'{pipe.id}.{p["id"]}'
99
+ sub_pipe_name = p["name"]
100
+
101
+ if hasattr(function_module, "name"):
102
+ sub_pipe_name = f"{function_module.name}{sub_pipe_name}"
103
+
104
+ pipe_flag = {"type": pipe.type}
105
+
106
+ pipe_models.append(
107
+ {
108
+ "id": sub_pipe_id,
109
+ "name": sub_pipe_name,
110
+ "object": "model",
111
+ "created": pipe.created_at,
112
+ "owned_by": "openai",
113
+ "pipe": pipe_flag,
114
+ }
115
+ )
116
+ else:
117
+ pipe_flag = {"type": "pipe"}
118
+
119
+ log.debug(
120
+ f"get_function_models: function '{pipe.id}' is a single pipe {{ 'id': {pipe.id}, 'name': {pipe.name} }}"
121
+ )
122
+
123
+ pipe_models.append(
124
+ {
125
+ "id": pipe.id,
126
+ "name": pipe.name,
127
+ "object": "model",
128
+ "created": pipe.created_at,
129
+ "owned_by": "openai",
130
+ "pipe": pipe_flag,
131
+ }
132
+ )
133
+
134
+ return pipe_models
135
+
136
+
137
+ async def generate_function_chat_completion(
138
+ request, form_data, user, models: dict = {}
139
+ ):
140
+ async def execute_pipe(pipe, params):
141
+ if inspect.iscoroutinefunction(pipe):
142
+ return await pipe(**params)
143
+ else:
144
+ return pipe(**params)
145
+
146
+ async def get_message_content(res: str | Generator | AsyncGenerator) -> str:
147
+ if isinstance(res, str):
148
+ return res
149
+ if isinstance(res, Generator):
150
+ return "".join(map(str, res))
151
+ if isinstance(res, AsyncGenerator):
152
+ return "".join([str(stream) async for stream in res])
153
+
154
+ def process_line(form_data: dict, line):
155
+ if isinstance(line, BaseModel):
156
+ line = line.model_dump_json()
157
+ line = f"data: {line}"
158
+ if isinstance(line, dict):
159
+ line = f"data: {json.dumps(line)}"
160
+
161
+ try:
162
+ line = line.decode("utf-8")
163
+ except Exception:
164
+ pass
165
+
166
+ if line.startswith("data:"):
167
+ return f"{line}\n\n"
168
+ else:
169
+ line = openai_chat_chunk_message_template(form_data["model"], line)
170
+ return f"data: {json.dumps(line)}\n\n"
171
+
172
+ def get_pipe_id(form_data: dict) -> str:
173
+ pipe_id = form_data["model"]
174
+ if "." in pipe_id:
175
+ pipe_id, _ = pipe_id.split(".", 1)
176
+ return pipe_id
177
+
178
+ def get_function_params(function_module, form_data, user, extra_params=None):
179
+ if extra_params is None:
180
+ extra_params = {}
181
+
182
+ pipe_id = get_pipe_id(form_data)
183
+
184
+ # Get the signature of the function
185
+ sig = inspect.signature(function_module.pipe)
186
+ params = {"body": form_data} | {
187
+ k: v for k, v in extra_params.items() if k in sig.parameters
188
+ }
189
+
190
+ if "__user__" in params and hasattr(function_module, "UserValves"):
191
+ user_valves = Functions.get_user_valves_by_id_and_user_id(pipe_id, user.id)
192
+ try:
193
+ params["__user__"]["valves"] = function_module.UserValves(**user_valves)
194
+ except Exception as e:
195
+ log.exception(e)
196
+ params["__user__"]["valves"] = function_module.UserValves()
197
+
198
+ return params
199
+
200
+ model_id = form_data.get("model")
201
+ model_info = Models.get_model_by_id(model_id)
202
+
203
+ metadata = form_data.pop("metadata", {})
204
+
205
+ files = metadata.get("files", [])
206
+ tool_ids = metadata.get("tool_ids", [])
207
+ # Check if tool_ids is None
208
+ if tool_ids is None:
209
+ tool_ids = []
210
+
211
+ __event_emitter__ = None
212
+ __event_call__ = None
213
+ __task__ = None
214
+ __task_body__ = None
215
+
216
+ if metadata:
217
+ if all(k in metadata for k in ("session_id", "chat_id", "message_id")):
218
+ __event_emitter__ = get_event_emitter(metadata)
219
+ __event_call__ = get_event_call(metadata)
220
+ __task__ = metadata.get("task", None)
221
+ __task_body__ = metadata.get("task_body", None)
222
+
223
+ extra_params = {
224
+ "__event_emitter__": __event_emitter__,
225
+ "__event_call__": __event_call__,
226
+ "__chat_id__": metadata.get("chat_id", None),
227
+ "__session_id__": metadata.get("session_id", None),
228
+ "__message_id__": metadata.get("message_id", None),
229
+ "__task__": __task__,
230
+ "__task_body__": __task_body__,
231
+ "__files__": files,
232
+ "__user__": {
233
+ "id": user.id,
234
+ "email": user.email,
235
+ "name": user.name,
236
+ "role": user.role,
237
+ },
238
+ "__metadata__": metadata,
239
+ "__request__": request,
240
+ }
241
+ extra_params["__tools__"] = get_tools(
242
+ request,
243
+ tool_ids,
244
+ user,
245
+ {
246
+ **extra_params,
247
+ "__model__": models.get(form_data["model"], None),
248
+ "__messages__": form_data["messages"],
249
+ "__files__": files,
250
+ },
251
+ )
252
+
253
+ if model_info:
254
+ if model_info.base_model_id:
255
+ form_data["model"] = model_info.base_model_id
256
+
257
+ params = model_info.params.model_dump()
258
+ form_data = apply_model_params_to_body_openai(params, form_data)
259
+ form_data = apply_model_system_prompt_to_body(params, form_data, metadata, user)
260
+
261
+ pipe_id = get_pipe_id(form_data)
262
+ function_module = get_function_module_by_id(request, pipe_id)
263
+
264
+ pipe = function_module.pipe
265
+ params = get_function_params(function_module, form_data, user, extra_params)
266
+
267
+ if form_data.get("stream", False):
268
+
269
+ async def stream_content():
270
+ try:
271
+ res = await execute_pipe(pipe, params)
272
+
273
+ # Directly return if the response is a StreamingResponse
274
+ if isinstance(res, StreamingResponse):
275
+ async for data in res.body_iterator:
276
+ yield data
277
+ return
278
+ if isinstance(res, dict):
279
+ yield f"data: {json.dumps(res)}\n\n"
280
+ return
281
+
282
+ except Exception as e:
283
+ log.error(f"Error: {e}")
284
+ yield f"data: {json.dumps({'error': {'detail':str(e)}})}\n\n"
285
+ return
286
+
287
+ if isinstance(res, str):
288
+ message = openai_chat_chunk_message_template(form_data["model"], res)
289
+ yield f"data: {json.dumps(message)}\n\n"
290
+
291
+ if isinstance(res, Iterator):
292
+ for line in res:
293
+ yield process_line(form_data, line)
294
+
295
+ if isinstance(res, AsyncGenerator):
296
+ async for line in res:
297
+ yield process_line(form_data, line)
298
+
299
+ if isinstance(res, str) or isinstance(res, Generator):
300
+ finish_message = openai_chat_chunk_message_template(
301
+ form_data["model"], ""
302
+ )
303
+ finish_message["choices"][0]["finish_reason"] = "stop"
304
+ yield f"data: {json.dumps(finish_message)}\n\n"
305
+ yield "data: [DONE]"
306
+
307
+ return StreamingResponse(stream_content(), media_type="text/event-stream")
308
+ else:
309
+ try:
310
+ res = await execute_pipe(pipe, params)
311
+
312
+ except Exception as e:
313
+ log.error(f"Error: {e}")
314
+ return {"error": {"detail": str(e)}}
315
+
316
+ if isinstance(res, StreamingResponse) or isinstance(res, dict):
317
+ return res
318
+ if isinstance(res, BaseModel):
319
+ return res.model_dump()
320
+
321
+ message = await get_message_content(res)
322
+ return openai_chat_completion_message_template(form_data["model"], message)
backend/open_webui/internal/db.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ from contextlib import contextmanager
4
+ from typing import Any, Optional
5
+
6
+ from open_webui.internal.wrappers import register_connection
7
+ from open_webui.env import (
8
+ OPEN_WEBUI_DIR,
9
+ DATABASE_URL,
10
+ DATABASE_SCHEMA,
11
+ SRC_LOG_LEVELS,
12
+ DATABASE_POOL_MAX_OVERFLOW,
13
+ DATABASE_POOL_RECYCLE,
14
+ DATABASE_POOL_SIZE,
15
+ DATABASE_POOL_TIMEOUT,
16
+ )
17
+ from peewee_migrate import Router
18
+ from sqlalchemy import Dialect, create_engine, MetaData, types
19
+ from sqlalchemy.ext.declarative import declarative_base
20
+ from sqlalchemy.orm import scoped_session, sessionmaker
21
+ from sqlalchemy.pool import QueuePool, NullPool
22
+ from sqlalchemy.sql.type_api import _T
23
+ from typing_extensions import Self
24
+
25
+ log = logging.getLogger(__name__)
26
+ log.setLevel(SRC_LOG_LEVELS["DB"])
27
+
28
+
29
+ class JSONField(types.TypeDecorator):
30
+ impl = types.Text
31
+ cache_ok = True
32
+
33
+ def process_bind_param(self, value: Optional[_T], dialect: Dialect) -> Any:
34
+ return json.dumps(value)
35
+
36
+ def process_result_value(self, value: Optional[_T], dialect: Dialect) -> Any:
37
+ if value is not None:
38
+ return json.loads(value)
39
+
40
+ def copy(self, **kw: Any) -> Self:
41
+ return JSONField(self.impl.length)
42
+
43
+ def db_value(self, value):
44
+ return json.dumps(value)
45
+
46
+ def python_value(self, value):
47
+ if value is not None:
48
+ return json.loads(value)
49
+
50
+
51
+ # Workaround to handle the peewee migration
52
+ # This is required to ensure the peewee migration is handled before the alembic migration
53
+ def handle_peewee_migration(DATABASE_URL):
54
+ # db = None
55
+ try:
56
+ # Replace the postgresql:// with postgres:// to handle the peewee migration
57
+ db = register_connection(DATABASE_URL.replace("postgresql://", "postgres://"))
58
+ migrate_dir = OPEN_WEBUI_DIR / "internal" / "migrations"
59
+ router = Router(db, logger=log, migrate_dir=migrate_dir)
60
+ router.run()
61
+ db.close()
62
+
63
+ except Exception as e:
64
+ log.error(f"Failed to initialize the database connection: {e}")
65
+ raise
66
+ finally:
67
+ # Properly closing the database connection
68
+ if db and not db.is_closed():
69
+ db.close()
70
+
71
+ # Assert if db connection has been closed
72
+ assert db.is_closed(), "Database connection is still open."
73
+
74
+
75
+ handle_peewee_migration(DATABASE_URL)
76
+
77
+
78
+ SQLALCHEMY_DATABASE_URL = DATABASE_URL
79
+ if "sqlite" in SQLALCHEMY_DATABASE_URL:
80
+ engine = create_engine(
81
+ SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
82
+ )
83
+ else:
84
+ if DATABASE_POOL_SIZE > 0:
85
+ engine = create_engine(
86
+ SQLALCHEMY_DATABASE_URL,
87
+ pool_size=DATABASE_POOL_SIZE,
88
+ max_overflow=DATABASE_POOL_MAX_OVERFLOW,
89
+ pool_timeout=DATABASE_POOL_TIMEOUT,
90
+ pool_recycle=DATABASE_POOL_RECYCLE,
91
+ pool_pre_ping=True,
92
+ poolclass=QueuePool,
93
+ )
94
+ else:
95
+ engine = create_engine(
96
+ SQLALCHEMY_DATABASE_URL, pool_pre_ping=True, poolclass=NullPool
97
+ )
98
+
99
+
100
+ SessionLocal = sessionmaker(
101
+ autocommit=False, autoflush=False, bind=engine, expire_on_commit=False
102
+ )
103
+ metadata_obj = MetaData(schema=DATABASE_SCHEMA)
104
+ Base = declarative_base(metadata=metadata_obj)
105
+ Session = scoped_session(SessionLocal)
106
+
107
+
108
+ def get_session():
109
+ db = SessionLocal()
110
+ try:
111
+ yield db
112
+ finally:
113
+ db.close()
114
+
115
+
116
+ 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")