github-actions[bot] commited on
Commit
831bbaa
0 Parent(s):

GitHub deploy: 1e8abea753fb6cd58482cab5027d5bcbd0a2db2e

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .dockerignore +19 -0
  2. .env.example +13 -0
  3. .eslintignore +13 -0
  4. .eslintrc.cjs +31 -0
  5. .gitattributes +2 -0
  6. .github/FUNDING.yml +1 -0
  7. .github/ISSUE_TEMPLATE/bug_report.md +66 -0
  8. .github/ISSUE_TEMPLATE/feature_request.md +19 -0
  9. .github/dependabot.yml +12 -0
  10. .github/pull_request_template.md +72 -0
  11. .github/workflows/build-release.yml +70 -0
  12. .github/workflows/deploy-to-hf-spaces.yml +59 -0
  13. .github/workflows/docker-build.yaml +478 -0
  14. .github/workflows/format-backend.yaml +39 -0
  15. .github/workflows/format-build-frontend.yaml +57 -0
  16. .github/workflows/integration-test.yml +250 -0
  17. .github/workflows/lint-backend.disabled +27 -0
  18. .github/workflows/lint-frontend.disabled +21 -0
  19. .github/workflows/release-pypi.yml +31 -0
  20. .gitignore +309 -0
  21. .npmrc +1 -0
  22. .prettierignore +316 -0
  23. .prettierrc +9 -0
  24. CHANGELOG.md +824 -0
  25. CODE_OF_CONDUCT.md +77 -0
  26. Caddyfile.localhost +64 -0
  27. Dockerfile +161 -0
  28. INSTALLATION.md +35 -0
  29. LICENSE +21 -0
  30. Makefile +33 -0
  31. README.md +211 -0
  32. TROUBLESHOOTING.md +36 -0
  33. backend/.dockerignore +14 -0
  34. backend/.gitignore +16 -0
  35. backend/alembic.ini +114 -0
  36. backend/apps/audio/main.py +524 -0
  37. backend/apps/images/main.py +580 -0
  38. backend/apps/images/utils/comfyui.py +409 -0
  39. backend/apps/ollama/main.py +1071 -0
  40. backend/apps/openai/main.py +514 -0
  41. backend/apps/rag/main.py +1461 -0
  42. backend/apps/rag/search/brave.py +42 -0
  43. backend/apps/rag/search/duckduckgo.py +49 -0
  44. backend/apps/rag/search/google_pse.py +51 -0
  45. backend/apps/rag/search/jina_search.py +41 -0
  46. backend/apps/rag/search/main.py +20 -0
  47. backend/apps/rag/search/searxng.py +92 -0
  48. backend/apps/rag/search/serper.py +43 -0
  49. backend/apps/rag/search/serply.py +70 -0
  50. backend/apps/rag/search/serpstack.py +49 -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,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ## Installation Method
12
+
13
+ [Describe the method you used to install the project, e.g., git clone, Docker, pip, etc.]
14
+
15
+ ## Environment
16
+
17
+ - **Open WebUI Version:** [e.g., v0.3.11]
18
+ - **Ollama (if applicable):** [e.g., v0.2.0, v0.1.32-rc1]
19
+
20
+ - **Operating System:** [e.g., Windows 10, macOS Big Sur, Ubuntu 20.04]
21
+ - **Browser (if applicable):** [e.g., Chrome 100.0, Firefox 98.0]
22
+
23
+ **Confirmation:**
24
+
25
+ - [ ] I have read and followed all the instructions provided in the README.md.
26
+ - [ ] I am on the latest version of both Open WebUI and Ollama.
27
+ - [ ] I have included the browser console logs.
28
+ - [ ] I have included the Docker container logs.
29
+ - [ ] I have provided the exact steps to reproduce the bug in the "Steps to Reproduce" section below.
30
+
31
+ ## Expected Behavior:
32
+
33
+ [Describe what you expected to happen.]
34
+
35
+ ## Actual Behavior:
36
+
37
+ [Describe what actually happened.]
38
+
39
+ ## Description
40
+
41
+ **Bug Summary:**
42
+ [Provide a brief but clear summary of the bug]
43
+
44
+ ## Reproduction Details
45
+
46
+ **Steps to Reproduce:**
47
+ [Outline the steps to reproduce the bug. Be as detailed as possible.]
48
+
49
+ ## Logs and Screenshots
50
+
51
+ **Browser Console Logs:**
52
+ [Include relevant browser console logs, if applicable]
53
+
54
+ **Docker Container Logs:**
55
+ [Include relevant Docker container logs, if applicable]
56
+
57
+ **Screenshots/Screen Recordings (if applicable):**
58
+ [Attach any relevant screenshots to help illustrate the issue]
59
+
60
+ ## Additional Information
61
+
62
+ [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.]
63
+
64
+ ## Note
65
+
66
+ 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,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ name: Feature request
3
+ about: Suggest an idea for this project
4
+ title: ''
5
+ labels: ''
6
+ assignees: ''
7
+ ---
8
+
9
+ **Is your feature request related to a problem? Please describe.**
10
+ A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
11
+
12
+ **Describe the solution you'd like**
13
+ A clear and concise description of what you want to happen.
14
+
15
+ **Describe alternatives you've considered**
16
+ A clear and concise description of any alternative solutions or features you've considered.
17
+
18
+ **Additional context**
19
+ 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,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ env:
59
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
60
+
61
+ - name: Trigger Docker build workflow
62
+ uses: actions/github-script@v7
63
+ with:
64
+ script: |
65
+ github.rest.actions.createWorkflowDispatch({
66
+ owner: context.repo.owner,
67
+ repo: context.repo.repo,
68
+ workflow_id: 'docker-build.yaml',
69
+ ref: 'v${{ steps.get_version.outputs.version }}',
70
+ })
.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,478 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
368
+ merge-cuda-images:
369
+ runs-on: ubuntu-latest
370
+ needs: [ build-cuda-image ]
371
+ steps:
372
+ # GitHub Packages requires the entire repository name to be in lowercase
373
+ # although the repository owner has a lowercase username, this prevents some people from running actions after forking
374
+ - name: Set repository and image name to lowercase
375
+ run: |
376
+ echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
377
+ echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
378
+ env:
379
+ IMAGE_NAME: '${{ github.repository }}'
380
+
381
+ - name: Download digests
382
+ uses: actions/download-artifact@v4
383
+ with:
384
+ pattern: digests-cuda-*
385
+ path: /tmp/digests
386
+ merge-multiple: true
387
+
388
+ - name: Set up Docker Buildx
389
+ uses: docker/setup-buildx-action@v3
390
+
391
+ - name: Log in to the Container registry
392
+ uses: docker/login-action@v3
393
+ with:
394
+ registry: ${{ env.REGISTRY }}
395
+ username: ${{ github.actor }}
396
+ password: ${{ secrets.GITHUB_TOKEN }}
397
+
398
+ - name: Extract metadata for Docker images (default latest tag)
399
+ id: meta
400
+ uses: docker/metadata-action@v5
401
+ with:
402
+ images: ${{ env.FULL_IMAGE_NAME }}
403
+ tags: |
404
+ type=ref,event=branch
405
+ type=ref,event=tag
406
+ type=sha,prefix=git-
407
+ type=semver,pattern={{version}}
408
+ type=semver,pattern={{major}}.{{minor}}
409
+ type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=cuda
410
+ flavor: |
411
+ latest=${{ github.ref == 'refs/heads/main' }}
412
+ suffix=-cuda,onlatest=true
413
+
414
+ - name: Create manifest list and push
415
+ working-directory: /tmp/digests
416
+ run: |
417
+ docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
418
+ $(printf '${{ env.FULL_IMAGE_NAME }}@sha256:%s ' *)
419
+
420
+ - name: Inspect image
421
+ run: |
422
+ docker buildx imagetools inspect ${{ env.FULL_IMAGE_NAME }}:${{ steps.meta.outputs.version }}
423
+
424
+ merge-ollama-images:
425
+ runs-on: ubuntu-latest
426
+ needs: [ build-ollama-image ]
427
+ steps:
428
+ # GitHub Packages requires the entire repository name to be in lowercase
429
+ # although the repository owner has a lowercase username, this prevents some people from running actions after forking
430
+ - name: Set repository and image name to lowercase
431
+ run: |
432
+ echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
433
+ echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
434
+ env:
435
+ IMAGE_NAME: '${{ github.repository }}'
436
+
437
+ - name: Download digests
438
+ uses: actions/download-artifact@v4
439
+ with:
440
+ pattern: digests-ollama-*
441
+ path: /tmp/digests
442
+ merge-multiple: true
443
+
444
+ - name: Set up Docker Buildx
445
+ uses: docker/setup-buildx-action@v3
446
+
447
+ - name: Log in to the Container registry
448
+ uses: docker/login-action@v3
449
+ with:
450
+ registry: ${{ env.REGISTRY }}
451
+ username: ${{ github.actor }}
452
+ password: ${{ secrets.GITHUB_TOKEN }}
453
+
454
+ - name: Extract metadata for Docker images (default ollama tag)
455
+ id: meta
456
+ uses: docker/metadata-action@v5
457
+ with:
458
+ images: ${{ env.FULL_IMAGE_NAME }}
459
+ tags: |
460
+ type=ref,event=branch
461
+ type=ref,event=tag
462
+ type=sha,prefix=git-
463
+ type=semver,pattern={{version}}
464
+ type=semver,pattern={{major}}.{{minor}}
465
+ type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=ollama
466
+ flavor: |
467
+ latest=${{ github.ref == 'refs/heads/main' }}
468
+ suffix=-ollama,onlatest=true
469
+
470
+ - name: Create manifest list and push
471
+ working-directory: /tmp/digests
472
+ run: |
473
+ docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
474
+ $(printf '${{ env.FULL_IMAGE_NAME }}@sha256:%s ' *)
475
+
476
+ - name: Inspect image
477
+ run: |
478
+ 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@v4
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: '20' # 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: '20'
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,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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/[email protected]
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@v4
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 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
+ run: |
186
+ cd backend
187
+ uvicorn main:app --port "8081" --forwarded-allow-ips '*' &
188
+ UVICORN_PID=$!
189
+ # Wait up to 20 seconds for the server to start
190
+ for i in {1..20}; do
191
+ curl -s http://localhost:8081/api/config > /dev/null && break
192
+ sleep 1
193
+ if [ $i -eq 20 ]; then
194
+ echo "Server failed to start"
195
+ kill -9 $UVICORN_PID
196
+ exit 1
197
+ fi
198
+ done
199
+ # Check that the server is still running after 5 seconds
200
+ sleep 5
201
+ if ! kill -0 $UVICORN_PID; then
202
+ echo "Server has stopped"
203
+ exit 1
204
+ fi
205
+
206
+ # Check that service will reconnect to postgres when connection will be closed
207
+ status_code=$(curl --write-out %{http_code} -s --output /dev/null http://localhost:8081/health/db)
208
+ if [[ "$status_code" -ne 200 ]] ; then
209
+ echo "Server has failed before postgres reconnect check"
210
+ exit 1
211
+ fi
212
+
213
+ echo "Terminating all connections to postgres..."
214
+ python -c "import os, psycopg2 as pg2; \
215
+ conn = pg2.connect(dsn=os.environ['DATABASE_URL'].replace('+pool', '')); \
216
+ cur = conn.cursor(); \
217
+ cur.execute('SELECT pg_terminate_backend(psa.pid) FROM pg_stat_activity psa WHERE datname = current_database() AND pid <> pg_backend_pid();')"
218
+
219
+ status_code=$(curl --write-out %{http_code} -s --output /dev/null http://localhost:8081/health/db)
220
+ if [[ "$status_code" -ne 200 ]] ; then
221
+ echo "Server has not reconnected to postgres after connection was closed: returned status $status_code"
222
+ exit 1
223
+ fi
224
+
225
+ # - name: Test backend with MySQL
226
+ # if: success() || steps.sqlite.conclusion == 'failure' || steps.postgres.conclusion == 'failure'
227
+ # env:
228
+ # WEBUI_SECRET_KEY: secret-key
229
+ # GLOBAL_LOG_LEVEL: debug
230
+ # DATABASE_URL: mysql://root:mysql@localhost:3306/mysql
231
+ # run: |
232
+ # cd backend
233
+ # uvicorn main:app --port "8083" --forwarded-allow-ips '*' &
234
+ # UVICORN_PID=$!
235
+ # # Wait up to 20 seconds for the server to start
236
+ # for i in {1..20}; do
237
+ # curl -s http://localhost:8083/api/config > /dev/null && break
238
+ # sleep 1
239
+ # if [ $i -eq 20 ]; then
240
+ # echo "Server failed to start"
241
+ # kill -9 $UVICORN_PID
242
+ # exit 1
243
+ # fi
244
+ # done
245
+ # # Check that the server is still running after 5 seconds
246
+ # sleep 5
247
+ # if ! kill -0 $UVICORN_PID; then
248
+ # echo "Server has stopped"
249
+ # exit 1
250
+ # 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@v4
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,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Release to PyPI
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
+ environment:
12
+ name: pypi
13
+ url: https://pypi.org/p/open-webui
14
+ permissions:
15
+ id-token: write
16
+ steps:
17
+ - name: Checkout repository
18
+ uses: actions/checkout@v4
19
+ - uses: actions/setup-node@v4
20
+ with:
21
+ node-version: 18
22
+ - uses: actions/setup-python@v5
23
+ with:
24
+ python-version: 3.11
25
+ - name: Build
26
+ run: |
27
+ python -m pip install --upgrade pip
28
+ pip install build
29
+ python -m build .
30
+ - name: Publish package distributions to PyPI
31
+ 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,824 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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.13] - 2024-08-14
9
+
10
+ ### Added
11
+
12
+ - **🎨 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.
13
+ - **🔄 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.
14
+ - **🌀 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.
15
+ - **📶 Websocket Reconnection**: Enhanced reliability with the capability to automatically reconnect when a websocket is closed, ensuring consistent and stable communication.
16
+ - **🤳 Haptic Feedback on Support Devices**: Android devices now support haptic feedback for an immersive tactile experience during certain interactions.
17
+
18
+ ### Fixed
19
+
20
+ - **🛠️ 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.
21
+ - **🔀 Session Handling**: Fixed an issue mandating session_id on client-side to ensure smoother session management and transitions.
22
+ - **🖋️ Minor Bug Fixes and Format Corrections**: Various minor fixes including typo corrections, backend formatting improvements, and test amendments enhancing overall system stability and performance.
23
+
24
+ ### Changed
25
+
26
+ - **🚀 Migration to SvelteKit 2**: Upgraded the underlying framework to SvelteKit version 2, offering enhanced speed, better code structure, and improved deployment capabilities.
27
+ - **🧹 General Cleanup and Refactoring**: Performed broad cleanup and refactoring across the platform, improving code efficiency and maintaining high standards of code health.
28
+ - **🚧 Integration Testing Improvements**: Modified how Cypress integration tests detect chat messages and updated sharing tests for better reliability and accuracy.
29
+ - **📁 Standardized '.safetensors' File Extension**: Renamed the '.sft' file extension to '.safetensors' for ComfyUI workflows, standardizing file formats across the platform.
30
+
31
+ ### Removed
32
+
33
+ - **🗑️ Deprecated Frontend Functions**: Removed frontend functions that were migrated to backend to declutter the codebase and reduce redundancy.
34
+
35
+ ## [0.3.12] - 2024-08-07
36
+
37
+ ### Added
38
+
39
+ - **🔄 Sidebar Infinite Scroll**: Added an infinite scroll feature in the sidebar for more efficient chat navigation, reducing load times and enhancing user experience.
40
+ - **🚀 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.
41
+ - **🔒 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.
42
+ - **🌍 Language Updates**: Added Malay (Bahasa Malaysia) translation and updated Catalan and Traditional Chinese translations to improve accessibility for more users.
43
+
44
+ ### Fixed
45
+
46
+ - **📊 Markdown Rendering Issues**: Resolved issues with markdown rendering to ensure consistent and correct display across components.
47
+ - **🛠️ Styling Issues**: Multiple fixes applied to styling throughout the application, improving the overall visual experience and interface consistency.
48
+ - **🗃️ Modal Handling**: Fixed an issue where modals were not closing correctly in various model chat scenarios, enhancing usability and interface reliability.
49
+ - **📄 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.
50
+ - **🔧 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.
51
+ - **🔄 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.
52
+
53
+ ### Changed
54
+
55
+ - **🔧 Backend Dependency Updates**: Updated several backend dependencies such as boto3, pypdf, python-pptx, validators, and black, ensuring up-to-date security and performance optimizations.
56
+
57
+ ## [0.3.11] - 2024-08-02
58
+
59
+ ### Added
60
+
61
+ - **📊 Model Information Display**: Added visuals for model selection, including images next to model names for more intuitive navigation.
62
+ - **🗣 ElevenLabs Voice Adaptations**: Voice enhancements including support for ElevenLabs voice ID by name for personalized vocal interactions.
63
+ - **⌨️ Arrow Keys Model Selection**: Users can now use arrow keys for quicker model selection, enhancing accessibility.
64
+ - **🔍 Fuzzy Search in Model Selector**: Enhanced model selector with fuzzy search to locate models swiftly, including descriptions.
65
+ - **🕹️ 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.
66
+ - **💾 Display File Size for Uploads**: Enhanced file interface now displays file size, preparing for upcoming upload restrictions.
67
+ - **🎚️ Advanced Params "Min P"**: Added 'Min P' parameter in the advanced settings for customized model precision control.
68
+ - **🔒 Enhanced OAuth**: Introduced custom redirect URI support for OAuth behind reverse proxies, enabling safer authentication processes.
69
+ - **🖥 Enhanced Latex Rendering**: Adjustments made to latex rendering processes, now accurately detecting and presenting latex inputs from text.
70
+ - **🌐 Internationalization**: Enhanced with new Romanian and updated Vietnamese and Ukrainian translations, helping broaden accessibility for international users.
71
+
72
+ ### Fixed
73
+
74
+ - **🔧 Tags Handling in Document Upload**: Tags are now properly sent to the upload document handler, resolving issues with missing metadata.
75
+ - **🖥️ Sensitive Input Fields**: Corrected browser misinterpretation of secure input fields, preventing misclassification as password fields.
76
+ - **📂 Static Path Resolution in PDF Generation**: Fixed static paths that adjust dynamically to prevent issues across various environments.
77
+
78
+ ### Changed
79
+
80
+ - **🎨 UI/UX Styling Enhancements**: Multiple minor styling updates for a cleaner and more intuitive user interface.
81
+ - **🚧 Refactoring Various Components**: Numerous refactoring changes across styling, file handling, and function simplifications for clarity and performance.
82
+ - **🎛️ User Valves Management**: Moved user valves from settings to direct chat controls for more user-friendly access during interactions.
83
+
84
+ ### Removed
85
+
86
+ - **⚙️ Health Check Logging**: Removed verbose logging from the health checking processes to declutter logs and improve backend performance.
87
+
88
+ ## [0.3.10] - 2024-07-17
89
+
90
+ ### Fixed
91
+
92
+ - **🔄 Improved File Upload**: Addressed the issue where file uploads lacked animation.
93
+ - **💬 Chat Continuity**: Fixed a problem where existing chats were not functioning properly in some instances.
94
+ - **🗂️ Chat File Reset**: Resolved the issue of chat files not resetting for new conversations, now ensuring a clean slate for each chat session.
95
+ - **📁 Document Workspace Uploads**: Corrected the handling of document uploads in the workspace using the Files API.
96
+
97
+ ## [0.3.9] - 2024-07-17
98
+
99
+ ### Added
100
+
101
+ - **📁 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.
102
+ - **🔧 "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.
103
+ - **📜 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.
104
+ - **🛠️ 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.
105
+ - **🎨 Styling Refactor**: Various styling updates for a cleaner and more cohesive user interface.
106
+ - **🌐 Enhanced Translations**: Improved translations for Catalan, Ukrainian, and Brazilian Portuguese.
107
+
108
+ ### Fixed
109
+
110
+ - **🔧 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.
111
+ - **🪲 Debug Logs**: Fixed an issue where debug logs were not being logged properly.
112
+ - **🔑 Automatic1111 Auth Key**: The auth key for Automatic1111 is no longer required.
113
+ - **📝 Title Generation**: Ensured that the title generation runs only once, even when multiple models are in a chat.
114
+ - **✅ Boolean Values in Params**: Added support for boolean values in parameters.
115
+ - **🖼️ Files Overlay Styling**: Fixed the styling issue with the files overlay.
116
+
117
+ ### Changed
118
+
119
+ - **⬆️ Dependency Updates**
120
+ - Upgraded 'pydantic' from version 2.7.1 to 2.8.2.
121
+ - Upgraded 'sqlalchemy' from version 2.0.30 to 2.0.31.
122
+ - Upgraded 'unstructured' from version 0.14.9 to 0.14.10.
123
+ - Upgraded 'chromadb' from version 0.5.3 to 0.5.4.
124
+
125
+ ## [0.3.8] - 2024-07-09
126
+
127
+ ### Added
128
+
129
+ - **💬 Chat Controls**: Easily adjust parameters for each chat session, offering more precise control over your interactions.
130
+ - **📌 Pinned Chats**: Support for pinned chats, allowing you to keep important conversations easily accessible.
131
+ - **📄 Apache Tika Integration**: Added support for using Apache Tika as a document loader, enhancing document processing capabilities.
132
+ - **🛠️ Custom Environment for OpenID Claims**: Allows setting custom claims for OpenID, providing more flexibility in user authentication.
133
+ - **🔧 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.
134
+ - **↔️ Sideways Scrolling in Settings**: Settings tabs container now supports horizontal scrolling for easier navigation.
135
+ - **🌑 Darker OLED Theme**: Includes a new, darker OLED theme and improved styling for the light theme, enhancing visual appeal.
136
+ - **🌐 Language Updates**: Updated translations for Indonesian, German, French, and Catalan languages, expanding accessibility.
137
+
138
+ ### Fixed
139
+
140
+ - **⏰ OpenAI Streaming Timeout**: Resolved issues with OpenAI streaming response using the 'AIOHTTP_CLIENT_TIMEOUT' setting, ensuring reliable performance.
141
+ - **💡 User Valves**: Fixed malfunctioning user valves, ensuring proper functionality.
142
+ - **🔄 Collapsible Components**: Addressed issues with collapsible components not working, restoring expected behavior.
143
+
144
+ ### Changed
145
+
146
+ - **🗃️ Database Backend**: Switched from Peewee to SQLAlchemy for improved concurrency support, enhancing database performance.
147
+ - **⬆️ ChromaDB Update**: Upgraded to version 0.5.3. Ensure your remote ChromaDB instance matches this version.
148
+ - **🔤 Primary Font Styling**: Updated primary font to Archivo for better visual consistency.
149
+ - **🔄 Font Change for Windows**: Replaced Arimo with Inter font for Windows users, improving readability.
150
+ - **🚀 Lazy Loading**: Implemented lazy loading for 'faster_whisper' and 'sentence_transformers' to reduce startup memory usage.
151
+ - **📋 Task Generation Payload**: Task generations now include only the "task" field in the body instead of "title".
152
+
153
+ ## [0.3.7] - 2024-06-29
154
+
155
+ ### Added
156
+
157
+ - **🌐 Enhanced Internationalization (i18n)**: Newly introduced Indonesian translation, and updated translations for Turkish, Chinese, and Catalan languages to improve user accessibility.
158
+
159
+ ### Fixed
160
+
161
+ - **🕵️‍♂️ Browser Language Detection**: Corrected the issue where the application was not properly detecting and adapting to the browser's language settings.
162
+ - **🔐 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).
163
+ - **💬 Chat/Completions Endpoint**: Resolved an issue where the chat/completions endpoint was non-functional when the stream option was set to False.
164
+ - **🚫 'WEBUI_AUTH' Configuration**: Addressed the problem where setting 'WEBUI_AUTH' to False was not being applied correctly.
165
+
166
+ ### Changed
167
+
168
+ - **📦 Dependency Update**: Upgraded 'authlib' from version 1.3.0 to 1.3.1 to ensure better security and performance enhancements.
169
+
170
+ ## [0.3.6] - 2024-06-27
171
+
172
+ ### Added
173
+
174
+ - **✨ "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.
175
+ - **📁 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.
176
+ - **🛠️ Tool Enhancements**: Tools now support citations and "Valves". Documentation will be available shortly.
177
+ - **🔗 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.
178
+ - **🔒 Experimental OAuth Support**: New experimental OAuth support. Check our documentation for more details.
179
+ - **🖼️ Custom Background Support**: Set a custom background from Settings > Interface to personalize your experience.
180
+ - **🔑 AUTOMATIC1111_API_AUTH Support**: Enhanced security for the AUTOMATIC1111 API.
181
+ - **🎨 Code Highlight Optimization**: Improved code highlighting features.
182
+ - **🎙️ Voice Interruption Feature**: Reintroduced and now toggleable from Settings > Interface.
183
+ - **��� Wakelock API**: Now in use to prevent screen dimming during important tasks.
184
+ - **🔐 API Key Privacy**: All API keys are now hidden by default for better security.
185
+ - **🔍 New Web Search Provider**: Added jina_search as a new option.
186
+ - **🌐 Enhanced Internationalization (i18n)**: Improved Korean translation and updated Chinese and Ukrainian translations.
187
+
188
+ ### Fixed
189
+
190
+ - **🔧 Conversation Mode Issue**: Fixed the issue where Conversation Mode remained active after being removed from settings.
191
+ - **📏 Scroll Button Obstruction**: Resolved the issue where the scrollToBottom button container obstructed clicks on buttons beneath it.
192
+
193
+ ### Changed
194
+
195
+ - **⏲️ AIOHTTP_CLIENT_TIMEOUT**: Now set to 'None' by default for improved configuration flexibility.
196
+ - **📞 Voice Call Enhancements**: Improved by skipping code blocks and expressions during calls.
197
+ - **🚫 Error Message Handling**: Disabled the continuation of operations with error messages.
198
+ - **🗂️ Playground Relocation**: Moved the Playground from the workspace to the user menu for better user experience.
199
+
200
+ ## [0.3.5] - 2024-06-16
201
+
202
+ ### Added
203
+
204
+ - **📞 Enhanced Voice Call**: Text-to-speech (TTS) callback now operates in real-time for each sentence, reducing latency by not waiting for full completion.
205
+ - **👆 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.
206
+ - **😊 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.
207
+ - **🖱️ Quick Archive/Delete**: Use the Shift key + mouseover on the chat list to swiftly archive or delete items.
208
+ - **📝 Markdown Support in Model Descriptions**: You can now format model descriptions with markdown, enabling bold text, links, etc.
209
+ - **🧠 Editable Memories**: Adds the capability to modify memories.
210
+ - **📋 Admin Panel Sorting**: Introduces the ability to sort users/chats within the admin panel.
211
+ - **🌑 Dark Mode for Quick Selectors**: Dark mode now available for chat quick selectors (prompts, models, documents).
212
+ - **🔧 Advanced Parameters**: Adds 'num_keep' and 'num_batch' to advanced parameters for customization.
213
+ - **📅 Dynamic System Prompts**: New variables '{{CURRENT_DATETIME}}', '{{CURRENT_TIME}}', '{{USER_LOCATION}}' added for system prompts. Ensure '{{USER_LOCATION}}' is toggled on from Settings > Interface.
214
+ - **🌐 Tavily Web Search**: Includes Tavily as a web search provider option.
215
+ - **🖊️ Federated Auth Usernames**: Ability to set user names for federated authentication.
216
+ - **🔗 Auto Clean URLs**: When adding connection URLs, trailing slashes are now automatically removed.
217
+ - **🌐 Enhanced Translations**: Improved Chinese and Swedish translations.
218
+
219
+ ### Fixed
220
+
221
+ - **⏳ 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.
222
+ - **❌ Message Delete Freeze**: Resolved an issue where message deletion would sometimes cause the web UI to freeze.
223
+
224
+ ## [0.3.4] - 2024-06-12
225
+
226
+ ### Fixed
227
+
228
+ - **🔒 Mixed Content with HTTPS Issue**: Resolved a problem where mixed content (HTTP and HTTPS) was causing security warnings and blocking resources on HTTPS sites.
229
+ - **🔍 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.
230
+ - **💾 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.
231
+
232
+ ## [0.3.3] - 2024-06-12
233
+
234
+ ### Added
235
+
236
+ - **🛠️ 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.
237
+ - **🌐 DuckDuckGo Integration**: Added DuckDuckGo as a web search provider, giving you more search options.
238
+ - **🌏 Enhanced Translations**: Improved translations for Vietnamese and Chinese languages, making the interface more accessible.
239
+
240
+ ### Fixed
241
+
242
+ - **🔗 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.
243
+ - **🖥️ 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.
244
+ - **🔧 Dependency Issues in pip**: Fixed issues related to pip installations, ensuring all dependencies are correctly managed to prevent installation errors.
245
+
246
+ ## [0.3.2] - 2024-06-10
247
+
248
+ ### Added
249
+
250
+ - **🔍 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.
251
+ - **🌐 New Web Search Provider**: We have added Serply as a new option for web search providers, giving you more choices for your search needs.
252
+ - **🌏 Improved Translations**: We've enhanced translations for Chinese and Portuguese.
253
+
254
+ ### Fixed
255
+
256
+ - **🎤 Audio File Upload Issue**: The bug that prevented audio files from being uploaded in chat input has been fixed, ensuring smooth communication.
257
+ - **💬 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.
258
+ - **⚙️ 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.
259
+
260
+ ## [0.3.1] - 2024-06-09
261
+
262
+ ### Fixed
263
+
264
+ - **💬 Chat Functionality**: Resolved the issue where chat functionality was not working for specific models.
265
+
266
+ ## [0.3.0] - 2024-06-09
267
+
268
+ ### Added
269
+
270
+ - **📚 Knowledge Support for Models**: Attach documents directly to models from the models workspace, enhancing the information available to each model.
271
+ - **🎙️ Hands-Free Voice Call Feature**: Initiate voice calls without needing to use your hands, making interactions more seamless.
272
+ - **📹 Video Call Feature**: Enable video calls with supported vision models like Llava and GPT-4o, adding a visual dimension to your communications.
273
+ - **🎛️ Enhanced UI for Voice Recording**: Improved user interface for the voice recording feature, making it more intuitive and user-friendly.
274
+ - **🌐 External STT Support**: Now support for external Speech-To-Text services, providing more flexibility in choosing your STT provider.
275
+ - **⚙️ Unified Settings**: Consolidated settings including document settings under a new admin settings section for easier management.
276
+ - **🌑 Dark Mode Splash Screen**: A new splash screen for dark mode, ensuring a consistent and visually appealing experience for dark mode users.
277
+ - **📥 Upload Pipeline**: Directly upload pipelines from the admin settings > pipelines section, streamlining the pipeline management process.
278
+ - **🌍 Improved Language Support**: Enhanced support for Chinese and Ukrainian languages, better catering to a global user base.
279
+
280
+ ### Fixed
281
+
282
+ - **🛠️ Playground Issue**: Fixed the playground not functioning properly, ensuring a smoother user experience.
283
+ - **🔥 Temperature Parameter Issue**: Corrected the issue where the temperature value '0' was not being passed correctly.
284
+ - **📝 Prompt Input Clearing**: Resolved prompt input textarea not being cleared right away, ensuring a clean slate for new inputs.
285
+ - **✨ Various UI Styling Issues**: Fixed numerous user interface styling problems for a more cohesive look.
286
+ - **👥 Active Users Display**: Fixed active users showing active sessions instead of actual users, now reflecting accurate user activity.
287
+ - **🌐 Community Platform Compatibility**: The Community Platform is back online and fully compatible with Open WebUI.
288
+
289
+ ### Changed
290
+
291
+ - **📝 RAG Implementation**: Updated the RAG (Retrieval-Augmented Generation) implementation to use a system prompt for context, instead of overriding the user's prompt.
292
+ - **🔄 Settings Relocation**: Moved Models, Connections, Audio, and Images settings to the admin settings for better organization.
293
+ - **✍️ Improved Title Generation**: Enhanced the default prompt for title generation, yielding better results.
294
+ - **🔧 Backend Task Management**: Tasks like title generation and search query generation are now managed on the backend side and controlled only by the admin.
295
+ - **🔍 Editable Search Query Prompt**: You can now edit the search query generation prompt, offering more control over how queries are generated.
296
+ - **📏 Prompt Length Threshold**: Set the prompt length threshold for search query generation from the admin settings, giving more customization options.
297
+ - **📣 Settings Consolidation**: Merged the Banners admin setting with the Interface admin setting for a more streamlined settings area.
298
+
299
+ ## [0.2.5] - 2024-06-05
300
+
301
+ ### Added
302
+
303
+ - **👥 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.
304
+ - **🗂️ 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.
305
+ - **⚙️ 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.
306
+ - **🌐 Enhanced Translations**: We've improved the Chinese translations and added support for Turkmen and Norwegian languages to make the interface more accessible globally.
307
+
308
+ ### Fixed
309
+
310
+ - **📱 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.
311
+
312
+ ## [0.2.4] - 2024-06-03
313
+
314
+ ### Added
315
+
316
+ - **👤 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.
317
+ - **🌐 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.
318
+ - **❓ 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).
319
+ - **🌍 Enhanced Translation**: Improvements have been made to translations.
320
+
321
+ ### Fixed
322
+
323
+ - **🔍 SearxNG Web Search**: Fixed the issue where the SearxNG web search functionality was not working properly.
324
+
325
+ ## [0.2.3] - 2024-06-03
326
+
327
+ ### Added
328
+
329
+ - **📁 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.
330
+ - **✏️ Edit Titles with Double Click**: Double-click on titles to rename them quickly and efficiently.
331
+ - **🧩 Batch Multiple Embeddings**: Introduced 'RAG_EMBEDDING_OPENAI_BATCH_SIZE' to process multiple embeddings in a batch, enhancing performance for large datasets.
332
+ - **🌍 Improved Translations**: Enhanced the translation quality across various languages for a better user experience.
333
+
334
+ ### Fixed
335
+
336
+ - **🛠️ Modelfile Migration Script**: Fixed an issue where the modelfile migration script would fail if an invalid modelfile was encountered.
337
+ - **💬 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.
338
+ - **🔊 Local TTS Voice Selection**: Fixed the issue where the selected local Text-to-Speech (TTS) voice was not being displayed in settings.
339
+
340
+ ## [0.2.2] - 2024-06-02
341
+
342
+ ### Added
343
+
344
+ - **🌊 Mermaid Rendering Support**: We've included support for Mermaid rendering. This allows you to create beautiful diagrams and flowcharts directly within Open WebUI.
345
+ - **🔄 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.
346
+
347
+ ### Fixed
348
+
349
+ - **🔧 Pipelines Filter Issue**: We've addressed an issue with the pipelines where filters were not functioning as expected.
350
+
351
+ ## [0.2.1] - 2024-06-02
352
+
353
+ ### Added
354
+
355
+ - **🖱️ Single Model Export Button**: Easily export models with just one click using the new single model export button.
356
+ - **🖥️ Advanced Parameters Support**: Added support for 'num_thread', 'use_mmap', and 'use_mlock' parameters for Ollama.
357
+ - **🌐 Improved Vietnamese Translation**: Enhanced Vietnamese language support for a better user experience for our Vietnamese-speaking community.
358
+
359
+ ### Fixed
360
+
361
+ - **🔧 OpenAI URL API Save Issue**: Corrected a problem preventing the saving of OpenAI URL API settings.
362
+ - **🚫 Display Issue with Disabled Ollama API**: Fixed the display bug causing models to appear in settings when the Ollama API was disabled.
363
+
364
+ ### Changed
365
+
366
+ - **💡 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.
367
+
368
+ ## [0.2.0] - 2024-06-01
369
+
370
+ ### Added
371
+
372
+ - **🔧 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.
373
+ - **🔗 Function Calling via Pipelines**: Integrate function calling seamlessly through Pipelines.
374
+ - **⚖️ User Rate Limiting via Pipelines**: Implement user-specific rate limits to manage API usage efficiently.
375
+ - **📊 Usage Monitoring with Langfuse**: Track and analyze usage statistics with Langfuse integration through Pipelines.
376
+ - **🕒 Conversation Turn Limits**: Set limits on conversation turns to manage interactions better through Pipelines.
377
+ - **🛡️ Toxic Message Filtering**: Automatically filter out toxic messages to maintain a safe environment using Pipelines.
378
+ - **🔍 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.
379
+ - **🗂️ Models Workspace**: Create and manage model presets for both Ollama/OpenAI API. Note: The old Modelfiles workspace is deprecated.
380
+ - **🛠️ Model Builder Feature**: Build and edit all models with persistent builder mode.
381
+ - **🏷️ Model Tagging Support**: Organize models with tagging features in the models workspace.
382
+ - **📋 Model Ordering Support**: Effortlessly organize models by dragging and dropping them into the desired positions within the models workspace.
383
+ - **📈 OpenAI Generation Stats**: Access detailed generation statistics for OpenAI models.
384
+ - **📅 System Prompt Variables**: New variables added: '{{CURRENT_DATE}}' and '{{USER_NAME}}' for dynamic prompts.
385
+ - **📢 Global Banner Support**: Manage global banners from admin settings > banners.
386
+ - **🗃️ Enhanced Archived Chats Modal**: Search and export archived chats easily.
387
+ - **📂 Archive All Button**: Quickly archive all chats from settings > chats.
388
+ - **🌐 Improved Translations**: Added and improved translations for French, Croatian, Cebuano, and Vietnamese.
389
+
390
+ ### Fixed
391
+
392
+ - **🔍 Archived Chats Visibility**: Resolved issue with archived chats not showing in the admin panel.
393
+ - **💬 Message Styling**: Fixed styling issues affecting message appearance.
394
+ - **🔗 Shared Chat Responses**: Corrected the issue where shared chat response messages were not readonly.
395
+ - **🖥️ UI Enhancement**: Fixed the scrollbar overlapping issue with the message box in the user interface.
396
+
397
+ ### Changed
398
+
399
+ - **💾 User Settings Storage**: User settings are now saved on the backend, ensuring consistency across all devices.
400
+ - **📡 Unified API Requests**: The API request for getting models is now unified to '/api/models' for easier usage.
401
+ - **🔄 Versioning Update**: Our versioning will now follow the format 0.x for major updates and 0.x.y for patches.
402
+ - **📦 Export All Chats (All Users)**: Moved this functionality to the Admin Panel settings for better organization and accessibility.
403
+
404
+ ### Removed
405
+
406
+ - **🚫 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.
407
+
408
+ ## [0.1.125] - 2024-05-19
409
+
410
+ ### Added
411
+
412
+ - **🔄 Updated UI**: Chat interface revamped with chat bubbles. Easily switch back to the old style via settings > interface > chat bubble UI.
413
+ - **📂 Enhanced Sidebar UI**: Model files, documents, prompts, and playground merged into Workspace for streamlined access.
414
+ - **🚀 Improved Many Model Interaction**: All responses now displayed simultaneously for a smoother experience.
415
+ - **🐍 Python Code Execution**: Execute Python code locally in the browser with libraries like 'requests', 'beautifulsoup4', 'numpy', 'pandas', 'seaborn', 'matplotlib', 'scikit-learn', 'scipy', 'regex'.
416
+ - **🧠 Experimental Memory Feature**: Manually input personal information you want LLMs to remember via settings > personalization > memory.
417
+ - **💾 Persistent Settings**: Settings now saved as config.json for convenience.
418
+ - **🩺 Health Check Endpoint**: Added for Docker deployment.
419
+ - **↕️ RTL Support**: Toggle chat direction via settings > interface > chat direction.
420
+ - **🖥️ PowerPoint Support**: RAG pipeline now supports PowerPoint documents.
421
+ - **🌐 Language Updates**: Ukrainian, Turkish, Arabic, Chinese, Serbian, Vietnamese updated; Punjabi added.
422
+
423
+ ### Changed
424
+
425
+ - **👤 Shared Chat Update**: Shared chat now includes creator user information.
426
+
427
+ ## [0.1.124] - 2024-05-08
428
+
429
+ ### Added
430
+
431
+ - **🖼️ Improved Chat Sidebar**: Now conveniently displays time ranges and organizes chats by today, yesterday, and more.
432
+ - **📜 Citations in RAG Feature**: Easily track the context fed to the LLM with added citations in the RAG feature.
433
+ - **🔒 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.
434
+ - **📹 Enhanced YouTube RAG Pipeline**: Now supports non-English videos for an enriched experience.
435
+ - **🔊 Specify OpenAI TTS Models**: Customize your TTS experience by specifying OpenAI TTS models.
436
+ - **🔧 Additional Environment Variables**: Discover more environment variables in our comprehensive documentation at Open WebUI Documentation (https://docs.openwebui.com).
437
+ - **🌐 Language Support**: Arabic, Finnish, and Hindi added; Improved support for German, Vietnamese, and Chinese.
438
+
439
+ ### Fixed
440
+
441
+ - **🛠️ Model Selector Styling**: Addressed styling issues for improved user experience.
442
+ - **⚠️ Warning Messages**: Resolved backend warning messages.
443
+
444
+ ### Changed
445
+
446
+ - **📝 Title Generation**: Limited output to 50 tokens.
447
+ - **📦 Helm Charts**: Removed Helm charts, now available in a separate repository (https://github.com/open-webui/helm-charts).
448
+
449
+ ## [0.1.123] - 2024-05-02
450
+
451
+ ### Added
452
+
453
+ - **🎨 New Landing Page Design**: Refreshed design for a more modern look and optimized use of screen space.
454
+ - **📹 Youtube RAG Pipeline**: Introduces dedicated RAG pipeline for Youtube videos, enabling interaction with video transcriptions directly.
455
+ - **🔧 Enhanced Admin Panel**: Streamlined user management with options to add users directly or in bulk via CSV import.
456
+ - **👥 '@' Model Integration**: Easily switch to specific models during conversations; old collaborative chat feature phased out.
457
+ - **🌐 Language Enhancements**: Swedish translation added, plus improvements to German, Spanish, and the addition of Doge translation.
458
+
459
+ ### Fixed
460
+
461
+ - **🗑️ Delete Chat Shortcut**: Addressed issue where shortcut wasn't functioning.
462
+ - **🖼️ Modal Closing Bug**: Resolved unexpected closure of modal when dragging from within.
463
+ - **✏️ Edit Button Styling**: Fixed styling inconsistency with edit buttons.
464
+ - **🌐 Image Generation Compatibility Issue**: Rectified image generation compatibility issue with third-party APIs.
465
+ - **📱 iOS PWA Icon Fix**: Corrected iOS PWA home screen icon shape.
466
+ - **🔍 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.
467
+
468
+ ### Changed
469
+
470
+ - **🔄 Unlimited Context Length**: Advanced settings now allow unlimited max context length (previously limited to 16000).
471
+ - **👑 Super Admin Assignment**: The first signup is automatically assigned a super admin role, unchangeable by other admins.
472
+ - **🛡️ Admin User Restrictions**: User action buttons from the admin panel are now disabled for users with admin roles.
473
+ - **🔝 Default Model Selector**: Set as default model option now exclusively available on the landing page.
474
+
475
+ ## [0.1.122] - 2024-04-27
476
+
477
+ ### Added
478
+
479
+ - **🌟 Enhanced RAG Pipeline**: Now with hybrid searching via 'BM25', reranking powered by 'CrossEncoder', and configurable relevance score thresholds.
480
+ - **🛢️ External Database Support**: Seamlessly connect to custom SQLite or Postgres databases using the 'DATABASE_URL' environment variable.
481
+ - **🌐 Remote ChromaDB Support**: Introducing the capability to connect to remote ChromaDB servers.
482
+ - **👨‍💼 Improved Admin Panel**: Admins can now conveniently check users' chat lists and last active status directly from the admin panel.
483
+ - **🎨 Splash Screen**: Introducing a loading splash screen for a smoother user experience.
484
+ - **🌍 Language Support Expansion**: Added support for Bangla (bn-BD), along with enhancements to Chinese, Spanish, and Ukrainian translations.
485
+ - **💻 Improved LaTeX Rendering Performance**: Enjoy faster rendering times for LaTeX equations.
486
+ - **🔧 More Environment Variables**: Explore additional environment variables in our documentation (https://docs.openwebui.com), including the 'ENABLE_LITELLM' option to manage memory usage.
487
+
488
+ ### Fixed
489
+
490
+ - **🔧 Ollama Compatibility**: Resolved errors occurring when Ollama server version isn't an integer, such as SHA builds or RCs.
491
+ - **🐛 Various OpenAI API Issues**: Addressed several issues related to the OpenAI API.
492
+ - **🛑 Stop Sequence Issue**: Fixed the problem where the stop sequence with a backslash '\' was not functioning.
493
+ - **🔤 Font Fallback**: Corrected font fallback issue.
494
+
495
+ ### Changed
496
+
497
+ - **⌨️ Prompt Input Behavior on Mobile**: Enter key prompt submission disabled on mobile devices for improved user experience.
498
+
499
+ ## [0.1.121] - 2024-04-24
500
+
501
+ ### Fixed
502
+
503
+ - **🔧 Translation Issues**: Addressed various translation discrepancies.
504
+ - **🔒 LiteLLM Security Fix**: Updated LiteLLM version to resolve a security vulnerability.
505
+ - **🖥️ HTML Tag Display**: Rectified the issue where the '< br >' tag wasn't displaying correctly.
506
+ - **🔗 WebSocket Connection**: Resolved the failure of WebSocket connection under HTTPS security for ComfyUI server.
507
+ - **📜 FileReader Optimization**: Implemented FileReader initialization per image in multi-file drag & drop to ensure reusability.
508
+ - **🏷️ Tag Display**: Corrected tag display inconsistencies.
509
+ - **📦 Archived Chat Styling**: Fixed styling issues in archived chat.
510
+ - **🔖 Safari Copy Button Bug**: Addressed the bug where the copy button failed to copy links in Safari.
511
+
512
+ ## [0.1.120] - 2024-04-20
513
+
514
+ ### Added
515
+
516
+ - **📦 Archive Chat Feature**: Easily archive chats with a new sidebar button, and access archived chats via the profile button > archived chats.
517
+ - **🔊 Configurable Text-to-Speech Endpoint**: Customize your Text-to-Speech experience with configurable OpenAI endpoints.
518
+ - **🛠️ Improved Error Handling**: Enhanced error message handling for connection failures.
519
+ - **⌨️ Enhanced Shortcut**: When editing messages, use ctrl/cmd+enter to save and submit, and esc to close.
520
+ - **🌐 Language Support**: Added support for Georgian and enhanced translations for Portuguese and Vietnamese.
521
+
522
+ ### Fixed
523
+
524
+ - **🔧 Model Selector**: Resolved issue where default model selection was not saving.
525
+ - **🔗 Share Link Copy Button**: Fixed bug where the copy button wasn't copying links in Safari.
526
+ - **🎨 Light Theme Styling**: Addressed styling issue with the light theme.
527
+
528
+ ## [0.1.119] - 2024-04-16
529
+
530
+ ### Added
531
+
532
+ - **🌟 Enhanced RAG Embedding Support**: Ollama, and OpenAI models can now be used for RAG embedding model.
533
+ - **🔄 Seamless Integration**: Copy 'ollama run <model name>' directly from Ollama page to easily select and pull models.
534
+ - **🏷️ Tagging Feature**: Add tags to chats directly via the sidebar chat menu.
535
+ - **📱 Mobile Accessibility**: Swipe left and right on mobile to effortlessly open and close the sidebar.
536
+ - **🔍 Improved Navigation**: Admin panel now supports pagination for user list.
537
+ - **🌍 Additional Language Support**: Added Polish language support.
538
+
539
+ ### Fixed
540
+
541
+ - **🌍 Language Enhancements**: Vietnamese and Spanish translations have been improved.
542
+ - **🔧 Helm Fixes**: Resolved issues with Helm trailing slash and manifest.json.
543
+
544
+ ### Changed
545
+
546
+ - **🐳 Docker Optimization**: Updated docker image build process to utilize 'uv' for significantly faster builds compared to 'pip3'.
547
+
548
+ ## [0.1.118] - 2024-04-10
549
+
550
+ ### Added
551
+
552
+ - **🦙 Ollama and CUDA Images**: Added support for ':ollama' and ':cuda' tagged images.
553
+ - **👍 Enhanced Response Rating**: Now you can annotate your ratings for better feedback.
554
+ - **👤 User Initials Profile Photo**: User initials are now the default profile photo.
555
+ - **🔍 Update RAG Embedding Model**: Customize RAG embedding model directly in document settings.
556
+ - **🌍 Additional Language Support**: Added Turkish language support.
557
+
558
+ ### Fixed
559
+
560
+ - **🔒 Share Chat Permission**: Resolved issue with chat sharing permissions.
561
+ - **🛠 Modal Close**: Modals can now be closed using the Esc key.
562
+
563
+ ### Changed
564
+
565
+ - **🎨 Admin Panel Styling**: Refreshed styling for the admin panel.
566
+ - **🐳 Docker Image Build**: Updated docker image build process for improved efficiency.
567
+
568
+ ## [0.1.117] - 2024-04-03
569
+
570
+ ### Added
571
+
572
+ - 🗨️ **Local Chat Sharing**: Share chat links seamlessly between users.
573
+ - 🔑 **API Key Generation Support**: Generate secret keys to leverage Open WebUI with OpenAI libraries.
574
+ - 📄 **Chat Download as PDF**: Easily download chats in PDF format.
575
+ - 📝 **Improved Logging**: Enhancements to logging functionality.
576
+ - 📧 **Trusted Email Authentication**: Authenticate using a trusted email header.
577
+
578
+ ### Fixed
579
+
580
+ - 🌷 **Enhanced Dutch Translation**: Improved translation for Dutch users.
581
+ - ⚪ **White Theme Styling**: Resolved styling issue with the white theme.
582
+ - 📜 **LaTeX Chat Screen Overflow**: Fixed screen overflow issue with LaTeX rendering.
583
+ - 🔒 **Security Patches**: Applied necessary security patches.
584
+
585
+ ## [0.1.116] - 2024-03-31
586
+
587
+ ### Added
588
+
589
+ - **🔄 Enhanced UI**: Model selector now conveniently located in the navbar, enabling seamless switching between multiple models during conversations.
590
+ - **🔍 Improved Model Selector**: Directly pull a model from the selector/Models now display detailed information for better understanding.
591
+ - **💬 Webhook Support**: Now compatible with Google Chat and Microsoft Teams.
592
+ - **🌐 Localization**: Korean translation (I18n) now available.
593
+ - **🌑 Dark Theme**: OLED dark theme introduced for reduced strain during prolonged usage.
594
+ - **🏷️ Tag Autocomplete**: Dropdown feature added for effortless chat tagging.
595
+
596
+ ### Fixed
597
+
598
+ - **🔽 Auto-Scrolling**: Addressed OpenAI auto-scrolling issue.
599
+ - **🏷️ Tag Validation**: Implemented tag validation to prevent empty string tags.
600
+ - **🚫 Model Whitelisting**: Resolved LiteLLM model whitelisting issue.
601
+ - **✅ Spelling**: Corrected various spelling issues for improved readability.
602
+
603
+ ## [0.1.115] - 2024-03-24
604
+
605
+ ### Added
606
+
607
+ - **🔍 Custom Model Selector**: Easily find and select custom models with the new search filter feature.
608
+ - **🛑 Cancel Model Download**: Added the ability to cancel model downloads.
609
+ - **🎨 Image Generation ComfyUI**: Image generation now supports ComfyUI.
610
+ - **🌟 Updated Light Theme**: Updated the light theme for a fresh look.
611
+ - **🌍 Additional Language Support**: Now supporting Bulgarian, Italian, Portuguese, Japanese, and Dutch.
612
+
613
+ ### Fixed
614
+
615
+ - **🔧 Fixed Broken Experimental GGUF Upload**: Resolved issues with experimental GGUF upload functionality.
616
+
617
+ ### Changed
618
+
619
+ - **🔄 Vector Storage Reset Button**: Moved the reset vector storage button to document settings.
620
+
621
+ ## [0.1.114] - 2024-03-20
622
+
623
+ ### Added
624
+
625
+ - **🔗 Webhook Integration**: Now you can subscribe to new user sign-up events via webhook. Simply navigate to the admin panel > admin settings > webhook URL.
626
+ - **🛡️ Enhanced Model Filtering**: Alongside Ollama, OpenAI proxy model whitelisting, we've added model filtering functionality for LiteLLM proxy.
627
+ - **🌍 Expanded Language Support**: Spanish, Catalan, and Vietnamese languages are now available, with improvements made to others.
628
+
629
+ ### Fixed
630
+
631
+ - **🔧 Input Field Spelling**: Resolved issue with spelling mistakes in input fields.
632
+ - **🖊️ Light Mode Styling**: Fixed styling issue with light mode in document adding.
633
+
634
+ ### Changed
635
+
636
+ - **🔄 Language Sorting**: Languages are now sorted alphabetically by their code for improved organization.
637
+
638
+ ## [0.1.113] - 2024-03-18
639
+
640
+ ### Added
641
+
642
+ - 🌍 **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).
643
+ - 🎨 **System-wide Theme**: Introducing a new system-wide theme for enhanced visual experience.
644
+
645
+ ### Fixed
646
+
647
+ - 🌑 **Dark Background on Select Fields**: Improved readability by adding a dark background to select fields, addressing issues on certain browsers/devices.
648
+ - **Multiple OPENAI_API_BASE_URLS Issue**: Resolved issue where multiple base URLs caused conflicts when one wasn't functioning.
649
+ - **RAG Encoding Issue**: Fixed encoding problem in RAG.
650
+ - **npm Audit Fix**: Addressed npm audit findings.
651
+ - **Reduced Scroll Threshold**: Improved auto-scroll experience by reducing the scroll threshold from 50px to 5px.
652
+
653
+ ### Changed
654
+
655
+ - 🔄 **Sidebar UI Update**: Updated sidebar UI to feature a chat menu dropdown, replacing two icons for improved navigation.
656
+
657
+ ## [0.1.112] - 2024-03-15
658
+
659
+ ### Fixed
660
+
661
+ - 🗨️ Resolved chat malfunction after image generation.
662
+ - 🎨 Fixed various RAG issues.
663
+ - 🧪 Rectified experimental broken GGUF upload logic.
664
+
665
+ ## [0.1.111] - 2024-03-10
666
+
667
+ ### Added
668
+
669
+ - 🛡️ **Model Whitelisting**: Admins now have the ability to whitelist models for users with the 'user' role.
670
+ - 🔄 **Update All Models**: Added a convenient button to update all models at once.
671
+ - 📄 **Toggle PDF OCR**: Users can now toggle PDF OCR option for improved parsing performance.
672
+ - 🎨 **DALL-E Integration**: Introduced DALL-E integration for image generation alongside automatic1111.
673
+ - 🛠️ **RAG API Refactoring**: Refactored RAG logic and exposed its API, with additional documentation to follow.
674
+
675
+ ### Fixed
676
+
677
+ - 🔒 **Max Token Settings**: Added max token settings for anthropic/claude-3-sonnet-20240229 (Issue #1094).
678
+ - 🔧 **Misalignment Issue**: Corrected misalignment of Edit and Delete Icons when Chat Title is Empty (Issue #1104).
679
+ - 🔄 **Context Loss Fix**: Resolved RAG losing context on model response regeneration with Groq models via API key (Issue #1105).
680
+ - 📁 **File Handling Bug**: Addressed File Not Found Notification when Dropping a Conversation Element (Issue #1098).
681
+ - 🖱️ **Dragged File Styling**: Fixed dragged file layover styling issue.
682
+
683
+ ## [0.1.110] - 2024-03-06
684
+
685
+ ### Added
686
+
687
+ - **🌐 Multiple OpenAI Servers Support**: Enjoy seamless integration with multiple OpenAI-compatible APIs, now supported natively.
688
+
689
+ ### Fixed
690
+
691
+ - **🔍 OCR Issue**: Resolved PDF parsing issue caused by OCR malfunction.
692
+ - **🚫 RAG Issue**: Fixed the RAG functionality, ensuring it operates smoothly.
693
+ - **📄 "Add Docs" Model Button**: Addressed the non-functional behavior of the "Add Docs" model button.
694
+
695
+ ## [0.1.109] - 2024-03-06
696
+
697
+ ### Added
698
+
699
+ - **🔄 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).
700
+ - **🔧 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).
701
+ - **🔍 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).
702
+
703
+ ### Fixed
704
+
705
+ - **🛠️ RAG Collection**: Implemented a dynamic mechanism to recreate RAG collections, ensuring users have up-to-date and accurate data (#1031).
706
+ - **📝 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).
707
+ - **⏹️ Playground Cancel Functionality**: Introducing a new "Cancel" option for stopping Ollama generation in the Playground, enhancing user control and usability (#1006).
708
+ - **🔤 Typographical Error in 'ASSISTANT' Field**: Corrected a typographical error in the 'ASSISTANT' field within the GGUF model upload template for accuracy and consistency (#1061).
709
+
710
+ ### Changed
711
+
712
+ - **🔄 Refactored Message Deletion Logic**: Streamlined message deletion process for improved efficiency and user experience, simplifying interactions within the platform (#1004).
713
+ - **⚠️ 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.
714
+
715
+ ## [0.1.108] - 2024-03-02
716
+
717
+ ### Added
718
+
719
+ - **🎮 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.
720
+ - **🛠️ Direct Database Download for Admins**: Admins can now download the database directly from the WebUI via the admin settings.
721
+ - **🎨 Additional RAG Settings**: Customize your RAG process with the ability to edit the TOP K value. Navigate to Documents > Settings > General to make changes.
722
+ - **🖥️ UI Improvements**: Tooltips now available in the input area and sidebar handle. More tooltips will be added across other parts of the UI.
723
+
724
+ ### Fixed
725
+
726
+ - Resolved input autofocus issue on mobile when the sidebar is open, making it easier to use.
727
+ - Corrected numbered list display issue in Safari (#963).
728
+ - Restricted user ability to delete chats without proper permissions (#993).
729
+
730
+ ### Changed
731
+
732
+ - **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.
733
+ - **Database Renaming**: Starting from this release, `ollama.db` will be automatically renamed to `webui.db`.
734
+
735
+ ## [0.1.107] - 2024-03-01
736
+
737
+ ### Added
738
+
739
+ - **🚀 Makefile and LLM Update Script**: Included Makefile and a script for LLM updates in the repository.
740
+
741
+ ### Fixed
742
+
743
+ - Corrected issue where links in the settings modal didn't appear clickable (#960).
744
+ - Fixed problem with web UI port not taking effect due to incorrect environment variable name in run-compose.sh (#996).
745
+ - Enhanced user experience by displaying chat in browser title and enabling automatic scrolling to the bottom (#992).
746
+
747
+ ### Changed
748
+
749
+ - Upgraded toast library from `svelte-french-toast` to `svelte-sonner` for a more polished UI.
750
+ - Enhanced accessibility with the addition of dark mode on the authentication page.
751
+
752
+ ## [0.1.106] - 2024-02-27
753
+
754
+ ### Added
755
+
756
+ - **🎯 Auto-focus Feature**: The input area now automatically focuses when initiating or opening a chat conversation.
757
+
758
+ ### Fixed
759
+
760
+ - Corrected typo from "HuggingFace" to "Hugging Face" (Issue #924).
761
+ - Resolved bug causing errors in chat completion API calls to OpenAI due to missing "num_ctx" parameter (Issue #927).
762
+ - Fixed issues preventing text editing, selection, and cursor retention in the input field (Issue #940).
763
+ - 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)
764
+
765
+ ## [0.1.105] - 2024-02-25
766
+
767
+ ### Added
768
+
769
+ - **📄 Document Selection**: Now you can select and delete multiple documents at once for easier management.
770
+
771
+ ### Changed
772
+
773
+ - **🏷️ 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.
774
+
775
+ ## [0.1.104] - 2024-02-25
776
+
777
+ ### Added
778
+
779
+ - **🔄 Check for Updates**: Keep your system current by checking for updates conveniently located in Settings > About.
780
+ - **🗑️ Automatic Tag Deletion**: Unused tags on the sidebar will now be deleted automatically with just a click.
781
+
782
+ ### Changed
783
+
784
+ - **🎨 Modernized Styling**: Enjoy a refreshed look with updated styling for a more contemporary experience.
785
+
786
+ ## [0.1.103] - 2024-02-25
787
+
788
+ ### Added
789
+
790
+ - **🔗 Built-in LiteLLM Proxy**: Now includes LiteLLM proxy within Open WebUI for enhanced functionality.
791
+
792
+ - Easily integrate existing LiteLLM configurations using `-v /path/to/config.yaml:/app/backend/data/litellm/config.yaml` flag.
793
+ - When utilizing Docker container to run Open WebUI, ensure connections to localhost use `host.docker.internal`.
794
+
795
+ - **🖼️ Image Generation Enhancements**: Introducing Advanced Settings with Image Preview Feature.
796
+ - Customize image generation by setting the number of steps; defaults to A1111 value.
797
+
798
+ ### Fixed
799
+
800
+ - Resolved issue with RAG scan halting document loading upon encountering unsupported MIME types or exceptions (Issue #866).
801
+
802
+ ### Changed
803
+
804
+ - Ollama is no longer required to run Open WebUI.
805
+ - Access our comprehensive documentation at [Open WebUI Documentation](https://docs.openwebui.com/).
806
+
807
+ ## [0.1.102] - 2024-02-22
808
+
809
+ ### Added
810
+
811
+ - **🖼️ Image Generation**: Generate Images using the AUTOMATIC1111/stable-diffusion-webui API. You can set this up in Settings > Images.
812
+ - **📝 Change title generation prompt**: Change the prompt used to generate titles for your chats. You can set this up in the Settings > Interface.
813
+ - **🤖 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.
814
+ - **📢 CHANGELOG.md/Popup**: This popup will show you the latest changes.
815
+
816
+ ## [0.1.101] - 2024-02-22
817
+
818
+ ### Fixed
819
+
820
+ - LaTex output formatting issue (#828)
821
+
822
+ ### Changed
823
+
824
+ - 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 [email protected]. 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,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # syntax=docker/dockerfile:1
2
+ # Initialize device type args
3
+ # use build args in the docker build commmand 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
+ ARG BUILD_HASH=dev-build
15
+ # Override at your own risk - non-root configurations are untested
16
+ ARG UID=0
17
+ ARG GID=0
18
+
19
+ ######## WebUI frontend ########
20
+ FROM --platform=$BUILDPLATFORM node:21-alpine3.19 as build
21
+ ARG BUILD_HASH
22
+
23
+ WORKDIR /app
24
+
25
+ COPY package.json package-lock.json ./
26
+ RUN npm ci
27
+
28
+ COPY . .
29
+ ENV APP_BUILD_HASH=${BUILD_HASH}
30
+ RUN npm run build
31
+
32
+ ######## WebUI backend ########
33
+ FROM python:3.11-slim-bookworm as base
34
+
35
+ # Use args
36
+ ARG USE_CUDA
37
+ ARG USE_OLLAMA
38
+ ARG USE_CUDA_VER
39
+ ARG USE_EMBEDDING_MODEL
40
+ ARG USE_RERANKING_MODEL
41
+ ARG UID
42
+ ARG GID
43
+
44
+ ## Basis ##
45
+ ENV ENV=prod \
46
+ PORT=8080 \
47
+ # pass build args to the build
48
+ USE_OLLAMA_DOCKER=${USE_OLLAMA} \
49
+ USE_CUDA_DOCKER=${USE_CUDA} \
50
+ USE_CUDA_DOCKER_VER=${USE_CUDA_VER} \
51
+ USE_EMBEDDING_MODEL_DOCKER=${USE_EMBEDDING_MODEL} \
52
+ USE_RERANKING_MODEL_DOCKER=${USE_RERANKING_MODEL}
53
+
54
+ ## Basis URL Config ##
55
+ ENV OLLAMA_BASE_URL="/ollama" \
56
+ OPENAI_API_BASE_URL=""
57
+
58
+ ## API Key and Security Config ##
59
+ ENV OPENAI_API_KEY="" \
60
+ WEBUI_SECRET_KEY="" \
61
+ SCARF_NO_ANALYTICS=true \
62
+ DO_NOT_TRACK=true \
63
+ ANONYMIZED_TELEMETRY=false
64
+
65
+ #### Other models #########################################################
66
+ ## whisper TTS model settings ##
67
+ ENV WHISPER_MODEL="base" \
68
+ WHISPER_MODEL_DIR="/app/backend/data/cache/whisper/models"
69
+
70
+ ## RAG Embedding model settings ##
71
+ ENV RAG_EMBEDDING_MODEL="$USE_EMBEDDING_MODEL_DOCKER" \
72
+ RAG_RERANKING_MODEL="$USE_RERANKING_MODEL_DOCKER" \
73
+ SENTENCE_TRANSFORMERS_HOME="/app/backend/data/cache/embedding/models"
74
+
75
+ ## Hugging Face download cache ##
76
+ ENV HF_HOME="/app/backend/data/cache/embedding/models"
77
+ #### Other models ##########################################################
78
+
79
+ WORKDIR /app/backend
80
+
81
+ ENV HOME /root
82
+ # Create user and group if not root
83
+ RUN if [ $UID -ne 0 ]; then \
84
+ if [ $GID -ne 0 ]; then \
85
+ addgroup --gid $GID app; \
86
+ fi; \
87
+ adduser --uid $UID --gid $GID --home $HOME --disabled-password --no-create-home app; \
88
+ fi
89
+
90
+ RUN mkdir -p $HOME/.cache/chroma
91
+ RUN echo -n 00000000-0000-0000-0000-000000000000 > $HOME/.cache/chroma/telemetry_user_id
92
+
93
+ # Make sure the user has access to the app and root directory
94
+ RUN chown -R $UID:$GID /app $HOME
95
+
96
+ RUN if [ "$USE_OLLAMA" = "true" ]; then \
97
+ apt-get update && \
98
+ # Install pandoc and netcat
99
+ apt-get install -y --no-install-recommends pandoc netcat-openbsd curl && \
100
+ apt-get install -y --no-install-recommends gcc python3-dev && \
101
+ # for RAG OCR
102
+ apt-get install -y --no-install-recommends ffmpeg libsm6 libxext6 && \
103
+ # install helper tools
104
+ apt-get install -y --no-install-recommends curl jq && \
105
+ # install ollama
106
+ curl -fsSL https://ollama.com/install.sh | sh && \
107
+ # cleanup
108
+ rm -rf /var/lib/apt/lists/*; \
109
+ else \
110
+ apt-get update && \
111
+ # Install pandoc, netcat and gcc
112
+ apt-get install -y --no-install-recommends pandoc gcc netcat-openbsd curl jq && \
113
+ apt-get install -y --no-install-recommends gcc python3-dev && \
114
+ # for RAG OCR
115
+ apt-get install -y --no-install-recommends ffmpeg libsm6 libxext6 && \
116
+ # cleanup
117
+ rm -rf /var/lib/apt/lists/*; \
118
+ fi
119
+
120
+ # install python dependencies
121
+ COPY --chown=$UID:$GID ./backend/requirements.txt ./requirements.txt
122
+
123
+ RUN pip3 install uv && \
124
+ if [ "$USE_CUDA" = "true" ]; then \
125
+ # If you use CUDA the whisper and embedding model will be downloaded on first use
126
+ pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/$USE_CUDA_DOCKER_VER --no-cache-dir && \
127
+ uv pip install --system -r requirements.txt --no-cache-dir && \
128
+ python -c "import os; from sentence_transformers import SentenceTransformer; SentenceTransformer(os.environ['RAG_EMBEDDING_MODEL'], device='cpu')" && \
129
+ 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'])"; \
130
+ else \
131
+ pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu --no-cache-dir && \
132
+ uv pip install --system -r requirements.txt --no-cache-dir && \
133
+ python -c "import os; from sentence_transformers import SentenceTransformer; SentenceTransformer(os.environ['RAG_EMBEDDING_MODEL'], device='cpu')" && \
134
+ 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'])"; \
135
+ fi; \
136
+ chown -R $UID:$GID /app/backend/data/
137
+
138
+
139
+
140
+ # copy embedding weight from build
141
+ # RUN mkdir -p /root/.cache/chroma/onnx_models/all-MiniLM-L6-v2
142
+ # COPY --from=build /app/onnx /root/.cache/chroma/onnx_models/all-MiniLM-L6-v2/onnx
143
+
144
+ # copy built frontend files
145
+ COPY --chown=$UID:$GID --from=build /app/build /app/build
146
+ COPY --chown=$UID:$GID --from=build /app/CHANGELOG.md /app/CHANGELOG.md
147
+ COPY --chown=$UID:$GID --from=build /app/package.json /app/package.json
148
+
149
+ # copy backend files
150
+ COPY --chown=$UID:$GID ./backend .
151
+
152
+ EXPOSE 8080
153
+
154
+ HEALTHCHECK CMD curl --silent --fail http://localhost:${PORT:-8080}/health | jq -ne 'input.status == true' || exit 1
155
+
156
+ USER $UID:$GID
157
+
158
+ ARG BUILD_HASH
159
+ ENV WEBUI_BUILD_VERSION=${BUILD_HASH}
160
+
161
+ 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,211 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: Open WebUI
3
+ emoji: 🐳
4
+ colorFrom: purple
5
+ colorTo: gray
6
+ sdk: docker
7
+ app_port: 8080
8
+ ---
9
+ # Open WebUI (Formerly Ollama 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` and `TavilySearch` 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
+ > [!NOTE]
71
+ > 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.
72
+
73
+ ### Quick Start with Docker 🐳
74
+
75
+ > [!WARNING]
76
+ > 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.
77
+
78
+ > [!TIP]
79
+ > 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.
80
+
81
+ ### Installation with Default Configuration
82
+
83
+ - **If Ollama is on your computer**, use this command:
84
+
85
+ ```bash
86
+ 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
87
+ ```
88
+
89
+ - **If Ollama is on a Different Server**, use this command:
90
+
91
+ To connect to Ollama on another server, change the `OLLAMA_BASE_URL` to the server's URL:
92
+
93
+ ```bash
94
+ 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
95
+ ```
96
+
97
+ - **To run Open WebUI with Nvidia GPU support**, use this command:
98
+
99
+ ```bash
100
+ 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
101
+ ```
102
+
103
+ ### Installation for OpenAI API Usage Only
104
+
105
+ - **If you're only using OpenAI API**, use this command:
106
+
107
+ ```bash
108
+ 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
109
+ ```
110
+
111
+ ### Installing Open WebUI with Bundled Ollama Support
112
+
113
+ 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:
114
+
115
+ - **With GPU Support**:
116
+ Utilize GPU resources by running the following command:
117
+
118
+ ```bash
119
+ 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
120
+ ```
121
+
122
+ - **For CPU Only**:
123
+ If you're not using a GPU, use this command instead:
124
+
125
+ ```bash
126
+ 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
127
+ ```
128
+
129
+ 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.
130
+
131
+ After installation, you can access Open WebUI at [http://localhost:3000](http://localhost:3000). Enjoy! 😄
132
+
133
+ ### Other Installation Methods
134
+
135
+ 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.
136
+
137
+ ### Troubleshooting
138
+
139
+ 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).
140
+
141
+ #### Open WebUI: Server Connection Error
142
+
143
+ 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`.
144
+
145
+ **Example Docker Command**:
146
+
147
+ ```bash
148
+ 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
149
+ ```
150
+
151
+ ### Keeping Your Docker Installation Up-to-Date
152
+
153
+ In case you want to update your local Docker installation to the latest version, you can do it with [Watchtower](https://containrrr.dev/watchtower/):
154
+
155
+ ```bash
156
+ docker run --rm --volume /var/run/docker.sock:/var/run/docker.sock containrrr/watchtower --run-once open-webui
157
+ ```
158
+
159
+ In the last part of the command, replace `open-webui` with your container name if it is different.
160
+
161
+ Check our Migration Guide available in our [Open WebUI Documentation](https://docs.openwebui.com/migration/).
162
+
163
+ ### Using the Dev Branch 🌙
164
+
165
+ > [!WARNING]
166
+ > The `:dev` branch contains the latest unstable features and changes. Use it at your own risk as it may have bugs or incomplete features.
167
+
168
+ 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:
169
+
170
+ ```bash
171
+ 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
172
+ ```
173
+
174
+ ## What's Next? 🌟
175
+
176
+ Discover upcoming features on our roadmap in the [Open WebUI Documentation](https://docs.openwebui.com/roadmap/).
177
+
178
+ ## Supporters ✨
179
+
180
+ A big shoutout to our amazing supporters who's helping to make this project possible! 🙏
181
+
182
+ ### Platinum Sponsors 🤍
183
+
184
+ - We're looking for Sponsors!
185
+
186
+ ### Acknowledgments
187
+
188
+ Special thanks to [Prof. Lawrence Kim](https://www.lhkim.com/) and [Prof. Nick Vincent](https://www.nickmvincent.com/) for their invaluable support and guidance in shaping this project into a research endeavor. Grateful for your mentorship throughout the journey! 🙌
189
+
190
+ ## License 📜
191
+
192
+ This project is licensed under the [MIT License](LICENSE) - see the [LICENSE](LICENSE) file for details. 📄
193
+
194
+ ## Support 💬
195
+
196
+ If you have any questions, suggestions, or need assistance, please open an issue or join our
197
+ [Open WebUI Discord community](https://discord.gg/5rJgQTnV4s) to connect with us! 🤝
198
+
199
+ ## Star History
200
+
201
+ <a href="https://star-history.com/#open-webui/open-webui&Date">
202
+ <picture>
203
+ <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date&theme=dark" />
204
+ <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
205
+ <img alt="Star History Chart" src="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
206
+ </picture>
207
+ </a>
208
+
209
+ ---
210
+
211
+ Created by [Timothy J. 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 Reponses 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,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __pycache__
2
+ .env
3
+ _old
4
+ uploads
5
+ .ipynb_checkpoints
6
+ *.db
7
+ _test
8
+ Pipfile
9
+ !/data
10
+ /data/*
11
+ !/data/litellm
12
+ /data/litellm/*
13
+ !data/litellm/config.yaml
14
+
15
+ !data/config.json
16
+ .webui_secret_key
backend/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/apps/audio/main.py ADDED
@@ -0,0 +1,524 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+
9
+ import requests
10
+ from fastapi import (
11
+ FastAPI,
12
+ Request,
13
+ Depends,
14
+ HTTPException,
15
+ status,
16
+ UploadFile,
17
+ File,
18
+ )
19
+ from fastapi.middleware.cors import CORSMiddleware
20
+ from fastapi.responses import FileResponse
21
+ from pydantic import BaseModel
22
+
23
+ from config import (
24
+ SRC_LOG_LEVELS,
25
+ CACHE_DIR,
26
+ WHISPER_MODEL,
27
+ WHISPER_MODEL_DIR,
28
+ WHISPER_MODEL_AUTO_UPDATE,
29
+ DEVICE_TYPE,
30
+ AUDIO_STT_OPENAI_API_BASE_URL,
31
+ AUDIO_STT_OPENAI_API_KEY,
32
+ AUDIO_TTS_OPENAI_API_BASE_URL,
33
+ AUDIO_TTS_OPENAI_API_KEY,
34
+ AUDIO_TTS_API_KEY,
35
+ AUDIO_STT_ENGINE,
36
+ AUDIO_STT_MODEL,
37
+ AUDIO_TTS_ENGINE,
38
+ AUDIO_TTS_MODEL,
39
+ AUDIO_TTS_VOICE,
40
+ AppConfig,
41
+ CORS_ALLOW_ORIGIN,
42
+ )
43
+ from constants import ERROR_MESSAGES
44
+ from utils.utils import (
45
+ get_current_user,
46
+ get_verified_user,
47
+ get_admin_user,
48
+ )
49
+
50
+ log = logging.getLogger(__name__)
51
+ log.setLevel(SRC_LOG_LEVELS["AUDIO"])
52
+
53
+ app = FastAPI()
54
+ app.add_middleware(
55
+ CORSMiddleware,
56
+ allow_origins=CORS_ALLOW_ORIGIN,
57
+ allow_credentials=True,
58
+ allow_methods=["*"],
59
+ allow_headers=["*"],
60
+ )
61
+
62
+ app.state.config = AppConfig()
63
+
64
+ app.state.config.STT_OPENAI_API_BASE_URL = AUDIO_STT_OPENAI_API_BASE_URL
65
+ app.state.config.STT_OPENAI_API_KEY = AUDIO_STT_OPENAI_API_KEY
66
+ app.state.config.STT_ENGINE = AUDIO_STT_ENGINE
67
+ app.state.config.STT_MODEL = AUDIO_STT_MODEL
68
+
69
+ app.state.config.TTS_OPENAI_API_BASE_URL = AUDIO_TTS_OPENAI_API_BASE_URL
70
+ app.state.config.TTS_OPENAI_API_KEY = AUDIO_TTS_OPENAI_API_KEY
71
+ app.state.config.TTS_ENGINE = AUDIO_TTS_ENGINE
72
+ app.state.config.TTS_MODEL = AUDIO_TTS_MODEL
73
+ app.state.config.TTS_VOICE = AUDIO_TTS_VOICE
74
+ app.state.config.TTS_API_KEY = AUDIO_TTS_API_KEY
75
+
76
+ # setting device type for whisper model
77
+ whisper_device_type = DEVICE_TYPE if DEVICE_TYPE and DEVICE_TYPE == "cuda" else "cpu"
78
+ log.info(f"whisper_device_type: {whisper_device_type}")
79
+
80
+ SPEECH_CACHE_DIR = Path(CACHE_DIR).joinpath("./audio/speech/")
81
+ SPEECH_CACHE_DIR.mkdir(parents=True, exist_ok=True)
82
+
83
+
84
+ class TTSConfigForm(BaseModel):
85
+ OPENAI_API_BASE_URL: str
86
+ OPENAI_API_KEY: str
87
+ API_KEY: str
88
+ ENGINE: str
89
+ MODEL: str
90
+ VOICE: str
91
+
92
+
93
+ class STTConfigForm(BaseModel):
94
+ OPENAI_API_BASE_URL: str
95
+ OPENAI_API_KEY: str
96
+ ENGINE: str
97
+ MODEL: str
98
+
99
+
100
+ class AudioConfigUpdateForm(BaseModel):
101
+ tts: TTSConfigForm
102
+ stt: STTConfigForm
103
+
104
+
105
+ from pydub import AudioSegment
106
+ from pydub.utils import mediainfo
107
+
108
+
109
+ def is_mp4_audio(file_path):
110
+ """Check if the given file is an MP4 audio file."""
111
+ if not os.path.isfile(file_path):
112
+ print(f"File not found: {file_path}")
113
+ return False
114
+
115
+ info = mediainfo(file_path)
116
+ if (
117
+ info.get("codec_name") == "aac"
118
+ and info.get("codec_type") == "audio"
119
+ and info.get("codec_tag_string") == "mp4a"
120
+ ):
121
+ return True
122
+ return False
123
+
124
+
125
+ def convert_mp4_to_wav(file_path, output_path):
126
+ """Convert MP4 audio file to WAV format."""
127
+ audio = AudioSegment.from_file(file_path, format="mp4")
128
+ audio.export(output_path, format="wav")
129
+ print(f"Converted {file_path} to {output_path}")
130
+
131
+
132
+ @app.get("/config")
133
+ async def get_audio_config(user=Depends(get_admin_user)):
134
+ return {
135
+ "tts": {
136
+ "OPENAI_API_BASE_URL": app.state.config.TTS_OPENAI_API_BASE_URL,
137
+ "OPENAI_API_KEY": app.state.config.TTS_OPENAI_API_KEY,
138
+ "API_KEY": app.state.config.TTS_API_KEY,
139
+ "ENGINE": app.state.config.TTS_ENGINE,
140
+ "MODEL": app.state.config.TTS_MODEL,
141
+ "VOICE": app.state.config.TTS_VOICE,
142
+ },
143
+ "stt": {
144
+ "OPENAI_API_BASE_URL": app.state.config.STT_OPENAI_API_BASE_URL,
145
+ "OPENAI_API_KEY": app.state.config.STT_OPENAI_API_KEY,
146
+ "ENGINE": app.state.config.STT_ENGINE,
147
+ "MODEL": app.state.config.STT_MODEL,
148
+ },
149
+ }
150
+
151
+
152
+ @app.post("/config/update")
153
+ async def update_audio_config(
154
+ form_data: AudioConfigUpdateForm, user=Depends(get_admin_user)
155
+ ):
156
+ app.state.config.TTS_OPENAI_API_BASE_URL = form_data.tts.OPENAI_API_BASE_URL
157
+ app.state.config.TTS_OPENAI_API_KEY = form_data.tts.OPENAI_API_KEY
158
+ app.state.config.TTS_API_KEY = form_data.tts.API_KEY
159
+ app.state.config.TTS_ENGINE = form_data.tts.ENGINE
160
+ app.state.config.TTS_MODEL = form_data.tts.MODEL
161
+ app.state.config.TTS_VOICE = form_data.tts.VOICE
162
+
163
+ app.state.config.STT_OPENAI_API_BASE_URL = form_data.stt.OPENAI_API_BASE_URL
164
+ app.state.config.STT_OPENAI_API_KEY = form_data.stt.OPENAI_API_KEY
165
+ app.state.config.STT_ENGINE = form_data.stt.ENGINE
166
+ app.state.config.STT_MODEL = form_data.stt.MODEL
167
+
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
+ },
177
+ "stt": {
178
+ "OPENAI_API_BASE_URL": app.state.config.STT_OPENAI_API_BASE_URL,
179
+ "OPENAI_API_KEY": app.state.config.STT_OPENAI_API_KEY,
180
+ "ENGINE": app.state.config.STT_ENGINE,
181
+ "MODEL": app.state.config.STT_MODEL,
182
+ },
183
+ }
184
+
185
+
186
+ @app.post("/speech")
187
+ async def speech(request: Request, user=Depends(get_verified_user)):
188
+ body = await request.body()
189
+ name = hashlib.sha256(body).hexdigest()
190
+
191
+ file_path = SPEECH_CACHE_DIR.joinpath(f"{name}.mp3")
192
+ file_body_path = SPEECH_CACHE_DIR.joinpath(f"{name}.json")
193
+
194
+ # Check if the file already exists in the cache
195
+ if file_path.is_file():
196
+ return FileResponse(file_path)
197
+
198
+ if app.state.config.TTS_ENGINE == "openai":
199
+ headers = {}
200
+ headers["Authorization"] = f"Bearer {app.state.config.TTS_OPENAI_API_KEY}"
201
+ headers["Content-Type"] = "application/json"
202
+
203
+ try:
204
+ body = body.decode("utf-8")
205
+ body = json.loads(body)
206
+ body["model"] = app.state.config.TTS_MODEL
207
+ body = json.dumps(body).encode("utf-8")
208
+ except Exception as e:
209
+ pass
210
+
211
+ r = None
212
+ try:
213
+ r = requests.post(
214
+ url=f"{app.state.config.TTS_OPENAI_API_BASE_URL}/audio/speech",
215
+ data=body,
216
+ headers=headers,
217
+ stream=True,
218
+ )
219
+
220
+ r.raise_for_status()
221
+
222
+ # Save the streaming content to a file
223
+ with open(file_path, "wb") as f:
224
+ for chunk in r.iter_content(chunk_size=8192):
225
+ f.write(chunk)
226
+
227
+ with open(file_body_path, "w") as f:
228
+ json.dump(json.loads(body.decode("utf-8")), f)
229
+
230
+ # Return the saved file
231
+ return FileResponse(file_path)
232
+
233
+ except Exception as e:
234
+ log.exception(e)
235
+ error_detail = "Open WebUI: Server Connection Error"
236
+ if r is not None:
237
+ try:
238
+ res = r.json()
239
+ if "error" in res:
240
+ error_detail = f"External: {res['error']['message']}"
241
+ except Exception:
242
+ error_detail = f"External: {e}"
243
+
244
+ raise HTTPException(
245
+ status_code=r.status_code if r != None else 500,
246
+ detail=error_detail,
247
+ )
248
+
249
+ elif app.state.config.TTS_ENGINE == "elevenlabs":
250
+ payload = None
251
+ try:
252
+ payload = json.loads(body.decode("utf-8"))
253
+ except Exception as e:
254
+ log.exception(e)
255
+ raise HTTPException(status_code=400, detail="Invalid JSON payload")
256
+
257
+ voice_id = payload.get("voice", "")
258
+
259
+ if voice_id not in get_available_voices():
260
+ raise HTTPException(
261
+ status_code=400,
262
+ detail="Invalid voice id",
263
+ )
264
+
265
+ url = f"https://api.elevenlabs.io/v1/text-to-speech/{voice_id}"
266
+
267
+ headers = {
268
+ "Accept": "audio/mpeg",
269
+ "Content-Type": "application/json",
270
+ "xi-api-key": app.state.config.TTS_API_KEY,
271
+ }
272
+
273
+ data = {
274
+ "text": payload["input"],
275
+ "model_id": app.state.config.TTS_MODEL,
276
+ "voice_settings": {"stability": 0.5, "similarity_boost": 0.5},
277
+ }
278
+
279
+ try:
280
+ r = requests.post(url, json=data, headers=headers)
281
+
282
+ r.raise_for_status()
283
+
284
+ # Save the streaming content to a file
285
+ with open(file_path, "wb") as f:
286
+ for chunk in r.iter_content(chunk_size=8192):
287
+ f.write(chunk)
288
+
289
+ with open(file_body_path, "w") as f:
290
+ json.dump(json.loads(body.decode("utf-8")), f)
291
+
292
+ # Return the saved file
293
+ return FileResponse(file_path)
294
+
295
+ except Exception as e:
296
+ log.exception(e)
297
+ error_detail = "Open WebUI: Server Connection Error"
298
+ if r is not None:
299
+ try:
300
+ res = r.json()
301
+ if "error" in res:
302
+ error_detail = f"External: {res['error']['message']}"
303
+ except Exception:
304
+ error_detail = f"External: {e}"
305
+
306
+ raise HTTPException(
307
+ status_code=r.status_code if r != None else 500,
308
+ detail=error_detail,
309
+ )
310
+
311
+
312
+ @app.post("/transcriptions")
313
+ def transcribe(
314
+ file: UploadFile = File(...),
315
+ user=Depends(get_current_user),
316
+ ):
317
+ log.info(f"file.content_type: {file.content_type}")
318
+
319
+ if file.content_type not in ["audio/mpeg", "audio/wav"]:
320
+ raise HTTPException(
321
+ status_code=status.HTTP_400_BAD_REQUEST,
322
+ detail=ERROR_MESSAGES.FILE_NOT_SUPPORTED,
323
+ )
324
+
325
+ try:
326
+ ext = file.filename.split(".")[-1]
327
+
328
+ id = uuid.uuid4()
329
+ filename = f"{id}.{ext}"
330
+
331
+ file_dir = f"{CACHE_DIR}/audio/transcriptions"
332
+ os.makedirs(file_dir, exist_ok=True)
333
+ file_path = f"{file_dir}/{filename}"
334
+
335
+ print(filename)
336
+
337
+ contents = file.file.read()
338
+ with open(file_path, "wb") as f:
339
+ f.write(contents)
340
+ f.close()
341
+
342
+ if app.state.config.STT_ENGINE == "":
343
+ from faster_whisper import WhisperModel
344
+
345
+ whisper_kwargs = {
346
+ "model_size_or_path": WHISPER_MODEL,
347
+ "device": whisper_device_type,
348
+ "compute_type": "int8",
349
+ "download_root": WHISPER_MODEL_DIR,
350
+ "local_files_only": not WHISPER_MODEL_AUTO_UPDATE,
351
+ }
352
+
353
+ log.debug(f"whisper_kwargs: {whisper_kwargs}")
354
+
355
+ try:
356
+ model = WhisperModel(**whisper_kwargs)
357
+ except Exception:
358
+ log.warning(
359
+ "WhisperModel initialization failed, attempting download with local_files_only=False"
360
+ )
361
+ whisper_kwargs["local_files_only"] = False
362
+ model = WhisperModel(**whisper_kwargs)
363
+
364
+ segments, info = model.transcribe(file_path, beam_size=5)
365
+ log.info(
366
+ "Detected language '%s' with probability %f"
367
+ % (info.language, info.language_probability)
368
+ )
369
+
370
+ transcript = "".join([segment.text for segment in list(segments)])
371
+
372
+ data = {"text": transcript.strip()}
373
+
374
+ # save the transcript to a json file
375
+ transcript_file = f"{file_dir}/{id}.json"
376
+ with open(transcript_file, "w") as f:
377
+ json.dump(data, f)
378
+
379
+ print(data)
380
+
381
+ return data
382
+
383
+ elif app.state.config.STT_ENGINE == "openai":
384
+ if is_mp4_audio(file_path):
385
+ print("is_mp4_audio")
386
+ os.rename(file_path, file_path.replace(".wav", ".mp4"))
387
+ # Convert MP4 audio file to WAV format
388
+ convert_mp4_to_wav(file_path.replace(".wav", ".mp4"), file_path)
389
+
390
+ headers = {"Authorization": f"Bearer {app.state.config.STT_OPENAI_API_KEY}"}
391
+
392
+ files = {"file": (filename, open(file_path, "rb"))}
393
+ data = {"model": app.state.config.STT_MODEL}
394
+
395
+ print(files, data)
396
+
397
+ r = None
398
+ try:
399
+ r = requests.post(
400
+ url=f"{app.state.config.STT_OPENAI_API_BASE_URL}/audio/transcriptions",
401
+ headers=headers,
402
+ files=files,
403
+ data=data,
404
+ )
405
+
406
+ r.raise_for_status()
407
+
408
+ data = r.json()
409
+
410
+ # save the transcript to a json file
411
+ transcript_file = f"{file_dir}/{id}.json"
412
+ with open(transcript_file, "w") as f:
413
+ json.dump(data, f)
414
+
415
+ print(data)
416
+ return data
417
+ except Exception as e:
418
+ log.exception(e)
419
+ error_detail = "Open WebUI: Server Connection Error"
420
+ if r is not None:
421
+ try:
422
+ res = r.json()
423
+ if "error" in res:
424
+ error_detail = f"External: {res['error']['message']}"
425
+ except Exception:
426
+ error_detail = f"External: {e}"
427
+
428
+ raise HTTPException(
429
+ status_code=r.status_code if r != None else 500,
430
+ detail=error_detail,
431
+ )
432
+
433
+ except Exception as e:
434
+ log.exception(e)
435
+
436
+ raise HTTPException(
437
+ status_code=status.HTTP_400_BAD_REQUEST,
438
+ detail=ERROR_MESSAGES.DEFAULT(e),
439
+ )
440
+
441
+
442
+ def get_available_models() -> list[dict]:
443
+ if app.state.config.TTS_ENGINE == "openai":
444
+ return [{"id": "tts-1"}, {"id": "tts-1-hd"}]
445
+ elif app.state.config.TTS_ENGINE == "elevenlabs":
446
+ headers = {
447
+ "xi-api-key": app.state.config.TTS_API_KEY,
448
+ "Content-Type": "application/json",
449
+ }
450
+
451
+ try:
452
+ response = requests.get(
453
+ "https://api.elevenlabs.io/v1/models", headers=headers
454
+ )
455
+ response.raise_for_status()
456
+ models = response.json()
457
+ return [
458
+ {"name": model["name"], "id": model["model_id"]} for model in models
459
+ ]
460
+ except requests.RequestException as e:
461
+ log.error(f"Error fetching voices: {str(e)}")
462
+ return []
463
+
464
+
465
+ @app.get("/models")
466
+ async def get_models(user=Depends(get_verified_user)):
467
+ return {"models": get_available_models()}
468
+
469
+
470
+ def get_available_voices() -> dict:
471
+ """Returns {voice_id: voice_name} dict"""
472
+ ret = {}
473
+ if app.state.config.TTS_ENGINE == "openai":
474
+ ret = {
475
+ "alloy": "alloy",
476
+ "echo": "echo",
477
+ "fable": "fable",
478
+ "onyx": "onyx",
479
+ "nova": "nova",
480
+ "shimmer": "shimmer",
481
+ }
482
+ elif app.state.config.TTS_ENGINE == "elevenlabs":
483
+ try:
484
+ ret = get_elevenlabs_voices()
485
+ except Exception as e:
486
+ # Avoided @lru_cache with exception
487
+ pass
488
+
489
+ return ret
490
+
491
+
492
+ @lru_cache
493
+ def get_elevenlabs_voices() -> dict:
494
+ """
495
+ Note, set the following in your .env file to use Elevenlabs:
496
+ AUDIO_TTS_ENGINE=elevenlabs
497
+ AUDIO_TTS_API_KEY=sk_... # Your Elevenlabs API key
498
+ AUDIO_TTS_VOICE=EXAVITQu4vr4xnSDxMaL # From https://api.elevenlabs.io/v1/voices
499
+ AUDIO_TTS_MODEL=eleven_multilingual_v2
500
+ """
501
+ headers = {
502
+ "xi-api-key": app.state.config.TTS_API_KEY,
503
+ "Content-Type": "application/json",
504
+ }
505
+ try:
506
+ # TODO: Add retries
507
+ response = requests.get("https://api.elevenlabs.io/v1/voices", headers=headers)
508
+ response.raise_for_status()
509
+ voices_data = response.json()
510
+
511
+ voices = {}
512
+ for voice in voices_data.get("voices", []):
513
+ voices[voice["voice_id"]] = voice["name"]
514
+ except requests.RequestException as e:
515
+ # Avoid @lru_cache with exception
516
+ log.error(f"Error fetching voices: {str(e)}")
517
+ raise RuntimeError(f"Error fetching voices: {str(e)}")
518
+
519
+ return voices
520
+
521
+
522
+ @app.get("/voices")
523
+ async def get_voices(user=Depends(get_verified_user)):
524
+ return {"voices": [{"id": k, "name": v} for k, v in get_available_voices().items()]}
backend/apps/images/main.py ADDED
@@ -0,0 +1,580 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import re
2
+ import requests
3
+ from fastapi import (
4
+ FastAPI,
5
+ Request,
6
+ Depends,
7
+ HTTPException,
8
+ )
9
+ from fastapi.middleware.cors import CORSMiddleware
10
+
11
+ from constants import ERROR_MESSAGES
12
+ from utils.utils import (
13
+ get_verified_user,
14
+ get_admin_user,
15
+ )
16
+
17
+ from apps.images.utils.comfyui import ImageGenerationPayload, comfyui_generate_image
18
+ from typing import Optional
19
+ from pydantic import BaseModel
20
+ from pathlib import Path
21
+ import mimetypes
22
+ import uuid
23
+ import base64
24
+ import json
25
+ import logging
26
+
27
+ from config import (
28
+ SRC_LOG_LEVELS,
29
+ CACHE_DIR,
30
+ IMAGE_GENERATION_ENGINE,
31
+ ENABLE_IMAGE_GENERATION,
32
+ AUTOMATIC1111_BASE_URL,
33
+ AUTOMATIC1111_API_AUTH,
34
+ COMFYUI_BASE_URL,
35
+ COMFYUI_CFG_SCALE,
36
+ COMFYUI_SAMPLER,
37
+ COMFYUI_SCHEDULER,
38
+ COMFYUI_SD3,
39
+ COMFYUI_FLUX,
40
+ COMFYUI_FLUX_WEIGHT_DTYPE,
41
+ COMFYUI_FLUX_FP8_CLIP,
42
+ IMAGES_OPENAI_API_BASE_URL,
43
+ IMAGES_OPENAI_API_KEY,
44
+ IMAGE_GENERATION_MODEL,
45
+ IMAGE_SIZE,
46
+ IMAGE_STEPS,
47
+ AppConfig,
48
+ CORS_ALLOW_ORIGIN,
49
+ )
50
+
51
+ log = logging.getLogger(__name__)
52
+ log.setLevel(SRC_LOG_LEVELS["IMAGES"])
53
+
54
+ IMAGE_CACHE_DIR = Path(CACHE_DIR).joinpath("./image/generations/")
55
+ IMAGE_CACHE_DIR.mkdir(parents=True, exist_ok=True)
56
+
57
+ app = FastAPI()
58
+ app.add_middleware(
59
+ CORSMiddleware,
60
+ allow_origins=CORS_ALLOW_ORIGIN,
61
+ allow_credentials=True,
62
+ allow_methods=["*"],
63
+ allow_headers=["*"],
64
+ )
65
+
66
+ app.state.config = AppConfig()
67
+
68
+ app.state.config.ENGINE = IMAGE_GENERATION_ENGINE
69
+ app.state.config.ENABLED = ENABLE_IMAGE_GENERATION
70
+
71
+ app.state.config.OPENAI_API_BASE_URL = IMAGES_OPENAI_API_BASE_URL
72
+ app.state.config.OPENAI_API_KEY = IMAGES_OPENAI_API_KEY
73
+
74
+ app.state.config.MODEL = IMAGE_GENERATION_MODEL
75
+
76
+ app.state.config.AUTOMATIC1111_BASE_URL = AUTOMATIC1111_BASE_URL
77
+ app.state.config.AUTOMATIC1111_API_AUTH = AUTOMATIC1111_API_AUTH
78
+ app.state.config.COMFYUI_BASE_URL = COMFYUI_BASE_URL
79
+
80
+ app.state.config.IMAGE_SIZE = IMAGE_SIZE
81
+ app.state.config.IMAGE_STEPS = IMAGE_STEPS
82
+ app.state.config.COMFYUI_CFG_SCALE = COMFYUI_CFG_SCALE
83
+ app.state.config.COMFYUI_SAMPLER = COMFYUI_SAMPLER
84
+ app.state.config.COMFYUI_SCHEDULER = COMFYUI_SCHEDULER
85
+ app.state.config.COMFYUI_SD3 = COMFYUI_SD3
86
+ app.state.config.COMFYUI_FLUX = COMFYUI_FLUX
87
+ app.state.config.COMFYUI_FLUX_WEIGHT_DTYPE = COMFYUI_FLUX_WEIGHT_DTYPE
88
+ app.state.config.COMFYUI_FLUX_FP8_CLIP = COMFYUI_FLUX_FP8_CLIP
89
+
90
+
91
+ def get_automatic1111_api_auth():
92
+ if app.state.config.AUTOMATIC1111_API_AUTH is None:
93
+ return ""
94
+ else:
95
+ auth1111_byte_string = app.state.config.AUTOMATIC1111_API_AUTH.encode("utf-8")
96
+ auth1111_base64_encoded_bytes = base64.b64encode(auth1111_byte_string)
97
+ auth1111_base64_encoded_string = auth1111_base64_encoded_bytes.decode("utf-8")
98
+ return f"Basic {auth1111_base64_encoded_string}"
99
+
100
+
101
+ @app.get("/config")
102
+ async def get_config(request: Request, user=Depends(get_admin_user)):
103
+ return {
104
+ "engine": app.state.config.ENGINE,
105
+ "enabled": app.state.config.ENABLED,
106
+ }
107
+
108
+
109
+ class ConfigUpdateForm(BaseModel):
110
+ engine: str
111
+ enabled: bool
112
+
113
+
114
+ @app.post("/config/update")
115
+ async def update_config(form_data: ConfigUpdateForm, user=Depends(get_admin_user)):
116
+ app.state.config.ENGINE = form_data.engine
117
+ app.state.config.ENABLED = form_data.enabled
118
+ return {
119
+ "engine": app.state.config.ENGINE,
120
+ "enabled": app.state.config.ENABLED,
121
+ }
122
+
123
+
124
+ class EngineUrlUpdateForm(BaseModel):
125
+ AUTOMATIC1111_BASE_URL: Optional[str] = None
126
+ AUTOMATIC1111_API_AUTH: Optional[str] = None
127
+ COMFYUI_BASE_URL: Optional[str] = None
128
+
129
+
130
+ @app.get("/url")
131
+ async def get_engine_url(user=Depends(get_admin_user)):
132
+ return {
133
+ "AUTOMATIC1111_BASE_URL": app.state.config.AUTOMATIC1111_BASE_URL,
134
+ "AUTOMATIC1111_API_AUTH": app.state.config.AUTOMATIC1111_API_AUTH,
135
+ "COMFYUI_BASE_URL": app.state.config.COMFYUI_BASE_URL,
136
+ }
137
+
138
+
139
+ @app.post("/url/update")
140
+ async def update_engine_url(
141
+ form_data: EngineUrlUpdateForm, user=Depends(get_admin_user)
142
+ ):
143
+ if form_data.AUTOMATIC1111_BASE_URL is None:
144
+ app.state.config.AUTOMATIC1111_BASE_URL = AUTOMATIC1111_BASE_URL
145
+ else:
146
+ url = form_data.AUTOMATIC1111_BASE_URL.strip("/")
147
+ try:
148
+ r = requests.head(url)
149
+ r.raise_for_status()
150
+ app.state.config.AUTOMATIC1111_BASE_URL = url
151
+ except Exception as e:
152
+ raise HTTPException(status_code=400, detail=ERROR_MESSAGES.INVALID_URL)
153
+
154
+ if form_data.COMFYUI_BASE_URL is None:
155
+ app.state.config.COMFYUI_BASE_URL = COMFYUI_BASE_URL
156
+ else:
157
+ url = form_data.COMFYUI_BASE_URL.strip("/")
158
+
159
+ try:
160
+ r = requests.head(url)
161
+ r.raise_for_status()
162
+ app.state.config.COMFYUI_BASE_URL = url
163
+ except Exception as e:
164
+ raise HTTPException(status_code=400, detail=ERROR_MESSAGES.INVALID_URL)
165
+
166
+ if form_data.AUTOMATIC1111_API_AUTH is None:
167
+ app.state.config.AUTOMATIC1111_API_AUTH = AUTOMATIC1111_API_AUTH
168
+ else:
169
+ app.state.config.AUTOMATIC1111_API_AUTH = form_data.AUTOMATIC1111_API_AUTH
170
+
171
+ return {
172
+ "AUTOMATIC1111_BASE_URL": app.state.config.AUTOMATIC1111_BASE_URL,
173
+ "AUTOMATIC1111_API_AUTH": app.state.config.AUTOMATIC1111_API_AUTH,
174
+ "COMFYUI_BASE_URL": app.state.config.COMFYUI_BASE_URL,
175
+ "status": True,
176
+ }
177
+
178
+
179
+ class OpenAIConfigUpdateForm(BaseModel):
180
+ url: str
181
+ key: str
182
+
183
+
184
+ @app.get("/openai/config")
185
+ async def get_openai_config(user=Depends(get_admin_user)):
186
+ return {
187
+ "OPENAI_API_BASE_URL": app.state.config.OPENAI_API_BASE_URL,
188
+ "OPENAI_API_KEY": app.state.config.OPENAI_API_KEY,
189
+ }
190
+
191
+
192
+ @app.post("/openai/config/update")
193
+ async def update_openai_config(
194
+ form_data: OpenAIConfigUpdateForm, user=Depends(get_admin_user)
195
+ ):
196
+ if form_data.key == "":
197
+ raise HTTPException(status_code=400, detail=ERROR_MESSAGES.API_KEY_NOT_FOUND)
198
+
199
+ app.state.config.OPENAI_API_BASE_URL = form_data.url
200
+ app.state.config.OPENAI_API_KEY = form_data.key
201
+
202
+ return {
203
+ "status": True,
204
+ "OPENAI_API_BASE_URL": app.state.config.OPENAI_API_BASE_URL,
205
+ "OPENAI_API_KEY": app.state.config.OPENAI_API_KEY,
206
+ }
207
+
208
+
209
+ class ImageSizeUpdateForm(BaseModel):
210
+ size: str
211
+
212
+
213
+ @app.get("/size")
214
+ async def get_image_size(user=Depends(get_admin_user)):
215
+ return {"IMAGE_SIZE": app.state.config.IMAGE_SIZE}
216
+
217
+
218
+ @app.post("/size/update")
219
+ async def update_image_size(
220
+ form_data: ImageSizeUpdateForm, user=Depends(get_admin_user)
221
+ ):
222
+ pattern = r"^\d+x\d+$" # Regular expression pattern
223
+ if re.match(pattern, form_data.size):
224
+ app.state.config.IMAGE_SIZE = form_data.size
225
+ return {
226
+ "IMAGE_SIZE": app.state.config.IMAGE_SIZE,
227
+ "status": True,
228
+ }
229
+ else:
230
+ raise HTTPException(
231
+ status_code=400,
232
+ detail=ERROR_MESSAGES.INCORRECT_FORMAT(" (e.g., 512x512)."),
233
+ )
234
+
235
+
236
+ class ImageStepsUpdateForm(BaseModel):
237
+ steps: int
238
+
239
+
240
+ @app.get("/steps")
241
+ async def get_image_size(user=Depends(get_admin_user)):
242
+ return {"IMAGE_STEPS": app.state.config.IMAGE_STEPS}
243
+
244
+
245
+ @app.post("/steps/update")
246
+ async def update_image_size(
247
+ form_data: ImageStepsUpdateForm, user=Depends(get_admin_user)
248
+ ):
249
+ if form_data.steps >= 0:
250
+ app.state.config.IMAGE_STEPS = form_data.steps
251
+ return {
252
+ "IMAGE_STEPS": app.state.config.IMAGE_STEPS,
253
+ "status": True,
254
+ }
255
+ else:
256
+ raise HTTPException(
257
+ status_code=400,
258
+ detail=ERROR_MESSAGES.INCORRECT_FORMAT(" (e.g., 50)."),
259
+ )
260
+
261
+
262
+ @app.get("/models")
263
+ def get_models(user=Depends(get_verified_user)):
264
+ try:
265
+ if app.state.config.ENGINE == "openai":
266
+ return [
267
+ {"id": "dall-e-2", "name": "DALL·E 2"},
268
+ {"id": "dall-e-3", "name": "DALL·E 3"},
269
+ ]
270
+ elif app.state.config.ENGINE == "comfyui":
271
+
272
+ r = requests.get(url=f"{app.state.config.COMFYUI_BASE_URL}/object_info")
273
+ info = r.json()
274
+
275
+ return list(
276
+ map(
277
+ lambda model: {"id": model, "name": model},
278
+ info["CheckpointLoaderSimple"]["input"]["required"]["ckpt_name"][0],
279
+ )
280
+ )
281
+
282
+ else:
283
+ r = requests.get(
284
+ url=f"{app.state.config.AUTOMATIC1111_BASE_URL}/sdapi/v1/sd-models",
285
+ headers={"authorization": get_automatic1111_api_auth()},
286
+ )
287
+ models = r.json()
288
+ return list(
289
+ map(
290
+ lambda model: {"id": model["title"], "name": model["model_name"]},
291
+ models,
292
+ )
293
+ )
294
+ except Exception as e:
295
+ app.state.config.ENABLED = False
296
+ raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(e))
297
+
298
+
299
+ @app.get("/models/default")
300
+ async def get_default_model(user=Depends(get_admin_user)):
301
+ try:
302
+ if app.state.config.ENGINE == "openai":
303
+ return {
304
+ "model": (
305
+ app.state.config.MODEL if app.state.config.MODEL else "dall-e-2"
306
+ )
307
+ }
308
+ elif app.state.config.ENGINE == "comfyui":
309
+ return {"model": (app.state.config.MODEL if app.state.config.MODEL else "")}
310
+ else:
311
+ r = requests.get(
312
+ url=f"{app.state.config.AUTOMATIC1111_BASE_URL}/sdapi/v1/options",
313
+ headers={"authorization": get_automatic1111_api_auth()},
314
+ )
315
+ options = r.json()
316
+ return {"model": options["sd_model_checkpoint"]}
317
+ except Exception as e:
318
+ app.state.config.ENABLED = False
319
+ raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(e))
320
+
321
+
322
+ class UpdateModelForm(BaseModel):
323
+ model: str
324
+
325
+
326
+ def set_model_handler(model: str):
327
+ if app.state.config.ENGINE in ["openai", "comfyui"]:
328
+ app.state.config.MODEL = model
329
+ return app.state.config.MODEL
330
+ else:
331
+ api_auth = get_automatic1111_api_auth()
332
+ r = requests.get(
333
+ url=f"{app.state.config.AUTOMATIC1111_BASE_URL}/sdapi/v1/options",
334
+ headers={"authorization": api_auth},
335
+ )
336
+ options = r.json()
337
+
338
+ if model != options["sd_model_checkpoint"]:
339
+ options["sd_model_checkpoint"] = model
340
+ r = requests.post(
341
+ url=f"{app.state.config.AUTOMATIC1111_BASE_URL}/sdapi/v1/options",
342
+ json=options,
343
+ headers={"authorization": api_auth},
344
+ )
345
+
346
+ return options
347
+
348
+
349
+ @app.post("/models/default/update")
350
+ def update_default_model(
351
+ form_data: UpdateModelForm,
352
+ user=Depends(get_verified_user),
353
+ ):
354
+ return set_model_handler(form_data.model)
355
+
356
+
357
+ class GenerateImageForm(BaseModel):
358
+ model: Optional[str] = None
359
+ prompt: str
360
+ n: int = 1
361
+ size: Optional[str] = None
362
+ negative_prompt: Optional[str] = None
363
+
364
+
365
+ def save_b64_image(b64_str):
366
+ try:
367
+ image_id = str(uuid.uuid4())
368
+
369
+ if "," in b64_str:
370
+ header, encoded = b64_str.split(",", 1)
371
+ mime_type = header.split(";")[0]
372
+
373
+ img_data = base64.b64decode(encoded)
374
+ image_format = mimetypes.guess_extension(mime_type)
375
+
376
+ image_filename = f"{image_id}{image_format}"
377
+ file_path = IMAGE_CACHE_DIR / f"{image_filename}"
378
+ with open(file_path, "wb") as f:
379
+ f.write(img_data)
380
+ return image_filename
381
+ else:
382
+ image_filename = f"{image_id}.png"
383
+ file_path = IMAGE_CACHE_DIR.joinpath(image_filename)
384
+
385
+ img_data = base64.b64decode(b64_str)
386
+
387
+ # Write the image data to a file
388
+ with open(file_path, "wb") as f:
389
+ f.write(img_data)
390
+ return image_filename
391
+
392
+ except Exception as e:
393
+ log.exception(f"Error saving image: {e}")
394
+ return None
395
+
396
+
397
+ def save_url_image(url):
398
+ image_id = str(uuid.uuid4())
399
+ try:
400
+ r = requests.get(url)
401
+ r.raise_for_status()
402
+ if r.headers["content-type"].split("/")[0] == "image":
403
+
404
+ mime_type = r.headers["content-type"]
405
+ image_format = mimetypes.guess_extension(mime_type)
406
+
407
+ if not image_format:
408
+ raise ValueError("Could not determine image type from MIME type")
409
+
410
+ image_filename = f"{image_id}{image_format}"
411
+
412
+ file_path = IMAGE_CACHE_DIR.joinpath(f"{image_filename}")
413
+ with open(file_path, "wb") as image_file:
414
+ for chunk in r.iter_content(chunk_size=8192):
415
+ image_file.write(chunk)
416
+ return image_filename
417
+ else:
418
+ log.error(f"Url does not point to an image.")
419
+ return None
420
+
421
+ except Exception as e:
422
+ log.exception(f"Error saving image: {e}")
423
+ return None
424
+
425
+
426
+ @app.post("/generations")
427
+ async def image_generations(
428
+ form_data: GenerateImageForm,
429
+ user=Depends(get_verified_user),
430
+ ):
431
+ width, height = tuple(map(int, app.state.config.IMAGE_SIZE.split("x")))
432
+
433
+ r = None
434
+ try:
435
+ if app.state.config.ENGINE == "openai":
436
+
437
+ headers = {}
438
+ headers["Authorization"] = f"Bearer {app.state.config.OPENAI_API_KEY}"
439
+ headers["Content-Type"] = "application/json"
440
+
441
+ data = {
442
+ "model": (
443
+ app.state.config.MODEL
444
+ if app.state.config.MODEL != ""
445
+ else "dall-e-2"
446
+ ),
447
+ "prompt": form_data.prompt,
448
+ "n": form_data.n,
449
+ "size": (
450
+ form_data.size if form_data.size else app.state.config.IMAGE_SIZE
451
+ ),
452
+ "response_format": "b64_json",
453
+ }
454
+
455
+ r = requests.post(
456
+ url=f"{app.state.config.OPENAI_API_BASE_URL}/images/generations",
457
+ json=data,
458
+ headers=headers,
459
+ )
460
+
461
+ r.raise_for_status()
462
+ res = r.json()
463
+
464
+ images = []
465
+
466
+ for image in res["data"]:
467
+ image_filename = save_b64_image(image["b64_json"])
468
+ images.append({"url": f"/cache/image/generations/{image_filename}"})
469
+ file_body_path = IMAGE_CACHE_DIR.joinpath(f"{image_filename}.json")
470
+
471
+ with open(file_body_path, "w") as f:
472
+ json.dump(data, f)
473
+
474
+ return images
475
+
476
+ elif app.state.config.ENGINE == "comfyui":
477
+
478
+ data = {
479
+ "prompt": form_data.prompt,
480
+ "width": width,
481
+ "height": height,
482
+ "n": form_data.n,
483
+ }
484
+
485
+ if app.state.config.IMAGE_STEPS is not None:
486
+ data["steps"] = app.state.config.IMAGE_STEPS
487
+
488
+ if form_data.negative_prompt is not None:
489
+ data["negative_prompt"] = form_data.negative_prompt
490
+
491
+ if app.state.config.COMFYUI_CFG_SCALE:
492
+ data["cfg_scale"] = app.state.config.COMFYUI_CFG_SCALE
493
+
494
+ if app.state.config.COMFYUI_SAMPLER is not None:
495
+ data["sampler"] = app.state.config.COMFYUI_SAMPLER
496
+
497
+ if app.state.config.COMFYUI_SCHEDULER is not None:
498
+ data["scheduler"] = app.state.config.COMFYUI_SCHEDULER
499
+
500
+ if app.state.config.COMFYUI_SD3 is not None:
501
+ data["sd3"] = app.state.config.COMFYUI_SD3
502
+
503
+ if app.state.config.COMFYUI_FLUX is not None:
504
+ data["flux"] = app.state.config.COMFYUI_FLUX
505
+
506
+ if app.state.config.COMFYUI_FLUX_WEIGHT_DTYPE is not None:
507
+ data["flux_weight_dtype"] = app.state.config.COMFYUI_FLUX_WEIGHT_DTYPE
508
+
509
+ if app.state.config.COMFYUI_FLUX_FP8_CLIP is not None:
510
+ data["flux_fp8_clip"] = app.state.config.COMFYUI_FLUX_FP8_CLIP
511
+
512
+ data = ImageGenerationPayload(**data)
513
+
514
+ res = await comfyui_generate_image(
515
+ app.state.config.MODEL,
516
+ data,
517
+ user.id,
518
+ app.state.config.COMFYUI_BASE_URL,
519
+ )
520
+ log.debug(f"res: {res}")
521
+
522
+ images = []
523
+
524
+ for image in res["data"]:
525
+ image_filename = save_url_image(image["url"])
526
+ images.append({"url": f"/cache/image/generations/{image_filename}"})
527
+ file_body_path = IMAGE_CACHE_DIR.joinpath(f"{image_filename}.json")
528
+
529
+ with open(file_body_path, "w") as f:
530
+ json.dump(data.model_dump(exclude_none=True), f)
531
+
532
+ log.debug(f"images: {images}")
533
+ return images
534
+ else:
535
+ if form_data.model:
536
+ set_model_handler(form_data.model)
537
+
538
+ data = {
539
+ "prompt": form_data.prompt,
540
+ "batch_size": form_data.n,
541
+ "width": width,
542
+ "height": height,
543
+ }
544
+
545
+ if app.state.config.IMAGE_STEPS is not None:
546
+ data["steps"] = app.state.config.IMAGE_STEPS
547
+
548
+ if form_data.negative_prompt is not None:
549
+ data["negative_prompt"] = form_data.negative_prompt
550
+
551
+ r = requests.post(
552
+ url=f"{app.state.config.AUTOMATIC1111_BASE_URL}/sdapi/v1/txt2img",
553
+ json=data,
554
+ headers={"authorization": get_automatic1111_api_auth()},
555
+ )
556
+
557
+ res = r.json()
558
+
559
+ log.debug(f"res: {res}")
560
+
561
+ images = []
562
+
563
+ for image in res["images"]:
564
+ image_filename = save_b64_image(image)
565
+ images.append({"url": f"/cache/image/generations/{image_filename}"})
566
+ file_body_path = IMAGE_CACHE_DIR.joinpath(f"{image_filename}.json")
567
+
568
+ with open(file_body_path, "w") as f:
569
+ json.dump({**data, "info": res["info"]}, f)
570
+
571
+ return images
572
+
573
+ except Exception as e:
574
+ error = e
575
+
576
+ if r != None:
577
+ data = r.json()
578
+ if "error" in data:
579
+ error = data["error"]["message"]
580
+ raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(error))
backend/apps/images/utils/comfyui.py ADDED
@@ -0,0 +1,409 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import asyncio
2
+ import websocket # NOTE: websocket-client (https://github.com/websocket-client/websocket-client)
3
+ import json
4
+ import urllib.request
5
+ import urllib.parse
6
+ import random
7
+ import logging
8
+
9
+ from config import SRC_LOG_LEVELS
10
+
11
+ log = logging.getLogger(__name__)
12
+ log.setLevel(SRC_LOG_LEVELS["COMFYUI"])
13
+
14
+ from pydantic import BaseModel
15
+
16
+ from typing import Optional
17
+
18
+ COMFYUI_DEFAULT_PROMPT = """
19
+ {
20
+ "3": {
21
+ "inputs": {
22
+ "seed": 0,
23
+ "steps": 20,
24
+ "cfg": 8,
25
+ "sampler_name": "euler",
26
+ "scheduler": "normal",
27
+ "denoise": 1,
28
+ "model": [
29
+ "4",
30
+ 0
31
+ ],
32
+ "positive": [
33
+ "6",
34
+ 0
35
+ ],
36
+ "negative": [
37
+ "7",
38
+ 0
39
+ ],
40
+ "latent_image": [
41
+ "5",
42
+ 0
43
+ ]
44
+ },
45
+ "class_type": "KSampler",
46
+ "_meta": {
47
+ "title": "KSampler"
48
+ }
49
+ },
50
+ "4": {
51
+ "inputs": {
52
+ "ckpt_name": "model.safetensors"
53
+ },
54
+ "class_type": "CheckpointLoaderSimple",
55
+ "_meta": {
56
+ "title": "Load Checkpoint"
57
+ }
58
+ },
59
+ "5": {
60
+ "inputs": {
61
+ "width": 512,
62
+ "height": 512,
63
+ "batch_size": 1
64
+ },
65
+ "class_type": "EmptyLatentImage",
66
+ "_meta": {
67
+ "title": "Empty Latent Image"
68
+ }
69
+ },
70
+ "6": {
71
+ "inputs": {
72
+ "text": "Prompt",
73
+ "clip": [
74
+ "4",
75
+ 1
76
+ ]
77
+ },
78
+ "class_type": "CLIPTextEncode",
79
+ "_meta": {
80
+ "title": "CLIP Text Encode (Prompt)"
81
+ }
82
+ },
83
+ "7": {
84
+ "inputs": {
85
+ "text": "Negative Prompt",
86
+ "clip": [
87
+ "4",
88
+ 1
89
+ ]
90
+ },
91
+ "class_type": "CLIPTextEncode",
92
+ "_meta": {
93
+ "title": "CLIP Text Encode (Prompt)"
94
+ }
95
+ },
96
+ "8": {
97
+ "inputs": {
98
+ "samples": [
99
+ "3",
100
+ 0
101
+ ],
102
+ "vae": [
103
+ "4",
104
+ 2
105
+ ]
106
+ },
107
+ "class_type": "VAEDecode",
108
+ "_meta": {
109
+ "title": "VAE Decode"
110
+ }
111
+ },
112
+ "9": {
113
+ "inputs": {
114
+ "filename_prefix": "ComfyUI",
115
+ "images": [
116
+ "8",
117
+ 0
118
+ ]
119
+ },
120
+ "class_type": "SaveImage",
121
+ "_meta": {
122
+ "title": "Save Image"
123
+ }
124
+ }
125
+ }
126
+ """
127
+
128
+ FLUX_DEFAULT_PROMPT = """
129
+ {
130
+ "5": {
131
+ "inputs": {
132
+ "width": 1024,
133
+ "height": 1024,
134
+ "batch_size": 1
135
+ },
136
+ "class_type": "EmptyLatentImage"
137
+ },
138
+ "6": {
139
+ "inputs": {
140
+ "text": "Input Text Here",
141
+ "clip": [
142
+ "11",
143
+ 0
144
+ ]
145
+ },
146
+ "class_type": "CLIPTextEncode"
147
+ },
148
+ "8": {
149
+ "inputs": {
150
+ "samples": [
151
+ "13",
152
+ 0
153
+ ],
154
+ "vae": [
155
+ "10",
156
+ 0
157
+ ]
158
+ },
159
+ "class_type": "VAEDecode"
160
+ },
161
+ "9": {
162
+ "inputs": {
163
+ "filename_prefix": "ComfyUI",
164
+ "images": [
165
+ "8",
166
+ 0
167
+ ]
168
+ },
169
+ "class_type": "SaveImage"
170
+ },
171
+ "10": {
172
+ "inputs": {
173
+ "vae_name": "ae.safetensors"
174
+ },
175
+ "class_type": "VAELoader"
176
+ },
177
+ "11": {
178
+ "inputs": {
179
+ "clip_name1": "clip_l.safetensors",
180
+ "clip_name2": "t5xxl_fp16.safetensors",
181
+ "type": "flux"
182
+ },
183
+ "class_type": "DualCLIPLoader"
184
+ },
185
+ "12": {
186
+ "inputs": {
187
+ "unet_name": "flux1-dev.safetensors",
188
+ "weight_dtype": "default"
189
+ },
190
+ "class_type": "UNETLoader"
191
+ },
192
+ "13": {
193
+ "inputs": {
194
+ "noise": [
195
+ "25",
196
+ 0
197
+ ],
198
+ "guider": [
199
+ "22",
200
+ 0
201
+ ],
202
+ "sampler": [
203
+ "16",
204
+ 0
205
+ ],
206
+ "sigmas": [
207
+ "17",
208
+ 0
209
+ ],
210
+ "latent_image": [
211
+ "5",
212
+ 0
213
+ ]
214
+ },
215
+ "class_type": "SamplerCustomAdvanced"
216
+ },
217
+ "16": {
218
+ "inputs": {
219
+ "sampler_name": "euler"
220
+ },
221
+ "class_type": "KSamplerSelect"
222
+ },
223
+ "17": {
224
+ "inputs": {
225
+ "scheduler": "simple",
226
+ "steps": 20,
227
+ "denoise": 1,
228
+ "model": [
229
+ "12",
230
+ 0
231
+ ]
232
+ },
233
+ "class_type": "BasicScheduler"
234
+ },
235
+ "22": {
236
+ "inputs": {
237
+ "model": [
238
+ "12",
239
+ 0
240
+ ],
241
+ "conditioning": [
242
+ "6",
243
+ 0
244
+ ]
245
+ },
246
+ "class_type": "BasicGuider"
247
+ },
248
+ "25": {
249
+ "inputs": {
250
+ "noise_seed": 778937779713005
251
+ },
252
+ "class_type": "RandomNoise"
253
+ }
254
+ }
255
+ """
256
+
257
+
258
+ def queue_prompt(prompt, client_id, base_url):
259
+ log.info("queue_prompt")
260
+ p = {"prompt": prompt, "client_id": client_id}
261
+ data = json.dumps(p).encode("utf-8")
262
+ req = urllib.request.Request(f"{base_url}/prompt", data=data)
263
+ return json.loads(urllib.request.urlopen(req).read())
264
+
265
+
266
+ def get_image(filename, subfolder, folder_type, base_url):
267
+ log.info("get_image")
268
+ data = {"filename": filename, "subfolder": subfolder, "type": folder_type}
269
+ url_values = urllib.parse.urlencode(data)
270
+ with urllib.request.urlopen(f"{base_url}/view?{url_values}") as response:
271
+ return response.read()
272
+
273
+
274
+ def get_image_url(filename, subfolder, folder_type, base_url):
275
+ log.info("get_image")
276
+ data = {"filename": filename, "subfolder": subfolder, "type": folder_type}
277
+ url_values = urllib.parse.urlencode(data)
278
+ return f"{base_url}/view?{url_values}"
279
+
280
+
281
+ def get_history(prompt_id, base_url):
282
+ log.info("get_history")
283
+ with urllib.request.urlopen(f"{base_url}/history/{prompt_id}") as response:
284
+ return json.loads(response.read())
285
+
286
+
287
+ def get_images(ws, prompt, client_id, base_url):
288
+ prompt_id = queue_prompt(prompt, client_id, base_url)["prompt_id"]
289
+ output_images = []
290
+ while True:
291
+ out = ws.recv()
292
+ if isinstance(out, str):
293
+ message = json.loads(out)
294
+ if message["type"] == "executing":
295
+ data = message["data"]
296
+ if data["node"] is None and data["prompt_id"] == prompt_id:
297
+ break # Execution is done
298
+ else:
299
+ continue # previews are binary data
300
+
301
+ history = get_history(prompt_id, base_url)[prompt_id]
302
+ for o in history["outputs"]:
303
+ for node_id in history["outputs"]:
304
+ node_output = history["outputs"][node_id]
305
+ if "images" in node_output:
306
+ for image in node_output["images"]:
307
+ url = get_image_url(
308
+ image["filename"], image["subfolder"], image["type"], base_url
309
+ )
310
+ output_images.append({"url": url})
311
+ return {"data": output_images}
312
+
313
+
314
+ class ImageGenerationPayload(BaseModel):
315
+ prompt: str
316
+ negative_prompt: Optional[str] = ""
317
+ steps: Optional[int] = None
318
+ seed: Optional[int] = None
319
+ width: int
320
+ height: int
321
+ n: int = 1
322
+ cfg_scale: Optional[float] = None
323
+ sampler: Optional[str] = None
324
+ scheduler: Optional[str] = None
325
+ sd3: Optional[bool] = None
326
+ flux: Optional[bool] = None
327
+ flux_weight_dtype: Optional[str] = None
328
+ flux_fp8_clip: Optional[bool] = None
329
+
330
+
331
+ async def comfyui_generate_image(
332
+ model: str, payload: ImageGenerationPayload, client_id, base_url
333
+ ):
334
+ ws_url = base_url.replace("http://", "ws://").replace("https://", "wss://")
335
+
336
+ comfyui_prompt = json.loads(COMFYUI_DEFAULT_PROMPT)
337
+
338
+ if payload.cfg_scale:
339
+ comfyui_prompt["3"]["inputs"]["cfg"] = payload.cfg_scale
340
+
341
+ if payload.sampler:
342
+ comfyui_prompt["3"]["inputs"]["sampler"] = payload.sampler
343
+
344
+ if payload.scheduler:
345
+ comfyui_prompt["3"]["inputs"]["scheduler"] = payload.scheduler
346
+
347
+ if payload.sd3:
348
+ comfyui_prompt["5"]["class_type"] = "EmptySD3LatentImage"
349
+
350
+ if payload.steps:
351
+ comfyui_prompt["3"]["inputs"]["steps"] = payload.steps
352
+
353
+ comfyui_prompt["4"]["inputs"]["ckpt_name"] = model
354
+ comfyui_prompt["7"]["inputs"]["text"] = payload.negative_prompt
355
+ comfyui_prompt["3"]["inputs"]["seed"] = (
356
+ payload.seed if payload.seed else random.randint(0, 18446744073709551614)
357
+ )
358
+
359
+ # as Flux uses a completely different workflow, we must treat it specially
360
+ if payload.flux:
361
+ comfyui_prompt = json.loads(FLUX_DEFAULT_PROMPT)
362
+ comfyui_prompt["12"]["inputs"]["unet_name"] = model
363
+ comfyui_prompt["25"]["inputs"]["noise_seed"] = (
364
+ payload.seed if payload.seed else random.randint(0, 18446744073709551614)
365
+ )
366
+
367
+ if payload.sampler:
368
+ comfyui_prompt["16"]["inputs"]["sampler_name"] = payload.sampler
369
+
370
+ if payload.steps:
371
+ comfyui_prompt["17"]["inputs"]["steps"] = payload.steps
372
+
373
+ if payload.scheduler:
374
+ comfyui_prompt["17"]["inputs"]["scheduler"] = payload.scheduler
375
+
376
+ if payload.flux_weight_dtype:
377
+ comfyui_prompt["12"]["inputs"]["weight_dtype"] = payload.flux_weight_dtype
378
+
379
+ if payload.flux_fp8_clip:
380
+ comfyui_prompt["11"]["inputs"][
381
+ "clip_name2"
382
+ ] = "t5xxl_fp8_e4m3fn.safetensors"
383
+
384
+ comfyui_prompt["5"]["inputs"]["batch_size"] = payload.n
385
+ comfyui_prompt["5"]["inputs"]["width"] = payload.width
386
+ comfyui_prompt["5"]["inputs"]["height"] = payload.height
387
+
388
+ # set the text prompt for our positive CLIPTextEncode
389
+ comfyui_prompt["6"]["inputs"]["text"] = payload.prompt
390
+
391
+ try:
392
+ ws = websocket.WebSocket()
393
+ ws.connect(f"{ws_url}/ws?clientId={client_id}")
394
+ log.info("WebSocket connection established.")
395
+ except Exception as e:
396
+ log.exception(f"Failed to connect to WebSocket server: {e}")
397
+ return None
398
+
399
+ try:
400
+ images = await asyncio.to_thread(
401
+ get_images, ws, comfyui_prompt, client_id, base_url
402
+ )
403
+ except Exception as e:
404
+ log.exception(f"Error while receiving images: {e}")
405
+ images = None
406
+
407
+ ws.close()
408
+
409
+ return images
backend/apps/ollama/main.py ADDED
@@ -0,0 +1,1071 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import (
2
+ FastAPI,
3
+ Request,
4
+ HTTPException,
5
+ Depends,
6
+ UploadFile,
7
+ File,
8
+ )
9
+ from fastapi.middleware.cors import CORSMiddleware
10
+ from fastapi.responses import StreamingResponse
11
+
12
+ from pydantic import BaseModel, ConfigDict
13
+
14
+ import os
15
+ import re
16
+ import random
17
+ import requests
18
+ import json
19
+ import aiohttp
20
+ import asyncio
21
+ import logging
22
+ import time
23
+ from urllib.parse import urlparse
24
+ from typing import Optional, Union
25
+
26
+ from starlette.background import BackgroundTask
27
+
28
+ from apps.webui.models.models import Models
29
+ from constants import ERROR_MESSAGES
30
+ from utils.utils import (
31
+ get_verified_user,
32
+ get_admin_user,
33
+ )
34
+
35
+ from config import (
36
+ SRC_LOG_LEVELS,
37
+ OLLAMA_BASE_URLS,
38
+ ENABLE_OLLAMA_API,
39
+ AIOHTTP_CLIENT_TIMEOUT,
40
+ ENABLE_MODEL_FILTER,
41
+ MODEL_FILTER_LIST,
42
+ UPLOAD_DIR,
43
+ AppConfig,
44
+ CORS_ALLOW_ORIGIN,
45
+ )
46
+ from utils.misc import (
47
+ calculate_sha256,
48
+ apply_model_params_to_body_ollama,
49
+ apply_model_params_to_body_openai,
50
+ apply_model_system_prompt_to_body,
51
+ )
52
+
53
+ log = logging.getLogger(__name__)
54
+ log.setLevel(SRC_LOG_LEVELS["OLLAMA"])
55
+
56
+ app = FastAPI()
57
+ app.add_middleware(
58
+ CORSMiddleware,
59
+ allow_origins=CORS_ALLOW_ORIGIN,
60
+ allow_credentials=True,
61
+ allow_methods=["*"],
62
+ allow_headers=["*"],
63
+ )
64
+
65
+ app.state.config = AppConfig()
66
+
67
+ app.state.config.ENABLE_MODEL_FILTER = ENABLE_MODEL_FILTER
68
+ app.state.config.MODEL_FILTER_LIST = MODEL_FILTER_LIST
69
+
70
+ app.state.config.ENABLE_OLLAMA_API = ENABLE_OLLAMA_API
71
+ app.state.config.OLLAMA_BASE_URLS = OLLAMA_BASE_URLS
72
+ app.state.MODELS = {}
73
+
74
+
75
+ # TODO: Implement a more intelligent load balancing mechanism for distributing requests among multiple backend instances.
76
+ # Current implementation uses a simple round-robin approach (random.choice). Consider incorporating algorithms like weighted round-robin,
77
+ # least connections, or least response time for better resource utilization and performance optimization.
78
+
79
+
80
+ @app.middleware("http")
81
+ async def check_url(request: Request, call_next):
82
+ if len(app.state.MODELS) == 0:
83
+ await get_all_models()
84
+ else:
85
+ pass
86
+
87
+ response = await call_next(request)
88
+ return response
89
+
90
+
91
+ @app.head("/")
92
+ @app.get("/")
93
+ async def get_status():
94
+ return {"status": True}
95
+
96
+
97
+ @app.get("/config")
98
+ async def get_config(user=Depends(get_admin_user)):
99
+ return {"ENABLE_OLLAMA_API": app.state.config.ENABLE_OLLAMA_API}
100
+
101
+
102
+ class OllamaConfigForm(BaseModel):
103
+ enable_ollama_api: Optional[bool] = None
104
+
105
+
106
+ @app.post("/config/update")
107
+ async def update_config(form_data: OllamaConfigForm, user=Depends(get_admin_user)):
108
+ app.state.config.ENABLE_OLLAMA_API = form_data.enable_ollama_api
109
+ return {"ENABLE_OLLAMA_API": app.state.config.ENABLE_OLLAMA_API}
110
+
111
+
112
+ @app.get("/urls")
113
+ async def get_ollama_api_urls(user=Depends(get_admin_user)):
114
+ return {"OLLAMA_BASE_URLS": app.state.config.OLLAMA_BASE_URLS}
115
+
116
+
117
+ class UrlUpdateForm(BaseModel):
118
+ urls: list[str]
119
+
120
+
121
+ @app.post("/urls/update")
122
+ async def update_ollama_api_url(form_data: UrlUpdateForm, user=Depends(get_admin_user)):
123
+ app.state.config.OLLAMA_BASE_URLS = form_data.urls
124
+
125
+ log.info(f"app.state.config.OLLAMA_BASE_URLS: {app.state.config.OLLAMA_BASE_URLS}")
126
+ return {"OLLAMA_BASE_URLS": app.state.config.OLLAMA_BASE_URLS}
127
+
128
+
129
+ async def fetch_url(url):
130
+ timeout = aiohttp.ClientTimeout(total=5)
131
+ try:
132
+ async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
133
+ async with session.get(url) as response:
134
+ return await response.json()
135
+ except Exception as e:
136
+ # Handle connection error here
137
+ log.error(f"Connection error: {e}")
138
+ return None
139
+
140
+
141
+ async def cleanup_response(
142
+ response: Optional[aiohttp.ClientResponse],
143
+ session: Optional[aiohttp.ClientSession],
144
+ ):
145
+ if response:
146
+ response.close()
147
+ if session:
148
+ await session.close()
149
+
150
+
151
+ async def post_streaming_url(url: str, payload: Union[str, bytes], stream: bool = True):
152
+ r = None
153
+ try:
154
+ session = aiohttp.ClientSession(
155
+ trust_env=True, timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT)
156
+ )
157
+ r = await session.post(
158
+ url,
159
+ data=payload,
160
+ headers={"Content-Type": "application/json"},
161
+ )
162
+ r.raise_for_status()
163
+
164
+ if stream:
165
+ return StreamingResponse(
166
+ r.content,
167
+ status_code=r.status,
168
+ headers=dict(r.headers),
169
+ background=BackgroundTask(
170
+ cleanup_response, response=r, session=session
171
+ ),
172
+ )
173
+ else:
174
+ res = await r.json()
175
+ await cleanup_response(r, session)
176
+ return res
177
+
178
+ except Exception as e:
179
+ error_detail = "Open WebUI: Server Connection Error"
180
+ if r is not None:
181
+ try:
182
+ res = await r.json()
183
+ if "error" in res:
184
+ error_detail = f"Ollama: {res['error']}"
185
+ except Exception:
186
+ error_detail = f"Ollama: {e}"
187
+
188
+ raise HTTPException(
189
+ status_code=r.status if r else 500,
190
+ detail=error_detail,
191
+ )
192
+
193
+
194
+ def merge_models_lists(model_lists):
195
+ merged_models = {}
196
+
197
+ for idx, model_list in enumerate(model_lists):
198
+ if model_list is not None:
199
+ for model in model_list:
200
+ digest = model["digest"]
201
+ if digest not in merged_models:
202
+ model["urls"] = [idx]
203
+ merged_models[digest] = model
204
+ else:
205
+ merged_models[digest]["urls"].append(idx)
206
+
207
+ return list(merged_models.values())
208
+
209
+
210
+ async def get_all_models():
211
+ log.info("get_all_models()")
212
+
213
+ if app.state.config.ENABLE_OLLAMA_API:
214
+ tasks = [
215
+ fetch_url(f"{url}/api/tags") for url in app.state.config.OLLAMA_BASE_URLS
216
+ ]
217
+ responses = await asyncio.gather(*tasks)
218
+
219
+ models = {
220
+ "models": merge_models_lists(
221
+ map(
222
+ lambda response: response["models"] if response else None, responses
223
+ )
224
+ )
225
+ }
226
+
227
+ else:
228
+ models = {"models": []}
229
+
230
+ app.state.MODELS = {model["model"]: model for model in models["models"]}
231
+
232
+ return models
233
+
234
+
235
+ @app.get("/api/tags")
236
+ @app.get("/api/tags/{url_idx}")
237
+ async def get_ollama_tags(
238
+ url_idx: Optional[int] = None, user=Depends(get_verified_user)
239
+ ):
240
+ if url_idx is None:
241
+ models = await get_all_models()
242
+
243
+ if app.state.config.ENABLE_MODEL_FILTER:
244
+ if user.role == "user":
245
+ models["models"] = list(
246
+ filter(
247
+ lambda model: model["name"]
248
+ in app.state.config.MODEL_FILTER_LIST,
249
+ models["models"],
250
+ )
251
+ )
252
+ return models
253
+ return models
254
+ else:
255
+ url = app.state.config.OLLAMA_BASE_URLS[url_idx]
256
+
257
+ r = None
258
+ try:
259
+ r = requests.request(method="GET", url=f"{url}/api/tags")
260
+ r.raise_for_status()
261
+
262
+ return r.json()
263
+ except Exception as e:
264
+ log.exception(e)
265
+ error_detail = "Open WebUI: Server Connection Error"
266
+ if r is not None:
267
+ try:
268
+ res = r.json()
269
+ if "error" in res:
270
+ error_detail = f"Ollama: {res['error']}"
271
+ except Exception:
272
+ error_detail = f"Ollama: {e}"
273
+
274
+ raise HTTPException(
275
+ status_code=r.status_code if r else 500,
276
+ detail=error_detail,
277
+ )
278
+
279
+
280
+ @app.get("/api/version")
281
+ @app.get("/api/version/{url_idx}")
282
+ async def get_ollama_versions(url_idx: Optional[int] = None):
283
+ if app.state.config.ENABLE_OLLAMA_API:
284
+ if url_idx is None:
285
+ # returns lowest version
286
+ tasks = [
287
+ fetch_url(f"{url}/api/version")
288
+ for url in app.state.config.OLLAMA_BASE_URLS
289
+ ]
290
+ responses = await asyncio.gather(*tasks)
291
+ responses = list(filter(lambda x: x is not None, responses))
292
+
293
+ if len(responses) > 0:
294
+ lowest_version = min(
295
+ responses,
296
+ key=lambda x: tuple(
297
+ map(int, re.sub(r"^v|-.*", "", x["version"]).split("."))
298
+ ),
299
+ )
300
+
301
+ return {"version": lowest_version["version"]}
302
+ else:
303
+ raise HTTPException(
304
+ status_code=500,
305
+ detail=ERROR_MESSAGES.OLLAMA_NOT_FOUND,
306
+ )
307
+ else:
308
+ url = app.state.config.OLLAMA_BASE_URLS[url_idx]
309
+
310
+ r = None
311
+ try:
312
+ r = requests.request(method="GET", url=f"{url}/api/version")
313
+ r.raise_for_status()
314
+
315
+ return r.json()
316
+ except Exception as e:
317
+ log.exception(e)
318
+ error_detail = "Open WebUI: Server Connection Error"
319
+ if r is not None:
320
+ try:
321
+ res = r.json()
322
+ if "error" in res:
323
+ error_detail = f"Ollama: {res['error']}"
324
+ except Exception:
325
+ error_detail = f"Ollama: {e}"
326
+
327
+ raise HTTPException(
328
+ status_code=r.status_code if r else 500,
329
+ detail=error_detail,
330
+ )
331
+ else:
332
+ return {"version": False}
333
+
334
+
335
+ class ModelNameForm(BaseModel):
336
+ name: str
337
+
338
+
339
+ @app.post("/api/pull")
340
+ @app.post("/api/pull/{url_idx}")
341
+ async def pull_model(
342
+ form_data: ModelNameForm, url_idx: int = 0, user=Depends(get_admin_user)
343
+ ):
344
+ url = app.state.config.OLLAMA_BASE_URLS[url_idx]
345
+ log.info(f"url: {url}")
346
+
347
+ # Admin should be able to pull models from any source
348
+ payload = {**form_data.model_dump(exclude_none=True), "insecure": True}
349
+
350
+ return await post_streaming_url(f"{url}/api/pull", json.dumps(payload))
351
+
352
+
353
+ class PushModelForm(BaseModel):
354
+ name: str
355
+ insecure: Optional[bool] = None
356
+ stream: Optional[bool] = None
357
+
358
+
359
+ @app.delete("/api/push")
360
+ @app.delete("/api/push/{url_idx}")
361
+ async def push_model(
362
+ form_data: PushModelForm,
363
+ url_idx: Optional[int] = None,
364
+ user=Depends(get_admin_user),
365
+ ):
366
+ if url_idx is None:
367
+ if form_data.name in app.state.MODELS:
368
+ url_idx = app.state.MODELS[form_data.name]["urls"][0]
369
+ else:
370
+ raise HTTPException(
371
+ status_code=400,
372
+ detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.name),
373
+ )
374
+
375
+ url = app.state.config.OLLAMA_BASE_URLS[url_idx]
376
+ log.debug(f"url: {url}")
377
+
378
+ return await post_streaming_url(
379
+ f"{url}/api/push", form_data.model_dump_json(exclude_none=True).encode()
380
+ )
381
+
382
+
383
+ class CreateModelForm(BaseModel):
384
+ name: str
385
+ modelfile: Optional[str] = None
386
+ stream: Optional[bool] = None
387
+ path: Optional[str] = None
388
+
389
+
390
+ @app.post("/api/create")
391
+ @app.post("/api/create/{url_idx}")
392
+ async def create_model(
393
+ form_data: CreateModelForm, url_idx: int = 0, user=Depends(get_admin_user)
394
+ ):
395
+ log.debug(f"form_data: {form_data}")
396
+ url = app.state.config.OLLAMA_BASE_URLS[url_idx]
397
+ log.info(f"url: {url}")
398
+
399
+ return await post_streaming_url(
400
+ f"{url}/api/create", form_data.model_dump_json(exclude_none=True).encode()
401
+ )
402
+
403
+
404
+ class CopyModelForm(BaseModel):
405
+ source: str
406
+ destination: str
407
+
408
+
409
+ @app.post("/api/copy")
410
+ @app.post("/api/copy/{url_idx}")
411
+ async def copy_model(
412
+ form_data: CopyModelForm,
413
+ url_idx: Optional[int] = None,
414
+ user=Depends(get_admin_user),
415
+ ):
416
+ if url_idx is None:
417
+ if form_data.source in app.state.MODELS:
418
+ url_idx = app.state.MODELS[form_data.source]["urls"][0]
419
+ else:
420
+ raise HTTPException(
421
+ status_code=400,
422
+ detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.source),
423
+ )
424
+
425
+ url = app.state.config.OLLAMA_BASE_URLS[url_idx]
426
+ log.info(f"url: {url}")
427
+ r = requests.request(
428
+ method="POST",
429
+ url=f"{url}/api/copy",
430
+ headers={"Content-Type": "application/json"},
431
+ data=form_data.model_dump_json(exclude_none=True).encode(),
432
+ )
433
+
434
+ try:
435
+ r.raise_for_status()
436
+
437
+ log.debug(f"r.text: {r.text}")
438
+
439
+ return True
440
+ except Exception as e:
441
+ log.exception(e)
442
+ error_detail = "Open WebUI: Server Connection Error"
443
+ if r is not None:
444
+ try:
445
+ res = r.json()
446
+ if "error" in res:
447
+ error_detail = f"Ollama: {res['error']}"
448
+ except Exception:
449
+ error_detail = f"Ollama: {e}"
450
+
451
+ raise HTTPException(
452
+ status_code=r.status_code if r else 500,
453
+ detail=error_detail,
454
+ )
455
+
456
+
457
+ @app.delete("/api/delete")
458
+ @app.delete("/api/delete/{url_idx}")
459
+ async def delete_model(
460
+ form_data: ModelNameForm,
461
+ url_idx: Optional[int] = None,
462
+ user=Depends(get_admin_user),
463
+ ):
464
+ if url_idx is None:
465
+ if form_data.name in app.state.MODELS:
466
+ url_idx = app.state.MODELS[form_data.name]["urls"][0]
467
+ else:
468
+ raise HTTPException(
469
+ status_code=400,
470
+ detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.name),
471
+ )
472
+
473
+ url = app.state.config.OLLAMA_BASE_URLS[url_idx]
474
+ log.info(f"url: {url}")
475
+
476
+ r = requests.request(
477
+ method="DELETE",
478
+ url=f"{url}/api/delete",
479
+ headers={"Content-Type": "application/json"},
480
+ data=form_data.model_dump_json(exclude_none=True).encode(),
481
+ )
482
+ try:
483
+ r.raise_for_status()
484
+
485
+ log.debug(f"r.text: {r.text}")
486
+
487
+ return True
488
+ except Exception as e:
489
+ log.exception(e)
490
+ error_detail = "Open WebUI: Server Connection Error"
491
+ if r is not None:
492
+ try:
493
+ res = r.json()
494
+ if "error" in res:
495
+ error_detail = f"Ollama: {res['error']}"
496
+ except Exception:
497
+ error_detail = f"Ollama: {e}"
498
+
499
+ raise HTTPException(
500
+ status_code=r.status_code if r else 500,
501
+ detail=error_detail,
502
+ )
503
+
504
+
505
+ @app.post("/api/show")
506
+ async def show_model_info(form_data: ModelNameForm, user=Depends(get_verified_user)):
507
+ if form_data.name not in app.state.MODELS:
508
+ raise HTTPException(
509
+ status_code=400,
510
+ detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.name),
511
+ )
512
+
513
+ url_idx = random.choice(app.state.MODELS[form_data.name]["urls"])
514
+ url = app.state.config.OLLAMA_BASE_URLS[url_idx]
515
+ log.info(f"url: {url}")
516
+
517
+ r = requests.request(
518
+ method="POST",
519
+ url=f"{url}/api/show",
520
+ headers={"Content-Type": "application/json"},
521
+ data=form_data.model_dump_json(exclude_none=True).encode(),
522
+ )
523
+ try:
524
+ r.raise_for_status()
525
+
526
+ return r.json()
527
+ except Exception as e:
528
+ log.exception(e)
529
+ error_detail = "Open WebUI: Server Connection Error"
530
+ if r is not None:
531
+ try:
532
+ res = r.json()
533
+ if "error" in res:
534
+ error_detail = f"Ollama: {res['error']}"
535
+ except Exception:
536
+ error_detail = f"Ollama: {e}"
537
+
538
+ raise HTTPException(
539
+ status_code=r.status_code if r else 500,
540
+ detail=error_detail,
541
+ )
542
+
543
+
544
+ class GenerateEmbeddingsForm(BaseModel):
545
+ model: str
546
+ prompt: str
547
+ options: Optional[dict] = None
548
+ keep_alive: Optional[Union[int, str]] = None
549
+
550
+
551
+ @app.post("/api/embeddings")
552
+ @app.post("/api/embeddings/{url_idx}")
553
+ async def generate_embeddings(
554
+ form_data: GenerateEmbeddingsForm,
555
+ url_idx: Optional[int] = None,
556
+ user=Depends(get_verified_user),
557
+ ):
558
+ if url_idx is None:
559
+ model = form_data.model
560
+
561
+ if ":" not in model:
562
+ model = f"{model}:latest"
563
+
564
+ if model in app.state.MODELS:
565
+ url_idx = random.choice(app.state.MODELS[model]["urls"])
566
+ else:
567
+ raise HTTPException(
568
+ status_code=400,
569
+ detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
570
+ )
571
+
572
+ url = app.state.config.OLLAMA_BASE_URLS[url_idx]
573
+ log.info(f"url: {url}")
574
+
575
+ r = requests.request(
576
+ method="POST",
577
+ url=f"{url}/api/embeddings",
578
+ headers={"Content-Type": "application/json"},
579
+ data=form_data.model_dump_json(exclude_none=True).encode(),
580
+ )
581
+ try:
582
+ r.raise_for_status()
583
+
584
+ return r.json()
585
+ except Exception as e:
586
+ log.exception(e)
587
+ error_detail = "Open WebUI: Server Connection Error"
588
+ if r is not None:
589
+ try:
590
+ res = r.json()
591
+ if "error" in res:
592
+ error_detail = f"Ollama: {res['error']}"
593
+ except Exception:
594
+ error_detail = f"Ollama: {e}"
595
+
596
+ raise HTTPException(
597
+ status_code=r.status_code if r else 500,
598
+ detail=error_detail,
599
+ )
600
+
601
+
602
+ def generate_ollama_embeddings(
603
+ form_data: GenerateEmbeddingsForm,
604
+ url_idx: Optional[int] = None,
605
+ ):
606
+ log.info(f"generate_ollama_embeddings {form_data}")
607
+
608
+ if url_idx is None:
609
+ model = form_data.model
610
+
611
+ if ":" not in model:
612
+ model = f"{model}:latest"
613
+
614
+ if model in app.state.MODELS:
615
+ url_idx = random.choice(app.state.MODELS[model]["urls"])
616
+ else:
617
+ raise HTTPException(
618
+ status_code=400,
619
+ detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
620
+ )
621
+
622
+ url = app.state.config.OLLAMA_BASE_URLS[url_idx]
623
+ log.info(f"url: {url}")
624
+
625
+ r = requests.request(
626
+ method="POST",
627
+ url=f"{url}/api/embeddings",
628
+ headers={"Content-Type": "application/json"},
629
+ data=form_data.model_dump_json(exclude_none=True).encode(),
630
+ )
631
+ try:
632
+ r.raise_for_status()
633
+
634
+ data = r.json()
635
+
636
+ log.info(f"generate_ollama_embeddings {data}")
637
+
638
+ if "embedding" in data:
639
+ return data["embedding"]
640
+ else:
641
+ raise Exception("Something went wrong :/")
642
+ except Exception as e:
643
+ log.exception(e)
644
+ error_detail = "Open WebUI: Server Connection Error"
645
+ if r is not None:
646
+ try:
647
+ res = r.json()
648
+ if "error" in res:
649
+ error_detail = f"Ollama: {res['error']}"
650
+ except Exception:
651
+ error_detail = f"Ollama: {e}"
652
+
653
+ raise Exception(error_detail)
654
+
655
+
656
+ class GenerateCompletionForm(BaseModel):
657
+ model: str
658
+ prompt: str
659
+ images: Optional[list[str]] = None
660
+ format: Optional[str] = None
661
+ options: Optional[dict] = None
662
+ system: Optional[str] = None
663
+ template: Optional[str] = None
664
+ context: Optional[str] = None
665
+ stream: Optional[bool] = True
666
+ raw: Optional[bool] = None
667
+ keep_alive: Optional[Union[int, str]] = None
668
+
669
+
670
+ @app.post("/api/generate")
671
+ @app.post("/api/generate/{url_idx}")
672
+ async def generate_completion(
673
+ form_data: GenerateCompletionForm,
674
+ url_idx: Optional[int] = None,
675
+ user=Depends(get_verified_user),
676
+ ):
677
+ if url_idx is None:
678
+ model = form_data.model
679
+
680
+ if ":" not in model:
681
+ model = f"{model}:latest"
682
+
683
+ if model in app.state.MODELS:
684
+ url_idx = random.choice(app.state.MODELS[model]["urls"])
685
+ else:
686
+ raise HTTPException(
687
+ status_code=400,
688
+ detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
689
+ )
690
+
691
+ url = app.state.config.OLLAMA_BASE_URLS[url_idx]
692
+ log.info(f"url: {url}")
693
+
694
+ return await post_streaming_url(
695
+ f"{url}/api/generate", form_data.model_dump_json(exclude_none=True).encode()
696
+ )
697
+
698
+
699
+ class ChatMessage(BaseModel):
700
+ role: str
701
+ content: str
702
+ images: Optional[list[str]] = None
703
+
704
+
705
+ class GenerateChatCompletionForm(BaseModel):
706
+ model: str
707
+ messages: list[ChatMessage]
708
+ format: Optional[str] = None
709
+ options: Optional[dict] = None
710
+ template: Optional[str] = None
711
+ stream: Optional[bool] = None
712
+ keep_alive: Optional[Union[int, str]] = None
713
+
714
+
715
+ def get_ollama_url(url_idx: Optional[int], model: str):
716
+ if url_idx is None:
717
+ if model not in app.state.MODELS:
718
+ raise HTTPException(
719
+ status_code=400,
720
+ detail=ERROR_MESSAGES.MODEL_NOT_FOUND(model),
721
+ )
722
+ url_idx = random.choice(app.state.MODELS[model]["urls"])
723
+ url = app.state.config.OLLAMA_BASE_URLS[url_idx]
724
+ return url
725
+
726
+
727
+ @app.post("/api/chat")
728
+ @app.post("/api/chat/{url_idx}")
729
+ async def generate_chat_completion(
730
+ form_data: GenerateChatCompletionForm,
731
+ url_idx: Optional[int] = None,
732
+ user=Depends(get_verified_user),
733
+ ):
734
+ log.debug(f"{form_data.model_dump_json(exclude_none=True).encode()}=")
735
+
736
+ payload = {
737
+ **form_data.model_dump(exclude_none=True, exclude=["metadata"]),
738
+ }
739
+ if "metadata" in payload:
740
+ del payload["metadata"]
741
+
742
+ model_id = form_data.model
743
+ model_info = Models.get_model_by_id(model_id)
744
+
745
+ if model_info:
746
+ if model_info.base_model_id:
747
+ payload["model"] = model_info.base_model_id
748
+
749
+ params = model_info.params.model_dump()
750
+
751
+ if params:
752
+ if payload.get("options") is None:
753
+ payload["options"] = {}
754
+
755
+ payload["options"] = apply_model_params_to_body_ollama(
756
+ params, payload["options"]
757
+ )
758
+ payload = apply_model_system_prompt_to_body(params, payload, user)
759
+
760
+ if ":" not in payload["model"]:
761
+ payload["model"] = f"{payload['model']}:latest"
762
+
763
+ url = get_ollama_url(url_idx, payload["model"])
764
+ log.info(f"url: {url}")
765
+ log.debug(payload)
766
+
767
+ return await post_streaming_url(f"{url}/api/chat", json.dumps(payload))
768
+
769
+
770
+ # TODO: we should update this part once Ollama supports other types
771
+ class OpenAIChatMessageContent(BaseModel):
772
+ type: str
773
+ model_config = ConfigDict(extra="allow")
774
+
775
+
776
+ class OpenAIChatMessage(BaseModel):
777
+ role: str
778
+ content: Union[str, OpenAIChatMessageContent]
779
+
780
+ model_config = ConfigDict(extra="allow")
781
+
782
+
783
+ class OpenAIChatCompletionForm(BaseModel):
784
+ model: str
785
+ messages: list[OpenAIChatMessage]
786
+
787
+ model_config = ConfigDict(extra="allow")
788
+
789
+
790
+ @app.post("/v1/chat/completions")
791
+ @app.post("/v1/chat/completions/{url_idx}")
792
+ async def generate_openai_chat_completion(
793
+ form_data: dict,
794
+ url_idx: Optional[int] = None,
795
+ user=Depends(get_verified_user),
796
+ ):
797
+ completion_form = OpenAIChatCompletionForm(**form_data)
798
+ payload = {**completion_form.model_dump(exclude_none=True, exclude=["metadata"])}
799
+ if "metadata" in payload:
800
+ del payload["metadata"]
801
+
802
+ model_id = completion_form.model
803
+ model_info = Models.get_model_by_id(model_id)
804
+
805
+ if model_info:
806
+ if model_info.base_model_id:
807
+ payload["model"] = model_info.base_model_id
808
+
809
+ params = model_info.params.model_dump()
810
+
811
+ if params:
812
+ payload = apply_model_params_to_body_openai(params, payload)
813
+ payload = apply_model_system_prompt_to_body(params, payload, user)
814
+
815
+ if ":" not in payload["model"]:
816
+ payload["model"] = f"{payload['model']}:latest"
817
+
818
+ url = get_ollama_url(url_idx, payload["model"])
819
+ log.info(f"url: {url}")
820
+
821
+ return await post_streaming_url(
822
+ f"{url}/v1/chat/completions",
823
+ json.dumps(payload),
824
+ stream=payload.get("stream", False),
825
+ )
826
+
827
+
828
+ @app.get("/v1/models")
829
+ @app.get("/v1/models/{url_idx}")
830
+ async def get_openai_models(
831
+ url_idx: Optional[int] = None,
832
+ user=Depends(get_verified_user),
833
+ ):
834
+ if url_idx is None:
835
+ models = await get_all_models()
836
+
837
+ if app.state.config.ENABLE_MODEL_FILTER:
838
+ if user.role == "user":
839
+ models["models"] = list(
840
+ filter(
841
+ lambda model: model["name"]
842
+ in app.state.config.MODEL_FILTER_LIST,
843
+ models["models"],
844
+ )
845
+ )
846
+
847
+ return {
848
+ "data": [
849
+ {
850
+ "id": model["model"],
851
+ "object": "model",
852
+ "created": int(time.time()),
853
+ "owned_by": "openai",
854
+ }
855
+ for model in models["models"]
856
+ ],
857
+ "object": "list",
858
+ }
859
+
860
+ else:
861
+ url = app.state.config.OLLAMA_BASE_URLS[url_idx]
862
+ try:
863
+ r = requests.request(method="GET", url=f"{url}/api/tags")
864
+ r.raise_for_status()
865
+
866
+ models = r.json()
867
+
868
+ return {
869
+ "data": [
870
+ {
871
+ "id": model["model"],
872
+ "object": "model",
873
+ "created": int(time.time()),
874
+ "owned_by": "openai",
875
+ }
876
+ for model in models["models"]
877
+ ],
878
+ "object": "list",
879
+ }
880
+
881
+ except Exception as e:
882
+ log.exception(e)
883
+ error_detail = "Open WebUI: Server Connection Error"
884
+ if r is not None:
885
+ try:
886
+ res = r.json()
887
+ if "error" in res:
888
+ error_detail = f"Ollama: {res['error']}"
889
+ except Exception:
890
+ error_detail = f"Ollama: {e}"
891
+
892
+ raise HTTPException(
893
+ status_code=r.status_code if r else 500,
894
+ detail=error_detail,
895
+ )
896
+
897
+
898
+ class UrlForm(BaseModel):
899
+ url: str
900
+
901
+
902
+ class UploadBlobForm(BaseModel):
903
+ filename: str
904
+
905
+
906
+ def parse_huggingface_url(hf_url):
907
+ try:
908
+ # Parse the URL
909
+ parsed_url = urlparse(hf_url)
910
+
911
+ # Get the path and split it into components
912
+ path_components = parsed_url.path.split("/")
913
+
914
+ # Extract the desired output
915
+ model_file = path_components[-1]
916
+
917
+ return model_file
918
+ except ValueError:
919
+ return None
920
+
921
+
922
+ async def download_file_stream(
923
+ ollama_url, file_url, file_path, file_name, chunk_size=1024 * 1024
924
+ ):
925
+ done = False
926
+
927
+ if os.path.exists(file_path):
928
+ current_size = os.path.getsize(file_path)
929
+ else:
930
+ current_size = 0
931
+
932
+ headers = {"Range": f"bytes={current_size}-"} if current_size > 0 else {}
933
+
934
+ timeout = aiohttp.ClientTimeout(total=600) # Set the timeout
935
+
936
+ async with aiohttp.ClientSession(timeout=timeout, trust_env=True) as session:
937
+ async with session.get(file_url, headers=headers) as response:
938
+ total_size = int(response.headers.get("content-length", 0)) + current_size
939
+
940
+ with open(file_path, "ab+") as file:
941
+ async for data in response.content.iter_chunked(chunk_size):
942
+ current_size += len(data)
943
+ file.write(data)
944
+
945
+ done = current_size == total_size
946
+ progress = round((current_size / total_size) * 100, 2)
947
+
948
+ yield f'data: {{"progress": {progress}, "completed": {current_size}, "total": {total_size}}}\n\n'
949
+
950
+ if done:
951
+ file.seek(0)
952
+ hashed = calculate_sha256(file)
953
+ file.seek(0)
954
+
955
+ url = f"{ollama_url}/api/blobs/sha256:{hashed}"
956
+ response = requests.post(url, data=file)
957
+
958
+ if response.ok:
959
+ res = {
960
+ "done": done,
961
+ "blob": f"sha256:{hashed}",
962
+ "name": file_name,
963
+ }
964
+ os.remove(file_path)
965
+
966
+ yield f"data: {json.dumps(res)}\n\n"
967
+ else:
968
+ raise "Ollama: Could not create blob, Please try again."
969
+
970
+
971
+ # url = "https://huggingface.co/TheBloke/stablelm-zephyr-3b-GGUF/resolve/main/stablelm-zephyr-3b.Q2_K.gguf"
972
+ @app.post("/models/download")
973
+ @app.post("/models/download/{url_idx}")
974
+ async def download_model(
975
+ form_data: UrlForm,
976
+ url_idx: Optional[int] = None,
977
+ user=Depends(get_admin_user),
978
+ ):
979
+ allowed_hosts = ["https://huggingface.co/", "https://github.com/"]
980
+
981
+ if not any(form_data.url.startswith(host) for host in allowed_hosts):
982
+ raise HTTPException(
983
+ status_code=400,
984
+ detail="Invalid file_url. Only URLs from allowed hosts are permitted.",
985
+ )
986
+
987
+ if url_idx is None:
988
+ url_idx = 0
989
+ url = app.state.config.OLLAMA_BASE_URLS[url_idx]
990
+
991
+ file_name = parse_huggingface_url(form_data.url)
992
+
993
+ if file_name:
994
+ file_path = f"{UPLOAD_DIR}/{file_name}"
995
+
996
+ return StreamingResponse(
997
+ download_file_stream(url, form_data.url, file_path, file_name),
998
+ )
999
+ else:
1000
+ return None
1001
+
1002
+
1003
+ @app.post("/models/upload")
1004
+ @app.post("/models/upload/{url_idx}")
1005
+ def upload_model(
1006
+ file: UploadFile = File(...),
1007
+ url_idx: Optional[int] = None,
1008
+ user=Depends(get_admin_user),
1009
+ ):
1010
+ if url_idx is None:
1011
+ url_idx = 0
1012
+ ollama_url = app.state.config.OLLAMA_BASE_URLS[url_idx]
1013
+
1014
+ file_path = f"{UPLOAD_DIR}/{file.filename}"
1015
+
1016
+ # Save file in chunks
1017
+ with open(file_path, "wb+") as f:
1018
+ for chunk in file.file:
1019
+ f.write(chunk)
1020
+
1021
+ def file_process_stream():
1022
+ nonlocal ollama_url
1023
+ total_size = os.path.getsize(file_path)
1024
+ chunk_size = 1024 * 1024
1025
+ try:
1026
+ with open(file_path, "rb") as f:
1027
+ total = 0
1028
+ done = False
1029
+
1030
+ while not done:
1031
+ chunk = f.read(chunk_size)
1032
+ if not chunk:
1033
+ done = True
1034
+ continue
1035
+
1036
+ total += len(chunk)
1037
+ progress = round((total / total_size) * 100, 2)
1038
+
1039
+ res = {
1040
+ "progress": progress,
1041
+ "total": total_size,
1042
+ "completed": total,
1043
+ }
1044
+ yield f"data: {json.dumps(res)}\n\n"
1045
+
1046
+ if done:
1047
+ f.seek(0)
1048
+ hashed = calculate_sha256(f)
1049
+ f.seek(0)
1050
+
1051
+ url = f"{ollama_url}/api/blobs/sha256:{hashed}"
1052
+ response = requests.post(url, data=f)
1053
+
1054
+ if response.ok:
1055
+ res = {
1056
+ "done": done,
1057
+ "blob": f"sha256:{hashed}",
1058
+ "name": file.filename,
1059
+ }
1060
+ os.remove(file_path)
1061
+ yield f"data: {json.dumps(res)}\n\n"
1062
+ else:
1063
+ raise Exception(
1064
+ "Ollama: Could not create blob, Please try again."
1065
+ )
1066
+
1067
+ except Exception as e:
1068
+ res = {"error": str(e)}
1069
+ yield f"data: {json.dumps(res)}\n\n"
1070
+
1071
+ return StreamingResponse(file_process_stream(), media_type="text/event-stream")
backend/apps/openai/main.py ADDED
@@ -0,0 +1,514 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, Request, HTTPException, Depends
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from fastapi.responses import StreamingResponse, FileResponse
4
+
5
+ import requests
6
+ import aiohttp
7
+ import asyncio
8
+ import json
9
+ import logging
10
+
11
+ from pydantic import BaseModel
12
+ from starlette.background import BackgroundTask
13
+
14
+ from apps.webui.models.models import Models
15
+ from constants import ERROR_MESSAGES
16
+ from utils.utils import (
17
+ get_verified_user,
18
+ get_admin_user,
19
+ )
20
+ from utils.misc import (
21
+ apply_model_params_to_body_openai,
22
+ apply_model_system_prompt_to_body,
23
+ )
24
+
25
+ from config import (
26
+ SRC_LOG_LEVELS,
27
+ ENABLE_OPENAI_API,
28
+ AIOHTTP_CLIENT_TIMEOUT,
29
+ OPENAI_API_BASE_URLS,
30
+ OPENAI_API_KEYS,
31
+ CACHE_DIR,
32
+ ENABLE_MODEL_FILTER,
33
+ MODEL_FILTER_LIST,
34
+ AppConfig,
35
+ CORS_ALLOW_ORIGIN,
36
+ )
37
+ from typing import Optional, Literal, overload
38
+
39
+
40
+ import hashlib
41
+ from pathlib import Path
42
+
43
+ log = logging.getLogger(__name__)
44
+ log.setLevel(SRC_LOG_LEVELS["OPENAI"])
45
+
46
+ app = FastAPI()
47
+ app.add_middleware(
48
+ CORSMiddleware,
49
+ allow_origins=CORS_ALLOW_ORIGIN,
50
+ allow_credentials=True,
51
+ allow_methods=["*"],
52
+ allow_headers=["*"],
53
+ )
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=5)
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 "gpt" in model["id"]
229
+ ]
230
+ )
231
+
232
+ return merged_list
233
+
234
+
235
+ def is_openai_api_disabled():
236
+ api_keys = app.state.config.OPENAI_API_KEYS
237
+ no_keys = len(api_keys) == 1 and api_keys[0] == ""
238
+ return no_keys or not app.state.config.ENABLE_OPENAI_API
239
+
240
+
241
+ async def get_all_models_raw() -> list:
242
+ if is_openai_api_disabled():
243
+ return []
244
+
245
+ # Check if API KEYS length is same than API URLS length
246
+ num_urls = len(app.state.config.OPENAI_API_BASE_URLS)
247
+ num_keys = len(app.state.config.OPENAI_API_KEYS)
248
+
249
+ if num_keys != num_urls:
250
+ # if there are more keys than urls, remove the extra keys
251
+ if num_keys > num_urls:
252
+ new_keys = app.state.config.OPENAI_API_KEYS[:num_urls]
253
+ app.state.config.OPENAI_API_KEYS = new_keys
254
+ # if there are more urls than keys, add empty keys
255
+ else:
256
+ app.state.config.OPENAI_API_KEYS += [""] * (num_urls - num_keys)
257
+
258
+ tasks = [
259
+ fetch_url(f"{url}/models", app.state.config.OPENAI_API_KEYS[idx])
260
+ for idx, url in enumerate(app.state.config.OPENAI_API_BASE_URLS)
261
+ ]
262
+
263
+ responses = await asyncio.gather(*tasks)
264
+ log.debug(f"get_all_models:responses() {responses}")
265
+
266
+ return responses
267
+
268
+
269
+ @overload
270
+ async def get_all_models(raw: Literal[True]) -> list: ...
271
+
272
+
273
+ @overload
274
+ async def get_all_models(raw: Literal[False] = False) -> dict[str, list]: ...
275
+
276
+
277
+ async def get_all_models(raw=False) -> dict[str, list] | list:
278
+ log.info("get_all_models()")
279
+ if is_openai_api_disabled():
280
+ return [] if raw else {"data": []}
281
+
282
+ responses = await get_all_models_raw()
283
+ if raw:
284
+ return responses
285
+
286
+ def extract_data(response):
287
+ if response and "data" in response:
288
+ return response["data"]
289
+ if isinstance(response, list):
290
+ return response
291
+ return None
292
+
293
+ models = {"data": merge_models_lists(map(extract_data, responses))}
294
+
295
+ log.debug(f"models: {models}")
296
+ app.state.MODELS = {model["id"]: model for model in models["data"]}
297
+
298
+ return models
299
+
300
+
301
+ @app.get("/models")
302
+ @app.get("/models/{url_idx}")
303
+ async def get_models(url_idx: Optional[int] = None, user=Depends(get_verified_user)):
304
+ if url_idx is None:
305
+ models = await get_all_models()
306
+ if app.state.config.ENABLE_MODEL_FILTER:
307
+ if user.role == "user":
308
+ models["data"] = list(
309
+ filter(
310
+ lambda model: model["id"] in app.state.config.MODEL_FILTER_LIST,
311
+ models["data"],
312
+ )
313
+ )
314
+ return models
315
+ return models
316
+ else:
317
+ url = app.state.config.OPENAI_API_BASE_URLS[url_idx]
318
+ key = app.state.config.OPENAI_API_KEYS[url_idx]
319
+
320
+ headers = {}
321
+ headers["Authorization"] = f"Bearer {key}"
322
+ headers["Content-Type"] = "application/json"
323
+
324
+ r = None
325
+
326
+ try:
327
+ r = requests.request(method="GET", url=f"{url}/models", headers=headers)
328
+ r.raise_for_status()
329
+
330
+ response_data = r.json()
331
+ if "api.openai.com" in url:
332
+ response_data["data"] = list(
333
+ filter(lambda model: "gpt" in model["id"], response_data["data"])
334
+ )
335
+
336
+ return response_data
337
+ except Exception as e:
338
+ log.exception(e)
339
+ error_detail = "Open WebUI: Server Connection Error"
340
+ if r is not None:
341
+ try:
342
+ res = r.json()
343
+ if "error" in res:
344
+ error_detail = f"External: {res['error']}"
345
+ except Exception:
346
+ error_detail = f"External: {e}"
347
+
348
+ raise HTTPException(
349
+ status_code=r.status_code if r else 500,
350
+ detail=error_detail,
351
+ )
352
+
353
+
354
+ @app.post("/chat/completions")
355
+ @app.post("/chat/completions/{url_idx}")
356
+ async def generate_chat_completion(
357
+ form_data: dict,
358
+ url_idx: Optional[int] = None,
359
+ user=Depends(get_verified_user),
360
+ ):
361
+ idx = 0
362
+ payload = {**form_data}
363
+
364
+ if "metadata" in payload:
365
+ del payload["metadata"]
366
+
367
+ model_id = form_data.get("model")
368
+ model_info = Models.get_model_by_id(model_id)
369
+
370
+ if model_info:
371
+ if model_info.base_model_id:
372
+ payload["model"] = model_info.base_model_id
373
+
374
+ params = model_info.params.model_dump()
375
+ payload = apply_model_params_to_body_openai(params, payload)
376
+ payload = apply_model_system_prompt_to_body(params, payload, user)
377
+
378
+ model = app.state.MODELS[payload.get("model")]
379
+ idx = model["urlIdx"]
380
+
381
+ if "pipeline" in model and model.get("pipeline"):
382
+ payload["user"] = {
383
+ "name": user.name,
384
+ "id": user.id,
385
+ "email": user.email,
386
+ "role": user.role,
387
+ }
388
+
389
+ # Convert the modified body back to JSON
390
+ payload = json.dumps(payload)
391
+
392
+ log.debug(payload)
393
+
394
+ url = app.state.config.OPENAI_API_BASE_URLS[idx]
395
+ key = app.state.config.OPENAI_API_KEYS[idx]
396
+
397
+ headers = {}
398
+ headers["Authorization"] = f"Bearer {key}"
399
+ headers["Content-Type"] = "application/json"
400
+ if "openrouter.ai" in app.state.config.OPENAI_API_BASE_URLS[idx]:
401
+ headers["HTTP-Referer"] = "https://openwebui.com/"
402
+ headers["X-Title"] = "Open WebUI"
403
+
404
+ r = None
405
+ session = None
406
+ streaming = False
407
+
408
+ try:
409
+ session = aiohttp.ClientSession(
410
+ trust_env=True, timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT)
411
+ )
412
+ r = await session.request(
413
+ method="POST",
414
+ url=f"{url}/chat/completions",
415
+ data=payload,
416
+ headers=headers,
417
+ )
418
+
419
+ r.raise_for_status()
420
+
421
+ # Check if response is SSE
422
+ if "text/event-stream" in r.headers.get("Content-Type", ""):
423
+ streaming = True
424
+ return StreamingResponse(
425
+ r.content,
426
+ status_code=r.status,
427
+ headers=dict(r.headers),
428
+ background=BackgroundTask(
429
+ cleanup_response, response=r, session=session
430
+ ),
431
+ )
432
+ else:
433
+ response_data = await r.json()
434
+ return response_data
435
+ except Exception as e:
436
+ log.exception(e)
437
+ error_detail = "Open WebUI: Server Connection Error"
438
+ if r is not None:
439
+ try:
440
+ res = await r.json()
441
+ print(res)
442
+ if "error" in res:
443
+ error_detail = f"External: {res['error']['message'] if 'message' in res['error'] else res['error']}"
444
+ except Exception:
445
+ error_detail = f"External: {e}"
446
+ raise HTTPException(status_code=r.status if r else 500, detail=error_detail)
447
+ finally:
448
+ if not streaming and session:
449
+ if r:
450
+ r.close()
451
+ await session.close()
452
+
453
+
454
+ @app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
455
+ async def proxy(path: str, request: Request, user=Depends(get_verified_user)):
456
+ idx = 0
457
+
458
+ body = await request.body()
459
+
460
+ url = app.state.config.OPENAI_API_BASE_URLS[idx]
461
+ key = app.state.config.OPENAI_API_KEYS[idx]
462
+
463
+ target_url = f"{url}/{path}"
464
+
465
+ headers = {}
466
+ headers["Authorization"] = f"Bearer {key}"
467
+ headers["Content-Type"] = "application/json"
468
+
469
+ r = None
470
+ session = None
471
+ streaming = False
472
+
473
+ try:
474
+ session = aiohttp.ClientSession(trust_env=True)
475
+ r = await session.request(
476
+ method=request.method,
477
+ url=target_url,
478
+ data=body,
479
+ headers=headers,
480
+ )
481
+
482
+ r.raise_for_status()
483
+
484
+ # Check if response is SSE
485
+ if "text/event-stream" in r.headers.get("Content-Type", ""):
486
+ streaming = True
487
+ return StreamingResponse(
488
+ r.content,
489
+ status_code=r.status,
490
+ headers=dict(r.headers),
491
+ background=BackgroundTask(
492
+ cleanup_response, response=r, session=session
493
+ ),
494
+ )
495
+ else:
496
+ response_data = await r.json()
497
+ return response_data
498
+ except Exception as e:
499
+ log.exception(e)
500
+ error_detail = "Open WebUI: Server Connection Error"
501
+ if r is not None:
502
+ try:
503
+ res = await r.json()
504
+ print(res)
505
+ if "error" in res:
506
+ error_detail = f"External: {res['error']['message'] if 'message' in res['error'] else res['error']}"
507
+ except Exception:
508
+ error_detail = f"External: {e}"
509
+ raise HTTPException(status_code=r.status if r else 500, detail=error_detail)
510
+ finally:
511
+ if not streaming and session:
512
+ if r:
513
+ r.close()
514
+ await session.close()
backend/apps/rag/main.py ADDED
@@ -0,0 +1,1461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import (
2
+ FastAPI,
3
+ Depends,
4
+ HTTPException,
5
+ status,
6
+ UploadFile,
7
+ File,
8
+ Form,
9
+ )
10
+ from fastapi.middleware.cors import CORSMiddleware
11
+ import requests
12
+ import os, shutil, logging, re
13
+ from datetime import datetime
14
+
15
+ from pathlib import Path
16
+ from typing import Union, Sequence, Iterator, Any
17
+
18
+ from chromadb.utils.batch_utils import create_batches
19
+ from langchain_core.documents import Document
20
+
21
+ from langchain_community.document_loaders import (
22
+ WebBaseLoader,
23
+ TextLoader,
24
+ PyPDFLoader,
25
+ CSVLoader,
26
+ BSHTMLLoader,
27
+ Docx2txtLoader,
28
+ UnstructuredEPubLoader,
29
+ UnstructuredWordDocumentLoader,
30
+ UnstructuredMarkdownLoader,
31
+ UnstructuredXMLLoader,
32
+ UnstructuredRSTLoader,
33
+ UnstructuredExcelLoader,
34
+ UnstructuredPowerPointLoader,
35
+ YoutubeLoader,
36
+ OutlookMessageLoader,
37
+ )
38
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
39
+
40
+ import validators
41
+ import urllib.parse
42
+ import socket
43
+
44
+
45
+ from pydantic import BaseModel
46
+ from typing import Optional
47
+ import mimetypes
48
+ import uuid
49
+ import json
50
+
51
+ from apps.webui.models.documents import (
52
+ Documents,
53
+ DocumentForm,
54
+ DocumentResponse,
55
+ )
56
+ from apps.webui.models.files import (
57
+ Files,
58
+ )
59
+
60
+ from apps.rag.utils import (
61
+ get_model_path,
62
+ get_embedding_function,
63
+ query_doc,
64
+ query_doc_with_hybrid_search,
65
+ query_collection,
66
+ query_collection_with_hybrid_search,
67
+ )
68
+
69
+ from apps.rag.search.brave import search_brave
70
+ from apps.rag.search.google_pse import search_google_pse
71
+ from apps.rag.search.main import SearchResult
72
+ from apps.rag.search.searxng import search_searxng
73
+ from apps.rag.search.serper import search_serper
74
+ from apps.rag.search.serpstack import search_serpstack
75
+ from apps.rag.search.serply import search_serply
76
+ from apps.rag.search.duckduckgo import search_duckduckgo
77
+ from apps.rag.search.tavily import search_tavily
78
+ from apps.rag.search.jina_search import search_jina
79
+
80
+ from utils.misc import (
81
+ calculate_sha256,
82
+ calculate_sha256_string,
83
+ sanitize_filename,
84
+ extract_folders_after_data_docs,
85
+ )
86
+ from utils.utils import get_verified_user, get_admin_user
87
+
88
+ from config import (
89
+ AppConfig,
90
+ ENV,
91
+ SRC_LOG_LEVELS,
92
+ UPLOAD_DIR,
93
+ DOCS_DIR,
94
+ CONTENT_EXTRACTION_ENGINE,
95
+ TIKA_SERVER_URL,
96
+ RAG_TOP_K,
97
+ RAG_RELEVANCE_THRESHOLD,
98
+ RAG_EMBEDDING_ENGINE,
99
+ RAG_EMBEDDING_MODEL,
100
+ RAG_EMBEDDING_MODEL_AUTO_UPDATE,
101
+ RAG_EMBEDDING_MODEL_TRUST_REMOTE_CODE,
102
+ ENABLE_RAG_HYBRID_SEARCH,
103
+ ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION,
104
+ RAG_RERANKING_MODEL,
105
+ PDF_EXTRACT_IMAGES,
106
+ RAG_RERANKING_MODEL_AUTO_UPDATE,
107
+ RAG_RERANKING_MODEL_TRUST_REMOTE_CODE,
108
+ RAG_OPENAI_API_BASE_URL,
109
+ RAG_OPENAI_API_KEY,
110
+ DEVICE_TYPE,
111
+ CHROMA_CLIENT,
112
+ CHUNK_SIZE,
113
+ CHUNK_OVERLAP,
114
+ RAG_TEMPLATE,
115
+ ENABLE_RAG_LOCAL_WEB_FETCH,
116
+ YOUTUBE_LOADER_LANGUAGE,
117
+ ENABLE_RAG_WEB_SEARCH,
118
+ RAG_WEB_SEARCH_ENGINE,
119
+ RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
120
+ SEARXNG_QUERY_URL,
121
+ GOOGLE_PSE_API_KEY,
122
+ GOOGLE_PSE_ENGINE_ID,
123
+ BRAVE_SEARCH_API_KEY,
124
+ SERPSTACK_API_KEY,
125
+ SERPSTACK_HTTPS,
126
+ SERPER_API_KEY,
127
+ SERPLY_API_KEY,
128
+ TAVILY_API_KEY,
129
+ RAG_WEB_SEARCH_RESULT_COUNT,
130
+ RAG_WEB_SEARCH_CONCURRENT_REQUESTS,
131
+ RAG_EMBEDDING_OPENAI_BATCH_SIZE,
132
+ CORS_ALLOW_ORIGIN,
133
+ )
134
+
135
+ from constants import ERROR_MESSAGES
136
+
137
+ log = logging.getLogger(__name__)
138
+ log.setLevel(SRC_LOG_LEVELS["RAG"])
139
+
140
+ app = FastAPI()
141
+
142
+ app.state.config = AppConfig()
143
+
144
+ app.state.config.TOP_K = RAG_TOP_K
145
+ app.state.config.RELEVANCE_THRESHOLD = RAG_RELEVANCE_THRESHOLD
146
+
147
+ app.state.config.ENABLE_RAG_HYBRID_SEARCH = ENABLE_RAG_HYBRID_SEARCH
148
+ app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION = (
149
+ ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION
150
+ )
151
+
152
+ app.state.config.CONTENT_EXTRACTION_ENGINE = CONTENT_EXTRACTION_ENGINE
153
+ app.state.config.TIKA_SERVER_URL = TIKA_SERVER_URL
154
+
155
+ app.state.config.CHUNK_SIZE = CHUNK_SIZE
156
+ app.state.config.CHUNK_OVERLAP = CHUNK_OVERLAP
157
+
158
+ app.state.config.RAG_EMBEDDING_ENGINE = RAG_EMBEDDING_ENGINE
159
+ app.state.config.RAG_EMBEDDING_MODEL = RAG_EMBEDDING_MODEL
160
+ app.state.config.RAG_EMBEDDING_OPENAI_BATCH_SIZE = RAG_EMBEDDING_OPENAI_BATCH_SIZE
161
+ app.state.config.RAG_RERANKING_MODEL = RAG_RERANKING_MODEL
162
+ app.state.config.RAG_TEMPLATE = RAG_TEMPLATE
163
+
164
+
165
+ app.state.config.OPENAI_API_BASE_URL = RAG_OPENAI_API_BASE_URL
166
+ app.state.config.OPENAI_API_KEY = RAG_OPENAI_API_KEY
167
+
168
+ app.state.config.PDF_EXTRACT_IMAGES = PDF_EXTRACT_IMAGES
169
+
170
+
171
+ app.state.config.YOUTUBE_LOADER_LANGUAGE = YOUTUBE_LOADER_LANGUAGE
172
+ app.state.YOUTUBE_LOADER_TRANSLATION = None
173
+
174
+
175
+ app.state.config.ENABLE_RAG_WEB_SEARCH = ENABLE_RAG_WEB_SEARCH
176
+ app.state.config.RAG_WEB_SEARCH_ENGINE = RAG_WEB_SEARCH_ENGINE
177
+ app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST = RAG_WEB_SEARCH_DOMAIN_FILTER_LIST
178
+
179
+ app.state.config.SEARXNG_QUERY_URL = SEARXNG_QUERY_URL
180
+ app.state.config.GOOGLE_PSE_API_KEY = GOOGLE_PSE_API_KEY
181
+ app.state.config.GOOGLE_PSE_ENGINE_ID = GOOGLE_PSE_ENGINE_ID
182
+ app.state.config.BRAVE_SEARCH_API_KEY = BRAVE_SEARCH_API_KEY
183
+ app.state.config.SERPSTACK_API_KEY = SERPSTACK_API_KEY
184
+ app.state.config.SERPSTACK_HTTPS = SERPSTACK_HTTPS
185
+ app.state.config.SERPER_API_KEY = SERPER_API_KEY
186
+ app.state.config.SERPLY_API_KEY = SERPLY_API_KEY
187
+ app.state.config.TAVILY_API_KEY = TAVILY_API_KEY
188
+ app.state.config.RAG_WEB_SEARCH_RESULT_COUNT = RAG_WEB_SEARCH_RESULT_COUNT
189
+ app.state.config.RAG_WEB_SEARCH_CONCURRENT_REQUESTS = RAG_WEB_SEARCH_CONCURRENT_REQUESTS
190
+
191
+
192
+ def update_embedding_model(
193
+ embedding_model: str,
194
+ update_model: bool = False,
195
+ ):
196
+ if embedding_model and app.state.config.RAG_EMBEDDING_ENGINE == "":
197
+ import sentence_transformers
198
+
199
+ app.state.sentence_transformer_ef = sentence_transformers.SentenceTransformer(
200
+ get_model_path(embedding_model, update_model),
201
+ device=DEVICE_TYPE,
202
+ trust_remote_code=RAG_EMBEDDING_MODEL_TRUST_REMOTE_CODE,
203
+ )
204
+ else:
205
+ app.state.sentence_transformer_ef = None
206
+
207
+
208
+ def update_reranking_model(
209
+ reranking_model: str,
210
+ update_model: bool = False,
211
+ ):
212
+ if reranking_model:
213
+ import sentence_transformers
214
+
215
+ app.state.sentence_transformer_rf = sentence_transformers.CrossEncoder(
216
+ get_model_path(reranking_model, update_model),
217
+ device=DEVICE_TYPE,
218
+ trust_remote_code=RAG_RERANKING_MODEL_TRUST_REMOTE_CODE,
219
+ )
220
+ else:
221
+ app.state.sentence_transformer_rf = None
222
+
223
+
224
+ update_embedding_model(
225
+ app.state.config.RAG_EMBEDDING_MODEL,
226
+ RAG_EMBEDDING_MODEL_AUTO_UPDATE,
227
+ )
228
+
229
+ update_reranking_model(
230
+ app.state.config.RAG_RERANKING_MODEL,
231
+ RAG_RERANKING_MODEL_AUTO_UPDATE,
232
+ )
233
+
234
+
235
+ app.state.EMBEDDING_FUNCTION = get_embedding_function(
236
+ app.state.config.RAG_EMBEDDING_ENGINE,
237
+ app.state.config.RAG_EMBEDDING_MODEL,
238
+ app.state.sentence_transformer_ef,
239
+ app.state.config.OPENAI_API_KEY,
240
+ app.state.config.OPENAI_API_BASE_URL,
241
+ app.state.config.RAG_EMBEDDING_OPENAI_BATCH_SIZE,
242
+ )
243
+
244
+ app.add_middleware(
245
+ CORSMiddleware,
246
+ allow_origins=CORS_ALLOW_ORIGIN,
247
+ allow_credentials=True,
248
+ allow_methods=["*"],
249
+ allow_headers=["*"],
250
+ )
251
+
252
+
253
+ class CollectionNameForm(BaseModel):
254
+ collection_name: Optional[str] = "test"
255
+
256
+
257
+ class UrlForm(CollectionNameForm):
258
+ url: str
259
+
260
+
261
+ class SearchForm(CollectionNameForm):
262
+ query: str
263
+
264
+
265
+ @app.get("/")
266
+ async def get_status():
267
+ return {
268
+ "status": True,
269
+ "chunk_size": app.state.config.CHUNK_SIZE,
270
+ "chunk_overlap": app.state.config.CHUNK_OVERLAP,
271
+ "template": app.state.config.RAG_TEMPLATE,
272
+ "embedding_engine": app.state.config.RAG_EMBEDDING_ENGINE,
273
+ "embedding_model": app.state.config.RAG_EMBEDDING_MODEL,
274
+ "reranking_model": app.state.config.RAG_RERANKING_MODEL,
275
+ "openai_batch_size": app.state.config.RAG_EMBEDDING_OPENAI_BATCH_SIZE,
276
+ }
277
+
278
+
279
+ @app.get("/embedding")
280
+ async def get_embedding_config(user=Depends(get_admin_user)):
281
+ return {
282
+ "status": True,
283
+ "embedding_engine": app.state.config.RAG_EMBEDDING_ENGINE,
284
+ "embedding_model": app.state.config.RAG_EMBEDDING_MODEL,
285
+ "openai_config": {
286
+ "url": app.state.config.OPENAI_API_BASE_URL,
287
+ "key": app.state.config.OPENAI_API_KEY,
288
+ "batch_size": app.state.config.RAG_EMBEDDING_OPENAI_BATCH_SIZE,
289
+ },
290
+ }
291
+
292
+
293
+ @app.get("/reranking")
294
+ async def get_reraanking_config(user=Depends(get_admin_user)):
295
+ return {
296
+ "status": True,
297
+ "reranking_model": app.state.config.RAG_RERANKING_MODEL,
298
+ }
299
+
300
+
301
+ class OpenAIConfigForm(BaseModel):
302
+ url: str
303
+ key: str
304
+ batch_size: Optional[int] = None
305
+
306
+
307
+ class EmbeddingModelUpdateForm(BaseModel):
308
+ openai_config: Optional[OpenAIConfigForm] = None
309
+ embedding_engine: str
310
+ embedding_model: str
311
+
312
+
313
+ @app.post("/embedding/update")
314
+ async def update_embedding_config(
315
+ form_data: EmbeddingModelUpdateForm, user=Depends(get_admin_user)
316
+ ):
317
+ log.info(
318
+ f"Updating embedding model: {app.state.config.RAG_EMBEDDING_MODEL} to {form_data.embedding_model}"
319
+ )
320
+ try:
321
+ app.state.config.RAG_EMBEDDING_ENGINE = form_data.embedding_engine
322
+ app.state.config.RAG_EMBEDDING_MODEL = form_data.embedding_model
323
+
324
+ if app.state.config.RAG_EMBEDDING_ENGINE in ["ollama", "openai"]:
325
+ if form_data.openai_config is not None:
326
+ app.state.config.OPENAI_API_BASE_URL = form_data.openai_config.url
327
+ app.state.config.OPENAI_API_KEY = form_data.openai_config.key
328
+ app.state.config.RAG_EMBEDDING_OPENAI_BATCH_SIZE = (
329
+ form_data.openai_config.batch_size
330
+ if form_data.openai_config.batch_size
331
+ else 1
332
+ )
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_OPENAI_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
+ "openai_config": {
350
+ "url": app.state.config.OPENAI_API_BASE_URL,
351
+ "key": app.state.config.OPENAI_API_KEY,
352
+ "batch_size": app.state.config.RAG_EMBEDDING_OPENAI_BATCH_SIZE,
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
+ "chunk_size": app.state.config.CHUNK_SIZE,
402
+ "chunk_overlap": app.state.config.CHUNK_OVERLAP,
403
+ },
404
+ "youtube": {
405
+ "language": app.state.config.YOUTUBE_LOADER_LANGUAGE,
406
+ "translation": app.state.YOUTUBE_LOADER_TRANSLATION,
407
+ },
408
+ "web": {
409
+ "ssl_verification": app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION,
410
+ "search": {
411
+ "enabled": app.state.config.ENABLE_RAG_WEB_SEARCH,
412
+ "engine": app.state.config.RAG_WEB_SEARCH_ENGINE,
413
+ "searxng_query_url": app.state.config.SEARXNG_QUERY_URL,
414
+ "google_pse_api_key": app.state.config.GOOGLE_PSE_API_KEY,
415
+ "google_pse_engine_id": app.state.config.GOOGLE_PSE_ENGINE_ID,
416
+ "brave_search_api_key": app.state.config.BRAVE_SEARCH_API_KEY,
417
+ "serpstack_api_key": app.state.config.SERPSTACK_API_KEY,
418
+ "serpstack_https": app.state.config.SERPSTACK_HTTPS,
419
+ "serper_api_key": app.state.config.SERPER_API_KEY,
420
+ "serply_api_key": app.state.config.SERPLY_API_KEY,
421
+ "tavily_api_key": app.state.config.TAVILY_API_KEY,
422
+ "result_count": app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
423
+ "concurrent_requests": app.state.config.RAG_WEB_SEARCH_CONCURRENT_REQUESTS,
424
+ },
425
+ },
426
+ }
427
+
428
+
429
+ class ContentExtractionConfig(BaseModel):
430
+ engine: str = ""
431
+ tika_server_url: Optional[str] = None
432
+
433
+
434
+ class ChunkParamUpdateForm(BaseModel):
435
+ chunk_size: int
436
+ chunk_overlap: int
437
+
438
+
439
+ class YoutubeLoaderConfig(BaseModel):
440
+ language: list[str]
441
+ translation: Optional[str] = None
442
+
443
+
444
+ class WebSearchConfig(BaseModel):
445
+ enabled: bool
446
+ engine: Optional[str] = None
447
+ searxng_query_url: Optional[str] = None
448
+ google_pse_api_key: Optional[str] = None
449
+ google_pse_engine_id: Optional[str] = None
450
+ brave_search_api_key: Optional[str] = None
451
+ serpstack_api_key: Optional[str] = None
452
+ serpstack_https: Optional[bool] = None
453
+ serper_api_key: Optional[str] = None
454
+ serply_api_key: Optional[str] = None
455
+ tavily_api_key: Optional[str] = None
456
+ result_count: Optional[int] = None
457
+ concurrent_requests: Optional[int] = None
458
+
459
+
460
+ class WebConfig(BaseModel):
461
+ search: WebSearchConfig
462
+ web_loader_ssl_verification: Optional[bool] = None
463
+
464
+
465
+ class ConfigUpdateForm(BaseModel):
466
+ pdf_extract_images: Optional[bool] = None
467
+ content_extraction: Optional[ContentExtractionConfig] = None
468
+ chunk: Optional[ChunkParamUpdateForm] = None
469
+ youtube: Optional[YoutubeLoaderConfig] = None
470
+ web: Optional[WebConfig] = None
471
+
472
+
473
+ @app.post("/config/update")
474
+ async def update_rag_config(form_data: ConfigUpdateForm, user=Depends(get_admin_user)):
475
+ app.state.config.PDF_EXTRACT_IMAGES = (
476
+ form_data.pdf_extract_images
477
+ if form_data.pdf_extract_images is not None
478
+ else app.state.config.PDF_EXTRACT_IMAGES
479
+ )
480
+
481
+ if form_data.content_extraction is not None:
482
+ log.info(f"Updating text settings: {form_data.content_extraction}")
483
+ app.state.config.CONTENT_EXTRACTION_ENGINE = form_data.content_extraction.engine
484
+ app.state.config.TIKA_SERVER_URL = form_data.content_extraction.tika_server_url
485
+
486
+ if form_data.chunk is not None:
487
+ app.state.config.CHUNK_SIZE = form_data.chunk.chunk_size
488
+ app.state.config.CHUNK_OVERLAP = form_data.chunk.chunk_overlap
489
+
490
+ if form_data.youtube is not None:
491
+ app.state.config.YOUTUBE_LOADER_LANGUAGE = form_data.youtube.language
492
+ app.state.YOUTUBE_LOADER_TRANSLATION = form_data.youtube.translation
493
+
494
+ if form_data.web is not None:
495
+ app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION = (
496
+ form_data.web.web_loader_ssl_verification
497
+ )
498
+
499
+ app.state.config.ENABLE_RAG_WEB_SEARCH = form_data.web.search.enabled
500
+ app.state.config.RAG_WEB_SEARCH_ENGINE = form_data.web.search.engine
501
+ app.state.config.SEARXNG_QUERY_URL = form_data.web.search.searxng_query_url
502
+ app.state.config.GOOGLE_PSE_API_KEY = form_data.web.search.google_pse_api_key
503
+ app.state.config.GOOGLE_PSE_ENGINE_ID = (
504
+ form_data.web.search.google_pse_engine_id
505
+ )
506
+ app.state.config.BRAVE_SEARCH_API_KEY = (
507
+ form_data.web.search.brave_search_api_key
508
+ )
509
+ app.state.config.SERPSTACK_API_KEY = form_data.web.search.serpstack_api_key
510
+ app.state.config.SERPSTACK_HTTPS = form_data.web.search.serpstack_https
511
+ app.state.config.SERPER_API_KEY = form_data.web.search.serper_api_key
512
+ app.state.config.SERPLY_API_KEY = form_data.web.search.serply_api_key
513
+ app.state.config.TAVILY_API_KEY = form_data.web.search.tavily_api_key
514
+ app.state.config.RAG_WEB_SEARCH_RESULT_COUNT = form_data.web.search.result_count
515
+ app.state.config.RAG_WEB_SEARCH_CONCURRENT_REQUESTS = (
516
+ form_data.web.search.concurrent_requests
517
+ )
518
+
519
+ return {
520
+ "status": True,
521
+ "pdf_extract_images": app.state.config.PDF_EXTRACT_IMAGES,
522
+ "content_extraction": {
523
+ "engine": app.state.config.CONTENT_EXTRACTION_ENGINE,
524
+ "tika_server_url": app.state.config.TIKA_SERVER_URL,
525
+ },
526
+ "chunk": {
527
+ "chunk_size": app.state.config.CHUNK_SIZE,
528
+ "chunk_overlap": app.state.config.CHUNK_OVERLAP,
529
+ },
530
+ "youtube": {
531
+ "language": app.state.config.YOUTUBE_LOADER_LANGUAGE,
532
+ "translation": app.state.YOUTUBE_LOADER_TRANSLATION,
533
+ },
534
+ "web": {
535
+ "ssl_verification": app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION,
536
+ "search": {
537
+ "enabled": app.state.config.ENABLE_RAG_WEB_SEARCH,
538
+ "engine": app.state.config.RAG_WEB_SEARCH_ENGINE,
539
+ "searxng_query_url": app.state.config.SEARXNG_QUERY_URL,
540
+ "google_pse_api_key": app.state.config.GOOGLE_PSE_API_KEY,
541
+ "google_pse_engine_id": app.state.config.GOOGLE_PSE_ENGINE_ID,
542
+ "brave_search_api_key": app.state.config.BRAVE_SEARCH_API_KEY,
543
+ "serpstack_api_key": app.state.config.SERPSTACK_API_KEY,
544
+ "serpstack_https": app.state.config.SERPSTACK_HTTPS,
545
+ "serper_api_key": app.state.config.SERPER_API_KEY,
546
+ "serply_api_key": app.state.config.SERPLY_API_KEY,
547
+ "tavily_api_key": app.state.config.TAVILY_API_KEY,
548
+ "result_count": app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
549
+ "concurrent_requests": app.state.config.RAG_WEB_SEARCH_CONCURRENT_REQUESTS,
550
+ },
551
+ },
552
+ }
553
+
554
+
555
+ @app.get("/template")
556
+ async def get_rag_template(user=Depends(get_verified_user)):
557
+ return {
558
+ "status": True,
559
+ "template": app.state.config.RAG_TEMPLATE,
560
+ }
561
+
562
+
563
+ @app.get("/query/settings")
564
+ async def get_query_settings(user=Depends(get_admin_user)):
565
+ return {
566
+ "status": True,
567
+ "template": app.state.config.RAG_TEMPLATE,
568
+ "k": app.state.config.TOP_K,
569
+ "r": app.state.config.RELEVANCE_THRESHOLD,
570
+ "hybrid": app.state.config.ENABLE_RAG_HYBRID_SEARCH,
571
+ }
572
+
573
+
574
+ class QuerySettingsForm(BaseModel):
575
+ k: Optional[int] = None
576
+ r: Optional[float] = None
577
+ template: Optional[str] = None
578
+ hybrid: Optional[bool] = None
579
+
580
+
581
+ @app.post("/query/settings/update")
582
+ async def update_query_settings(
583
+ form_data: QuerySettingsForm, user=Depends(get_admin_user)
584
+ ):
585
+ app.state.config.RAG_TEMPLATE = (
586
+ form_data.template if form_data.template else RAG_TEMPLATE
587
+ )
588
+ app.state.config.TOP_K = form_data.k if form_data.k else 4
589
+ app.state.config.RELEVANCE_THRESHOLD = form_data.r if form_data.r else 0.0
590
+ app.state.config.ENABLE_RAG_HYBRID_SEARCH = (
591
+ form_data.hybrid if form_data.hybrid else False
592
+ )
593
+ return {
594
+ "status": True,
595
+ "template": app.state.config.RAG_TEMPLATE,
596
+ "k": app.state.config.TOP_K,
597
+ "r": app.state.config.RELEVANCE_THRESHOLD,
598
+ "hybrid": app.state.config.ENABLE_RAG_HYBRID_SEARCH,
599
+ }
600
+
601
+
602
+ class QueryDocForm(BaseModel):
603
+ collection_name: str
604
+ query: str
605
+ k: Optional[int] = None
606
+ r: Optional[float] = None
607
+ hybrid: Optional[bool] = None
608
+
609
+
610
+ @app.post("/query/doc")
611
+ def query_doc_handler(
612
+ form_data: QueryDocForm,
613
+ user=Depends(get_verified_user),
614
+ ):
615
+ try:
616
+ if app.state.config.ENABLE_RAG_HYBRID_SEARCH:
617
+ return query_doc_with_hybrid_search(
618
+ collection_name=form_data.collection_name,
619
+ query=form_data.query,
620
+ embedding_function=app.state.EMBEDDING_FUNCTION,
621
+ k=form_data.k if form_data.k else app.state.config.TOP_K,
622
+ reranking_function=app.state.sentence_transformer_rf,
623
+ r=(
624
+ form_data.r if form_data.r else app.state.config.RELEVANCE_THRESHOLD
625
+ ),
626
+ )
627
+ else:
628
+ return query_doc(
629
+ collection_name=form_data.collection_name,
630
+ query=form_data.query,
631
+ embedding_function=app.state.EMBEDDING_FUNCTION,
632
+ k=form_data.k if form_data.k else app.state.config.TOP_K,
633
+ )
634
+ except Exception as e:
635
+ log.exception(e)
636
+ raise HTTPException(
637
+ status_code=status.HTTP_400_BAD_REQUEST,
638
+ detail=ERROR_MESSAGES.DEFAULT(e),
639
+ )
640
+
641
+
642
+ class QueryCollectionsForm(BaseModel):
643
+ collection_names: list[str]
644
+ query: str
645
+ k: Optional[int] = None
646
+ r: Optional[float] = None
647
+ hybrid: Optional[bool] = None
648
+
649
+
650
+ @app.post("/query/collection")
651
+ def query_collection_handler(
652
+ form_data: QueryCollectionsForm,
653
+ user=Depends(get_verified_user),
654
+ ):
655
+ try:
656
+ if app.state.config.ENABLE_RAG_HYBRID_SEARCH:
657
+ return query_collection_with_hybrid_search(
658
+ collection_names=form_data.collection_names,
659
+ query=form_data.query,
660
+ embedding_function=app.state.EMBEDDING_FUNCTION,
661
+ k=form_data.k if form_data.k else app.state.config.TOP_K,
662
+ reranking_function=app.state.sentence_transformer_rf,
663
+ r=(
664
+ form_data.r if form_data.r else app.state.config.RELEVANCE_THRESHOLD
665
+ ),
666
+ )
667
+ else:
668
+ return query_collection(
669
+ collection_names=form_data.collection_names,
670
+ query=form_data.query,
671
+ embedding_function=app.state.EMBEDDING_FUNCTION,
672
+ k=form_data.k if form_data.k else app.state.config.TOP_K,
673
+ )
674
+
675
+ except Exception as e:
676
+ log.exception(e)
677
+ raise HTTPException(
678
+ status_code=status.HTTP_400_BAD_REQUEST,
679
+ detail=ERROR_MESSAGES.DEFAULT(e),
680
+ )
681
+
682
+
683
+ @app.post("/youtube")
684
+ def store_youtube_video(form_data: UrlForm, user=Depends(get_verified_user)):
685
+ try:
686
+ loader = YoutubeLoader.from_youtube_url(
687
+ form_data.url,
688
+ add_video_info=True,
689
+ language=app.state.config.YOUTUBE_LOADER_LANGUAGE,
690
+ translation=app.state.YOUTUBE_LOADER_TRANSLATION,
691
+ )
692
+ data = loader.load()
693
+
694
+ collection_name = form_data.collection_name
695
+ if collection_name == "":
696
+ collection_name = calculate_sha256_string(form_data.url)[:63]
697
+
698
+ store_data_in_vector_db(data, collection_name, overwrite=True)
699
+ return {
700
+ "status": True,
701
+ "collection_name": collection_name,
702
+ "filename": form_data.url,
703
+ }
704
+ except Exception as e:
705
+ log.exception(e)
706
+ raise HTTPException(
707
+ status_code=status.HTTP_400_BAD_REQUEST,
708
+ detail=ERROR_MESSAGES.DEFAULT(e),
709
+ )
710
+
711
+
712
+ @app.post("/web")
713
+ def store_web(form_data: UrlForm, user=Depends(get_verified_user)):
714
+ # "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
715
+ try:
716
+ loader = get_web_loader(
717
+ form_data.url,
718
+ verify_ssl=app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION,
719
+ )
720
+ data = loader.load()
721
+
722
+ collection_name = form_data.collection_name
723
+ if collection_name == "":
724
+ collection_name = calculate_sha256_string(form_data.url)[:63]
725
+
726
+ store_data_in_vector_db(data, collection_name, overwrite=True)
727
+ return {
728
+ "status": True,
729
+ "collection_name": collection_name,
730
+ "filename": form_data.url,
731
+ }
732
+ except Exception as e:
733
+ log.exception(e)
734
+ raise HTTPException(
735
+ status_code=status.HTTP_400_BAD_REQUEST,
736
+ detail=ERROR_MESSAGES.DEFAULT(e),
737
+ )
738
+
739
+
740
+ def get_web_loader(url: Union[str, Sequence[str]], verify_ssl: bool = True):
741
+ # Check if the URL is valid
742
+ if not validate_url(url):
743
+ raise ValueError(ERROR_MESSAGES.INVALID_URL)
744
+ return SafeWebBaseLoader(
745
+ url,
746
+ verify_ssl=verify_ssl,
747
+ requests_per_second=RAG_WEB_SEARCH_CONCURRENT_REQUESTS,
748
+ continue_on_failure=True,
749
+ )
750
+
751
+
752
+ def validate_url(url: Union[str, Sequence[str]]):
753
+ if isinstance(url, str):
754
+ if isinstance(validators.url(url), validators.ValidationError):
755
+ raise ValueError(ERROR_MESSAGES.INVALID_URL)
756
+ if not ENABLE_RAG_LOCAL_WEB_FETCH:
757
+ # Local web fetch is disabled, filter out any URLs that resolve to private IP addresses
758
+ parsed_url = urllib.parse.urlparse(url)
759
+ # Get IPv4 and IPv6 addresses
760
+ ipv4_addresses, ipv6_addresses = resolve_hostname(parsed_url.hostname)
761
+ # Check if any of the resolved addresses are private
762
+ # This is technically still vulnerable to DNS rebinding attacks, as we don't control WebBaseLoader
763
+ for ip in ipv4_addresses:
764
+ if validators.ipv4(ip, private=True):
765
+ raise ValueError(ERROR_MESSAGES.INVALID_URL)
766
+ for ip in ipv6_addresses:
767
+ if validators.ipv6(ip, private=True):
768
+ raise ValueError(ERROR_MESSAGES.INVALID_URL)
769
+ return True
770
+ elif isinstance(url, Sequence):
771
+ return all(validate_url(u) for u in url)
772
+ else:
773
+ return False
774
+
775
+
776
+ def resolve_hostname(hostname):
777
+ # Get address information
778
+ addr_info = socket.getaddrinfo(hostname, None)
779
+
780
+ # Extract IP addresses from address information
781
+ ipv4_addresses = [info[4][0] for info in addr_info if info[0] == socket.AF_INET]
782
+ ipv6_addresses = [info[4][0] for info in addr_info if info[0] == socket.AF_INET6]
783
+
784
+ return ipv4_addresses, ipv6_addresses
785
+
786
+
787
+ def search_web(engine: str, query: str) -> list[SearchResult]:
788
+ """Search the web using a search engine and return the results as a list of SearchResult objects.
789
+ Will look for a search engine API key in environment variables in the following order:
790
+ - SEARXNG_QUERY_URL
791
+ - GOOGLE_PSE_API_KEY + GOOGLE_PSE_ENGINE_ID
792
+ - BRAVE_SEARCH_API_KEY
793
+ - SERPSTACK_API_KEY
794
+ - SERPER_API_KEY
795
+ - SERPLY_API_KEY
796
+ - TAVILY_API_KEY
797
+ Args:
798
+ query (str): The query to search for
799
+ """
800
+
801
+ # TODO: add playwright to search the web
802
+ if engine == "searxng":
803
+ if app.state.config.SEARXNG_QUERY_URL:
804
+ return search_searxng(
805
+ app.state.config.SEARXNG_QUERY_URL,
806
+ query,
807
+ app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
808
+ app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
809
+ )
810
+ else:
811
+ raise Exception("No SEARXNG_QUERY_URL found in environment variables")
812
+ elif engine == "google_pse":
813
+ if (
814
+ app.state.config.GOOGLE_PSE_API_KEY
815
+ and app.state.config.GOOGLE_PSE_ENGINE_ID
816
+ ):
817
+ return search_google_pse(
818
+ app.state.config.GOOGLE_PSE_API_KEY,
819
+ app.state.config.GOOGLE_PSE_ENGINE_ID,
820
+ query,
821
+ app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
822
+ app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
823
+ )
824
+ else:
825
+ raise Exception(
826
+ "No GOOGLE_PSE_API_KEY or GOOGLE_PSE_ENGINE_ID found in environment variables"
827
+ )
828
+ elif engine == "brave":
829
+ if app.state.config.BRAVE_SEARCH_API_KEY:
830
+ return search_brave(
831
+ app.state.config.BRAVE_SEARCH_API_KEY,
832
+ query,
833
+ app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
834
+ app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
835
+ )
836
+ else:
837
+ raise Exception("No BRAVE_SEARCH_API_KEY found in environment variables")
838
+ elif engine == "serpstack":
839
+ if app.state.config.SERPSTACK_API_KEY:
840
+ return search_serpstack(
841
+ app.state.config.SERPSTACK_API_KEY,
842
+ query,
843
+ app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
844
+ app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
845
+ https_enabled=app.state.config.SERPSTACK_HTTPS,
846
+ )
847
+ else:
848
+ raise Exception("No SERPSTACK_API_KEY found in environment variables")
849
+ elif engine == "serper":
850
+ if app.state.config.SERPER_API_KEY:
851
+ return search_serper(
852
+ app.state.config.SERPER_API_KEY,
853
+ query,
854
+ app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
855
+ app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
856
+ )
857
+ else:
858
+ raise Exception("No SERPER_API_KEY found in environment variables")
859
+ elif engine == "serply":
860
+ if app.state.config.SERPLY_API_KEY:
861
+ return search_serply(
862
+ app.state.config.SERPLY_API_KEY,
863
+ query,
864
+ app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
865
+ app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
866
+ )
867
+ else:
868
+ raise Exception("No SERPLY_API_KEY found in environment variables")
869
+ elif engine == "duckduckgo":
870
+ return search_duckduckgo(
871
+ query,
872
+ app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
873
+ app.state.config.RAG_WEB_SEARCH_DOMAIN_FILTER_LIST,
874
+ )
875
+ elif engine == "tavily":
876
+ if app.state.config.TAVILY_API_KEY:
877
+ return search_tavily(
878
+ app.state.config.TAVILY_API_KEY,
879
+ query,
880
+ app.state.config.RAG_WEB_SEARCH_RESULT_COUNT,
881
+ )
882
+ else:
883
+ raise Exception("No TAVILY_API_KEY found in environment variables")
884
+ elif engine == "jina":
885
+ return search_jina(query, app.state.config.RAG_WEB_SEARCH_RESULT_COUNT)
886
+ else:
887
+ raise Exception("No search engine API key found in environment variables")
888
+
889
+
890
+ @app.post("/web/search")
891
+ def store_web_search(form_data: SearchForm, user=Depends(get_verified_user)):
892
+ try:
893
+ logging.info(
894
+ f"trying to web search with {app.state.config.RAG_WEB_SEARCH_ENGINE, form_data.query}"
895
+ )
896
+ web_results = search_web(
897
+ app.state.config.RAG_WEB_SEARCH_ENGINE, form_data.query
898
+ )
899
+ except Exception as e:
900
+ log.exception(e)
901
+
902
+ print(e)
903
+ raise HTTPException(
904
+ status_code=status.HTTP_400_BAD_REQUEST,
905
+ detail=ERROR_MESSAGES.WEB_SEARCH_ERROR(e),
906
+ )
907
+
908
+ try:
909
+ urls = [result.link for result in web_results]
910
+ loader = get_web_loader(urls)
911
+ data = loader.load()
912
+
913
+ collection_name = form_data.collection_name
914
+ if collection_name == "":
915
+ collection_name = calculate_sha256_string(form_data.query)[:63]
916
+
917
+ store_data_in_vector_db(data, collection_name, overwrite=True)
918
+ return {
919
+ "status": True,
920
+ "collection_name": collection_name,
921
+ "filenames": urls,
922
+ }
923
+ except Exception as e:
924
+ log.exception(e)
925
+ raise HTTPException(
926
+ status_code=status.HTTP_400_BAD_REQUEST,
927
+ detail=ERROR_MESSAGES.DEFAULT(e),
928
+ )
929
+
930
+
931
+ def store_data_in_vector_db(
932
+ data, collection_name, metadata: Optional[dict] = None, overwrite: bool = False
933
+ ) -> bool:
934
+
935
+ text_splitter = RecursiveCharacterTextSplitter(
936
+ chunk_size=app.state.config.CHUNK_SIZE,
937
+ chunk_overlap=app.state.config.CHUNK_OVERLAP,
938
+ add_start_index=True,
939
+ )
940
+
941
+ docs = text_splitter.split_documents(data)
942
+
943
+ if len(docs) > 0:
944
+ log.info(f"store_data_in_vector_db {docs}")
945
+ return store_docs_in_vector_db(docs, collection_name, metadata, overwrite), None
946
+ else:
947
+ raise ValueError(ERROR_MESSAGES.EMPTY_CONTENT)
948
+
949
+
950
+ def store_text_in_vector_db(
951
+ text, metadata, collection_name, overwrite: bool = False
952
+ ) -> bool:
953
+ text_splitter = RecursiveCharacterTextSplitter(
954
+ chunk_size=app.state.config.CHUNK_SIZE,
955
+ chunk_overlap=app.state.config.CHUNK_OVERLAP,
956
+ add_start_index=True,
957
+ )
958
+ docs = text_splitter.create_documents([text], metadatas=[metadata])
959
+ return store_docs_in_vector_db(docs, collection_name, overwrite=overwrite)
960
+
961
+
962
+ def store_docs_in_vector_db(
963
+ docs, collection_name, metadata: Optional[dict] = None, overwrite: bool = False
964
+ ) -> bool:
965
+ log.info(f"store_docs_in_vector_db {docs} {collection_name}")
966
+
967
+ texts = [doc.page_content for doc in docs]
968
+ metadatas = [{**doc.metadata, **(metadata if metadata else {})} for doc in docs]
969
+
970
+ # ChromaDB does not like datetime formats
971
+ # for meta-data so convert them to string.
972
+ for metadata in metadatas:
973
+ for key, value in metadata.items():
974
+ if isinstance(value, datetime):
975
+ metadata[key] = str(value)
976
+
977
+ try:
978
+ if overwrite:
979
+ for collection in CHROMA_CLIENT.list_collections():
980
+ if collection_name == collection.name:
981
+ log.info(f"deleting existing collection {collection_name}")
982
+ CHROMA_CLIENT.delete_collection(name=collection_name)
983
+
984
+ collection = CHROMA_CLIENT.create_collection(name=collection_name)
985
+
986
+ embedding_func = get_embedding_function(
987
+ app.state.config.RAG_EMBEDDING_ENGINE,
988
+ app.state.config.RAG_EMBEDDING_MODEL,
989
+ app.state.sentence_transformer_ef,
990
+ app.state.config.OPENAI_API_KEY,
991
+ app.state.config.OPENAI_API_BASE_URL,
992
+ app.state.config.RAG_EMBEDDING_OPENAI_BATCH_SIZE,
993
+ )
994
+
995
+ embedding_texts = list(map(lambda x: x.replace("\n", " "), texts))
996
+ embeddings = embedding_func(embedding_texts)
997
+
998
+ for batch in create_batches(
999
+ api=CHROMA_CLIENT,
1000
+ ids=[str(uuid.uuid4()) for _ in texts],
1001
+ metadatas=metadatas,
1002
+ embeddings=embeddings,
1003
+ documents=texts,
1004
+ ):
1005
+ collection.add(*batch)
1006
+
1007
+ return True
1008
+ except Exception as e:
1009
+ if e.__class__.__name__ == "UniqueConstraintError":
1010
+ return True
1011
+
1012
+ log.exception(e)
1013
+
1014
+ return False
1015
+
1016
+
1017
+ class TikaLoader:
1018
+ def __init__(self, file_path, mime_type=None):
1019
+ self.file_path = file_path
1020
+ self.mime_type = mime_type
1021
+
1022
+ def load(self) -> list[Document]:
1023
+ with open(self.file_path, "rb") as f:
1024
+ data = f.read()
1025
+
1026
+ if self.mime_type is not None:
1027
+ headers = {"Content-Type": self.mime_type}
1028
+ else:
1029
+ headers = {}
1030
+
1031
+ endpoint = app.state.config.TIKA_SERVER_URL
1032
+ if not endpoint.endswith("/"):
1033
+ endpoint += "/"
1034
+ endpoint += "tika/text"
1035
+
1036
+ r = requests.put(endpoint, data=data, headers=headers)
1037
+
1038
+ if r.ok:
1039
+ raw_metadata = r.json()
1040
+ text = raw_metadata.get("X-TIKA:content", "<No text content found>")
1041
+
1042
+ if "Content-Type" in raw_metadata:
1043
+ headers["Content-Type"] = raw_metadata["Content-Type"]
1044
+
1045
+ log.info("Tika extracted text: %s", text)
1046
+
1047
+ return [Document(page_content=text, metadata=headers)]
1048
+ else:
1049
+ raise Exception(f"Error calling Tika: {r.reason}")
1050
+
1051
+
1052
+ def get_loader(filename: str, file_content_type: str, file_path: str):
1053
+ file_ext = filename.split(".")[-1].lower()
1054
+ known_type = True
1055
+
1056
+ known_source_ext = [
1057
+ "go",
1058
+ "py",
1059
+ "java",
1060
+ "sh",
1061
+ "bat",
1062
+ "ps1",
1063
+ "cmd",
1064
+ "js",
1065
+ "ts",
1066
+ "css",
1067
+ "cpp",
1068
+ "hpp",
1069
+ "h",
1070
+ "c",
1071
+ "cs",
1072
+ "sql",
1073
+ "log",
1074
+ "ini",
1075
+ "pl",
1076
+ "pm",
1077
+ "r",
1078
+ "dart",
1079
+ "dockerfile",
1080
+ "env",
1081
+ "php",
1082
+ "hs",
1083
+ "hsc",
1084
+ "lua",
1085
+ "nginxconf",
1086
+ "conf",
1087
+ "m",
1088
+ "mm",
1089
+ "plsql",
1090
+ "perl",
1091
+ "rb",
1092
+ "rs",
1093
+ "db2",
1094
+ "scala",
1095
+ "bash",
1096
+ "swift",
1097
+ "vue",
1098
+ "svelte",
1099
+ "msg",
1100
+ "ex",
1101
+ "exs",
1102
+ "erl",
1103
+ "tsx",
1104
+ "jsx",
1105
+ "hs",
1106
+ "lhs",
1107
+ ]
1108
+
1109
+ if (
1110
+ app.state.config.CONTENT_EXTRACTION_ENGINE == "tika"
1111
+ and app.state.config.TIKA_SERVER_URL
1112
+ ):
1113
+ if file_ext in known_source_ext or (
1114
+ file_content_type and file_content_type.find("text/") >= 0
1115
+ ):
1116
+ loader = TextLoader(file_path, autodetect_encoding=True)
1117
+ else:
1118
+ loader = TikaLoader(file_path, file_content_type)
1119
+ else:
1120
+ if file_ext == "pdf":
1121
+ loader = PyPDFLoader(
1122
+ file_path, extract_images=app.state.config.PDF_EXTRACT_IMAGES
1123
+ )
1124
+ elif file_ext == "csv":
1125
+ loader = CSVLoader(file_path)
1126
+ elif file_ext == "rst":
1127
+ loader = UnstructuredRSTLoader(file_path, mode="elements")
1128
+ elif file_ext == "xml":
1129
+ loader = UnstructuredXMLLoader(file_path)
1130
+ elif file_ext in ["htm", "html"]:
1131
+ loader = BSHTMLLoader(file_path, open_encoding="unicode_escape")
1132
+ elif file_ext == "md":
1133
+ loader = UnstructuredMarkdownLoader(file_path)
1134
+ elif file_content_type == "application/epub+zip":
1135
+ loader = UnstructuredEPubLoader(file_path)
1136
+ elif (
1137
+ file_content_type
1138
+ == "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
1139
+ or file_ext in ["doc", "docx"]
1140
+ ):
1141
+ loader = Docx2txtLoader(file_path)
1142
+ elif file_content_type in [
1143
+ "application/vnd.ms-excel",
1144
+ "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
1145
+ ] or file_ext in ["xls", "xlsx"]:
1146
+ loader = UnstructuredExcelLoader(file_path)
1147
+ elif file_content_type in [
1148
+ "application/vnd.ms-powerpoint",
1149
+ "application/vnd.openxmlformats-officedocument.presentationml.presentation",
1150
+ ] or file_ext in ["ppt", "pptx"]:
1151
+ loader = UnstructuredPowerPointLoader(file_path)
1152
+ elif file_ext == "msg":
1153
+ loader = OutlookMessageLoader(file_path)
1154
+ elif file_ext in known_source_ext or (
1155
+ file_content_type and file_content_type.find("text/") >= 0
1156
+ ):
1157
+ loader = TextLoader(file_path, autodetect_encoding=True)
1158
+ else:
1159
+ loader = TextLoader(file_path, autodetect_encoding=True)
1160
+ known_type = False
1161
+
1162
+ return loader, known_type
1163
+
1164
+
1165
+ @app.post("/doc")
1166
+ def store_doc(
1167
+ collection_name: Optional[str] = Form(None),
1168
+ file: UploadFile = File(...),
1169
+ user=Depends(get_verified_user),
1170
+ ):
1171
+ # "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
1172
+
1173
+ log.info(f"file.content_type: {file.content_type}")
1174
+ try:
1175
+ unsanitized_filename = file.filename
1176
+ filename = os.path.basename(unsanitized_filename)
1177
+
1178
+ file_path = f"{UPLOAD_DIR}/{filename}"
1179
+
1180
+ contents = file.file.read()
1181
+ with open(file_path, "wb") as f:
1182
+ f.write(contents)
1183
+ f.close()
1184
+
1185
+ f = open(file_path, "rb")
1186
+ if collection_name is None:
1187
+ collection_name = calculate_sha256(f)[:63]
1188
+ f.close()
1189
+
1190
+ loader, known_type = get_loader(filename, file.content_type, file_path)
1191
+ data = loader.load()
1192
+
1193
+ try:
1194
+ result = store_data_in_vector_db(data, collection_name)
1195
+
1196
+ if result:
1197
+ return {
1198
+ "status": True,
1199
+ "collection_name": collection_name,
1200
+ "filename": filename,
1201
+ "known_type": known_type,
1202
+ }
1203
+ except Exception as e:
1204
+ raise HTTPException(
1205
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
1206
+ detail=e,
1207
+ )
1208
+ except Exception as e:
1209
+ log.exception(e)
1210
+ if "No pandoc was found" in str(e):
1211
+ raise HTTPException(
1212
+ status_code=status.HTTP_400_BAD_REQUEST,
1213
+ detail=ERROR_MESSAGES.PANDOC_NOT_INSTALLED,
1214
+ )
1215
+ else:
1216
+ raise HTTPException(
1217
+ status_code=status.HTTP_400_BAD_REQUEST,
1218
+ detail=ERROR_MESSAGES.DEFAULT(e),
1219
+ )
1220
+
1221
+
1222
+ class ProcessDocForm(BaseModel):
1223
+ file_id: str
1224
+ collection_name: Optional[str] = None
1225
+
1226
+
1227
+ @app.post("/process/doc")
1228
+ def process_doc(
1229
+ form_data: ProcessDocForm,
1230
+ user=Depends(get_verified_user),
1231
+ ):
1232
+ try:
1233
+ file = Files.get_file_by_id(form_data.file_id)
1234
+ file_path = file.meta.get("path", f"{UPLOAD_DIR}/{file.filename}")
1235
+
1236
+ f = open(file_path, "rb")
1237
+
1238
+ collection_name = form_data.collection_name
1239
+ if collection_name is None:
1240
+ collection_name = calculate_sha256(f)[:63]
1241
+ f.close()
1242
+
1243
+ loader, known_type = get_loader(
1244
+ file.filename, file.meta.get("content_type"), file_path
1245
+ )
1246
+ data = loader.load()
1247
+
1248
+ try:
1249
+ result = store_data_in_vector_db(
1250
+ data,
1251
+ collection_name,
1252
+ {
1253
+ "file_id": form_data.file_id,
1254
+ "name": file.meta.get("name", file.filename),
1255
+ },
1256
+ )
1257
+
1258
+ if result:
1259
+ return {
1260
+ "status": True,
1261
+ "collection_name": collection_name,
1262
+ "known_type": known_type,
1263
+ "filename": file.meta.get("name", file.filename),
1264
+ }
1265
+ except Exception as e:
1266
+ raise HTTPException(
1267
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
1268
+ detail=e,
1269
+ )
1270
+ except Exception as e:
1271
+ log.exception(e)
1272
+ if "No pandoc was found" in str(e):
1273
+ raise HTTPException(
1274
+ status_code=status.HTTP_400_BAD_REQUEST,
1275
+ detail=ERROR_MESSAGES.PANDOC_NOT_INSTALLED,
1276
+ )
1277
+ else:
1278
+ raise HTTPException(
1279
+ status_code=status.HTTP_400_BAD_REQUEST,
1280
+ detail=ERROR_MESSAGES.DEFAULT(e),
1281
+ )
1282
+
1283
+
1284
+ class TextRAGForm(BaseModel):
1285
+ name: str
1286
+ content: str
1287
+ collection_name: Optional[str] = None
1288
+
1289
+
1290
+ @app.post("/text")
1291
+ def store_text(
1292
+ form_data: TextRAGForm,
1293
+ user=Depends(get_verified_user),
1294
+ ):
1295
+
1296
+ collection_name = form_data.collection_name
1297
+ if collection_name is None:
1298
+ collection_name = calculate_sha256_string(form_data.content)
1299
+
1300
+ result = store_text_in_vector_db(
1301
+ form_data.content,
1302
+ metadata={"name": form_data.name, "created_by": user.id},
1303
+ collection_name=collection_name,
1304
+ )
1305
+
1306
+ if result:
1307
+ return {"status": True, "collection_name": collection_name}
1308
+ else:
1309
+ raise HTTPException(
1310
+ status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
1311
+ detail=ERROR_MESSAGES.DEFAULT(),
1312
+ )
1313
+
1314
+
1315
+ @app.get("/scan")
1316
+ def scan_docs_dir(user=Depends(get_admin_user)):
1317
+ for path in Path(DOCS_DIR).rglob("./**/*"):
1318
+ try:
1319
+ if path.is_file() and not path.name.startswith("."):
1320
+ tags = extract_folders_after_data_docs(path)
1321
+ filename = path.name
1322
+ file_content_type = mimetypes.guess_type(path)
1323
+
1324
+ f = open(path, "rb")
1325
+ collection_name = calculate_sha256(f)[:63]
1326
+ f.close()
1327
+
1328
+ loader, known_type = get_loader(
1329
+ filename, file_content_type[0], str(path)
1330
+ )
1331
+ data = loader.load()
1332
+
1333
+ try:
1334
+ result = store_data_in_vector_db(data, collection_name)
1335
+
1336
+ if result:
1337
+ sanitized_filename = sanitize_filename(filename)
1338
+ doc = Documents.get_doc_by_name(sanitized_filename)
1339
+
1340
+ if doc is None:
1341
+ doc = Documents.insert_new_doc(
1342
+ user.id,
1343
+ DocumentForm(
1344
+ **{
1345
+ "name": sanitized_filename,
1346
+ "title": filename,
1347
+ "collection_name": collection_name,
1348
+ "filename": filename,
1349
+ "content": (
1350
+ json.dumps(
1351
+ {
1352
+ "tags": list(
1353
+ map(
1354
+ lambda name: {"name": name},
1355
+ tags,
1356
+ )
1357
+ )
1358
+ }
1359
+ )
1360
+ if len(tags)
1361
+ else "{}"
1362
+ ),
1363
+ }
1364
+ ),
1365
+ )
1366
+ except Exception as e:
1367
+ log.exception(e)
1368
+ pass
1369
+
1370
+ except Exception as e:
1371
+ log.exception(e)
1372
+
1373
+ return True
1374
+
1375
+
1376
+ @app.get("/reset/db")
1377
+ def reset_vector_db(user=Depends(get_admin_user)):
1378
+ CHROMA_CLIENT.reset()
1379
+
1380
+
1381
+ @app.get("/reset/uploads")
1382
+ def reset_upload_dir(user=Depends(get_admin_user)) -> bool:
1383
+ folder = f"{UPLOAD_DIR}"
1384
+ try:
1385
+ # Check if the directory exists
1386
+ if os.path.exists(folder):
1387
+ # Iterate over all the files and directories in the specified directory
1388
+ for filename in os.listdir(folder):
1389
+ file_path = os.path.join(folder, filename)
1390
+ try:
1391
+ if os.path.isfile(file_path) or os.path.islink(file_path):
1392
+ os.unlink(file_path) # Remove the file or link
1393
+ elif os.path.isdir(file_path):
1394
+ shutil.rmtree(file_path) # Remove the directory
1395
+ except Exception as e:
1396
+ print(f"Failed to delete {file_path}. Reason: {e}")
1397
+ else:
1398
+ print(f"The directory {folder} does not exist")
1399
+ except Exception as e:
1400
+ print(f"Failed to process the directory {folder}. Reason: {e}")
1401
+
1402
+ return True
1403
+
1404
+
1405
+ @app.get("/reset")
1406
+ def reset(user=Depends(get_admin_user)) -> bool:
1407
+ folder = f"{UPLOAD_DIR}"
1408
+ for filename in os.listdir(folder):
1409
+ file_path = os.path.join(folder, filename)
1410
+ try:
1411
+ if os.path.isfile(file_path) or os.path.islink(file_path):
1412
+ os.unlink(file_path)
1413
+ elif os.path.isdir(file_path):
1414
+ shutil.rmtree(file_path)
1415
+ except Exception as e:
1416
+ log.error("Failed to delete %s. Reason: %s" % (file_path, e))
1417
+
1418
+ try:
1419
+ CHROMA_CLIENT.reset()
1420
+ except Exception as e:
1421
+ log.exception(e)
1422
+
1423
+ return True
1424
+
1425
+
1426
+ class SafeWebBaseLoader(WebBaseLoader):
1427
+ """WebBaseLoader with enhanced error handling for URLs."""
1428
+
1429
+ def lazy_load(self) -> Iterator[Document]:
1430
+ """Lazy load text from the url(s) in web_path with error handling."""
1431
+ for path in self.web_paths:
1432
+ try:
1433
+ soup = self._scrape(path, bs_kwargs=self.bs_kwargs)
1434
+ text = soup.get_text(**self.bs_get_text_kwargs)
1435
+
1436
+ # Build metadata
1437
+ metadata = {"source": path}
1438
+ if title := soup.find("title"):
1439
+ metadata["title"] = title.get_text()
1440
+ if description := soup.find("meta", attrs={"name": "description"}):
1441
+ metadata["description"] = description.get(
1442
+ "content", "No description found."
1443
+ )
1444
+ if html := soup.find("html"):
1445
+ metadata["language"] = html.get("lang", "No language found.")
1446
+
1447
+ yield Document(page_content=text, metadata=metadata)
1448
+ except Exception as e:
1449
+ # Log the error and continue with the next URL
1450
+ log.error(f"Error loading {path}: {e}")
1451
+
1452
+
1453
+ if ENV == "dev":
1454
+
1455
+ @app.get("/ef")
1456
+ async def get_embeddings():
1457
+ return {"result": app.state.EMBEDDING_FUNCTION("hello world")}
1458
+
1459
+ @app.get("/ef/{text}")
1460
+ async def get_embeddings_text(text: str):
1461
+ return {"result": app.state.EMBEDDING_FUNCTION(text)}
backend/apps/rag/search/brave.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import Optional
3
+ import requests
4
+
5
+ from apps.rag.search.main import SearchResult, get_filtered_results
6
+ from config import SRC_LOG_LEVELS
7
+
8
+ log = logging.getLogger(__name__)
9
+ log.setLevel(SRC_LOG_LEVELS["RAG"])
10
+
11
+
12
+ def search_brave(
13
+ api_key: str, query: str, count: int, filter_list: Optional[list[str]] = None
14
+ ) -> list[SearchResult]:
15
+ """Search using Brave's Search API and return the results as a list of SearchResult objects.
16
+
17
+ Args:
18
+ api_key (str): A Brave Search API key
19
+ query (str): The query to search for
20
+ """
21
+ url = "https://api.search.brave.com/res/v1/web/search"
22
+ headers = {
23
+ "Accept": "application/json",
24
+ "Accept-Encoding": "gzip",
25
+ "X-Subscription-Token": api_key,
26
+ }
27
+ params = {"q": query, "count": count}
28
+
29
+ response = requests.get(url, headers=headers, params=params)
30
+ response.raise_for_status()
31
+
32
+ json_response = response.json()
33
+ results = json_response.get("web", {}).get("results", [])
34
+ if filter_list:
35
+ results = get_filtered_results(results, filter_list)
36
+
37
+ return [
38
+ SearchResult(
39
+ link=result["url"], title=result.get("title"), snippet=result.get("snippet")
40
+ )
41
+ for result in results[:count]
42
+ ]
backend/apps/rag/search/duckduckgo.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ from typing import Optional
3
+ from apps.rag.search.main import SearchResult, get_filtered_results
4
+ from duckduckgo_search import DDGS
5
+ from config import SRC_LOG_LEVELS
6
+
7
+ log = logging.getLogger(__name__)
8
+ log.setLevel(SRC_LOG_LEVELS["RAG"])
9
+
10
+
11
+ def search_duckduckgo(
12
+ query: str, count: int, filter_list: Optional[list[str]] = None
13
+ ) -> list[SearchResult]:
14
+ """
15
+ Search using DuckDuckGo's Search API and return the results as a list of SearchResult objects.
16
+ Args:
17
+ query (str): The query to search for
18
+ count (int): The number of results to return
19
+
20
+ Returns:
21
+ list[SearchResult]: A list of search results
22
+ """
23
+ # Use the DDGS context manager to create a DDGS object
24
+ with DDGS() as ddgs:
25
+ # Use the ddgs.text() method to perform the search
26
+ ddgs_gen = ddgs.text(
27
+ query, safesearch="moderate", max_results=count, backend="api"
28
+ )
29
+ # Check if there are search results
30
+ if ddgs_gen:
31
+ # Convert the search results into a list
32
+ search_results = [r for r in ddgs_gen]
33
+
34
+ # Create an empty list to store the SearchResult objects
35
+ results = []
36
+ # Iterate over each search result
37
+ for result in search_results:
38
+ # Create a SearchResult object and append it to the results list
39
+ results.append(
40
+ SearchResult(
41
+ link=result["href"],
42
+ title=result.get("title"),
43
+ snippet=result.get("body"),
44
+ )
45
+ )
46
+ if filter_list:
47
+ results = get_filtered_results(results, filter_list)
48
+ # Return the list of search results
49
+ return results
backend/apps/rag/search/google_pse.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ from typing import Optional
4
+ import requests
5
+
6
+ from apps.rag.search.main import SearchResult, get_filtered_results
7
+ from config import SRC_LOG_LEVELS
8
+
9
+ log = logging.getLogger(__name__)
10
+ log.setLevel(SRC_LOG_LEVELS["RAG"])
11
+
12
+
13
+ def search_google_pse(
14
+ api_key: str,
15
+ search_engine_id: str,
16
+ query: str,
17
+ count: int,
18
+ filter_list: Optional[list[str]] = None,
19
+ ) -> list[SearchResult]:
20
+ """Search using Google's Programmable Search Engine API and return the results as a list of SearchResult objects.
21
+
22
+ Args:
23
+ api_key (str): A Programmable Search Engine API key
24
+ search_engine_id (str): A Programmable Search Engine ID
25
+ query (str): The query to search for
26
+ """
27
+ url = "https://www.googleapis.com/customsearch/v1"
28
+
29
+ headers = {"Content-Type": "application/json"}
30
+ params = {
31
+ "cx": search_engine_id,
32
+ "q": query,
33
+ "key": api_key,
34
+ "num": count,
35
+ }
36
+
37
+ response = requests.request("GET", url, headers=headers, params=params)
38
+ response.raise_for_status()
39
+
40
+ json_response = response.json()
41
+ results = json_response.get("items", [])
42
+ if filter_list:
43
+ results = get_filtered_results(results, filter_list)
44
+ return [
45
+ SearchResult(
46
+ link=result["link"],
47
+ title=result.get("title"),
48
+ snippet=result.get("snippet"),
49
+ )
50
+ for result in results
51
+ ]
backend/apps/rag/search/jina_search.py ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import requests
3
+ from yarl import URL
4
+
5
+ from apps.rag.search.main import SearchResult
6
+ from config import SRC_LOG_LEVELS
7
+
8
+ log = logging.getLogger(__name__)
9
+ log.setLevel(SRC_LOG_LEVELS["RAG"])
10
+
11
+
12
+ def search_jina(query: str, count: int) -> list[SearchResult]:
13
+ """
14
+ Search using Jina's Search API and return the results as a list of SearchResult objects.
15
+ Args:
16
+ query (str): The query to search for
17
+ count (int): The number of results to return
18
+
19
+ Returns:
20
+ list[SearchResult]: A list of search results
21
+ """
22
+ jina_search_endpoint = "https://s.jina.ai/"
23
+ headers = {
24
+ "Accept": "application/json",
25
+ }
26
+ url = str(URL(jina_search_endpoint + query))
27
+ response = requests.get(url, headers=headers)
28
+ response.raise_for_status()
29
+ data = response.json()
30
+
31
+ results = []
32
+ for result in data["data"][:count]:
33
+ results.append(
34
+ SearchResult(
35
+ link=result["url"],
36
+ title=result.get("title"),
37
+ snippet=result.get("content"),
38
+ )
39
+ )
40
+
41
+ return results
backend/apps/rag/search/main.py ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+ from urllib.parse import urlparse
3
+ from pydantic import BaseModel
4
+
5
+
6
+ def get_filtered_results(results, filter_list):
7
+ if not filter_list:
8
+ return results
9
+ filtered_results = []
10
+ for result in results:
11
+ domain = urlparse(result["url"]).netloc
12
+ if any(domain.endswith(filtered_domain) for filtered_domain in filter_list):
13
+ filtered_results.append(result)
14
+ return filtered_results
15
+
16
+
17
+ class SearchResult(BaseModel):
18
+ link: str
19
+ title: Optional[str]
20
+ snippet: Optional[str]
backend/apps/rag/search/searxng.py ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import requests
3
+
4
+ from typing import Optional
5
+
6
+ from apps.rag.search.main import SearchResult, get_filtered_results
7
+ from config import SRC_LOG_LEVELS
8
+
9
+ log = logging.getLogger(__name__)
10
+ log.setLevel(SRC_LOG_LEVELS["RAG"])
11
+
12
+
13
+ def search_searxng(
14
+ query_url: str,
15
+ query: str,
16
+ count: int,
17
+ filter_list: Optional[list[str]] = None,
18
+ **kwargs,
19
+ ) -> list[SearchResult]:
20
+ """
21
+ Search a SearXNG instance for a given query and return the results as a list of SearchResult objects.
22
+
23
+ The function allows passing additional parameters such as language or time_range to tailor the search result.
24
+
25
+ Args:
26
+ query_url (str): The base URL of the SearXNG server.
27
+ query (str): The search term or question to find in the SearXNG database.
28
+ count (int): The maximum number of results to retrieve from the search.
29
+
30
+ Keyword Args:
31
+ language (str): Language filter for the search results; e.g., "en-US". Defaults to an empty string.
32
+ safesearch (int): Safe search filter for safer web results; 0 = off, 1 = moderate, 2 = strict. Defaults to 1 (moderate).
33
+ time_range (str): Time range for filtering results by date; e.g., "2023-04-05..today" or "all-time". Defaults to ''.
34
+ categories: (Optional[list[str]]): Specific categories within which the search should be performed, defaulting to an empty string if not provided.
35
+
36
+ Returns:
37
+ list[SearchResult]: A list of SearchResults sorted by relevance score in descending order.
38
+
39
+ Raise:
40
+ requests.exceptions.RequestException: If a request error occurs during the search process.
41
+ """
42
+
43
+ # Default values for optional parameters are provided as empty strings or None when not specified.
44
+ language = kwargs.get("language", "en-US")
45
+ safesearch = kwargs.get("safesearch", "1")
46
+ time_range = kwargs.get("time_range", "")
47
+ categories = "".join(kwargs.get("categories", []))
48
+
49
+ params = {
50
+ "q": query,
51
+ "format": "json",
52
+ "pageno": 1,
53
+ "safesearch": safesearch,
54
+ "language": language,
55
+ "time_range": time_range,
56
+ "categories": categories,
57
+ "theme": "simple",
58
+ "image_proxy": 0,
59
+ }
60
+
61
+ # Legacy query format
62
+ if "<query>" in query_url:
63
+ # Strip all query parameters from the URL
64
+ query_url = query_url.split("?")[0]
65
+
66
+ log.debug(f"searching {query_url}")
67
+
68
+ response = requests.get(
69
+ query_url,
70
+ headers={
71
+ "User-Agent": "Open WebUI (https://github.com/open-webui/open-webui) RAG Bot",
72
+ "Accept": "text/html",
73
+ "Accept-Encoding": "gzip, deflate",
74
+ "Accept-Language": "en-US,en;q=0.5",
75
+ "Connection": "keep-alive",
76
+ },
77
+ params=params,
78
+ )
79
+
80
+ response.raise_for_status() # Raise an exception for HTTP errors.
81
+
82
+ json_response = response.json()
83
+ results = json_response.get("results", [])
84
+ sorted_results = sorted(results, key=lambda x: x.get("score", 0), reverse=True)
85
+ if filter_list:
86
+ sorted_results = get_filtered_results(sorted_results, filter_list)
87
+ return [
88
+ SearchResult(
89
+ link=result["url"], title=result.get("title"), snippet=result.get("content")
90
+ )
91
+ for result in sorted_results[:count]
92
+ ]
backend/apps/rag/search/serper.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ from typing import Optional
4
+ import requests
5
+
6
+ from apps.rag.search.main import SearchResult, get_filtered_results
7
+ from config import SRC_LOG_LEVELS
8
+
9
+ log = logging.getLogger(__name__)
10
+ log.setLevel(SRC_LOG_LEVELS["RAG"])
11
+
12
+
13
+ def search_serper(
14
+ api_key: str, query: str, count: int, filter_list: Optional[list[str]] = None
15
+ ) -> list[SearchResult]:
16
+ """Search using serper.dev's API and return the results as a list of SearchResult objects.
17
+
18
+ Args:
19
+ api_key (str): A serper.dev API key
20
+ query (str): The query to search for
21
+ """
22
+ url = "https://google.serper.dev/search"
23
+
24
+ payload = json.dumps({"q": query})
25
+ headers = {"X-API-KEY": api_key, "Content-Type": "application/json"}
26
+
27
+ response = requests.request("POST", url, headers=headers, data=payload)
28
+ response.raise_for_status()
29
+
30
+ json_response = response.json()
31
+ results = sorted(
32
+ json_response.get("organic", []), key=lambda x: x.get("position", 0)
33
+ )
34
+ if filter_list:
35
+ results = get_filtered_results(results, filter_list)
36
+ return [
37
+ SearchResult(
38
+ link=result["link"],
39
+ title=result.get("title"),
40
+ snippet=result.get("description"),
41
+ )
42
+ for result in results[:count]
43
+ ]
backend/apps/rag/search/serply.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ from typing import Optional
4
+ import requests
5
+ from urllib.parse import urlencode
6
+
7
+ from apps.rag.search.main import SearchResult, get_filtered_results
8
+ from config import SRC_LOG_LEVELS
9
+
10
+ log = logging.getLogger(__name__)
11
+ log.setLevel(SRC_LOG_LEVELS["RAG"])
12
+
13
+
14
+ def search_serply(
15
+ api_key: str,
16
+ query: str,
17
+ count: int,
18
+ hl: str = "us",
19
+ limit: int = 10,
20
+ device_type: str = "desktop",
21
+ proxy_location: str = "US",
22
+ filter_list: Optional[list[str]] = None,
23
+ ) -> list[SearchResult]:
24
+ """Search using serper.dev's API and return the results as a list of SearchResult objects.
25
+
26
+ Args:
27
+ api_key (str): A serply.io API key
28
+ query (str): The query to search for
29
+ hl (str): Host Language code to display results in (reference https://developers.google.com/custom-search/docs/xml_results?hl=en#wsInterfaceLanguages)
30
+ limit (int): The maximum number of results to return [10-100, defaults to 10]
31
+ """
32
+ log.info("Searching with Serply")
33
+
34
+ url = "https://api.serply.io/v1/search/"
35
+
36
+ query_payload = {
37
+ "q": query,
38
+ "language": "en",
39
+ "num": limit,
40
+ "gl": proxy_location.upper(),
41
+ "hl": hl.lower(),
42
+ }
43
+
44
+ url = f"{url}{urlencode(query_payload)}"
45
+ headers = {
46
+ "X-API-KEY": api_key,
47
+ "X-User-Agent": device_type,
48
+ "User-Agent": "open-webui",
49
+ "X-Proxy-Location": proxy_location,
50
+ }
51
+
52
+ response = requests.request("GET", url, headers=headers)
53
+ response.raise_for_status()
54
+
55
+ json_response = response.json()
56
+ log.info(f"results from serply search: {json_response}")
57
+
58
+ results = sorted(
59
+ json_response.get("results", []), key=lambda x: x.get("realPosition", 0)
60
+ )
61
+ if filter_list:
62
+ results = get_filtered_results(results, filter_list)
63
+ return [
64
+ SearchResult(
65
+ link=result["link"],
66
+ title=result.get("title"),
67
+ snippet=result.get("description"),
68
+ )
69
+ for result in results[:count]
70
+ ]
backend/apps/rag/search/serpstack.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import logging
3
+ from typing import Optional
4
+ import requests
5
+
6
+ from apps.rag.search.main import SearchResult, get_filtered_results
7
+ from config import SRC_LOG_LEVELS
8
+
9
+ log = logging.getLogger(__name__)
10
+ log.setLevel(SRC_LOG_LEVELS["RAG"])
11
+
12
+
13
+ def search_serpstack(
14
+ api_key: str,
15
+ query: str,
16
+ count: int,
17
+ filter_list: Optional[list[str]] = None,
18
+ https_enabled: bool = True,
19
+ ) -> list[SearchResult]:
20
+ """Search using serpstack.com's and return the results as a list of SearchResult objects.
21
+
22
+ Args:
23
+ api_key (str): A serpstack.com API key
24
+ query (str): The query to search for
25
+ https_enabled (bool): Whether to use HTTPS or HTTP for the API request
26
+ """
27
+ url = f"{'https' if https_enabled else 'http'}://api.serpstack.com/search"
28
+
29
+ headers = {"Content-Type": "application/json"}
30
+ params = {
31
+ "access_key": api_key,
32
+ "query": query,
33
+ }
34
+
35
+ response = requests.request("POST", url, headers=headers, params=params)
36
+ response.raise_for_status()
37
+
38
+ json_response = response.json()
39
+ results = sorted(
40
+ json_response.get("organic_results", []), key=lambda x: x.get("position", 0)
41
+ )
42
+ if filter_list:
43
+ results = get_filtered_results(results, filter_list)
44
+ return [
45
+ SearchResult(
46
+ link=result["url"], title=result.get("title"), snippet=result.get("snippet")
47
+ )
48
+ for result in results[:count]
49
+ ]