github-actions[bot]
commited on
Commit
•
8437908
0
Parent(s):
GitHub deploy: 96c865404d36637eafadb6d2dd2365c85d452648
Browse filesThis view is limited to 50 files because it contains too many changes.
See raw diff
- .dockerignore +19 -0
- .env.example +13 -0
- .eslintignore +13 -0
- .eslintrc.cjs +31 -0
- .gitattributes +2 -0
- .github/FUNDING.yml +1 -0
- .github/ISSUE_TEMPLATE/bug_report.md +80 -0
- .github/ISSUE_TEMPLATE/feature_request.md +35 -0
- .github/dependabot.yml +12 -0
- .github/pull_request_template.md +72 -0
- .github/workflows/build-release.yml +72 -0
- .github/workflows/deploy-to-hf-spaces.yml +59 -0
- .github/workflows/docker-build.yaml +477 -0
- .github/workflows/format-backend.yaml +39 -0
- .github/workflows/format-build-frontend.yaml +57 -0
- .github/workflows/integration-test.yml +253 -0
- .github/workflows/lint-backend.disabled +27 -0
- .github/workflows/lint-frontend.disabled +21 -0
- .github/workflows/release-pypi.yml +32 -0
- .gitignore +309 -0
- .npmrc +1 -0
- .prettierignore +316 -0
- .prettierrc +9 -0
- CHANGELOG.md +1226 -0
- CODE_OF_CONDUCT.md +77 -0
- Caddyfile.localhost +64 -0
- Dockerfile +176 -0
- INSTALLATION.md +35 -0
- LICENSE +21 -0
- Makefile +33 -0
- README.md +219 -0
- TROUBLESHOOTING.md +36 -0
- backend/.dockerignore +14 -0
- backend/.gitignore +12 -0
- backend/dev.sh +2 -0
- backend/open_webui/__init__.py +77 -0
- backend/open_webui/alembic.ini +114 -0
- backend/open_webui/apps/audio/main.py +641 -0
- backend/open_webui/apps/images/main.py +598 -0
- backend/open_webui/apps/images/utils/comfyui.py +186 -0
- backend/open_webui/apps/ollama/main.py +1123 -0
- backend/open_webui/apps/openai/main.py +557 -0
- backend/open_webui/apps/retrieval/loaders/main.py +190 -0
- backend/open_webui/apps/retrieval/main.py +1332 -0
- backend/open_webui/apps/retrieval/models/colbert.py +81 -0
- backend/open_webui/apps/retrieval/utils.py +573 -0
- backend/open_webui/apps/retrieval/vector/connector.py +14 -0
- backend/open_webui/apps/retrieval/vector/dbs/chroma.py +161 -0
- backend/open_webui/apps/retrieval/vector/dbs/milvus.py +286 -0
- backend/open_webui/apps/retrieval/vector/dbs/qdrant.py +179 -0
.dockerignore
ADDED
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
.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,2 @@
|
|
|
|
|
|
|
1 |
+
*.sh text eol=lf
|
2 |
+
*.ttf filter=lfs diff=lfs merge=lfs -text
|
.github/FUNDING.yml
ADDED
@@ -0,0 +1 @@
|
|
|
|
|
1 |
+
github: tjbck
|
.github/ISSUE_TEMPLATE/bug_report.md
ADDED
@@ -0,0 +1,80 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
name: Bug report
|
3 |
+
about: Create a report to help us improve
|
4 |
+
title: ''
|
5 |
+
labels: ''
|
6 |
+
assignees: ''
|
7 |
+
---
|
8 |
+
|
9 |
+
# Bug Report
|
10 |
+
|
11 |
+
## Important Notes
|
12 |
+
|
13 |
+
- **Before submitting a bug report**: Please check the Issues or Discussions section to see if a similar issue or feature request has already been posted. It's likely we're already tracking it! If you’re unsure, start a discussion post first. This will help us efficiently focus on improving the project.
|
14 |
+
|
15 |
+
- **Collaborate respectfully**: 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. Remember, Open WebUI is a volunteer-driven project managed by a single maintainer and supported by contributors who also have full-time jobs. We appreciate your time and ask that you respect ours.
|
16 |
+
|
17 |
+
- **Contributing**: 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.
|
18 |
+
|
19 |
+
- **Bug reproducibility**: 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" 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!
|
20 |
+
|
21 |
+
Note: Please remove the notes above when submitting your post. Thank you for your understanding and support!
|
22 |
+
|
23 |
+
---
|
24 |
+
|
25 |
+
## Installation Method
|
26 |
+
|
27 |
+
[Describe the method you used to install the project, e.g., git clone, Docker, pip, etc.]
|
28 |
+
|
29 |
+
## Environment
|
30 |
+
|
31 |
+
- **Open WebUI Version:** [e.g., v0.3.11]
|
32 |
+
- **Ollama (if applicable):** [e.g., v0.2.0, v0.1.32-rc1]
|
33 |
+
|
34 |
+
- **Operating System:** [e.g., Windows 10, macOS Big Sur, Ubuntu 20.04]
|
35 |
+
- **Browser (if applicable):** [e.g., Chrome 100.0, Firefox 98.0]
|
36 |
+
|
37 |
+
**Confirmation:**
|
38 |
+
|
39 |
+
- [ ] I have read and followed all the instructions provided in the README.md.
|
40 |
+
- [ ] I am on the latest version of both Open WebUI and Ollama.
|
41 |
+
- [ ] I have included the browser console logs.
|
42 |
+
- [ ] I have included the Docker container logs.
|
43 |
+
- [ ] I have provided the exact steps to reproduce the bug in the "Steps to Reproduce" section below.
|
44 |
+
|
45 |
+
## Expected Behavior:
|
46 |
+
|
47 |
+
[Describe what you expected to happen.]
|
48 |
+
|
49 |
+
## Actual Behavior:
|
50 |
+
|
51 |
+
[Describe what actually happened.]
|
52 |
+
|
53 |
+
## Description
|
54 |
+
|
55 |
+
**Bug Summary:**
|
56 |
+
[Provide a brief but clear summary of the bug]
|
57 |
+
|
58 |
+
## Reproduction Details
|
59 |
+
|
60 |
+
**Steps to Reproduce:**
|
61 |
+
[Outline the steps to reproduce the bug. Be as detailed as possible.]
|
62 |
+
|
63 |
+
## Logs and Screenshots
|
64 |
+
|
65 |
+
**Browser Console Logs:**
|
66 |
+
[Include relevant browser console logs, if applicable]
|
67 |
+
|
68 |
+
**Docker Container Logs:**
|
69 |
+
[Include relevant Docker container logs, if applicable]
|
70 |
+
|
71 |
+
**Screenshots/Screen Recordings (if applicable):**
|
72 |
+
[Attach any relevant screenshots to help illustrate the issue]
|
73 |
+
|
74 |
+
## Additional Information
|
75 |
+
|
76 |
+
[Include any additional details that may help in understanding and reproducing the issue. This could include specific configurations, error messages, or anything else relevant to the bug.]
|
77 |
+
|
78 |
+
## Note
|
79 |
+
|
80 |
+
If the bug report is incomplete or does not follow the provided instructions, it may not be addressed. Please ensure that you have followed the steps outlined in the README.md and troubleshooting.md documents, and provide all necessary information for us to reproduce and address the issue. Thank you!
|
.github/ISSUE_TEMPLATE/feature_request.md
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
name: Feature request
|
3 |
+
about: Suggest an idea for this project
|
4 |
+
title: ''
|
5 |
+
labels: ''
|
6 |
+
assignees: ''
|
7 |
+
---
|
8 |
+
|
9 |
+
# Feature Request
|
10 |
+
|
11 |
+
## Important Notes
|
12 |
+
|
13 |
+
- **Before submitting a report**: Please check the Issues or Discussions section to see if a similar issue or feature request has already been posted. It's likely we're already tracking it! If you’re unsure, start a discussion post first. This will help us efficiently focus on improving the project.
|
14 |
+
|
15 |
+
- **Collaborate respectfully**: 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. Remember, Open WebUI is a volunteer-driven project managed by a single maintainer and supported by contributors who also have full-time jobs. We appreciate your time and ask that you respect ours.
|
16 |
+
|
17 |
+
- **Contributing**: 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.
|
18 |
+
|
19 |
+
- **Bug reproducibility**: 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" 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!
|
20 |
+
|
21 |
+
Note: Please remove the notes above when submitting your post. Thank you for your understanding and support!
|
22 |
+
|
23 |
+
---
|
24 |
+
|
25 |
+
**Is your feature request related to a problem? Please describe.**
|
26 |
+
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
|
27 |
+
|
28 |
+
**Describe the solution you'd like**
|
29 |
+
A clear and concise description of what you want to happen.
|
30 |
+
|
31 |
+
**Describe alternatives you've considered**
|
32 |
+
A clear and concise description of any alternative solutions or features you've considered.
|
33 |
+
|
34 |
+
**Additional context**
|
35 |
+
Add any other context or screenshots about the feature request here.
|
.github/dependabot.yml
ADDED
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
version: 2
|
2 |
+
updates:
|
3 |
+
- package-ecosystem: pip
|
4 |
+
directory: '/backend'
|
5 |
+
schedule:
|
6 |
+
interval: monthly
|
7 |
+
target-branch: 'dev'
|
8 |
+
- package-ecosystem: 'github-actions'
|
9 |
+
directory: '/'
|
10 |
+
schedule:
|
11 |
+
# Check for updates to GitHub Actions every week
|
12 |
+
interval: monthly
|
.github/pull_request_template.md
ADDED
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 for validating 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 cleary 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]
|
.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/deploy-to-hf-spaces.yml
ADDED
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: Deploy to HuggingFace Spaces
|
2 |
+
|
3 |
+
on:
|
4 |
+
push:
|
5 |
+
branches:
|
6 |
+
- dev
|
7 |
+
- main
|
8 |
+
workflow_dispatch:
|
9 |
+
|
10 |
+
jobs:
|
11 |
+
check-secret:
|
12 |
+
runs-on: ubuntu-latest
|
13 |
+
outputs:
|
14 |
+
token-set: ${{ steps.check-key.outputs.defined }}
|
15 |
+
steps:
|
16 |
+
- id: check-key
|
17 |
+
env:
|
18 |
+
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
19 |
+
if: "${{ env.HF_TOKEN != '' }}"
|
20 |
+
run: echo "defined=true" >> $GITHUB_OUTPUT
|
21 |
+
|
22 |
+
deploy:
|
23 |
+
runs-on: ubuntu-latest
|
24 |
+
needs: [check-secret]
|
25 |
+
if: needs.check-secret.outputs.token-set == 'true'
|
26 |
+
env:
|
27 |
+
HF_TOKEN: ${{ secrets.HF_TOKEN }}
|
28 |
+
steps:
|
29 |
+
- name: Checkout repository
|
30 |
+
uses: actions/checkout@v4
|
31 |
+
|
32 |
+
- name: Remove git history
|
33 |
+
run: rm -rf .git
|
34 |
+
|
35 |
+
- name: Prepend YAML front matter to README.md
|
36 |
+
run: |
|
37 |
+
echo "---" > temp_readme.md
|
38 |
+
echo "title: Open WebUI" >> temp_readme.md
|
39 |
+
echo "emoji: 🐳" >> temp_readme.md
|
40 |
+
echo "colorFrom: purple" >> temp_readme.md
|
41 |
+
echo "colorTo: gray" >> temp_readme.md
|
42 |
+
echo "sdk: docker" >> temp_readme.md
|
43 |
+
echo "app_port: 8080" >> temp_readme.md
|
44 |
+
echo "---" >> temp_readme.md
|
45 |
+
cat README.md >> temp_readme.md
|
46 |
+
mv temp_readme.md README.md
|
47 |
+
|
48 |
+
- name: Configure git
|
49 |
+
run: |
|
50 |
+
git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com"
|
51 |
+
git config --global user.name "github-actions[bot]"
|
52 |
+
- name: Set up Git and push to Space
|
53 |
+
run: |
|
54 |
+
git init --initial-branch=main
|
55 |
+
git lfs track "*.ttf"
|
56 |
+
rm demo.gif
|
57 |
+
git add .
|
58 |
+
git commit -m "GitHub deploy: ${{ github.sha }}"
|
59 |
+
git push --force https://open-webui:${HF_TOKEN}@huggingface.co/spaces/open-webui/open-webui main
|
.github/workflows/docker-build.yaml
ADDED
@@ -0,0 +1,477 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: Create and publish Docker images with specific build args
|
2 |
+
|
3 |
+
on:
|
4 |
+
workflow_dispatch:
|
5 |
+
push:
|
6 |
+
branches:
|
7 |
+
- main
|
8 |
+
- dev
|
9 |
+
tags:
|
10 |
+
- v*
|
11 |
+
|
12 |
+
env:
|
13 |
+
REGISTRY: ghcr.io
|
14 |
+
|
15 |
+
jobs:
|
16 |
+
build-main-image:
|
17 |
+
runs-on: ubuntu-latest
|
18 |
+
permissions:
|
19 |
+
contents: read
|
20 |
+
packages: write
|
21 |
+
strategy:
|
22 |
+
fail-fast: false
|
23 |
+
matrix:
|
24 |
+
platform:
|
25 |
+
- linux/amd64
|
26 |
+
- linux/arm64
|
27 |
+
|
28 |
+
steps:
|
29 |
+
# GitHub Packages requires the entire repository name to be in lowercase
|
30 |
+
# although the repository owner has a lowercase username, this prevents some people from running actions after forking
|
31 |
+
- name: Set repository and image name to lowercase
|
32 |
+
run: |
|
33 |
+
echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
|
34 |
+
echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
|
35 |
+
env:
|
36 |
+
IMAGE_NAME: '${{ github.repository }}'
|
37 |
+
|
38 |
+
- name: Prepare
|
39 |
+
run: |
|
40 |
+
platform=${{ matrix.platform }}
|
41 |
+
echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
|
42 |
+
|
43 |
+
- name: Checkout repository
|
44 |
+
uses: actions/checkout@v4
|
45 |
+
|
46 |
+
- name: Set up QEMU
|
47 |
+
uses: docker/setup-qemu-action@v3
|
48 |
+
|
49 |
+
- name: Set up Docker Buildx
|
50 |
+
uses: docker/setup-buildx-action@v3
|
51 |
+
|
52 |
+
- name: Log in to the Container registry
|
53 |
+
uses: docker/login-action@v3
|
54 |
+
with:
|
55 |
+
registry: ${{ env.REGISTRY }}
|
56 |
+
username: ${{ github.actor }}
|
57 |
+
password: ${{ secrets.GITHUB_TOKEN }}
|
58 |
+
|
59 |
+
- name: Extract metadata for Docker images (default latest tag)
|
60 |
+
id: meta
|
61 |
+
uses: docker/metadata-action@v5
|
62 |
+
with:
|
63 |
+
images: ${{ env.FULL_IMAGE_NAME }}
|
64 |
+
tags: |
|
65 |
+
type=ref,event=branch
|
66 |
+
type=ref,event=tag
|
67 |
+
type=sha,prefix=git-
|
68 |
+
type=semver,pattern={{version}}
|
69 |
+
type=semver,pattern={{major}}.{{minor}}
|
70 |
+
flavor: |
|
71 |
+
latest=${{ github.ref == 'refs/heads/main' }}
|
72 |
+
|
73 |
+
- name: Extract metadata for Docker cache
|
74 |
+
id: cache-meta
|
75 |
+
uses: docker/metadata-action@v5
|
76 |
+
with:
|
77 |
+
images: ${{ env.FULL_IMAGE_NAME }}
|
78 |
+
tags: |
|
79 |
+
type=ref,event=branch
|
80 |
+
${{ github.ref_type == 'tag' && 'type=raw,value=main' || '' }}
|
81 |
+
flavor: |
|
82 |
+
prefix=cache-${{ matrix.platform }}-
|
83 |
+
latest=false
|
84 |
+
|
85 |
+
- name: Build Docker image (latest)
|
86 |
+
uses: docker/build-push-action@v5
|
87 |
+
id: build
|
88 |
+
with:
|
89 |
+
context: .
|
90 |
+
push: true
|
91 |
+
platforms: ${{ matrix.platform }}
|
92 |
+
labels: ${{ steps.meta.outputs.labels }}
|
93 |
+
outputs: type=image,name=${{ env.FULL_IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
|
94 |
+
cache-from: type=registry,ref=${{ steps.cache-meta.outputs.tags }}
|
95 |
+
cache-to: type=registry,ref=${{ steps.cache-meta.outputs.tags }},mode=max
|
96 |
+
build-args: |
|
97 |
+
BUILD_HASH=${{ github.sha }}
|
98 |
+
|
99 |
+
- name: Export digest
|
100 |
+
run: |
|
101 |
+
mkdir -p /tmp/digests
|
102 |
+
digest="${{ steps.build.outputs.digest }}"
|
103 |
+
touch "/tmp/digests/${digest#sha256:}"
|
104 |
+
|
105 |
+
- name: Upload digest
|
106 |
+
uses: actions/upload-artifact@v4
|
107 |
+
with:
|
108 |
+
name: digests-main-${{ env.PLATFORM_PAIR }}
|
109 |
+
path: /tmp/digests/*
|
110 |
+
if-no-files-found: error
|
111 |
+
retention-days: 1
|
112 |
+
|
113 |
+
build-cuda-image:
|
114 |
+
runs-on: ubuntu-latest
|
115 |
+
permissions:
|
116 |
+
contents: read
|
117 |
+
packages: write
|
118 |
+
strategy:
|
119 |
+
fail-fast: false
|
120 |
+
matrix:
|
121 |
+
platform:
|
122 |
+
- linux/amd64
|
123 |
+
- linux/arm64
|
124 |
+
|
125 |
+
steps:
|
126 |
+
# GitHub Packages requires the entire repository name to be in lowercase
|
127 |
+
# although the repository owner has a lowercase username, this prevents some people from running actions after forking
|
128 |
+
- name: Set repository and image name to lowercase
|
129 |
+
run: |
|
130 |
+
echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
|
131 |
+
echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
|
132 |
+
env:
|
133 |
+
IMAGE_NAME: '${{ github.repository }}'
|
134 |
+
|
135 |
+
- name: Prepare
|
136 |
+
run: |
|
137 |
+
platform=${{ matrix.platform }}
|
138 |
+
echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
|
139 |
+
|
140 |
+
- name: Checkout repository
|
141 |
+
uses: actions/checkout@v4
|
142 |
+
|
143 |
+
- name: Set up QEMU
|
144 |
+
uses: docker/setup-qemu-action@v3
|
145 |
+
|
146 |
+
- name: Set up Docker Buildx
|
147 |
+
uses: docker/setup-buildx-action@v3
|
148 |
+
|
149 |
+
- name: Log in to the Container registry
|
150 |
+
uses: docker/login-action@v3
|
151 |
+
with:
|
152 |
+
registry: ${{ env.REGISTRY }}
|
153 |
+
username: ${{ github.actor }}
|
154 |
+
password: ${{ secrets.GITHUB_TOKEN }}
|
155 |
+
|
156 |
+
- name: Extract metadata for Docker images (cuda tag)
|
157 |
+
id: meta
|
158 |
+
uses: docker/metadata-action@v5
|
159 |
+
with:
|
160 |
+
images: ${{ env.FULL_IMAGE_NAME }}
|
161 |
+
tags: |
|
162 |
+
type=ref,event=branch
|
163 |
+
type=ref,event=tag
|
164 |
+
type=sha,prefix=git-
|
165 |
+
type=semver,pattern={{version}}
|
166 |
+
type=semver,pattern={{major}}.{{minor}}
|
167 |
+
type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=cuda
|
168 |
+
flavor: |
|
169 |
+
latest=${{ github.ref == 'refs/heads/main' }}
|
170 |
+
suffix=-cuda,onlatest=true
|
171 |
+
|
172 |
+
- name: Extract metadata for Docker cache
|
173 |
+
id: cache-meta
|
174 |
+
uses: docker/metadata-action@v5
|
175 |
+
with:
|
176 |
+
images: ${{ env.FULL_IMAGE_NAME }}
|
177 |
+
tags: |
|
178 |
+
type=ref,event=branch
|
179 |
+
${{ github.ref_type == 'tag' && 'type=raw,value=main' || '' }}
|
180 |
+
flavor: |
|
181 |
+
prefix=cache-cuda-${{ matrix.platform }}-
|
182 |
+
latest=false
|
183 |
+
|
184 |
+
- name: Build Docker image (cuda)
|
185 |
+
uses: docker/build-push-action@v5
|
186 |
+
id: build
|
187 |
+
with:
|
188 |
+
context: .
|
189 |
+
push: true
|
190 |
+
platforms: ${{ matrix.platform }}
|
191 |
+
labels: ${{ steps.meta.outputs.labels }}
|
192 |
+
outputs: type=image,name=${{ env.FULL_IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
|
193 |
+
cache-from: type=registry,ref=${{ steps.cache-meta.outputs.tags }}
|
194 |
+
cache-to: type=registry,ref=${{ steps.cache-meta.outputs.tags }},mode=max
|
195 |
+
build-args: |
|
196 |
+
BUILD_HASH=${{ github.sha }}
|
197 |
+
USE_CUDA=true
|
198 |
+
|
199 |
+
- name: Export digest
|
200 |
+
run: |
|
201 |
+
mkdir -p /tmp/digests
|
202 |
+
digest="${{ steps.build.outputs.digest }}"
|
203 |
+
touch "/tmp/digests/${digest#sha256:}"
|
204 |
+
|
205 |
+
- name: Upload digest
|
206 |
+
uses: actions/upload-artifact@v4
|
207 |
+
with:
|
208 |
+
name: digests-cuda-${{ env.PLATFORM_PAIR }}
|
209 |
+
path: /tmp/digests/*
|
210 |
+
if-no-files-found: error
|
211 |
+
retention-days: 1
|
212 |
+
|
213 |
+
build-ollama-image:
|
214 |
+
runs-on: ubuntu-latest
|
215 |
+
permissions:
|
216 |
+
contents: read
|
217 |
+
packages: write
|
218 |
+
strategy:
|
219 |
+
fail-fast: false
|
220 |
+
matrix:
|
221 |
+
platform:
|
222 |
+
- linux/amd64
|
223 |
+
- linux/arm64
|
224 |
+
|
225 |
+
steps:
|
226 |
+
# GitHub Packages requires the entire repository name to be in lowercase
|
227 |
+
# although the repository owner has a lowercase username, this prevents some people from running actions after forking
|
228 |
+
- name: Set repository and image name to lowercase
|
229 |
+
run: |
|
230 |
+
echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
|
231 |
+
echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
|
232 |
+
env:
|
233 |
+
IMAGE_NAME: '${{ github.repository }}'
|
234 |
+
|
235 |
+
- name: Prepare
|
236 |
+
run: |
|
237 |
+
platform=${{ matrix.platform }}
|
238 |
+
echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
|
239 |
+
|
240 |
+
- name: Checkout repository
|
241 |
+
uses: actions/checkout@v4
|
242 |
+
|
243 |
+
- name: Set up QEMU
|
244 |
+
uses: docker/setup-qemu-action@v3
|
245 |
+
|
246 |
+
- name: Set up Docker Buildx
|
247 |
+
uses: docker/setup-buildx-action@v3
|
248 |
+
|
249 |
+
- name: Log in to the Container registry
|
250 |
+
uses: docker/login-action@v3
|
251 |
+
with:
|
252 |
+
registry: ${{ env.REGISTRY }}
|
253 |
+
username: ${{ github.actor }}
|
254 |
+
password: ${{ secrets.GITHUB_TOKEN }}
|
255 |
+
|
256 |
+
- name: Extract metadata for Docker images (ollama tag)
|
257 |
+
id: meta
|
258 |
+
uses: docker/metadata-action@v5
|
259 |
+
with:
|
260 |
+
images: ${{ env.FULL_IMAGE_NAME }}
|
261 |
+
tags: |
|
262 |
+
type=ref,event=branch
|
263 |
+
type=ref,event=tag
|
264 |
+
type=sha,prefix=git-
|
265 |
+
type=semver,pattern={{version}}
|
266 |
+
type=semver,pattern={{major}}.{{minor}}
|
267 |
+
type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=ollama
|
268 |
+
flavor: |
|
269 |
+
latest=${{ github.ref == 'refs/heads/main' }}
|
270 |
+
suffix=-ollama,onlatest=true
|
271 |
+
|
272 |
+
- name: Extract metadata for Docker cache
|
273 |
+
id: cache-meta
|
274 |
+
uses: docker/metadata-action@v5
|
275 |
+
with:
|
276 |
+
images: ${{ env.FULL_IMAGE_NAME }}
|
277 |
+
tags: |
|
278 |
+
type=ref,event=branch
|
279 |
+
${{ github.ref_type == 'tag' && 'type=raw,value=main' || '' }}
|
280 |
+
flavor: |
|
281 |
+
prefix=cache-ollama-${{ matrix.platform }}-
|
282 |
+
latest=false
|
283 |
+
|
284 |
+
- name: Build Docker image (ollama)
|
285 |
+
uses: docker/build-push-action@v5
|
286 |
+
id: build
|
287 |
+
with:
|
288 |
+
context: .
|
289 |
+
push: true
|
290 |
+
platforms: ${{ matrix.platform }}
|
291 |
+
labels: ${{ steps.meta.outputs.labels }}
|
292 |
+
outputs: type=image,name=${{ env.FULL_IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
|
293 |
+
cache-from: type=registry,ref=${{ steps.cache-meta.outputs.tags }}
|
294 |
+
cache-to: type=registry,ref=${{ steps.cache-meta.outputs.tags }},mode=max
|
295 |
+
build-args: |
|
296 |
+
BUILD_HASH=${{ github.sha }}
|
297 |
+
USE_OLLAMA=true
|
298 |
+
|
299 |
+
- name: Export digest
|
300 |
+
run: |
|
301 |
+
mkdir -p /tmp/digests
|
302 |
+
digest="${{ steps.build.outputs.digest }}"
|
303 |
+
touch "/tmp/digests/${digest#sha256:}"
|
304 |
+
|
305 |
+
- name: Upload digest
|
306 |
+
uses: actions/upload-artifact@v4
|
307 |
+
with:
|
308 |
+
name: digests-ollama-${{ env.PLATFORM_PAIR }}
|
309 |
+
path: /tmp/digests/*
|
310 |
+
if-no-files-found: error
|
311 |
+
retention-days: 1
|
312 |
+
|
313 |
+
merge-main-images:
|
314 |
+
runs-on: ubuntu-latest
|
315 |
+
needs: [build-main-image]
|
316 |
+
steps:
|
317 |
+
# GitHub Packages requires the entire repository name to be in lowercase
|
318 |
+
# although the repository owner has a lowercase username, this prevents some people from running actions after forking
|
319 |
+
- name: Set repository and image name to lowercase
|
320 |
+
run: |
|
321 |
+
echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
|
322 |
+
echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
|
323 |
+
env:
|
324 |
+
IMAGE_NAME: '${{ github.repository }}'
|
325 |
+
|
326 |
+
- name: Download digests
|
327 |
+
uses: actions/download-artifact@v4
|
328 |
+
with:
|
329 |
+
pattern: digests-main-*
|
330 |
+
path: /tmp/digests
|
331 |
+
merge-multiple: true
|
332 |
+
|
333 |
+
- name: Set up Docker Buildx
|
334 |
+
uses: docker/setup-buildx-action@v3
|
335 |
+
|
336 |
+
- name: Log in to the Container registry
|
337 |
+
uses: docker/login-action@v3
|
338 |
+
with:
|
339 |
+
registry: ${{ env.REGISTRY }}
|
340 |
+
username: ${{ github.actor }}
|
341 |
+
password: ${{ secrets.GITHUB_TOKEN }}
|
342 |
+
|
343 |
+
- name: Extract metadata for Docker images (default latest tag)
|
344 |
+
id: meta
|
345 |
+
uses: docker/metadata-action@v5
|
346 |
+
with:
|
347 |
+
images: ${{ env.FULL_IMAGE_NAME }}
|
348 |
+
tags: |
|
349 |
+
type=ref,event=branch
|
350 |
+
type=ref,event=tag
|
351 |
+
type=sha,prefix=git-
|
352 |
+
type=semver,pattern={{version}}
|
353 |
+
type=semver,pattern={{major}}.{{minor}}
|
354 |
+
flavor: |
|
355 |
+
latest=${{ github.ref == 'refs/heads/main' }}
|
356 |
+
|
357 |
+
- name: Create manifest list and push
|
358 |
+
working-directory: /tmp/digests
|
359 |
+
run: |
|
360 |
+
docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
|
361 |
+
$(printf '${{ env.FULL_IMAGE_NAME }}@sha256:%s ' *)
|
362 |
+
|
363 |
+
- name: Inspect image
|
364 |
+
run: |
|
365 |
+
docker buildx imagetools inspect ${{ env.FULL_IMAGE_NAME }}:${{ steps.meta.outputs.version }}
|
366 |
+
|
367 |
+
merge-cuda-images:
|
368 |
+
runs-on: ubuntu-latest
|
369 |
+
needs: [build-cuda-image]
|
370 |
+
steps:
|
371 |
+
# GitHub Packages requires the entire repository name to be in lowercase
|
372 |
+
# although the repository owner has a lowercase username, this prevents some people from running actions after forking
|
373 |
+
- name: Set repository and image name to lowercase
|
374 |
+
run: |
|
375 |
+
echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
|
376 |
+
echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
|
377 |
+
env:
|
378 |
+
IMAGE_NAME: '${{ github.repository }}'
|
379 |
+
|
380 |
+
- name: Download digests
|
381 |
+
uses: actions/download-artifact@v4
|
382 |
+
with:
|
383 |
+
pattern: digests-cuda-*
|
384 |
+
path: /tmp/digests
|
385 |
+
merge-multiple: true
|
386 |
+
|
387 |
+
- name: Set up Docker Buildx
|
388 |
+
uses: docker/setup-buildx-action@v3
|
389 |
+
|
390 |
+
- name: Log in to the Container registry
|
391 |
+
uses: docker/login-action@v3
|
392 |
+
with:
|
393 |
+
registry: ${{ env.REGISTRY }}
|
394 |
+
username: ${{ github.actor }}
|
395 |
+
password: ${{ secrets.GITHUB_TOKEN }}
|
396 |
+
|
397 |
+
- name: Extract metadata for Docker images (default latest tag)
|
398 |
+
id: meta
|
399 |
+
uses: docker/metadata-action@v5
|
400 |
+
with:
|
401 |
+
images: ${{ env.FULL_IMAGE_NAME }}
|
402 |
+
tags: |
|
403 |
+
type=ref,event=branch
|
404 |
+
type=ref,event=tag
|
405 |
+
type=sha,prefix=git-
|
406 |
+
type=semver,pattern={{version}}
|
407 |
+
type=semver,pattern={{major}}.{{minor}}
|
408 |
+
type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=cuda
|
409 |
+
flavor: |
|
410 |
+
latest=${{ github.ref == 'refs/heads/main' }}
|
411 |
+
suffix=-cuda,onlatest=true
|
412 |
+
|
413 |
+
- name: Create manifest list and push
|
414 |
+
working-directory: /tmp/digests
|
415 |
+
run: |
|
416 |
+
docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
|
417 |
+
$(printf '${{ env.FULL_IMAGE_NAME }}@sha256:%s ' *)
|
418 |
+
|
419 |
+
- name: Inspect image
|
420 |
+
run: |
|
421 |
+
docker buildx imagetools inspect ${{ env.FULL_IMAGE_NAME }}:${{ steps.meta.outputs.version }}
|
422 |
+
|
423 |
+
merge-ollama-images:
|
424 |
+
runs-on: ubuntu-latest
|
425 |
+
needs: [build-ollama-image]
|
426 |
+
steps:
|
427 |
+
# GitHub Packages requires the entire repository name to be in lowercase
|
428 |
+
# although the repository owner has a lowercase username, this prevents some people from running actions after forking
|
429 |
+
- name: Set repository and image name to lowercase
|
430 |
+
run: |
|
431 |
+
echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
|
432 |
+
echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
|
433 |
+
env:
|
434 |
+
IMAGE_NAME: '${{ github.repository }}'
|
435 |
+
|
436 |
+
- name: Download digests
|
437 |
+
uses: actions/download-artifact@v4
|
438 |
+
with:
|
439 |
+
pattern: digests-ollama-*
|
440 |
+
path: /tmp/digests
|
441 |
+
merge-multiple: true
|
442 |
+
|
443 |
+
- name: Set up Docker Buildx
|
444 |
+
uses: docker/setup-buildx-action@v3
|
445 |
+
|
446 |
+
- name: Log in to the Container registry
|
447 |
+
uses: docker/login-action@v3
|
448 |
+
with:
|
449 |
+
registry: ${{ env.REGISTRY }}
|
450 |
+
username: ${{ github.actor }}
|
451 |
+
password: ${{ secrets.GITHUB_TOKEN }}
|
452 |
+
|
453 |
+
- name: Extract metadata for Docker images (default ollama tag)
|
454 |
+
id: meta
|
455 |
+
uses: docker/metadata-action@v5
|
456 |
+
with:
|
457 |
+
images: ${{ env.FULL_IMAGE_NAME }}
|
458 |
+
tags: |
|
459 |
+
type=ref,event=branch
|
460 |
+
type=ref,event=tag
|
461 |
+
type=sha,prefix=git-
|
462 |
+
type=semver,pattern={{version}}
|
463 |
+
type=semver,pattern={{major}}.{{minor}}
|
464 |
+
type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=ollama
|
465 |
+
flavor: |
|
466 |
+
latest=${{ github.ref == 'refs/heads/main' }}
|
467 |
+
suffix=-ollama,onlatest=true
|
468 |
+
|
469 |
+
- name: Create manifest list and push
|
470 |
+
working-directory: /tmp/digests
|
471 |
+
run: |
|
472 |
+
docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
|
473 |
+
$(printf '${{ env.FULL_IMAGE_NAME }}@sha256:%s ' *)
|
474 |
+
|
475 |
+
- name: Inspect image
|
476 |
+
run: |
|
477 |
+
docker buildx imagetools inspect ${{ env.FULL_IMAGE_NAME }}:${{ steps.meta.outputs.version }}
|
.github/workflows/format-backend.yaml
ADDED
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: Python CI
|
2 |
+
|
3 |
+
on:
|
4 |
+
push:
|
5 |
+
branches:
|
6 |
+
- main
|
7 |
+
- dev
|
8 |
+
pull_request:
|
9 |
+
branches:
|
10 |
+
- main
|
11 |
+
- dev
|
12 |
+
|
13 |
+
jobs:
|
14 |
+
build:
|
15 |
+
name: 'Format Backend'
|
16 |
+
runs-on: ubuntu-latest
|
17 |
+
|
18 |
+
strategy:
|
19 |
+
matrix:
|
20 |
+
python-version: [3.11]
|
21 |
+
|
22 |
+
steps:
|
23 |
+
- uses: actions/checkout@v4
|
24 |
+
|
25 |
+
- name: Set up Python
|
26 |
+
uses: actions/setup-python@v5
|
27 |
+
with:
|
28 |
+
python-version: ${{ matrix.python-version }}
|
29 |
+
|
30 |
+
- name: Install dependencies
|
31 |
+
run: |
|
32 |
+
python -m pip install --upgrade pip
|
33 |
+
pip install black
|
34 |
+
|
35 |
+
- name: Format backend
|
36 |
+
run: npm run format:backend
|
37 |
+
|
38 |
+
- name: Check for changes after format
|
39 |
+
run: git diff --exit-code
|
.github/workflows/format-build-frontend.yaml
ADDED
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
name: Frontend Build
|
2 |
+
|
3 |
+
on:
|
4 |
+
push:
|
5 |
+
branches:
|
6 |
+
- main
|
7 |
+
- dev
|
8 |
+
pull_request:
|
9 |
+
branches:
|
10 |
+
- main
|
11 |
+
- dev
|
12 |
+
|
13 |
+
jobs:
|
14 |
+
build:
|
15 |
+
name: 'Format & Build Frontend'
|
16 |
+
runs-on: ubuntu-latest
|
17 |
+
steps:
|
18 |
+
- name: Checkout Repository
|
19 |
+
uses: actions/checkout@v4
|
20 |
+
|
21 |
+
- name: Setup Node.js
|
22 |
+
uses: actions/setup-node@v4
|
23 |
+
with:
|
24 |
+
node-version: '22' # Or specify any other version you want to use
|
25 |
+
|
26 |
+
- name: Install Dependencies
|
27 |
+
run: npm install
|
28 |
+
|
29 |
+
- name: Format Frontend
|
30 |
+
run: npm run format
|
31 |
+
|
32 |
+
- name: Run i18next
|
33 |
+
run: npm run i18n:parse
|
34 |
+
|
35 |
+
- name: Check for Changes After Format
|
36 |
+
run: git diff --exit-code
|
37 |
+
|
38 |
+
- name: Build Frontend
|
39 |
+
run: npm run build
|
40 |
+
|
41 |
+
test-frontend:
|
42 |
+
name: 'Frontend Unit Tests'
|
43 |
+
runs-on: ubuntu-latest
|
44 |
+
steps:
|
45 |
+
- name: Checkout Repository
|
46 |
+
uses: actions/checkout@v4
|
47 |
+
|
48 |
+
- name: Setup Node.js
|
49 |
+
uses: actions/setup-node@v4
|
50 |
+
with:
|
51 |
+
node-version: '22'
|
52 |
+
|
53 |
+
- name: Install Dependencies
|
54 |
+
run: npm ci
|
55 |
+
|
56 |
+
- name: Run vitest
|
57 |
+
run: npm run test:frontend
|
.github/workflows/integration-test.yml
ADDED
@@ -0,0 +1,253 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
with:
|
56 |
+
browser: chrome
|
57 |
+
wait-on: 'http://localhost:3000'
|
58 |
+
config: baseUrl=http://localhost:3000
|
59 |
+
|
60 |
+
- uses: actions/upload-artifact@v4
|
61 |
+
if: always()
|
62 |
+
name: Upload Cypress videos
|
63 |
+
with:
|
64 |
+
name: cypress-videos
|
65 |
+
path: cypress/videos
|
66 |
+
if-no-files-found: ignore
|
67 |
+
|
68 |
+
- name: Extract Compose logs
|
69 |
+
if: always()
|
70 |
+
run: |
|
71 |
+
docker compose logs > compose-logs.txt
|
72 |
+
|
73 |
+
- uses: actions/upload-artifact@v4
|
74 |
+
if: always()
|
75 |
+
name: Upload Compose logs
|
76 |
+
with:
|
77 |
+
name: compose-logs
|
78 |
+
path: compose-logs.txt
|
79 |
+
if-no-files-found: ignore
|
80 |
+
|
81 |
+
# pytest:
|
82 |
+
# name: Run Backend Tests
|
83 |
+
# runs-on: ubuntu-latest
|
84 |
+
# steps:
|
85 |
+
# - uses: actions/checkout@v4
|
86 |
+
|
87 |
+
# - name: Set up Python
|
88 |
+
# uses: actions/setup-python@v5
|
89 |
+
# with:
|
90 |
+
# python-version: ${{ matrix.python-version }}
|
91 |
+
|
92 |
+
# - name: Install dependencies
|
93 |
+
# run: |
|
94 |
+
# python -m pip install --upgrade pip
|
95 |
+
# pip install -r backend/requirements.txt
|
96 |
+
|
97 |
+
# - name: pytest run
|
98 |
+
# run: |
|
99 |
+
# ls -al
|
100 |
+
# cd backend
|
101 |
+
# PYTHONPATH=. pytest . -o log_cli=true -o log_cli_level=INFO
|
102 |
+
|
103 |
+
migration_test:
|
104 |
+
name: Run Migration Tests
|
105 |
+
runs-on: ubuntu-latest
|
106 |
+
services:
|
107 |
+
postgres:
|
108 |
+
image: postgres
|
109 |
+
env:
|
110 |
+
POSTGRES_PASSWORD: postgres
|
111 |
+
options: >-
|
112 |
+
--health-cmd pg_isready
|
113 |
+
--health-interval 10s
|
114 |
+
--health-timeout 5s
|
115 |
+
--health-retries 5
|
116 |
+
ports:
|
117 |
+
- 5432:5432
|
118 |
+
# mysql:
|
119 |
+
# image: mysql
|
120 |
+
# env:
|
121 |
+
# MYSQL_ROOT_PASSWORD: mysql
|
122 |
+
# MYSQL_DATABASE: mysql
|
123 |
+
# options: >-
|
124 |
+
# --health-cmd "mysqladmin ping -h localhost"
|
125 |
+
# --health-interval 10s
|
126 |
+
# --health-timeout 5s
|
127 |
+
# --health-retries 5
|
128 |
+
# ports:
|
129 |
+
# - 3306:3306
|
130 |
+
steps:
|
131 |
+
- name: Checkout Repository
|
132 |
+
uses: actions/checkout@v4
|
133 |
+
|
134 |
+
- name: Set up Python
|
135 |
+
uses: actions/setup-python@v5
|
136 |
+
with:
|
137 |
+
python-version: ${{ matrix.python-version }}
|
138 |
+
|
139 |
+
- name: Set up uv
|
140 |
+
uses: yezz123/setup-uv@v4
|
141 |
+
with:
|
142 |
+
uv-venv: venv
|
143 |
+
|
144 |
+
- name: Activate virtualenv
|
145 |
+
run: |
|
146 |
+
. venv/bin/activate
|
147 |
+
echo PATH=$PATH >> $GITHUB_ENV
|
148 |
+
|
149 |
+
- name: Install dependencies
|
150 |
+
run: |
|
151 |
+
uv pip install -r backend/requirements.txt
|
152 |
+
|
153 |
+
- name: Test backend with SQLite
|
154 |
+
id: sqlite
|
155 |
+
env:
|
156 |
+
WEBUI_SECRET_KEY: secret-key
|
157 |
+
GLOBAL_LOG_LEVEL: debug
|
158 |
+
run: |
|
159 |
+
cd backend
|
160 |
+
uvicorn open_webui.main:app --port "8080" --forwarded-allow-ips '*' &
|
161 |
+
UVICORN_PID=$!
|
162 |
+
# Wait up to 40 seconds for the server to start
|
163 |
+
for i in {1..40}; do
|
164 |
+
curl -s http://localhost:8080/api/config > /dev/null && break
|
165 |
+
sleep 1
|
166 |
+
if [ $i -eq 40 ]; then
|
167 |
+
echo "Server failed to start"
|
168 |
+
kill -9 $UVICORN_PID
|
169 |
+
exit 1
|
170 |
+
fi
|
171 |
+
done
|
172 |
+
# Check that the server is still running after 5 seconds
|
173 |
+
sleep 5
|
174 |
+
if ! kill -0 $UVICORN_PID; then
|
175 |
+
echo "Server has stopped"
|
176 |
+
exit 1
|
177 |
+
fi
|
178 |
+
|
179 |
+
- name: Test backend with Postgres
|
180 |
+
if: success() || steps.sqlite.conclusion == 'failure'
|
181 |
+
env:
|
182 |
+
WEBUI_SECRET_KEY: secret-key
|
183 |
+
GLOBAL_LOG_LEVEL: debug
|
184 |
+
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/postgres
|
185 |
+
DATABASE_POOL_SIZE: 10
|
186 |
+
DATABASE_POOL_MAX_OVERFLOW: 10
|
187 |
+
DATABASE_POOL_TIMEOUT: 30
|
188 |
+
run: |
|
189 |
+
cd backend
|
190 |
+
uvicorn open_webui.main:app --port "8081" --forwarded-allow-ips '*' &
|
191 |
+
UVICORN_PID=$!
|
192 |
+
# Wait up to 20 seconds for the server to start
|
193 |
+
for i in {1..20}; do
|
194 |
+
curl -s http://localhost:8081/api/config > /dev/null && break
|
195 |
+
sleep 1
|
196 |
+
if [ $i -eq 20 ]; then
|
197 |
+
echo "Server failed to start"
|
198 |
+
kill -9 $UVICORN_PID
|
199 |
+
exit 1
|
200 |
+
fi
|
201 |
+
done
|
202 |
+
# Check that the server is still running after 5 seconds
|
203 |
+
sleep 5
|
204 |
+
if ! kill -0 $UVICORN_PID; then
|
205 |
+
echo "Server has stopped"
|
206 |
+
exit 1
|
207 |
+
fi
|
208 |
+
|
209 |
+
# Check that service will reconnect to postgres when connection will be closed
|
210 |
+
status_code=$(curl --write-out %{http_code} -s --output /dev/null http://localhost:8081/health/db)
|
211 |
+
if [[ "$status_code" -ne 200 ]] ; then
|
212 |
+
echo "Server has failed before postgres reconnect check"
|
213 |
+
exit 1
|
214 |
+
fi
|
215 |
+
|
216 |
+
echo "Terminating all connections to postgres..."
|
217 |
+
python -c "import os, psycopg2 as pg2; \
|
218 |
+
conn = pg2.connect(dsn=os.environ['DATABASE_URL'].replace('+pool', '')); \
|
219 |
+
cur = conn.cursor(); \
|
220 |
+
cur.execute('SELECT pg_terminate_backend(psa.pid) FROM pg_stat_activity psa WHERE datname = current_database() AND pid <> pg_backend_pid();')"
|
221 |
+
|
222 |
+
status_code=$(curl --write-out %{http_code} -s --output /dev/null http://localhost:8081/health/db)
|
223 |
+
if [[ "$status_code" -ne 200 ]] ; then
|
224 |
+
echo "Server has not reconnected to postgres after connection was closed: returned status $status_code"
|
225 |
+
exit 1
|
226 |
+
fi
|
227 |
+
|
228 |
+
# - name: Test backend with MySQL
|
229 |
+
# if: success() || steps.sqlite.conclusion == 'failure' || steps.postgres.conclusion == 'failure'
|
230 |
+
# env:
|
231 |
+
# WEBUI_SECRET_KEY: secret-key
|
232 |
+
# GLOBAL_LOG_LEVEL: debug
|
233 |
+
# DATABASE_URL: mysql://root:mysql@localhost:3306/mysql
|
234 |
+
# run: |
|
235 |
+
# cd backend
|
236 |
+
# uvicorn open_webui.main:app --port "8083" --forwarded-allow-ips '*' &
|
237 |
+
# UVICORN_PID=$!
|
238 |
+
# # Wait up to 20 seconds for the server to start
|
239 |
+
# for i in {1..20}; do
|
240 |
+
# curl -s http://localhost:8083/api/config > /dev/null && break
|
241 |
+
# sleep 1
|
242 |
+
# if [ $i -eq 20 ]; then
|
243 |
+
# echo "Server failed to start"
|
244 |
+
# kill -9 $UVICORN_PID
|
245 |
+
# exit 1
|
246 |
+
# fi
|
247 |
+
# done
|
248 |
+
# # Check that the server is still running after 5 seconds
|
249 |
+
# sleep 5
|
250 |
+
# if ! kill -0 $UVICORN_PID; then
|
251 |
+
# echo "Server has stopped"
|
252 |
+
# exit 1
|
253 |
+
# 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: 18
|
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
|
.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
@@ -0,0 +1,1226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Changelog
|
2 |
+
|
3 |
+
All notable changes to this project will be documented in this file.
|
4 |
+
|
5 |
+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
6 |
+
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
7 |
+
|
8 |
+
## [0.3.35] - 2024-10-26
|
9 |
+
|
10 |
+
### Added
|
11 |
+
|
12 |
+
- **📁 Robust File Handling**: Enhanced file input handling for chat. If the content extraction fails or is empty, users will now receive a clear warning, preventing silent failures and ensuring you always know what's happening with your uploads.
|
13 |
+
- **🌍 New Language Support**: Introduced Hungarian translations and updated French translations, expanding the platform's language accessibility for a more global user base.
|
14 |
+
|
15 |
+
### Fixed
|
16 |
+
|
17 |
+
- **📚 Knowledge Base Loading Issue**: Resolved a critical bug where the Knowledge Base was not loading, ensuring smooth access to your stored documents and improving information retrieval in RAG-enhanced workflows.
|
18 |
+
- **🛠️ Tool Parameters Issue**: Fixed an error where tools were not functioning correctly when required parameters were missing, ensuring reliable tool performance and more efficient task completions.
|
19 |
+
- **🔗 Merged Response Loss in Multi-Model Chats**: Addressed an issue where responses in multi-model chat workflows were being deleted after follow-up queries, improving consistency and ensuring smoother interactions across models.
|
20 |
+
|
21 |
+
## [0.3.34] - 2024-10-26
|
22 |
+
|
23 |
+
### Added
|
24 |
+
|
25 |
+
- **🔧 Feedback Export Enhancements**: Feedback history data can now be exported to JSON, allowing for seamless integration in RLHF processing and further analysis.
|
26 |
+
- **🗂️ Embedding Model Lazy Loading**: Search functionality for leaderboard reranking is now more efficient, as embedding models are lazy-loaded only when needed, optimizing performance.
|
27 |
+
- **🎨 Rich Text Input Toggle**: Users can now switch back to legacy textarea input for chat if they prefer simpler text input, though rich text is still the default until deprecation.
|
28 |
+
- **🛠️ Improved Tool Calling Mechanism**: Enhanced method for parsing and calling tools, improving the reliability and robustness of tool function calls.
|
29 |
+
- **🌐 Globalization Enhancements**: Updates to internationalization (i18n) support, further refining multi-language compatibility and accuracy.
|
30 |
+
|
31 |
+
### Fixed
|
32 |
+
|
33 |
+
- **🖥️ Folder Rename Fix for Firefox**: Addressed a persistent issue where users could not rename folders by pressing enter in Firefox, now ensuring seamless folder management across browsers.
|
34 |
+
- **🔠 Tiktoken Model Text Splitter Issue**: Resolved an issue where the tiktoken text splitter wasn’t working in Docker installations, restoring full functionality for tokenized text editing.
|
35 |
+
- **💼 S3 File Upload Issue**: Fixed a problem affecting S3 file uploads, ensuring smooth operations for those who store files on cloud storage.
|
36 |
+
- **🔒 Strict-Transport-Security Crash**: Resolved a crash when setting the Strict-Transport-Security (HSTS) header, improving stability and security enhancements.
|
37 |
+
- **🚫 OIDC Boolean Access Fix**: Addressed an issue with boolean values not being accessed correctly during OIDC logins, ensuring login reliability.
|
38 |
+
- **⚙️ Rich Text Paste Behavior**: Refined paste behavior in rich text input to make it smoother and more intuitive when pasting various content types.
|
39 |
+
- **🔨 Model Exclusion for Arena Fix**: Corrected the filter function that was not properly excluding models from the arena, improving model management.
|
40 |
+
- **🏷️ "Tags Generation Prompt" Fix**: Addressed an issue preventing custom "tags generation prompts" from registering properly, ensuring custom prompt work seamlessly.
|
41 |
+
|
42 |
+
## [0.3.33] - 2024-10-24
|
43 |
+
|
44 |
+
### Added
|
45 |
+
|
46 |
+
- **🏆 Evaluation Leaderboard**: Easily track your performance through a new leaderboard system where your ratings contribute to a real-time ranking based on the Elo system. Sibling responses (regenerations, many model chats) are required for your ratings to count in the leaderboard. Additionally, you can opt-in to share your feedback history and be part of the community-wide leaderboard. Expect further improvements as we refine the algorithm—help us build the best community leaderboard!
|
47 |
+
- **⚔️ Arena Model Evaluation**: Enable blind A/B testing of models directly from Admin Settings > Evaluation for a true side-by-side comparison. Ideal for pinpointing the best model for your needs.
|
48 |
+
- **🎯 Topic-Based Leaderboard**: Discover more accurate rankings with experimental topic-based reranking, which adjusts leaderboard standings based on tag similarity in feedback. Get more relevant insights based on specific topics!
|
49 |
+
- **📁 Folders Support for Chats**: Organize your chats better by grouping them into folders. Drag and drop chats between folders and export them seamlessly for easy sharing or analysis.
|
50 |
+
- **📤 Easy Chat Import via Drag & Drop**: Save time by simply dragging and dropping chat exports (JSON) directly onto the sidebar to import them into your workspace—streamlined, efficient, and intuitive!
|
51 |
+
- **📚 Enhanced Knowledge Collection**: Now, you can reference individual files from a knowledge collection—ideal for more precise Retrieval-Augmented Generations (RAG) queries and document analysis.
|
52 |
+
- **🏷️ Enhanced Tagging System**: Tags now take up less space! Utilize the new 'tag:' query system to manage, search, and organize your conversations more effectively without cluttering the interface.
|
53 |
+
- **🧠 Auto-Tagging for Chats**: Your conversations are now automatically tagged for improved organization, mirroring the efficiency of auto-generated titles.
|
54 |
+
- **🔍 Backend Chat Query System**: Chat filtering has become more efficient, now handled through the backend\*\* instead of your browser, improving search performance and accuracy.
|
55 |
+
- **🎮 Revamped Playground**: Experience a refreshed and optimized Playground for smoother testing, tweaks, and experimentation of your models and tools.
|
56 |
+
- **🧩 Token-Based Text Splitter**: Introducing token-based text splitting (tiktoken), giving you more precise control over how text is processed. Previously, only character-based splitting was available.
|
57 |
+
- **🔢 Ollama Batch Embeddings**: Leverage new batch embedding support for improved efficiency and performance with Ollama embedding models.
|
58 |
+
- **🔍 Enhanced Add Text Content Modal**: Enjoy a cleaner, more intuitive workflow for adding and curating knowledge content with an upgraded input modal from our Knowledge workspace.
|
59 |
+
- **🖋️ Rich Text Input for Chats**: Make your chat inputs more dynamic with support for rich text formatting. Your conversations just got a lot more polished and professional.
|
60 |
+
- **⚡ Faster Whisper Model Configurability**: Customize your local faster whisper model directly from the WebUI.
|
61 |
+
- **☁️ Experimental S3 Support**: Enable stateless WebUI instances with S3 support, greatly enhancing scalability and balancing heavy workloads.
|
62 |
+
- **🔕 Disable Update Toast**: Now you can streamline your workspace even further—choose to disable update notifications for a more focused experience.
|
63 |
+
- **🌟 RAG Citation Relevance Percentage**: Easily assess citation accuracy with the addition of relevance percentages in RAG results.
|
64 |
+
- **⚙️ Mermaid Copy Button**: Mermaid diagrams now come with a handy copy button, simplifying the extraction and use of diagram contents directly in your workflow.
|
65 |
+
- **🎨 UI Redesign**: Major interface redesign that will make navigation smoother, keep your focus where it matters, and ensure a modern look.
|
66 |
+
|
67 |
+
### Fixed
|
68 |
+
|
69 |
+
- **🎙️ Voice Note Mic Stopping Issue**: Fixed the issue where the microphone stayed active after ending a voice note recording, ensuring your audio workflow runs smoothly.
|
70 |
+
|
71 |
+
### Removed
|
72 |
+
|
73 |
+
- **👋 Goodbye Sidebar Tags**: Sidebar tag clutter is gone. We’ve shifted tag buttons to more effective query-based tag filtering for a sleeker, more agile interface.
|
74 |
+
|
75 |
+
## [0.3.32] - 2024-10-06
|
76 |
+
|
77 |
+
### Added
|
78 |
+
|
79 |
+
- **🔢 Workspace Enhancements**: Added a display count for models, prompts, tools, and functions in the workspace, providing a clear overview and easier management.
|
80 |
+
|
81 |
+
### Fixed
|
82 |
+
|
83 |
+
- **🖥️ Web and YouTube Attachment Fix**: Resolved an issue where attaching web links and YouTube videos was malfunctioning, ensuring seamless integration and display within chats.
|
84 |
+
- **📞 Call Mode Activation on Landing Page**: Fixed a bug where call mode was not operational from the landing page.
|
85 |
+
|
86 |
+
### Changed
|
87 |
+
|
88 |
+
- **🔄 URL Parameter Refinement**: Updated the 'tool_ids' URL parameter to 'tools' or 'tool-ids' for more intuitive and consistent user experience.
|
89 |
+
- **🎨 Floating Buttons Styling Update**: Refactored the styling of floating buttons to intelligently adjust to the left side when there isn't enough room on the right, improving interface usability and aesthetic.
|
90 |
+
- **🔧 Enhanced Accessibility for Floating Buttons**: Implemented the ability to close floating buttons with the 'Esc' key, making workflow smoother and more efficient for users navigating via keyboard.
|
91 |
+
- **🖇️ Updated Information URL**: Information URLs now direct users to a general release page rather than a version-specific URL, ensuring access to the latest and relevant details all in one place.
|
92 |
+
- **📦 Library Dependencies Update**: Upgraded dependencies to ensure compatibility and performance optimization for pip installs.
|
93 |
+
|
94 |
+
## [0.3.31] - 2024-10-06
|
95 |
+
|
96 |
+
### Added
|
97 |
+
|
98 |
+
- **📚 Knowledge Feature**: Reimagined documents feature, now more performant with a better UI for enhanced organization; includes streamlined API integration for Retrieval-Augmented Generation (RAG). Detailed documentation forthcoming: https://docs.openwebui.com/
|
99 |
+
- **🌐 New Landing Page**: Freshly designed landing page; toggle between the new UI and the classic chat UI from Settings > Interface for a personalized experience.
|
100 |
+
- **📁 Full Document Retrieval Mode**: Toggle between full document retrieval or traditional snippets by clicking on the file item. This mode enhances document capabilities and supports comprehensive tasks like summarization by utilizing the entire content instead of RAG.
|
101 |
+
- **📄 Extracted File Content Display**: View extracted content directly by clicking on the file item, simplifying file analysis.
|
102 |
+
- **🎨 Artifacts Feature**: Render web content and SVGs directly in the interface, supporting quick iterations and live changes.
|
103 |
+
- **🖊️ Editable Code Blocks**: Supercharged code blocks now allow live editing directly in the LLM response, with live reloads supported by artifacts.
|
104 |
+
- **🔧 Code Block Enhancements**: Introduced a floating copy button in code blocks to facilitate easier code copying without scrolling.
|
105 |
+
- **🔍 SVG Pan/Zoom**: Enhanced interaction with SVG images, including Mermaid diagrams, via new pan and zoom capabilities.
|
106 |
+
- **🔍 Text Select Quick Actions**: New floating buttons appear when text is highlighted in LLM responses, offering deeper interactions like "Ask a Question" or "Explain".
|
107 |
+
- **🗃️ Database Pool Configuration**: Enhanced database handling to support scalable user growth.
|
108 |
+
- **🔊 Experimental Audio Compression**: Compress audio files to navigate around the 25MB limit for OpenAI's speech-to-text processing.
|
109 |
+
- **🔍 Query Embedding**: Adjusted embedding behavior to enhance system performance by not repeating query embedding.
|
110 |
+
- **💾 Lazy Load Optimizations**: Implemented lazy loading of large dependencies to minimize initial memory usage, boosting performance.
|
111 |
+
- **🍏 Apple Touch Icon Support**: Optimizes the display of icons for web bookmarks on Apple mobile devices.
|
112 |
+
- **🔽 Expandable Content Markdown Support**: Introducing 'details', 'summary' tag support for creating expandable content sections in markdown, facilitating cleaner, organized documentation and interactive content display.
|
113 |
+
|
114 |
+
### Fixed
|
115 |
+
|
116 |
+
- **🔘 Action Button Issue**: Resolved a bug where action buttons were not functioning, enhancing UI reliability.
|
117 |
+
- **🔄 Multi-Model Chat Loop**: Fixed an infinite loop issue in multi-model chat environments, ensuring smoother chat operations.
|
118 |
+
- **📄 Chat PDF/TXT Export Issue**: Resolved problems with exporting chat logs to PDF and TXT formats.
|
119 |
+
- **🔊 Call to Text-to-Speech Issues**: Rectified problems with text-to-speech functions to improve audio interactions.
|
120 |
+
|
121 |
+
### Changed
|
122 |
+
|
123 |
+
- **⚙️ Endpoint Renaming**: Renamed 'rag' endpoints to 'retrieval' for clearer function description.
|
124 |
+
- **🎨 Styling and Interface Updates**: Multiple refinements across the platform to enhance visual appeal and user interaction.
|
125 |
+
|
126 |
+
### Removed
|
127 |
+
|
128 |
+
- **🗑️ Deprecated 'DOCS_DIR'**: Removed the outdated 'docs_dir' variable in favor of more direct file management solutions, with direct file directory syncing and API uploads for a more integrated experience.
|
129 |
+
|
130 |
+
## [0.3.30] - 2024-09-26
|
131 |
+
|
132 |
+
### Fixed
|
133 |
+
|
134 |
+
- **🍞 Update Available Toast Dismissal**: Enhanced user experience by ensuring that once the update available notification is dismissed, it won't reappear for 24 hours.
|
135 |
+
- **📋 Ollama /embed Form Data**: Adjusted the integration inaccuracies in the /embed form data to ensure it perfectly matches with Ollama's specifications.
|
136 |
+
- **🔧 O1 Max Completion Tokens Issue**: Resolved compatibility issues with OpenAI's o1 models max_completion_tokens param to ensure smooth operation.
|
137 |
+
- **🔄 Pip Install Database Issue**: Fixed a critical issue where database changes during pip installations were reverting and not saving chat logs, now ensuring data persistence and reliability in chat operations.
|
138 |
+
- **🏷️ Chat Rename Tab Update**: Fixed the functionality to change the web browser's tab title simultaneously when a chat is renamed, keeping tab titles consistent.
|
139 |
+
|
140 |
+
## [0.3.29] - 2023-09-25
|
141 |
+
|
142 |
+
### Fixed
|
143 |
+
|
144 |
+
- **🔧 KaTeX Rendering Improvement**: Resolved specific corner cases in KaTeX rendering to enhance the display of complex mathematical notation.
|
145 |
+
- **📞 'Call' URL Parameter Fix**: Corrected functionality for 'call' URL search parameter ensuring reliable activation of voice calls through URL triggers.
|
146 |
+
- **🔄 Configuration Reset Fix**: Fixed the RESET_CONFIG_ON_START to ensure settings revert to default correctly upon each startup, improving reliability in configuration management.
|
147 |
+
- **🌍 Filter Outlet Hook Fix**: Addressed issues in the filter outlet hook, ensuring all filter functions operate as intended.
|
148 |
+
|
149 |
+
## [0.3.28] - 2024-09-24
|
150 |
+
|
151 |
+
### Fixed
|
152 |
+
|
153 |
+
- **🔍 Web Search Functionality**: Corrected an issue where the web search option was not functioning properly.
|
154 |
+
|
155 |
+
## [0.3.27] - 2024-09-24
|
156 |
+
|
157 |
+
### Fixed
|
158 |
+
|
159 |
+
- **🔄 Periodic Cleanup Error Resolved**: Fixed a critical RuntimeError related to the 'periodic_usage_pool_cleanup' coroutine, ensuring smooth and efficient performance post-pip install, correcting a persisting issue from version 0.3.26.
|
160 |
+
- **📊 Enhanced LaTeX Rendering**: Improved rendering for LaTeX content, enhancing clarity and visual presentation in documents and mathematical models.
|
161 |
+
|
162 |
+
## [0.3.26] - 2024-09-24
|
163 |
+
|
164 |
+
### Fixed
|
165 |
+
|
166 |
+
- **🔄 Event Loop Error Resolution**: Addressed a critical error where a missing running event loop caused 'periodic_usage_pool_cleanup' to fail with pip installs. This fix ensures smoother and more reliable updates and installations, enhancing overall system stability.
|
167 |
+
|
168 |
+
## [0.3.25] - 2024-09-24
|
169 |
+
|
170 |
+
### Fixed
|
171 |
+
|
172 |
+
- **🖼️ Image Generation Functionality**: Resolved an issue where image generation was not functioning, restoring full capability for visual content creation.
|
173 |
+
- **⚖️ Rate Response Corrections**: Addressed a problem where rate responses were not working, ensuring reliable feedback mechanisms are operational.
|
174 |
+
|
175 |
+
## [0.3.24] - 2024-09-24
|
176 |
+
|
177 |
+
### Added
|
178 |
+
|
179 |
+
- **🚀 Rendering Optimization**: Significantly improved message rendering performance, enhancing user experience and webui responsiveness.
|
180 |
+
- **💖 Favorite Response Feature in Chat Overview**: Users can now mark responses as favorite directly from the chat overview, enhancing ease of retrieval and organization of preferred responses.
|
181 |
+
- **💬 Create Message Pairs with Shortcut**: Implemented creation of new message pairs using Cmd/Ctrl+Shift+Enter, making conversation editing faster and more intuitive.
|
182 |
+
- **🌍 Expanded User Prompt Variables**: Added weekday, timezone, and language information variables to user prompts to match system prompt variables.
|
183 |
+
- **🎵 Enhanced Audio Support**: Now includes support for 'audio/x-m4a' files, broadening compatibility with audio content within the platform.
|
184 |
+
- **🔏 Model URL Search Parameter**: Added an ability to select a model directly via URL parameters, streamlining navigation and model access.
|
185 |
+
- **📄 Enhanced PDF Citations**: PDF citations now open at the associated page, streamlining reference checks and document handling.
|
186 |
+
- **🔧Use of Redis in Sockets**: Enhanced socket implementation to fully support Redis, enabling effective stateless instances suitable for scalable load balancing.
|
187 |
+
- **🌍 Stream Individual Model Responses**: Allows specific models to have individualized streaming settings, enhancing performance and customization.
|
188 |
+
- **🕒 Display Model Hash and Last Modified Timestamp for Ollama Models**: Provides critical model details directly in the Models workspace for enhanced tracking.
|
189 |
+
- **❗ Update Info Notification for Admins**: Ensures administrators receive immediate updates upon login, keeping them informed of the latest changes and system statuses.
|
190 |
+
|
191 |
+
### Fixed
|
192 |
+
|
193 |
+
- **🗑️ Temporary File Handling On Windows**: Fixed an issue causing errors when accessing a temporary file being used by another process, Tools & Functions should now work as intended.
|
194 |
+
- **🔓 Authentication Toggle Issue**: Resolved the malfunction where setting 'WEBUI_AUTH=False' did not appropriately disable authentication, ensuring that user experience and system security settings function as configured.
|
195 |
+
- **🔧 Save As Copy Issue for Many Model Chats**: Resolved an error preventing users from save messages as copies in many model chats.
|
196 |
+
- **🔒 Sidebar Closure on Mobile**: Resolved an issue where the mobile sidebar remained open after menu engagement, improving user interface responsivity and comfort.
|
197 |
+
- **🛡️ Tooltip XSS Vulnerability**: Resolved a cross-site scripting (XSS) issue within tooltips, ensuring enhanced security and data integrity during user interactions.
|
198 |
+
|
199 |
+
### Changed
|
200 |
+
|
201 |
+
- **↩️ Deprecated Interface Stream Response Settings**: Moved to advanced parameters to streamline interface settings and enhance user clarity.
|
202 |
+
- **⚙️ Renamed 'speedRate' to 'playbackRate'**: Standardizes terminology, improving usability and understanding in media settings.
|
203 |
+
|
204 |
+
## [0.3.23] - 2024-09-21
|
205 |
+
|
206 |
+
### Added
|
207 |
+
|
208 |
+
- **🚀 WebSocket Redis Support**: Enhanced load balancing capabilities for multiple instance setups, promoting better performance and reliability in WebUI.
|
209 |
+
- **🔧 Adjustable Chat Controls**: Introduced width-adjustable chat controls, enabling a personalized and more comfortable user interface.
|
210 |
+
- **🌎 i18n Updates**: Improved and updated the Chinese translations.
|
211 |
+
|
212 |
+
### Fixed
|
213 |
+
|
214 |
+
- **🌐 Task Model Unloading Issue**: Modified task handling to use the Ollama /api/chat endpoint instead of OpenAI compatible endpoint, ensuring models stay loaded and ready with custom parameters, thus minimizing delays in task execution.
|
215 |
+
- **📝 Title Generation Fix for OpenAI Compatible APIs**: Resolved an issue preventing the generation of titles, enhancing consistency and reliability when using multiple API providers.
|
216 |
+
- **🗃️ RAG Duplicate Collection Issue**: Fixed a bug causing repeated processing of the same uploaded file. Now utilizes indexed files to prevent unnecessary duplications, optimizing resource usage.
|
217 |
+
- **🖼️ Image Generation Enhancement**: Refactored OpenAI image generation endpoint to be asynchronous, preventing the WebUI from becoming unresponsive during processing, thus enhancing user experience.
|
218 |
+
- **🔓 Downgrade Authlib**: Reverted Authlib to version 1.3.1 to address and resolve issues concerning OAuth functionality.
|
219 |
+
|
220 |
+
### Changed
|
221 |
+
|
222 |
+
- **🔍 Improved Message Interaction**: Enhanced the message node interface to allow for easier focus redirection with a simple click, streamlining user interaction.
|
223 |
+
- **✨ Styling Refactor**: Updated WebUI styling for a cleaner, more modern look, enhancing user experience across the platform.
|
224 |
+
|
225 |
+
## [0.3.22] - 2024-09-19
|
226 |
+
|
227 |
+
### Added
|
228 |
+
|
229 |
+
- **⭐ Chat Overview**: Introducing a node-based interactive messages diagram for improved visualization of conversation flows.
|
230 |
+
- **🔗 Multiple Vector DB Support**: Now supports multiple vector databases, including the newly added Milvus support. Community contributions for additional database support are highly encouraged!
|
231 |
+
- **📡 Experimental Non-Stream Chat Completion**: Experimental feature allowing the use of OpenAI o1 models, which do not support streaming, ensuring more versatile model deployment.
|
232 |
+
- **🔍 Experimental Colbert-AI Reranker Integration**: Added support for "jinaai/jina-colbert-v2" as a reranker, enhancing search relevance and accuracy. Note: it may not function at all on low-spec computers.
|
233 |
+
- **🕸️ ENABLE_WEBSOCKET_SUPPORT**: Added environment variable for instances to ignore websocket upgrades, stabilizing connections on platforms with websocket issues.
|
234 |
+
- **🔊 Azure Speech Service Integration**: Added support for Azure Speech services for Text-to-Speech (TTS).
|
235 |
+
- **🎚️ Customizable Playback Speed**: Playback speed control is now available in Call mode settings, allowing users to adjust audio playback speed to their preferences.
|
236 |
+
- **🧠 Enhanced Error Messaging**: System now displays helpful error messages directly to users during chat completion issues.
|
237 |
+
- **📂 Save Model as Transparent PNG**: Model profile images are now saved as PNGs, supporting transparency and improving visual integration.
|
238 |
+
- **📱 iPhone Compatibility Adjustments**: Added padding to accommodate the iPhone navigation bar, improving UI display on these devices.
|
239 |
+
- **🔗 Secure Response Headers**: Implemented security response headers, bolstering web application security.
|
240 |
+
- **🔧 Enhanced AUTOMATIC1111 Settings**: Users can now configure 'CFG Scale', 'Sampler', and 'Scheduler' parameters directly in the admin settings, enhancing workflow flexibility without source code modifications.
|
241 |
+
- **🌍 i18n Updates**: Enhanced translations for Chinese, Ukrainian, Russian, and French, fostering a better localized experience.
|
242 |
+
|
243 |
+
### Fixed
|
244 |
+
|
245 |
+
- **🛠️ Chat Message Deletion**: Resolved issues with chat message deletion, ensuring a smoother user interaction and system stability.
|
246 |
+
- **🔢 Ordered List Numbering**: Fixed the incorrect ordering in lists.
|
247 |
+
|
248 |
+
### Changed
|
249 |
+
|
250 |
+
- **🎨 Transparent Icon Handling**: Allowed model icons to be displayed on transparent backgrounds, improving UI aesthetics.
|
251 |
+
- **📝 Improved RAG Template**: Enhanced Retrieval-Augmented Generation template, optimizing context handling and error checking for more precise operation.
|
252 |
+
|
253 |
+
## [0.3.21] - 2024-09-08
|
254 |
+
|
255 |
+
### Added
|
256 |
+
|
257 |
+
- **📊 Document Count Display**: Now displays the total number of documents directly within the dashboard.
|
258 |
+
- **🚀 Ollama Embed API Endpoint**: Enabled /api/embed endpoint proxy support.
|
259 |
+
|
260 |
+
### Fixed
|
261 |
+
|
262 |
+
- **🐳 Docker Launch Issue**: Resolved the problem preventing Open-WebUI from launching correctly when using Docker.
|
263 |
+
|
264 |
+
### Changed
|
265 |
+
|
266 |
+
- **🔍 Enhanced Search Prompts**: Improved the search query generation prompts for better accuracy and user interaction, enhancing the overall search experience.
|
267 |
+
|
268 |
+
## [0.3.20] - 2024-09-07
|
269 |
+
|
270 |
+
### Added
|
271 |
+
|
272 |
+
- **🌐 Translation Update**: Updated Catalan translations to improve user experience for Catalan speakers.
|
273 |
+
|
274 |
+
### Fixed
|
275 |
+
|
276 |
+
- **📄 PDF Download**: Resolved a configuration issue with fonts directory, ensuring PDFs are now downloaded with the correct formatting.
|
277 |
+
- **🛠️ Installation of Tools & Functions Requirements**: Fixed a bug where necessary requirements for tools and functions were not properly installing.
|
278 |
+
- **🔗 Inline Image Link Rendering**: Enabled rendering of images directly from links in chat.
|
279 |
+
- **📞 Post-Call User Interface Cleanup**: Adjusted UI behavior to automatically close chat controls after a voice call ends, reducing screen clutter.
|
280 |
+
- **🎙️ Microphone Deactivation Post-Call**: Addressed an issue where the microphone remained active after calls.
|
281 |
+
- **✍️ Markdown Spacing Correction**: Corrected spacing in Markdown rendering, ensuring text appears neatly and as expected.
|
282 |
+
- **🔄 Message Re-rendering**: Fixed an issue causing all response messages to re-render with each new message, now improving chat performance.
|
283 |
+
|
284 |
+
### Changed
|
285 |
+
|
286 |
+
- **🌐 Refined Web Search Integration**: Deprecated the Search Query Generation Prompt threshold; introduced a toggle button for "Enable Web Search Query Generation" allowing users to opt-in to using web search more judiciously.
|
287 |
+
- **📝 Default Prompt Templates Update**: Emptied environment variable templates for search and title generation now default to the Open WebUI default prompt templates, simplifying configuration efforts.
|
288 |
+
|
289 |
+
## [0.3.19] - 2024-09-05
|
290 |
+
|
291 |
+
### Added
|
292 |
+
|
293 |
+
- **🌐 Translation Update**: Improved Chinese translations.
|
294 |
+
|
295 |
+
### Fixed
|
296 |
+
|
297 |
+
- **📂 DATA_DIR Overriding**: Fixed an issue to avoid overriding DATA_DIR, preventing errors when directories are set identically, ensuring smoother operation and data management.
|
298 |
+
- **🛠️ Frontmatter Extraction**: Fixed the extraction process for frontmatter in tools and functions.
|
299 |
+
|
300 |
+
### Changed
|
301 |
+
|
302 |
+
- **🎨 UI Styling**: Refined the user interface styling for enhanced visual coherence and user experience.
|
303 |
+
|
304 |
+
## [0.3.18] - 2024-09-04
|
305 |
+
|
306 |
+
### Added
|
307 |
+
|
308 |
+
- **🛠️ Direct Database Execution for Tools & Functions**: Enhanced the execution of Python files for tools and functions, now directly loading from the database for a more streamlined backend process.
|
309 |
+
|
310 |
+
### Fixed
|
311 |
+
|
312 |
+
- **🔄 Automatic Rewrite of Import Statements in Tools & Functions**: Tool and function scripts that import 'utils', 'apps', 'main', 'config' will now automatically rename these with 'open_webui.', ensuring compatibility and consistency across different modules.
|
313 |
+
- **🎨 Styling Adjustments**: Minor fixes in the visual styling to improve user experience and interface consistency.
|
314 |
+
|
315 |
+
## [0.3.17] - 2024-09-04
|
316 |
+
|
317 |
+
### Added
|
318 |
+
|
319 |
+
- **🔄 Import/Export Configuration**: Users can now import and export webui configurations from admin settings > Database, simplifying setup replication across systems.
|
320 |
+
- **🌍 Web Search via URL Parameter**: Added support for activating web search directly through URL by setting 'web-search=true'.
|
321 |
+
- **🌐 SearchApi Integration**: Added support for SearchApi as an alternative web search provider, enhancing search capabilities within the platform.
|
322 |
+
- **🔍 Literal Type Support in Tools**: Tools now support the Literal type.
|
323 |
+
- **🌍 Updated Translations**: Improved translations for Chinese, Ukrainian, and Catalan.
|
324 |
+
|
325 |
+
### Fixed
|
326 |
+
|
327 |
+
- **🔧 Pip Install Issue**: Resolved the issue where pip install failed due to missing 'alembic.ini', ensuring smoother installation processes.
|
328 |
+
- **🌃 Automatic Theme Update**: Fixed an issue where the color theme did not update dynamically with system changes.
|
329 |
+
- **🛠️ User Agent in ComfyUI**: Added default headers in ComfyUI to fix access issues, improving reliability in network communications.
|
330 |
+
- **🔄 Missing Chat Completion Response Headers**: Ensured proper return of proxied response headers during chat completion, improving API reliability.
|
331 |
+
- **🔗 Websocket Connection Prioritization**: Modified socket.io configuration to prefer websockets and more reliably fallback to polling, enhancing connection stability.
|
332 |
+
- **🎭 Accessibility Enhancements**: Added missing ARIA labels for buttons, improving accessibility for visually impaired users.
|
333 |
+
- **⚖️ Advanced Parameter**: Fixed an issue ensuring that advanced parameters are correctly applied in all scenarios, ensuring consistent behavior of user-defined settings.
|
334 |
+
|
335 |
+
### Changed
|
336 |
+
|
337 |
+
- **🔁 Namespace Reorganization**: Reorganized all Python files under the 'open_webui' namespace to streamline the project structure and improve maintainability. Tools and functions importing from 'utils' should now use 'open_webui.utils'.
|
338 |
+
- **🚧 Dependency Updates**: Updated several backend dependencies like 'aiohttp', 'authlib', 'duckduckgo-search', 'flask-cors', and 'langchain' to their latest versions, enhancing performance and security.
|
339 |
+
|
340 |
+
## [0.3.16] - 2024-08-27
|
341 |
+
|
342 |
+
### Added
|
343 |
+
|
344 |
+
- **🚀 Config DB Migration**: Migrated configuration handling from config.json to the database, enabling high-availability setups and load balancing across multiple Open WebUI instances.
|
345 |
+
- **🔗 Call Mode Activation via URL**: Added a 'call=true' URL search parameter enabling direct shortcuts to activate call mode, enhancing user interaction on mobile devices.
|
346 |
+
- **✨ TTS Content Control**: Added functionality to control how message content is segmented for Text-to-Speech (TTS) generation requests, allowing for more flexible speech output options.
|
347 |
+
- **😄 Show Knowledge Search Status**: Enhanced model usage transparency by displaying status when working with knowledge-augmented models, helping users understand the system's state during queries.
|
348 |
+
- **👆 Click-to-Copy for Codespan**: Enhanced interactive experience in the WebUI by allowing users to click to copy content from code spans directly.
|
349 |
+
- **🚫 API User Blocking via Model Filter**: Introduced the ability to block API users based on customized model filters, enhancing security and control over API access.
|
350 |
+
- **🎬 Call Overlay Styling**: Adjusted call overlay styling on large screens to not cover the entire interface, but only the chat control area, for a more unobtrusive interaction experience.
|
351 |
+
|
352 |
+
### Fixed
|
353 |
+
|
354 |
+
- **🔧 LaTeX Rendering Issue**: Addressed an issue that affected the correct rendering of LaTeX.
|
355 |
+
- **📁 File Leak Prevention**: Resolved the issue of uploaded files mistakenly being accessible across user chats.
|
356 |
+
- **🔧 Pipe Functions with '**files**' Param**: Fixed issues with '**files**' parameter not functioning correctly in pipe functions.
|
357 |
+
- **📝 Markdown Processing for RAG**: Fixed issues with processing Markdown in files.
|
358 |
+
- **🚫 Duplicate System Prompts**: Fixed bugs causing system prompts to duplicate.
|
359 |
+
|
360 |
+
### Changed
|
361 |
+
|
362 |
+
- **🔋 Wakelock Permission**: Optimized the activation of wakelock to only engage during call mode, conserving device resources and improving battery performance during idle periods.
|
363 |
+
- **🔍 Content-Type for Ollama Chats**: Added 'application/x-ndjson' content-type to '/api/chat' endpoint responses to match raw Ollama responses.
|
364 |
+
- **✋ Disable Signups Conditionally**: Implemented conditional logic to disable sign-ups when 'ENABLE_LOGIN_FORM' is set to false.
|
365 |
+
|
366 |
+
## [0.3.15] - 2024-08-21
|
367 |
+
|
368 |
+
### Added
|
369 |
+
|
370 |
+
- **🔗 Temporary Chat Activation**: Integrated a new URL parameter 'temporary-chat=true' to enable temporary chat sessions directly through the URL.
|
371 |
+
- **🌄 ComfyUI Seed Node Support**: Introduced seed node support in ComfyUI for image generation, allowing users to specify node IDs for randomized seed assignment.
|
372 |
+
|
373 |
+
### Fixed
|
374 |
+
|
375 |
+
- **🛠️ Tools and Functions**: Resolved a critical issue where Tools and Functions were not properly functioning, restoring full capability and reliability to these essential features.
|
376 |
+
- **🔘 Chat Action Button in Many Model Chat**: Fixed the malfunctioning of chat action buttons in many model chat environments, ensuring a smoother and more responsive user interaction.
|
377 |
+
- **⏪ Many Model Chat Compatibility**: Restored backward compatibility for many model chats.
|
378 |
+
|
379 |
+
## [0.3.14] - 2024-08-21
|
380 |
+
|
381 |
+
### Added
|
382 |
+
|
383 |
+
- **🛠️ Custom ComfyUI Workflow**: Deprecating several older environment variables, this enhancement introduces a new, customizable workflow for a more tailored user experience.
|
384 |
+
- **🔀 Merge Responses in Many Model Chat**: Enhances the dialogue by merging responses from multiple models into a single, coherent reply, improving the interaction quality in many model chats.
|
385 |
+
- **✅ Multiple Instances of Same Model in Chats**: Enhanced many model chat to support adding multiple instances of the same model.
|
386 |
+
- **🔧 Quick Actions in Model Workspace**: Enhanced Shift key quick actions for hiding/unhiding and deleting models, facilitating a smoother workflow.
|
387 |
+
- **🗨️ Markdown Rendering in User Messages**: User messages are now rendered in Markdown, enhancing readability and interaction.
|
388 |
+
- **💬 Temporary Chat Feature**: Introduced a temporary chat feature, deprecating the old chat history setting to enhance user interaction flexibility.
|
389 |
+
- **🖋️ User Message Editing**: Enhanced the user chat editing feature to allow saving changes without sending, providing more flexibility in message management.
|
390 |
+
- **🛡️ Security Enhancements**: Various security improvements implemented across the platform to ensure safer user experiences.
|
391 |
+
- **🌍 Updated Translations**: Enhanced translations for Chinese, Ukrainian, and Bahasa Malaysia, improving localization and user comprehension.
|
392 |
+
|
393 |
+
### Fixed
|
394 |
+
|
395 |
+
- **📑 Mermaid Rendering Issue**: Addressed issues with Mermaid chart rendering to ensure clean and clear visual data representation.
|
396 |
+
- **🎭 PWA Icon Maskability**: Fixed the Progressive Web App icon to be maskable, ensuring proper display on various device home screens.
|
397 |
+
- **🔀 Cloned Model Chat Freezing Issue**: Fixed a bug where cloning many model chats would cause freezing, enhancing stability and responsiveness.
|
398 |
+
- **🔍 Generic Error Handling and Refinements**: Various minor fixes and refinements to address previously untracked issues, ensuring smoother operations.
|
399 |
+
|
400 |
+
### Changed
|
401 |
+
|
402 |
+
- **🖼️ Image Generation Refactor**: Overhauled image generation processes for improved efficiency and quality.
|
403 |
+
- **🔨 Refactor Tool and Function Calling**: Refactored tool and function calling mechanisms for improved clarity and maintainability.
|
404 |
+
- **🌐 Backend Library Updates**: Updated critical backend libraries including SQLAlchemy, uvicorn[standard], faster-whisper, bcrypt, and boto3 for enhanced performance and security.
|
405 |
+
|
406 |
+
### Removed
|
407 |
+
|
408 |
+
- **🚫 Deprecated ComfyUI Environment Variables**: Removed several outdated environment variables related to ComfyUI settings, simplifying configuration management.
|
409 |
+
|
410 |
+
## [0.3.13] - 2024-08-14
|
411 |
+
|
412 |
+
### Added
|
413 |
+
|
414 |
+
- **🎨 Enhanced Markdown Rendering**: Significant improvements in rendering markdown, ensuring smooth and reliable display of LaTeX and Mermaid charts, enhancing user experience with more robust visual content.
|
415 |
+
- **🔄 Auto-Install Tools & Functions Python Dependencies**: For 'Tools' and 'Functions', Open WebUI now automatically install extra python requirements specified in the frontmatter, streamlining setup processes and customization.
|
416 |
+
- **🌀 OAuth Email Claim Customization**: Introduced an 'OAUTH_EMAIL_CLAIM' variable to allow customization of the default "email" claim within OAuth configurations, providing greater flexibility in authentication processes.
|
417 |
+
- **📶 Websocket Reconnection**: Enhanced reliability with the capability to automatically reconnect when a websocket is closed, ensuring consistent and stable communication.
|
418 |
+
- **🤳 Haptic Feedback on Support Devices**: Android devices now support haptic feedback for an immersive tactile experience during certain interactions.
|
419 |
+
|
420 |
+
### Fixed
|
421 |
+
|
422 |
+
- **🛠️ ComfyUI Performance Improvement**: Addressed an issue causing FastAPI to stall when ComfyUI image generation was active; now runs in a separate thread to prevent UI unresponsiveness.
|
423 |
+
- **🔀 Session Handling**: Fixed an issue mandating session_id on client-side to ensure smoother session management and transitions.
|
424 |
+
- **🖋️ Minor Bug Fixes and Format Corrections**: Various minor fixes including typo corrections, backend formatting improvements, and test amendments enhancing overall system stability and performance.
|
425 |
+
|
426 |
+
### Changed
|
427 |
+
|
428 |
+
- **🚀 Migration to SvelteKit 2**: Upgraded the underlying framework to SvelteKit version 2, offering enhanced speed, better code structure, and improved deployment capabilities.
|
429 |
+
- **🧹 General Cleanup and Refactoring**: Performed broad cleanup and refactoring across the platform, improving code efficiency and maintaining high standards of code health.
|
430 |
+
- **🚧 Integration Testing Improvements**: Modified how Cypress integration tests detect chat messages and updated sharing tests for better reliability and accuracy.
|
431 |
+
- **📁 Standardized '.safetensors' File Extension**: Renamed the '.sft' file extension to '.safetensors' for ComfyUI workflows, standardizing file formats across the platform.
|
432 |
+
|
433 |
+
### Removed
|
434 |
+
|
435 |
+
- **🗑️ Deprecated Frontend Functions**: Removed frontend functions that were migrated to backend to declutter the codebase and reduce redundancy.
|
436 |
+
|
437 |
+
## [0.3.12] - 2024-08-07
|
438 |
+
|
439 |
+
### Added
|
440 |
+
|
441 |
+
- **🔄 Sidebar Infinite Scroll**: Added an infinite scroll feature in the sidebar for more efficient chat navigation, reducing load times and enhancing user experience.
|
442 |
+
- **🚀 Enhanced Markdown Rendering**: Support for rendering all code blocks and making images clickable for preview; codespan styling is also enhanced to improve readability and user interaction.
|
443 |
+
- **🔒 Admin Shared Chat Visibility**: Admins no longer have default visibility over shared chats when ENABLE_ADMIN_CHAT_ACCESS is set to false, tightening security and privacy settings for users.
|
444 |
+
- **🌍 Language Updates**: Added Malay (Bahasa Malaysia) translation and updated Catalan and Traditional Chinese translations to improve accessibility for more users.
|
445 |
+
|
446 |
+
### Fixed
|
447 |
+
|
448 |
+
- **📊 Markdown Rendering Issues**: Resolved issues with markdown rendering to ensure consistent and correct display across components.
|
449 |
+
- **🛠️ Styling Issues**: Multiple fixes applied to styling throughout the application, improving the overall visual experience and interface consistency.
|
450 |
+
- **🗃️ Modal Handling**: Fixed an issue where modals were not closing correctly in various model chat scenarios, enhancing usability and interface reliability.
|
451 |
+
- **📄 Missing OpenAI Usage Information**: Resolved issues where usage statistics for OpenAI services were not being correctly displayed, ensuring users have access to crucial data for managing and monitoring their API consumption.
|
452 |
+
- **🔧 Non-Streaming Support for Functions Plugin**: Fixed a functionality issue with the Functions plugin where non-streaming operations were not functioning as intended, restoring full capabilities for async and sync integration within the platform.
|
453 |
+
- **🔄 Environment Variable Type Correction (COMFYUI_FLUX_FP8_CLIP)**: Corrected the data type of the 'COMFYUI_FLUX_FP8_CLIP' environment variable from string to boolean, ensuring environment settings apply correctly and enhance configuration management.
|
454 |
+
|
455 |
+
### Changed
|
456 |
+
|
457 |
+
- **🔧 Backend Dependency Updates**: Updated several backend dependencies such as boto3, pypdf, python-pptx, validators, and black, ensuring up-to-date security and performance optimizations.
|
458 |
+
|
459 |
+
## [0.3.11] - 2024-08-02
|
460 |
+
|
461 |
+
### Added
|
462 |
+
|
463 |
+
- **📊 Model Information Display**: Added visuals for model selection, including images next to model names for more intuitive navigation.
|
464 |
+
- **🗣 ElevenLabs Voice Adaptations**: Voice enhancements including support for ElevenLabs voice ID by name for personalized vocal interactions.
|
465 |
+
- **⌨️ Arrow Keys Model Selection**: Users can now use arrow keys for quicker model selection, enhancing accessibility.
|
466 |
+
- **🔍 Fuzzy Search in Model Selector**: Enhanced model selector with fuzzy search to locate models swiftly, including descriptions.
|
467 |
+
- **🕹️ ComfyUI Flux Image Generation**: Added support for the new Flux image gen model; introduces environment controls like weight precision and CLIP model options in Settings.
|
468 |
+
- **💾 Display File Size for Uploads**: Enhanced file interface now displays file size, preparing for upcoming upload restrictions.
|
469 |
+
- **🎚️ Advanced Params "Min P"**: Added 'Min P' parameter in the advanced settings for customized model precision control.
|
470 |
+
- **🔒 Enhanced OAuth**: Introduced custom redirect URI support for OAuth behind reverse proxies, enabling safer authentication processes.
|
471 |
+
- **🖥 Enhanced Latex Rendering**: Adjustments made to latex rendering processes, now accurately detecting and presenting latex inputs from text.
|
472 |
+
- **🌐 Internationalization**: Enhanced with new Romanian and updated Vietnamese and Ukrainian translations, helping broaden accessibility for international users.
|
473 |
+
|
474 |
+
### Fixed
|
475 |
+
|
476 |
+
- **🔧 Tags Handling in Document Upload**: Tags are now properly sent to the upload document handler, resolving issues with missing metadata.
|
477 |
+
- **🖥️ Sensitive Input Fields**: Corrected browser misinterpretation of secure input fields, preventing misclassification as password fields.
|
478 |
+
- **📂 Static Path Resolution in PDF Generation**: Fixed static paths that adjust dynamically to prevent issues across various environments.
|
479 |
+
|
480 |
+
### Changed
|
481 |
+
|
482 |
+
- **🎨 UI/UX Styling Enhancements**: Multiple minor styling updates for a cleaner and more intuitive user interface.
|
483 |
+
- **🚧 Refactoring Various Components**: Numerous refactoring changes across styling, file handling, and function simplifications for clarity and performance.
|
484 |
+
- **🎛️ User Valves Management**: Moved user valves from settings to direct chat controls for more user-friendly access during interactions.
|
485 |
+
|
486 |
+
### Removed
|
487 |
+
|
488 |
+
- **⚙️ Health Check Logging**: Removed verbose logging from the health checking processes to declutter logs and improve backend performance.
|
489 |
+
|
490 |
+
## [0.3.10] - 2024-07-17
|
491 |
+
|
492 |
+
### Fixed
|
493 |
+
|
494 |
+
- **🔄 Improved File Upload**: Addressed the issue where file uploads lacked animation.
|
495 |
+
- **💬 Chat Continuity**: Fixed a problem where existing chats were not functioning properly in some instances.
|
496 |
+
- **🗂️ Chat File Reset**: Resolved the issue of chat files not resetting for new conversations, now ensuring a clean slate for each chat session.
|
497 |
+
- **📁 Document Workspace Uploads**: Corrected the handling of document uploads in the workspace using the Files API.
|
498 |
+
|
499 |
+
## [0.3.9] - 2024-07-17
|
500 |
+
|
501 |
+
### Added
|
502 |
+
|
503 |
+
- **📁 Files Chat Controls**: We've reverted to the old file handling behavior where uploaded files are always included. You can now manage files directly within the chat controls section, giving you the ability to remove files as needed.
|
504 |
+
- **🔧 "Action" Function Support**: Introducing a new "Action" function to write custom buttons to the message toolbar. This feature enables more interactive messaging, with documentation coming soon.
|
505 |
+
- **📜 Citations Handling**: For newly uploaded files in documents workspace, citations will now display the actual filename. Additionally, you can click on these filenames to open the file in a new tab for easier access.
|
506 |
+
- **🛠️ Event Emitter and Call Updates**: Enhanced 'event_emitter' to allow message replacement and 'event_call' to support text input for Tools and Functions. Detailed documentation will be provided shortly.
|
507 |
+
- **🎨 Styling Refactor**: Various styling updates for a cleaner and more cohesive user interface.
|
508 |
+
- **🌐 Enhanced Translations**: Improved translations for Catalan, Ukrainian, and Brazilian Portuguese.
|
509 |
+
|
510 |
+
### Fixed
|
511 |
+
|
512 |
+
- **🔧 Chat Controls Priority**: Resolved an issue where Chat Controls values were being overridden by model information parameters. The priority is now Chat Controls, followed by Global Settings, then Model Settings.
|
513 |
+
- **🪲 Debug Logs**: Fixed an issue where debug logs were not being logged properly.
|
514 |
+
- **🔑 Automatic1111 Auth Key**: The auth key for Automatic1111 is no longer required.
|
515 |
+
- **📝 Title Generation**: Ensured that the title generation runs only once, even when multiple models are in a chat.
|
516 |
+
- **✅ Boolean Values in Params**: Added support for boolean values in parameters.
|
517 |
+
- **🖼️ Files Overlay Styling**: Fixed the styling issue with the files overlay.
|
518 |
+
|
519 |
+
### Changed
|
520 |
+
|
521 |
+
- **⬆️ Dependency Updates**
|
522 |
+
- Upgraded 'pydantic' from version 2.7.1 to 2.8.2.
|
523 |
+
- Upgraded 'sqlalchemy' from version 2.0.30 to 2.0.31.
|
524 |
+
- Upgraded 'unstructured' from version 0.14.9 to 0.14.10.
|
525 |
+
- Upgraded 'chromadb' from version 0.5.3 to 0.5.4.
|
526 |
+
|
527 |
+
## [0.3.8] - 2024-07-09
|
528 |
+
|
529 |
+
### Added
|
530 |
+
|
531 |
+
- **💬 Chat Controls**: Easily adjust parameters for each chat session, offering more precise control over your interactions.
|
532 |
+
- **📌 Pinned Chats**: Support for pinned chats, allowing you to keep important conversations easily accessible.
|
533 |
+
- **📄 Apache Tika Integration**: Added support for using Apache Tika as a document loader, enhancing document processing capabilities.
|
534 |
+
- **🛠️ Custom Environment for OpenID Claims**: Allows setting custom claims for OpenID, providing more flexibility in user authentication.
|
535 |
+
- **🔧 Enhanced Tools & Functions API**: Introduced 'event_emitter' and 'event_call', now you can also add citations for better documentation and tracking. Detailed documentation will be provided on our documentation website.
|
536 |
+
- **↔️ Sideways Scrolling in Settings**: Settings tabs container now supports horizontal scrolling for easier navigation.
|
537 |
+
- **🌑 Darker OLED Theme**: Includes a new, darker OLED theme and improved styling for the light theme, enhancing visual appeal.
|
538 |
+
- **🌐 Language Updates**: Updated translations for Indonesian, German, French, and Catalan languages, expanding accessibility.
|
539 |
+
|
540 |
+
### Fixed
|
541 |
+
|
542 |
+
- **⏰ OpenAI Streaming Timeout**: Resolved issues with OpenAI streaming response using the 'AIOHTTP_CLIENT_TIMEOUT' setting, ensuring reliable performance.
|
543 |
+
- **💡 User Valves**: Fixed malfunctioning user valves, ensuring proper functionality.
|
544 |
+
- **🔄 Collapsible Components**: Addressed issues with collapsible components not working, restoring expected behavior.
|
545 |
+
|
546 |
+
### Changed
|
547 |
+
|
548 |
+
- **🗃️ Database Backend**: Switched from Peewee to SQLAlchemy for improved concurrency support, enhancing database performance.
|
549 |
+
- **⬆️ ChromaDB Update**: Upgraded to version 0.5.3. Ensure your remote ChromaDB instance matches this version.
|
550 |
+
- **🔤 Primary Font Styling**: Updated primary font to Archivo for better visual consistency.
|
551 |
+
- **🔄 Font Change for Windows**: Replaced Arimo with Inter font for Windows users, improving readability.
|
552 |
+
- **🚀 Lazy Loading**: Implemented lazy loading for 'faster_whisper' and 'sentence_transformers' to reduce startup memory usage.
|
553 |
+
- **📋 Task Generation Payload**: Task generations now include only the "task" field in the body instead of "title".
|
554 |
+
|
555 |
+
## [0.3.7] - 2024-06-29
|
556 |
+
|
557 |
+
### Added
|
558 |
+
|
559 |
+
- **🌐 Enhanced Internationalization (i18n)**: Newly introduced Indonesian translation, and updated translations for Turkish, Chinese, and Catalan languages to improve user accessibility.
|
560 |
+
|
561 |
+
### Fixed
|
562 |
+
|
563 |
+
- **🕵️♂️ Browser Language Detection**: Corrected the issue where the application was not properly detecting and adapting to the browser's language settings.
|
564 |
+
- **🔐 OIDC Admin Role Assignment**: Fixed a bug where the admin role was not being assigned to the first user who signed up via OpenID Connect (OIDC).
|
565 |
+
- **💬 Chat/Completions Endpoint**: Resolved an issue where the chat/completions endpoint was non-functional when the stream option was set to False.
|
566 |
+
- **🚫 'WEBUI_AUTH' Configuration**: Addressed the problem where setting 'WEBUI_AUTH' to False was not being applied correctly.
|
567 |
+
|
568 |
+
### Changed
|
569 |
+
|
570 |
+
- **📦 Dependency Update**: Upgraded 'authlib' from version 1.3.0 to 1.3.1 to ensure better security and performance enhancements.
|
571 |
+
|
572 |
+
## [0.3.6] - 2024-06-27
|
573 |
+
|
574 |
+
### Added
|
575 |
+
|
576 |
+
- **✨ "Functions" Feature**: You can now utilize "Functions" like filters (middleware) and pipe (model) functions directly within the WebUI. While largely compatible with Pipelines, these native functions can be executed easily within Open WebUI. Example use cases for filter functions include usage monitoring, real-time translation, moderation, and automemory. For pipe functions, the scope ranges from Cohere and Anthropic integration directly within Open WebUI, enabling "Valves" for per-user OpenAI API key usage, and much more. If you encounter issues, SAFE_MODE has been introduced.
|
577 |
+
- **📁 Files API**: Compatible with OpenAI, this feature allows for custom Retrieval-Augmented Generation (RAG) in conjunction with the Filter Function. More examples will be shared on our community platform and official documentation website.
|
578 |
+
- **🛠️ Tool Enhancements**: Tools now support citations and "Valves". Documentation will be available shortly.
|
579 |
+
- **🔗 Iframe Support via Files API**: Enables rendering HTML directly into your chat interface using functions and tools. Use cases include playing games like DOOM and Snake, displaying a weather applet, and implementing Anthropic "artifacts"-like features. Stay tuned for updates on our community platform and documentation.
|
580 |
+
- **🔒 Experimental OAuth Support**: New experimental OAuth support. Check our documentation for more details.
|
581 |
+
- **🖼️ Custom Background Support**: Set a custom background from Settings > Interface to personalize your experience.
|
582 |
+
- **🔑 AUTOMATIC1111_API_AUTH Support**: Enhanced security for the AUTOMATIC1111 API.
|
583 |
+
- **🎨 Code Highlight Optimization**: Improved code highlighting features.
|
584 |
+
- **🎙️ Voice Interruption Feature**: Reintroduced and now toggleable from Settings > Interface.
|
585 |
+
- **💤 Wakelock API**: Now in use to prevent screen dimming during important tasks.
|
586 |
+
- **🔐 API Key Privacy**: All API keys are now hidden by default for better security.
|
587 |
+
- **🔍 New Web Search Provider**: Added jina_search as a new option.
|
588 |
+
- **🌐 Enhanced Internationalization (i18n)**: Improved Korean translation and updated Chinese and Ukrainian translations.
|
589 |
+
|
590 |
+
### Fixed
|
591 |
+
|
592 |
+
- **🔧 Conversation Mode Issue**: Fixed the issue where Conversation Mode remained active after being removed from settings.
|
593 |
+
- **📏 Scroll Button Obstruction**: Resolved the issue where the scrollToBottom button container obstructed clicks on buttons beneath it.
|
594 |
+
|
595 |
+
### Changed
|
596 |
+
|
597 |
+
- **⏲️ AIOHTTP_CLIENT_TIMEOUT**: Now set to 'None' by default for improved configuration flexibility.
|
598 |
+
- **📞 Voice Call Enhancements**: Improved by skipping code blocks and expressions during calls.
|
599 |
+
- **🚫 Error Message Handling**: Disabled the continuation of operations with error messages.
|
600 |
+
- **🗂️ Playground Relocation**: Moved the Playground from the workspace to the user menu for better user experience.
|
601 |
+
|
602 |
+
## [0.3.5] - 2024-06-16
|
603 |
+
|
604 |
+
### Added
|
605 |
+
|
606 |
+
- **📞 Enhanced Voice Call**: Text-to-speech (TTS) callback now operates in real-time for each sentence, reducing latency by not waiting for full completion.
|
607 |
+
- **👆 Tap to Interrupt**: During a call, you can now stop the assistant from speaking by simply tapping, instead of using voice. This resolves the issue of the speaker's voice being mistakenly registered as input.
|
608 |
+
- **😊 Emoji Call**: Toggle this feature on from the Settings > Interface, allowing LLMs to express emotions using emojis during voice calls for a more dynamic interaction.
|
609 |
+
- **🖱️ Quick Archive/Delete**: Use the Shift key + mouseover on the chat list to swiftly archive or delete items.
|
610 |
+
- **📝 Markdown Support in Model Descriptions**: You can now format model descriptions with markdown, enabling bold text, links, etc.
|
611 |
+
- **🧠 Editable Memories**: Adds the capability to modify memories.
|
612 |
+
- **📋 Admin Panel Sorting**: Introduces the ability to sort users/chats within the admin panel.
|
613 |
+
- **🌑 Dark Mode for Quick Selectors**: Dark mode now available for chat quick selectors (prompts, models, documents).
|
614 |
+
- **🔧 Advanced Parameters**: Adds 'num_keep' and 'num_batch' to advanced parameters for customization.
|
615 |
+
- **📅 Dynamic System Prompts**: New variables '{{CURRENT_DATETIME}}', '{{CURRENT_TIME}}', '{{USER_LOCATION}}' added for system prompts. Ensure '{{USER_LOCATION}}' is toggled on from Settings > Interface.
|
616 |
+
- **🌐 Tavily Web Search**: Includes Tavily as a web search provider option.
|
617 |
+
- **🖊️ Federated Auth Usernames**: Ability to set user names for federated authentication.
|
618 |
+
- **🔗 Auto Clean URLs**: When adding connection URLs, trailing slashes are now automatically removed.
|
619 |
+
- **🌐 Enhanced Translations**: Improved Chinese and Swedish translations.
|
620 |
+
|
621 |
+
### Fixed
|
622 |
+
|
623 |
+
- **⏳ AIOHTTP_CLIENT_TIMEOUT**: Introduced a new environment variable 'AIOHTTP_CLIENT_TIMEOUT' for requests to Ollama lasting longer than 5 minutes. Default is 300 seconds; set to blank ('') for no timeout.
|
624 |
+
- **❌ Message Delete Freeze**: Resolved an issue where message deletion would sometimes cause the web UI to freeze.
|
625 |
+
|
626 |
+
## [0.3.4] - 2024-06-12
|
627 |
+
|
628 |
+
### Fixed
|
629 |
+
|
630 |
+
- **🔒 Mixed Content with HTTPS Issue**: Resolved a problem where mixed content (HTTP and HTTPS) was causing security warnings and blocking resources on HTTPS sites.
|
631 |
+
- **🔍 Web Search Issue**: Addressed the problem where web search functionality was not working correctly. The 'ENABLE_RAG_LOCAL_WEB_FETCH' option has been reintroduced to restore proper web searching capabilities.
|
632 |
+
- **💾 RAG Template Not Being Saved**: Fixed an issue where the RAG template was not being saved correctly, ensuring your custom templates are now preserved as expected.
|
633 |
+
|
634 |
+
## [0.3.3] - 2024-06-12
|
635 |
+
|
636 |
+
### Added
|
637 |
+
|
638 |
+
- **🛠️ Native Python Function Calling**: Introducing native Python function calling within Open WebUI. We’ve also included a built-in code editor to seamlessly develop and integrate function code within the 'Tools' workspace. With this, you can significantly enhance your LLM’s capabilities by creating custom RAG pipelines, web search tools, and even agent-like features such as sending Discord messages.
|
639 |
+
- **🌐 DuckDuckGo Integration**: Added DuckDuckGo as a web search provider, giving you more search options.
|
640 |
+
- **🌏 Enhanced Translations**: Improved translations for Vietnamese and Chinese languages, making the interface more accessible.
|
641 |
+
|
642 |
+
### Fixed
|
643 |
+
|
644 |
+
- **🔗 Web Search URL Error Handling**: Fixed the issue where a single URL error would disrupt the data loading process in Web Search mode. Now, such errors will be handled gracefully to ensure uninterrupted data loading.
|
645 |
+
- **🖥️ Frontend Responsiveness**: Resolved the problem where the frontend would stop responding if the backend encounters an error while downloading a model. Improved error handling to maintain frontend stability.
|
646 |
+
- **🔧 Dependency Issues in pip**: Fixed issues related to pip installations, ensuring all dependencies are correctly managed to prevent installation errors.
|
647 |
+
|
648 |
+
## [0.3.2] - 2024-06-10
|
649 |
+
|
650 |
+
### Added
|
651 |
+
|
652 |
+
- **🔍 Web Search Query Status**: The web search query will now persist in the results section to aid in easier debugging and tracking of search queries.
|
653 |
+
- **🌐 New Web Search Provider**: We have added Serply as a new option for web search providers, giving you more choices for your search needs.
|
654 |
+
- **🌏 Improved Translations**: We've enhanced translations for Chinese and Portuguese.
|
655 |
+
|
656 |
+
### Fixed
|
657 |
+
|
658 |
+
- **🎤 Audio File Upload Issue**: The bug that prevented audio files from being uploaded in chat input has been fixed, ensuring smooth communication.
|
659 |
+
- **💬 Message Input Handling**: Improved the handling of message inputs by instantly clearing images and text after sending, along with immediate visual indications when a response message is loading, enhancing user feedback.
|
660 |
+
- **⚙️ Parameter Registration and Validation**: Fixed the issue where parameters were not registering in certain cases and addressed the problem where users were unable to save due to invalid input errors.
|
661 |
+
|
662 |
+
## [0.3.1] - 2024-06-09
|
663 |
+
|
664 |
+
### Fixed
|
665 |
+
|
666 |
+
- **💬 Chat Functionality**: Resolved the issue where chat functionality was not working for specific models.
|
667 |
+
|
668 |
+
## [0.3.0] - 2024-06-09
|
669 |
+
|
670 |
+
### Added
|
671 |
+
|
672 |
+
- **📚 Knowledge Support for Models**: Attach documents directly to models from the models workspace, enhancing the information available to each model.
|
673 |
+
- **🎙️ Hands-Free Voice Call Feature**: Initiate voice calls without needing to use your hands, making interactions more seamless.
|
674 |
+
- **📹 Video Call Feature**: Enable video calls with supported vision models like Llava and GPT-4o, adding a visual dimension to your communications.
|
675 |
+
- **🎛️ Enhanced UI for Voice Recording**: Improved user interface for the voice recording feature, making it more intuitive and user-friendly.
|
676 |
+
- **🌐 External STT Support**: Now support for external Speech-To-Text services, providing more flexibility in choosing your STT provider.
|
677 |
+
- **⚙️ Unified Settings**: Consolidated settings including document settings under a new admin settings section for easier management.
|
678 |
+
- **🌑 Dark Mode Splash Screen**: A new splash screen for dark mode, ensuring a consistent and visually appealing experience for dark mode users.
|
679 |
+
- **📥 Upload Pipeline**: Directly upload pipelines from the admin settings > pipelines section, streamlining the pipeline management process.
|
680 |
+
- **🌍 Improved Language Support**: Enhanced support for Chinese and Ukrainian languages, better catering to a global user base.
|
681 |
+
|
682 |
+
### Fixed
|
683 |
+
|
684 |
+
- **🛠️ Playground Issue**: Fixed the playground not functioning properly, ensuring a smoother user experience.
|
685 |
+
- **🔥 Temperature Parameter Issue**: Corrected the issue where the temperature value '0' was not being passed correctly.
|
686 |
+
- **📝 Prompt Input Clearing**: Resolved prompt input textarea not being cleared right away, ensuring a clean slate for new inputs.
|
687 |
+
- **✨ Various UI Styling Issues**: Fixed numerous user interface styling problems for a more cohesive look.
|
688 |
+
- **👥 Active Users Display**: Fixed active users showing active sessions instead of actual users, now reflecting accurate user activity.
|
689 |
+
- **🌐 Community Platform Compatibility**: The Community Platform is back online and fully compatible with Open WebUI.
|
690 |
+
|
691 |
+
### Changed
|
692 |
+
|
693 |
+
- **📝 RAG Implementation**: Updated the RAG (Retrieval-Augmented Generation) implementation to use a system prompt for context, instead of overriding the user's prompt.
|
694 |
+
- **🔄 Settings Relocation**: Moved Models, Connections, Audio, and Images settings to the admin settings for better organization.
|
695 |
+
- **✍️ Improved Title Generation**: Enhanced the default prompt for title generation, yielding better results.
|
696 |
+
- **🔧 Backend Task Management**: Tasks like title generation and search query generation are now managed on the backend side and controlled only by the admin.
|
697 |
+
- **🔍 Editable Search Query Prompt**: You can now edit the search query generation prompt, offering more control over how queries are generated.
|
698 |
+
- **📏 Prompt Length Threshold**: Set the prompt length threshold for search query generation from the admin settings, giving more customization options.
|
699 |
+
- **📣 Settings Consolidation**: Merged the Banners admin setting with the Interface admin setting for a more streamlined settings area.
|
700 |
+
|
701 |
+
## [0.2.5] - 2024-06-05
|
702 |
+
|
703 |
+
### Added
|
704 |
+
|
705 |
+
- **👥 Active Users Indicator**: Now you can see how many people are currently active and what they are running. This helps you gauge when performance might slow down due to a high number of users.
|
706 |
+
- **🗂️ Create Ollama Modelfile**: The option to create a modelfile for Ollama has been reintroduced in the Settings > Models section, making it easier to manage your models.
|
707 |
+
- **⚙️ Default Model Setting**: Added an option to set the default model from Settings > Interface. This feature is now easily accessible, especially convenient for mobile users as it was previously hidden.
|
708 |
+
- **🌐 Enhanced Translations**: We've improved the Chinese translations and added support for Turkmen and Norwegian languages to make the interface more accessible globally.
|
709 |
+
|
710 |
+
### Fixed
|
711 |
+
|
712 |
+
- **📱 Mobile View Improvements**: The UI now uses dvh (dynamic viewport height) instead of vh (viewport height), providing a better and more responsive experience for mobile users.
|
713 |
+
|
714 |
+
## [0.2.4] - 2024-06-03
|
715 |
+
|
716 |
+
### Added
|
717 |
+
|
718 |
+
- **👤 Improved Account Pending Page**: The account pending page now displays admin details by default to avoid confusion. You can disable this feature in the admin settings if needed.
|
719 |
+
- **🌐 HTTP Proxy Support**: We have enabled the use of the 'http_proxy' environment variable in OpenAI and Ollama API calls, making it easier to configure network settings.
|
720 |
+
- **❓ Quick Access to Documentation**: You can now easily access Open WebUI documents via a question mark button located at the bottom right corner of the screen (available on larger screens like PCs).
|
721 |
+
- **🌍 Enhanced Translation**: Improvements have been made to translations.
|
722 |
+
|
723 |
+
### Fixed
|
724 |
+
|
725 |
+
- **🔍 SearxNG Web Search**: Fixed the issue where the SearxNG web search functionality was not working properly.
|
726 |
+
|
727 |
+
## [0.2.3] - 2024-06-03
|
728 |
+
|
729 |
+
### Added
|
730 |
+
|
731 |
+
- **📁 Export Chat as JSON**: You can now export individual chats as JSON files from the navbar menu by navigating to 'Download > Export Chat'. This makes sharing specific conversations easier.
|
732 |
+
- **✏️ Edit Titles with Double Click**: Double-click on titles to rename them quickly and efficiently.
|
733 |
+
- **🧩 Batch Multiple Embeddings**: Introduced 'RAG_EMBEDDING_OPENAI_BATCH_SIZE' to process multiple embeddings in a batch, enhancing performance for large datasets.
|
734 |
+
- **🌍 Improved Translations**: Enhanced the translation quality across various languages for a better user experience.
|
735 |
+
|
736 |
+
### Fixed
|
737 |
+
|
738 |
+
- **🛠️ Modelfile Migration Script**: Fixed an issue where the modelfile migration script would fail if an invalid modelfile was encountered.
|
739 |
+
- **💬 Zhuyin Input Method on Mac**: Resolved an issue where using the Zhuyin input method in the Web UI on a Mac caused text to send immediately upon pressing the enter key, leading to incorrect input.
|
740 |
+
- **🔊 Local TTS Voice Selection**: Fixed the issue where the selected local Text-to-Speech (TTS) voice was not being displayed in settings.
|
741 |
+
|
742 |
+
## [0.2.2] - 2024-06-02
|
743 |
+
|
744 |
+
### Added
|
745 |
+
|
746 |
+
- **🌊 Mermaid Rendering Support**: We've included support for Mermaid rendering. This allows you to create beautiful diagrams and flowcharts directly within Open WebUI.
|
747 |
+
- **🔄 New Environment Variable 'RESET_CONFIG_ON_START'**: Introducing a new environment variable: 'RESET_CONFIG_ON_START'. Set this variable to reset your configuration settings upon starting the application, making it easier to revert to default settings.
|
748 |
+
|
749 |
+
### Fixed
|
750 |
+
|
751 |
+
- **🔧 Pipelines Filter Issue**: We've addressed an issue with the pipelines where filters were not functioning as expected.
|
752 |
+
|
753 |
+
## [0.2.1] - 2024-06-02
|
754 |
+
|
755 |
+
### Added
|
756 |
+
|
757 |
+
- **🖱️ Single Model Export Button**: Easily export models with just one click using the new single model export button.
|
758 |
+
- **🖥️ Advanced Parameters Support**: Added support for 'num_thread', 'use_mmap', and 'use_mlock' parameters for Ollama.
|
759 |
+
- **🌐 Improved Vietnamese Translation**: Enhanced Vietnamese language support for a better user experience for our Vietnamese-speaking community.
|
760 |
+
|
761 |
+
### Fixed
|
762 |
+
|
763 |
+
- **🔧 OpenAI URL API Save Issue**: Corrected a problem preventing the saving of OpenAI URL API settings.
|
764 |
+
- **🚫 Display Issue with Disabled Ollama API**: Fixed the display bug causing models to appear in settings when the Ollama API was disabled.
|
765 |
+
|
766 |
+
### Changed
|
767 |
+
|
768 |
+
- **💡 Versioning Update**: As a reminder from our previous update, version 0.2.y will focus primarily on bug fixes, while major updates will be designated as 0.x from now on for better version tracking.
|
769 |
+
|
770 |
+
## [0.2.0] - 2024-06-01
|
771 |
+
|
772 |
+
### Added
|
773 |
+
|
774 |
+
- **🔧 Pipelines Support**: Open WebUI now includes a plugin framework for enhanced customization and functionality (https://github.com/open-webui/pipelines). Easily add custom logic and integrate Python libraries, from AI agents to home automation APIs.
|
775 |
+
- **🔗 Function Calling via Pipelines**: Integrate function calling seamlessly through Pipelines.
|
776 |
+
- **⚖️ User Rate Limiting via Pipelines**: Implement user-specific rate limits to manage API usage efficiently.
|
777 |
+
- **📊 Usage Monitoring with Langfuse**: Track and analyze usage statistics with Langfuse integration through Pipelines.
|
778 |
+
- **🕒 Conversation Turn Limits**: Set limits on conversation turns to manage interactions better through Pipelines.
|
779 |
+
- **🛡️ Toxic Message Filtering**: Automatically filter out toxic messages to maintain a safe environment using Pipelines.
|
780 |
+
- **🔍 Web Search Support**: Introducing built-in web search capabilities via RAG API, allowing users to search using SearXNG, Google Programmatic Search Engine, Brave Search, serpstack, and serper. Activate it effortlessly by adding necessary variables from Document settings > Web Params.
|
781 |
+
- **🗂️ Models Workspace**: Create and manage model presets for both Ollama/OpenAI API. Note: The old Modelfiles workspace is deprecated.
|
782 |
+
- **🛠️ Model Builder Feature**: Build and edit all models with persistent builder mode.
|
783 |
+
- **🏷️ Model Tagging Support**: Organize models with tagging features in the models workspace.
|
784 |
+
- **📋 Model Ordering Support**: Effortlessly organize models by dragging and dropping them into the desired positions within the models workspace.
|
785 |
+
- **📈 OpenAI Generation Stats**: Access detailed generation statistics for OpenAI models.
|
786 |
+
- **📅 System Prompt Variables**: New variables added: '{{CURRENT_DATE}}' and '{{USER_NAME}}' for dynamic prompts.
|
787 |
+
- **📢 Global Banner Support**: Manage global banners from admin settings > banners.
|
788 |
+
- **🗃️ Enhanced Archived Chats Modal**: Search and export archived chats easily.
|
789 |
+
- **📂 Archive All Button**: Quickly archive all chats from settings > chats.
|
790 |
+
- **🌐 Improved Translations**: Added and improved translations for French, Croatian, Cebuano, and Vietnamese.
|
791 |
+
|
792 |
+
### Fixed
|
793 |
+
|
794 |
+
- **🔍 Archived Chats Visibility**: Resolved issue with archived chats not showing in the admin panel.
|
795 |
+
- **💬 Message Styling**: Fixed styling issues affecting message appearance.
|
796 |
+
- **🔗 Shared Chat Responses**: Corrected the issue where shared chat response messages were not readonly.
|
797 |
+
- **🖥️ UI Enhancement**: Fixed the scrollbar overlapping issue with the message box in the user interface.
|
798 |
+
|
799 |
+
### Changed
|
800 |
+
|
801 |
+
- **💾 User Settings Storage**: User settings are now saved on the backend, ensuring consistency across all devices.
|
802 |
+
- **📡 Unified API Requests**: The API request for getting models is now unified to '/api/models' for easier usage.
|
803 |
+
- **🔄 Versioning Update**: Our versioning will now follow the format 0.x for major updates and 0.x.y for patches.
|
804 |
+
- **📦 Export All Chats (All Users)**: Moved this functionality to the Admin Panel settings for better organization and accessibility.
|
805 |
+
|
806 |
+
### Removed
|
807 |
+
|
808 |
+
- **🚫 Bundled LiteLLM Support Deprecated**: Migrate your LiteLLM config.yaml to a self-hosted LiteLLM instance. LiteLLM can still be added via OpenAI Connections. Download the LiteLLM config.yaml from admin settings > database > export LiteLLM config.yaml.
|
809 |
+
|
810 |
+
## [0.1.125] - 2024-05-19
|
811 |
+
|
812 |
+
### Added
|
813 |
+
|
814 |
+
- **🔄 Updated UI**: Chat interface revamped with chat bubbles. Easily switch back to the old style via settings > interface > chat bubble UI.
|
815 |
+
- **📂 Enhanced Sidebar UI**: Model files, documents, prompts, and playground merged into Workspace for streamlined access.
|
816 |
+
- **🚀 Improved Many Model Interaction**: All responses now displayed simultaneously for a smoother experience.
|
817 |
+
- **🐍 Python Code Execution**: Execute Python code locally in the browser with libraries like 'requests', 'beautifulsoup4', 'numpy', 'pandas', 'seaborn', 'matplotlib', 'scikit-learn', 'scipy', 'regex'.
|
818 |
+
- **🧠 Experimental Memory Feature**: Manually input personal information you want LLMs to remember via settings > personalization > memory.
|
819 |
+
- **💾 Persistent Settings**: Settings now saved as config.json for convenience.
|
820 |
+
- **🩺 Health Check Endpoint**: Added for Docker deployment.
|
821 |
+
- **↕️ RTL Support**: Toggle chat direction via settings > interface > chat direction.
|
822 |
+
- **🖥️ PowerPoint Support**: RAG pipeline now supports PowerPoint documents.
|
823 |
+
- **🌐 Language Updates**: Ukrainian, Turkish, Arabic, Chinese, Serbian, Vietnamese updated; Punjabi added.
|
824 |
+
|
825 |
+
### Changed
|
826 |
+
|
827 |
+
- **👤 Shared Chat Update**: Shared chat now includes creator user information.
|
828 |
+
|
829 |
+
## [0.1.124] - 2024-05-08
|
830 |
+
|
831 |
+
### Added
|
832 |
+
|
833 |
+
- **🖼️ Improved Chat Sidebar**: Now conveniently displays time ranges and organizes chats by today, yesterday, and more.
|
834 |
+
- **📜 Citations in RAG Feature**: Easily track the context fed to the LLM with added citations in the RAG feature.
|
835 |
+
- **🔒 Auth Disable Option**: Introducing the ability to disable authentication. Set 'WEBUI_AUTH' to False to disable authentication. Note: Only applicable for fresh installations without existing users.
|
836 |
+
- **📹 Enhanced YouTube RAG Pipeline**: Now supports non-English videos for an enriched experience.
|
837 |
+
- **🔊 Specify OpenAI TTS Models**: Customize your TTS experience by specifying OpenAI TTS models.
|
838 |
+
- **🔧 Additional Environment Variables**: Discover more environment variables in our comprehensive documentation at Open WebUI Documentation (https://docs.openwebui.com).
|
839 |
+
- **🌐 Language Support**: Arabic, Finnish, and Hindi added; Improved support for German, Vietnamese, and Chinese.
|
840 |
+
|
841 |
+
### Fixed
|
842 |
+
|
843 |
+
- **🛠️ Model Selector Styling**: Addressed styling issues for improved user experience.
|
844 |
+
- **⚠️ Warning Messages**: Resolved backend warning messages.
|
845 |
+
|
846 |
+
### Changed
|
847 |
+
|
848 |
+
- **📝 Title Generation**: Limited output to 50 tokens.
|
849 |
+
- **📦 Helm Charts**: Removed Helm charts, now available in a separate repository (https://github.com/open-webui/helm-charts).
|
850 |
+
|
851 |
+
## [0.1.123] - 2024-05-02
|
852 |
+
|
853 |
+
### Added
|
854 |
+
|
855 |
+
- **🎨 New Landing Page Design**: Refreshed design for a more modern look and optimized use of screen space.
|
856 |
+
- **📹 Youtube RAG Pipeline**: Introduces dedicated RAG pipeline for Youtube videos, enabling interaction with video transcriptions directly.
|
857 |
+
- **🔧 Enhanced Admin Panel**: Streamlined user management with options to add users directly or in bulk via CSV import.
|
858 |
+
- **👥 '@' Model Integration**: Easily switch to specific models during conversations; old collaborative chat feature phased out.
|
859 |
+
- **🌐 Language Enhancements**: Swedish translation added, plus improvements to German, Spanish, and the addition of Doge translation.
|
860 |
+
|
861 |
+
### Fixed
|
862 |
+
|
863 |
+
- **🗑️ Delete Chat Shortcut**: Addressed issue where shortcut wasn't functioning.
|
864 |
+
- **🖼️ Modal Closing Bug**: Resolved unexpected closure of modal when dragging from within.
|
865 |
+
- **✏️ Edit Button Styling**: Fixed styling inconsistency with edit buttons.
|
866 |
+
- **🌐 Image Generation Compatibility Issue**: Rectified image generation compatibility issue with third-party APIs.
|
867 |
+
- **📱 iOS PWA Icon Fix**: Corrected iOS PWA home screen icon shape.
|
868 |
+
- **🔍 Scroll Gesture Bug**: Adjusted gesture sensitivity to prevent accidental activation when scrolling through code on mobile; now requires scrolling from the leftmost side to open the sidebar.
|
869 |
+
|
870 |
+
### Changed
|
871 |
+
|
872 |
+
- **🔄 Unlimited Context Length**: Advanced settings now allow unlimited max context length (previously limited to 16000).
|
873 |
+
- **👑 Super Admin Assignment**: The first signup is automatically assigned a super admin role, unchangeable by other admins.
|
874 |
+
- **🛡️ Admin User Restrictions**: User action buttons from the admin panel are now disabled for users with admin roles.
|
875 |
+
- **🔝 Default Model Selector**: Set as default model option now exclusively available on the landing page.
|
876 |
+
|
877 |
+
## [0.1.122] - 2024-04-27
|
878 |
+
|
879 |
+
### Added
|
880 |
+
|
881 |
+
- **🌟 Enhanced RAG Pipeline**: Now with hybrid searching via 'BM25', reranking powered by 'CrossEncoder', and configurable relevance score thresholds.
|
882 |
+
- **🛢️ External Database Support**: Seamlessly connect to custom SQLite or Postgres databases using the 'DATABASE_URL' environment variable.
|
883 |
+
- **🌐 Remote ChromaDB Support**: Introducing the capability to connect to remote ChromaDB servers.
|
884 |
+
- **👨💼 Improved Admin Panel**: Admins can now conveniently check users' chat lists and last active status directly from the admin panel.
|
885 |
+
- **🎨 Splash Screen**: Introducing a loading splash screen for a smoother user experience.
|
886 |
+
- **🌍 Language Support Expansion**: Added support for Bangla (bn-BD), along with enhancements to Chinese, Spanish, and Ukrainian translations.
|
887 |
+
- **💻 Improved LaTeX Rendering Performance**: Enjoy faster rendering times for LaTeX equations.
|
888 |
+
- **🔧 More Environment Variables**: Explore additional environment variables in our documentation (https://docs.openwebui.com), including the 'ENABLE_LITELLM' option to manage memory usage.
|
889 |
+
|
890 |
+
### Fixed
|
891 |
+
|
892 |
+
- **🔧 Ollama Compatibility**: Resolved errors occurring when Ollama server version isn't an integer, such as SHA builds or RCs.
|
893 |
+
- **🐛 Various OpenAI API Issues**: Addressed several issues related to the OpenAI API.
|
894 |
+
- **🛑 Stop Sequence Issue**: Fixed the problem where the stop sequence with a backslash '\' was not functioning.
|
895 |
+
- **🔤 Font Fallback**: Corrected font fallback issue.
|
896 |
+
|
897 |
+
### Changed
|
898 |
+
|
899 |
+
- **⌨️ Prompt Input Behavior on Mobile**: Enter key prompt submission disabled on mobile devices for improved user experience.
|
900 |
+
|
901 |
+
## [0.1.121] - 2024-04-24
|
902 |
+
|
903 |
+
### Fixed
|
904 |
+
|
905 |
+
- **🔧 Translation Issues**: Addressed various translation discrepancies.
|
906 |
+
- **🔒 LiteLLM Security Fix**: Updated LiteLLM version to resolve a security vulnerability.
|
907 |
+
- **🖥️ HTML Tag Display**: Rectified the issue where the '< br >' tag wasn't displaying correctly.
|
908 |
+
- **🔗 WebSocket Connection**: Resolved the failure of WebSocket connection under HTTPS security for ComfyUI server.
|
909 |
+
- **📜 FileReader Optimization**: Implemented FileReader initialization per image in multi-file drag & drop to ensure reusability.
|
910 |
+
- **🏷️ Tag Display**: Corrected tag display inconsistencies.
|
911 |
+
- **📦 Archived Chat Styling**: Fixed styling issues in archived chat.
|
912 |
+
- **🔖 Safari Copy Button Bug**: Addressed the bug where the copy button failed to copy links in Safari.
|
913 |
+
|
914 |
+
## [0.1.120] - 2024-04-20
|
915 |
+
|
916 |
+
### Added
|
917 |
+
|
918 |
+
- **📦 Archive Chat Feature**: Easily archive chats with a new sidebar button, and access archived chats via the profile button > archived chats.
|
919 |
+
- **🔊 Configurable Text-to-Speech Endpoint**: Customize your Text-to-Speech experience with configurable OpenAI endpoints.
|
920 |
+
- **🛠️ Improved Error Handling**: Enhanced error message handling for connection failures.
|
921 |
+
- **⌨️ Enhanced Shortcut**: When editing messages, use ctrl/cmd+enter to save and submit, and esc to close.
|
922 |
+
- **🌐 Language Support**: Added support for Georgian and enhanced translations for Portuguese and Vietnamese.
|
923 |
+
|
924 |
+
### Fixed
|
925 |
+
|
926 |
+
- **🔧 Model Selector**: Resolved issue where default model selection was not saving.
|
927 |
+
- **🔗 Share Link Copy Button**: Fixed bug where the copy button wasn't copying links in Safari.
|
928 |
+
- **🎨 Light Theme Styling**: Addressed styling issue with the light theme.
|
929 |
+
|
930 |
+
## [0.1.119] - 2024-04-16
|
931 |
+
|
932 |
+
### Added
|
933 |
+
|
934 |
+
- **🌟 Enhanced RAG Embedding Support**: Ollama, and OpenAI models can now be used for RAG embedding model.
|
935 |
+
- **🔄 Seamless Integration**: Copy 'ollama run <model name>' directly from Ollama page to easily select and pull models.
|
936 |
+
- **🏷️ Tagging Feature**: Add tags to chats directly via the sidebar chat menu.
|
937 |
+
- **📱 Mobile Accessibility**: Swipe left and right on mobile to effortlessly open and close the sidebar.
|
938 |
+
- **🔍 Improved Navigation**: Admin panel now supports pagination for user list.
|
939 |
+
- **🌍 Additional Language Support**: Added Polish language support.
|
940 |
+
|
941 |
+
### Fixed
|
942 |
+
|
943 |
+
- **🌍 Language Enhancements**: Vietnamese and Spanish translations have been improved.
|
944 |
+
- **🔧 Helm Fixes**: Resolved issues with Helm trailing slash and manifest.json.
|
945 |
+
|
946 |
+
### Changed
|
947 |
+
|
948 |
+
- **🐳 Docker Optimization**: Updated docker image build process to utilize 'uv' for significantly faster builds compared to 'pip3'.
|
949 |
+
|
950 |
+
## [0.1.118] - 2024-04-10
|
951 |
+
|
952 |
+
### Added
|
953 |
+
|
954 |
+
- **🦙 Ollama and CUDA Images**: Added support for ':ollama' and ':cuda' tagged images.
|
955 |
+
- **👍 Enhanced Response Rating**: Now you can annotate your ratings for better feedback.
|
956 |
+
- **👤 User Initials Profile Photo**: User initials are now the default profile photo.
|
957 |
+
- **🔍 Update RAG Embedding Model**: Customize RAG embedding model directly in document settings.
|
958 |
+
- **🌍 Additional Language Support**: Added Turkish language support.
|
959 |
+
|
960 |
+
### Fixed
|
961 |
+
|
962 |
+
- **🔒 Share Chat Permission**: Resolved issue with chat sharing permissions.
|
963 |
+
- **🛠 Modal Close**: Modals can now be closed using the Esc key.
|
964 |
+
|
965 |
+
### Changed
|
966 |
+
|
967 |
+
- **🎨 Admin Panel Styling**: Refreshed styling for the admin panel.
|
968 |
+
- **🐳 Docker Image Build**: Updated docker image build process for improved efficiency.
|
969 |
+
|
970 |
+
## [0.1.117] - 2024-04-03
|
971 |
+
|
972 |
+
### Added
|
973 |
+
|
974 |
+
- 🗨️ **Local Chat Sharing**: Share chat links seamlessly between users.
|
975 |
+
- 🔑 **API Key Generation Support**: Generate secret keys to leverage Open WebUI with OpenAI libraries.
|
976 |
+
- 📄 **Chat Download as PDF**: Easily download chats in PDF format.
|
977 |
+
- 📝 **Improved Logging**: Enhancements to logging functionality.
|
978 |
+
- 📧 **Trusted Email Authentication**: Authenticate using a trusted email header.
|
979 |
+
|
980 |
+
### Fixed
|
981 |
+
|
982 |
+
- 🌷 **Enhanced Dutch Translation**: Improved translation for Dutch users.
|
983 |
+
- ⚪ **White Theme Styling**: Resolved styling issue with the white theme.
|
984 |
+
- 📜 **LaTeX Chat Screen Overflow**: Fixed screen overflow issue with LaTeX rendering.
|
985 |
+
- 🔒 **Security Patches**: Applied necessary security patches.
|
986 |
+
|
987 |
+
## [0.1.116] - 2024-03-31
|
988 |
+
|
989 |
+
### Added
|
990 |
+
|
991 |
+
- **🔄 Enhanced UI**: Model selector now conveniently located in the navbar, enabling seamless switching between multiple models during conversations.
|
992 |
+
- **🔍 Improved Model Selector**: Directly pull a model from the selector/Models now display detailed information for better understanding.
|
993 |
+
- **💬 Webhook Support**: Now compatible with Google Chat and Microsoft Teams.
|
994 |
+
- **🌐 Localization**: Korean translation (I18n) now available.
|
995 |
+
- **🌑 Dark Theme**: OLED dark theme introduced for reduced strain during prolonged usage.
|
996 |
+
- **🏷️ Tag Autocomplete**: Dropdown feature added for effortless chat tagging.
|
997 |
+
|
998 |
+
### Fixed
|
999 |
+
|
1000 |
+
- **🔽 Auto-Scrolling**: Addressed OpenAI auto-scrolling issue.
|
1001 |
+
- **🏷️ Tag Validation**: Implemented tag validation to prevent empty string tags.
|
1002 |
+
- **🚫 Model Whitelisting**: Resolved LiteLLM model whitelisting issue.
|
1003 |
+
- **✅ Spelling**: Corrected various spelling issues for improved readability.
|
1004 |
+
|
1005 |
+
## [0.1.115] - 2024-03-24
|
1006 |
+
|
1007 |
+
### Added
|
1008 |
+
|
1009 |
+
- **🔍 Custom Model Selector**: Easily find and select custom models with the new search filter feature.
|
1010 |
+
- **🛑 Cancel Model Download**: Added the ability to cancel model downloads.
|
1011 |
+
- **🎨 Image Generation ComfyUI**: Image generation now supports ComfyUI.
|
1012 |
+
- **🌟 Updated Light Theme**: Updated the light theme for a fresh look.
|
1013 |
+
- **🌍 Additional Language Support**: Now supporting Bulgarian, Italian, Portuguese, Japanese, and Dutch.
|
1014 |
+
|
1015 |
+
### Fixed
|
1016 |
+
|
1017 |
+
- **🔧 Fixed Broken Experimental GGUF Upload**: Resolved issues with experimental GGUF upload functionality.
|
1018 |
+
|
1019 |
+
### Changed
|
1020 |
+
|
1021 |
+
- **🔄 Vector Storage Reset Button**: Moved the reset vector storage button to document settings.
|
1022 |
+
|
1023 |
+
## [0.1.114] - 2024-03-20
|
1024 |
+
|
1025 |
+
### Added
|
1026 |
+
|
1027 |
+
- **🔗 Webhook Integration**: Now you can subscribe to new user sign-up events via webhook. Simply navigate to the admin panel > admin settings > webhook URL.
|
1028 |
+
- **🛡️ Enhanced Model Filtering**: Alongside Ollama, OpenAI proxy model whitelisting, we've added model filtering functionality for LiteLLM proxy.
|
1029 |
+
- **🌍 Expanded Language Support**: Spanish, Catalan, and Vietnamese languages are now available, with improvements made to others.
|
1030 |
+
|
1031 |
+
### Fixed
|
1032 |
+
|
1033 |
+
- **🔧 Input Field Spelling**: Resolved issue with spelling mistakes in input fields.
|
1034 |
+
- **🖊️ Light Mode Styling**: Fixed styling issue with light mode in document adding.
|
1035 |
+
|
1036 |
+
### Changed
|
1037 |
+
|
1038 |
+
- **🔄 Language Sorting**: Languages are now sorted alphabetically by their code for improved organization.
|
1039 |
+
|
1040 |
+
## [0.1.113] - 2024-03-18
|
1041 |
+
|
1042 |
+
### Added
|
1043 |
+
|
1044 |
+
- 🌍 **Localization**: You can now change the UI language in Settings > General. We support Ukrainian, German, Farsi (Persian), Traditional and Simplified Chinese and French translations. You can help us to translate the UI into your language! More info in our [CONTRIBUTION.md](https://github.com/open-webui/open-webui/blob/main/docs/CONTRIBUTING.md#-translations-and-internationalization).
|
1045 |
+
- 🎨 **System-wide Theme**: Introducing a new system-wide theme for enhanced visual experience.
|
1046 |
+
|
1047 |
+
### Fixed
|
1048 |
+
|
1049 |
+
- 🌑 **Dark Background on Select Fields**: Improved readability by adding a dark background to select fields, addressing issues on certain browsers/devices.
|
1050 |
+
- **Multiple OPENAI_API_BASE_URLS Issue**: Resolved issue where multiple base URLs caused conflicts when one wasn't functioning.
|
1051 |
+
- **RAG Encoding Issue**: Fixed encoding problem in RAG.
|
1052 |
+
- **npm Audit Fix**: Addressed npm audit findings.
|
1053 |
+
- **Reduced Scroll Threshold**: Improved auto-scroll experience by reducing the scroll threshold from 50px to 5px.
|
1054 |
+
|
1055 |
+
### Changed
|
1056 |
+
|
1057 |
+
- 🔄 **Sidebar UI Update**: Updated sidebar UI to feature a chat menu dropdown, replacing two icons for improved navigation.
|
1058 |
+
|
1059 |
+
## [0.1.112] - 2024-03-15
|
1060 |
+
|
1061 |
+
### Fixed
|
1062 |
+
|
1063 |
+
- 🗨️ Resolved chat malfunction after image generation.
|
1064 |
+
- 🎨 Fixed various RAG issues.
|
1065 |
+
- 🧪 Rectified experimental broken GGUF upload logic.
|
1066 |
+
|
1067 |
+
## [0.1.111] - 2024-03-10
|
1068 |
+
|
1069 |
+
### Added
|
1070 |
+
|
1071 |
+
- 🛡️ **Model Whitelisting**: Admins now have the ability to whitelist models for users with the 'user' role.
|
1072 |
+
- 🔄 **Update All Models**: Added a convenient button to update all models at once.
|
1073 |
+
- 📄 **Toggle PDF OCR**: Users can now toggle PDF OCR option for improved parsing performance.
|
1074 |
+
- 🎨 **DALL-E Integration**: Introduced DALL-E integration for image generation alongside automatic1111.
|
1075 |
+
- 🛠️ **RAG API Refactoring**: Refactored RAG logic and exposed its API, with additional documentation to follow.
|
1076 |
+
|
1077 |
+
### Fixed
|
1078 |
+
|
1079 |
+
- 🔒 **Max Token Settings**: Added max token settings for anthropic/claude-3-sonnet-20240229 (Issue #1094).
|
1080 |
+
- 🔧 **Misalignment Issue**: Corrected misalignment of Edit and Delete Icons when Chat Title is Empty (Issue #1104).
|
1081 |
+
- 🔄 **Context Loss Fix**: Resolved RAG losing context on model response regeneration with Groq models via API key (Issue #1105).
|
1082 |
+
- 📁 **File Handling Bug**: Addressed File Not Found Notification when Dropping a Conversation Element (Issue #1098).
|
1083 |
+
- 🖱️ **Dragged File Styling**: Fixed dragged file layover styling issue.
|
1084 |
+
|
1085 |
+
## [0.1.110] - 2024-03-06
|
1086 |
+
|
1087 |
+
### Added
|
1088 |
+
|
1089 |
+
- **🌐 Multiple OpenAI Servers Support**: Enjoy seamless integration with multiple OpenAI-compatible APIs, now supported natively.
|
1090 |
+
|
1091 |
+
### Fixed
|
1092 |
+
|
1093 |
+
- **🔍 OCR Issue**: Resolved PDF parsing issue caused by OCR malfunction.
|
1094 |
+
- **🚫 RAG Issue**: Fixed the RAG functionality, ensuring it operates smoothly.
|
1095 |
+
- **📄 "Add Docs" Model Button**: Addressed the non-functional behavior of the "Add Docs" model button.
|
1096 |
+
|
1097 |
+
## [0.1.109] - 2024-03-06
|
1098 |
+
|
1099 |
+
### Added
|
1100 |
+
|
1101 |
+
- **🔄 Multiple Ollama Servers Support**: Enjoy enhanced scalability and performance with support for multiple Ollama servers in a single WebUI. Load balancing features are now available, providing improved efficiency (#788, #278).
|
1102 |
+
- **🔧 Support for Claude 3 and Gemini**: Responding to user requests, we've expanded our toolset to include Claude 3 and Gemini, offering a wider range of functionalities within our platform (#1064).
|
1103 |
+
- **🔍 OCR Functionality for PDF Loader**: We've augmented our PDF loader with Optical Character Recognition (OCR) capabilities. Now, extract text from scanned documents and images within PDFs, broadening the scope of content processing (#1050).
|
1104 |
+
|
1105 |
+
### Fixed
|
1106 |
+
|
1107 |
+
- **🛠️ RAG Collection**: Implemented a dynamic mechanism to recreate RAG collections, ensuring users have up-to-date and accurate data (#1031).
|
1108 |
+
- **📝 User Agent Headers**: Fixed issue of RAG web requests being sent with empty user_agent headers, reducing rejections from certain websites. Realistic headers are now utilized for these requests (#1024).
|
1109 |
+
- **⏹️ Playground Cancel Functionality**: Introducing a new "Cancel" option for stopping Ollama generation in the Playground, enhancing user control and usability (#1006).
|
1110 |
+
- **🔤 Typographical Error in 'ASSISTANT' Field**: Corrected a typographical error in the 'ASSISTANT' field within the GGUF model upload template for accuracy and consistency (#1061).
|
1111 |
+
|
1112 |
+
### Changed
|
1113 |
+
|
1114 |
+
- **🔄 Refactored Message Deletion Logic**: Streamlined message deletion process for improved efficiency and user experience, simplifying interactions within the platform (#1004).
|
1115 |
+
- **⚠️ Deprecation of `OLLAMA_API_BASE_URL`**: Deprecated `OLLAMA_API_BASE_URL` environment variable; recommend using `OLLAMA_BASE_URL` instead. Refer to our documentation for further details.
|
1116 |
+
|
1117 |
+
## [0.1.108] - 2024-03-02
|
1118 |
+
|
1119 |
+
### Added
|
1120 |
+
|
1121 |
+
- **🎮 Playground Feature (Beta)**: Explore the full potential of the raw API through an intuitive UI with our new playground feature, accessible to admins. Simply click on the bottom name area of the sidebar to access it. The playground feature offers two modes text completion (notebook) and chat completion. As it's in beta, please report any issues you encounter.
|
1122 |
+
- **🛠️ Direct Database Download for Admins**: Admins can now download the database directly from the WebUI via the admin settings.
|
1123 |
+
- **🎨 Additional RAG Settings**: Customize your RAG process with the ability to edit the TOP K value. Navigate to Documents > Settings > General to make changes.
|
1124 |
+
- **🖥️ UI Improvements**: Tooltips now available in the input area and sidebar handle. More tooltips will be added across other parts of the UI.
|
1125 |
+
|
1126 |
+
### Fixed
|
1127 |
+
|
1128 |
+
- Resolved input autofocus issue on mobile when the sidebar is open, making it easier to use.
|
1129 |
+
- Corrected numbered list display issue in Safari (#963).
|
1130 |
+
- Restricted user ability to delete chats without proper permissions (#993).
|
1131 |
+
|
1132 |
+
### Changed
|
1133 |
+
|
1134 |
+
- **Simplified Ollama Settings**: Ollama settings now don't require the `/api` suffix. You can now utilize the Ollama base URL directly, e.g., `http://localhost:11434`. Also, an `OLLAMA_BASE_URL` environment variable has been added.
|
1135 |
+
- **Database Renaming**: Starting from this release, `ollama.db` will be automatically renamed to `webui.db`.
|
1136 |
+
|
1137 |
+
## [0.1.107] - 2024-03-01
|
1138 |
+
|
1139 |
+
### Added
|
1140 |
+
|
1141 |
+
- **🚀 Makefile and LLM Update Script**: Included Makefile and a script for LLM updates in the repository.
|
1142 |
+
|
1143 |
+
### Fixed
|
1144 |
+
|
1145 |
+
- Corrected issue where links in the settings modal didn't appear clickable (#960).
|
1146 |
+
- Fixed problem with web UI port not taking effect due to incorrect environment variable name in run-compose.sh (#996).
|
1147 |
+
- Enhanced user experience by displaying chat in browser title and enabling automatic scrolling to the bottom (#992).
|
1148 |
+
|
1149 |
+
### Changed
|
1150 |
+
|
1151 |
+
- Upgraded toast library from `svelte-french-toast` to `svelte-sonner` for a more polished UI.
|
1152 |
+
- Enhanced accessibility with the addition of dark mode on the authentication page.
|
1153 |
+
|
1154 |
+
## [0.1.106] - 2024-02-27
|
1155 |
+
|
1156 |
+
### Added
|
1157 |
+
|
1158 |
+
- **🎯 Auto-focus Feature**: The input area now automatically focuses when initiating or opening a chat conversation.
|
1159 |
+
|
1160 |
+
### Fixed
|
1161 |
+
|
1162 |
+
- Corrected typo from "HuggingFace" to "Hugging Face" (Issue #924).
|
1163 |
+
- Resolved bug causing errors in chat completion API calls to OpenAI due to missing "num_ctx" parameter (Issue #927).
|
1164 |
+
- Fixed issues preventing text editing, selection, and cursor retention in the input field (Issue #940).
|
1165 |
+
- Fixed a bug where defining an OpenAI-compatible API server using 'OPENAI_API_BASE_URL' containing 'openai' string resulted in hiding models not containing 'gpt' string from the model menu. (Issue #930)
|
1166 |
+
|
1167 |
+
## [0.1.105] - 2024-02-25
|
1168 |
+
|
1169 |
+
### Added
|
1170 |
+
|
1171 |
+
- **📄 Document Selection**: Now you can select and delete multiple documents at once for easier management.
|
1172 |
+
|
1173 |
+
### Changed
|
1174 |
+
|
1175 |
+
- **🏷️ Document Pre-tagging**: Simply click the "+" button at the top, enter tag names in the popup window, or select from a list of existing tags. Then, upload files with the added tags for streamlined organization.
|
1176 |
+
|
1177 |
+
## [0.1.104] - 2024-02-25
|
1178 |
+
|
1179 |
+
### Added
|
1180 |
+
|
1181 |
+
- **🔄 Check for Updates**: Keep your system current by checking for updates conveniently located in Settings > About.
|
1182 |
+
- **🗑️ Automatic Tag Deletion**: Unused tags on the sidebar will now be deleted automatically with just a click.
|
1183 |
+
|
1184 |
+
### Changed
|
1185 |
+
|
1186 |
+
- **🎨 Modernized Styling**: Enjoy a refreshed look with updated styling for a more contemporary experience.
|
1187 |
+
|
1188 |
+
## [0.1.103] - 2024-02-25
|
1189 |
+
|
1190 |
+
### Added
|
1191 |
+
|
1192 |
+
- **🔗 Built-in LiteLLM Proxy**: Now includes LiteLLM proxy within Open WebUI for enhanced functionality.
|
1193 |
+
|
1194 |
+
- Easily integrate existing LiteLLM configurations using `-v /path/to/config.yaml:/app/backend/data/litellm/config.yaml` flag.
|
1195 |
+
- When utilizing Docker container to run Open WebUI, ensure connections to localhost use `host.docker.internal`.
|
1196 |
+
|
1197 |
+
- **🖼️ Image Generation Enhancements**: Introducing Advanced Settings with Image Preview Feature.
|
1198 |
+
- Customize image generation by setting the number of steps; defaults to A1111 value.
|
1199 |
+
|
1200 |
+
### Fixed
|
1201 |
+
|
1202 |
+
- Resolved issue with RAG scan halting document loading upon encountering unsupported MIME types or exceptions (Issue #866).
|
1203 |
+
|
1204 |
+
### Changed
|
1205 |
+
|
1206 |
+
- Ollama is no longer required to run Open WebUI.
|
1207 |
+
- Access our comprehensive documentation at [Open WebUI Documentation](https://docs.openwebui.com/).
|
1208 |
+
|
1209 |
+
## [0.1.102] - 2024-02-22
|
1210 |
+
|
1211 |
+
### Added
|
1212 |
+
|
1213 |
+
- **🖼️ Image Generation**: Generate Images using the AUTOMATIC1111/stable-diffusion-webui API. You can set this up in Settings > Images.
|
1214 |
+
- **📝 Change title generation prompt**: Change the prompt used to generate titles for your chats. You can set this up in the Settings > Interface.
|
1215 |
+
- **🤖 Change embedding model**: Change the embedding model used to generate embeddings for your chats in the Dockerfile. Use any sentence transformer model from huggingface.co.
|
1216 |
+
- **📢 CHANGELOG.md/Popup**: This popup will show you the latest changes.
|
1217 |
+
|
1218 |
+
## [0.1.101] - 2024-02-22
|
1219 |
+
|
1220 |
+
### Fixed
|
1221 |
+
|
1222 |
+
- LaTex output formatting issue (#828)
|
1223 |
+
|
1224 |
+
### Changed
|
1225 |
+
|
1226 |
+
- Instead of having the previous 1.0.0-alpha.101, we switched to semantic versioning as a way to respect global conventions.
|
CODE_OF_CONDUCT.md
ADDED
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Contributor Covenant Code of Conduct
|
2 |
+
|
3 |
+
## Our Pledge
|
4 |
+
|
5 |
+
We as members, contributors, and leaders pledge to make participation in our
|
6 |
+
community a harassment-free experience for everyone, regardless of age, body
|
7 |
+
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
8 |
+
identity and expression, level of experience, education, socio-economic status,
|
9 |
+
nationality, personal appearance, race, religion, or sexual identity
|
10 |
+
and orientation.
|
11 |
+
|
12 |
+
We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
|
13 |
+
|
14 |
+
## Our Standards
|
15 |
+
|
16 |
+
Examples of behavior that contribute to a positive environment for our community include:
|
17 |
+
|
18 |
+
- Demonstrating empathy and kindness toward other people
|
19 |
+
- Being respectful of differing opinions, viewpoints, and experiences
|
20 |
+
- Giving and gracefully accepting constructive feedback
|
21 |
+
- Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
|
22 |
+
- Focusing on what is best not just for us as individuals, but for the overall community
|
23 |
+
|
24 |
+
Examples of unacceptable behavior include:
|
25 |
+
|
26 |
+
- The use of sexualized language or imagery, and sexual attention or advances of any kind
|
27 |
+
- Trolling, insulting or derogatory comments, and personal or political attacks
|
28 |
+
- Public or private harassment
|
29 |
+
- Publishing others' private information, such as a physical or email address, without their explicit permission
|
30 |
+
- **Spamming of any kind**
|
31 |
+
- Aggressive sales tactics targeting our community members are strictly prohibited. You can mention your product if it's relevant to the discussion, but under no circumstances should you push it forcefully
|
32 |
+
- Other conduct which could reasonably be considered inappropriate in a professional setting
|
33 |
+
|
34 |
+
## Enforcement Responsibilities
|
35 |
+
|
36 |
+
Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
|
37 |
+
|
38 |
+
## Scope
|
39 |
+
|
40 |
+
This Code of Conduct applies within all community spaces and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
|
41 |
+
|
42 |
+
## Enforcement
|
43 |
+
|
44 |
+
Instances of abusive, harassing, spamming, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at hello@openwebui.com. All complaints will be reviewed and investigated promptly and fairly.
|
45 |
+
|
46 |
+
All community leaders are obligated to respect the privacy and security of the reporter of any incident.
|
47 |
+
|
48 |
+
## Enforcement Guidelines
|
49 |
+
|
50 |
+
Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
|
51 |
+
|
52 |
+
### 1. Temporary Ban
|
53 |
+
|
54 |
+
**Community Impact**: Any violation of community standards, including but not limited to inappropriate language, unprofessional behavior, harassment, or spamming.
|
55 |
+
|
56 |
+
**Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
|
57 |
+
|
58 |
+
### 2. Permanent Ban
|
59 |
+
|
60 |
+
**Community Impact**: Repeated or severe violations of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
|
61 |
+
|
62 |
+
**Consequence**: A permanent ban from any sort of public interaction within the community.
|
63 |
+
|
64 |
+
## Attribution
|
65 |
+
|
66 |
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
67 |
+
version 2.0, available at
|
68 |
+
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
69 |
+
|
70 |
+
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
71 |
+
enforcement ladder](https://github.com/mozilla/diversity).
|
72 |
+
|
73 |
+
[homepage]: https://www.contributor-covenant.org
|
74 |
+
|
75 |
+
For answers to common questions about this code of conduct, see the FAQ at
|
76 |
+
https://www.contributor-covenant.org/faq. Translations are available at
|
77 |
+
https://www.contributor-covenant.org/translations.
|
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,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# syntax=docker/dockerfile:1
|
2 |
+
# Initialize device type args
|
3 |
+
# use build args in the docker build command with --build-arg="BUILDARG=true"
|
4 |
+
ARG USE_CUDA=false
|
5 |
+
ARG USE_OLLAMA=false
|
6 |
+
# Tested with cu117 for CUDA 11 and cu121 for CUDA 12 (default)
|
7 |
+
ARG USE_CUDA_VER=cu121
|
8 |
+
# any sentence transformer model; models to use can be found at https://huggingface.co/models?library=sentence-transformers
|
9 |
+
# Leaderboard: https://huggingface.co/spaces/mteb/leaderboard
|
10 |
+
# for better performance and multilangauge support use "intfloat/multilingual-e5-large" (~2.5GB) or "intfloat/multilingual-e5-base" (~1.5GB)
|
11 |
+
# IMPORTANT: If you change the embedding model (sentence-transformers/all-MiniLM-L6-v2) and vice versa, you aren't able to use RAG Chat with your previous documents loaded in the WebUI! You need to re-embed them.
|
12 |
+
ARG USE_EMBEDDING_MODEL=sentence-transformers/all-MiniLM-L6-v2
|
13 |
+
ARG USE_RERANKING_MODEL=""
|
14 |
+
|
15 |
+
# Tiktoken encoding name; models to use can be found at https://huggingface.co/models?library=tiktoken
|
16 |
+
ARG USE_TIKTOKEN_ENCODING_NAME="cl100k_base"
|
17 |
+
|
18 |
+
ARG BUILD_HASH=dev-build
|
19 |
+
# Override at your own risk - non-root configurations are untested
|
20 |
+
ARG UID=0
|
21 |
+
ARG GID=0
|
22 |
+
|
23 |
+
######## WebUI frontend ########
|
24 |
+
FROM --platform=$BUILDPLATFORM node:22-alpine3.20 AS build
|
25 |
+
ARG BUILD_HASH
|
26 |
+
|
27 |
+
WORKDIR /app
|
28 |
+
|
29 |
+
COPY package.json package-lock.json ./
|
30 |
+
RUN npm ci
|
31 |
+
|
32 |
+
COPY . .
|
33 |
+
ENV APP_BUILD_HASH=${BUILD_HASH}
|
34 |
+
RUN npm run build
|
35 |
+
|
36 |
+
######## WebUI backend ########
|
37 |
+
FROM python:3.11-slim-bookworm AS base
|
38 |
+
|
39 |
+
# Use args
|
40 |
+
ARG USE_CUDA
|
41 |
+
ARG USE_OLLAMA
|
42 |
+
ARG USE_CUDA_VER
|
43 |
+
ARG USE_EMBEDDING_MODEL
|
44 |
+
ARG USE_RERANKING_MODEL
|
45 |
+
ARG UID
|
46 |
+
ARG GID
|
47 |
+
|
48 |
+
## Basis ##
|
49 |
+
ENV ENV=prod \
|
50 |
+
PORT=8080 \
|
51 |
+
# pass build args to the build
|
52 |
+
USE_OLLAMA_DOCKER=${USE_OLLAMA} \
|
53 |
+
USE_CUDA_DOCKER=${USE_CUDA} \
|
54 |
+
USE_CUDA_DOCKER_VER=${USE_CUDA_VER} \
|
55 |
+
USE_EMBEDDING_MODEL_DOCKER=${USE_EMBEDDING_MODEL} \
|
56 |
+
USE_RERANKING_MODEL_DOCKER=${USE_RERANKING_MODEL}
|
57 |
+
|
58 |
+
## Basis URL Config ##
|
59 |
+
ENV OLLAMA_BASE_URL="/ollama" \
|
60 |
+
OPENAI_API_BASE_URL=""
|
61 |
+
|
62 |
+
## API Key and Security Config ##
|
63 |
+
ENV OPENAI_API_KEY="" \
|
64 |
+
WEBUI_SECRET_KEY="" \
|
65 |
+
SCARF_NO_ANALYTICS=true \
|
66 |
+
DO_NOT_TRACK=true \
|
67 |
+
ANONYMIZED_TELEMETRY=false
|
68 |
+
|
69 |
+
#### Other models #########################################################
|
70 |
+
## whisper TTS model settings ##
|
71 |
+
ENV WHISPER_MODEL="base" \
|
72 |
+
WHISPER_MODEL_DIR="/app/backend/data/cache/whisper/models"
|
73 |
+
|
74 |
+
## RAG Embedding model settings ##
|
75 |
+
ENV RAG_EMBEDDING_MODEL="$USE_EMBEDDING_MODEL_DOCKER" \
|
76 |
+
RAG_RERANKING_MODEL="$USE_RERANKING_MODEL_DOCKER" \
|
77 |
+
SENTENCE_TRANSFORMERS_HOME="/app/backend/data/cache/embedding/models"
|
78 |
+
|
79 |
+
## Tiktoken model settings ##
|
80 |
+
ENV TIKTOKEN_ENCODING_NAME="cl100k_base" \
|
81 |
+
TIKTOKEN_CACHE_DIR="/app/backend/data/cache/tiktoken"
|
82 |
+
|
83 |
+
## Hugging Face download cache ##
|
84 |
+
ENV HF_HOME="/app/backend/data/cache/embedding/models"
|
85 |
+
|
86 |
+
## Torch Extensions ##
|
87 |
+
# ENV TORCH_EXTENSIONS_DIR="/.cache/torch_extensions"
|
88 |
+
|
89 |
+
#### Other models ##########################################################
|
90 |
+
|
91 |
+
WORKDIR /app/backend
|
92 |
+
|
93 |
+
ENV HOME=/root
|
94 |
+
# Create user and group if not root
|
95 |
+
RUN if [ $UID -ne 0 ]; then \
|
96 |
+
if [ $GID -ne 0 ]; then \
|
97 |
+
addgroup --gid $GID app; \
|
98 |
+
fi; \
|
99 |
+
adduser --uid $UID --gid $GID --home $HOME --disabled-password --no-create-home app; \
|
100 |
+
fi
|
101 |
+
|
102 |
+
RUN mkdir -p $HOME/.cache/chroma
|
103 |
+
RUN echo -n 00000000-0000-0000-0000-000000000000 > $HOME/.cache/chroma/telemetry_user_id
|
104 |
+
|
105 |
+
# Make sure the user has access to the app and root directory
|
106 |
+
RUN chown -R $UID:$GID /app $HOME
|
107 |
+
|
108 |
+
RUN if [ "$USE_OLLAMA" = "true" ]; then \
|
109 |
+
apt-get update && \
|
110 |
+
# Install pandoc and netcat
|
111 |
+
apt-get install -y --no-install-recommends git build-essential pandoc netcat-openbsd curl && \
|
112 |
+
apt-get install -y --no-install-recommends gcc python3-dev && \
|
113 |
+
# for RAG OCR
|
114 |
+
apt-get install -y --no-install-recommends ffmpeg libsm6 libxext6 && \
|
115 |
+
# install helper tools
|
116 |
+
apt-get install -y --no-install-recommends curl jq && \
|
117 |
+
# install ollama
|
118 |
+
curl -fsSL https://ollama.com/install.sh | sh && \
|
119 |
+
# cleanup
|
120 |
+
rm -rf /var/lib/apt/lists/*; \
|
121 |
+
else \
|
122 |
+
apt-get update && \
|
123 |
+
# Install pandoc, netcat and gcc
|
124 |
+
apt-get install -y --no-install-recommends git build-essential pandoc gcc netcat-openbsd curl jq && \
|
125 |
+
apt-get install -y --no-install-recommends gcc python3-dev && \
|
126 |
+
# for RAG OCR
|
127 |
+
apt-get install -y --no-install-recommends ffmpeg libsm6 libxext6 && \
|
128 |
+
# cleanup
|
129 |
+
rm -rf /var/lib/apt/lists/*; \
|
130 |
+
fi
|
131 |
+
|
132 |
+
# install python dependencies
|
133 |
+
COPY --chown=$UID:$GID ./backend/requirements.txt ./requirements.txt
|
134 |
+
|
135 |
+
RUN pip3 install uv && \
|
136 |
+
if [ "$USE_CUDA" = "true" ]; then \
|
137 |
+
# If you use CUDA the whisper and embedding model will be downloaded on first use
|
138 |
+
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/$USE_CUDA_DOCKER_VER --no-cache-dir && \
|
139 |
+
uv pip install --system -r requirements.txt --no-cache-dir && \
|
140 |
+
python -c "import os; from sentence_transformers import SentenceTransformer; SentenceTransformer(os.environ['RAG_EMBEDDING_MODEL'], device='cpu')" && \
|
141 |
+
python -c "import os; from faster_whisper import WhisperModel; WhisperModel(os.environ['WHISPER_MODEL'], device='cpu', compute_type='int8', download_root=os.environ['WHISPER_MODEL_DIR'])"; \
|
142 |
+
python -c "import os; import tiktoken; tiktoken.get_encoding(os.environ['TIKTOKEN_ENCODING_NAME'])"; \
|
143 |
+
else \
|
144 |
+
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu --no-cache-dir && \
|
145 |
+
uv pip install --system -r requirements.txt --no-cache-dir && \
|
146 |
+
python -c "import os; from sentence_transformers import SentenceTransformer; SentenceTransformer(os.environ['RAG_EMBEDDING_MODEL'], device='cpu')" && \
|
147 |
+
python -c "import os; from faster_whisper import WhisperModel; WhisperModel(os.environ['WHISPER_MODEL'], device='cpu', compute_type='int8', download_root=os.environ['WHISPER_MODEL_DIR'])"; \
|
148 |
+
python -c "import os; import tiktoken; tiktoken.get_encoding(os.environ['TIKTOKEN_ENCODING_NAME'])"; \
|
149 |
+
fi; \
|
150 |
+
chown -R $UID:$GID /app/backend/data/
|
151 |
+
|
152 |
+
|
153 |
+
|
154 |
+
# copy embedding weight from build
|
155 |
+
# RUN mkdir -p /root/.cache/chroma/onnx_models/all-MiniLM-L6-v2
|
156 |
+
# COPY --from=build /app/onnx /root/.cache/chroma/onnx_models/all-MiniLM-L6-v2/onnx
|
157 |
+
|
158 |
+
# copy built frontend files
|
159 |
+
COPY --chown=$UID:$GID --from=build /app/build /app/build
|
160 |
+
COPY --chown=$UID:$GID --from=build /app/CHANGELOG.md /app/CHANGELOG.md
|
161 |
+
COPY --chown=$UID:$GID --from=build /app/package.json /app/package.json
|
162 |
+
|
163 |
+
# copy backend files
|
164 |
+
COPY --chown=$UID:$GID ./backend .
|
165 |
+
|
166 |
+
EXPOSE 8080
|
167 |
+
|
168 |
+
HEALTHCHECK CMD curl --silent --fail http://localhost:${PORT:-8080}/health | jq -ne 'input.status == true' || exit 1
|
169 |
+
|
170 |
+
USER $UID:$GID
|
171 |
+
|
172 |
+
ARG BUILD_HASH
|
173 |
+
ENV WEBUI_BUILD_VERSION=${BUILD_HASH}
|
174 |
+
ENV DOCKER=true
|
175 |
+
|
176 |
+
CMD [ "bash", "start.sh"]
|
INSTALLATION.md
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
### Installing Both Ollama and Open WebUI Using Kustomize
|
2 |
+
|
3 |
+
For cpu-only pod
|
4 |
+
|
5 |
+
```bash
|
6 |
+
kubectl apply -f ./kubernetes/manifest/base
|
7 |
+
```
|
8 |
+
|
9 |
+
For gpu-enabled pod
|
10 |
+
|
11 |
+
```bash
|
12 |
+
kubectl apply -k ./kubernetes/manifest
|
13 |
+
```
|
14 |
+
|
15 |
+
### Installing Both Ollama and Open WebUI Using Helm
|
16 |
+
|
17 |
+
Package Helm file first
|
18 |
+
|
19 |
+
```bash
|
20 |
+
helm package ./kubernetes/helm/
|
21 |
+
```
|
22 |
+
|
23 |
+
For cpu-only pod
|
24 |
+
|
25 |
+
```bash
|
26 |
+
helm install ollama-webui ./ollama-webui-*.tgz
|
27 |
+
```
|
28 |
+
|
29 |
+
For gpu-enabled pod
|
30 |
+
|
31 |
+
```bash
|
32 |
+
helm install ollama-webui ./ollama-webui-*.tgz --set ollama.resources.limits.nvidia.com/gpu="1"
|
33 |
+
```
|
34 |
+
|
35 |
+
Check the `kubernetes/helm/values.yaml` file to know which parameters are available for customization
|
LICENSE
ADDED
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
MIT License
|
2 |
+
|
3 |
+
Copyright (c) 2023 Timothy Jaeryang Baek
|
4 |
+
|
5 |
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
6 |
+
of this software and associated documentation files (the "Software"), to deal
|
7 |
+
in the Software without restriction, including without limitation the rights
|
8 |
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
9 |
+
copies of the Software, and to permit persons to whom the Software is
|
10 |
+
furnished to do so, subject to the following conditions:
|
11 |
+
|
12 |
+
The above copyright notice and this permission notice shall be included in all
|
13 |
+
copies or substantial portions of the Software.
|
14 |
+
|
15 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
16 |
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
17 |
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
18 |
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
19 |
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
20 |
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
21 |
+
SOFTWARE.
|
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,219 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
---
|
2 |
+
title: Open WebUI
|
3 |
+
emoji: 🐳
|
4 |
+
colorFrom: purple
|
5 |
+
colorTo: gray
|
6 |
+
sdk: docker
|
7 |
+
app_port: 8080
|
8 |
+
---
|
9 |
+
# Open WebUI 👋
|
10 |
+
|
11 |
+
![GitHub stars](https://img.shields.io/github/stars/open-webui/open-webui?style=social)
|
12 |
+
![GitHub forks](https://img.shields.io/github/forks/open-webui/open-webui?style=social)
|
13 |
+
![GitHub watchers](https://img.shields.io/github/watchers/open-webui/open-webui?style=social)
|
14 |
+
![GitHub repo size](https://img.shields.io/github/repo-size/open-webui/open-webui)
|
15 |
+
![GitHub language count](https://img.shields.io/github/languages/count/open-webui/open-webui)
|
16 |
+
![GitHub top language](https://img.shields.io/github/languages/top/open-webui/open-webui)
|
17 |
+
![GitHub last commit](https://img.shields.io/github/last-commit/open-webui/open-webui?color=red)
|
18 |
+
![Hits](https://hits.seeyoufarm.com/api/count/incr/badge.svg?url=https%3A%2F%2Fgithub.com%2Follama-webui%2Follama-wbui&count_bg=%2379C83D&title_bg=%23555555&icon=&icon_color=%23E7E7E7&title=hits&edge_flat=false)
|
19 |
+
[![Discord](https://img.shields.io/badge/Discord-Open_WebUI-blue?logo=discord&logoColor=white)](https://discord.gg/5rJgQTnV4s)
|
20 |
+
[![](https://img.shields.io/static/v1?label=Sponsor&message=%E2%9D%A4&logo=GitHub&color=%23fe8e86)](https://github.com/sponsors/tjbck)
|
21 |
+
|
22 |
+
Open WebUI is an [extensible](https://github.com/open-webui/pipelines), feature-rich, and user-friendly self-hosted WebUI designed to operate entirely offline. It supports various LLM runners, including Ollama and OpenAI-compatible APIs. For more information, be sure to check out our [Open WebUI Documentation](https://docs.openwebui.com/).
|
23 |
+
|
24 |
+
![Open WebUI Demo](./demo.gif)
|
25 |
+
|
26 |
+
## Key Features of Open WebUI ⭐
|
27 |
+
|
28 |
+
- 🚀 **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.
|
29 |
+
|
30 |
+
- 🤝 **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**.
|
31 |
+
|
32 |
+
- 🧩 **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.
|
33 |
+
|
34 |
+
- 📱 **Responsive Design**: Enjoy a seamless experience across Desktop PC, Laptop, and Mobile devices.
|
35 |
+
|
36 |
+
- 📱 **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.
|
37 |
+
|
38 |
+
- ✒️🔢 **Full Markdown and LaTeX Support**: Elevate your LLM experience with comprehensive Markdown and LaTeX capabilities for enriched interaction.
|
39 |
+
|
40 |
+
- 🎤📹 **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.
|
41 |
+
|
42 |
+
- 🛠️ **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.
|
43 |
+
|
44 |
+
- 🐍 **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.
|
45 |
+
|
46 |
+
- 📚 **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.
|
47 |
+
|
48 |
+
- 🔍 **Web Search for RAG**: Perform web searches using providers like `SearXNG`, `Google PSE`, `Brave Search`, `serpstack`, `serper`, `Serply`, `DuckDuckGo`, `TavilySearch` and `SearchApi` and inject the results directly into your chat experience.
|
49 |
+
|
50 |
+
- 🌐 **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.
|
51 |
+
|
52 |
+
- 🎨 **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.
|
53 |
+
|
54 |
+
- ⚙️ **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.
|
55 |
+
|
56 |
+
- 🔐 **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.
|
57 |
+
|
58 |
+
- 🌐🌍 **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!
|
59 |
+
|
60 |
+
- 🌟 **Continuous Updates**: We are committed to improving Open WebUI with regular updates, fixes, and new features.
|
61 |
+
|
62 |
+
Want to learn more about Open WebUI's features? Check out our [Open WebUI documentation](https://docs.openwebui.com/features) for a comprehensive overview!
|
63 |
+
|
64 |
+
## 🔗 Also Check Out Open WebUI Community!
|
65 |
+
|
66 |
+
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! 🚀
|
67 |
+
|
68 |
+
## How to Install 🚀
|
69 |
+
|
70 |
+
### Installation via Python pip 🐍
|
71 |
+
|
72 |
+
Open WebUI can be installed using pip, the Python package installer. Before proceeding, ensure you're using **Python 3.11** to avoid compatibility issues.
|
73 |
+
|
74 |
+
1. **Install Open WebUI**:
|
75 |
+
Open your terminal and run the following command to install Open WebUI:
|
76 |
+
|
77 |
+
```bash
|
78 |
+
pip install open-webui
|
79 |
+
```
|
80 |
+
|
81 |
+
2. **Running Open WebUI**:
|
82 |
+
After installation, you can start Open WebUI by executing:
|
83 |
+
|
84 |
+
```bash
|
85 |
+
open-webui serve
|
86 |
+
```
|
87 |
+
|
88 |
+
This will start the Open WebUI server, which you can access at [http://localhost:8080](http://localhost:8080)
|
89 |
+
|
90 |
+
### Quick Start with Docker 🐳
|
91 |
+
|
92 |
+
> [!NOTE]
|
93 |
+
> 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.
|
94 |
+
|
95 |
+
> [!WARNING]
|
96 |
+
> 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.
|
97 |
+
|
98 |
+
> [!TIP]
|
99 |
+
> 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.
|
100 |
+
|
101 |
+
### Installation with Default Configuration
|
102 |
+
|
103 |
+
- **If Ollama is on your computer**, use this command:
|
104 |
+
|
105 |
+
```bash
|
106 |
+
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
|
107 |
+
```
|
108 |
+
|
109 |
+
- **If Ollama is on a Different Server**, use this command:
|
110 |
+
|
111 |
+
To connect to Ollama on another server, change the `OLLAMA_BASE_URL` to the server's URL:
|
112 |
+
|
113 |
+
```bash
|
114 |
+
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
|
115 |
+
```
|
116 |
+
|
117 |
+
- **To run Open WebUI with Nvidia GPU support**, use this command:
|
118 |
+
|
119 |
+
```bash
|
120 |
+
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
|
121 |
+
```
|
122 |
+
|
123 |
+
### Installation for OpenAI API Usage Only
|
124 |
+
|
125 |
+
- **If you're only using OpenAI API**, use this command:
|
126 |
+
|
127 |
+
```bash
|
128 |
+
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
|
129 |
+
```
|
130 |
+
|
131 |
+
### Installing Open WebUI with Bundled Ollama Support
|
132 |
+
|
133 |
+
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:
|
134 |
+
|
135 |
+
- **With GPU Support**:
|
136 |
+
Utilize GPU resources by running the following command:
|
137 |
+
|
138 |
+
```bash
|
139 |
+
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
|
140 |
+
```
|
141 |
+
|
142 |
+
- **For CPU Only**:
|
143 |
+
If you're not using a GPU, use this command instead:
|
144 |
+
|
145 |
+
```bash
|
146 |
+
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
|
147 |
+
```
|
148 |
+
|
149 |
+
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.
|
150 |
+
|
151 |
+
After installation, you can access Open WebUI at [http://localhost:3000](http://localhost:3000). Enjoy! 😄
|
152 |
+
|
153 |
+
### Other Installation Methods
|
154 |
+
|
155 |
+
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.
|
156 |
+
|
157 |
+
### Troubleshooting
|
158 |
+
|
159 |
+
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).
|
160 |
+
|
161 |
+
#### Open WebUI: Server Connection Error
|
162 |
+
|
163 |
+
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`.
|
164 |
+
|
165 |
+
**Example Docker Command**:
|
166 |
+
|
167 |
+
```bash
|
168 |
+
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
|
169 |
+
```
|
170 |
+
|
171 |
+
### Keeping Your Docker Installation Up-to-Date
|
172 |
+
|
173 |
+
In case you want to update your local Docker installation to the latest version, you can do it with [Watchtower](https://containrrr.dev/watchtower/):
|
174 |
+
|
175 |
+
```bash
|
176 |
+
docker run --rm --volume /var/run/docker.sock:/var/run/docker.sock containrrr/watchtower --run-once open-webui
|
177 |
+
```
|
178 |
+
|
179 |
+
In the last part of the command, replace `open-webui` with your container name if it is different.
|
180 |
+
|
181 |
+
Check our Migration Guide available in our [Open WebUI Documentation](https://docs.openwebui.com/tutorials/migration/).
|
182 |
+
|
183 |
+
### Using the Dev Branch 🌙
|
184 |
+
|
185 |
+
> [!WARNING]
|
186 |
+
> The `:dev` branch contains the latest unstable features and changes. Use it at your own risk as it may have bugs or incomplete features.
|
187 |
+
|
188 |
+
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:
|
189 |
+
|
190 |
+
```bash
|
191 |
+
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
|
192 |
+
```
|
193 |
+
|
194 |
+
## What's Next? 🌟
|
195 |
+
|
196 |
+
Discover upcoming features on our roadmap in the [Open WebUI Documentation](https://docs.openwebui.com/roadmap/).
|
197 |
+
|
198 |
+
## License 📜
|
199 |
+
|
200 |
+
This project is licensed under the [MIT License](LICENSE) - see the [LICENSE](LICENSE) file for details. 📄
|
201 |
+
|
202 |
+
## Support 💬
|
203 |
+
|
204 |
+
If you have any questions, suggestions, or need assistance, please open an issue or join our
|
205 |
+
[Open WebUI Discord community](https://discord.gg/5rJgQTnV4s) to connect with us! 🤝
|
206 |
+
|
207 |
+
## Star History
|
208 |
+
|
209 |
+
<a href="https://star-history.com/#open-webui/open-webui&Date">
|
210 |
+
<picture>
|
211 |
+
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date&theme=dark" />
|
212 |
+
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
213 |
+
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
|
214 |
+
</picture>
|
215 |
+
</a>
|
216 |
+
|
217 |
+
---
|
218 |
+
|
219 |
+
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,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import base64
|
2 |
+
import os
|
3 |
+
import random
|
4 |
+
from pathlib import Path
|
5 |
+
|
6 |
+
import typer
|
7 |
+
import uvicorn
|
8 |
+
|
9 |
+
app = typer.Typer()
|
10 |
+
|
11 |
+
KEY_FILE = Path.cwd() / ".webui_secret_key"
|
12 |
+
|
13 |
+
|
14 |
+
@app.command()
|
15 |
+
def serve(
|
16 |
+
host: str = "0.0.0.0",
|
17 |
+
port: int = 8080,
|
18 |
+
):
|
19 |
+
os.environ["FROM_INIT_PY"] = "true"
|
20 |
+
if os.getenv("WEBUI_SECRET_KEY") is None:
|
21 |
+
typer.echo(
|
22 |
+
"Loading WEBUI_SECRET_KEY from file, not provided as an environment variable."
|
23 |
+
)
|
24 |
+
if not KEY_FILE.exists():
|
25 |
+
typer.echo(f"Generating a new secret key and saving it to {KEY_FILE}")
|
26 |
+
KEY_FILE.write_bytes(base64.b64encode(random.randbytes(12)))
|
27 |
+
typer.echo(f"Loading WEBUI_SECRET_KEY from {KEY_FILE}")
|
28 |
+
os.environ["WEBUI_SECRET_KEY"] = KEY_FILE.read_text()
|
29 |
+
|
30 |
+
if os.getenv("USE_CUDA_DOCKER", "false") == "true":
|
31 |
+
typer.echo(
|
32 |
+
"CUDA is enabled, appending LD_LIBRARY_PATH to include torch/cudnn & cublas libraries."
|
33 |
+
)
|
34 |
+
LD_LIBRARY_PATH = os.getenv("LD_LIBRARY_PATH", "").split(":")
|
35 |
+
os.environ["LD_LIBRARY_PATH"] = ":".join(
|
36 |
+
LD_LIBRARY_PATH
|
37 |
+
+ [
|
38 |
+
"/usr/local/lib/python3.11/site-packages/torch/lib",
|
39 |
+
"/usr/local/lib/python3.11/site-packages/nvidia/cudnn/lib",
|
40 |
+
]
|
41 |
+
)
|
42 |
+
try:
|
43 |
+
import torch
|
44 |
+
|
45 |
+
assert torch.cuda.is_available(), "CUDA not available"
|
46 |
+
typer.echo("CUDA seems to be working")
|
47 |
+
except Exception as e:
|
48 |
+
typer.echo(
|
49 |
+
"Error when testing CUDA but USE_CUDA_DOCKER is true. "
|
50 |
+
"Resetting USE_CUDA_DOCKER to false and removing "
|
51 |
+
f"LD_LIBRARY_PATH modifications: {e}"
|
52 |
+
)
|
53 |
+
os.environ["USE_CUDA_DOCKER"] = "false"
|
54 |
+
os.environ["LD_LIBRARY_PATH"] = ":".join(LD_LIBRARY_PATH)
|
55 |
+
|
56 |
+
import open_webui.main # we need set environment variables before importing main
|
57 |
+
|
58 |
+
uvicorn.run(open_webui.main.app, host=host, port=port, forwarded_allow_ips="*")
|
59 |
+
|
60 |
+
|
61 |
+
@app.command()
|
62 |
+
def dev(
|
63 |
+
host: str = "0.0.0.0",
|
64 |
+
port: int = 8080,
|
65 |
+
reload: bool = True,
|
66 |
+
):
|
67 |
+
uvicorn.run(
|
68 |
+
"open_webui.main:app",
|
69 |
+
host=host,
|
70 |
+
port=port,
|
71 |
+
reload=reload,
|
72 |
+
forwarded_allow_ips="*",
|
73 |
+
)
|
74 |
+
|
75 |
+
|
76 |
+
if __name__ == "__main__":
|
77 |
+
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/apps/audio/main.py
ADDED
@@ -0,0 +1,641 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import hashlib
|
2 |
+
import json
|
3 |
+
import logging
|
4 |
+
import os
|
5 |
+
import uuid
|
6 |
+
from functools import lru_cache
|
7 |
+
from pathlib import Path
|
8 |
+
from pydub import AudioSegment
|
9 |
+
from pydub.silence import split_on_silence
|
10 |
+
|
11 |
+
import requests
|
12 |
+
from open_webui.config import (
|
13 |
+
AUDIO_STT_ENGINE,
|
14 |
+
AUDIO_STT_MODEL,
|
15 |
+
AUDIO_STT_OPENAI_API_BASE_URL,
|
16 |
+
AUDIO_STT_OPENAI_API_KEY,
|
17 |
+
AUDIO_TTS_API_KEY,
|
18 |
+
AUDIO_TTS_ENGINE,
|
19 |
+
AUDIO_TTS_MODEL,
|
20 |
+
AUDIO_TTS_OPENAI_API_BASE_URL,
|
21 |
+
AUDIO_TTS_OPENAI_API_KEY,
|
22 |
+
AUDIO_TTS_SPLIT_ON,
|
23 |
+
AUDIO_TTS_VOICE,
|
24 |
+
AUDIO_TTS_AZURE_SPEECH_REGION,
|
25 |
+
AUDIO_TTS_AZURE_SPEECH_OUTPUT_FORMAT,
|
26 |
+
CACHE_DIR,
|
27 |
+
CORS_ALLOW_ORIGIN,
|
28 |
+
WHISPER_MODEL,
|
29 |
+
WHISPER_MODEL_AUTO_UPDATE,
|
30 |
+
WHISPER_MODEL_DIR,
|
31 |
+
AppConfig,
|
32 |
+
)
|
33 |
+
|
34 |
+
from open_webui.constants import ERROR_MESSAGES
|
35 |
+
from open_webui.env import ENV, SRC_LOG_LEVELS, DEVICE_TYPE
|
36 |
+
from fastapi import Depends, FastAPI, File, HTTPException, Request, UploadFile, status
|
37 |
+
from fastapi.middleware.cors import CORSMiddleware
|
38 |
+
from fastapi.responses import FileResponse
|
39 |
+
from pydantic import BaseModel
|
40 |
+
from open_webui.utils.utils import get_admin_user, get_verified_user
|
41 |
+
|
42 |
+
# Constants
|
43 |
+
MAX_FILE_SIZE_MB = 25
|
44 |
+
MAX_FILE_SIZE = MAX_FILE_SIZE_MB * 1024 * 1024 # Convert MB to bytes
|
45 |
+
|
46 |
+
|
47 |
+
log = logging.getLogger(__name__)
|
48 |
+
log.setLevel(SRC_LOG_LEVELS["AUDIO"])
|
49 |
+
|
50 |
+
app = FastAPI(docs_url="/docs" if ENV == "dev" else None, openapi_url="/openapi.json" if ENV == "dev" else None, redoc_url=None)
|
51 |
+
|
52 |
+
app.add_middleware(
|
53 |
+
CORSMiddleware,
|
54 |
+
allow_origins=CORS_ALLOW_ORIGIN,
|
55 |
+
allow_credentials=True,
|
56 |
+
allow_methods=["*"],
|
57 |
+
allow_headers=["*"],
|
58 |
+
)
|
59 |
+
|
60 |
+
app.state.config = AppConfig()
|
61 |
+
|
62 |
+
app.state.config.STT_OPENAI_API_BASE_URL = AUDIO_STT_OPENAI_API_BASE_URL
|
63 |
+
app.state.config.STT_OPENAI_API_KEY = AUDIO_STT_OPENAI_API_KEY
|
64 |
+
app.state.config.STT_ENGINE = AUDIO_STT_ENGINE
|
65 |
+
app.state.config.STT_MODEL = AUDIO_STT_MODEL
|
66 |
+
|
67 |
+
app.state.config.WHISPER_MODEL = WHISPER_MODEL
|
68 |
+
app.state.faster_whisper_model = None
|
69 |
+
|
70 |
+
app.state.config.TTS_OPENAI_API_BASE_URL = AUDIO_TTS_OPENAI_API_BASE_URL
|
71 |
+
app.state.config.TTS_OPENAI_API_KEY = AUDIO_TTS_OPENAI_API_KEY
|
72 |
+
app.state.config.TTS_ENGINE = AUDIO_TTS_ENGINE
|
73 |
+
app.state.config.TTS_MODEL = AUDIO_TTS_MODEL
|
74 |
+
app.state.config.TTS_VOICE = AUDIO_TTS_VOICE
|
75 |
+
app.state.config.TTS_API_KEY = AUDIO_TTS_API_KEY
|
76 |
+
app.state.config.TTS_SPLIT_ON = AUDIO_TTS_SPLIT_ON
|
77 |
+
|
78 |
+
app.state.config.TTS_AZURE_SPEECH_REGION = AUDIO_TTS_AZURE_SPEECH_REGION
|
79 |
+
app.state.config.TTS_AZURE_SPEECH_OUTPUT_FORMAT = AUDIO_TTS_AZURE_SPEECH_OUTPUT_FORMAT
|
80 |
+
|
81 |
+
# setting device type for whisper model
|
82 |
+
whisper_device_type = DEVICE_TYPE if DEVICE_TYPE and DEVICE_TYPE == "cuda" else "cpu"
|
83 |
+
log.info(f"whisper_device_type: {whisper_device_type}")
|
84 |
+
|
85 |
+
SPEECH_CACHE_DIR = Path(CACHE_DIR).joinpath("./audio/speech/")
|
86 |
+
SPEECH_CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
87 |
+
|
88 |
+
|
89 |
+
def set_faster_whisper_model(model: str, auto_update: bool = False):
|
90 |
+
if model and app.state.config.STT_ENGINE == "":
|
91 |
+
from faster_whisper import WhisperModel
|
92 |
+
|
93 |
+
faster_whisper_kwargs = {
|
94 |
+
"model_size_or_path": model,
|
95 |
+
"device": whisper_device_type,
|
96 |
+
"compute_type": "int8",
|
97 |
+
"download_root": WHISPER_MODEL_DIR,
|
98 |
+
"local_files_only": not auto_update,
|
99 |
+
}
|
100 |
+
|
101 |
+
try:
|
102 |
+
app.state.faster_whisper_model = WhisperModel(**faster_whisper_kwargs)
|
103 |
+
except Exception:
|
104 |
+
log.warning(
|
105 |
+
"WhisperModel initialization failed, attempting download with local_files_only=False"
|
106 |
+
)
|
107 |
+
faster_whisper_kwargs["local_files_only"] = False
|
108 |
+
app.state.faster_whisper_model = WhisperModel(**faster_whisper_kwargs)
|
109 |
+
|
110 |
+
else:
|
111 |
+
app.state.faster_whisper_model = None
|
112 |
+
|
113 |
+
|
114 |
+
class TTSConfigForm(BaseModel):
|
115 |
+
OPENAI_API_BASE_URL: str
|
116 |
+
OPENAI_API_KEY: str
|
117 |
+
API_KEY: str
|
118 |
+
ENGINE: str
|
119 |
+
MODEL: str
|
120 |
+
VOICE: str
|
121 |
+
SPLIT_ON: str
|
122 |
+
AZURE_SPEECH_REGION: str
|
123 |
+
AZURE_SPEECH_OUTPUT_FORMAT: str
|
124 |
+
|
125 |
+
|
126 |
+
class STTConfigForm(BaseModel):
|
127 |
+
OPENAI_API_BASE_URL: str
|
128 |
+
OPENAI_API_KEY: str
|
129 |
+
ENGINE: str
|
130 |
+
MODEL: str
|
131 |
+
WHISPER_MODEL: str
|
132 |
+
|
133 |
+
|
134 |
+
class AudioConfigUpdateForm(BaseModel):
|
135 |
+
tts: TTSConfigForm
|
136 |
+
stt: STTConfigForm
|
137 |
+
|
138 |
+
|
139 |
+
from pydub import AudioSegment
|
140 |
+
from pydub.utils import mediainfo
|
141 |
+
|
142 |
+
|
143 |
+
def is_mp4_audio(file_path):
|
144 |
+
"""Check if the given file is an MP4 audio file."""
|
145 |
+
if not os.path.isfile(file_path):
|
146 |
+
print(f"File not found: {file_path}")
|
147 |
+
return False
|
148 |
+
|
149 |
+
info = mediainfo(file_path)
|
150 |
+
if (
|
151 |
+
info.get("codec_name") == "aac"
|
152 |
+
and info.get("codec_type") == "audio"
|
153 |
+
and info.get("codec_tag_string") == "mp4a"
|
154 |
+
):
|
155 |
+
return True
|
156 |
+
return False
|
157 |
+
|
158 |
+
|
159 |
+
def convert_mp4_to_wav(file_path, output_path):
|
160 |
+
"""Convert MP4 audio file to WAV format."""
|
161 |
+
audio = AudioSegment.from_file(file_path, format="mp4")
|
162 |
+
audio.export(output_path, format="wav")
|
163 |
+
print(f"Converted {file_path} to {output_path}")
|
164 |
+
|
165 |
+
|
166 |
+
@app.get("/config")
|
167 |
+
async def get_audio_config(user=Depends(get_admin_user)):
|
168 |
+
return {
|
169 |
+
"tts": {
|
170 |
+
"OPENAI_API_BASE_URL": app.state.config.TTS_OPENAI_API_BASE_URL,
|
171 |
+
"OPENAI_API_KEY": app.state.config.TTS_OPENAI_API_KEY,
|
172 |
+
"API_KEY": app.state.config.TTS_API_KEY,
|
173 |
+
"ENGINE": app.state.config.TTS_ENGINE,
|
174 |
+
"MODEL": app.state.config.TTS_MODEL,
|
175 |
+
"VOICE": app.state.config.TTS_VOICE,
|
176 |
+
"SPLIT_ON": app.state.config.TTS_SPLIT_ON,
|
177 |
+
"AZURE_SPEECH_REGION": app.state.config.TTS_AZURE_SPEECH_REGION,
|
178 |
+
"AZURE_SPEECH_OUTPUT_FORMAT": app.state.config.TTS_AZURE_SPEECH_OUTPUT_FORMAT,
|
179 |
+
},
|
180 |
+
"stt": {
|
181 |
+
"OPENAI_API_BASE_URL": app.state.config.STT_OPENAI_API_BASE_URL,
|
182 |
+
"OPENAI_API_KEY": app.state.config.STT_OPENAI_API_KEY,
|
183 |
+
"ENGINE": app.state.config.STT_ENGINE,
|
184 |
+
"MODEL": app.state.config.STT_MODEL,
|
185 |
+
"WHISPER_MODEL": app.state.config.WHISPER_MODEL,
|
186 |
+
},
|
187 |
+
}
|
188 |
+
|
189 |
+
|
190 |
+
@app.post("/config/update")
|
191 |
+
async def update_audio_config(
|
192 |
+
form_data: AudioConfigUpdateForm, user=Depends(get_admin_user)
|
193 |
+
):
|
194 |
+
app.state.config.TTS_OPENAI_API_BASE_URL = form_data.tts.OPENAI_API_BASE_URL
|
195 |
+
app.state.config.TTS_OPENAI_API_KEY = form_data.tts.OPENAI_API_KEY
|
196 |
+
app.state.config.TTS_API_KEY = form_data.tts.API_KEY
|
197 |
+
app.state.config.TTS_ENGINE = form_data.tts.ENGINE
|
198 |
+
app.state.config.TTS_MODEL = form_data.tts.MODEL
|
199 |
+
app.state.config.TTS_VOICE = form_data.tts.VOICE
|
200 |
+
app.state.config.TTS_SPLIT_ON = form_data.tts.SPLIT_ON
|
201 |
+
app.state.config.TTS_AZURE_SPEECH_REGION = form_data.tts.AZURE_SPEECH_REGION
|
202 |
+
app.state.config.TTS_AZURE_SPEECH_OUTPUT_FORMAT = (
|
203 |
+
form_data.tts.AZURE_SPEECH_OUTPUT_FORMAT
|
204 |
+
)
|
205 |
+
|
206 |
+
app.state.config.STT_OPENAI_API_BASE_URL = form_data.stt.OPENAI_API_BASE_URL
|
207 |
+
app.state.config.STT_OPENAI_API_KEY = form_data.stt.OPENAI_API_KEY
|
208 |
+
app.state.config.STT_ENGINE = form_data.stt.ENGINE
|
209 |
+
app.state.config.STT_MODEL = form_data.stt.MODEL
|
210 |
+
app.state.config.WHISPER_MODEL = form_data.stt.WHISPER_MODEL
|
211 |
+
set_faster_whisper_model(form_data.stt.WHISPER_MODEL, WHISPER_MODEL_AUTO_UPDATE)
|
212 |
+
|
213 |
+
return {
|
214 |
+
"tts": {
|
215 |
+
"OPENAI_API_BASE_URL": app.state.config.TTS_OPENAI_API_BASE_URL,
|
216 |
+
"OPENAI_API_KEY": app.state.config.TTS_OPENAI_API_KEY,
|
217 |
+
"API_KEY": app.state.config.TTS_API_KEY,
|
218 |
+
"ENGINE": app.state.config.TTS_ENGINE,
|
219 |
+
"MODEL": app.state.config.TTS_MODEL,
|
220 |
+
"VOICE": app.state.config.TTS_VOICE,
|
221 |
+
"SPLIT_ON": app.state.config.TTS_SPLIT_ON,
|
222 |
+
"AZURE_SPEECH_REGION": app.state.config.TTS_AZURE_SPEECH_REGION,
|
223 |
+
"AZURE_SPEECH_OUTPUT_FORMAT": app.state.config.TTS_AZURE_SPEECH_OUTPUT_FORMAT,
|
224 |
+
},
|
225 |
+
"stt": {
|
226 |
+
"OPENAI_API_BASE_URL": app.state.config.STT_OPENAI_API_BASE_URL,
|
227 |
+
"OPENAI_API_KEY": app.state.config.STT_OPENAI_API_KEY,
|
228 |
+
"ENGINE": app.state.config.STT_ENGINE,
|
229 |
+
"MODEL": app.state.config.STT_MODEL,
|
230 |
+
"WHISPER_MODEL": app.state.config.WHISPER_MODEL,
|
231 |
+
},
|
232 |
+
}
|
233 |
+
|
234 |
+
|
235 |
+
@app.post("/speech")
|
236 |
+
async def speech(request: Request, user=Depends(get_verified_user)):
|
237 |
+
body = await request.body()
|
238 |
+
name = hashlib.sha256(body).hexdigest()
|
239 |
+
|
240 |
+
file_path = SPEECH_CACHE_DIR.joinpath(f"{name}.mp3")
|
241 |
+
file_body_path = SPEECH_CACHE_DIR.joinpath(f"{name}.json")
|
242 |
+
|
243 |
+
# Check if the file already exists in the cache
|
244 |
+
if file_path.is_file():
|
245 |
+
return FileResponse(file_path)
|
246 |
+
|
247 |
+
if app.state.config.TTS_ENGINE == "openai":
|
248 |
+
headers = {}
|
249 |
+
headers["Authorization"] = f"Bearer {app.state.config.TTS_OPENAI_API_KEY}"
|
250 |
+
headers["Content-Type"] = "application/json"
|
251 |
+
|
252 |
+
try:
|
253 |
+
body = body.decode("utf-8")
|
254 |
+
body = json.loads(body)
|
255 |
+
body["model"] = app.state.config.TTS_MODEL
|
256 |
+
body = json.dumps(body).encode("utf-8")
|
257 |
+
except Exception:
|
258 |
+
pass
|
259 |
+
|
260 |
+
r = None
|
261 |
+
try:
|
262 |
+
r = requests.post(
|
263 |
+
url=f"{app.state.config.TTS_OPENAI_API_BASE_URL}/audio/speech",
|
264 |
+
data=body,
|
265 |
+
headers=headers,
|
266 |
+
stream=True,
|
267 |
+
)
|
268 |
+
|
269 |
+
r.raise_for_status()
|
270 |
+
|
271 |
+
# Save the streaming content to a file
|
272 |
+
with open(file_path, "wb") as f:
|
273 |
+
for chunk in r.iter_content(chunk_size=8192):
|
274 |
+
f.write(chunk)
|
275 |
+
|
276 |
+
with open(file_body_path, "w") as f:
|
277 |
+
json.dump(json.loads(body.decode("utf-8")), f)
|
278 |
+
|
279 |
+
# Return the saved file
|
280 |
+
return FileResponse(file_path)
|
281 |
+
|
282 |
+
except Exception as e:
|
283 |
+
log.exception(e)
|
284 |
+
error_detail = "Open WebUI: Server Connection Error"
|
285 |
+
if r is not None:
|
286 |
+
try:
|
287 |
+
res = r.json()
|
288 |
+
if "error" in res:
|
289 |
+
error_detail = f"External: {res['error']['message']}"
|
290 |
+
except Exception:
|
291 |
+
error_detail = f"External: {e}"
|
292 |
+
|
293 |
+
raise HTTPException(
|
294 |
+
status_code=r.status_code if r != None else 500,
|
295 |
+
detail=error_detail,
|
296 |
+
)
|
297 |
+
|
298 |
+
elif app.state.config.TTS_ENGINE == "elevenlabs":
|
299 |
+
payload = None
|
300 |
+
try:
|
301 |
+
payload = json.loads(body.decode("utf-8"))
|
302 |
+
except Exception as e:
|
303 |
+
log.exception(e)
|
304 |
+
raise HTTPException(status_code=400, detail="Invalid JSON payload")
|
305 |
+
|
306 |
+
voice_id = payload.get("voice", "")
|
307 |
+
|
308 |
+
if voice_id not in get_available_voices():
|
309 |
+
raise HTTPException(
|
310 |
+
status_code=400,
|
311 |
+
detail="Invalid voice id",
|
312 |
+
)
|
313 |
+
|
314 |
+
url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}"
|
315 |
+
|
316 |
+
headers = {
|
317 |
+
"Accept": "audio/mpeg",
|
318 |
+
"Content-Type": "application/json",
|
319 |
+
"xi-api-key": app.state.config.TTS_API_KEY,
|
320 |
+
}
|
321 |
+
|
322 |
+
data = {
|
323 |
+
"text": payload["input"],
|
324 |
+
"model_id": app.state.config.TTS_MODEL,
|
325 |
+
"voice_settings": {"stability": 0.5, "similarity_boost": 0.5},
|
326 |
+
}
|
327 |
+
|
328 |
+
try:
|
329 |
+
r = requests.post(url, json=data, headers=headers)
|
330 |
+
|
331 |
+
r.raise_for_status()
|
332 |
+
|
333 |
+
# Save the streaming content to a file
|
334 |
+
with open(file_path, "wb") as f:
|
335 |
+
for chunk in r.iter_content(chunk_size=8192):
|
336 |
+
f.write(chunk)
|
337 |
+
|
338 |
+
with open(file_body_path, "w") as f:
|
339 |
+
json.dump(json.loads(body.decode("utf-8")), f)
|
340 |
+
|
341 |
+
# Return the saved file
|
342 |
+
return FileResponse(file_path)
|
343 |
+
|
344 |
+
except Exception as e:
|
345 |
+
log.exception(e)
|
346 |
+
error_detail = "Open WebUI: Server Connection Error"
|
347 |
+
if r is not None:
|
348 |
+
try:
|
349 |
+
res = r.json()
|
350 |
+
if "error" in res:
|
351 |
+
error_detail = f"External: {res['error']['message']}"
|
352 |
+
except Exception:
|
353 |
+
error_detail = f"External: {e}"
|
354 |
+
|
355 |
+
raise HTTPException(
|
356 |
+
status_code=r.status_code if r != None else 500,
|
357 |
+
detail=error_detail,
|
358 |
+
)
|
359 |
+
|
360 |
+
elif app.state.config.TTS_ENGINE == "azure":
|
361 |
+
payload = None
|
362 |
+
try:
|
363 |
+
payload = json.loads(body.decode("utf-8"))
|
364 |
+
except Exception as e:
|
365 |
+
log.exception(e)
|
366 |
+
raise HTTPException(status_code=400, detail="Invalid JSON payload")
|
367 |
+
|
368 |
+
region = app.state.config.TTS_AZURE_SPEECH_REGION
|
369 |
+
language = app.state.config.TTS_VOICE
|
370 |
+
locale = "-".join(app.state.config.TTS_VOICE.split("-")[:1])
|
371 |
+
output_format = app.state.config.TTS_AZURE_SPEECH_OUTPUT_FORMAT
|
372 |
+
url = f"https://{region}.tts.speech.microsoft.com/cognitiveservices/v1"
|
373 |
+
|
374 |
+
headers = {
|
375 |
+
"Ocp-Apim-Subscription-Key": app.state.config.TTS_API_KEY,
|
376 |
+
"Content-Type": "application/ssml+xml",
|
377 |
+
"X-Microsoft-OutputFormat": output_format,
|
378 |
+
}
|
379 |
+
|
380 |
+
data = f"""<speak version="1.0" xmlns="http://www.w3.org/2001/10/synthesis" xml:lang="{locale}">
|
381 |
+
<voice name="{language}">{payload["input"]}</voice>
|
382 |
+
</speak>"""
|
383 |
+
|
384 |
+
response = requests.post(url, headers=headers, data=data)
|
385 |
+
|
386 |
+
if response.status_code == 200:
|
387 |
+
with open(file_path, "wb") as f:
|
388 |
+
f.write(response.content)
|
389 |
+
return FileResponse(file_path)
|
390 |
+
else:
|
391 |
+
log.error(f"Error synthesizing speech - {response.reason}")
|
392 |
+
raise HTTPException(
|
393 |
+
status_code=500, detail=f"Error synthesizing speech - {response.reason}"
|
394 |
+
)
|
395 |
+
|
396 |
+
|
397 |
+
def transcribe(file_path):
|
398 |
+
print("transcribe", file_path)
|
399 |
+
filename = os.path.basename(file_path)
|
400 |
+
file_dir = os.path.dirname(file_path)
|
401 |
+
id = filename.split(".")[0]
|
402 |
+
|
403 |
+
if app.state.config.STT_ENGINE == "":
|
404 |
+
if app.state.faster_whisper_model is None:
|
405 |
+
set_faster_whisper_model(app.state.config.WHISPER_MODEL)
|
406 |
+
|
407 |
+
model = app.state.faster_whisper_model
|
408 |
+
segments, info = model.transcribe(file_path, beam_size=5)
|
409 |
+
log.info(
|
410 |
+
"Detected language '%s' with probability %f"
|
411 |
+
% (info.language, info.language_probability)
|
412 |
+
)
|
413 |
+
|
414 |
+
transcript = "".join([segment.text for segment in list(segments)])
|
415 |
+
data = {"text": transcript.strip()}
|
416 |
+
|
417 |
+
# save the transcript to a json file
|
418 |
+
transcript_file = f"{file_dir}/{id}.json"
|
419 |
+
with open(transcript_file, "w") as f:
|
420 |
+
json.dump(data, f)
|
421 |
+
|
422 |
+
log.debug(data)
|
423 |
+
return data
|
424 |
+
elif app.state.config.STT_ENGINE == "openai":
|
425 |
+
if is_mp4_audio(file_path):
|
426 |
+
print("is_mp4_audio")
|
427 |
+
os.rename(file_path, file_path.replace(".wav", ".mp4"))
|
428 |
+
# Convert MP4 audio file to WAV format
|
429 |
+
convert_mp4_to_wav(file_path.replace(".wav", ".mp4"), file_path)
|
430 |
+
|
431 |
+
headers = {"Authorization": f"Bearer {app.state.config.STT_OPENAI_API_KEY}"}
|
432 |
+
|
433 |
+
files = {"file": (filename, open(file_path, "rb"))}
|
434 |
+
data = {"model": app.state.config.STT_MODEL}
|
435 |
+
|
436 |
+
log.debug(files, data)
|
437 |
+
|
438 |
+
r = None
|
439 |
+
try:
|
440 |
+
r = requests.post(
|
441 |
+
url=f"{app.state.config.STT_OPENAI_API_BASE_URL}/audio/transcriptions",
|
442 |
+
headers=headers,
|
443 |
+
files=files,
|
444 |
+
data=data,
|
445 |
+
)
|
446 |
+
|
447 |
+
r.raise_for_status()
|
448 |
+
|
449 |
+
data = r.json()
|
450 |
+
|
451 |
+
# save the transcript to a json file
|
452 |
+
transcript_file = f"{file_dir}/{id}.json"
|
453 |
+
with open(transcript_file, "w") as f:
|
454 |
+
json.dump(data, f)
|
455 |
+
|
456 |
+
print(data)
|
457 |
+
return data
|
458 |
+
except Exception as e:
|
459 |
+
log.exception(e)
|
460 |
+
error_detail = "Open WebUI: Server Connection Error"
|
461 |
+
if r is not None:
|
462 |
+
try:
|
463 |
+
res = r.json()
|
464 |
+
if "error" in res:
|
465 |
+
error_detail = f"External: {res['error']['message']}"
|
466 |
+
except Exception:
|
467 |
+
error_detail = f"External: {e}"
|
468 |
+
|
469 |
+
raise Exception(error_detail)
|
470 |
+
|
471 |
+
|
472 |
+
@app.post("/transcriptions")
|
473 |
+
def transcription(
|
474 |
+
file: UploadFile = File(...),
|
475 |
+
user=Depends(get_verified_user),
|
476 |
+
):
|
477 |
+
log.info(f"file.content_type: {file.content_type}")
|
478 |
+
|
479 |
+
if file.content_type not in ["audio/mpeg", "audio/wav", "audio/ogg", "audio/x-m4a"]:
|
480 |
+
raise HTTPException(
|
481 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
482 |
+
detail=ERROR_MESSAGES.FILE_NOT_SUPPORTED,
|
483 |
+
)
|
484 |
+
|
485 |
+
try:
|
486 |
+
ext = file.filename.split(".")[-1]
|
487 |
+
id = uuid.uuid4()
|
488 |
+
|
489 |
+
filename = f"{id}.{ext}"
|
490 |
+
contents = file.file.read()
|
491 |
+
|
492 |
+
file_dir = f"{CACHE_DIR}/audio/transcriptions"
|
493 |
+
os.makedirs(file_dir, exist_ok=True)
|
494 |
+
file_path = f"{file_dir}/{filename}"
|
495 |
+
|
496 |
+
with open(file_path, "wb") as f:
|
497 |
+
f.write(contents)
|
498 |
+
|
499 |
+
try:
|
500 |
+
if os.path.getsize(file_path) > MAX_FILE_SIZE: # file is bigger than 25MB
|
501 |
+
log.debug(f"File size is larger than {MAX_FILE_SIZE_MB}MB")
|
502 |
+
audio = AudioSegment.from_file(file_path)
|
503 |
+
audio = audio.set_frame_rate(16000).set_channels(1) # Compress audio
|
504 |
+
compressed_path = f"{file_dir}/{id}_compressed.opus"
|
505 |
+
audio.export(compressed_path, format="opus", bitrate="32k")
|
506 |
+
log.debug(f"Compressed audio to {compressed_path}")
|
507 |
+
file_path = compressed_path
|
508 |
+
|
509 |
+
if (
|
510 |
+
os.path.getsize(file_path) > MAX_FILE_SIZE
|
511 |
+
): # Still larger than 25MB after compression
|
512 |
+
log.debug(
|
513 |
+
f"Compressed file size is still larger than {MAX_FILE_SIZE_MB}MB: {os.path.getsize(file_path)}"
|
514 |
+
)
|
515 |
+
raise HTTPException(
|
516 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
517 |
+
detail=ERROR_MESSAGES.FILE_TOO_LARGE(
|
518 |
+
size=f"{MAX_FILE_SIZE_MB}MB"
|
519 |
+
),
|
520 |
+
)
|
521 |
+
|
522 |
+
data = transcribe(file_path)
|
523 |
+
else:
|
524 |
+
data = transcribe(file_path)
|
525 |
+
|
526 |
+
file_path = file_path.split("/")[-1]
|
527 |
+
return {**data, "filename": file_path}
|
528 |
+
except Exception as e:
|
529 |
+
log.exception(e)
|
530 |
+
raise HTTPException(
|
531 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
532 |
+
detail=ERROR_MESSAGES.DEFAULT(e),
|
533 |
+
)
|
534 |
+
|
535 |
+
except Exception as e:
|
536 |
+
log.exception(e)
|
537 |
+
|
538 |
+
raise HTTPException(
|
539 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
540 |
+
detail=ERROR_MESSAGES.DEFAULT(e),
|
541 |
+
)
|
542 |
+
|
543 |
+
|
544 |
+
def get_available_models() -> list[dict]:
|
545 |
+
if app.state.config.TTS_ENGINE == "openai":
|
546 |
+
return [{"id": "tts-1"}, {"id": "tts-1-hd"}]
|
547 |
+
elif app.state.config.TTS_ENGINE == "elevenlabs":
|
548 |
+
headers = {
|
549 |
+
"xi-api-key": app.state.config.TTS_API_KEY,
|
550 |
+
"Content-Type": "application/json",
|
551 |
+
}
|
552 |
+
|
553 |
+
try:
|
554 |
+
response = requests.get(
|
555 |
+
"https://api.elevenlabs.io/v1/models", headers=headers, timeout=5
|
556 |
+
)
|
557 |
+
response.raise_for_status()
|
558 |
+
models = response.json()
|
559 |
+
return [
|
560 |
+
{"name": model["name"], "id": model["model_id"]} for model in models
|
561 |
+
]
|
562 |
+
except requests.RequestException as e:
|
563 |
+
log.error(f"Error fetching voices: {str(e)}")
|
564 |
+
return []
|
565 |
+
|
566 |
+
|
567 |
+
@app.get("/models")
|
568 |
+
async def get_models(user=Depends(get_verified_user)):
|
569 |
+
return {"models": get_available_models()}
|
570 |
+
|
571 |
+
|
572 |
+
def get_available_voices() -> dict:
|
573 |
+
"""Returns {voice_id: voice_name} dict"""
|
574 |
+
ret = {}
|
575 |
+
if app.state.config.TTS_ENGINE == "openai":
|
576 |
+
ret = {
|
577 |
+
"alloy": "alloy",
|
578 |
+
"echo": "echo",
|
579 |
+
"fable": "fable",
|
580 |
+
"onyx": "onyx",
|
581 |
+
"nova": "nova",
|
582 |
+
"shimmer": "shimmer",
|
583 |
+
}
|
584 |
+
elif app.state.config.TTS_ENGINE == "elevenlabs":
|
585 |
+
try:
|
586 |
+
ret = get_elevenlabs_voices()
|
587 |
+
except Exception:
|
588 |
+
# Avoided @lru_cache with exception
|
589 |
+
pass
|
590 |
+
elif app.state.config.TTS_ENGINE == "azure":
|
591 |
+
try:
|
592 |
+
region = app.state.config.TTS_AZURE_SPEECH_REGION
|
593 |
+
url = f"https://{region}.tts.speech.microsoft.com/cognitiveservices/voices/list"
|
594 |
+
headers = {"Ocp-Apim-Subscription-Key": app.state.config.TTS_API_KEY}
|
595 |
+
|
596 |
+
response = requests.get(url, headers=headers)
|
597 |
+
response.raise_for_status()
|
598 |
+
voices = response.json()
|
599 |
+
for voice in voices:
|
600 |
+
ret[voice["ShortName"]] = (
|
601 |
+
f"{voice['DisplayName']} ({voice['ShortName']})"
|
602 |
+
)
|
603 |
+
except requests.RequestException as e:
|
604 |
+
log.error(f"Error fetching voices: {str(e)}")
|
605 |
+
|
606 |
+
return ret
|
607 |
+
|
608 |
+
|
609 |
+
@lru_cache
|
610 |
+
def get_elevenlabs_voices() -> dict:
|
611 |
+
"""
|
612 |
+
Note, set the following in your .env file to use Elevenlabs:
|
613 |
+
AUDIO_TTS_ENGINE=elevenlabs
|
614 |
+
AUDIO_TTS_API_KEY=sk_... # Your Elevenlabs API key
|
615 |
+
AUDIO_TTS_VOICE=EXAVITQu4vr4xnSDxMaL # From https://api.elevenlabs.io/v1/voices
|
616 |
+
AUDIO_TTS_MODEL=eleven_multilingual_v2
|
617 |
+
"""
|
618 |
+
headers = {
|
619 |
+
"xi-api-key": app.state.config.TTS_API_KEY,
|
620 |
+
"Content-Type": "application/json",
|
621 |
+
}
|
622 |
+
try:
|
623 |
+
# TODO: Add retries
|
624 |
+
response = requests.get("https://api.elevenlabs.io/v1/voices", headers=headers)
|
625 |
+
response.raise_for_status()
|
626 |
+
voices_data = response.json()
|
627 |
+
|
628 |
+
voices = {}
|
629 |
+
for voice in voices_data.get("voices", []):
|
630 |
+
voices[voice["voice_id"]] = voice["name"]
|
631 |
+
except requests.RequestException as e:
|
632 |
+
# Avoid @lru_cache with exception
|
633 |
+
log.error(f"Error fetching voices: {str(e)}")
|
634 |
+
raise RuntimeError(f"Error fetching voices: {str(e)}")
|
635 |
+
|
636 |
+
return voices
|
637 |
+
|
638 |
+
|
639 |
+
@app.get("/voices")
|
640 |
+
async def get_voices(user=Depends(get_verified_user)):
|
641 |
+
return {"voices": [{"id": k, "name": v} for k, v in get_available_voices().items()]}
|
backend/open_webui/apps/images/main.py
ADDED
@@ -0,0 +1,598 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import asyncio
|
2 |
+
import base64
|
3 |
+
import json
|
4 |
+
import logging
|
5 |
+
import mimetypes
|
6 |
+
import re
|
7 |
+
import uuid
|
8 |
+
from pathlib import Path
|
9 |
+
from typing import Optional
|
10 |
+
|
11 |
+
import requests
|
12 |
+
from open_webui.apps.images.utils.comfyui import (
|
13 |
+
ComfyUIGenerateImageForm,
|
14 |
+
ComfyUIWorkflow,
|
15 |
+
comfyui_generate_image,
|
16 |
+
)
|
17 |
+
from open_webui.config import (
|
18 |
+
AUTOMATIC1111_API_AUTH,
|
19 |
+
AUTOMATIC1111_BASE_URL,
|
20 |
+
AUTOMATIC1111_CFG_SCALE,
|
21 |
+
AUTOMATIC1111_SAMPLER,
|
22 |
+
AUTOMATIC1111_SCHEDULER,
|
23 |
+
CACHE_DIR,
|
24 |
+
COMFYUI_BASE_URL,
|
25 |
+
COMFYUI_WORKFLOW,
|
26 |
+
COMFYUI_WORKFLOW_NODES,
|
27 |
+
CORS_ALLOW_ORIGIN,
|
28 |
+
ENABLE_IMAGE_GENERATION,
|
29 |
+
IMAGE_GENERATION_ENGINE,
|
30 |
+
IMAGE_GENERATION_MODEL,
|
31 |
+
IMAGE_SIZE,
|
32 |
+
IMAGE_STEPS,
|
33 |
+
IMAGES_OPENAI_API_BASE_URL,
|
34 |
+
IMAGES_OPENAI_API_KEY,
|
35 |
+
AppConfig,
|
36 |
+
)
|
37 |
+
from open_webui.constants import ERROR_MESSAGES
|
38 |
+
from open_webui.env import ENV, SRC_LOG_LEVELS
|
39 |
+
from fastapi import Depends, FastAPI, HTTPException, Request
|
40 |
+
from fastapi.middleware.cors import CORSMiddleware
|
41 |
+
from pydantic import BaseModel
|
42 |
+
from open_webui.utils.utils import get_admin_user, get_verified_user
|
43 |
+
|
44 |
+
log = logging.getLogger(__name__)
|
45 |
+
log.setLevel(SRC_LOG_LEVELS["IMAGES"])
|
46 |
+
|
47 |
+
IMAGE_CACHE_DIR = Path(CACHE_DIR).joinpath("./image/generations/")
|
48 |
+
IMAGE_CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
49 |
+
|
50 |
+
app = FastAPI(docs_url="/docs" if ENV == "dev" else None, openapi_url="/openapi.json" if ENV == "dev" else None, redoc_url=None)
|
51 |
+
|
52 |
+
app.add_middleware(
|
53 |
+
CORSMiddleware,
|
54 |
+
allow_origins=CORS_ALLOW_ORIGIN,
|
55 |
+
allow_credentials=True,
|
56 |
+
allow_methods=["*"],
|
57 |
+
allow_headers=["*"],
|
58 |
+
)
|
59 |
+
|
60 |
+
app.state.config = AppConfig()
|
61 |
+
|
62 |
+
app.state.config.ENGINE = IMAGE_GENERATION_ENGINE
|
63 |
+
app.state.config.ENABLED = ENABLE_IMAGE_GENERATION
|
64 |
+
|
65 |
+
app.state.config.OPENAI_API_BASE_URL = IMAGES_OPENAI_API_BASE_URL
|
66 |
+
app.state.config.OPENAI_API_KEY = IMAGES_OPENAI_API_KEY
|
67 |
+
|
68 |
+
app.state.config.MODEL = IMAGE_GENERATION_MODEL
|
69 |
+
|
70 |
+
app.state.config.AUTOMATIC1111_BASE_URL = AUTOMATIC1111_BASE_URL
|
71 |
+
app.state.config.AUTOMATIC1111_API_AUTH = AUTOMATIC1111_API_AUTH
|
72 |
+
app.state.config.AUTOMATIC1111_CFG_SCALE = AUTOMATIC1111_CFG_SCALE
|
73 |
+
app.state.config.AUTOMATIC1111_SAMPLER = AUTOMATIC1111_SAMPLER
|
74 |
+
app.state.config.AUTOMATIC1111_SCHEDULER = AUTOMATIC1111_SCHEDULER
|
75 |
+
app.state.config.COMFYUI_BASE_URL = COMFYUI_BASE_URL
|
76 |
+
app.state.config.COMFYUI_WORKFLOW = COMFYUI_WORKFLOW
|
77 |
+
app.state.config.COMFYUI_WORKFLOW_NODES = COMFYUI_WORKFLOW_NODES
|
78 |
+
|
79 |
+
app.state.config.IMAGE_SIZE = IMAGE_SIZE
|
80 |
+
app.state.config.IMAGE_STEPS = IMAGE_STEPS
|
81 |
+
|
82 |
+
|
83 |
+
@app.get("/config")
|
84 |
+
async def get_config(request: Request, user=Depends(get_admin_user)):
|
85 |
+
return {
|
86 |
+
"enabled": app.state.config.ENABLED,
|
87 |
+
"engine": app.state.config.ENGINE,
|
88 |
+
"openai": {
|
89 |
+
"OPENAI_API_BASE_URL": app.state.config.OPENAI_API_BASE_URL,
|
90 |
+
"OPENAI_API_KEY": app.state.config.OPENAI_API_KEY,
|
91 |
+
},
|
92 |
+
"automatic1111": {
|
93 |
+
"AUTOMATIC1111_BASE_URL": app.state.config.AUTOMATIC1111_BASE_URL,
|
94 |
+
"AUTOMATIC1111_API_AUTH": app.state.config.AUTOMATIC1111_API_AUTH,
|
95 |
+
"AUTOMATIC1111_CFG_SCALE": app.state.config.AUTOMATIC1111_CFG_SCALE,
|
96 |
+
"AUTOMATIC1111_SAMPLER": app.state.config.AUTOMATIC1111_SAMPLER,
|
97 |
+
"AUTOMATIC1111_SCHEDULER": app.state.config.AUTOMATIC1111_SCHEDULER,
|
98 |
+
},
|
99 |
+
"comfyui": {
|
100 |
+
"COMFYUI_BASE_URL": app.state.config.COMFYUI_BASE_URL,
|
101 |
+
"COMFYUI_WORKFLOW": app.state.config.COMFYUI_WORKFLOW,
|
102 |
+
"COMFYUI_WORKFLOW_NODES": app.state.config.COMFYUI_WORKFLOW_NODES,
|
103 |
+
},
|
104 |
+
}
|
105 |
+
|
106 |
+
|
107 |
+
class OpenAIConfigForm(BaseModel):
|
108 |
+
OPENAI_API_BASE_URL: str
|
109 |
+
OPENAI_API_KEY: str
|
110 |
+
|
111 |
+
|
112 |
+
class Automatic1111ConfigForm(BaseModel):
|
113 |
+
AUTOMATIC1111_BASE_URL: str
|
114 |
+
AUTOMATIC1111_API_AUTH: str
|
115 |
+
AUTOMATIC1111_CFG_SCALE: Optional[str]
|
116 |
+
AUTOMATIC1111_SAMPLER: Optional[str]
|
117 |
+
AUTOMATIC1111_SCHEDULER: Optional[str]
|
118 |
+
|
119 |
+
|
120 |
+
class ComfyUIConfigForm(BaseModel):
|
121 |
+
COMFYUI_BASE_URL: str
|
122 |
+
COMFYUI_WORKFLOW: str
|
123 |
+
COMFYUI_WORKFLOW_NODES: list[dict]
|
124 |
+
|
125 |
+
|
126 |
+
class ConfigForm(BaseModel):
|
127 |
+
enabled: bool
|
128 |
+
engine: str
|
129 |
+
openai: OpenAIConfigForm
|
130 |
+
automatic1111: Automatic1111ConfigForm
|
131 |
+
comfyui: ComfyUIConfigForm
|
132 |
+
|
133 |
+
|
134 |
+
@app.post("/config/update")
|
135 |
+
async def update_config(form_data: ConfigForm, user=Depends(get_admin_user)):
|
136 |
+
app.state.config.ENGINE = form_data.engine
|
137 |
+
app.state.config.ENABLED = form_data.enabled
|
138 |
+
|
139 |
+
app.state.config.OPENAI_API_BASE_URL = form_data.openai.OPENAI_API_BASE_URL
|
140 |
+
app.state.config.OPENAI_API_KEY = form_data.openai.OPENAI_API_KEY
|
141 |
+
|
142 |
+
app.state.config.AUTOMATIC1111_BASE_URL = (
|
143 |
+
form_data.automatic1111.AUTOMATIC1111_BASE_URL
|
144 |
+
)
|
145 |
+
app.state.config.AUTOMATIC1111_API_AUTH = (
|
146 |
+
form_data.automatic1111.AUTOMATIC1111_API_AUTH
|
147 |
+
)
|
148 |
+
|
149 |
+
app.state.config.AUTOMATIC1111_CFG_SCALE = (
|
150 |
+
float(form_data.automatic1111.AUTOMATIC1111_CFG_SCALE)
|
151 |
+
if form_data.automatic1111.AUTOMATIC1111_CFG_SCALE
|
152 |
+
else None
|
153 |
+
)
|
154 |
+
app.state.config.AUTOMATIC1111_SAMPLER = (
|
155 |
+
form_data.automatic1111.AUTOMATIC1111_SAMPLER
|
156 |
+
if form_data.automatic1111.AUTOMATIC1111_SAMPLER
|
157 |
+
else None
|
158 |
+
)
|
159 |
+
app.state.config.AUTOMATIC1111_SCHEDULER = (
|
160 |
+
form_data.automatic1111.AUTOMATIC1111_SCHEDULER
|
161 |
+
if form_data.automatic1111.AUTOMATIC1111_SCHEDULER
|
162 |
+
else None
|
163 |
+
)
|
164 |
+
|
165 |
+
app.state.config.COMFYUI_BASE_URL = form_data.comfyui.COMFYUI_BASE_URL.strip("/")
|
166 |
+
app.state.config.COMFYUI_WORKFLOW = form_data.comfyui.COMFYUI_WORKFLOW
|
167 |
+
app.state.config.COMFYUI_WORKFLOW_NODES = form_data.comfyui.COMFYUI_WORKFLOW_NODES
|
168 |
+
|
169 |
+
return {
|
170 |
+
"enabled": app.state.config.ENABLED,
|
171 |
+
"engine": app.state.config.ENGINE,
|
172 |
+
"openai": {
|
173 |
+
"OPENAI_API_BASE_URL": app.state.config.OPENAI_API_BASE_URL,
|
174 |
+
"OPENAI_API_KEY": app.state.config.OPENAI_API_KEY,
|
175 |
+
},
|
176 |
+
"automatic1111": {
|
177 |
+
"AUTOMATIC1111_BASE_URL": app.state.config.AUTOMATIC1111_BASE_URL,
|
178 |
+
"AUTOMATIC1111_API_AUTH": app.state.config.AUTOMATIC1111_API_AUTH,
|
179 |
+
"AUTOMATIC1111_CFG_SCALE": app.state.config.AUTOMATIC1111_CFG_SCALE,
|
180 |
+
"AUTOMATIC1111_SAMPLER": app.state.config.AUTOMATIC1111_SAMPLER,
|
181 |
+
"AUTOMATIC1111_SCHEDULER": app.state.config.AUTOMATIC1111_SCHEDULER,
|
182 |
+
},
|
183 |
+
"comfyui": {
|
184 |
+
"COMFYUI_BASE_URL": app.state.config.COMFYUI_BASE_URL,
|
185 |
+
"COMFYUI_WORKFLOW": app.state.config.COMFYUI_WORKFLOW,
|
186 |
+
"COMFYUI_WORKFLOW_NODES": app.state.config.COMFYUI_WORKFLOW_NODES,
|
187 |
+
},
|
188 |
+
}
|
189 |
+
|
190 |
+
|
191 |
+
def get_automatic1111_api_auth():
|
192 |
+
if app.state.config.AUTOMATIC1111_API_AUTH is None:
|
193 |
+
return ""
|
194 |
+
else:
|
195 |
+
auth1111_byte_string = app.state.config.AUTOMATIC1111_API_AUTH.encode("utf-8")
|
196 |
+
auth1111_base64_encoded_bytes = base64.b64encode(auth1111_byte_string)
|
197 |
+
auth1111_base64_encoded_string = auth1111_base64_encoded_bytes.decode("utf-8")
|
198 |
+
return f"Basic {auth1111_base64_encoded_string}"
|
199 |
+
|
200 |
+
|
201 |
+
@app.get("/config/url/verify")
|
202 |
+
async def verify_url(user=Depends(get_admin_user)):
|
203 |
+
if app.state.config.ENGINE == "automatic1111":
|
204 |
+
try:
|
205 |
+
r = requests.get(
|
206 |
+
url=f"{app.state.config.AUTOMATIC1111_BASE_URL}/sdapi/v1/options",
|
207 |
+
headers={"authorization": get_automatic1111_api_auth()},
|
208 |
+
)
|
209 |
+
r.raise_for_status()
|
210 |
+
return True
|
211 |
+
except Exception:
|
212 |
+
app.state.config.ENABLED = False
|
213 |
+
raise HTTPException(status_code=400, detail=ERROR_MESSAGES.INVALID_URL)
|
214 |
+
elif app.state.config.ENGINE == "comfyui":
|
215 |
+
try:
|
216 |
+
r = requests.get(url=f"{app.state.config.COMFYUI_BASE_URL}/object_info")
|
217 |
+
r.raise_for_status()
|
218 |
+
return True
|
219 |
+
except Exception:
|
220 |
+
app.state.config.ENABLED = False
|
221 |
+
raise HTTPException(status_code=400, detail=ERROR_MESSAGES.INVALID_URL)
|
222 |
+
else:
|
223 |
+
return True
|
224 |
+
|
225 |
+
|
226 |
+
def set_image_model(model: str):
|
227 |
+
log.info(f"Setting image model to {model}")
|
228 |
+
app.state.config.MODEL = model
|
229 |
+
if app.state.config.ENGINE in ["", "automatic1111"]:
|
230 |
+
api_auth = get_automatic1111_api_auth()
|
231 |
+
r = requests.get(
|
232 |
+
url=f"{app.state.config.AUTOMATIC1111_BASE_URL}/sdapi/v1/options",
|
233 |
+
headers={"authorization": api_auth},
|
234 |
+
)
|
235 |
+
options = r.json()
|
236 |
+
if model != options["sd_model_checkpoint"]:
|
237 |
+
options["sd_model_checkpoint"] = model
|
238 |
+
r = requests.post(
|
239 |
+
url=f"{app.state.config.AUTOMATIC1111_BASE_URL}/sdapi/v1/options",
|
240 |
+
json=options,
|
241 |
+
headers={"authorization": api_auth},
|
242 |
+
)
|
243 |
+
return app.state.config.MODEL
|
244 |
+
|
245 |
+
|
246 |
+
def get_image_model():
|
247 |
+
if app.state.config.ENGINE == "openai":
|
248 |
+
return app.state.config.MODEL if app.state.config.MODEL else "dall-e-2"
|
249 |
+
elif app.state.config.ENGINE == "comfyui":
|
250 |
+
return app.state.config.MODEL if app.state.config.MODEL else ""
|
251 |
+
elif app.state.config.ENGINE == "automatic1111" or app.state.config.ENGINE == "":
|
252 |
+
try:
|
253 |
+
r = requests.get(
|
254 |
+
url=f"{app.state.config.AUTOMATIC1111_BASE_URL}/sdapi/v1/options",
|
255 |
+
headers={"authorization": get_automatic1111_api_auth()},
|
256 |
+
)
|
257 |
+
options = r.json()
|
258 |
+
return options["sd_model_checkpoint"]
|
259 |
+
except Exception as e:
|
260 |
+
app.state.config.ENABLED = False
|
261 |
+
raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(e))
|
262 |
+
|
263 |
+
|
264 |
+
class ImageConfigForm(BaseModel):
|
265 |
+
MODEL: str
|
266 |
+
IMAGE_SIZE: str
|
267 |
+
IMAGE_STEPS: int
|
268 |
+
|
269 |
+
|
270 |
+
@app.get("/image/config")
|
271 |
+
async def get_image_config(user=Depends(get_admin_user)):
|
272 |
+
return {
|
273 |
+
"MODEL": app.state.config.MODEL,
|
274 |
+
"IMAGE_SIZE": app.state.config.IMAGE_SIZE,
|
275 |
+
"IMAGE_STEPS": app.state.config.IMAGE_STEPS,
|
276 |
+
}
|
277 |
+
|
278 |
+
|
279 |
+
@app.post("/image/config/update")
|
280 |
+
async def update_image_config(form_data: ImageConfigForm, user=Depends(get_admin_user)):
|
281 |
+
|
282 |
+
set_image_model(form_data.MODEL)
|
283 |
+
|
284 |
+
pattern = r"^\d+x\d+$"
|
285 |
+
if re.match(pattern, form_data.IMAGE_SIZE):
|
286 |
+
app.state.config.IMAGE_SIZE = form_data.IMAGE_SIZE
|
287 |
+
else:
|
288 |
+
raise HTTPException(
|
289 |
+
status_code=400,
|
290 |
+
detail=ERROR_MESSAGES.INCORRECT_FORMAT(" (e.g., 512x512)."),
|
291 |
+
)
|
292 |
+
|
293 |
+
if form_data.IMAGE_STEPS >= 0:
|
294 |
+
app.state.config.IMAGE_STEPS = form_data.IMAGE_STEPS
|
295 |
+
else:
|
296 |
+
raise HTTPException(
|
297 |
+
status_code=400,
|
298 |
+
detail=ERROR_MESSAGES.INCORRECT_FORMAT(" (e.g., 50)."),
|
299 |
+
)
|
300 |
+
|
301 |
+
return {
|
302 |
+
"MODEL": app.state.config.MODEL,
|
303 |
+
"IMAGE_SIZE": app.state.config.IMAGE_SIZE,
|
304 |
+
"IMAGE_STEPS": app.state.config.IMAGE_STEPS,
|
305 |
+
}
|
306 |
+
|
307 |
+
|
308 |
+
@app.get("/models")
|
309 |
+
def get_models(user=Depends(get_verified_user)):
|
310 |
+
try:
|
311 |
+
if app.state.config.ENGINE == "openai":
|
312 |
+
return [
|
313 |
+
{"id": "dall-e-2", "name": "DALL·E 2"},
|
314 |
+
{"id": "dall-e-3", "name": "DALL·E 3"},
|
315 |
+
]
|
316 |
+
elif app.state.config.ENGINE == "comfyui":
|
317 |
+
# TODO - get models from comfyui
|
318 |
+
r = requests.get(url=f"{app.state.config.COMFYUI_BASE_URL}/object_info")
|
319 |
+
info = r.json()
|
320 |
+
|
321 |
+
workflow = json.loads(app.state.config.COMFYUI_WORKFLOW)
|
322 |
+
model_node_id = None
|
323 |
+
|
324 |
+
for node in app.state.config.COMFYUI_WORKFLOW_NODES:
|
325 |
+
if node["type"] == "model":
|
326 |
+
if node["node_ids"]:
|
327 |
+
model_node_id = node["node_ids"][0]
|
328 |
+
break
|
329 |
+
|
330 |
+
if model_node_id:
|
331 |
+
model_list_key = None
|
332 |
+
|
333 |
+
print(workflow[model_node_id]["class_type"])
|
334 |
+
for key in info[workflow[model_node_id]["class_type"]]["input"][
|
335 |
+
"required"
|
336 |
+
]:
|
337 |
+
if "_name" in key:
|
338 |
+
model_list_key = key
|
339 |
+
break
|
340 |
+
|
341 |
+
if model_list_key:
|
342 |
+
return list(
|
343 |
+
map(
|
344 |
+
lambda model: {"id": model, "name": model},
|
345 |
+
info[workflow[model_node_id]["class_type"]]["input"][
|
346 |
+
"required"
|
347 |
+
][model_list_key][0],
|
348 |
+
)
|
349 |
+
)
|
350 |
+
else:
|
351 |
+
return list(
|
352 |
+
map(
|
353 |
+
lambda model: {"id": model, "name": model},
|
354 |
+
info["CheckpointLoaderSimple"]["input"]["required"][
|
355 |
+
"ckpt_name"
|
356 |
+
][0],
|
357 |
+
)
|
358 |
+
)
|
359 |
+
elif (
|
360 |
+
app.state.config.ENGINE == "automatic1111" or app.state.config.ENGINE == ""
|
361 |
+
):
|
362 |
+
r = requests.get(
|
363 |
+
url=f"{app.state.config.AUTOMATIC1111_BASE_URL}/sdapi/v1/sd-models",
|
364 |
+
headers={"authorization": get_automatic1111_api_auth()},
|
365 |
+
)
|
366 |
+
models = r.json()
|
367 |
+
return list(
|
368 |
+
map(
|
369 |
+
lambda model: {"id": model["title"], "name": model["model_name"]},
|
370 |
+
models,
|
371 |
+
)
|
372 |
+
)
|
373 |
+
except Exception as e:
|
374 |
+
app.state.config.ENABLED = False
|
375 |
+
raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(e))
|
376 |
+
|
377 |
+
|
378 |
+
class GenerateImageForm(BaseModel):
|
379 |
+
model: Optional[str] = None
|
380 |
+
prompt: str
|
381 |
+
size: Optional[str] = None
|
382 |
+
n: int = 1
|
383 |
+
negative_prompt: Optional[str] = None
|
384 |
+
|
385 |
+
|
386 |
+
def save_b64_image(b64_str):
|
387 |
+
try:
|
388 |
+
image_id = str(uuid.uuid4())
|
389 |
+
|
390 |
+
if "," in b64_str:
|
391 |
+
header, encoded = b64_str.split(",", 1)
|
392 |
+
mime_type = header.split(";")[0]
|
393 |
+
|
394 |
+
img_data = base64.b64decode(encoded)
|
395 |
+
image_format = mimetypes.guess_extension(mime_type)
|
396 |
+
|
397 |
+
image_filename = f"{image_id}{image_format}"
|
398 |
+
file_path = IMAGE_CACHE_DIR / f"{image_filename}"
|
399 |
+
with open(file_path, "wb") as f:
|
400 |
+
f.write(img_data)
|
401 |
+
return image_filename
|
402 |
+
else:
|
403 |
+
image_filename = f"{image_id}.png"
|
404 |
+
file_path = IMAGE_CACHE_DIR.joinpath(image_filename)
|
405 |
+
|
406 |
+
img_data = base64.b64decode(b64_str)
|
407 |
+
|
408 |
+
# Write the image data to a file
|
409 |
+
with open(file_path, "wb") as f:
|
410 |
+
f.write(img_data)
|
411 |
+
return image_filename
|
412 |
+
|
413 |
+
except Exception as e:
|
414 |
+
log.exception(f"Error saving image: {e}")
|
415 |
+
return None
|
416 |
+
|
417 |
+
|
418 |
+
def save_url_image(url):
|
419 |
+
image_id = str(uuid.uuid4())
|
420 |
+
try:
|
421 |
+
r = requests.get(url)
|
422 |
+
r.raise_for_status()
|
423 |
+
if r.headers["content-type"].split("/")[0] == "image":
|
424 |
+
mime_type = r.headers["content-type"]
|
425 |
+
image_format = mimetypes.guess_extension(mime_type)
|
426 |
+
|
427 |
+
if not image_format:
|
428 |
+
raise ValueError("Could not determine image type from MIME type")
|
429 |
+
|
430 |
+
image_filename = f"{image_id}{image_format}"
|
431 |
+
|
432 |
+
file_path = IMAGE_CACHE_DIR.joinpath(f"{image_filename}")
|
433 |
+
with open(file_path, "wb") as image_file:
|
434 |
+
for chunk in r.iter_content(chunk_size=8192):
|
435 |
+
image_file.write(chunk)
|
436 |
+
return image_filename
|
437 |
+
else:
|
438 |
+
log.error("Url does not point to an image.")
|
439 |
+
return None
|
440 |
+
|
441 |
+
except Exception as e:
|
442 |
+
log.exception(f"Error saving image: {e}")
|
443 |
+
return None
|
444 |
+
|
445 |
+
|
446 |
+
@app.post("/generations")
|
447 |
+
async def image_generations(
|
448 |
+
form_data: GenerateImageForm,
|
449 |
+
user=Depends(get_verified_user),
|
450 |
+
):
|
451 |
+
width, height = tuple(map(int, app.state.config.IMAGE_SIZE.split("x")))
|
452 |
+
|
453 |
+
r = None
|
454 |
+
try:
|
455 |
+
if app.state.config.ENGINE == "openai":
|
456 |
+
headers = {}
|
457 |
+
headers["Authorization"] = f"Bearer {app.state.config.OPENAI_API_KEY}"
|
458 |
+
headers["Content-Type"] = "application/json"
|
459 |
+
|
460 |
+
data = {
|
461 |
+
"model": (
|
462 |
+
app.state.config.MODEL
|
463 |
+
if app.state.config.MODEL != ""
|
464 |
+
else "dall-e-2"
|
465 |
+
),
|
466 |
+
"prompt": form_data.prompt,
|
467 |
+
"n": form_data.n,
|
468 |
+
"size": (
|
469 |
+
form_data.size if form_data.size else app.state.config.IMAGE_SIZE
|
470 |
+
),
|
471 |
+
"response_format": "b64_json",
|
472 |
+
}
|
473 |
+
|
474 |
+
# Use asyncio.to_thread for the requests.post call
|
475 |
+
r = await asyncio.to_thread(
|
476 |
+
requests.post,
|
477 |
+
url=f"{app.state.config.OPENAI_API_BASE_URL}/images/generations",
|
478 |
+
json=data,
|
479 |
+
headers=headers,
|
480 |
+
)
|
481 |
+
|
482 |
+
r.raise_for_status()
|
483 |
+
res = r.json()
|
484 |
+
|
485 |
+
images = []
|
486 |
+
|
487 |
+
for image in res["data"]:
|
488 |
+
image_filename = save_b64_image(image["b64_json"])
|
489 |
+
images.append({"url": f"/cache/image/generations/{image_filename}"})
|
490 |
+
file_body_path = IMAGE_CACHE_DIR.joinpath(f"{image_filename}.json")
|
491 |
+
|
492 |
+
with open(file_body_path, "w") as f:
|
493 |
+
json.dump(data, f)
|
494 |
+
|
495 |
+
return images
|
496 |
+
|
497 |
+
elif app.state.config.ENGINE == "comfyui":
|
498 |
+
data = {
|
499 |
+
"prompt": form_data.prompt,
|
500 |
+
"width": width,
|
501 |
+
"height": height,
|
502 |
+
"n": form_data.n,
|
503 |
+
}
|
504 |
+
|
505 |
+
if app.state.config.IMAGE_STEPS is not None:
|
506 |
+
data["steps"] = app.state.config.IMAGE_STEPS
|
507 |
+
|
508 |
+
if form_data.negative_prompt is not None:
|
509 |
+
data["negative_prompt"] = form_data.negative_prompt
|
510 |
+
|
511 |
+
form_data = ComfyUIGenerateImageForm(
|
512 |
+
**{
|
513 |
+
"workflow": ComfyUIWorkflow(
|
514 |
+
**{
|
515 |
+
"workflow": app.state.config.COMFYUI_WORKFLOW,
|
516 |
+
"nodes": app.state.config.COMFYUI_WORKFLOW_NODES,
|
517 |
+
}
|
518 |
+
),
|
519 |
+
**data,
|
520 |
+
}
|
521 |
+
)
|
522 |
+
res = await comfyui_generate_image(
|
523 |
+
app.state.config.MODEL,
|
524 |
+
form_data,
|
525 |
+
user.id,
|
526 |
+
app.state.config.COMFYUI_BASE_URL,
|
527 |
+
)
|
528 |
+
log.debug(f"res: {res}")
|
529 |
+
|
530 |
+
images = []
|
531 |
+
|
532 |
+
for image in res["data"]:
|
533 |
+
image_filename = save_url_image(image["url"])
|
534 |
+
images.append({"url": f"/cache/image/generations/{image_filename}"})
|
535 |
+
file_body_path = IMAGE_CACHE_DIR.joinpath(f"{image_filename}.json")
|
536 |
+
|
537 |
+
with open(file_body_path, "w") as f:
|
538 |
+
json.dump(form_data.model_dump(exclude_none=True), f)
|
539 |
+
|
540 |
+
log.debug(f"images: {images}")
|
541 |
+
return images
|
542 |
+
elif (
|
543 |
+
app.state.config.ENGINE == "automatic1111" or app.state.config.ENGINE == ""
|
544 |
+
):
|
545 |
+
if form_data.model:
|
546 |
+
set_image_model(form_data.model)
|
547 |
+
|
548 |
+
data = {
|
549 |
+
"prompt": form_data.prompt,
|
550 |
+
"batch_size": form_data.n,
|
551 |
+
"width": width,
|
552 |
+
"height": height,
|
553 |
+
}
|
554 |
+
|
555 |
+
if app.state.config.IMAGE_STEPS is not None:
|
556 |
+
data["steps"] = app.state.config.IMAGE_STEPS
|
557 |
+
|
558 |
+
if form_data.negative_prompt is not None:
|
559 |
+
data["negative_prompt"] = form_data.negative_prompt
|
560 |
+
|
561 |
+
if app.state.config.AUTOMATIC1111_CFG_SCALE:
|
562 |
+
data["cfg_scale"] = app.state.config.AUTOMATIC1111_CFG_SCALE
|
563 |
+
|
564 |
+
if app.state.config.AUTOMATIC1111_SAMPLER:
|
565 |
+
data["sampler_name"] = app.state.config.AUTOMATIC1111_SAMPLER
|
566 |
+
|
567 |
+
if app.state.config.AUTOMATIC1111_SCHEDULER:
|
568 |
+
data["scheduler"] = app.state.config.AUTOMATIC1111_SCHEDULER
|
569 |
+
|
570 |
+
# Use asyncio.to_thread for the requests.post call
|
571 |
+
r = await asyncio.to_thread(
|
572 |
+
requests.post,
|
573 |
+
url=f"{app.state.config.AUTOMATIC1111_BASE_URL}/sdapi/v1/txt2img",
|
574 |
+
json=data,
|
575 |
+
headers={"authorization": get_automatic1111_api_auth()},
|
576 |
+
)
|
577 |
+
|
578 |
+
res = r.json()
|
579 |
+
log.debug(f"res: {res}")
|
580 |
+
|
581 |
+
images = []
|
582 |
+
|
583 |
+
for image in res["images"]:
|
584 |
+
image_filename = save_b64_image(image)
|
585 |
+
images.append({"url": f"/cache/image/generations/{image_filename}"})
|
586 |
+
file_body_path = IMAGE_CACHE_DIR.joinpath(f"{image_filename}.json")
|
587 |
+
|
588 |
+
with open(file_body_path, "w") as f:
|
589 |
+
json.dump({**data, "info": res["info"]}, f)
|
590 |
+
|
591 |
+
return images
|
592 |
+
except Exception as e:
|
593 |
+
error = e
|
594 |
+
if r != None:
|
595 |
+
data = r.json()
|
596 |
+
if "error" in data:
|
597 |
+
error = data["error"]["message"]
|
598 |
+
raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(error))
|
backend/open_webui/apps/images/utils/comfyui.py
ADDED
@@ -0,0 +1,186 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import asyncio
|
2 |
+
import json
|
3 |
+
import logging
|
4 |
+
import random
|
5 |
+
import urllib.parse
|
6 |
+
import urllib.request
|
7 |
+
from typing import Optional
|
8 |
+
|
9 |
+
import websocket # NOTE: websocket-client (https://github.com/websocket-client/websocket-client)
|
10 |
+
from open_webui.env import SRC_LOG_LEVELS
|
11 |
+
from pydantic import BaseModel
|
12 |
+
|
13 |
+
log = logging.getLogger(__name__)
|
14 |
+
log.setLevel(SRC_LOG_LEVELS["COMFYUI"])
|
15 |
+
|
16 |
+
default_headers = {"User-Agent": "Mozilla/5.0"}
|
17 |
+
|
18 |
+
|
19 |
+
def queue_prompt(prompt, client_id, base_url):
|
20 |
+
log.info("queue_prompt")
|
21 |
+
p = {"prompt": prompt, "client_id": client_id}
|
22 |
+
data = json.dumps(p).encode("utf-8")
|
23 |
+
log.debug(f"queue_prompt data: {data}")
|
24 |
+
try:
|
25 |
+
req = urllib.request.Request(
|
26 |
+
f"{base_url}/prompt", data=data, headers=default_headers
|
27 |
+
)
|
28 |
+
response = urllib.request.urlopen(req).read()
|
29 |
+
return json.loads(response)
|
30 |
+
except Exception as e:
|
31 |
+
log.exception(f"Error while queuing prompt: {e}")
|
32 |
+
raise e
|
33 |
+
|
34 |
+
|
35 |
+
def get_image(filename, subfolder, folder_type, base_url):
|
36 |
+
log.info("get_image")
|
37 |
+
data = {"filename": filename, "subfolder": subfolder, "type": folder_type}
|
38 |
+
url_values = urllib.parse.urlencode(data)
|
39 |
+
req = urllib.request.Request(
|
40 |
+
f"{base_url}/view?{url_values}", headers=default_headers
|
41 |
+
)
|
42 |
+
with urllib.request.urlopen(req) as response:
|
43 |
+
return response.read()
|
44 |
+
|
45 |
+
|
46 |
+
def get_image_url(filename, subfolder, folder_type, base_url):
|
47 |
+
log.info("get_image")
|
48 |
+
data = {"filename": filename, "subfolder": subfolder, "type": folder_type}
|
49 |
+
url_values = urllib.parse.urlencode(data)
|
50 |
+
return f"{base_url}/view?{url_values}"
|
51 |
+
|
52 |
+
|
53 |
+
def get_history(prompt_id, base_url):
|
54 |
+
log.info("get_history")
|
55 |
+
|
56 |
+
req = urllib.request.Request(
|
57 |
+
f"{base_url}/history/{prompt_id}", headers=default_headers
|
58 |
+
)
|
59 |
+
with urllib.request.urlopen(req) as response:
|
60 |
+
return json.loads(response.read())
|
61 |
+
|
62 |
+
|
63 |
+
def get_images(ws, prompt, client_id, base_url):
|
64 |
+
prompt_id = queue_prompt(prompt, client_id, base_url)["prompt_id"]
|
65 |
+
output_images = []
|
66 |
+
while True:
|
67 |
+
out = ws.recv()
|
68 |
+
if isinstance(out, str):
|
69 |
+
message = json.loads(out)
|
70 |
+
if message["type"] == "executing":
|
71 |
+
data = message["data"]
|
72 |
+
if data["node"] is None and data["prompt_id"] == prompt_id:
|
73 |
+
break # Execution is done
|
74 |
+
else:
|
75 |
+
continue # previews are binary data
|
76 |
+
|
77 |
+
history = get_history(prompt_id, base_url)[prompt_id]
|
78 |
+
for o in history["outputs"]:
|
79 |
+
for node_id in history["outputs"]:
|
80 |
+
node_output = history["outputs"][node_id]
|
81 |
+
if "images" in node_output:
|
82 |
+
for image in node_output["images"]:
|
83 |
+
url = get_image_url(
|
84 |
+
image["filename"], image["subfolder"], image["type"], base_url
|
85 |
+
)
|
86 |
+
output_images.append({"url": url})
|
87 |
+
return {"data": output_images}
|
88 |
+
|
89 |
+
|
90 |
+
class ComfyUINodeInput(BaseModel):
|
91 |
+
type: Optional[str] = None
|
92 |
+
node_ids: list[str] = []
|
93 |
+
key: Optional[str] = "text"
|
94 |
+
value: Optional[str] = None
|
95 |
+
|
96 |
+
|
97 |
+
class ComfyUIWorkflow(BaseModel):
|
98 |
+
workflow: str
|
99 |
+
nodes: list[ComfyUINodeInput]
|
100 |
+
|
101 |
+
|
102 |
+
class ComfyUIGenerateImageForm(BaseModel):
|
103 |
+
workflow: ComfyUIWorkflow
|
104 |
+
|
105 |
+
prompt: str
|
106 |
+
negative_prompt: Optional[str] = None
|
107 |
+
width: int
|
108 |
+
height: int
|
109 |
+
n: int = 1
|
110 |
+
|
111 |
+
steps: Optional[int] = None
|
112 |
+
seed: Optional[int] = None
|
113 |
+
|
114 |
+
|
115 |
+
async def comfyui_generate_image(
|
116 |
+
model: str, payload: ComfyUIGenerateImageForm, client_id, base_url
|
117 |
+
):
|
118 |
+
ws_url = base_url.replace("http://", "ws://").replace("https://", "wss://")
|
119 |
+
workflow = json.loads(payload.workflow.workflow)
|
120 |
+
|
121 |
+
for node in payload.workflow.nodes:
|
122 |
+
if node.type:
|
123 |
+
if node.type == "model":
|
124 |
+
for node_id in node.node_ids:
|
125 |
+
workflow[node_id]["inputs"][node.key] = model
|
126 |
+
elif node.type == "prompt":
|
127 |
+
for node_id in node.node_ids:
|
128 |
+
workflow[node_id]["inputs"][
|
129 |
+
node.key if node.key else "text"
|
130 |
+
] = payload.prompt
|
131 |
+
elif node.type == "negative_prompt":
|
132 |
+
for node_id in node.node_ids:
|
133 |
+
workflow[node_id]["inputs"][
|
134 |
+
node.key if node.key else "text"
|
135 |
+
] = payload.negative_prompt
|
136 |
+
elif node.type == "width":
|
137 |
+
for node_id in node.node_ids:
|
138 |
+
workflow[node_id]["inputs"][
|
139 |
+
node.key if node.key else "width"
|
140 |
+
] = payload.width
|
141 |
+
elif node.type == "height":
|
142 |
+
for node_id in node.node_ids:
|
143 |
+
workflow[node_id]["inputs"][
|
144 |
+
node.key if node.key else "height"
|
145 |
+
] = payload.height
|
146 |
+
elif node.type == "n":
|
147 |
+
for node_id in node.node_ids:
|
148 |
+
workflow[node_id]["inputs"][
|
149 |
+
node.key if node.key else "batch_size"
|
150 |
+
] = payload.n
|
151 |
+
elif node.type == "steps":
|
152 |
+
for node_id in node.node_ids:
|
153 |
+
workflow[node_id]["inputs"][
|
154 |
+
node.key if node.key else "steps"
|
155 |
+
] = payload.steps
|
156 |
+
elif node.type == "seed":
|
157 |
+
seed = (
|
158 |
+
payload.seed
|
159 |
+
if payload.seed
|
160 |
+
else random.randint(0, 18446744073709551614)
|
161 |
+
)
|
162 |
+
for node_id in node.node_ids:
|
163 |
+
workflow[node_id]["inputs"][node.key] = seed
|
164 |
+
else:
|
165 |
+
for node_id in node.node_ids:
|
166 |
+
workflow[node_id]["inputs"][node.key] = node.value
|
167 |
+
|
168 |
+
try:
|
169 |
+
ws = websocket.WebSocket()
|
170 |
+
ws.connect(f"{ws_url}/ws?clientId={client_id}")
|
171 |
+
log.info("WebSocket connection established.")
|
172 |
+
except Exception as e:
|
173 |
+
log.exception(f"Failed to connect to WebSocket server: {e}")
|
174 |
+
return None
|
175 |
+
|
176 |
+
try:
|
177 |
+
log.info("Sending workflow to WebSocket server.")
|
178 |
+
log.info(f"Workflow: {workflow}")
|
179 |
+
images = await asyncio.to_thread(get_images, ws, workflow, client_id, base_url)
|
180 |
+
except Exception as e:
|
181 |
+
log.exception(f"Error while receiving images: {e}")
|
182 |
+
images = None
|
183 |
+
|
184 |
+
ws.close()
|
185 |
+
|
186 |
+
return images
|
backend/open_webui/apps/ollama/main.py
ADDED
@@ -0,0 +1,1123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import asyncio
|
2 |
+
import json
|
3 |
+
import logging
|
4 |
+
import os
|
5 |
+
import random
|
6 |
+
import re
|
7 |
+
import time
|
8 |
+
from typing import Optional, Union
|
9 |
+
from urllib.parse import urlparse
|
10 |
+
|
11 |
+
import aiohttp
|
12 |
+
import requests
|
13 |
+
from open_webui.apps.webui.models.models import Models
|
14 |
+
from open_webui.config import (
|
15 |
+
CORS_ALLOW_ORIGIN,
|
16 |
+
ENABLE_MODEL_FILTER,
|
17 |
+
ENABLE_OLLAMA_API,
|
18 |
+
MODEL_FILTER_LIST,
|
19 |
+
OLLAMA_BASE_URLS,
|
20 |
+
UPLOAD_DIR,
|
21 |
+
AppConfig,
|
22 |
+
)
|
23 |
+
from open_webui.env import AIOHTTP_CLIENT_TIMEOUT
|
24 |
+
|
25 |
+
|
26 |
+
from open_webui.constants import ERROR_MESSAGES
|
27 |
+
from open_webui.env import ENV, SRC_LOG_LEVELS
|
28 |
+
from fastapi import Depends, FastAPI, File, HTTPException, Request, UploadFile
|
29 |
+
from fastapi.middleware.cors import CORSMiddleware
|
30 |
+
from fastapi.responses import StreamingResponse
|
31 |
+
from pydantic import BaseModel, ConfigDict
|
32 |
+
from starlette.background import BackgroundTask
|
33 |
+
|
34 |
+
|
35 |
+
from open_webui.utils.misc import (
|
36 |
+
calculate_sha256,
|
37 |
+
)
|
38 |
+
from open_webui.utils.payload import (
|
39 |
+
apply_model_params_to_body_ollama,
|
40 |
+
apply_model_params_to_body_openai,
|
41 |
+
apply_model_system_prompt_to_body,
|
42 |
+
)
|
43 |
+
from open_webui.utils.utils import get_admin_user, get_verified_user
|
44 |
+
|
45 |
+
log = logging.getLogger(__name__)
|
46 |
+
log.setLevel(SRC_LOG_LEVELS["OLLAMA"])
|
47 |
+
|
48 |
+
|
49 |
+
app = FastAPI(docs_url="/docs" if ENV == "dev" else None, openapi_url="/openapi.json" if ENV == "dev" else None, redoc_url=None)
|
50 |
+
|
51 |
+
app.add_middleware(
|
52 |
+
CORSMiddleware,
|
53 |
+
allow_origins=CORS_ALLOW_ORIGIN,
|
54 |
+
allow_credentials=True,
|
55 |
+
allow_methods=["*"],
|
56 |
+
allow_headers=["*"],
|
57 |
+
)
|
58 |
+
|
59 |
+
app.state.config = AppConfig()
|
60 |
+
|
61 |
+
app.state.config.ENABLE_MODEL_FILTER = ENABLE_MODEL_FILTER
|
62 |
+
app.state.config.MODEL_FILTER_LIST = MODEL_FILTER_LIST
|
63 |
+
|
64 |
+
app.state.config.ENABLE_OLLAMA_API = ENABLE_OLLAMA_API
|
65 |
+
app.state.config.OLLAMA_BASE_URLS = OLLAMA_BASE_URLS
|
66 |
+
app.state.MODELS = {}
|
67 |
+
|
68 |
+
|
69 |
+
# TODO: Implement a more intelligent load balancing mechanism for distributing requests among multiple backend instances.
|
70 |
+
# Current implementation uses a simple round-robin approach (random.choice). Consider incorporating algorithms like weighted round-robin,
|
71 |
+
# least connections, or least response time for better resource utilization and performance optimization.
|
72 |
+
|
73 |
+
|
74 |
+
@app.middleware("http")
|
75 |
+
async def check_url(request: Request, call_next):
|
76 |
+
if len(app.state.MODELS) == 0:
|
77 |
+
await get_all_models()
|
78 |
+
else:
|
79 |
+
pass
|
80 |
+
|
81 |
+
response = await call_next(request)
|
82 |
+
return response
|
83 |
+
|
84 |
+
|
85 |
+
@app.head("/")
|
86 |
+
@app.get("/")
|
87 |
+
async def get_status():
|
88 |
+
return {"status": True}
|
89 |
+
|
90 |
+
|
91 |
+
@app.get("/config")
|
92 |
+
async def get_config(user=Depends(get_admin_user)):
|
93 |
+
return {"ENABLE_OLLAMA_API": app.state.config.ENABLE_OLLAMA_API}
|
94 |
+
|
95 |
+
|
96 |
+
class OllamaConfigForm(BaseModel):
|
97 |
+
enable_ollama_api: Optional[bool] = None
|
98 |
+
|
99 |
+
|
100 |
+
@app.post("/config/update")
|
101 |
+
async def update_config(form_data: OllamaConfigForm, user=Depends(get_admin_user)):
|
102 |
+
app.state.config.ENABLE_OLLAMA_API = form_data.enable_ollama_api
|
103 |
+
return {"ENABLE_OLLAMA_API": app.state.config.ENABLE_OLLAMA_API}
|
104 |
+
|
105 |
+
|
106 |
+
@app.get("/urls")
|
107 |
+
async def get_ollama_api_urls(user=Depends(get_admin_user)):
|
108 |
+
return {"OLLAMA_BASE_URLS": app.state.config.OLLAMA_BASE_URLS}
|
109 |
+
|
110 |
+
|
111 |
+
class UrlUpdateForm(BaseModel):
|
112 |
+
urls: list[str]
|
113 |
+
|
114 |
+
|
115 |
+
@app.post("/urls/update")
|
116 |
+
async def update_ollama_api_url(form_data: UrlUpdateForm, user=Depends(get_admin_user)):
|
117 |
+
app.state.config.OLLAMA_BASE_URLS = form_data.urls
|
118 |
+
|
119 |
+
log.info(f"app.state.config.OLLAMA_BASE_URLS: {app.state.config.OLLAMA_BASE_URLS}")
|
120 |
+
return {"OLLAMA_BASE_URLS": app.state.config.OLLAMA_BASE_URLS}
|
121 |
+
|
122 |
+
|
123 |
+
async def fetch_url(url):
|
124 |
+
timeout = aiohttp.ClientTimeout(total=3)
|
125 |
+
try:
|
126 |
+
async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
|
127 |
+
async with session.get(url) as response:
|
128 |
+
return await response.json()
|
129 |
+
except Exception as e:
|
130 |
+
# Handle connection error here
|
131 |
+
log.error(f"Connection error: {e}")
|
132 |
+
return None
|
133 |
+
|
134 |
+
|
135 |
+
async def cleanup_response(
|
136 |
+
response: Optional[aiohttp.ClientResponse],
|
137 |
+
session: Optional[aiohttp.ClientSession],
|
138 |
+
):
|
139 |
+
if response:
|
140 |
+
response.close()
|
141 |
+
if session:
|
142 |
+
await session.close()
|
143 |
+
|
144 |
+
|
145 |
+
async def post_streaming_url(
|
146 |
+
url: str, payload: Union[str, bytes], stream: bool = True, content_type=None
|
147 |
+
):
|
148 |
+
r = None
|
149 |
+
try:
|
150 |
+
session = aiohttp.ClientSession(
|
151 |
+
trust_env=True, timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT)
|
152 |
+
)
|
153 |
+
r = await session.post(
|
154 |
+
url,
|
155 |
+
data=payload,
|
156 |
+
headers={"Content-Type": "application/json"},
|
157 |
+
)
|
158 |
+
r.raise_for_status()
|
159 |
+
|
160 |
+
if stream:
|
161 |
+
headers = dict(r.headers)
|
162 |
+
if content_type:
|
163 |
+
headers["Content-Type"] = content_type
|
164 |
+
return StreamingResponse(
|
165 |
+
r.content,
|
166 |
+
status_code=r.status,
|
167 |
+
headers=headers,
|
168 |
+
background=BackgroundTask(
|
169 |
+
cleanup_response, response=r, session=session
|
170 |
+
),
|
171 |
+
)
|
172 |
+
else:
|
173 |
+
res = await r.json()
|
174 |
+
await cleanup_response(r, session)
|
175 |
+
return res
|
176 |
+
|
177 |
+
except Exception as e:
|
178 |
+
error_detail = "Open WebUI: Server Connection Error"
|
179 |
+
if r is not None:
|
180 |
+
try:
|
181 |
+
res = await r.json()
|
182 |
+
if "error" in res:
|
183 |
+
error_detail = f"Ollama: {res['error']}"
|
184 |
+
except Exception:
|
185 |
+
error_detail = f"Ollama: {e}"
|
186 |
+
|
187 |
+
raise HTTPException(
|
188 |
+
status_code=r.status if r else 500,
|
189 |
+
detail=error_detail,
|
190 |
+
)
|
191 |
+
|
192 |
+
|
193 |
+
def merge_models_lists(model_lists):
|
194 |
+
merged_models = {}
|
195 |
+
|
196 |
+
for idx, model_list in enumerate(model_lists):
|
197 |
+
if model_list is not None:
|
198 |
+
for model in model_list:
|
199 |
+
digest = model["digest"]
|
200 |
+
if digest not in merged_models:
|
201 |
+
model["urls"] = [idx]
|
202 |
+
merged_models[digest] = model
|
203 |
+
else:
|
204 |
+
merged_models[digest]["urls"].append(idx)
|
205 |
+
|
206 |
+
return list(merged_models.values())
|
207 |
+
|
208 |
+
|
209 |
+
async def get_all_models():
|
210 |
+
log.info("get_all_models()")
|
211 |
+
|
212 |
+
if app.state.config.ENABLE_OLLAMA_API:
|
213 |
+
tasks = [
|
214 |
+
fetch_url(f"{url}/api/tags") for url in app.state.config.OLLAMA_BASE_URLS
|
215 |
+
]
|
216 |
+
responses = await asyncio.gather(*tasks)
|
217 |
+
|
218 |
+
models = {
|
219 |
+
"models": merge_models_lists(
|
220 |
+
map(
|
221 |
+
lambda response: response["models"] if response else None, responses
|
222 |
+
)
|
223 |
+
)
|
224 |
+
}
|
225 |
+
|
226 |
+
else:
|
227 |
+
models = {"models": []}
|
228 |
+
|
229 |
+
app.state.MODELS = {model["model"]: model for model in models["models"]}
|
230 |
+
|
231 |
+
return models
|
232 |
+
|
233 |
+
|
234 |
+
@app.get("/api/tags")
|
235 |
+
@app.get("/api/tags/{url_idx}")
|
236 |
+
async def get_ollama_tags(
|
237 |
+
url_idx: Optional[int] = None, user=Depends(get_verified_user)
|
238 |
+
):
|
239 |
+
if url_idx is None:
|
240 |
+
models = await get_all_models()
|
241 |
+
|
242 |
+
if app.state.config.ENABLE_MODEL_FILTER:
|
243 |
+
if user.role == "user":
|
244 |
+
models["models"] = list(
|
245 |
+
filter(
|
246 |
+
lambda model: model["name"]
|
247 |
+
in app.state.config.MODEL_FILTER_LIST,
|
248 |
+
models["models"],
|
249 |
+
)
|
250 |
+
)
|
251 |
+
return models
|
252 |
+
return models
|
253 |
+
else:
|
254 |
+
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
|
255 |
+
|
256 |
+
r = None
|
257 |
+
try:
|
258 |
+
r = requests.request(method="GET", url=f"{url}/api/tags")
|
259 |
+
r.raise_for_status()
|
260 |
+
|
261 |
+
return r.json()
|
262 |
+
except Exception as e:
|
263 |
+
log.exception(e)
|
264 |
+
error_detail = "Open WebUI: Server Connection Error"
|
265 |
+
if r is not None:
|
266 |
+
try:
|
267 |
+
res = r.json()
|
268 |
+
if "error" in res:
|
269 |
+
error_detail = f"Ollama: {res['error']}"
|
270 |
+
except Exception:
|
271 |
+
error_detail = f"Ollama: {e}"
|
272 |
+
|
273 |
+
raise HTTPException(
|
274 |
+
status_code=r.status_code if r else 500,
|
275 |
+
detail=error_detail,
|
276 |
+
)
|
277 |
+
|
278 |
+
|
279 |
+
@app.get("/api/version")
|
280 |
+
@app.get("/api/version/{url_idx}")
|
281 |
+
async def get_ollama_versions(url_idx: Optional[int] = None):
|
282 |
+
if app.state.config.ENABLE_OLLAMA_API:
|
283 |
+
if url_idx is None:
|
284 |
+
# returns lowest version
|
285 |
+
tasks = [
|
286 |
+
fetch_url(f"{url}/api/version")
|
287 |
+
for url in app.state.config.OLLAMA_BASE_URLS
|
288 |
+
]
|
289 |
+
responses = await asyncio.gather(*tasks)
|
290 |
+
responses = list(filter(lambda x: x is not None, responses))
|
291 |
+
|
292 |
+
if len(responses) > 0:
|
293 |
+
lowest_version = min(
|
294 |
+
responses,
|
295 |
+
key=lambda x: tuple(
|
296 |
+
map(int, re.sub(r"^v|-.*", "", x["version"]).split("."))
|
297 |
+
),
|
298 |
+
)
|
299 |
+
|
300 |
+
return {"version": lowest_version["version"]}
|
301 |
+
else:
|
302 |
+
raise HTTPException(
|
303 |
+
status_code=500,
|
304 |
+
detail=ERROR_MESSAGES.OLLAMA_NOT_FOUND,
|
305 |
+
)
|
306 |
+
else:
|
307 |
+
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
|
308 |
+
|
309 |
+
r = None
|
310 |
+
try:
|
311 |
+
r = requests.request(method="GET", url=f"{url}/api/version")
|
312 |
+
r.raise_for_status()
|
313 |
+
|
314 |
+
return r.json()
|
315 |
+
except Exception as e:
|
316 |
+
log.exception(e)
|
317 |
+
error_detail = "Open WebUI: Server Connection Error"
|
318 |
+
if r is not None:
|
319 |
+
try:
|
320 |
+
res = r.json()
|
321 |
+
if "error" in res:
|
322 |
+
error_detail = f"Ollama: {res['error']}"
|
323 |
+
except Exception:
|
324 |
+
error_detail = f"Ollama: {e}"
|
325 |
+
|
326 |
+
raise HTTPException(
|
327 |
+
status_code=r.status_code if r else 500,
|
328 |
+
detail=error_detail,
|
329 |
+
)
|
330 |
+
else:
|
331 |
+
return {"version": False}
|
332 |
+
|
333 |
+
|
334 |
+
class ModelNameForm(BaseModel):
|
335 |
+
name: str
|
336 |
+
|
337 |
+
|
338 |
+
@app.post("/api/pull")
|
339 |
+
@app.post("/api/pull/{url_idx}")
|
340 |
+
async def pull_model(
|
341 |
+
form_data: ModelNameForm, url_idx: int = 0, user=Depends(get_admin_user)
|
342 |
+
):
|
343 |
+
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
|
344 |
+
log.info(f"url: {url}")
|
345 |
+
|
346 |
+
# Admin should be able to pull models from any source
|
347 |
+
payload = {**form_data.model_dump(exclude_none=True), "insecure": True}
|
348 |
+
|
349 |
+
return await post_streaming_url(f"{url}/api/pull", json.dumps(payload))
|
350 |
+
|
351 |
+
|
352 |
+
class PushModelForm(BaseModel):
|
353 |
+
name: str
|
354 |
+
insecure: Optional[bool] = None
|
355 |
+
stream: Optional[bool] = None
|
356 |
+
|
357 |
+
|
358 |
+
@app.delete("/api/push")
|
359 |
+
@app.delete("/api/push/{url_idx}")
|
360 |
+
async def push_model(
|
361 |
+
form_data: PushModelForm,
|
362 |
+
url_idx: Optional[int] = None,
|
363 |
+
user=Depends(get_admin_user),
|
364 |
+
):
|
365 |
+
if url_idx is None:
|
366 |
+
if form_data.name in app.state.MODELS:
|
367 |
+
url_idx = app.state.MODELS[form_data.name]["urls"][0]
|
368 |
+
else:
|
369 |
+
raise HTTPException(
|
370 |
+
status_code=400,
|
371 |
+
detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.name),
|
372 |
+
)
|
373 |
+
|
374 |
+
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
|
375 |
+
log.debug(f"url: {url}")
|
376 |
+
|
377 |
+
return await post_streaming_url(
|
378 |
+
f"{url}/api/push", form_data.model_dump_json(exclude_none=True).encode()
|
379 |
+
)
|
380 |
+
|
381 |
+
|
382 |
+
class CreateModelForm(BaseModel):
|
383 |
+
name: str
|
384 |
+
modelfile: Optional[str] = None
|
385 |
+
stream: Optional[bool] = None
|
386 |
+
path: Optional[str] = None
|
387 |
+
|
388 |
+
|
389 |
+
@app.post("/api/create")
|
390 |
+
@app.post("/api/create/{url_idx}")
|
391 |
+
async def create_model(
|
392 |
+
form_data: CreateModelForm, url_idx: int = 0, user=Depends(get_admin_user)
|
393 |
+
):
|
394 |
+
log.debug(f"form_data: {form_data}")
|
395 |
+
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
|
396 |
+
log.info(f"url: {url}")
|
397 |
+
|
398 |
+
return await post_streaming_url(
|
399 |
+
f"{url}/api/create", form_data.model_dump_json(exclude_none=True).encode()
|
400 |
+
)
|
401 |
+
|
402 |
+
|
403 |
+
class CopyModelForm(BaseModel):
|
404 |
+
source: str
|
405 |
+
destination: str
|
406 |
+
|
407 |
+
|
408 |
+
@app.post("/api/copy")
|
409 |
+
@app.post("/api/copy/{url_idx}")
|
410 |
+
async def copy_model(
|
411 |
+
form_data: CopyModelForm,
|
412 |
+
url_idx: Optional[int] = None,
|
413 |
+
user=Depends(get_admin_user),
|
414 |
+
):
|
415 |
+
if url_idx is None:
|
416 |
+
if form_data.source in app.state.MODELS:
|
417 |
+
url_idx = app.state.MODELS[form_data.source]["urls"][0]
|
418 |
+
else:
|
419 |
+
raise HTTPException(
|
420 |
+
status_code=400,
|
421 |
+
detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.source),
|
422 |
+
)
|
423 |
+
|
424 |
+
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
|
425 |
+
log.info(f"url: {url}")
|
426 |
+
r = requests.request(
|
427 |
+
method="POST",
|
428 |
+
url=f"{url}/api/copy",
|
429 |
+
headers={"Content-Type": "application/json"},
|
430 |
+
data=form_data.model_dump_json(exclude_none=True).encode(),
|
431 |
+
)
|
432 |
+
|
433 |
+
try:
|
434 |
+
r.raise_for_status()
|
435 |
+
|
436 |
+
log.debug(f"r.text: {r.text}")
|
437 |
+
|
438 |
+
return True
|
439 |
+
except Exception as e:
|
440 |
+
log.exception(e)
|
441 |
+
error_detail = "Open WebUI: Server Connection Error"
|
442 |
+
if r is not None:
|
443 |
+
try:
|
444 |
+
res = r.json()
|
445 |
+
if "error" in res:
|
446 |
+
error_detail = f"Ollama: {res['error']}"
|
447 |
+
except Exception:
|
448 |
+
error_detail = f"Ollama: {e}"
|
449 |
+
|
450 |
+
raise HTTPException(
|
451 |
+
status_code=r.status_code if r else 500,
|
452 |
+
detail=error_detail,
|
453 |
+
)
|
454 |
+
|
455 |
+
|
456 |
+
@app.delete("/api/delete")
|
457 |
+
@app.delete("/api/delete/{url_idx}")
|
458 |
+
async def delete_model(
|
459 |
+
form_data: ModelNameForm,
|
460 |
+
url_idx: Optional[int] = None,
|
461 |
+
user=Depends(get_admin_user),
|
462 |
+
):
|
463 |
+
if url_idx is None:
|
464 |
+
if form_data.name in app.state.MODELS:
|
465 |
+
url_idx = app.state.MODELS[form_data.name]["urls"][0]
|
466 |
+
else:
|
467 |
+
raise HTTPException(
|
468 |
+
status_code=400,
|
469 |
+
detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.name),
|
470 |
+
)
|
471 |
+
|
472 |
+
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
|
473 |
+
log.info(f"url: {url}")
|
474 |
+
|
475 |
+
r = requests.request(
|
476 |
+
method="DELETE",
|
477 |
+
url=f"{url}/api/delete",
|
478 |
+
headers={"Content-Type": "application/json"},
|
479 |
+
data=form_data.model_dump_json(exclude_none=True).encode(),
|
480 |
+
)
|
481 |
+
try:
|
482 |
+
r.raise_for_status()
|
483 |
+
|
484 |
+
log.debug(f"r.text: {r.text}")
|
485 |
+
|
486 |
+
return True
|
487 |
+
except Exception as e:
|
488 |
+
log.exception(e)
|
489 |
+
error_detail = "Open WebUI: Server Connection Error"
|
490 |
+
if r is not None:
|
491 |
+
try:
|
492 |
+
res = r.json()
|
493 |
+
if "error" in res:
|
494 |
+
error_detail = f"Ollama: {res['error']}"
|
495 |
+
except Exception:
|
496 |
+
error_detail = f"Ollama: {e}"
|
497 |
+
|
498 |
+
raise HTTPException(
|
499 |
+
status_code=r.status_code if r else 500,
|
500 |
+
detail=error_detail,
|
501 |
+
)
|
502 |
+
|
503 |
+
|
504 |
+
@app.post("/api/show")
|
505 |
+
async def show_model_info(form_data: ModelNameForm, user=Depends(get_verified_user)):
|
506 |
+
if form_data.name not in app.state.MODELS:
|
507 |
+
raise HTTPException(
|
508 |
+
status_code=400,
|
509 |
+
detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.name),
|
510 |
+
)
|
511 |
+
|
512 |
+
url_idx = random.choice(app.state.MODELS[form_data.name]["urls"])
|
513 |
+
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
|
514 |
+
log.info(f"url: {url}")
|
515 |
+
|
516 |
+
r = requests.request(
|
517 |
+
method="POST",
|
518 |
+
url=f"{url}/api/show",
|
519 |
+
headers={"Content-Type": "application/json"},
|
520 |
+
data=form_data.model_dump_json(exclude_none=True).encode(),
|
521 |
+
)
|
522 |
+
try:
|
523 |
+
r.raise_for_status()
|
524 |
+
|
525 |
+
return r.json()
|
526 |
+
except Exception as e:
|
527 |
+
log.exception(e)
|
528 |
+
error_detail = "Open WebUI: Server Connection Error"
|
529 |
+
if r is not None:
|
530 |
+
try:
|
531 |
+
res = r.json()
|
532 |
+
if "error" in res:
|
533 |
+
error_detail = f"Ollama: {res['error']}"
|
534 |
+
except Exception:
|
535 |
+
error_detail = f"Ollama: {e}"
|
536 |
+
|
537 |
+
raise HTTPException(
|
538 |
+
status_code=r.status_code if r else 500,
|
539 |
+
detail=error_detail,
|
540 |
+
)
|
541 |
+
|
542 |
+
|
543 |
+
class GenerateEmbeddingsForm(BaseModel):
|
544 |
+
model: str
|
545 |
+
prompt: str
|
546 |
+
options: Optional[dict] = None
|
547 |
+
keep_alive: Optional[Union[int, str]] = None
|
548 |
+
|
549 |
+
|
550 |
+
class GenerateEmbedForm(BaseModel):
|
551 |
+
model: str
|
552 |
+
input: list[str] | str
|
553 |
+
truncate: Optional[bool] = None
|
554 |
+
options: Optional[dict] = None
|
555 |
+
keep_alive: Optional[Union[int, str]] = None
|
556 |
+
|
557 |
+
|
558 |
+
@app.post("/api/embed")
|
559 |
+
@app.post("/api/embed/{url_idx}")
|
560 |
+
async def generate_embeddings(
|
561 |
+
form_data: GenerateEmbedForm,
|
562 |
+
url_idx: Optional[int] = None,
|
563 |
+
user=Depends(get_verified_user),
|
564 |
+
):
|
565 |
+
return generate_ollama_batch_embeddings(form_data, url_idx)
|
566 |
+
|
567 |
+
|
568 |
+
@app.post("/api/embeddings")
|
569 |
+
@app.post("/api/embeddings/{url_idx}")
|
570 |
+
async def generate_embeddings(
|
571 |
+
form_data: GenerateEmbeddingsForm,
|
572 |
+
url_idx: Optional[int] = None,
|
573 |
+
user=Depends(get_verified_user),
|
574 |
+
):
|
575 |
+
return generate_ollama_embeddings(form_data=form_data, url_idx=url_idx)
|
576 |
+
|
577 |
+
|
578 |
+
def generate_ollama_embeddings(
|
579 |
+
form_data: GenerateEmbeddingsForm,
|
580 |
+
url_idx: Optional[int] = None,
|
581 |
+
):
|
582 |
+
log.info(f"generate_ollama_embeddings {form_data}")
|
583 |
+
|
584 |
+
if url_idx is None:
|
585 |
+
model = form_data.model
|
586 |
+
|
587 |
+
if ":" not in model:
|
588 |
+
model = f"{model}:latest"
|
589 |
+
|
590 |
+
if model in app.state.MODELS:
|
591 |
+
url_idx = random.choice(app.state.MODELS[model]["urls"])
|
592 |
+
else:
|
593 |
+
raise HTTPException(
|
594 |
+
status_code=400,
|
595 |
+
detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
|
596 |
+
)
|
597 |
+
|
598 |
+
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
|
599 |
+
log.info(f"url: {url}")
|
600 |
+
|
601 |
+
r = requests.request(
|
602 |
+
method="POST",
|
603 |
+
url=f"{url}/api/embeddings",
|
604 |
+
headers={"Content-Type": "application/json"},
|
605 |
+
data=form_data.model_dump_json(exclude_none=True).encode(),
|
606 |
+
)
|
607 |
+
try:
|
608 |
+
r.raise_for_status()
|
609 |
+
|
610 |
+
data = r.json()
|
611 |
+
|
612 |
+
log.info(f"generate_ollama_embeddings {data}")
|
613 |
+
|
614 |
+
if "embedding" in data:
|
615 |
+
return data
|
616 |
+
else:
|
617 |
+
raise Exception("Something went wrong :/")
|
618 |
+
except Exception as e:
|
619 |
+
log.exception(e)
|
620 |
+
error_detail = "Open WebUI: Server Connection Error"
|
621 |
+
if r is not None:
|
622 |
+
try:
|
623 |
+
res = r.json()
|
624 |
+
if "error" in res:
|
625 |
+
error_detail = f"Ollama: {res['error']}"
|
626 |
+
except Exception:
|
627 |
+
error_detail = f"Ollama: {e}"
|
628 |
+
|
629 |
+
raise HTTPException(
|
630 |
+
status_code=r.status_code if r else 500,
|
631 |
+
detail=error_detail,
|
632 |
+
)
|
633 |
+
|
634 |
+
|
635 |
+
def generate_ollama_batch_embeddings(
|
636 |
+
form_data: GenerateEmbedForm,
|
637 |
+
url_idx: Optional[int] = None,
|
638 |
+
):
|
639 |
+
log.info(f"generate_ollama_batch_embeddings {form_data}")
|
640 |
+
|
641 |
+
if url_idx is None:
|
642 |
+
model = form_data.model
|
643 |
+
|
644 |
+
if ":" not in model:
|
645 |
+
model = f"{model}:latest"
|
646 |
+
|
647 |
+
if model in app.state.MODELS:
|
648 |
+
url_idx = random.choice(app.state.MODELS[model]["urls"])
|
649 |
+
else:
|
650 |
+
raise HTTPException(
|
651 |
+
status_code=400,
|
652 |
+
detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
|
653 |
+
)
|
654 |
+
|
655 |
+
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
|
656 |
+
log.info(f"url: {url}")
|
657 |
+
|
658 |
+
r = requests.request(
|
659 |
+
method="POST",
|
660 |
+
url=f"{url}/api/embed",
|
661 |
+
headers={"Content-Type": "application/json"},
|
662 |
+
data=form_data.model_dump_json(exclude_none=True).encode(),
|
663 |
+
)
|
664 |
+
try:
|
665 |
+
r.raise_for_status()
|
666 |
+
|
667 |
+
data = r.json()
|
668 |
+
|
669 |
+
log.info(f"generate_ollama_batch_embeddings {data}")
|
670 |
+
|
671 |
+
if "embeddings" in data:
|
672 |
+
return data
|
673 |
+
else:
|
674 |
+
raise Exception("Something went wrong :/")
|
675 |
+
except Exception as e:
|
676 |
+
log.exception(e)
|
677 |
+
error_detail = "Open WebUI: Server Connection Error"
|
678 |
+
if r is not None:
|
679 |
+
try:
|
680 |
+
res = r.json()
|
681 |
+
if "error" in res:
|
682 |
+
error_detail = f"Ollama: {res['error']}"
|
683 |
+
except Exception:
|
684 |
+
error_detail = f"Ollama: {e}"
|
685 |
+
|
686 |
+
raise Exception(error_detail)
|
687 |
+
|
688 |
+
|
689 |
+
class GenerateCompletionForm(BaseModel):
|
690 |
+
model: str
|
691 |
+
prompt: str
|
692 |
+
images: Optional[list[str]] = None
|
693 |
+
format: Optional[str] = None
|
694 |
+
options: Optional[dict] = None
|
695 |
+
system: Optional[str] = None
|
696 |
+
template: Optional[str] = None
|
697 |
+
context: Optional[str] = None
|
698 |
+
stream: Optional[bool] = True
|
699 |
+
raw: Optional[bool] = None
|
700 |
+
keep_alive: Optional[Union[int, str]] = None
|
701 |
+
|
702 |
+
|
703 |
+
@app.post("/api/generate")
|
704 |
+
@app.post("/api/generate/{url_idx}")
|
705 |
+
async def generate_completion(
|
706 |
+
form_data: GenerateCompletionForm,
|
707 |
+
url_idx: Optional[int] = None,
|
708 |
+
user=Depends(get_verified_user),
|
709 |
+
):
|
710 |
+
if url_idx is None:
|
711 |
+
model = form_data.model
|
712 |
+
|
713 |
+
if ":" not in model:
|
714 |
+
model = f"{model}:latest"
|
715 |
+
|
716 |
+
if model in app.state.MODELS:
|
717 |
+
url_idx = random.choice(app.state.MODELS[model]["urls"])
|
718 |
+
else:
|
719 |
+
raise HTTPException(
|
720 |
+
status_code=400,
|
721 |
+
detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
|
722 |
+
)
|
723 |
+
|
724 |
+
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
|
725 |
+
log.info(f"url: {url}")
|
726 |
+
|
727 |
+
return await post_streaming_url(
|
728 |
+
f"{url}/api/generate", form_data.model_dump_json(exclude_none=True).encode()
|
729 |
+
)
|
730 |
+
|
731 |
+
|
732 |
+
class ChatMessage(BaseModel):
|
733 |
+
role: str
|
734 |
+
content: str
|
735 |
+
images: Optional[list[str]] = None
|
736 |
+
|
737 |
+
|
738 |
+
class GenerateChatCompletionForm(BaseModel):
|
739 |
+
model: str
|
740 |
+
messages: list[ChatMessage]
|
741 |
+
format: Optional[str] = None
|
742 |
+
options: Optional[dict] = None
|
743 |
+
template: Optional[str] = None
|
744 |
+
stream: Optional[bool] = True
|
745 |
+
keep_alive: Optional[Union[int, str]] = None
|
746 |
+
|
747 |
+
|
748 |
+
def get_ollama_url(url_idx: Optional[int], model: str):
|
749 |
+
if url_idx is None:
|
750 |
+
if model not in app.state.MODELS:
|
751 |
+
raise HTTPException(
|
752 |
+
status_code=400,
|
753 |
+
detail=ERROR_MESSAGES.MODEL_NOT_FOUND(model),
|
754 |
+
)
|
755 |
+
url_idx = random.choice(app.state.MODELS[model]["urls"])
|
756 |
+
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
|
757 |
+
return url
|
758 |
+
|
759 |
+
|
760 |
+
@app.post("/api/chat")
|
761 |
+
@app.post("/api/chat/{url_idx}")
|
762 |
+
async def generate_chat_completion(
|
763 |
+
form_data: GenerateChatCompletionForm,
|
764 |
+
url_idx: Optional[int] = None,
|
765 |
+
user=Depends(get_verified_user),
|
766 |
+
bypass_filter: Optional[bool] = False,
|
767 |
+
):
|
768 |
+
payload = {**form_data.model_dump(exclude_none=True)}
|
769 |
+
log.debug(f"generate_chat_completion() - 1.payload = {payload}")
|
770 |
+
if "metadata" in payload:
|
771 |
+
del payload["metadata"]
|
772 |
+
|
773 |
+
model_id = form_data.model
|
774 |
+
|
775 |
+
if not bypass_filter and app.state.config.ENABLE_MODEL_FILTER:
|
776 |
+
if user.role == "user" and model_id not in app.state.config.MODEL_FILTER_LIST:
|
777 |
+
raise HTTPException(
|
778 |
+
status_code=403,
|
779 |
+
detail="Model not found",
|
780 |
+
)
|
781 |
+
|
782 |
+
model_info = Models.get_model_by_id(model_id)
|
783 |
+
|
784 |
+
if model_info:
|
785 |
+
if model_info.base_model_id:
|
786 |
+
payload["model"] = model_info.base_model_id
|
787 |
+
|
788 |
+
params = model_info.params.model_dump()
|
789 |
+
|
790 |
+
if params:
|
791 |
+
if payload.get("options") is None:
|
792 |
+
payload["options"] = {}
|
793 |
+
|
794 |
+
payload["options"] = apply_model_params_to_body_ollama(
|
795 |
+
params, payload["options"]
|
796 |
+
)
|
797 |
+
payload = apply_model_system_prompt_to_body(params, payload, user)
|
798 |
+
|
799 |
+
if ":" not in payload["model"]:
|
800 |
+
payload["model"] = f"{payload['model']}:latest"
|
801 |
+
|
802 |
+
url = get_ollama_url(url_idx, payload["model"])
|
803 |
+
log.info(f"url: {url}")
|
804 |
+
log.debug(f"generate_chat_completion() - 2.payload = {payload}")
|
805 |
+
|
806 |
+
return await post_streaming_url(
|
807 |
+
f"{url}/api/chat",
|
808 |
+
json.dumps(payload),
|
809 |
+
stream=form_data.stream,
|
810 |
+
content_type="application/x-ndjson",
|
811 |
+
)
|
812 |
+
|
813 |
+
|
814 |
+
# TODO: we should update this part once Ollama supports other types
|
815 |
+
class OpenAIChatMessageContent(BaseModel):
|
816 |
+
type: str
|
817 |
+
model_config = ConfigDict(extra="allow")
|
818 |
+
|
819 |
+
|
820 |
+
class OpenAIChatMessage(BaseModel):
|
821 |
+
role: str
|
822 |
+
content: Union[str, OpenAIChatMessageContent]
|
823 |
+
|
824 |
+
model_config = ConfigDict(extra="allow")
|
825 |
+
|
826 |
+
|
827 |
+
class OpenAIChatCompletionForm(BaseModel):
|
828 |
+
model: str
|
829 |
+
messages: list[OpenAIChatMessage]
|
830 |
+
|
831 |
+
model_config = ConfigDict(extra="allow")
|
832 |
+
|
833 |
+
|
834 |
+
@app.post("/v1/chat/completions")
|
835 |
+
@app.post("/v1/chat/completions/{url_idx}")
|
836 |
+
async def generate_openai_chat_completion(
|
837 |
+
form_data: dict,
|
838 |
+
url_idx: Optional[int] = None,
|
839 |
+
user=Depends(get_verified_user),
|
840 |
+
):
|
841 |
+
completion_form = OpenAIChatCompletionForm(**form_data)
|
842 |
+
payload = {**completion_form.model_dump(exclude_none=True, exclude=["metadata"])}
|
843 |
+
if "metadata" in payload:
|
844 |
+
del payload["metadata"]
|
845 |
+
|
846 |
+
model_id = completion_form.model
|
847 |
+
|
848 |
+
if app.state.config.ENABLE_MODEL_FILTER:
|
849 |
+
if user.role == "user" and model_id not in app.state.config.MODEL_FILTER_LIST:
|
850 |
+
raise HTTPException(
|
851 |
+
status_code=403,
|
852 |
+
detail="Model not found",
|
853 |
+
)
|
854 |
+
|
855 |
+
model_info = Models.get_model_by_id(model_id)
|
856 |
+
|
857 |
+
if model_info:
|
858 |
+
if model_info.base_model_id:
|
859 |
+
payload["model"] = model_info.base_model_id
|
860 |
+
|
861 |
+
params = model_info.params.model_dump()
|
862 |
+
|
863 |
+
if params:
|
864 |
+
payload = apply_model_params_to_body_openai(params, payload)
|
865 |
+
payload = apply_model_system_prompt_to_body(params, payload, user)
|
866 |
+
|
867 |
+
if ":" not in payload["model"]:
|
868 |
+
payload["model"] = f"{payload['model']}:latest"
|
869 |
+
|
870 |
+
url = get_ollama_url(url_idx, payload["model"])
|
871 |
+
log.info(f"url: {url}")
|
872 |
+
|
873 |
+
return await post_streaming_url(
|
874 |
+
f"{url}/v1/chat/completions",
|
875 |
+
json.dumps(payload),
|
876 |
+
stream=payload.get("stream", False),
|
877 |
+
)
|
878 |
+
|
879 |
+
|
880 |
+
@app.get("/v1/models")
|
881 |
+
@app.get("/v1/models/{url_idx}")
|
882 |
+
async def get_openai_models(
|
883 |
+
url_idx: Optional[int] = None,
|
884 |
+
user=Depends(get_verified_user),
|
885 |
+
):
|
886 |
+
if url_idx is None:
|
887 |
+
models = await get_all_models()
|
888 |
+
|
889 |
+
if app.state.config.ENABLE_MODEL_FILTER:
|
890 |
+
if user.role == "user":
|
891 |
+
models["models"] = list(
|
892 |
+
filter(
|
893 |
+
lambda model: model["name"]
|
894 |
+
in app.state.config.MODEL_FILTER_LIST,
|
895 |
+
models["models"],
|
896 |
+
)
|
897 |
+
)
|
898 |
+
|
899 |
+
return {
|
900 |
+
"data": [
|
901 |
+
{
|
902 |
+
"id": model["model"],
|
903 |
+
"object": "model",
|
904 |
+
"created": int(time.time()),
|
905 |
+
"owned_by": "openai",
|
906 |
+
}
|
907 |
+
for model in models["models"]
|
908 |
+
],
|
909 |
+
"object": "list",
|
910 |
+
}
|
911 |
+
|
912 |
+
else:
|
913 |
+
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
|
914 |
+
try:
|
915 |
+
r = requests.request(method="GET", url=f"{url}/api/tags")
|
916 |
+
r.raise_for_status()
|
917 |
+
|
918 |
+
models = r.json()
|
919 |
+
|
920 |
+
return {
|
921 |
+
"data": [
|
922 |
+
{
|
923 |
+
"id": model["model"],
|
924 |
+
"object": "model",
|
925 |
+
"created": int(time.time()),
|
926 |
+
"owned_by": "openai",
|
927 |
+
}
|
928 |
+
for model in models["models"]
|
929 |
+
],
|
930 |
+
"object": "list",
|
931 |
+
}
|
932 |
+
|
933 |
+
except Exception as e:
|
934 |
+
log.exception(e)
|
935 |
+
error_detail = "Open WebUI: Server Connection Error"
|
936 |
+
if r is not None:
|
937 |
+
try:
|
938 |
+
res = r.json()
|
939 |
+
if "error" in res:
|
940 |
+
error_detail = f"Ollama: {res['error']}"
|
941 |
+
except Exception:
|
942 |
+
error_detail = f"Ollama: {e}"
|
943 |
+
|
944 |
+
raise HTTPException(
|
945 |
+
status_code=r.status_code if r else 500,
|
946 |
+
detail=error_detail,
|
947 |
+
)
|
948 |
+
|
949 |
+
|
950 |
+
class UrlForm(BaseModel):
|
951 |
+
url: str
|
952 |
+
|
953 |
+
|
954 |
+
class UploadBlobForm(BaseModel):
|
955 |
+
filename: str
|
956 |
+
|
957 |
+
|
958 |
+
def parse_huggingface_url(hf_url):
|
959 |
+
try:
|
960 |
+
# Parse the URL
|
961 |
+
parsed_url = urlparse(hf_url)
|
962 |
+
|
963 |
+
# Get the path and split it into components
|
964 |
+
path_components = parsed_url.path.split("/")
|
965 |
+
|
966 |
+
# Extract the desired output
|
967 |
+
model_file = path_components[-1]
|
968 |
+
|
969 |
+
return model_file
|
970 |
+
except ValueError:
|
971 |
+
return None
|
972 |
+
|
973 |
+
|
974 |
+
async def download_file_stream(
|
975 |
+
ollama_url, file_url, file_path, file_name, chunk_size=1024 * 1024
|
976 |
+
):
|
977 |
+
done = False
|
978 |
+
|
979 |
+
if os.path.exists(file_path):
|
980 |
+
current_size = os.path.getsize(file_path)
|
981 |
+
else:
|
982 |
+
current_size = 0
|
983 |
+
|
984 |
+
headers = {"Range": f"bytes={current_size}-"} if current_size > 0 else {}
|
985 |
+
|
986 |
+
timeout = aiohttp.ClientTimeout(total=600) # Set the timeout
|
987 |
+
|
988 |
+
async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
|
989 |
+
async with session.get(file_url, headers=headers) as response:
|
990 |
+
total_size = int(response.headers.get("content-length", 0)) + current_size
|
991 |
+
|
992 |
+
with open(file_path, "ab+") as file:
|
993 |
+
async for data in response.content.iter_chunked(chunk_size):
|
994 |
+
current_size += len(data)
|
995 |
+
file.write(data)
|
996 |
+
|
997 |
+
done = current_size == total_size
|
998 |
+
progress = round((current_size / total_size) * 100, 2)
|
999 |
+
|
1000 |
+
yield f'data: {{"progress": {progress}, "completed": {current_size}, "total": {total_size}}}\n\n'
|
1001 |
+
|
1002 |
+
if done:
|
1003 |
+
file.seek(0)
|
1004 |
+
hashed = calculate_sha256(file)
|
1005 |
+
file.seek(0)
|
1006 |
+
|
1007 |
+
url = f"{ollama_url}/api/blobs/sha256:{hashed}"
|
1008 |
+
response = requests.post(url, data=file)
|
1009 |
+
|
1010 |
+
if response.ok:
|
1011 |
+
res = {
|
1012 |
+
"done": done,
|
1013 |
+
"blob": f"sha256:{hashed}",
|
1014 |
+
"name": file_name,
|
1015 |
+
}
|
1016 |
+
os.remove(file_path)
|
1017 |
+
|
1018 |
+
yield f"data: {json.dumps(res)}\n\n"
|
1019 |
+
else:
|
1020 |
+
raise "Ollama: Could not create blob, Please try again."
|
1021 |
+
|
1022 |
+
|
1023 |
+
# url = "https://huggingface.co/TheBloke/stablelm-zephyr-3b-GGUF/resolve/main/stablelm-zephyr-3b.Q2_K.gguf"
|
1024 |
+
@app.post("/models/download")
|
1025 |
+
@app.post("/models/download/{url_idx}")
|
1026 |
+
async def download_model(
|
1027 |
+
form_data: UrlForm,
|
1028 |
+
url_idx: Optional[int] = None,
|
1029 |
+
user=Depends(get_admin_user),
|
1030 |
+
):
|
1031 |
+
allowed_hosts = ["https://huggingface.co/", "https://github.com/"]
|
1032 |
+
|
1033 |
+
if not any(form_data.url.startswith(host) for host in allowed_hosts):
|
1034 |
+
raise HTTPException(
|
1035 |
+
status_code=400,
|
1036 |
+
detail="Invalid file_url. Only URLs from allowed hosts are permitted.",
|
1037 |
+
)
|
1038 |
+
|
1039 |
+
if url_idx is None:
|
1040 |
+
url_idx = 0
|
1041 |
+
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
|
1042 |
+
|
1043 |
+
file_name = parse_huggingface_url(form_data.url)
|
1044 |
+
|
1045 |
+
if file_name:
|
1046 |
+
file_path = f"{UPLOAD_DIR}/{file_name}"
|
1047 |
+
|
1048 |
+
return StreamingResponse(
|
1049 |
+
download_file_stream(url, form_data.url, file_path, file_name),
|
1050 |
+
)
|
1051 |
+
else:
|
1052 |
+
return None
|
1053 |
+
|
1054 |
+
|
1055 |
+
@app.post("/models/upload")
|
1056 |
+
@app.post("/models/upload/{url_idx}")
|
1057 |
+
def upload_model(
|
1058 |
+
file: UploadFile = File(...),
|
1059 |
+
url_idx: Optional[int] = None,
|
1060 |
+
user=Depends(get_admin_user),
|
1061 |
+
):
|
1062 |
+
if url_idx is None:
|
1063 |
+
url_idx = 0
|
1064 |
+
ollama_url = app.state.config.OLLAMA_BASE_URLS[url_idx]
|
1065 |
+
|
1066 |
+
file_path = f"{UPLOAD_DIR}/{file.filename}"
|
1067 |
+
|
1068 |
+
# Save file in chunks
|
1069 |
+
with open(file_path, "wb+") as f:
|
1070 |
+
for chunk in file.file:
|
1071 |
+
f.write(chunk)
|
1072 |
+
|
1073 |
+
def file_process_stream():
|
1074 |
+
nonlocal ollama_url
|
1075 |
+
total_size = os.path.getsize(file_path)
|
1076 |
+
chunk_size = 1024 * 1024
|
1077 |
+
try:
|
1078 |
+
with open(file_path, "rb") as f:
|
1079 |
+
total = 0
|
1080 |
+
done = False
|
1081 |
+
|
1082 |
+
while not done:
|
1083 |
+
chunk = f.read(chunk_size)
|
1084 |
+
if not chunk:
|
1085 |
+
done = True
|
1086 |
+
continue
|
1087 |
+
|
1088 |
+
total += len(chunk)
|
1089 |
+
progress = round((total / total_size) * 100, 2)
|
1090 |
+
|
1091 |
+
res = {
|
1092 |
+
"progress": progress,
|
1093 |
+
"total": total_size,
|
1094 |
+
"completed": total,
|
1095 |
+
}
|
1096 |
+
yield f"data: {json.dumps(res)}\n\n"
|
1097 |
+
|
1098 |
+
if done:
|
1099 |
+
f.seek(0)
|
1100 |
+
hashed = calculate_sha256(f)
|
1101 |
+
f.seek(0)
|
1102 |
+
|
1103 |
+
url = f"{ollama_url}/api/blobs/sha256:{hashed}"
|
1104 |
+
response = requests.post(url, data=f)
|
1105 |
+
|
1106 |
+
if response.ok:
|
1107 |
+
res = {
|
1108 |
+
"done": done,
|
1109 |
+
"blob": f"sha256:{hashed}",
|
1110 |
+
"name": file.filename,
|
1111 |
+
}
|
1112 |
+
os.remove(file_path)
|
1113 |
+
yield f"data: {json.dumps(res)}\n\n"
|
1114 |
+
else:
|
1115 |
+
raise Exception(
|
1116 |
+
"Ollama: Could not create blob, Please try again."
|
1117 |
+
)
|
1118 |
+
|
1119 |
+
except Exception as e:
|
1120 |
+
res = {"error": str(e)}
|
1121 |
+
yield f"data: {json.dumps(res)}\n\n"
|
1122 |
+
|
1123 |
+
return StreamingResponse(file_process_stream(), media_type="text/event-stream")
|
backend/open_webui/apps/openai/main.py
ADDED
@@ -0,0 +1,557 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import asyncio
|
2 |
+
import hashlib
|
3 |
+
import json
|
4 |
+
import logging
|
5 |
+
from pathlib import Path
|
6 |
+
from typing import Literal, Optional, overload
|
7 |
+
|
8 |
+
import aiohttp
|
9 |
+
import requests
|
10 |
+
from open_webui.apps.webui.models.models import Models
|
11 |
+
from open_webui.config import (
|
12 |
+
CACHE_DIR,
|
13 |
+
CORS_ALLOW_ORIGIN,
|
14 |
+
ENABLE_MODEL_FILTER,
|
15 |
+
ENABLE_OPENAI_API,
|
16 |
+
MODEL_FILTER_LIST,
|
17 |
+
OPENAI_API_BASE_URLS,
|
18 |
+
OPENAI_API_KEYS,
|
19 |
+
AppConfig,
|
20 |
+
)
|
21 |
+
from open_webui.env import (
|
22 |
+
AIOHTTP_CLIENT_TIMEOUT,
|
23 |
+
AIOHTTP_CLIENT_TIMEOUT_OPENAI_MODEL_LIST,
|
24 |
+
)
|
25 |
+
|
26 |
+
from open_webui.constants import ERROR_MESSAGES
|
27 |
+
from open_webui.env import ENV, SRC_LOG_LEVELS
|
28 |
+
from fastapi import Depends, FastAPI, HTTPException, Request
|
29 |
+
from fastapi.middleware.cors import CORSMiddleware
|
30 |
+
from fastapi.responses import FileResponse, StreamingResponse
|
31 |
+
from pydantic import BaseModel
|
32 |
+
from starlette.background import BackgroundTask
|
33 |
+
|
34 |
+
from open_webui.utils.payload import (
|
35 |
+
apply_model_params_to_body_openai,
|
36 |
+
apply_model_system_prompt_to_body,
|
37 |
+
)
|
38 |
+
|
39 |
+
from open_webui.utils.utils import get_admin_user, get_verified_user
|
40 |
+
|
41 |
+
log = logging.getLogger(__name__)
|
42 |
+
log.setLevel(SRC_LOG_LEVELS["OPENAI"])
|
43 |
+
|
44 |
+
|
45 |
+
app = FastAPI(docs_url="/docs" if ENV == "dev" else None, openapi_url="/openapi.json" if ENV == "dev" else None, redoc_url=None)
|
46 |
+
|
47 |
+
|
48 |
+
app.add_middleware(
|
49 |
+
CORSMiddleware,
|
50 |
+
allow_origins=CORS_ALLOW_ORIGIN,
|
51 |
+
allow_credentials=True,
|
52 |
+
allow_methods=["*"],
|
53 |
+
allow_headers=["*"],
|
54 |
+
)
|
55 |
+
|
56 |
+
app.state.config = AppConfig()
|
57 |
+
|
58 |
+
app.state.config.ENABLE_MODEL_FILTER = ENABLE_MODEL_FILTER
|
59 |
+
app.state.config.MODEL_FILTER_LIST = MODEL_FILTER_LIST
|
60 |
+
|
61 |
+
app.state.config.ENABLE_OPENAI_API = ENABLE_OPENAI_API
|
62 |
+
app.state.config.OPENAI_API_BASE_URLS = OPENAI_API_BASE_URLS
|
63 |
+
app.state.config.OPENAI_API_KEYS = OPENAI_API_KEYS
|
64 |
+
|
65 |
+
app.state.MODELS = {}
|
66 |
+
|
67 |
+
|
68 |
+
@app.middleware("http")
|
69 |
+
async def check_url(request: Request, call_next):
|
70 |
+
if len(app.state.MODELS) == 0:
|
71 |
+
await get_all_models()
|
72 |
+
|
73 |
+
response = await call_next(request)
|
74 |
+
return response
|
75 |
+
|
76 |
+
|
77 |
+
@app.get("/config")
|
78 |
+
async def get_config(user=Depends(get_admin_user)):
|
79 |
+
return {"ENABLE_OPENAI_API": app.state.config.ENABLE_OPENAI_API}
|
80 |
+
|
81 |
+
|
82 |
+
class OpenAIConfigForm(BaseModel):
|
83 |
+
enable_openai_api: Optional[bool] = None
|
84 |
+
|
85 |
+
|
86 |
+
@app.post("/config/update")
|
87 |
+
async def update_config(form_data: OpenAIConfigForm, user=Depends(get_admin_user)):
|
88 |
+
app.state.config.ENABLE_OPENAI_API = form_data.enable_openai_api
|
89 |
+
return {"ENABLE_OPENAI_API": app.state.config.ENABLE_OPENAI_API}
|
90 |
+
|
91 |
+
|
92 |
+
class UrlsUpdateForm(BaseModel):
|
93 |
+
urls: list[str]
|
94 |
+
|
95 |
+
|
96 |
+
class KeysUpdateForm(BaseModel):
|
97 |
+
keys: list[str]
|
98 |
+
|
99 |
+
|
100 |
+
@app.get("/urls")
|
101 |
+
async def get_openai_urls(user=Depends(get_admin_user)):
|
102 |
+
return {"OPENAI_API_BASE_URLS": app.state.config.OPENAI_API_BASE_URLS}
|
103 |
+
|
104 |
+
|
105 |
+
@app.post("/urls/update")
|
106 |
+
async def update_openai_urls(form_data: UrlsUpdateForm, user=Depends(get_admin_user)):
|
107 |
+
await get_all_models()
|
108 |
+
app.state.config.OPENAI_API_BASE_URLS = form_data.urls
|
109 |
+
return {"OPENAI_API_BASE_URLS": app.state.config.OPENAI_API_BASE_URLS}
|
110 |
+
|
111 |
+
|
112 |
+
@app.get("/keys")
|
113 |
+
async def get_openai_keys(user=Depends(get_admin_user)):
|
114 |
+
return {"OPENAI_API_KEYS": app.state.config.OPENAI_API_KEYS}
|
115 |
+
|
116 |
+
|
117 |
+
@app.post("/keys/update")
|
118 |
+
async def update_openai_key(form_data: KeysUpdateForm, user=Depends(get_admin_user)):
|
119 |
+
app.state.config.OPENAI_API_KEYS = form_data.keys
|
120 |
+
return {"OPENAI_API_KEYS": app.state.config.OPENAI_API_KEYS}
|
121 |
+
|
122 |
+
|
123 |
+
@app.post("/audio/speech")
|
124 |
+
async def speech(request: Request, user=Depends(get_verified_user)):
|
125 |
+
idx = None
|
126 |
+
try:
|
127 |
+
idx = app.state.config.OPENAI_API_BASE_URLS.index("https://api.openai.com/v1")
|
128 |
+
body = await request.body()
|
129 |
+
name = hashlib.sha256(body).hexdigest()
|
130 |
+
|
131 |
+
SPEECH_CACHE_DIR = Path(CACHE_DIR).joinpath("./audio/speech/")
|
132 |
+
SPEECH_CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
133 |
+
file_path = SPEECH_CACHE_DIR.joinpath(f"{name}.mp3")
|
134 |
+
file_body_path = SPEECH_CACHE_DIR.joinpath(f"{name}.json")
|
135 |
+
|
136 |
+
# Check if the file already exists in the cache
|
137 |
+
if file_path.is_file():
|
138 |
+
return FileResponse(file_path)
|
139 |
+
|
140 |
+
headers = {}
|
141 |
+
headers["Authorization"] = f"Bearer {app.state.config.OPENAI_API_KEYS[idx]}"
|
142 |
+
headers["Content-Type"] = "application/json"
|
143 |
+
if "openrouter.ai" in app.state.config.OPENAI_API_BASE_URLS[idx]:
|
144 |
+
headers["HTTP-Referer"] = "https://openwebui.com/"
|
145 |
+
headers["X-Title"] = "Open WebUI"
|
146 |
+
r = None
|
147 |
+
try:
|
148 |
+
r = requests.post(
|
149 |
+
url=f"{app.state.config.OPENAI_API_BASE_URLS[idx]}/audio/speech",
|
150 |
+
data=body,
|
151 |
+
headers=headers,
|
152 |
+
stream=True,
|
153 |
+
)
|
154 |
+
|
155 |
+
r.raise_for_status()
|
156 |
+
|
157 |
+
# Save the streaming content to a file
|
158 |
+
with open(file_path, "wb") as f:
|
159 |
+
for chunk in r.iter_content(chunk_size=8192):
|
160 |
+
f.write(chunk)
|
161 |
+
|
162 |
+
with open(file_body_path, "w") as f:
|
163 |
+
json.dump(json.loads(body.decode("utf-8")), f)
|
164 |
+
|
165 |
+
# Return the saved file
|
166 |
+
return FileResponse(file_path)
|
167 |
+
|
168 |
+
except Exception as e:
|
169 |
+
log.exception(e)
|
170 |
+
error_detail = "Open WebUI: Server Connection Error"
|
171 |
+
if r is not None:
|
172 |
+
try:
|
173 |
+
res = r.json()
|
174 |
+
if "error" in res:
|
175 |
+
error_detail = f"External: {res['error']}"
|
176 |
+
except Exception:
|
177 |
+
error_detail = f"External: {e}"
|
178 |
+
|
179 |
+
raise HTTPException(
|
180 |
+
status_code=r.status_code if r else 500, detail=error_detail
|
181 |
+
)
|
182 |
+
|
183 |
+
except ValueError:
|
184 |
+
raise HTTPException(status_code=401, detail=ERROR_MESSAGES.OPENAI_NOT_FOUND)
|
185 |
+
|
186 |
+
|
187 |
+
async def fetch_url(url, key):
|
188 |
+
timeout = aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT_OPENAI_MODEL_LIST)
|
189 |
+
try:
|
190 |
+
headers = {"Authorization": f"Bearer {key}"}
|
191 |
+
async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
|
192 |
+
async with session.get(url, headers=headers) as response:
|
193 |
+
return await response.json()
|
194 |
+
except Exception as e:
|
195 |
+
# Handle connection error here
|
196 |
+
log.error(f"Connection error: {e}")
|
197 |
+
return None
|
198 |
+
|
199 |
+
|
200 |
+
async def cleanup_response(
|
201 |
+
response: Optional[aiohttp.ClientResponse],
|
202 |
+
session: Optional[aiohttp.ClientSession],
|
203 |
+
):
|
204 |
+
if response:
|
205 |
+
response.close()
|
206 |
+
if session:
|
207 |
+
await session.close()
|
208 |
+
|
209 |
+
|
210 |
+
def merge_models_lists(model_lists):
|
211 |
+
log.debug(f"merge_models_lists {model_lists}")
|
212 |
+
merged_list = []
|
213 |
+
|
214 |
+
for idx, models in enumerate(model_lists):
|
215 |
+
if models is not None and "error" not in models:
|
216 |
+
merged_list.extend(
|
217 |
+
[
|
218 |
+
{
|
219 |
+
**model,
|
220 |
+
"name": model.get("name", model["id"]),
|
221 |
+
"owned_by": "openai",
|
222 |
+
"openai": model,
|
223 |
+
"urlIdx": idx,
|
224 |
+
}
|
225 |
+
for model in models
|
226 |
+
if "api.openai.com"
|
227 |
+
not in app.state.config.OPENAI_API_BASE_URLS[idx]
|
228 |
+
or not any(
|
229 |
+
name in model["id"]
|
230 |
+
for name in [
|
231 |
+
"babbage",
|
232 |
+
"dall-e",
|
233 |
+
"davinci",
|
234 |
+
"embedding",
|
235 |
+
"tts",
|
236 |
+
"whisper",
|
237 |
+
]
|
238 |
+
)
|
239 |
+
]
|
240 |
+
)
|
241 |
+
|
242 |
+
return merged_list
|
243 |
+
|
244 |
+
|
245 |
+
def is_openai_api_disabled():
|
246 |
+
return not app.state.config.ENABLE_OPENAI_API
|
247 |
+
|
248 |
+
|
249 |
+
async def get_all_models_raw() -> list:
|
250 |
+
if is_openai_api_disabled():
|
251 |
+
return []
|
252 |
+
|
253 |
+
# Check if API KEYS length is same than API URLS length
|
254 |
+
num_urls = len(app.state.config.OPENAI_API_BASE_URLS)
|
255 |
+
num_keys = len(app.state.config.OPENAI_API_KEYS)
|
256 |
+
|
257 |
+
if num_keys != num_urls:
|
258 |
+
# if there are more keys than urls, remove the extra keys
|
259 |
+
if num_keys > num_urls:
|
260 |
+
new_keys = app.state.config.OPENAI_API_KEYS[:num_urls]
|
261 |
+
app.state.config.OPENAI_API_KEYS = new_keys
|
262 |
+
# if there are more urls than keys, add empty keys
|
263 |
+
else:
|
264 |
+
app.state.config.OPENAI_API_KEYS += [""] * (num_urls - num_keys)
|
265 |
+
|
266 |
+
tasks = [
|
267 |
+
fetch_url(f"{url}/models", app.state.config.OPENAI_API_KEYS[idx])
|
268 |
+
for idx, url in enumerate(app.state.config.OPENAI_API_BASE_URLS)
|
269 |
+
]
|
270 |
+
|
271 |
+
responses = await asyncio.gather(*tasks)
|
272 |
+
log.debug(f"get_all_models:responses() {responses}")
|
273 |
+
|
274 |
+
return responses
|
275 |
+
|
276 |
+
|
277 |
+
@overload
|
278 |
+
async def get_all_models(raw: Literal[True]) -> list: ...
|
279 |
+
|
280 |
+
|
281 |
+
@overload
|
282 |
+
async def get_all_models(raw: Literal[False] = False) -> dict[str, list]: ...
|
283 |
+
|
284 |
+
|
285 |
+
async def get_all_models(raw=False) -> dict[str, list] | list:
|
286 |
+
log.info("get_all_models()")
|
287 |
+
if is_openai_api_disabled():
|
288 |
+
return [] if raw else {"data": []}
|
289 |
+
|
290 |
+
responses = await get_all_models_raw()
|
291 |
+
if raw:
|
292 |
+
return responses
|
293 |
+
|
294 |
+
def extract_data(response):
|
295 |
+
if response and "data" in response:
|
296 |
+
return response["data"]
|
297 |
+
if isinstance(response, list):
|
298 |
+
return response
|
299 |
+
return None
|
300 |
+
|
301 |
+
models = {"data": merge_models_lists(map(extract_data, responses))}
|
302 |
+
|
303 |
+
log.debug(f"models: {models}")
|
304 |
+
app.state.MODELS = {model["id"]: model for model in models["data"]}
|
305 |
+
|
306 |
+
return models
|
307 |
+
|
308 |
+
|
309 |
+
@app.get("/models")
|
310 |
+
@app.get("/models/{url_idx}")
|
311 |
+
async def get_models(url_idx: Optional[int] = None, user=Depends(get_verified_user)):
|
312 |
+
if url_idx is None:
|
313 |
+
models = await get_all_models()
|
314 |
+
if app.state.config.ENABLE_MODEL_FILTER:
|
315 |
+
if user.role == "user":
|
316 |
+
models["data"] = list(
|
317 |
+
filter(
|
318 |
+
lambda model: model["id"] in app.state.config.MODEL_FILTER_LIST,
|
319 |
+
models["data"],
|
320 |
+
)
|
321 |
+
)
|
322 |
+
return models
|
323 |
+
return models
|
324 |
+
else:
|
325 |
+
url = app.state.config.OPENAI_API_BASE_URLS[url_idx]
|
326 |
+
key = app.state.config.OPENAI_API_KEYS[url_idx]
|
327 |
+
|
328 |
+
headers = {}
|
329 |
+
headers["Authorization"] = f"Bearer {key}"
|
330 |
+
headers["Content-Type"] = "application/json"
|
331 |
+
|
332 |
+
r = None
|
333 |
+
|
334 |
+
try:
|
335 |
+
r = requests.request(method="GET", url=f"{url}/models", headers=headers)
|
336 |
+
r.raise_for_status()
|
337 |
+
|
338 |
+
response_data = r.json()
|
339 |
+
|
340 |
+
if "api.openai.com" in url:
|
341 |
+
# Filter the response data
|
342 |
+
response_data["data"] = [
|
343 |
+
model
|
344 |
+
for model in response_data["data"]
|
345 |
+
if not any(
|
346 |
+
name in model["id"]
|
347 |
+
for name in [
|
348 |
+
"babbage",
|
349 |
+
"dall-e",
|
350 |
+
"davinci",
|
351 |
+
"embedding",
|
352 |
+
"tts",
|
353 |
+
"whisper",
|
354 |
+
]
|
355 |
+
)
|
356 |
+
]
|
357 |
+
|
358 |
+
return response_data
|
359 |
+
except Exception as e:
|
360 |
+
log.exception(e)
|
361 |
+
error_detail = "Open WebUI: Server Connection Error"
|
362 |
+
if r is not None:
|
363 |
+
try:
|
364 |
+
res = r.json()
|
365 |
+
if "error" in res:
|
366 |
+
error_detail = f"External: {res['error']}"
|
367 |
+
except Exception:
|
368 |
+
error_detail = f"External: {e}"
|
369 |
+
|
370 |
+
raise HTTPException(
|
371 |
+
status_code=r.status_code if r else 500,
|
372 |
+
detail=error_detail,
|
373 |
+
)
|
374 |
+
|
375 |
+
|
376 |
+
@app.post("/chat/completions")
|
377 |
+
@app.post("/chat/completions/{url_idx}")
|
378 |
+
async def generate_chat_completion(
|
379 |
+
form_data: dict,
|
380 |
+
url_idx: Optional[int] = None,
|
381 |
+
user=Depends(get_verified_user),
|
382 |
+
):
|
383 |
+
idx = 0
|
384 |
+
payload = {**form_data}
|
385 |
+
|
386 |
+
if "metadata" in payload:
|
387 |
+
del payload["metadata"]
|
388 |
+
|
389 |
+
model_id = form_data.get("model")
|
390 |
+
model_info = Models.get_model_by_id(model_id)
|
391 |
+
|
392 |
+
if model_info:
|
393 |
+
if model_info.base_model_id:
|
394 |
+
payload["model"] = model_info.base_model_id
|
395 |
+
|
396 |
+
params = model_info.params.model_dump()
|
397 |
+
payload = apply_model_params_to_body_openai(params, payload)
|
398 |
+
payload = apply_model_system_prompt_to_body(params, payload, user)
|
399 |
+
|
400 |
+
model = app.state.MODELS[payload.get("model")]
|
401 |
+
idx = model["urlIdx"]
|
402 |
+
|
403 |
+
if "pipeline" in model and model.get("pipeline"):
|
404 |
+
payload["user"] = {
|
405 |
+
"name": user.name,
|
406 |
+
"id": user.id,
|
407 |
+
"email": user.email,
|
408 |
+
"role": user.role,
|
409 |
+
}
|
410 |
+
|
411 |
+
url = app.state.config.OPENAI_API_BASE_URLS[idx]
|
412 |
+
key = app.state.config.OPENAI_API_KEYS[idx]
|
413 |
+
is_o1 = payload["model"].lower().startswith("o1-")
|
414 |
+
|
415 |
+
# Change max_completion_tokens to max_tokens (Backward compatible)
|
416 |
+
if "api.openai.com" not in url and not is_o1:
|
417 |
+
if "max_completion_tokens" in payload:
|
418 |
+
# Remove "max_completion_tokens" from the payload
|
419 |
+
payload["max_tokens"] = payload["max_completion_tokens"]
|
420 |
+
del payload["max_completion_tokens"]
|
421 |
+
else:
|
422 |
+
if is_o1 and "max_tokens" in payload:
|
423 |
+
payload["max_completion_tokens"] = payload["max_tokens"]
|
424 |
+
del payload["max_tokens"]
|
425 |
+
if "max_tokens" in payload and "max_completion_tokens" in payload:
|
426 |
+
del payload["max_tokens"]
|
427 |
+
|
428 |
+
# Fix: O1 does not support the "system" parameter, Modify "system" to "user"
|
429 |
+
if is_o1 and payload["messages"][0]["role"] == "system":
|
430 |
+
payload["messages"][0]["role"] = "user"
|
431 |
+
|
432 |
+
# Convert the modified body back to JSON
|
433 |
+
payload = json.dumps(payload)
|
434 |
+
|
435 |
+
log.debug(payload)
|
436 |
+
|
437 |
+
headers = {}
|
438 |
+
headers["Authorization"] = f"Bearer {key}"
|
439 |
+
headers["Content-Type"] = "application/json"
|
440 |
+
if "openrouter.ai" in app.state.config.OPENAI_API_BASE_URLS[idx]:
|
441 |
+
headers["HTTP-Referer"] = "https://openwebui.com/"
|
442 |
+
headers["X-Title"] = "Open WebUI"
|
443 |
+
|
444 |
+
r = None
|
445 |
+
session = None
|
446 |
+
streaming = False
|
447 |
+
response = None
|
448 |
+
|
449 |
+
try:
|
450 |
+
session = aiohttp.ClientSession(
|
451 |
+
trust_env=True, timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT)
|
452 |
+
)
|
453 |
+
r = await session.request(
|
454 |
+
method="POST",
|
455 |
+
url=f"{url}/chat/completions",
|
456 |
+
data=payload,
|
457 |
+
headers=headers,
|
458 |
+
)
|
459 |
+
|
460 |
+
# Check if response is SSE
|
461 |
+
if "text/event-stream" in r.headers.get("Content-Type", ""):
|
462 |
+
streaming = True
|
463 |
+
return StreamingResponse(
|
464 |
+
r.content,
|
465 |
+
status_code=r.status,
|
466 |
+
headers=dict(r.headers),
|
467 |
+
background=BackgroundTask(
|
468 |
+
cleanup_response, response=r, session=session
|
469 |
+
),
|
470 |
+
)
|
471 |
+
else:
|
472 |
+
try:
|
473 |
+
response = await r.json()
|
474 |
+
except Exception as e:
|
475 |
+
log.error(e)
|
476 |
+
response = await r.text()
|
477 |
+
|
478 |
+
r.raise_for_status()
|
479 |
+
return response
|
480 |
+
except Exception as e:
|
481 |
+
log.exception(e)
|
482 |
+
error_detail = "Open WebUI: Server Connection Error"
|
483 |
+
if isinstance(response, dict):
|
484 |
+
if "error" in response:
|
485 |
+
error_detail = f"{response['error']['message'] if 'message' in response['error'] else response['error']}"
|
486 |
+
elif isinstance(response, str):
|
487 |
+
error_detail = response
|
488 |
+
|
489 |
+
raise HTTPException(status_code=r.status if r else 500, detail=error_detail)
|
490 |
+
finally:
|
491 |
+
if not streaming and session:
|
492 |
+
if r:
|
493 |
+
r.close()
|
494 |
+
await session.close()
|
495 |
+
|
496 |
+
|
497 |
+
@app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
|
498 |
+
async def proxy(path: str, request: Request, user=Depends(get_verified_user)):
|
499 |
+
idx = 0
|
500 |
+
|
501 |
+
body = await request.body()
|
502 |
+
|
503 |
+
url = app.state.config.OPENAI_API_BASE_URLS[idx]
|
504 |
+
key = app.state.config.OPENAI_API_KEYS[idx]
|
505 |
+
|
506 |
+
target_url = f"{url}/{path}"
|
507 |
+
|
508 |
+
headers = {}
|
509 |
+
headers["Authorization"] = f"Bearer {key}"
|
510 |
+
headers["Content-Type"] = "application/json"
|
511 |
+
|
512 |
+
r = None
|
513 |
+
session = None
|
514 |
+
streaming = False
|
515 |
+
|
516 |
+
try:
|
517 |
+
session = aiohttp.ClientSession(trust_env=True)
|
518 |
+
r = await session.request(
|
519 |
+
method=request.method,
|
520 |
+
url=target_url,
|
521 |
+
data=body,
|
522 |
+
headers=headers,
|
523 |
+
)
|
524 |
+
|
525 |
+
r.raise_for_status()
|
526 |
+
|
527 |
+
# Check if response is SSE
|
528 |
+
if "text/event-stream" in r.headers.get("Content-Type", ""):
|
529 |
+
streaming = True
|
530 |
+
return StreamingResponse(
|
531 |
+
r.content,
|
532 |
+
status_code=r.status,
|
533 |
+
headers=dict(r.headers),
|
534 |
+
background=BackgroundTask(
|
535 |
+
cleanup_response, response=r, session=session
|
536 |
+
),
|
537 |
+
)
|
538 |
+
else:
|
539 |
+
response_data = await r.json()
|
540 |
+
return response_data
|
541 |
+
except Exception as e:
|
542 |
+
log.exception(e)
|
543 |
+
error_detail = "Open WebUI: Server Connection Error"
|
544 |
+
if r is not None:
|
545 |
+
try:
|
546 |
+
res = await r.json()
|
547 |
+
print(res)
|
548 |
+
if "error" in res:
|
549 |
+
error_detail = f"External: {res['error']['message'] if 'message' in res['error'] else res['error']}"
|
550 |
+
except Exception:
|
551 |
+
error_detail = f"External: {e}"
|
552 |
+
raise HTTPException(status_code=r.status if r else 500, detail=error_detail)
|
553 |
+
finally:
|
554 |
+
if not streaming and session:
|
555 |
+
if r:
|
556 |
+
r.close()
|
557 |
+
await session.close()
|
backend/open_webui/apps/retrieval/loaders/main.py
ADDED
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import requests
|
2 |
+
import logging
|
3 |
+
import ftfy
|
4 |
+
|
5 |
+
from langchain_community.document_loaders import (
|
6 |
+
BSHTMLLoader,
|
7 |
+
CSVLoader,
|
8 |
+
Docx2txtLoader,
|
9 |
+
OutlookMessageLoader,
|
10 |
+
PyPDFLoader,
|
11 |
+
TextLoader,
|
12 |
+
UnstructuredEPubLoader,
|
13 |
+
UnstructuredExcelLoader,
|
14 |
+
UnstructuredMarkdownLoader,
|
15 |
+
UnstructuredPowerPointLoader,
|
16 |
+
UnstructuredRSTLoader,
|
17 |
+
UnstructuredXMLLoader,
|
18 |
+
YoutubeLoader,
|
19 |
+
)
|
20 |
+
from langchain_core.documents import Document
|
21 |
+
from open_webui.env import SRC_LOG_LEVELS
|
22 |
+
|
23 |
+
log = logging.getLogger(__name__)
|
24 |
+
log.setLevel(SRC_LOG_LEVELS["RAG"])
|
25 |
+
|
26 |
+
known_source_ext = [
|
27 |
+
"go",
|
28 |
+
"py",
|
29 |
+
"java",
|
30 |
+
"sh",
|
31 |
+
"bat",
|
32 |
+
"ps1",
|
33 |
+
"cmd",
|
34 |
+
"js",
|
35 |
+
"ts",
|
36 |
+
"css",
|
37 |
+
"cpp",
|
38 |
+
"hpp",
|
39 |
+
"h",
|
40 |
+
"c",
|
41 |
+
"cs",
|
42 |
+
"sql",
|
43 |
+
"log",
|
44 |
+
"ini",
|
45 |
+
"pl",
|
46 |
+
"pm",
|
47 |
+
"r",
|
48 |
+
"dart",
|
49 |
+
"dockerfile",
|
50 |
+
"env",
|
51 |
+
"php",
|
52 |
+
"hs",
|
53 |
+
"hsc",
|
54 |
+
"lua",
|
55 |
+
"nginxconf",
|
56 |
+
"conf",
|
57 |
+
"m",
|
58 |
+
"mm",
|
59 |
+
"plsql",
|
60 |
+
"perl",
|
61 |
+
"rb",
|
62 |
+
"rs",
|
63 |
+
"db2",
|
64 |
+
"scala",
|
65 |
+
"bash",
|
66 |
+
"swift",
|
67 |
+
"vue",
|
68 |
+
"svelte",
|
69 |
+
"msg",
|
70 |
+
"ex",
|
71 |
+
"exs",
|
72 |
+
"erl",
|
73 |
+
"tsx",
|
74 |
+
"jsx",
|
75 |
+
"hs",
|
76 |
+
"lhs",
|
77 |
+
]
|
78 |
+
|
79 |
+
|
80 |
+
class TikaLoader:
|
81 |
+
def __init__(self, url, file_path, mime_type=None):
|
82 |
+
self.url = url
|
83 |
+
self.file_path = file_path
|
84 |
+
self.mime_type = mime_type
|
85 |
+
|
86 |
+
def load(self) -> list[Document]:
|
87 |
+
with open(self.file_path, "rb") as f:
|
88 |
+
data = f.read()
|
89 |
+
|
90 |
+
if self.mime_type is not None:
|
91 |
+
headers = {"Content-Type": self.mime_type}
|
92 |
+
else:
|
93 |
+
headers = {}
|
94 |
+
|
95 |
+
endpoint = self.url
|
96 |
+
if not endpoint.endswith("/"):
|
97 |
+
endpoint += "/"
|
98 |
+
endpoint += "tika/text"
|
99 |
+
|
100 |
+
r = requests.put(endpoint, data=data, headers=headers)
|
101 |
+
|
102 |
+
if r.ok:
|
103 |
+
raw_metadata = r.json()
|
104 |
+
text = raw_metadata.get("X-TIKA:content", "<No text content found>")
|
105 |
+
|
106 |
+
if "Content-Type" in raw_metadata:
|
107 |
+
headers["Content-Type"] = raw_metadata["Content-Type"]
|
108 |
+
|
109 |
+
log.info("Tika extracted text: %s", text)
|
110 |
+
|
111 |
+
return [Document(page_content=text, metadata=headers)]
|
112 |
+
else:
|
113 |
+
raise Exception(f"Error calling Tika: {r.reason}")
|
114 |
+
|
115 |
+
|
116 |
+
class Loader:
|
117 |
+
def __init__(self, engine: str = "", **kwargs):
|
118 |
+
self.engine = engine
|
119 |
+
self.kwargs = kwargs
|
120 |
+
|
121 |
+
def load(
|
122 |
+
self, filename: str, file_content_type: str, file_path: str
|
123 |
+
) -> list[Document]:
|
124 |
+
loader = self._get_loader(filename, file_content_type, file_path)
|
125 |
+
docs = loader.load()
|
126 |
+
|
127 |
+
return [
|
128 |
+
Document(
|
129 |
+
page_content=ftfy.fix_text(doc.page_content), metadata=doc.metadata
|
130 |
+
)
|
131 |
+
for doc in docs
|
132 |
+
]
|
133 |
+
|
134 |
+
def _get_loader(self, filename: str, file_content_type: str, file_path: str):
|
135 |
+
file_ext = filename.split(".")[-1].lower()
|
136 |
+
|
137 |
+
if self.engine == "tika" and self.kwargs.get("TIKA_SERVER_URL"):
|
138 |
+
if file_ext in known_source_ext or (
|
139 |
+
file_content_type and file_content_type.find("text/") >= 0
|
140 |
+
):
|
141 |
+
loader = TextLoader(file_path, autodetect_encoding=True)
|
142 |
+
else:
|
143 |
+
loader = TikaLoader(
|
144 |
+
url=self.kwargs.get("TIKA_SERVER_URL"),
|
145 |
+
file_path=file_path,
|
146 |
+
mime_type=file_content_type,
|
147 |
+
)
|
148 |
+
else:
|
149 |
+
if file_ext == "pdf":
|
150 |
+
loader = PyPDFLoader(
|
151 |
+
file_path, extract_images=self.kwargs.get("PDF_EXTRACT_IMAGES")
|
152 |
+
)
|
153 |
+
elif file_ext == "csv":
|
154 |
+
loader = CSVLoader(file_path)
|
155 |
+
elif file_ext == "rst":
|
156 |
+
loader = UnstructuredRSTLoader(file_path, mode="elements")
|
157 |
+
elif file_ext == "xml":
|
158 |
+
loader = UnstructuredXMLLoader(file_path)
|
159 |
+
elif file_ext in ["htm", "html"]:
|
160 |
+
loader = BSHTMLLoader(file_path, open_encoding="unicode_escape")
|
161 |
+
elif file_ext == "md":
|
162 |
+
loader = UnstructuredMarkdownLoader(file_path)
|
163 |
+
elif file_content_type == "application/epub+zip":
|
164 |
+
loader = UnstructuredEPubLoader(file_path)
|
165 |
+
elif (
|
166 |
+
file_content_type
|
167 |
+
== "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
|
168 |
+
or file_ext == "docx"
|
169 |
+
):
|
170 |
+
loader = Docx2txtLoader(file_path)
|
171 |
+
elif file_content_type in [
|
172 |
+
"application/vnd.ms-excel",
|
173 |
+
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
174 |
+
] or file_ext in ["xls", "xlsx"]:
|
175 |
+
loader = UnstructuredExcelLoader(file_path)
|
176 |
+
elif file_content_type in [
|
177 |
+
"application/vnd.ms-powerpoint",
|
178 |
+
"application/vnd.openxmlformats-officedocument.presentationml.presentation",
|
179 |
+
] or file_ext in ["ppt", "pptx"]:
|
180 |
+
loader = UnstructuredPowerPointLoader(file_path)
|
181 |
+
elif file_ext == "msg":
|
182 |
+
loader = OutlookMessageLoader(file_path)
|
183 |
+
elif file_ext in known_source_ext or (
|
184 |
+
file_content_type and file_content_type.find("text/") >= 0
|
185 |
+
):
|
186 |
+
loader = TextLoader(file_path, autodetect_encoding=True)
|
187 |
+
else:
|
188 |
+
loader = TextLoader(file_path, autodetect_encoding=True)
|
189 |
+
|
190 |
+
return loader
|
backend/open_webui/apps/retrieval/main.py
ADDED
@@ -0,0 +1,1332 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# TODO: Merge this with the webui_app and make it a single app
|
2 |
+
|
3 |
+
import json
|
4 |
+
import logging
|
5 |
+
import mimetypes
|
6 |
+
import os
|
7 |
+
import shutil
|
8 |
+
|
9 |
+
import uuid
|
10 |
+
from datetime import datetime
|
11 |
+
from pathlib import Path
|
12 |
+
from typing import Iterator, Optional, Sequence, Union
|
13 |
+
|
14 |
+
from fastapi import Depends, FastAPI, File, Form, HTTPException, UploadFile, status
|
15 |
+
from fastapi.middleware.cors import CORSMiddleware
|
16 |
+
from pydantic import BaseModel
|
17 |
+
import tiktoken
|
18 |
+
|
19 |
+
|
20 |
+
from open_webui.storage.provider import Storage
|
21 |
+
from open_webui.apps.webui.models.knowledge import Knowledges
|
22 |
+
from open_webui.apps.retrieval.vector.connector import VECTOR_DB_CLIENT
|
23 |
+
|
24 |
+
# Document loaders
|
25 |
+
from open_webui.apps.retrieval.loaders.main import Loader
|
26 |
+
|
27 |
+
# Web search engines
|
28 |
+
from open_webui.apps.retrieval.web.main import SearchResult
|
29 |
+
from open_webui.apps.retrieval.web.utils import get_web_loader
|
30 |
+
from open_webui.apps.retrieval.web.brave import search_brave
|
31 |
+
from open_webui.apps.retrieval.web.duckduckgo import search_duckduckgo
|
32 |
+
from open_webui.apps.retrieval.web.google_pse import search_google_pse
|
33 |
+
from open_webui.apps.retrieval.web.jina_search import search_jina
|
34 |
+
from open_webui.apps.retrieval.web.searchapi import search_searchapi
|
35 |
+
from open_webui.apps.retrieval.web.searxng import search_searxng
|
36 |
+
from open_webui.apps.retrieval.web.serper import search_serper
|
37 |
+
from open_webui.apps.retrieval.web.serply import search_serply
|
38 |
+
from open_webui.apps.retrieval.web.serpstack import search_serpstack
|
39 |
+
from open_webui.apps.retrieval.web.tavily import search_tavily
|
40 |
+
|
41 |
+
|
42 |
+
from open_webui.apps.retrieval.utils import (
|
43 |
+
get_embedding_function,
|
44 |
+
get_model_path,
|
45 |
+
query_collection,
|
46 |
+
query_collection_with_hybrid_search,
|
47 |
+
query_doc,
|
48 |
+
query_doc_with_hybrid_search,
|
49 |
+
)
|
50 |
+
|
51 |
+
from open_webui.apps.webui.models.files import Files
|
52 |
+
from open_webui.config import (
|
53 |
+
BRAVE_SEARCH_API_KEY,
|
54 |
+
TIKTOKEN_ENCODING_NAME,
|
55 |
+
RAG_TEXT_SPLITTER,
|
56 |
+
CHUNK_OVERLAP,
|
57 |
+
CHUNK_SIZE,
|
58 |
+
CONTENT_EXTRACTION_ENGINE,
|
59 |
+
CORS_ALLOW_ORIGIN,
|
60 |
+
ENABLE_RAG_HYBRID_SEARCH,
|
61 |
+
ENABLE_RAG_LOCAL_WEB_FETCH,
|
62 |
+
ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION,
|
63 |
+
ENABLE_RAG_WEB_SEARCH,
|
64 |
+
ENV,
|
65 |
+
GOOGLE_PSE_API_KEY,
|
66 |
+
GOOGLE_PSE_ENGINE_ID,
|
67 |
+
PDF_EXTRACT_IMAGES,
|
68 |
+
RAG_EMBEDDING_ENGINE,
|
69 |
+
RAG_EMBEDDING_MODEL,
|
70 |
+
RAG_EMBEDDING_MODEL_AUTO_UPDATE,
|
71 |
+
RAG_EMBEDDING_MODEL_TRUST_REMOTE_CODE,
|
72 |
+
RAG_EMBEDDING_BATCH_SIZE,
|
73 |
+
RAG_FILE_MAX_COUNT,
|
74 |
+
RAG_FILE_MAX_SIZE,
|
75 |
+
RAG_OPENAI_API_BASE_URL,
|
76 |
+
RAG_OPENAI_API_KEY,
|
77 |
+
RAG_RELEVANCE_THRESHOLD,
|
78 |
+
RAG_RERANKING_MODEL,
|
79 |
+
RAG_RERANKING_MODEL_AUTO_UPDATE,
|
80 |
+
RAG_RERANKING_MODEL_TRUST_REMOTE_CODE,
|
81 |
+
DEFAULT_RAG_TEMPLATE,
|
82 |
+
RAG_TEMPLATE,
|
83 |
+
RAG_TOP_K,
|
84 |
+
RAG_WEB_SEARCH_CONCURRENT_REQUESTS,
|
85 |
+
RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
|
86 |
+
RAG_WEB_SEARCH_ENGINE,
|
87 |
+
RAG_WEB_SEARCH_RESULT_COUNT,
|
88 |
+
SEARCHAPI_API_KEY,
|
89 |
+
SEARCHAPI_ENGINE,
|
90 |
+
SEARXNG_QUERY_URL,
|
91 |
+
SERPER_API_KEY,
|
92 |
+
SERPLY_API_KEY,
|
93 |
+
SERPSTACK_API_KEY,
|
94 |
+
SERPSTACK_HTTPS,
|
95 |
+
TAVILY_API_KEY,
|
96 |
+
TIKA_SERVER_URL,
|
97 |
+
UPLOAD_DIR,
|
98 |
+
YOUTUBE_LOADER_LANGUAGE,
|
99 |
+
AppConfig,
|
100 |
+
)
|
101 |
+
from open_webui.constants import ERROR_MESSAGES
|
102 |
+
from open_webui.env import SRC_LOG_LEVELS, DEVICE_TYPE, DOCKER
|
103 |
+
from open_webui.utils.misc import (
|
104 |
+
calculate_sha256,
|
105 |
+
calculate_sha256_string,
|
106 |
+
extract_folders_after_data_docs,
|
107 |
+
sanitize_filename,
|
108 |
+
)
|
109 |
+
from open_webui.utils.utils import get_admin_user, get_verified_user
|
110 |
+
|
111 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter, TokenTextSplitter
|
112 |
+
from langchain_community.document_loaders import (
|
113 |
+
YoutubeLoader,
|
114 |
+
)
|
115 |
+
from langchain_core.documents import Document
|
116 |
+
|
117 |
+
|
118 |
+
log = logging.getLogger(__name__)
|
119 |
+
log.setLevel(SRC_LOG_LEVELS["RAG"])
|
120 |
+
|
121 |
+
app = FastAPI(docs_url="/docs" if ENV == "dev" else None, openapi_url="/openapi.json" if ENV == "dev" else None, redoc_url=None)
|
122 |
+
|
123 |
+
app.state.config = AppConfig()
|
124 |
+
|
125 |
+
app.state.config.TOP_K = RAG_TOP_K
|
126 |
+
app.state.config.RELEVANCE_THRESHOLD = RAG_RELEVANCE_THRESHOLD
|
127 |
+
app.state.config.FILE_MAX_SIZE = RAG_FILE_MAX_SIZE
|
128 |
+
app.state.config.FILE_MAX_COUNT = RAG_FILE_MAX_COUNT
|
129 |
+
|
130 |
+
app.state.config.ENABLE_RAG_HYBRID_SEARCH = ENABLE_RAG_HYBRID_SEARCH
|
131 |
+
app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION = (
|
132 |
+
ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION
|
133 |
+
)
|
134 |
+
|
135 |
+
app.state.config.CONTENT_EXTRACTION_ENGINE = CONTENT_EXTRACTION_ENGINE
|
136 |
+
app.state.config.TIKA_SERVER_URL = TIKA_SERVER_URL
|
137 |
+
|
138 |
+
app.state.config.TEXT_SPLITTER = RAG_TEXT_SPLITTER
|
139 |
+
app.state.config.TIKTOKEN_ENCODING_NAME = TIKTOKEN_ENCODING_NAME
|
140 |
+
|
141 |
+
app.state.config.CHUNK_SIZE = CHUNK_SIZE
|
142 |
+
app.state.config.CHUNK_OVERLAP = CHUNK_OVERLAP
|
143 |
+
|
144 |
+
app.state.config.RAG_EMBEDDING_ENGINE = RAG_EMBEDDING_ENGINE
|
145 |
+
app.state.config.RAG_EMBEDDING_MODEL = RAG_EMBEDDING_MODEL
|
146 |
+
app.state.config.RAG_EMBEDDING_BATCH_SIZE = RAG_EMBEDDING_BATCH_SIZE
|
147 |
+
app.state.config.RAG_RERANKING_MODEL = RAG_RERANKING_MODEL
|
148 |
+
app.state.config.RAG_TEMPLATE = RAG_TEMPLATE
|
149 |
+
|
150 |
+
app.state.config.OPENAI_API_BASE_URL = RAG_OPENAI_API_BASE_URL
|
151 |
+
app.state.config.OPENAI_API_KEY = RAG_OPENAI_API_KEY
|
152 |
+
|
153 |
+
app.state.config.PDF_EXTRACT_IMAGES = PDF_EXTRACT_IMAGES
|
154 |
+
|
155 |
+
app.state.config.YOUTUBE_LOADER_LANGUAGE = YOUTUBE_LOADER_LANGUAGE
|
156 |
+
app.state.YOUTUBE_LOADER_TRANSLATION = None
|
157 |
+
|
158 |
+
|
159 |
+
app.state.config.ENABLE_RAG_WEB_SEARCH = ENABLE_RAG_WEB_SEARCH
|
160 |
+
app.state.config.RAG_WEB_SEARCH_ENGINE = RAG_WEB_SEARCH_ENGINE
|
161 |
+
app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST = RAG_WEB_SEARCH_DOMAIN_FILTER_LIST
|
162 |
+
|
163 |
+
app.state.config.SEARXNG_QUERY_URL = SEARXNG_QUERY_URL
|
164 |
+
app.state.config.GOOGLE_PSE_API_KEY = GOOGLE_PSE_API_KEY
|
165 |
+
app.state.config.GOOGLE_PSE_ENGINE_ID = GOOGLE_PSE_ENGINE_ID
|
166 |
+
app.state.config.BRAVE_SEARCH_API_KEY = BRAVE_SEARCH_API_KEY
|
167 |
+
app.state.config.SERPSTACK_API_KEY = SERPSTACK_API_KEY
|
168 |
+
app.state.config.SERPSTACK_HTTPS = SERPSTACK_HTTPS
|
169 |
+
app.state.config.SERPER_API_KEY = SERPER_API_KEY
|
170 |
+
app.state.config.SERPLY_API_KEY = SERPLY_API_KEY
|
171 |
+
app.state.config.TAVILY_API_KEY = TAVILY_API_KEY
|
172 |
+
app.state.config.SEARCHAPI_API_KEY = SEARCHAPI_API_KEY
|
173 |
+
app.state.config.SEARCHAPI_ENGINE = SEARCHAPI_ENGINE
|
174 |
+
app.state.config.RAG_WEB_SEARCH_RESULT_COUNT = RAG_WEB_SEARCH_RESULT_COUNT
|
175 |
+
app.state.config.RAG_WEB_SEARCH_CONCURRENT_REQUESTS = RAG_WEB_SEARCH_CONCURRENT_REQUESTS
|
176 |
+
|
177 |
+
|
178 |
+
def update_embedding_model(
|
179 |
+
embedding_model: str,
|
180 |
+
auto_update: bool = False,
|
181 |
+
):
|
182 |
+
if embedding_model and app.state.config.RAG_EMBEDDING_ENGINE == "":
|
183 |
+
from sentence_transformers import SentenceTransformer
|
184 |
+
|
185 |
+
app.state.sentence_transformer_ef = SentenceTransformer(
|
186 |
+
get_model_path(embedding_model, auto_update),
|
187 |
+
device=DEVICE_TYPE,
|
188 |
+
trust_remote_code=RAG_EMBEDDING_MODEL_TRUST_REMOTE_CODE,
|
189 |
+
)
|
190 |
+
else:
|
191 |
+
app.state.sentence_transformer_ef = None
|
192 |
+
|
193 |
+
|
194 |
+
def update_reranking_model(
|
195 |
+
reranking_model: str,
|
196 |
+
auto_update: bool = False,
|
197 |
+
):
|
198 |
+
if reranking_model:
|
199 |
+
if any(model in reranking_model for model in ["jinaai/jina-colbert-v2"]):
|
200 |
+
try:
|
201 |
+
from open_webui.apps.retrieval.models.colbert import ColBERT
|
202 |
+
|
203 |
+
app.state.sentence_transformer_rf = ColBERT(
|
204 |
+
get_model_path(reranking_model, auto_update),
|
205 |
+
env="docker" if DOCKER else None,
|
206 |
+
)
|
207 |
+
except Exception as e:
|
208 |
+
log.error(f"ColBERT: {e}")
|
209 |
+
app.state.sentence_transformer_rf = None
|
210 |
+
app.state.config.ENABLE_RAG_HYBRID_SEARCH = False
|
211 |
+
else:
|
212 |
+
import sentence_transformers
|
213 |
+
|
214 |
+
try:
|
215 |
+
app.state.sentence_transformer_rf = sentence_transformers.CrossEncoder(
|
216 |
+
get_model_path(reranking_model, auto_update),
|
217 |
+
device=DEVICE_TYPE,
|
218 |
+
trust_remote_code=RAG_RERANKING_MODEL_TRUST_REMOTE_CODE,
|
219 |
+
)
|
220 |
+
except:
|
221 |
+
log.error("CrossEncoder error")
|
222 |
+
app.state.sentence_transformer_rf = None
|
223 |
+
app.state.config.ENABLE_RAG_HYBRID_SEARCH = False
|
224 |
+
else:
|
225 |
+
app.state.sentence_transformer_rf = None
|
226 |
+
|
227 |
+
|
228 |
+
update_embedding_model(
|
229 |
+
app.state.config.RAG_EMBEDDING_MODEL,
|
230 |
+
RAG_EMBEDDING_MODEL_AUTO_UPDATE,
|
231 |
+
)
|
232 |
+
|
233 |
+
update_reranking_model(
|
234 |
+
app.state.config.RAG_RERANKING_MODEL,
|
235 |
+
RAG_RERANKING_MODEL_AUTO_UPDATE,
|
236 |
+
)
|
237 |
+
|
238 |
+
|
239 |
+
app.state.EMBEDDING_FUNCTION = get_embedding_function(
|
240 |
+
app.state.config.RAG_EMBEDDING_ENGINE,
|
241 |
+
app.state.config.RAG_EMBEDDING_MODEL,
|
242 |
+
app.state.sentence_transformer_ef,
|
243 |
+
app.state.config.OPENAI_API_KEY,
|
244 |
+
app.state.config.OPENAI_API_BASE_URL,
|
245 |
+
app.state.config.RAG_EMBEDDING_BATCH_SIZE,
|
246 |
+
)
|
247 |
+
|
248 |
+
app.add_middleware(
|
249 |
+
CORSMiddleware,
|
250 |
+
allow_origins=CORS_ALLOW_ORIGIN,
|
251 |
+
allow_credentials=True,
|
252 |
+
allow_methods=["*"],
|
253 |
+
allow_headers=["*"],
|
254 |
+
)
|
255 |
+
|
256 |
+
|
257 |
+
class CollectionNameForm(BaseModel):
|
258 |
+
collection_name: Optional[str] = None
|
259 |
+
|
260 |
+
|
261 |
+
class ProcessUrlForm(CollectionNameForm):
|
262 |
+
url: str
|
263 |
+
|
264 |
+
|
265 |
+
class SearchForm(CollectionNameForm):
|
266 |
+
query: str
|
267 |
+
|
268 |
+
|
269 |
+
@app.get("/")
|
270 |
+
async def get_status():
|
271 |
+
return {
|
272 |
+
"status": True,
|
273 |
+
"chunk_size": app.state.config.CHUNK_SIZE,
|
274 |
+
"chunk_overlap": app.state.config.CHUNK_OVERLAP,
|
275 |
+
"template": app.state.config.RAG_TEMPLATE,
|
276 |
+
"embedding_engine": app.state.config.RAG_EMBEDDING_ENGINE,
|
277 |
+
"embedding_model": app.state.config.RAG_EMBEDDING_MODEL,
|
278 |
+
"reranking_model": app.state.config.RAG_RERANKING_MODEL,
|
279 |
+
"embedding_batch_size": app.state.config.RAG_EMBEDDING_BATCH_SIZE,
|
280 |
+
}
|
281 |
+
|
282 |
+
|
283 |
+
@app.get("/embedding")
|
284 |
+
async def get_embedding_config(user=Depends(get_admin_user)):
|
285 |
+
return {
|
286 |
+
"status": True,
|
287 |
+
"embedding_engine": app.state.config.RAG_EMBEDDING_ENGINE,
|
288 |
+
"embedding_model": app.state.config.RAG_EMBEDDING_MODEL,
|
289 |
+
"embedding_batch_size": app.state.config.RAG_EMBEDDING_BATCH_SIZE,
|
290 |
+
"openai_config": {
|
291 |
+
"url": app.state.config.OPENAI_API_BASE_URL,
|
292 |
+
"key": app.state.config.OPENAI_API_KEY,
|
293 |
+
},
|
294 |
+
}
|
295 |
+
|
296 |
+
|
297 |
+
@app.get("/reranking")
|
298 |
+
async def get_reraanking_config(user=Depends(get_admin_user)):
|
299 |
+
return {
|
300 |
+
"status": True,
|
301 |
+
"reranking_model": app.state.config.RAG_RERANKING_MODEL,
|
302 |
+
}
|
303 |
+
|
304 |
+
|
305 |
+
class OpenAIConfigForm(BaseModel):
|
306 |
+
url: str
|
307 |
+
key: str
|
308 |
+
|
309 |
+
|
310 |
+
class EmbeddingModelUpdateForm(BaseModel):
|
311 |
+
openai_config: Optional[OpenAIConfigForm] = None
|
312 |
+
embedding_engine: str
|
313 |
+
embedding_model: str
|
314 |
+
embedding_batch_size: Optional[int] = 1
|
315 |
+
|
316 |
+
|
317 |
+
@app.post("/embedding/update")
|
318 |
+
async def update_embedding_config(
|
319 |
+
form_data: EmbeddingModelUpdateForm, user=Depends(get_admin_user)
|
320 |
+
):
|
321 |
+
log.info(
|
322 |
+
f"Updating embedding model: {app.state.config.RAG_EMBEDDING_MODEL} to {form_data.embedding_model}"
|
323 |
+
)
|
324 |
+
try:
|
325 |
+
app.state.config.RAG_EMBEDDING_ENGINE = form_data.embedding_engine
|
326 |
+
app.state.config.RAG_EMBEDDING_MODEL = form_data.embedding_model
|
327 |
+
|
328 |
+
if app.state.config.RAG_EMBEDDING_ENGINE in ["ollama", "openai"]:
|
329 |
+
if form_data.openai_config is not None:
|
330 |
+
app.state.config.OPENAI_API_BASE_URL = form_data.openai_config.url
|
331 |
+
app.state.config.OPENAI_API_KEY = form_data.openai_config.key
|
332 |
+
app.state.config.RAG_EMBEDDING_BATCH_SIZE = form_data.embedding_batch_size
|
333 |
+
|
334 |
+
update_embedding_model(app.state.config.RAG_EMBEDDING_MODEL)
|
335 |
+
|
336 |
+
app.state.EMBEDDING_FUNCTION = get_embedding_function(
|
337 |
+
app.state.config.RAG_EMBEDDING_ENGINE,
|
338 |
+
app.state.config.RAG_EMBEDDING_MODEL,
|
339 |
+
app.state.sentence_transformer_ef,
|
340 |
+
app.state.config.OPENAI_API_KEY,
|
341 |
+
app.state.config.OPENAI_API_BASE_URL,
|
342 |
+
app.state.config.RAG_EMBEDDING_BATCH_SIZE,
|
343 |
+
)
|
344 |
+
|
345 |
+
return {
|
346 |
+
"status": True,
|
347 |
+
"embedding_engine": app.state.config.RAG_EMBEDDING_ENGINE,
|
348 |
+
"embedding_model": app.state.config.RAG_EMBEDDING_MODEL,
|
349 |
+
"embedding_batch_size": app.state.config.RAG_EMBEDDING_BATCH_SIZE,
|
350 |
+
"openai_config": {
|
351 |
+
"url": app.state.config.OPENAI_API_BASE_URL,
|
352 |
+
"key": app.state.config.OPENAI_API_KEY,
|
353 |
+
},
|
354 |
+
}
|
355 |
+
except Exception as e:
|
356 |
+
log.exception(f"Problem updating embedding model: {e}")
|
357 |
+
raise HTTPException(
|
358 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
359 |
+
detail=ERROR_MESSAGES.DEFAULT(e),
|
360 |
+
)
|
361 |
+
|
362 |
+
|
363 |
+
class RerankingModelUpdateForm(BaseModel):
|
364 |
+
reranking_model: str
|
365 |
+
|
366 |
+
|
367 |
+
@app.post("/reranking/update")
|
368 |
+
async def update_reranking_config(
|
369 |
+
form_data: RerankingModelUpdateForm, user=Depends(get_admin_user)
|
370 |
+
):
|
371 |
+
log.info(
|
372 |
+
f"Updating reranking model: {app.state.config.RAG_RERANKING_MODEL} to {form_data.reranking_model}"
|
373 |
+
)
|
374 |
+
try:
|
375 |
+
app.state.config.RAG_RERANKING_MODEL = form_data.reranking_model
|
376 |
+
|
377 |
+
update_reranking_model(app.state.config.RAG_RERANKING_MODEL, True)
|
378 |
+
|
379 |
+
return {
|
380 |
+
"status": True,
|
381 |
+
"reranking_model": app.state.config.RAG_RERANKING_MODEL,
|
382 |
+
}
|
383 |
+
except Exception as e:
|
384 |
+
log.exception(f"Problem updating reranking model: {e}")
|
385 |
+
raise HTTPException(
|
386 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
387 |
+
detail=ERROR_MESSAGES.DEFAULT(e),
|
388 |
+
)
|
389 |
+
|
390 |
+
|
391 |
+
@app.get("/config")
|
392 |
+
async def get_rag_config(user=Depends(get_admin_user)):
|
393 |
+
return {
|
394 |
+
"status": True,
|
395 |
+
"pdf_extract_images": app.state.config.PDF_EXTRACT_IMAGES,
|
396 |
+
"content_extraction": {
|
397 |
+
"engine": app.state.config.CONTENT_EXTRACTION_ENGINE,
|
398 |
+
"tika_server_url": app.state.config.TIKA_SERVER_URL,
|
399 |
+
},
|
400 |
+
"chunk": {
|
401 |
+
"text_splitter": app.state.config.TEXT_SPLITTER,
|
402 |
+
"chunk_size": app.state.config.CHUNK_SIZE,
|
403 |
+
"chunk_overlap": app.state.config.CHUNK_OVERLAP,
|
404 |
+
},
|
405 |
+
"file": {
|
406 |
+
"max_size": app.state.config.FILE_MAX_SIZE,
|
407 |
+
"max_count": app.state.config.FILE_MAX_COUNT,
|
408 |
+
},
|
409 |
+
"youtube": {
|
410 |
+
"language": app.state.config.YOUTUBE_LOADER_LANGUAGE,
|
411 |
+
"translation": app.state.YOUTUBE_LOADER_TRANSLATION,
|
412 |
+
},
|
413 |
+
"web": {
|
414 |
+
"ssl_verification": app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION,
|
415 |
+
"search": {
|
416 |
+
"enabled": app.state.config.ENABLE_RAG_WEB_SEARCH,
|
417 |
+
"engine": app.state.config.RAG_WEB_SEARCH_ENGINE,
|
418 |
+
"searxng_query_url": app.state.config.SEARXNG_QUERY_URL,
|
419 |
+
"google_pse_api_key": app.state.config.GOOGLE_PSE_API_KEY,
|
420 |
+
"google_pse_engine_id": app.state.config.GOOGLE_PSE_ENGINE_ID,
|
421 |
+
"brave_search_api_key": app.state.config.BRAVE_SEARCH_API_KEY,
|
422 |
+
"serpstack_api_key": app.state.config.SERPSTACK_API_KEY,
|
423 |
+
"serpstack_https": app.state.config.SERPSTACK_HTTPS,
|
424 |
+
"serper_api_key": app.state.config.SERPER_API_KEY,
|
425 |
+
"serply_api_key": app.state.config.SERPLY_API_KEY,
|
426 |
+
"tavily_api_key": app.state.config.TAVILY_API_KEY,
|
427 |
+
"searchapi_api_key": app.state.config.SEARCHAPI_API_KEY,
|
428 |
+
"seaarchapi_engine": app.state.config.SEARCHAPI_ENGINE,
|
429 |
+
"result_count": app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
|
430 |
+
"concurrent_requests": app.state.config.RAG_WEB_SEARCH_CONCURRENT_REQUESTS,
|
431 |
+
},
|
432 |
+
},
|
433 |
+
}
|
434 |
+
|
435 |
+
|
436 |
+
class FileConfig(BaseModel):
|
437 |
+
max_size: Optional[int] = None
|
438 |
+
max_count: Optional[int] = None
|
439 |
+
|
440 |
+
|
441 |
+
class ContentExtractionConfig(BaseModel):
|
442 |
+
engine: str = ""
|
443 |
+
tika_server_url: Optional[str] = None
|
444 |
+
|
445 |
+
|
446 |
+
class ChunkParamUpdateForm(BaseModel):
|
447 |
+
text_splitter: Optional[str] = None
|
448 |
+
chunk_size: int
|
449 |
+
chunk_overlap: int
|
450 |
+
|
451 |
+
|
452 |
+
class YoutubeLoaderConfig(BaseModel):
|
453 |
+
language: list[str]
|
454 |
+
translation: Optional[str] = None
|
455 |
+
|
456 |
+
|
457 |
+
class WebSearchConfig(BaseModel):
|
458 |
+
enabled: bool
|
459 |
+
engine: Optional[str] = None
|
460 |
+
searxng_query_url: Optional[str] = None
|
461 |
+
google_pse_api_key: Optional[str] = None
|
462 |
+
google_pse_engine_id: Optional[str] = None
|
463 |
+
brave_search_api_key: Optional[str] = None
|
464 |
+
serpstack_api_key: Optional[str] = None
|
465 |
+
serpstack_https: Optional[bool] = None
|
466 |
+
serper_api_key: Optional[str] = None
|
467 |
+
serply_api_key: Optional[str] = None
|
468 |
+
tavily_api_key: Optional[str] = None
|
469 |
+
searchapi_api_key: Optional[str] = None
|
470 |
+
searchapi_engine: Optional[str] = None
|
471 |
+
result_count: Optional[int] = None
|
472 |
+
concurrent_requests: Optional[int] = None
|
473 |
+
|
474 |
+
|
475 |
+
class WebConfig(BaseModel):
|
476 |
+
search: WebSearchConfig
|
477 |
+
web_loader_ssl_verification: Optional[bool] = None
|
478 |
+
|
479 |
+
|
480 |
+
class ConfigUpdateForm(BaseModel):
|
481 |
+
pdf_extract_images: Optional[bool] = None
|
482 |
+
file: Optional[FileConfig] = None
|
483 |
+
content_extraction: Optional[ContentExtractionConfig] = None
|
484 |
+
chunk: Optional[ChunkParamUpdateForm] = None
|
485 |
+
youtube: Optional[YoutubeLoaderConfig] = None
|
486 |
+
web: Optional[WebConfig] = None
|
487 |
+
|
488 |
+
|
489 |
+
@app.post("/config/update")
|
490 |
+
async def update_rag_config(form_data: ConfigUpdateForm, user=Depends(get_admin_user)):
|
491 |
+
app.state.config.PDF_EXTRACT_IMAGES = (
|
492 |
+
form_data.pdf_extract_images
|
493 |
+
if form_data.pdf_extract_images is not None
|
494 |
+
else app.state.config.PDF_EXTRACT_IMAGES
|
495 |
+
)
|
496 |
+
|
497 |
+
if form_data.file is not None:
|
498 |
+
app.state.config.FILE_MAX_SIZE = form_data.file.max_size
|
499 |
+
app.state.config.FILE_MAX_COUNT = form_data.file.max_count
|
500 |
+
|
501 |
+
if form_data.content_extraction is not None:
|
502 |
+
log.info(f"Updating text settings: {form_data.content_extraction}")
|
503 |
+
app.state.config.CONTENT_EXTRACTION_ENGINE = form_data.content_extraction.engine
|
504 |
+
app.state.config.TIKA_SERVER_URL = form_data.content_extraction.tika_server_url
|
505 |
+
|
506 |
+
if form_data.chunk is not None:
|
507 |
+
app.state.config.TEXT_SPLITTER = form_data.chunk.text_splitter
|
508 |
+
app.state.config.CHUNK_SIZE = form_data.chunk.chunk_size
|
509 |
+
app.state.config.CHUNK_OVERLAP = form_data.chunk.chunk_overlap
|
510 |
+
|
511 |
+
if form_data.youtube is not None:
|
512 |
+
app.state.config.YOUTUBE_LOADER_LANGUAGE = form_data.youtube.language
|
513 |
+
app.state.YOUTUBE_LOADER_TRANSLATION = form_data.youtube.translation
|
514 |
+
|
515 |
+
if form_data.web is not None:
|
516 |
+
app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION = (
|
517 |
+
form_data.web.web_loader_ssl_verification
|
518 |
+
)
|
519 |
+
|
520 |
+
app.state.config.ENABLE_RAG_WEB_SEARCH = form_data.web.search.enabled
|
521 |
+
app.state.config.RAG_WEB_SEARCH_ENGINE = form_data.web.search.engine
|
522 |
+
app.state.config.SEARXNG_QUERY_URL = form_data.web.search.searxng_query_url
|
523 |
+
app.state.config.GOOGLE_PSE_API_KEY = form_data.web.search.google_pse_api_key
|
524 |
+
app.state.config.GOOGLE_PSE_ENGINE_ID = (
|
525 |
+
form_data.web.search.google_pse_engine_id
|
526 |
+
)
|
527 |
+
app.state.config.BRAVE_SEARCH_API_KEY = (
|
528 |
+
form_data.web.search.brave_search_api_key
|
529 |
+
)
|
530 |
+
app.state.config.SERPSTACK_API_KEY = form_data.web.search.serpstack_api_key
|
531 |
+
app.state.config.SERPSTACK_HTTPS = form_data.web.search.serpstack_https
|
532 |
+
app.state.config.SERPER_API_KEY = form_data.web.search.serper_api_key
|
533 |
+
app.state.config.SERPLY_API_KEY = form_data.web.search.serply_api_key
|
534 |
+
app.state.config.TAVILY_API_KEY = form_data.web.search.tavily_api_key
|
535 |
+
app.state.config.SEARCHAPI_API_KEY = form_data.web.search.searchapi_api_key
|
536 |
+
app.state.config.SEARCHAPI_ENGINE = form_data.web.search.searchapi_engine
|
537 |
+
app.state.config.RAG_WEB_SEARCH_RESULT_COUNT = form_data.web.search.result_count
|
538 |
+
app.state.config.RAG_WEB_SEARCH_CONCURRENT_REQUESTS = (
|
539 |
+
form_data.web.search.concurrent_requests
|
540 |
+
)
|
541 |
+
|
542 |
+
return {
|
543 |
+
"status": True,
|
544 |
+
"pdf_extract_images": app.state.config.PDF_EXTRACT_IMAGES,
|
545 |
+
"file": {
|
546 |
+
"max_size": app.state.config.FILE_MAX_SIZE,
|
547 |
+
"max_count": app.state.config.FILE_MAX_COUNT,
|
548 |
+
},
|
549 |
+
"content_extraction": {
|
550 |
+
"engine": app.state.config.CONTENT_EXTRACTION_ENGINE,
|
551 |
+
"tika_server_url": app.state.config.TIKA_SERVER_URL,
|
552 |
+
},
|
553 |
+
"chunk": {
|
554 |
+
"text_splitter": app.state.config.TEXT_SPLITTER,
|
555 |
+
"chunk_size": app.state.config.CHUNK_SIZE,
|
556 |
+
"chunk_overlap": app.state.config.CHUNK_OVERLAP,
|
557 |
+
},
|
558 |
+
"youtube": {
|
559 |
+
"language": app.state.config.YOUTUBE_LOADER_LANGUAGE,
|
560 |
+
"translation": app.state.YOUTUBE_LOADER_TRANSLATION,
|
561 |
+
},
|
562 |
+
"web": {
|
563 |
+
"ssl_verification": app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION,
|
564 |
+
"search": {
|
565 |
+
"enabled": app.state.config.ENABLE_RAG_WEB_SEARCH,
|
566 |
+
"engine": app.state.config.RAG_WEB_SEARCH_ENGINE,
|
567 |
+
"searxng_query_url": app.state.config.SEARXNG_QUERY_URL,
|
568 |
+
"google_pse_api_key": app.state.config.GOOGLE_PSE_API_KEY,
|
569 |
+
"google_pse_engine_id": app.state.config.GOOGLE_PSE_ENGINE_ID,
|
570 |
+
"brave_search_api_key": app.state.config.BRAVE_SEARCH_API_KEY,
|
571 |
+
"serpstack_api_key": app.state.config.SERPSTACK_API_KEY,
|
572 |
+
"serpstack_https": app.state.config.SERPSTACK_HTTPS,
|
573 |
+
"serper_api_key": app.state.config.SERPER_API_KEY,
|
574 |
+
"serply_api_key": app.state.config.SERPLY_API_KEY,
|
575 |
+
"serachapi_api_key": app.state.config.SEARCHAPI_API_KEY,
|
576 |
+
"searchapi_engine": app.state.config.SEARCHAPI_ENGINE,
|
577 |
+
"tavily_api_key": app.state.config.TAVILY_API_KEY,
|
578 |
+
"result_count": app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
|
579 |
+
"concurrent_requests": app.state.config.RAG_WEB_SEARCH_CONCURRENT_REQUESTS,
|
580 |
+
},
|
581 |
+
},
|
582 |
+
}
|
583 |
+
|
584 |
+
|
585 |
+
@app.get("/template")
|
586 |
+
async def get_rag_template(user=Depends(get_verified_user)):
|
587 |
+
return {
|
588 |
+
"status": True,
|
589 |
+
"template": app.state.config.RAG_TEMPLATE,
|
590 |
+
}
|
591 |
+
|
592 |
+
|
593 |
+
@app.get("/query/settings")
|
594 |
+
async def get_query_settings(user=Depends(get_admin_user)):
|
595 |
+
return {
|
596 |
+
"status": True,
|
597 |
+
"template": app.state.config.RAG_TEMPLATE,
|
598 |
+
"k": app.state.config.TOP_K,
|
599 |
+
"r": app.state.config.RELEVANCE_THRESHOLD,
|
600 |
+
"hybrid": app.state.config.ENABLE_RAG_HYBRID_SEARCH,
|
601 |
+
}
|
602 |
+
|
603 |
+
|
604 |
+
class QuerySettingsForm(BaseModel):
|
605 |
+
k: Optional[int] = None
|
606 |
+
r: Optional[float] = None
|
607 |
+
template: Optional[str] = None
|
608 |
+
hybrid: Optional[bool] = None
|
609 |
+
|
610 |
+
|
611 |
+
@app.post("/query/settings/update")
|
612 |
+
async def update_query_settings(
|
613 |
+
form_data: QuerySettingsForm, user=Depends(get_admin_user)
|
614 |
+
):
|
615 |
+
app.state.config.RAG_TEMPLATE = form_data.template
|
616 |
+
app.state.config.TOP_K = form_data.k if form_data.k else 4
|
617 |
+
app.state.config.RELEVANCE_THRESHOLD = form_data.r if form_data.r else 0.0
|
618 |
+
|
619 |
+
app.state.config.ENABLE_RAG_HYBRID_SEARCH = (
|
620 |
+
form_data.hybrid if form_data.hybrid else False
|
621 |
+
)
|
622 |
+
|
623 |
+
return {
|
624 |
+
"status": True,
|
625 |
+
"template": app.state.config.RAG_TEMPLATE,
|
626 |
+
"k": app.state.config.TOP_K,
|
627 |
+
"r": app.state.config.RELEVANCE_THRESHOLD,
|
628 |
+
"hybrid": app.state.config.ENABLE_RAG_HYBRID_SEARCH,
|
629 |
+
}
|
630 |
+
|
631 |
+
|
632 |
+
####################################
|
633 |
+
#
|
634 |
+
# Document process and retrieval
|
635 |
+
#
|
636 |
+
####################################
|
637 |
+
|
638 |
+
|
639 |
+
def save_docs_to_vector_db(
|
640 |
+
docs,
|
641 |
+
collection_name,
|
642 |
+
metadata: Optional[dict] = None,
|
643 |
+
overwrite: bool = False,
|
644 |
+
split: bool = True,
|
645 |
+
add: bool = False,
|
646 |
+
) -> bool:
|
647 |
+
log.info(f"save_docs_to_vector_db {docs} {collection_name}")
|
648 |
+
|
649 |
+
# Check if entries with the same hash (metadata.hash) already exist
|
650 |
+
if metadata and "hash" in metadata:
|
651 |
+
result = VECTOR_DB_CLIENT.query(
|
652 |
+
collection_name=collection_name,
|
653 |
+
filter={"hash": metadata["hash"]},
|
654 |
+
)
|
655 |
+
|
656 |
+
if result is not None:
|
657 |
+
existing_doc_ids = result.ids[0]
|
658 |
+
if existing_doc_ids:
|
659 |
+
log.info(f"Document with hash {metadata['hash']} already exists")
|
660 |
+
raise ValueError(ERROR_MESSAGES.DUPLICATE_CONTENT)
|
661 |
+
|
662 |
+
if split:
|
663 |
+
if app.state.config.TEXT_SPLITTER in ["", "character"]:
|
664 |
+
text_splitter = RecursiveCharacterTextSplitter(
|
665 |
+
chunk_size=app.state.config.CHUNK_SIZE,
|
666 |
+
chunk_overlap=app.state.config.CHUNK_OVERLAP,
|
667 |
+
add_start_index=True,
|
668 |
+
)
|
669 |
+
elif app.state.config.TEXT_SPLITTER == "token":
|
670 |
+
log.info(
|
671 |
+
f"Using token text splitter: {app.state.config.TIKTOKEN_ENCODING_NAME}"
|
672 |
+
)
|
673 |
+
|
674 |
+
tiktoken.get_encoding(str(app.state.config.TIKTOKEN_ENCODING_NAME))
|
675 |
+
text_splitter = TokenTextSplitter(
|
676 |
+
encoding_name=str(app.state.config.TIKTOKEN_ENCODING_NAME),
|
677 |
+
chunk_size=app.state.config.CHUNK_SIZE,
|
678 |
+
chunk_overlap=app.state.config.CHUNK_OVERLAP,
|
679 |
+
add_start_index=True,
|
680 |
+
)
|
681 |
+
else:
|
682 |
+
raise ValueError(ERROR_MESSAGES.DEFAULT("Invalid text splitter"))
|
683 |
+
|
684 |
+
docs = text_splitter.split_documents(docs)
|
685 |
+
|
686 |
+
if len(docs) == 0:
|
687 |
+
raise ValueError(ERROR_MESSAGES.EMPTY_CONTENT)
|
688 |
+
|
689 |
+
texts = [doc.page_content for doc in docs]
|
690 |
+
metadatas = [
|
691 |
+
{
|
692 |
+
**doc.metadata,
|
693 |
+
**(metadata if metadata else {}),
|
694 |
+
"embedding_config": json.dumps(
|
695 |
+
{
|
696 |
+
"engine": app.state.config.RAG_EMBEDDING_ENGINE,
|
697 |
+
"model": app.state.config.RAG_EMBEDDING_MODEL,
|
698 |
+
}
|
699 |
+
),
|
700 |
+
}
|
701 |
+
for doc in docs
|
702 |
+
]
|
703 |
+
|
704 |
+
# ChromaDB does not like datetime formats
|
705 |
+
# for meta-data so convert them to string.
|
706 |
+
for metadata in metadatas:
|
707 |
+
for key, value in metadata.items():
|
708 |
+
if isinstance(value, datetime):
|
709 |
+
metadata[key] = str(value)
|
710 |
+
|
711 |
+
try:
|
712 |
+
if VECTOR_DB_CLIENT.has_collection(collection_name=collection_name):
|
713 |
+
log.info(f"collection {collection_name} already exists")
|
714 |
+
|
715 |
+
if overwrite:
|
716 |
+
VECTOR_DB_CLIENT.delete_collection(collection_name=collection_name)
|
717 |
+
log.info(f"deleting existing collection {collection_name}")
|
718 |
+
elif add is False:
|
719 |
+
log.info(
|
720 |
+
f"collection {collection_name} already exists, overwrite is False and add is False"
|
721 |
+
)
|
722 |
+
return True
|
723 |
+
|
724 |
+
log.info(f"adding to collection {collection_name}")
|
725 |
+
embedding_function = get_embedding_function(
|
726 |
+
app.state.config.RAG_EMBEDDING_ENGINE,
|
727 |
+
app.state.config.RAG_EMBEDDING_MODEL,
|
728 |
+
app.state.sentence_transformer_ef,
|
729 |
+
app.state.config.OPENAI_API_KEY,
|
730 |
+
app.state.config.OPENAI_API_BASE_URL,
|
731 |
+
app.state.config.RAG_EMBEDDING_BATCH_SIZE,
|
732 |
+
)
|
733 |
+
|
734 |
+
embeddings = embedding_function(
|
735 |
+
list(map(lambda x: x.replace("\n", " "), texts))
|
736 |
+
)
|
737 |
+
|
738 |
+
items = [
|
739 |
+
{
|
740 |
+
"id": str(uuid.uuid4()),
|
741 |
+
"text": text,
|
742 |
+
"vector": embeddings[idx],
|
743 |
+
"metadata": metadatas[idx],
|
744 |
+
}
|
745 |
+
for idx, text in enumerate(texts)
|
746 |
+
]
|
747 |
+
|
748 |
+
VECTOR_DB_CLIENT.insert(
|
749 |
+
collection_name=collection_name,
|
750 |
+
items=items,
|
751 |
+
)
|
752 |
+
|
753 |
+
return True
|
754 |
+
except Exception as e:
|
755 |
+
log.exception(e)
|
756 |
+
return False
|
757 |
+
|
758 |
+
|
759 |
+
class ProcessFileForm(BaseModel):
|
760 |
+
file_id: str
|
761 |
+
content: Optional[str] = None
|
762 |
+
collection_name: Optional[str] = None
|
763 |
+
|
764 |
+
|
765 |
+
@app.post("/process/file")
|
766 |
+
def process_file(
|
767 |
+
form_data: ProcessFileForm,
|
768 |
+
user=Depends(get_verified_user),
|
769 |
+
):
|
770 |
+
try:
|
771 |
+
file = Files.get_file_by_id(form_data.file_id)
|
772 |
+
|
773 |
+
collection_name = form_data.collection_name
|
774 |
+
|
775 |
+
if collection_name is None:
|
776 |
+
collection_name = f"file-{file.id}"
|
777 |
+
|
778 |
+
if form_data.content:
|
779 |
+
# Update the content in the file
|
780 |
+
# Usage: /files/{file_id}/data/content/update
|
781 |
+
|
782 |
+
VECTOR_DB_CLIENT.delete(
|
783 |
+
collection_name=f"file-{file.id}",
|
784 |
+
filter={"file_id": file.id},
|
785 |
+
)
|
786 |
+
|
787 |
+
docs = [
|
788 |
+
Document(
|
789 |
+
page_content=form_data.content,
|
790 |
+
metadata={
|
791 |
+
"name": file.meta.get("name", file.filename),
|
792 |
+
"created_by": file.user_id,
|
793 |
+
"file_id": file.id,
|
794 |
+
**file.meta,
|
795 |
+
},
|
796 |
+
)
|
797 |
+
]
|
798 |
+
|
799 |
+
text_content = form_data.content
|
800 |
+
elif form_data.collection_name:
|
801 |
+
# Check if the file has already been processed and save the content
|
802 |
+
# Usage: /knowledge/{id}/file/add, /knowledge/{id}/file/update
|
803 |
+
|
804 |
+
result = VECTOR_DB_CLIENT.query(
|
805 |
+
collection_name=f"file-{file.id}", filter={"file_id": file.id}
|
806 |
+
)
|
807 |
+
|
808 |
+
if result is not None and len(result.ids[0]) > 0:
|
809 |
+
docs = [
|
810 |
+
Document(
|
811 |
+
page_content=result.documents[0][idx],
|
812 |
+
metadata=result.metadatas[0][idx],
|
813 |
+
)
|
814 |
+
for idx, id in enumerate(result.ids[0])
|
815 |
+
]
|
816 |
+
else:
|
817 |
+
docs = [
|
818 |
+
Document(
|
819 |
+
page_content=file.data.get("content", ""),
|
820 |
+
metadata={
|
821 |
+
"name": file.meta.get("name", file.filename),
|
822 |
+
"created_by": file.user_id,
|
823 |
+
"file_id": file.id,
|
824 |
+
**file.meta,
|
825 |
+
},
|
826 |
+
)
|
827 |
+
]
|
828 |
+
|
829 |
+
text_content = file.data.get("content", "")
|
830 |
+
else:
|
831 |
+
# Process the file and save the content
|
832 |
+
# Usage: /files/
|
833 |
+
file_path = file.path
|
834 |
+
if file_path:
|
835 |
+
file_path = Storage.get_file(file_path)
|
836 |
+
loader = Loader(
|
837 |
+
engine=app.state.config.CONTENT_EXTRACTION_ENGINE,
|
838 |
+
TIKA_SERVER_URL=app.state.config.TIKA_SERVER_URL,
|
839 |
+
PDF_EXTRACT_IMAGES=app.state.config.PDF_EXTRACT_IMAGES,
|
840 |
+
)
|
841 |
+
docs = loader.load(
|
842 |
+
file.filename, file.meta.get("content_type"), file_path
|
843 |
+
)
|
844 |
+
else:
|
845 |
+
docs = [
|
846 |
+
Document(
|
847 |
+
page_content=file.data.get("content", ""),
|
848 |
+
metadata={
|
849 |
+
"name": file.filename,
|
850 |
+
"created_by": file.user_id,
|
851 |
+
"file_id": file.id,
|
852 |
+
**file.meta,
|
853 |
+
},
|
854 |
+
)
|
855 |
+
]
|
856 |
+
text_content = " ".join([doc.page_content for doc in docs])
|
857 |
+
|
858 |
+
log.debug(f"text_content: {text_content}")
|
859 |
+
Files.update_file_data_by_id(
|
860 |
+
file.id,
|
861 |
+
{"content": text_content},
|
862 |
+
)
|
863 |
+
|
864 |
+
hash = calculate_sha256_string(text_content)
|
865 |
+
Files.update_file_hash_by_id(file.id, hash)
|
866 |
+
|
867 |
+
try:
|
868 |
+
result = save_docs_to_vector_db(
|
869 |
+
docs=docs,
|
870 |
+
collection_name=collection_name,
|
871 |
+
metadata={
|
872 |
+
"file_id": file.id,
|
873 |
+
"name": file.meta.get("name", file.filename),
|
874 |
+
"hash": hash,
|
875 |
+
},
|
876 |
+
add=(True if form_data.collection_name else False),
|
877 |
+
)
|
878 |
+
|
879 |
+
if result:
|
880 |
+
Files.update_file_metadata_by_id(
|
881 |
+
file.id,
|
882 |
+
{
|
883 |
+
"collection_name": collection_name,
|
884 |
+
},
|
885 |
+
)
|
886 |
+
|
887 |
+
return {
|
888 |
+
"status": True,
|
889 |
+
"collection_name": collection_name,
|
890 |
+
"filename": file.meta.get("name", file.filename),
|
891 |
+
"content": text_content,
|
892 |
+
}
|
893 |
+
except Exception as e:
|
894 |
+
raise e
|
895 |
+
except Exception as e:
|
896 |
+
log.exception(e)
|
897 |
+
if "No pandoc was found" in str(e):
|
898 |
+
raise HTTPException(
|
899 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
900 |
+
detail=ERROR_MESSAGES.PANDOC_NOT_INSTALLED,
|
901 |
+
)
|
902 |
+
else:
|
903 |
+
raise HTTPException(
|
904 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
905 |
+
detail=str(e),
|
906 |
+
)
|
907 |
+
|
908 |
+
|
909 |
+
class ProcessTextForm(BaseModel):
|
910 |
+
name: str
|
911 |
+
content: str
|
912 |
+
collection_name: Optional[str] = None
|
913 |
+
|
914 |
+
|
915 |
+
@app.post("/process/text")
|
916 |
+
def process_text(
|
917 |
+
form_data: ProcessTextForm,
|
918 |
+
user=Depends(get_verified_user),
|
919 |
+
):
|
920 |
+
collection_name = form_data.collection_name
|
921 |
+
if collection_name is None:
|
922 |
+
collection_name = calculate_sha256_string(form_data.content)
|
923 |
+
|
924 |
+
docs = [
|
925 |
+
Document(
|
926 |
+
page_content=form_data.content,
|
927 |
+
metadata={"name": form_data.name, "created_by": user.id},
|
928 |
+
)
|
929 |
+
]
|
930 |
+
text_content = form_data.content
|
931 |
+
log.debug(f"text_content: {text_content}")
|
932 |
+
|
933 |
+
result = save_docs_to_vector_db(docs, collection_name)
|
934 |
+
|
935 |
+
if result:
|
936 |
+
return {
|
937 |
+
"status": True,
|
938 |
+
"collection_name": collection_name,
|
939 |
+
"content": text_content,
|
940 |
+
}
|
941 |
+
else:
|
942 |
+
raise HTTPException(
|
943 |
+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
944 |
+
detail=ERROR_MESSAGES.DEFAULT(),
|
945 |
+
)
|
946 |
+
|
947 |
+
|
948 |
+
@app.post("/process/youtube")
|
949 |
+
def process_youtube_video(form_data: ProcessUrlForm, user=Depends(get_verified_user)):
|
950 |
+
try:
|
951 |
+
collection_name = form_data.collection_name
|
952 |
+
if not collection_name:
|
953 |
+
collection_name = calculate_sha256_string(form_data.url)[:63]
|
954 |
+
|
955 |
+
loader = YoutubeLoader.from_youtube_url(
|
956 |
+
form_data.url,
|
957 |
+
add_video_info=True,
|
958 |
+
language=app.state.config.YOUTUBE_LOADER_LANGUAGE,
|
959 |
+
translation=app.state.YOUTUBE_LOADER_TRANSLATION,
|
960 |
+
)
|
961 |
+
docs = loader.load()
|
962 |
+
content = " ".join([doc.page_content for doc in docs])
|
963 |
+
log.debug(f"text_content: {content}")
|
964 |
+
save_docs_to_vector_db(docs, collection_name, overwrite=True)
|
965 |
+
|
966 |
+
return {
|
967 |
+
"status": True,
|
968 |
+
"collection_name": collection_name,
|
969 |
+
"filename": form_data.url,
|
970 |
+
"file": {
|
971 |
+
"data": {
|
972 |
+
"content": content,
|
973 |
+
},
|
974 |
+
"meta": {
|
975 |
+
"name": form_data.url,
|
976 |
+
},
|
977 |
+
},
|
978 |
+
}
|
979 |
+
except Exception as e:
|
980 |
+
log.exception(e)
|
981 |
+
raise HTTPException(
|
982 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
983 |
+
detail=ERROR_MESSAGES.DEFAULT(e),
|
984 |
+
)
|
985 |
+
|
986 |
+
|
987 |
+
@app.post("/process/web")
|
988 |
+
def process_web(form_data: ProcessUrlForm, user=Depends(get_verified_user)):
|
989 |
+
try:
|
990 |
+
collection_name = form_data.collection_name
|
991 |
+
if not collection_name:
|
992 |
+
collection_name = calculate_sha256_string(form_data.url)[:63]
|
993 |
+
|
994 |
+
loader = get_web_loader(
|
995 |
+
form_data.url,
|
996 |
+
verify_ssl=app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION,
|
997 |
+
requests_per_second=app.state.config.RAG_WEB_SEARCH_CONCURRENT_REQUESTS,
|
998 |
+
)
|
999 |
+
docs = loader.load()
|
1000 |
+
content = " ".join([doc.page_content for doc in docs])
|
1001 |
+
log.debug(f"text_content: {content}")
|
1002 |
+
save_docs_to_vector_db(docs, collection_name, overwrite=True)
|
1003 |
+
|
1004 |
+
return {
|
1005 |
+
"status": True,
|
1006 |
+
"collection_name": collection_name,
|
1007 |
+
"filename": form_data.url,
|
1008 |
+
"file": {
|
1009 |
+
"data": {
|
1010 |
+
"content": content,
|
1011 |
+
},
|
1012 |
+
"meta": {
|
1013 |
+
"name": form_data.url,
|
1014 |
+
},
|
1015 |
+
},
|
1016 |
+
}
|
1017 |
+
except Exception as e:
|
1018 |
+
log.exception(e)
|
1019 |
+
raise HTTPException(
|
1020 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
1021 |
+
detail=ERROR_MESSAGES.DEFAULT(e),
|
1022 |
+
)
|
1023 |
+
|
1024 |
+
|
1025 |
+
def search_web(engine: str, query: str) -> list[SearchResult]:
|
1026 |
+
"""Search the web using a search engine and return the results as a list of SearchResult objects.
|
1027 |
+
Will look for a search engine API key in environment variables in the following order:
|
1028 |
+
- SEARXNG_QUERY_URL
|
1029 |
+
- GOOGLE_PSE_API_KEY + GOOGLE_PSE_ENGINE_ID
|
1030 |
+
- BRAVE_SEARCH_API_KEY
|
1031 |
+
- SERPSTACK_API_KEY
|
1032 |
+
- SERPER_API_KEY
|
1033 |
+
- SERPLY_API_KEY
|
1034 |
+
- TAVILY_API_KEY
|
1035 |
+
- SEARCHAPI_API_KEY + SEARCHAPI_ENGINE (by default `google`)
|
1036 |
+
Args:
|
1037 |
+
query (str): The query to search for
|
1038 |
+
"""
|
1039 |
+
|
1040 |
+
# TODO: add playwright to search the web
|
1041 |
+
if engine == "searxng":
|
1042 |
+
if app.state.config.SEARXNG_QUERY_URL:
|
1043 |
+
return search_searxng(
|
1044 |
+
app.state.config.SEARXNG_QUERY_URL,
|
1045 |
+
query,
|
1046 |
+
app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
|
1047 |
+
app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
|
1048 |
+
)
|
1049 |
+
else:
|
1050 |
+
raise Exception("No SEARXNG_QUERY_URL found in environment variables")
|
1051 |
+
elif engine == "google_pse":
|
1052 |
+
if (
|
1053 |
+
app.state.config.GOOGLE_PSE_API_KEY
|
1054 |
+
and app.state.config.GOOGLE_PSE_ENGINE_ID
|
1055 |
+
):
|
1056 |
+
return search_google_pse(
|
1057 |
+
app.state.config.GOOGLE_PSE_API_KEY,
|
1058 |
+
app.state.config.GOOGLE_PSE_ENGINE_ID,
|
1059 |
+
query,
|
1060 |
+
app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
|
1061 |
+
app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
|
1062 |
+
)
|
1063 |
+
else:
|
1064 |
+
raise Exception(
|
1065 |
+
"No GOOGLE_PSE_API_KEY or GOOGLE_PSE_ENGINE_ID found in environment variables"
|
1066 |
+
)
|
1067 |
+
elif engine == "brave":
|
1068 |
+
if app.state.config.BRAVE_SEARCH_API_KEY:
|
1069 |
+
return search_brave(
|
1070 |
+
app.state.config.BRAVE_SEARCH_API_KEY,
|
1071 |
+
query,
|
1072 |
+
app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
|
1073 |
+
app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
|
1074 |
+
)
|
1075 |
+
else:
|
1076 |
+
raise Exception("No BRAVE_SEARCH_API_KEY found in environment variables")
|
1077 |
+
elif engine == "serpstack":
|
1078 |
+
if app.state.config.SERPSTACK_API_KEY:
|
1079 |
+
return search_serpstack(
|
1080 |
+
app.state.config.SERPSTACK_API_KEY,
|
1081 |
+
query,
|
1082 |
+
app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
|
1083 |
+
app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
|
1084 |
+
https_enabled=app.state.config.SERPSTACK_HTTPS,
|
1085 |
+
)
|
1086 |
+
else:
|
1087 |
+
raise Exception("No SERPSTACK_API_KEY found in environment variables")
|
1088 |
+
elif engine == "serper":
|
1089 |
+
if app.state.config.SERPER_API_KEY:
|
1090 |
+
return search_serper(
|
1091 |
+
app.state.config.SERPER_API_KEY,
|
1092 |
+
query,
|
1093 |
+
app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
|
1094 |
+
app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
|
1095 |
+
)
|
1096 |
+
else:
|
1097 |
+
raise Exception("No SERPER_API_KEY found in environment variables")
|
1098 |
+
elif engine == "serply":
|
1099 |
+
if app.state.config.SERPLY_API_KEY:
|
1100 |
+
return search_serply(
|
1101 |
+
app.state.config.SERPLY_API_KEY,
|
1102 |
+
query,
|
1103 |
+
app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
|
1104 |
+
app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
|
1105 |
+
)
|
1106 |
+
else:
|
1107 |
+
raise Exception("No SERPLY_API_KEY found in environment variables")
|
1108 |
+
elif engine == "duckduckgo":
|
1109 |
+
return search_duckduckgo(
|
1110 |
+
query,
|
1111 |
+
app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
|
1112 |
+
app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
|
1113 |
+
)
|
1114 |
+
elif engine == "tavily":
|
1115 |
+
if app.state.config.TAVILY_API_KEY:
|
1116 |
+
return search_tavily(
|
1117 |
+
app.state.config.TAVILY_API_KEY,
|
1118 |
+
query,
|
1119 |
+
app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
|
1120 |
+
)
|
1121 |
+
else:
|
1122 |
+
raise Exception("No TAVILY_API_KEY found in environment variables")
|
1123 |
+
elif engine == "searchapi":
|
1124 |
+
if app.state.config.SEARCHAPI_API_KEY:
|
1125 |
+
return search_searchapi(
|
1126 |
+
app.state.config.SEARCHAPI_API_KEY,
|
1127 |
+
app.state.config.SEARCHAPI_ENGINE,
|
1128 |
+
query,
|
1129 |
+
app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
|
1130 |
+
app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
|
1131 |
+
)
|
1132 |
+
else:
|
1133 |
+
raise Exception("No SEARCHAPI_API_KEY found in environment variables")
|
1134 |
+
elif engine == "jina":
|
1135 |
+
return search_jina(query, app.state.config.RAG_WEB_SEARCH_RESULT_COUNT)
|
1136 |
+
else:
|
1137 |
+
raise Exception("No search engine API key found in environment variables")
|
1138 |
+
|
1139 |
+
|
1140 |
+
@app.post("/process/web/search")
|
1141 |
+
def process_web_search(form_data: SearchForm, user=Depends(get_verified_user)):
|
1142 |
+
try:
|
1143 |
+
logging.info(
|
1144 |
+
f"trying to web search with {app.state.config.RAG_WEB_SEARCH_ENGINE, form_data.query}"
|
1145 |
+
)
|
1146 |
+
web_results = search_web(
|
1147 |
+
app.state.config.RAG_WEB_SEARCH_ENGINE, form_data.query
|
1148 |
+
)
|
1149 |
+
except Exception as e:
|
1150 |
+
log.exception(e)
|
1151 |
+
|
1152 |
+
print(e)
|
1153 |
+
raise HTTPException(
|
1154 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
1155 |
+
detail=ERROR_MESSAGES.WEB_SEARCH_ERROR(e),
|
1156 |
+
)
|
1157 |
+
|
1158 |
+
try:
|
1159 |
+
collection_name = form_data.collection_name
|
1160 |
+
if collection_name == "":
|
1161 |
+
collection_name = calculate_sha256_string(form_data.query)[:63]
|
1162 |
+
|
1163 |
+
urls = [result.link for result in web_results]
|
1164 |
+
|
1165 |
+
loader = get_web_loader(urls)
|
1166 |
+
docs = loader.load()
|
1167 |
+
|
1168 |
+
save_docs_to_vector_db(docs, collection_name, overwrite=True)
|
1169 |
+
|
1170 |
+
return {
|
1171 |
+
"status": True,
|
1172 |
+
"collection_name": collection_name,
|
1173 |
+
"filenames": urls,
|
1174 |
+
}
|
1175 |
+
except Exception as e:
|
1176 |
+
log.exception(e)
|
1177 |
+
raise HTTPException(
|
1178 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
1179 |
+
detail=ERROR_MESSAGES.DEFAULT(e),
|
1180 |
+
)
|
1181 |
+
|
1182 |
+
|
1183 |
+
class QueryDocForm(BaseModel):
|
1184 |
+
collection_name: str
|
1185 |
+
query: str
|
1186 |
+
k: Optional[int] = None
|
1187 |
+
r: Optional[float] = None
|
1188 |
+
hybrid: Optional[bool] = None
|
1189 |
+
|
1190 |
+
|
1191 |
+
@app.post("/query/doc")
|
1192 |
+
def query_doc_handler(
|
1193 |
+
form_data: QueryDocForm,
|
1194 |
+
user=Depends(get_verified_user),
|
1195 |
+
):
|
1196 |
+
try:
|
1197 |
+
if app.state.config.ENABLE_RAG_HYBRID_SEARCH:
|
1198 |
+
return query_doc_with_hybrid_search(
|
1199 |
+
collection_name=form_data.collection_name,
|
1200 |
+
query=form_data.query,
|
1201 |
+
embedding_function=app.state.EMBEDDING_FUNCTION,
|
1202 |
+
k=form_data.k if form_data.k else app.state.config.TOP_K,
|
1203 |
+
reranking_function=app.state.sentence_transformer_rf,
|
1204 |
+
r=(
|
1205 |
+
form_data.r if form_data.r else app.state.config.RELEVANCE_THRESHOLD
|
1206 |
+
),
|
1207 |
+
)
|
1208 |
+
else:
|
1209 |
+
return query_doc(
|
1210 |
+
collection_name=form_data.collection_name,
|
1211 |
+
query=form_data.query,
|
1212 |
+
embedding_function=app.state.EMBEDDING_FUNCTION,
|
1213 |
+
k=form_data.k if form_data.k else app.state.config.TOP_K,
|
1214 |
+
)
|
1215 |
+
except Exception as e:
|
1216 |
+
log.exception(e)
|
1217 |
+
raise HTTPException(
|
1218 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
1219 |
+
detail=ERROR_MESSAGES.DEFAULT(e),
|
1220 |
+
)
|
1221 |
+
|
1222 |
+
|
1223 |
+
class QueryCollectionsForm(BaseModel):
|
1224 |
+
collection_names: list[str]
|
1225 |
+
query: str
|
1226 |
+
k: Optional[int] = None
|
1227 |
+
r: Optional[float] = None
|
1228 |
+
hybrid: Optional[bool] = None
|
1229 |
+
|
1230 |
+
|
1231 |
+
@app.post("/query/collection")
|
1232 |
+
def query_collection_handler(
|
1233 |
+
form_data: QueryCollectionsForm,
|
1234 |
+
user=Depends(get_verified_user),
|
1235 |
+
):
|
1236 |
+
try:
|
1237 |
+
if app.state.config.ENABLE_RAG_HYBRID_SEARCH:
|
1238 |
+
return query_collection_with_hybrid_search(
|
1239 |
+
collection_names=form_data.collection_names,
|
1240 |
+
query=form_data.query,
|
1241 |
+
embedding_function=app.state.EMBEDDING_FUNCTION,
|
1242 |
+
k=form_data.k if form_data.k else app.state.config.TOP_K,
|
1243 |
+
reranking_function=app.state.sentence_transformer_rf,
|
1244 |
+
r=(
|
1245 |
+
form_data.r if form_data.r else app.state.config.RELEVANCE_THRESHOLD
|
1246 |
+
),
|
1247 |
+
)
|
1248 |
+
else:
|
1249 |
+
return query_collection(
|
1250 |
+
collection_names=form_data.collection_names,
|
1251 |
+
query=form_data.query,
|
1252 |
+
embedding_function=app.state.EMBEDDING_FUNCTION,
|
1253 |
+
k=form_data.k if form_data.k else app.state.config.TOP_K,
|
1254 |
+
)
|
1255 |
+
|
1256 |
+
except Exception as e:
|
1257 |
+
log.exception(e)
|
1258 |
+
raise HTTPException(
|
1259 |
+
status_code=status.HTTP_400_BAD_REQUEST,
|
1260 |
+
detail=ERROR_MESSAGES.DEFAULT(e),
|
1261 |
+
)
|
1262 |
+
|
1263 |
+
|
1264 |
+
####################################
|
1265 |
+
#
|
1266 |
+
# Vector DB operations
|
1267 |
+
#
|
1268 |
+
####################################
|
1269 |
+
|
1270 |
+
|
1271 |
+
class DeleteForm(BaseModel):
|
1272 |
+
collection_name: str
|
1273 |
+
file_id: str
|
1274 |
+
|
1275 |
+
|
1276 |
+
@app.post("/delete")
|
1277 |
+
def delete_entries_from_collection(form_data: DeleteForm, user=Depends(get_admin_user)):
|
1278 |
+
try:
|
1279 |
+
if VECTOR_DB_CLIENT.has_collection(collection_name=form_data.collection_name):
|
1280 |
+
file = Files.get_file_by_id(form_data.file_id)
|
1281 |
+
hash = file.hash
|
1282 |
+
|
1283 |
+
VECTOR_DB_CLIENT.delete(
|
1284 |
+
collection_name=form_data.collection_name,
|
1285 |
+
metadata={"hash": hash},
|
1286 |
+
)
|
1287 |
+
return {"status": True}
|
1288 |
+
else:
|
1289 |
+
return {"status": False}
|
1290 |
+
except Exception as e:
|
1291 |
+
log.exception(e)
|
1292 |
+
return {"status": False}
|
1293 |
+
|
1294 |
+
|
1295 |
+
@app.post("/reset/db")
|
1296 |
+
def reset_vector_db(user=Depends(get_admin_user)):
|
1297 |
+
VECTOR_DB_CLIENT.reset()
|
1298 |
+
Knowledges.delete_all_knowledge()
|
1299 |
+
|
1300 |
+
|
1301 |
+
@app.post("/reset/uploads")
|
1302 |
+
def reset_upload_dir(user=Depends(get_admin_user)) -> bool:
|
1303 |
+
folder = f"{UPLOAD_DIR}"
|
1304 |
+
try:
|
1305 |
+
# Check if the directory exists
|
1306 |
+
if os.path.exists(folder):
|
1307 |
+
# Iterate over all the files and directories in the specified directory
|
1308 |
+
for filename in os.listdir(folder):
|
1309 |
+
file_path = os.path.join(folder, filename)
|
1310 |
+
try:
|
1311 |
+
if os.path.isfile(file_path) or os.path.islink(file_path):
|
1312 |
+
os.unlink(file_path) # Remove the file or link
|
1313 |
+
elif os.path.isdir(file_path):
|
1314 |
+
shutil.rmtree(file_path) # Remove the directory
|
1315 |
+
except Exception as e:
|
1316 |
+
print(f"Failed to delete {file_path}. Reason: {e}")
|
1317 |
+
else:
|
1318 |
+
print(f"The directory {folder} does not exist")
|
1319 |
+
except Exception as e:
|
1320 |
+
print(f"Failed to process the directory {folder}. Reason: {e}")
|
1321 |
+
return True
|
1322 |
+
|
1323 |
+
|
1324 |
+
if ENV == "dev":
|
1325 |
+
|
1326 |
+
@app.get("/ef")
|
1327 |
+
async def get_embeddings():
|
1328 |
+
return {"result": app.state.EMBEDDING_FUNCTION("hello world")}
|
1329 |
+
|
1330 |
+
@app.get("/ef/{text}")
|
1331 |
+
async def get_embeddings_text(text: str):
|
1332 |
+
return {"result": app.state.EMBEDDING_FUNCTION(text)}
|
backend/open_webui/apps/retrieval/models/colbert.py
ADDED
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import torch
|
3 |
+
import numpy as np
|
4 |
+
from colbert.infra import ColBERTConfig
|
5 |
+
from colbert.modeling.checkpoint import Checkpoint
|
6 |
+
|
7 |
+
|
8 |
+
class ColBERT:
|
9 |
+
def __init__(self, name, **kwargs) -> None:
|
10 |
+
print("ColBERT: Loading model", name)
|
11 |
+
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
12 |
+
|
13 |
+
DOCKER = kwargs.get("env") == "docker"
|
14 |
+
if DOCKER:
|
15 |
+
# This is a workaround for the issue with the docker container
|
16 |
+
# where the torch extension is not loaded properly
|
17 |
+
# and the following error is thrown:
|
18 |
+
# /root/.cache/torch_extensions/py311_cpu/segmented_maxsim_cpp/segmented_maxsim_cpp.so: cannot open shared object file: No such file or directory
|
19 |
+
|
20 |
+
lock_file = (
|
21 |
+
"/root/.cache/torch_extensions/py311_cpu/segmented_maxsim_cpp/lock"
|
22 |
+
)
|
23 |
+
if os.path.exists(lock_file):
|
24 |
+
os.remove(lock_file)
|
25 |
+
|
26 |
+
self.ckpt = Checkpoint(
|
27 |
+
name,
|
28 |
+
colbert_config=ColBERTConfig(model_name=name),
|
29 |
+
).to(self.device)
|
30 |
+
pass
|
31 |
+
|
32 |
+
def calculate_similarity_scores(self, query_embeddings, document_embeddings):
|
33 |
+
|
34 |
+
query_embeddings = query_embeddings.to(self.device)
|
35 |
+
document_embeddings = document_embeddings.to(self.device)
|
36 |
+
|
37 |
+
# Validate dimensions to ensure compatibility
|
38 |
+
if query_embeddings.dim() != 3:
|
39 |
+
raise ValueError(
|
40 |
+
f"Expected query embeddings to have 3 dimensions, but got {query_embeddings.dim()}."
|
41 |
+
)
|
42 |
+
if document_embeddings.dim() != 3:
|
43 |
+
raise ValueError(
|
44 |
+
f"Expected document embeddings to have 3 dimensions, but got {document_embeddings.dim()}."
|
45 |
+
)
|
46 |
+
if query_embeddings.size(0) not in [1, document_embeddings.size(0)]:
|
47 |
+
raise ValueError(
|
48 |
+
"There should be either one query or queries equal to the number of documents."
|
49 |
+
)
|
50 |
+
|
51 |
+
# Transpose the query embeddings to align for matrix multiplication
|
52 |
+
transposed_query_embeddings = query_embeddings.permute(0, 2, 1)
|
53 |
+
# Compute similarity scores using batch matrix multiplication
|
54 |
+
computed_scores = torch.matmul(document_embeddings, transposed_query_embeddings)
|
55 |
+
# Apply max pooling to extract the highest semantic similarity across each document's sequence
|
56 |
+
maximum_scores = torch.max(computed_scores, dim=1).values
|
57 |
+
|
58 |
+
# Sum up the maximum scores across features to get the overall document relevance scores
|
59 |
+
final_scores = maximum_scores.sum(dim=1)
|
60 |
+
|
61 |
+
normalized_scores = torch.softmax(final_scores, dim=0)
|
62 |
+
|
63 |
+
return normalized_scores.detach().cpu().numpy().astype(np.float32)
|
64 |
+
|
65 |
+
def predict(self, sentences):
|
66 |
+
|
67 |
+
query = sentences[0][0]
|
68 |
+
docs = [i[1] for i in sentences]
|
69 |
+
|
70 |
+
# Embedding the documents
|
71 |
+
embedded_docs = self.ckpt.docFromText(docs, bsize=32)[0]
|
72 |
+
# Embedding the queries
|
73 |
+
embedded_queries = self.ckpt.queryFromText([query], bsize=32)
|
74 |
+
embedded_query = embedded_queries[0]
|
75 |
+
|
76 |
+
# Calculate retrieval scores for the query against all documents
|
77 |
+
scores = self.calculate_similarity_scores(
|
78 |
+
embedded_query.unsqueeze(0), embedded_docs
|
79 |
+
)
|
80 |
+
|
81 |
+
return scores
|
backend/open_webui/apps/retrieval/utils.py
ADDED
@@ -0,0 +1,573 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import logging
|
2 |
+
import os
|
3 |
+
import uuid
|
4 |
+
from typing import Optional, Union
|
5 |
+
|
6 |
+
import requests
|
7 |
+
|
8 |
+
from huggingface_hub import snapshot_download
|
9 |
+
from langchain.retrievers import ContextualCompressionRetriever, EnsembleRetriever
|
10 |
+
from langchain_community.retrievers import BM25Retriever
|
11 |
+
from langchain_core.documents import Document
|
12 |
+
|
13 |
+
|
14 |
+
from open_webui.apps.ollama.main import (
|
15 |
+
GenerateEmbedForm,
|
16 |
+
generate_ollama_batch_embeddings,
|
17 |
+
)
|
18 |
+
from open_webui.apps.retrieval.vector.connector import VECTOR_DB_CLIENT
|
19 |
+
from open_webui.utils.misc import get_last_user_message
|
20 |
+
|
21 |
+
from open_webui.env import SRC_LOG_LEVELS
|
22 |
+
from open_webui.config import DEFAULT_RAG_TEMPLATE
|
23 |
+
|
24 |
+
|
25 |
+
log = logging.getLogger(__name__)
|
26 |
+
log.setLevel(SRC_LOG_LEVELS["RAG"])
|
27 |
+
|
28 |
+
|
29 |
+
from typing import Any
|
30 |
+
|
31 |
+
from langchain_core.callbacks import CallbackManagerForRetrieverRun
|
32 |
+
from langchain_core.retrievers import BaseRetriever
|
33 |
+
|
34 |
+
|
35 |
+
class VectorSearchRetriever(BaseRetriever):
|
36 |
+
collection_name: Any
|
37 |
+
embedding_function: Any
|
38 |
+
top_k: int
|
39 |
+
|
40 |
+
def _get_relevant_documents(
|
41 |
+
self,
|
42 |
+
query: str,
|
43 |
+
*,
|
44 |
+
run_manager: CallbackManagerForRetrieverRun,
|
45 |
+
) -> list[Document]:
|
46 |
+
result = VECTOR_DB_CLIENT.search(
|
47 |
+
collection_name=self.collection_name,
|
48 |
+
vectors=[self.embedding_function(query)],
|
49 |
+
limit=self.top_k,
|
50 |
+
)
|
51 |
+
|
52 |
+
ids = result.ids[0]
|
53 |
+
metadatas = result.metadatas[0]
|
54 |
+
documents = result.documents[0]
|
55 |
+
|
56 |
+
results = []
|
57 |
+
for idx in range(len(ids)):
|
58 |
+
results.append(
|
59 |
+
Document(
|
60 |
+
metadata=metadatas[idx],
|
61 |
+
page_content=documents[idx],
|
62 |
+
)
|
63 |
+
)
|
64 |
+
return results
|
65 |
+
|
66 |
+
|
67 |
+
def query_doc(
|
68 |
+
collection_name: str,
|
69 |
+
query_embedding: list[float],
|
70 |
+
k: int,
|
71 |
+
):
|
72 |
+
try:
|
73 |
+
result = VECTOR_DB_CLIENT.search(
|
74 |
+
collection_name=collection_name,
|
75 |
+
vectors=[query_embedding],
|
76 |
+
limit=k,
|
77 |
+
)
|
78 |
+
|
79 |
+
log.info(f"query_doc:result {result}")
|
80 |
+
return result
|
81 |
+
except Exception as e:
|
82 |
+
print(e)
|
83 |
+
raise e
|
84 |
+
|
85 |
+
|
86 |
+
def query_doc_with_hybrid_search(
|
87 |
+
collection_name: str,
|
88 |
+
query: str,
|
89 |
+
embedding_function,
|
90 |
+
k: int,
|
91 |
+
reranking_function,
|
92 |
+
r: float,
|
93 |
+
) -> dict:
|
94 |
+
try:
|
95 |
+
result = VECTOR_DB_CLIENT.get(collection_name=collection_name)
|
96 |
+
|
97 |
+
bm25_retriever = BM25Retriever.from_texts(
|
98 |
+
texts=result.documents[0],
|
99 |
+
metadatas=result.metadatas[0],
|
100 |
+
)
|
101 |
+
bm25_retriever.k = k
|
102 |
+
|
103 |
+
vector_search_retriever = VectorSearchRetriever(
|
104 |
+
collection_name=collection_name,
|
105 |
+
embedding_function=embedding_function,
|
106 |
+
top_k=k,
|
107 |
+
)
|
108 |
+
|
109 |
+
ensemble_retriever = EnsembleRetriever(
|
110 |
+
retrievers=[bm25_retriever, vector_search_retriever], weights=[0.5, 0.5]
|
111 |
+
)
|
112 |
+
compressor = RerankCompressor(
|
113 |
+
embedding_function=embedding_function,
|
114 |
+
top_n=k,
|
115 |
+
reranking_function=reranking_function,
|
116 |
+
r_score=r,
|
117 |
+
)
|
118 |
+
|
119 |
+
compression_retriever = ContextualCompressionRetriever(
|
120 |
+
base_compressor=compressor, base_retriever=ensemble_retriever
|
121 |
+
)
|
122 |
+
|
123 |
+
result = compression_retriever.invoke(query)
|
124 |
+
result = {
|
125 |
+
"distances": [[d.metadata.get("score") for d in result]],
|
126 |
+
"documents": [[d.page_content for d in result]],
|
127 |
+
"metadatas": [[d.metadata for d in result]],
|
128 |
+
}
|
129 |
+
|
130 |
+
log.info(f"query_doc_with_hybrid_search:result {result}")
|
131 |
+
return result
|
132 |
+
except Exception as e:
|
133 |
+
raise e
|
134 |
+
|
135 |
+
|
136 |
+
def merge_and_sort_query_results(
|
137 |
+
query_results: list[dict], k: int, reverse: bool = False
|
138 |
+
) -> list[dict]:
|
139 |
+
# Initialize lists to store combined data
|
140 |
+
combined_distances = []
|
141 |
+
combined_documents = []
|
142 |
+
combined_metadatas = []
|
143 |
+
|
144 |
+
for data in query_results:
|
145 |
+
combined_distances.extend(data["distances"][0])
|
146 |
+
combined_documents.extend(data["documents"][0])
|
147 |
+
combined_metadatas.extend(data["metadatas"][0])
|
148 |
+
|
149 |
+
# Create a list of tuples (distance, document, metadata)
|
150 |
+
combined = list(zip(combined_distances, combined_documents, combined_metadatas))
|
151 |
+
|
152 |
+
# Sort the list based on distances
|
153 |
+
combined.sort(key=lambda x: x[0], reverse=reverse)
|
154 |
+
|
155 |
+
# We don't have anything :-(
|
156 |
+
if not combined:
|
157 |
+
sorted_distances = []
|
158 |
+
sorted_documents = []
|
159 |
+
sorted_metadatas = []
|
160 |
+
else:
|
161 |
+
# Unzip the sorted list
|
162 |
+
sorted_distances, sorted_documents, sorted_metadatas = zip(*combined)
|
163 |
+
|
164 |
+
# Slicing the lists to include only k elements
|
165 |
+
sorted_distances = list(sorted_distances)[:k]
|
166 |
+
sorted_documents = list(sorted_documents)[:k]
|
167 |
+
sorted_metadatas = list(sorted_metadatas)[:k]
|
168 |
+
|
169 |
+
# Create the output dictionary
|
170 |
+
result = {
|
171 |
+
"distances": [sorted_distances],
|
172 |
+
"documents": [sorted_documents],
|
173 |
+
"metadatas": [sorted_metadatas],
|
174 |
+
}
|
175 |
+
|
176 |
+
return result
|
177 |
+
|
178 |
+
|
179 |
+
def query_collection(
|
180 |
+
collection_names: list[str],
|
181 |
+
query: str,
|
182 |
+
embedding_function,
|
183 |
+
k: int,
|
184 |
+
) -> dict:
|
185 |
+
|
186 |
+
results = []
|
187 |
+
query_embedding = embedding_function(query)
|
188 |
+
|
189 |
+
for collection_name in collection_names:
|
190 |
+
if collection_name:
|
191 |
+
try:
|
192 |
+
result = query_doc(
|
193 |
+
collection_name=collection_name,
|
194 |
+
k=k,
|
195 |
+
query_embedding=query_embedding,
|
196 |
+
)
|
197 |
+
if result is not None:
|
198 |
+
results.append(result.model_dump())
|
199 |
+
except Exception as e:
|
200 |
+
log.exception(f"Error when querying the collection: {e}")
|
201 |
+
else:
|
202 |
+
pass
|
203 |
+
|
204 |
+
return merge_and_sort_query_results(results, k=k)
|
205 |
+
|
206 |
+
|
207 |
+
def query_collection_with_hybrid_search(
|
208 |
+
collection_names: list[str],
|
209 |
+
query: str,
|
210 |
+
embedding_function,
|
211 |
+
k: int,
|
212 |
+
reranking_function,
|
213 |
+
r: float,
|
214 |
+
) -> dict:
|
215 |
+
results = []
|
216 |
+
error = False
|
217 |
+
for collection_name in collection_names:
|
218 |
+
try:
|
219 |
+
result = query_doc_with_hybrid_search(
|
220 |
+
collection_name=collection_name,
|
221 |
+
query=query,
|
222 |
+
embedding_function=embedding_function,
|
223 |
+
k=k,
|
224 |
+
reranking_function=reranking_function,
|
225 |
+
r=r,
|
226 |
+
)
|
227 |
+
results.append(result)
|
228 |
+
except Exception as e:
|
229 |
+
log.exception(
|
230 |
+
"Error when querying the collection with " f"hybrid_search: {e}"
|
231 |
+
)
|
232 |
+
error = True
|
233 |
+
|
234 |
+
if error:
|
235 |
+
raise Exception(
|
236 |
+
"Hybrid search failed for all collections. Using Non hybrid search as fallback."
|
237 |
+
)
|
238 |
+
|
239 |
+
return merge_and_sort_query_results(results, k=k, reverse=True)
|
240 |
+
|
241 |
+
|
242 |
+
def rag_template(template: str, context: str, query: str):
|
243 |
+
if template == "":
|
244 |
+
template = DEFAULT_RAG_TEMPLATE
|
245 |
+
|
246 |
+
if "[context]" not in template and "{{CONTEXT}}" not in template:
|
247 |
+
log.debug(
|
248 |
+
"WARNING: The RAG template does not contain the '[context]' or '{{CONTEXT}}' placeholder."
|
249 |
+
)
|
250 |
+
|
251 |
+
if "<context>" in context and "</context>" in context:
|
252 |
+
log.debug(
|
253 |
+
"WARNING: Potential prompt injection attack: the RAG "
|
254 |
+
"context contains '<context>' and '</context>'. This might be "
|
255 |
+
"nothing, or the user might be trying to hack something."
|
256 |
+
)
|
257 |
+
|
258 |
+
query_placeholders = []
|
259 |
+
if "[query]" in context:
|
260 |
+
query_placeholder = "{{QUERY" + str(uuid.uuid4()) + "}}"
|
261 |
+
template = template.replace("[query]", query_placeholder)
|
262 |
+
query_placeholders.append(query_placeholder)
|
263 |
+
|
264 |
+
if "{{QUERY}}" in context:
|
265 |
+
query_placeholder = "{{QUERY" + str(uuid.uuid4()) + "}}"
|
266 |
+
template = template.replace("{{QUERY}}", query_placeholder)
|
267 |
+
query_placeholders.append(query_placeholder)
|
268 |
+
|
269 |
+
template = template.replace("[context]", context)
|
270 |
+
template = template.replace("{{CONTEXT}}", context)
|
271 |
+
template = template.replace("[query]", query)
|
272 |
+
template = template.replace("{{QUERY}}", query)
|
273 |
+
|
274 |
+
for query_placeholder in query_placeholders:
|
275 |
+
template = template.replace(query_placeholder, query)
|
276 |
+
|
277 |
+
return template
|
278 |
+
|
279 |
+
|
280 |
+
def get_embedding_function(
|
281 |
+
embedding_engine,
|
282 |
+
embedding_model,
|
283 |
+
embedding_function,
|
284 |
+
openai_key,
|
285 |
+
openai_url,
|
286 |
+
embedding_batch_size,
|
287 |
+
):
|
288 |
+
if embedding_engine == "":
|
289 |
+
return lambda query: embedding_function.encode(query).tolist()
|
290 |
+
elif embedding_engine in ["ollama", "openai"]:
|
291 |
+
func = lambda query: generate_embeddings(
|
292 |
+
engine=embedding_engine,
|
293 |
+
model=embedding_model,
|
294 |
+
text=query,
|
295 |
+
key=openai_key if embedding_engine == "openai" else "",
|
296 |
+
url=openai_url if embedding_engine == "openai" else "",
|
297 |
+
)
|
298 |
+
|
299 |
+
def generate_multiple(query, func):
|
300 |
+
if isinstance(query, list):
|
301 |
+
embeddings = []
|
302 |
+
for i in range(0, len(query), embedding_batch_size):
|
303 |
+
embeddings.extend(func(query[i : i + embedding_batch_size]))
|
304 |
+
return embeddings
|
305 |
+
else:
|
306 |
+
return func(query)
|
307 |
+
|
308 |
+
return lambda query: generate_multiple(query, func)
|
309 |
+
|
310 |
+
|
311 |
+
def get_rag_context(
|
312 |
+
files,
|
313 |
+
messages,
|
314 |
+
embedding_function,
|
315 |
+
k,
|
316 |
+
reranking_function,
|
317 |
+
r,
|
318 |
+
hybrid_search,
|
319 |
+
):
|
320 |
+
log.debug(f"files: {files} {messages} {embedding_function} {reranking_function}")
|
321 |
+
query = get_last_user_message(messages)
|
322 |
+
|
323 |
+
extracted_collections = []
|
324 |
+
relevant_contexts = []
|
325 |
+
|
326 |
+
for file in files:
|
327 |
+
if file.get("context") == "full":
|
328 |
+
context = {
|
329 |
+
"documents": [[file.get("file").get("data", {}).get("content")]],
|
330 |
+
"metadatas": [[{"file_id": file.get("id"), "name": file.get("name")}]],
|
331 |
+
}
|
332 |
+
else:
|
333 |
+
context = None
|
334 |
+
|
335 |
+
collection_names = []
|
336 |
+
if file.get("type") == "collection":
|
337 |
+
if file.get("legacy"):
|
338 |
+
collection_names = file.get("collection_names", [])
|
339 |
+
else:
|
340 |
+
collection_names.append(file["id"])
|
341 |
+
elif file.get("collection_name"):
|
342 |
+
collection_names.append(file["collection_name"])
|
343 |
+
elif file.get("id"):
|
344 |
+
if file.get("legacy"):
|
345 |
+
collection_names.append(f"{file['id']}")
|
346 |
+
else:
|
347 |
+
collection_names.append(f"file-{file['id']}")
|
348 |
+
|
349 |
+
collection_names = set(collection_names).difference(extracted_collections)
|
350 |
+
if not collection_names:
|
351 |
+
log.debug(f"skipping {file} as it has already been extracted")
|
352 |
+
continue
|
353 |
+
|
354 |
+
try:
|
355 |
+
context = None
|
356 |
+
if file.get("type") == "text":
|
357 |
+
context = file["content"]
|
358 |
+
else:
|
359 |
+
if hybrid_search:
|
360 |
+
try:
|
361 |
+
context = query_collection_with_hybrid_search(
|
362 |
+
collection_names=collection_names,
|
363 |
+
query=query,
|
364 |
+
embedding_function=embedding_function,
|
365 |
+
k=k,
|
366 |
+
reranking_function=reranking_function,
|
367 |
+
r=r,
|
368 |
+
)
|
369 |
+
except Exception as e:
|
370 |
+
log.debug(
|
371 |
+
"Error when using hybrid search, using"
|
372 |
+
" non hybrid search as fallback."
|
373 |
+
)
|
374 |
+
|
375 |
+
if (not hybrid_search) or (context is None):
|
376 |
+
context = query_collection(
|
377 |
+
collection_names=collection_names,
|
378 |
+
query=query,
|
379 |
+
embedding_function=embedding_function,
|
380 |
+
k=k,
|
381 |
+
)
|
382 |
+
except Exception as e:
|
383 |
+
log.exception(e)
|
384 |
+
|
385 |
+
extracted_collections.extend(collection_names)
|
386 |
+
|
387 |
+
if context:
|
388 |
+
if "data" in file:
|
389 |
+
del file["data"]
|
390 |
+
relevant_contexts.append({**context, "file": file})
|
391 |
+
|
392 |
+
contexts = []
|
393 |
+
citations = []
|
394 |
+
for context in relevant_contexts:
|
395 |
+
try:
|
396 |
+
if "documents" in context:
|
397 |
+
file_names = list(
|
398 |
+
set(
|
399 |
+
[
|
400 |
+
metadata["name"]
|
401 |
+
for metadata in context["metadatas"][0]
|
402 |
+
if metadata is not None and "name" in metadata
|
403 |
+
]
|
404 |
+
)
|
405 |
+
)
|
406 |
+
contexts.append(
|
407 |
+
((", ".join(file_names) + ":\n\n") if file_names else "")
|
408 |
+
+ "\n\n".join(
|
409 |
+
[text for text in context["documents"][0] if text is not None]
|
410 |
+
)
|
411 |
+
)
|
412 |
+
|
413 |
+
if "metadatas" in context:
|
414 |
+
citation = {
|
415 |
+
"source": context["file"],
|
416 |
+
"document": context["documents"][0],
|
417 |
+
"metadata": context["metadatas"][0],
|
418 |
+
}
|
419 |
+
if "distances" in context and context["distances"]:
|
420 |
+
citation["distances"] = context["distances"][0]
|
421 |
+
citations.append(citation)
|
422 |
+
except Exception as e:
|
423 |
+
log.exception(e)
|
424 |
+
|
425 |
+
print("contexts", contexts)
|
426 |
+
print("citations", citations)
|
427 |
+
|
428 |
+
return contexts, citations
|
429 |
+
|
430 |
+
|
431 |
+
def get_model_path(model: str, update_model: bool = False):
|
432 |
+
# Construct huggingface_hub kwargs with local_files_only to return the snapshot path
|
433 |
+
cache_dir = os.getenv("SENTENCE_TRANSFORMERS_HOME")
|
434 |
+
|
435 |
+
local_files_only = not update_model
|
436 |
+
|
437 |
+
snapshot_kwargs = {
|
438 |
+
"cache_dir": cache_dir,
|
439 |
+
"local_files_only": local_files_only,
|
440 |
+
}
|
441 |
+
|
442 |
+
log.debug(f"model: {model}")
|
443 |
+
log.debug(f"snapshot_kwargs: {snapshot_kwargs}")
|
444 |
+
|
445 |
+
# Inspiration from upstream sentence_transformers
|
446 |
+
if (
|
447 |
+
os.path.exists(model)
|
448 |
+
or ("\\" in model or model.count("/") > 1)
|
449 |
+
and local_files_only
|
450 |
+
):
|
451 |
+
# If fully qualified path exists, return input, else set repo_id
|
452 |
+
return model
|
453 |
+
elif "/" not in model:
|
454 |
+
# Set valid repo_id for model short-name
|
455 |
+
model = "sentence-transformers" + "/" + model
|
456 |
+
|
457 |
+
snapshot_kwargs["repo_id"] = model
|
458 |
+
|
459 |
+
# Attempt to query the huggingface_hub library to determine the local path and/or to update
|
460 |
+
try:
|
461 |
+
model_repo_path = snapshot_download(**snapshot_kwargs)
|
462 |
+
log.debug(f"model_repo_path: {model_repo_path}")
|
463 |
+
return model_repo_path
|
464 |
+
except Exception as e:
|
465 |
+
log.exception(f"Cannot determine model snapshot path: {e}")
|
466 |
+
return model
|
467 |
+
|
468 |
+
|
469 |
+
def generate_openai_batch_embeddings(
|
470 |
+
model: str, texts: list[str], key: str, url: str = "https://api.openai.com/v1"
|
471 |
+
) -> Optional[list[list[float]]]:
|
472 |
+
try:
|
473 |
+
r = requests.post(
|
474 |
+
f"{url}/embeddings",
|
475 |
+
headers={
|
476 |
+
"Content-Type": "application/json",
|
477 |
+
"Authorization": f"Bearer {key}",
|
478 |
+
},
|
479 |
+
json={"input": texts, "model": model},
|
480 |
+
)
|
481 |
+
r.raise_for_status()
|
482 |
+
data = r.json()
|
483 |
+
if "data" in data:
|
484 |
+
return [elem["embedding"] for elem in data["data"]]
|
485 |
+
else:
|
486 |
+
raise "Something went wrong :/"
|
487 |
+
except Exception as e:
|
488 |
+
print(e)
|
489 |
+
return None
|
490 |
+
|
491 |
+
|
492 |
+
def generate_embeddings(engine: str, model: str, text: Union[str, list[str]], **kwargs):
|
493 |
+
if engine == "ollama":
|
494 |
+
if isinstance(text, list):
|
495 |
+
embeddings = generate_ollama_batch_embeddings(
|
496 |
+
GenerateEmbedForm(**{"model": model, "input": text})
|
497 |
+
)
|
498 |
+
else:
|
499 |
+
embeddings = generate_ollama_batch_embeddings(
|
500 |
+
GenerateEmbedForm(**{"model": model, "input": [text]})
|
501 |
+
)
|
502 |
+
return (
|
503 |
+
embeddings["embeddings"][0]
|
504 |
+
if isinstance(text, str)
|
505 |
+
else embeddings["embeddings"]
|
506 |
+
)
|
507 |
+
elif engine == "openai":
|
508 |
+
key = kwargs.get("key", "")
|
509 |
+
url = kwargs.get("url", "https://api.openai.com/v1")
|
510 |
+
|
511 |
+
if isinstance(text, list):
|
512 |
+
embeddings = generate_openai_batch_embeddings(model, text, key, url)
|
513 |
+
else:
|
514 |
+
embeddings = generate_openai_batch_embeddings(model, [text], key, url)
|
515 |
+
|
516 |
+
return embeddings[0] if isinstance(text, str) else embeddings
|
517 |
+
|
518 |
+
|
519 |
+
import operator
|
520 |
+
from typing import Optional, Sequence
|
521 |
+
|
522 |
+
from langchain_core.callbacks import Callbacks
|
523 |
+
from langchain_core.documents import BaseDocumentCompressor, Document
|
524 |
+
|
525 |
+
|
526 |
+
class RerankCompressor(BaseDocumentCompressor):
|
527 |
+
embedding_function: Any
|
528 |
+
top_n: int
|
529 |
+
reranking_function: Any
|
530 |
+
r_score: float
|
531 |
+
|
532 |
+
class Config:
|
533 |
+
extra = "forbid"
|
534 |
+
arbitrary_types_allowed = True
|
535 |
+
|
536 |
+
def compress_documents(
|
537 |
+
self,
|
538 |
+
documents: Sequence[Document],
|
539 |
+
query: str,
|
540 |
+
callbacks: Optional[Callbacks] = None,
|
541 |
+
) -> Sequence[Document]:
|
542 |
+
reranking = self.reranking_function is not None
|
543 |
+
|
544 |
+
if reranking:
|
545 |
+
scores = self.reranking_function.predict(
|
546 |
+
[(query, doc.page_content) for doc in documents]
|
547 |
+
)
|
548 |
+
else:
|
549 |
+
from sentence_transformers import util
|
550 |
+
|
551 |
+
query_embedding = self.embedding_function(query)
|
552 |
+
document_embedding = self.embedding_function(
|
553 |
+
[doc.page_content for doc in documents]
|
554 |
+
)
|
555 |
+
scores = util.cos_sim(query_embedding, document_embedding)[0]
|
556 |
+
|
557 |
+
docs_with_scores = list(zip(documents, scores.tolist()))
|
558 |
+
if self.r_score:
|
559 |
+
docs_with_scores = [
|
560 |
+
(d, s) for d, s in docs_with_scores if s >= self.r_score
|
561 |
+
]
|
562 |
+
|
563 |
+
result = sorted(docs_with_scores, key=operator.itemgetter(1), reverse=True)
|
564 |
+
final_results = []
|
565 |
+
for doc, doc_score in result[: self.top_n]:
|
566 |
+
metadata = doc.metadata
|
567 |
+
metadata["score"] = doc_score
|
568 |
+
doc = Document(
|
569 |
+
page_content=doc.page_content,
|
570 |
+
metadata=metadata,
|
571 |
+
)
|
572 |
+
final_results.append(doc)
|
573 |
+
return final_results
|
backend/open_webui/apps/retrieval/vector/connector.py
ADDED
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from open_webui.config import VECTOR_DB
|
2 |
+
|
3 |
+
if VECTOR_DB == "milvus":
|
4 |
+
from open_webui.apps.retrieval.vector.dbs.milvus import MilvusClient
|
5 |
+
|
6 |
+
VECTOR_DB_CLIENT = MilvusClient()
|
7 |
+
elif VECTOR_DB == "qdrant":
|
8 |
+
from open_webui.apps.retrieval.vector.dbs.qdrant import QdrantClient
|
9 |
+
|
10 |
+
VECTOR_DB_CLIENT = QdrantClient()
|
11 |
+
else:
|
12 |
+
from open_webui.apps.retrieval.vector.dbs.chroma import ChromaClient
|
13 |
+
|
14 |
+
VECTOR_DB_CLIENT = ChromaClient()
|
backend/open_webui/apps/retrieval/vector/dbs/chroma.py
ADDED
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import chromadb
|
2 |
+
from chromadb import Settings
|
3 |
+
from chromadb.utils.batch_utils import create_batches
|
4 |
+
|
5 |
+
from typing import Optional
|
6 |
+
|
7 |
+
from open_webui.apps.retrieval.vector.main import VectorItem, SearchResult, GetResult
|
8 |
+
from open_webui.config import (
|
9 |
+
CHROMA_DATA_PATH,
|
10 |
+
CHROMA_HTTP_HOST,
|
11 |
+
CHROMA_HTTP_PORT,
|
12 |
+
CHROMA_HTTP_HEADERS,
|
13 |
+
CHROMA_HTTP_SSL,
|
14 |
+
CHROMA_TENANT,
|
15 |
+
CHROMA_DATABASE,
|
16 |
+
)
|
17 |
+
|
18 |
+
|
19 |
+
class ChromaClient:
|
20 |
+
def __init__(self):
|
21 |
+
if CHROMA_HTTP_HOST != "":
|
22 |
+
self.client = chromadb.HttpClient(
|
23 |
+
host=CHROMA_HTTP_HOST,
|
24 |
+
port=CHROMA_HTTP_PORT,
|
25 |
+
headers=CHROMA_HTTP_HEADERS,
|
26 |
+
ssl=CHROMA_HTTP_SSL,
|
27 |
+
tenant=CHROMA_TENANT,
|
28 |
+
database=CHROMA_DATABASE,
|
29 |
+
settings=Settings(allow_reset=True, anonymized_telemetry=False),
|
30 |
+
)
|
31 |
+
else:
|
32 |
+
self.client = chromadb.PersistentClient(
|
33 |
+
path=CHROMA_DATA_PATH,
|
34 |
+
settings=Settings(allow_reset=True, anonymized_telemetry=False),
|
35 |
+
tenant=CHROMA_TENANT,
|
36 |
+
database=CHROMA_DATABASE,
|
37 |
+
)
|
38 |
+
|
39 |
+
def has_collection(self, collection_name: str) -> bool:
|
40 |
+
# Check if the collection exists based on the collection name.
|
41 |
+
collections = self.client.list_collections()
|
42 |
+
return collection_name in [collection.name for collection in collections]
|
43 |
+
|
44 |
+
def delete_collection(self, collection_name: str):
|
45 |
+
# Delete the collection based on the collection name.
|
46 |
+
return self.client.delete_collection(name=collection_name)
|
47 |
+
|
48 |
+
def search(
|
49 |
+
self, collection_name: str, vectors: list[list[float | int]], limit: int
|
50 |
+
) -> Optional[SearchResult]:
|
51 |
+
# Search for the nearest neighbor items based on the vectors and return 'limit' number of results.
|
52 |
+
try:
|
53 |
+
collection = self.client.get_collection(name=collection_name)
|
54 |
+
if collection:
|
55 |
+
result = collection.query(
|
56 |
+
query_embeddings=vectors,
|
57 |
+
n_results=limit,
|
58 |
+
)
|
59 |
+
|
60 |
+
return SearchResult(
|
61 |
+
**{
|
62 |
+
"ids": result["ids"],
|
63 |
+
"distances": result["distances"],
|
64 |
+
"documents": result["documents"],
|
65 |
+
"metadatas": result["metadatas"],
|
66 |
+
}
|
67 |
+
)
|
68 |
+
return None
|
69 |
+
except Exception as e:
|
70 |
+
return None
|
71 |
+
|
72 |
+
def query(
|
73 |
+
self, collection_name: str, filter: dict, limit: Optional[int] = None
|
74 |
+
) -> Optional[GetResult]:
|
75 |
+
# Query the items from the collection based on the filter.
|
76 |
+
try:
|
77 |
+
collection = self.client.get_collection(name=collection_name)
|
78 |
+
if collection:
|
79 |
+
result = collection.get(
|
80 |
+
where=filter,
|
81 |
+
limit=limit,
|
82 |
+
)
|
83 |
+
|
84 |
+
return GetResult(
|
85 |
+
**{
|
86 |
+
"ids": [result["ids"]],
|
87 |
+
"documents": [result["documents"]],
|
88 |
+
"metadatas": [result["metadatas"]],
|
89 |
+
}
|
90 |
+
)
|
91 |
+
return None
|
92 |
+
except Exception as e:
|
93 |
+
print(e)
|
94 |
+
return None
|
95 |
+
|
96 |
+
def get(self, collection_name: str) -> Optional[GetResult]:
|
97 |
+
# Get all the items in the collection.
|
98 |
+
collection = self.client.get_collection(name=collection_name)
|
99 |
+
if collection:
|
100 |
+
result = collection.get()
|
101 |
+
return GetResult(
|
102 |
+
**{
|
103 |
+
"ids": [result["ids"]],
|
104 |
+
"documents": [result["documents"]],
|
105 |
+
"metadatas": [result["metadatas"]],
|
106 |
+
}
|
107 |
+
)
|
108 |
+
return None
|
109 |
+
|
110 |
+
def insert(self, collection_name: str, items: list[VectorItem]):
|
111 |
+
# Insert the items into the collection, if the collection does not exist, it will be created.
|
112 |
+
collection = self.client.get_or_create_collection(
|
113 |
+
name=collection_name, metadata={"hnsw:space": "cosine"}
|
114 |
+
)
|
115 |
+
|
116 |
+
ids = [item["id"] for item in items]
|
117 |
+
documents = [item["text"] for item in items]
|
118 |
+
embeddings = [item["vector"] for item in items]
|
119 |
+
metadatas = [item["metadata"] for item in items]
|
120 |
+
|
121 |
+
for batch in create_batches(
|
122 |
+
api=self.client,
|
123 |
+
documents=documents,
|
124 |
+
embeddings=embeddings,
|
125 |
+
ids=ids,
|
126 |
+
metadatas=metadatas,
|
127 |
+
):
|
128 |
+
collection.add(*batch)
|
129 |
+
|
130 |
+
def upsert(self, collection_name: str, items: list[VectorItem]):
|
131 |
+
# Update the items in the collection, if the items are not present, insert them. If the collection does not exist, it will be created.
|
132 |
+
collection = self.client.get_or_create_collection(
|
133 |
+
name=collection_name, metadata={"hnsw:space": "cosine"}
|
134 |
+
)
|
135 |
+
|
136 |
+
ids = [item["id"] for item in items]
|
137 |
+
documents = [item["text"] for item in items]
|
138 |
+
embeddings = [item["vector"] for item in items]
|
139 |
+
metadatas = [item["metadata"] for item in items]
|
140 |
+
|
141 |
+
collection.upsert(
|
142 |
+
ids=ids, documents=documents, embeddings=embeddings, metadatas=metadatas
|
143 |
+
)
|
144 |
+
|
145 |
+
def delete(
|
146 |
+
self,
|
147 |
+
collection_name: str,
|
148 |
+
ids: Optional[list[str]] = None,
|
149 |
+
filter: Optional[dict] = None,
|
150 |
+
):
|
151 |
+
# Delete the items from the collection based on the ids.
|
152 |
+
collection = self.client.get_collection(name=collection_name)
|
153 |
+
if collection:
|
154 |
+
if ids:
|
155 |
+
collection.delete(ids=ids)
|
156 |
+
elif filter:
|
157 |
+
collection.delete(where=filter)
|
158 |
+
|
159 |
+
def reset(self):
|
160 |
+
# Resets the database. This will delete all collections and item entries.
|
161 |
+
return self.client.reset()
|
backend/open_webui/apps/retrieval/vector/dbs/milvus.py
ADDED
@@ -0,0 +1,286 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from pymilvus import MilvusClient as Client
|
2 |
+
from pymilvus import FieldSchema, DataType
|
3 |
+
import json
|
4 |
+
|
5 |
+
from typing import Optional
|
6 |
+
|
7 |
+
from open_webui.apps.retrieval.vector.main import VectorItem, SearchResult, GetResult
|
8 |
+
from open_webui.config import (
|
9 |
+
MILVUS_URI,
|
10 |
+
)
|
11 |
+
|
12 |
+
|
13 |
+
class MilvusClient:
|
14 |
+
def __init__(self):
|
15 |
+
self.collection_prefix = "open_webui"
|
16 |
+
self.client = Client(uri=MILVUS_URI)
|
17 |
+
|
18 |
+
def _result_to_get_result(self, result) -> GetResult:
|
19 |
+
ids = []
|
20 |
+
documents = []
|
21 |
+
metadatas = []
|
22 |
+
|
23 |
+
for match in result:
|
24 |
+
_ids = []
|
25 |
+
_documents = []
|
26 |
+
_metadatas = []
|
27 |
+
for item in match:
|
28 |
+
_ids.append(item.get("id"))
|
29 |
+
_documents.append(item.get("data", {}).get("text"))
|
30 |
+
_metadatas.append(item.get("metadata"))
|
31 |
+
|
32 |
+
ids.append(_ids)
|
33 |
+
documents.append(_documents)
|
34 |
+
metadatas.append(_metadatas)
|
35 |
+
|
36 |
+
return GetResult(
|
37 |
+
**{
|
38 |
+
"ids": ids,
|
39 |
+
"documents": documents,
|
40 |
+
"metadatas": metadatas,
|
41 |
+
}
|
42 |
+
)
|
43 |
+
|
44 |
+
def _result_to_search_result(self, result) -> SearchResult:
|
45 |
+
ids = []
|
46 |
+
distances = []
|
47 |
+
documents = []
|
48 |
+
metadatas = []
|
49 |
+
|
50 |
+
for match in result:
|
51 |
+
_ids = []
|
52 |
+
_distances = []
|
53 |
+
_documents = []
|
54 |
+
_metadatas = []
|
55 |
+
|
56 |
+
for item in match:
|
57 |
+
_ids.append(item.get("id"))
|
58 |
+
_distances.append(item.get("distance"))
|
59 |
+
_documents.append(item.get("entity", {}).get("data", {}).get("text"))
|
60 |
+
_metadatas.append(item.get("entity", {}).get("metadata"))
|
61 |
+
|
62 |
+
ids.append(_ids)
|
63 |
+
distances.append(_distances)
|
64 |
+
documents.append(_documents)
|
65 |
+
metadatas.append(_metadatas)
|
66 |
+
|
67 |
+
return SearchResult(
|
68 |
+
**{
|
69 |
+
"ids": ids,
|
70 |
+
"distances": distances,
|
71 |
+
"documents": documents,
|
72 |
+
"metadatas": metadatas,
|
73 |
+
}
|
74 |
+
)
|
75 |
+
|
76 |
+
def _create_collection(self, collection_name: str, dimension: int):
|
77 |
+
schema = self.client.create_schema(
|
78 |
+
auto_id=False,
|
79 |
+
enable_dynamic_field=True,
|
80 |
+
)
|
81 |
+
schema.add_field(
|
82 |
+
field_name="id",
|
83 |
+
datatype=DataType.VARCHAR,
|
84 |
+
is_primary=True,
|
85 |
+
max_length=65535,
|
86 |
+
)
|
87 |
+
schema.add_field(
|
88 |
+
field_name="vector",
|
89 |
+
datatype=DataType.FLOAT_VECTOR,
|
90 |
+
dim=dimension,
|
91 |
+
description="vector",
|
92 |
+
)
|
93 |
+
schema.add_field(field_name="data", datatype=DataType.JSON, description="data")
|
94 |
+
schema.add_field(
|
95 |
+
field_name="metadata", datatype=DataType.JSON, description="metadata"
|
96 |
+
)
|
97 |
+
|
98 |
+
index_params = self.client.prepare_index_params()
|
99 |
+
index_params.add_index(
|
100 |
+
field_name="vector",
|
101 |
+
index_type="HNSW",
|
102 |
+
metric_type="COSINE",
|
103 |
+
params={"M": 16, "efConstruction": 100},
|
104 |
+
)
|
105 |
+
|
106 |
+
self.client.create_collection(
|
107 |
+
collection_name=f"{self.collection_prefix}_{collection_name}",
|
108 |
+
schema=schema,
|
109 |
+
index_params=index_params,
|
110 |
+
)
|
111 |
+
|
112 |
+
def has_collection(self, collection_name: str) -> bool:
|
113 |
+
# Check if the collection exists based on the collection name.
|
114 |
+
collection_name = collection_name.replace("-", "_")
|
115 |
+
return self.client.has_collection(
|
116 |
+
collection_name=f"{self.collection_prefix}_{collection_name}"
|
117 |
+
)
|
118 |
+
|
119 |
+
def delete_collection(self, collection_name: str):
|
120 |
+
# Delete the collection based on the collection name.
|
121 |
+
collection_name = collection_name.replace("-", "_")
|
122 |
+
return self.client.drop_collection(
|
123 |
+
collection_name=f"{self.collection_prefix}_{collection_name}"
|
124 |
+
)
|
125 |
+
|
126 |
+
def search(
|
127 |
+
self, collection_name: str, vectors: list[list[float | int]], limit: int
|
128 |
+
) -> Optional[SearchResult]:
|
129 |
+
# Search for the nearest neighbor items based on the vectors and return 'limit' number of results.
|
130 |
+
collection_name = collection_name.replace("-", "_")
|
131 |
+
result = self.client.search(
|
132 |
+
collection_name=f"{self.collection_prefix}_{collection_name}",
|
133 |
+
data=vectors,
|
134 |
+
limit=limit,
|
135 |
+
output_fields=["data", "metadata"],
|
136 |
+
)
|
137 |
+
|
138 |
+
return self._result_to_search_result(result)
|
139 |
+
|
140 |
+
def query(self, collection_name: str, filter: dict, limit: Optional[int] = None):
|
141 |
+
# Construct the filter string for querying
|
142 |
+
collection_name = collection_name.replace("-", "_")
|
143 |
+
if not self.has_collection(collection_name):
|
144 |
+
return None
|
145 |
+
|
146 |
+
filter_string = " && ".join(
|
147 |
+
[
|
148 |
+
f'metadata["{key}"] == {json.dumps(value)}'
|
149 |
+
for key, value in filter.items()
|
150 |
+
]
|
151 |
+
)
|
152 |
+
|
153 |
+
max_limit = 16383 # The maximum number of records per request
|
154 |
+
all_results = []
|
155 |
+
|
156 |
+
if limit is None:
|
157 |
+
limit = float("inf") # Use infinity as a placeholder for no limit
|
158 |
+
|
159 |
+
# Initialize offset and remaining to handle pagination
|
160 |
+
offset = 0
|
161 |
+
remaining = limit
|
162 |
+
|
163 |
+
try:
|
164 |
+
# Loop until there are no more items to fetch or the desired limit is reached
|
165 |
+
while remaining > 0:
|
166 |
+
print("remaining", remaining)
|
167 |
+
current_fetch = min(
|
168 |
+
max_limit, remaining
|
169 |
+
) # Determine how many items to fetch in this iteration
|
170 |
+
|
171 |
+
results = self.client.query(
|
172 |
+
collection_name=f"{self.collection_prefix}_{collection_name}",
|
173 |
+
filter=filter_string,
|
174 |
+
output_fields=["*"],
|
175 |
+
limit=current_fetch,
|
176 |
+
offset=offset,
|
177 |
+
)
|
178 |
+
|
179 |
+
if not results:
|
180 |
+
break
|
181 |
+
|
182 |
+
all_results.extend(results)
|
183 |
+
results_count = len(results)
|
184 |
+
remaining -= (
|
185 |
+
results_count # Decrease remaining by the number of items fetched
|
186 |
+
)
|
187 |
+
offset += results_count
|
188 |
+
|
189 |
+
# Break the loop if the results returned are less than the requested fetch count
|
190 |
+
if results_count < current_fetch:
|
191 |
+
break
|
192 |
+
|
193 |
+
print(all_results)
|
194 |
+
return self._result_to_get_result([all_results])
|
195 |
+
except Exception as e:
|
196 |
+
print(e)
|
197 |
+
return None
|
198 |
+
|
199 |
+
def get(self, collection_name: str) -> Optional[GetResult]:
|
200 |
+
# Get all the items in the collection.
|
201 |
+
collection_name = collection_name.replace("-", "_")
|
202 |
+
result = self.client.query(
|
203 |
+
collection_name=f"{self.collection_prefix}_{collection_name}",
|
204 |
+
filter='id != ""',
|
205 |
+
)
|
206 |
+
return self._result_to_get_result([result])
|
207 |
+
|
208 |
+
def insert(self, collection_name: str, items: list[VectorItem]):
|
209 |
+
# Insert the items into the collection, if the collection does not exist, it will be created.
|
210 |
+
collection_name = collection_name.replace("-", "_")
|
211 |
+
if not self.client.has_collection(
|
212 |
+
collection_name=f"{self.collection_prefix}_{collection_name}"
|
213 |
+
):
|
214 |
+
self._create_collection(
|
215 |
+
collection_name=collection_name, dimension=len(items[0]["vector"])
|
216 |
+
)
|
217 |
+
|
218 |
+
return self.client.insert(
|
219 |
+
collection_name=f"{self.collection_prefix}_{collection_name}",
|
220 |
+
data=[
|
221 |
+
{
|
222 |
+
"id": item["id"],
|
223 |
+
"vector": item["vector"],
|
224 |
+
"data": {"text": item["text"]},
|
225 |
+
"metadata": item["metadata"],
|
226 |
+
}
|
227 |
+
for item in items
|
228 |
+
],
|
229 |
+
)
|
230 |
+
|
231 |
+
def upsert(self, collection_name: str, items: list[VectorItem]):
|
232 |
+
# Update the items in the collection, if the items are not present, insert them. If the collection does not exist, it will be created.
|
233 |
+
collection_name = collection_name.replace("-", "_")
|
234 |
+
if not self.client.has_collection(
|
235 |
+
collection_name=f"{self.collection_prefix}_{collection_name}"
|
236 |
+
):
|
237 |
+
self._create_collection(
|
238 |
+
collection_name=collection_name, dimension=len(items[0]["vector"])
|
239 |
+
)
|
240 |
+
|
241 |
+
return self.client.upsert(
|
242 |
+
collection_name=f"{self.collection_prefix}_{collection_name}",
|
243 |
+
data=[
|
244 |
+
{
|
245 |
+
"id": item["id"],
|
246 |
+
"vector": item["vector"],
|
247 |
+
"data": {"text": item["text"]},
|
248 |
+
"metadata": item["metadata"],
|
249 |
+
}
|
250 |
+
for item in items
|
251 |
+
],
|
252 |
+
)
|
253 |
+
|
254 |
+
def delete(
|
255 |
+
self,
|
256 |
+
collection_name: str,
|
257 |
+
ids: Optional[list[str]] = None,
|
258 |
+
filter: Optional[dict] = None,
|
259 |
+
):
|
260 |
+
# Delete the items from the collection based on the ids.
|
261 |
+
collection_name = collection_name.replace("-", "_")
|
262 |
+
if ids:
|
263 |
+
return self.client.delete(
|
264 |
+
collection_name=f"{self.collection_prefix}_{collection_name}",
|
265 |
+
ids=ids,
|
266 |
+
)
|
267 |
+
elif filter:
|
268 |
+
# Convert the filter dictionary to a string using JSON_CONTAINS.
|
269 |
+
filter_string = " && ".join(
|
270 |
+
[
|
271 |
+
f'metadata["{key}"] == {json.dumps(value)}'
|
272 |
+
for key, value in filter.items()
|
273 |
+
]
|
274 |
+
)
|
275 |
+
|
276 |
+
return self.client.delete(
|
277 |
+
collection_name=f"{self.collection_prefix}_{collection_name}",
|
278 |
+
filter=filter_string,
|
279 |
+
)
|
280 |
+
|
281 |
+
def reset(self):
|
282 |
+
# Resets the database. This will delete all collections and item entries.
|
283 |
+
collection_names = self.client.list_collections()
|
284 |
+
for collection_name in collection_names:
|
285 |
+
if collection_name.startswith(self.collection_prefix):
|
286 |
+
self.client.drop_collection(collection_name=collection_name)
|
backend/open_webui/apps/retrieval/vector/dbs/qdrant.py
ADDED
@@ -0,0 +1,179 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Optional
|
2 |
+
|
3 |
+
from qdrant_client import QdrantClient as Qclient
|
4 |
+
from qdrant_client.http.models import PointStruct
|
5 |
+
from qdrant_client.models import models
|
6 |
+
|
7 |
+
from open_webui.apps.retrieval.vector.main import VectorItem, SearchResult, GetResult
|
8 |
+
from open_webui.config import QDRANT_URI
|
9 |
+
|
10 |
+
NO_LIMIT = 999999999
|
11 |
+
|
12 |
+
|
13 |
+
class QdrantClient:
|
14 |
+
def __init__(self):
|
15 |
+
self.collection_prefix = "open-webui"
|
16 |
+
self.QDRANT_URI = QDRANT_URI
|
17 |
+
self.client = Qclient(url=self.QDRANT_URI) if self.QDRANT_URI else None
|
18 |
+
|
19 |
+
def _result_to_get_result(self, points) -> GetResult:
|
20 |
+
ids = []
|
21 |
+
documents = []
|
22 |
+
metadatas = []
|
23 |
+
|
24 |
+
for point in points:
|
25 |
+
payload = point.payload
|
26 |
+
ids.append(point.id)
|
27 |
+
documents.append(payload["text"])
|
28 |
+
metadatas.append(payload["metadata"])
|
29 |
+
|
30 |
+
return GetResult(
|
31 |
+
**{
|
32 |
+
"ids": [ids],
|
33 |
+
"documents": [documents],
|
34 |
+
"metadatas": [metadatas],
|
35 |
+
}
|
36 |
+
)
|
37 |
+
|
38 |
+
def _create_collection(self, collection_name: str, dimension: int):
|
39 |
+
collection_name_with_prefix = f"{self.collection_prefix}_{collection_name}"
|
40 |
+
self.client.create_collection(
|
41 |
+
collection_name=collection_name_with_prefix,
|
42 |
+
vectors_config=models.VectorParams(
|
43 |
+
size=dimension, distance=models.Distance.COSINE
|
44 |
+
),
|
45 |
+
)
|
46 |
+
|
47 |
+
print(f"collection {collection_name_with_prefix} successfully created!")
|
48 |
+
|
49 |
+
def _create_collection_if_not_exists(self, collection_name, dimension):
|
50 |
+
if not self.has_collection(collection_name=collection_name):
|
51 |
+
self._create_collection(
|
52 |
+
collection_name=collection_name, dimension=dimension
|
53 |
+
)
|
54 |
+
|
55 |
+
def _create_points(self, items: list[VectorItem]):
|
56 |
+
return [
|
57 |
+
PointStruct(
|
58 |
+
id=item["id"],
|
59 |
+
vector=item["vector"],
|
60 |
+
payload={"text": item["text"], "metadata": item["metadata"]},
|
61 |
+
)
|
62 |
+
for item in items
|
63 |
+
]
|
64 |
+
|
65 |
+
def has_collection(self, collection_name: str) -> bool:
|
66 |
+
return self.client.collection_exists(
|
67 |
+
f"{self.collection_prefix}_{collection_name}"
|
68 |
+
)
|
69 |
+
|
70 |
+
def delete_collection(self, collection_name: str):
|
71 |
+
return self.client.delete_collection(
|
72 |
+
collection_name=f"{self.collection_prefix}_{collection_name}"
|
73 |
+
)
|
74 |
+
|
75 |
+
def search(
|
76 |
+
self, collection_name: str, vectors: list[list[float | int]], limit: int
|
77 |
+
) -> Optional[SearchResult]:
|
78 |
+
# Search for the nearest neighbor items based on the vectors and return 'limit' number of results.
|
79 |
+
if limit is None:
|
80 |
+
limit = NO_LIMIT # otherwise qdrant would set limit to 10!
|
81 |
+
|
82 |
+
query_response = self.client.query_points(
|
83 |
+
collection_name=f"{self.collection_prefix}_{collection_name}",
|
84 |
+
query=vectors[0],
|
85 |
+
limit=limit,
|
86 |
+
)
|
87 |
+
get_result = self._result_to_get_result(query_response.points)
|
88 |
+
return SearchResult(
|
89 |
+
ids=get_result.ids,
|
90 |
+
documents=get_result.documents,
|
91 |
+
metadatas=get_result.metadatas,
|
92 |
+
distances=[[point.score for point in query_response.points]],
|
93 |
+
)
|
94 |
+
|
95 |
+
def query(self, collection_name: str, filter: dict, limit: Optional[int] = None):
|
96 |
+
# Construct the filter string for querying
|
97 |
+
if not self.has_collection(collection_name):
|
98 |
+
return None
|
99 |
+
try:
|
100 |
+
if limit is None:
|
101 |
+
limit = NO_LIMIT # otherwise qdrant would set limit to 10!
|
102 |
+
|
103 |
+
field_conditions = []
|
104 |
+
for key, value in filter.items():
|
105 |
+
field_conditions.append(
|
106 |
+
models.FieldCondition(
|
107 |
+
key=f"metadata.{key}", match=models.MatchValue(value=value)
|
108 |
+
)
|
109 |
+
)
|
110 |
+
|
111 |
+
points = self.client.query_points(
|
112 |
+
collection_name=f"{self.collection_prefix}_{collection_name}",
|
113 |
+
query_filter=models.Filter(should=field_conditions),
|
114 |
+
limit=limit,
|
115 |
+
)
|
116 |
+
return self._result_to_get_result(points.points)
|
117 |
+
except Exception as e:
|
118 |
+
print(e)
|
119 |
+
return None
|
120 |
+
|
121 |
+
def get(self, collection_name: str) -> Optional[GetResult]:
|
122 |
+
# Get all the items in the collection.
|
123 |
+
points = self.client.query_points(
|
124 |
+
collection_name=f"{self.collection_prefix}_{collection_name}",
|
125 |
+
limit=NO_LIMIT, # otherwise qdrant would set limit to 10!
|
126 |
+
)
|
127 |
+
return self._result_to_get_result(points.points)
|
128 |
+
|
129 |
+
def insert(self, collection_name: str, items: list[VectorItem]):
|
130 |
+
# Insert the items into the collection, if the collection does not exist, it will be created.
|
131 |
+
self._create_collection_if_not_exists(collection_name, len(items[0]["vector"]))
|
132 |
+
points = self._create_points(items)
|
133 |
+
self.client.upload_points(f"{self.collection_prefix}_{collection_name}", points)
|
134 |
+
|
135 |
+
def upsert(self, collection_name: str, items: list[VectorItem]):
|
136 |
+
# Update the items in the collection, if the items are not present, insert them. If the collection does not exist, it will be created.
|
137 |
+
self._create_collection_if_not_exists(collection_name, len(items[0]["vector"]))
|
138 |
+
points = self._create_points(items)
|
139 |
+
return self.client.upsert(f"{self.collection_prefix}_{collection_name}", points)
|
140 |
+
|
141 |
+
def delete(
|
142 |
+
self,
|
143 |
+
collection_name: str,
|
144 |
+
ids: Optional[list[str]] = None,
|
145 |
+
filter: Optional[dict] = None,
|
146 |
+
):
|
147 |
+
# Delete the items from the collection based on the ids.
|
148 |
+
field_conditions = []
|
149 |
+
|
150 |
+
if ids:
|
151 |
+
for id_value in ids:
|
152 |
+
field_conditions.append(
|
153 |
+
models.FieldCondition(
|
154 |
+
key="metadata.id",
|
155 |
+
match=models.MatchValue(value=id_value),
|
156 |
+
),
|
157 |
+
),
|
158 |
+
elif filter:
|
159 |
+
for key, value in filter.items():
|
160 |
+
field_conditions.append(
|
161 |
+
models.FieldCondition(
|
162 |
+
key=f"metadata.{key}",
|
163 |
+
match=models.MatchValue(value=value),
|
164 |
+
),
|
165 |
+
),
|
166 |
+
|
167 |
+
return self.client.delete(
|
168 |
+
collection_name=f"{self.collection_prefix}_{collection_name}",
|
169 |
+
points_selector=models.FilterSelector(
|
170 |
+
filter=models.Filter(must=field_conditions)
|
171 |
+
),
|
172 |
+
)
|
173 |
+
|
174 |
+
def reset(self):
|
175 |
+
# Resets the database. This will delete all collections and item entries.
|
176 |
+
collection_names = self.client.get_collections().collections
|
177 |
+
for collection_name in collection_names:
|
178 |
+
if collection_name.name.startswith(self.collection_prefix):
|
179 |
+
self.client.delete_collection(collection_name=collection_name.name)
|