Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2407d9b905 | ||
|
|
25d9a728f4 | ||
|
|
103688936e | ||
|
|
ac73f97604 | ||
|
|
0d09571ca2 | ||
|
|
5b4409814b | ||
|
|
8cca648efa | ||
|
|
a8222e391b | ||
|
|
dca7ce9420 | ||
|
|
bcd5783752 | ||
|
|
12bd04d24d | ||
|
|
2bb6063dcb | ||
|
|
4d7c8b4a6a | ||
|
|
40617b9e0e | ||
|
|
52030a241c | ||
|
|
3d6605bbfd | ||
|
|
a60b0a108a | ||
|
|
48635ced35 | ||
|
|
f4dde86b36 | ||
|
|
fcc1e2729c | ||
|
|
e7c7c65227 | ||
|
|
b2d1aa3c6e | ||
|
|
24767bb0fa | ||
|
|
c000188728 | ||
|
|
db4adc0e89 | ||
|
|
cf08d34879 | ||
|
|
d2fdf6999b | ||
|
|
d9c8a2508f | ||
|
|
df2428b356 | ||
|
|
e39ce16a86 | ||
|
|
d67cf5d9f2 | ||
|
|
688bfac4ba | ||
|
|
7c2cb5899c | ||
|
|
b16ad094be | ||
|
|
d5715cec6f | ||
|
|
c7caa268ce | ||
|
|
de8e8af989 | ||
|
|
ddc88d615c | ||
|
|
7644d66902 | ||
|
|
177788540b | ||
|
|
65a9a7eae0 | ||
|
|
804340ee26 | ||
|
|
937f97d7d6 | ||
|
|
f6637cc78e | ||
|
|
29cd1bc739 | ||
|
|
31485835a7 | ||
|
|
e4b6855984 | ||
|
|
bbd3e38e25 | ||
|
|
b29d5b80cd | ||
|
|
edf7a3d142 | ||
|
|
8b425a6295 | ||
|
|
d42e3fce4a | ||
|
|
58cc57e8a4 | ||
|
|
d3a952877a | ||
|
|
07357afcf6 | ||
|
|
ceb4948a28 | ||
|
|
86a8eb1023 | ||
|
|
dced9e4094 | ||
|
|
803b2e35be | ||
|
|
23a9731899 | ||
|
|
4267e22d4a | ||
|
|
e3207f35d7 | ||
|
|
85264e76de | ||
|
|
1dc8056d84 | ||
|
|
853c14b4c2 | ||
|
|
01dba25466 | ||
|
|
9c3f54cf1c | ||
|
|
f4047eea77 | ||
|
|
0583847943 | ||
|
|
4b22aa819c | ||
|
|
630cea105e | ||
|
|
c61698efcf | ||
|
|
a37d411dcf | ||
|
|
eacec793e9 | ||
|
|
0e46f8091f | ||
|
|
7b9dc69362 | ||
|
|
0a16af4e96 | ||
|
|
24e696e341 | ||
|
|
0ea421ea20 | ||
|
|
3da6049a4a | ||
|
|
3839f18bb1 | ||
|
|
2b0e90c032 | ||
|
|
3a360e441e | ||
|
|
a463e58de6 | ||
|
|
7a59cc9186 | ||
|
|
ff6946c230 | ||
|
|
3ff773c199 | ||
|
|
8048d4ac39 | ||
|
|
8d7319441e | ||
|
|
d98a60fbbb | ||
|
|
093af754e7 | ||
|
|
fa1590df57 | ||
|
|
9e7ec0eb1e | ||
|
|
5051bfe7ab | ||
|
|
1db8dec4f5 | ||
|
|
dafedf5675 | ||
|
|
37a3de0703 | ||
|
|
72b25ab78b | ||
|
|
fbff4e19de | ||
|
|
2777bab148 | ||
|
|
4ec70e3d46 | ||
|
|
43b2eca418 | ||
|
|
99f7d1b62b | ||
|
|
62a5db7719 | ||
|
|
278a4edd0b | ||
|
|
279e3e970f | ||
|
|
88a5b5ff4c | ||
|
|
c159a1a120 | ||
|
|
1decefbe59 | ||
|
|
28157b4f8c | ||
|
|
e013df19f9 | ||
|
|
486f953ba2 | ||
|
|
407dc9a401 | ||
|
|
9fb2c9c86d | ||
|
|
60b8cfb9fa | ||
|
|
5a66f69460 | ||
|
|
578f116ebb | ||
|
|
d3b5ba8472 | ||
|
|
3e28c46026 | ||
|
|
71d7ba6c07 | ||
|
|
581c0f137e | ||
|
|
f2e78d7940 | ||
|
|
c821c3ecb0 | ||
|
|
b3de3295d6 | ||
|
|
0952772705 | ||
|
|
c0189e43ad | ||
|
|
8fad4fb264 | ||
|
|
e9cab818f8 | ||
|
|
3523cea8cc | ||
|
|
01002042a8 | ||
|
|
f81f3b3a02 | ||
|
|
99ee1a2702 | ||
|
|
7ede54ee0a | ||
|
|
e96d139180 | ||
|
|
e6da38464b | ||
|
|
1e9abe6d8c | ||
|
|
61af00d0a6 | ||
|
|
bb6864dd12 | ||
|
|
1404fd9fbd | ||
|
|
02479425a5 | ||
|
|
cd762db9bf | ||
|
|
6663fc3a6c | ||
|
|
67db71f140 | ||
|
|
aa94359f74 | ||
|
|
9726c0b7ee | ||
|
|
449f0c155b | ||
|
|
48f0992300 | ||
|
|
492bcf9d26 | ||
|
|
bbfe456f90 | ||
|
|
774140ae0f | ||
|
|
5590ad438f | ||
|
|
9eea1aff10 | ||
|
|
1a15a62b73 | ||
|
|
efcf6db687 | ||
|
|
66f00ce4bf | ||
|
|
d720e027ad | ||
|
|
f46837fd10 | ||
|
|
1477f14827 | ||
|
|
094a16ab49 | ||
|
|
86011e40be | ||
|
|
4451f86eb0 | ||
|
|
8f51c11bc2 | ||
|
|
01f438c3fe | ||
|
|
1f91e5d3c6 | ||
|
|
faf01bdeac | ||
|
|
bb21bf5239 | ||
|
|
919d65f36f | ||
|
|
19e82ace23 | ||
|
|
98159dbcae | ||
|
|
ba972ecd52 | ||
|
|
d2d23f4abd | ||
|
|
45180e829a | ||
|
|
cd02ff2e07 | ||
|
|
39fe385017 | ||
|
|
7452b87877 | ||
|
|
45d9a720b9 | ||
|
|
7fcc545672 | ||
|
|
5e1f4fa0ff | ||
|
|
efebf4d3a0 | ||
|
|
e304ca5bd5 | ||
|
|
8eb5807c5f | ||
|
|
7670543a39 | ||
|
|
ed926c8f26 | ||
|
|
b3a95f40fc | ||
|
|
96643f5b6d | ||
|
|
575db66295 | ||
|
|
47ec443728 | ||
|
|
d6f709574e | ||
|
|
4bc77b544e | ||
|
|
be93081bd7 | ||
|
|
70d0477418 | ||
|
|
f592748011 | ||
|
|
8a157578f4 | ||
|
|
8a1f321fd4 | ||
|
|
f97f21bf3a | ||
|
|
a651598d19 | ||
|
|
68d42ef850 | ||
|
|
979ec71522 | ||
|
|
6d0f757848 | ||
|
|
dc9445c4ec | ||
|
|
901c997054 | ||
|
|
99b88c3024 | ||
|
|
094a82b264 | ||
|
|
99604fd644 | ||
|
|
33ecc405cb | ||
|
|
ad49435a94 | ||
|
|
282a884fad | ||
|
|
d7363fd65f | ||
|
|
f23eb2a31c | ||
|
|
ccd2a0be5b | ||
|
|
47560d4d72 | ||
|
|
7f0c50f445 | ||
|
|
bed6aa63e1 | ||
|
|
6a109e972e | ||
|
|
2387877dae | ||
|
|
40f60c163d | ||
|
|
28c1de237b | ||
|
|
04bd09d027 | ||
|
|
35e8c77025 | ||
|
|
ffd9e9cbe7 | ||
|
|
8f5843c8bc | ||
|
|
397421ce0b | ||
|
|
0dc6220ae6 | ||
|
|
8ae99ad7bb | ||
|
|
fe4b7621b3 | ||
|
|
3da22af859 | ||
|
|
cb1445086e | ||
|
|
9ba424e18a | ||
|
|
dfc9412117 | ||
|
|
43aa23ea77 | ||
|
|
286896b941 | ||
|
|
b810868239 | ||
|
|
0b59aa940e | ||
|
|
f1c28455ad | ||
|
|
daa4b3284f | ||
|
|
72023f4d03 | ||
|
|
313c54a4d1 | ||
|
|
c82183f985 | ||
|
|
84fe62d557 | ||
|
|
43234c3c4d | ||
|
|
9e2d8470d4 | ||
|
|
057533f9cc | ||
|
|
e277dba8fe | ||
|
|
4525ac687b | ||
|
|
53f1caf91f | ||
|
|
7dd5c957cf | ||
|
|
a1e62ab422 | ||
|
|
1a42e96a3b | ||
|
|
13fe78428b | ||
|
|
50705f926e | ||
|
|
709258bbb5 | ||
|
|
d303f0351d | ||
|
|
82ed9b0a97 | ||
|
|
e13f1738d4 | ||
|
|
b43acc2b3d | ||
|
|
3e8d3b08fa | ||
|
|
c134de8799 | ||
|
|
ad98d4300b | ||
|
|
115231c0e5 | ||
|
|
72168b1586 | ||
|
|
93205d4320 | ||
|
|
64b6ac4c1f | ||
|
|
28faaa23c4 | ||
|
|
2ed9896dea | ||
|
|
84fd0e4152 | ||
|
|
7fb0228ac8 | ||
|
|
0845b7ffe5 | ||
|
|
55b6a82cd5 | ||
|
|
ff55ca4d75 | ||
|
|
2011e5711d | ||
|
|
e7d9755d97 | ||
|
|
20101579e0 | ||
|
|
8a745b9bbf | ||
|
|
2cb87a71f7 | ||
|
|
86a3e0a0b8 | ||
|
|
37b8ea3ab2 | ||
|
|
4cca1829c2 | ||
|
|
230e21b10c | ||
|
|
dd3cd4ac4f | ||
|
|
f0c2d47b24 | ||
|
|
5fa502e419 | ||
|
|
5a2fafceae | ||
|
|
b5ab9634e8 | ||
|
|
e289e02193 | ||
|
|
e966f54001 | ||
|
|
c11f02662f | ||
|
|
23575825a1 | ||
|
|
1e67035bd3 | ||
|
|
85077d198b | ||
|
|
7f17b31c12 | ||
|
|
01e54dae94 | ||
|
|
47cde38369 | ||
|
|
4616997e6a | ||
|
|
1aba7accbf | ||
|
|
32753326fa | ||
|
|
966e244e33 | ||
|
|
0c5950fb60 | ||
|
|
1d3c656286 | ||
|
|
74b1c80132 | ||
|
|
7aa41d5d0c | ||
|
|
4c30f22444 | ||
|
|
6af94ae8f3 | ||
|
|
2625cd8719 | ||
|
|
f91da291d9 | ||
|
|
5543f30c49 | ||
|
|
06666cb148 | ||
|
|
df314fda1d | ||
|
|
f758bf74c2 | ||
|
|
357b57e1d6 | ||
|
|
a10e038fff | ||
|
|
d8c4dd6f79 | ||
|
|
7ace997c53 | ||
|
|
62506b1955 | ||
|
|
53c9c48387 | ||
|
|
2df4e7207b | ||
|
|
f890fe6901 | ||
|
|
438e5d966f | ||
|
|
17cc3b7d72 | ||
|
|
d89c5b6c30 | ||
|
|
8fd5006b6f | ||
|
|
97448e25ec | ||
|
|
8916a284bd | ||
|
|
8e2aaaf94f | ||
|
|
e15f8b8baf | ||
|
|
890691319f | ||
|
|
21094ca88b | ||
|
|
9aea18f90c | ||
|
|
6202e09348 | ||
|
|
29ba56757d | ||
|
|
fbf5f2bb67 | ||
|
|
1134512b22 | ||
|
|
8424acef4b | ||
|
|
bc9b51402f | ||
|
|
1623396086 | ||
|
|
29447366d1 | ||
|
|
5941713b0c | ||
|
|
32a022a823 | ||
|
|
497471d16b | ||
|
|
fbb8c111ed | ||
|
|
059cc636f6 | ||
|
|
4df4091899 | ||
|
|
c7753f2d9b | ||
|
|
7bd7559bfe | ||
|
|
635cb8e3ff | ||
|
|
b23abcbfe5 | ||
|
|
30d0f8b1f6 | ||
|
|
b581536a66 | ||
|
|
77dcfb5062 | ||
|
|
b82324b7b7 | ||
|
|
e33fb2c751 | ||
|
|
1416387af1 | ||
|
|
f436f2c106 | ||
|
|
5229459c02 | ||
|
|
662f3cd1b3 | ||
|
|
ee60c3e92a | ||
|
|
58a6f5df98 | ||
|
|
50f6db5ae2 | ||
|
|
dc453efa5c | ||
|
|
ac3c271c9f | ||
|
|
397c1e7684 | ||
|
|
c8966b92f1 | ||
|
|
c3ca241e57 | ||
|
|
f9d829c1cd | ||
|
|
0a261b7401 | ||
|
|
d5ad0ae862 | ||
|
|
cd778582d5 | ||
|
|
25cc8049c8 | ||
|
|
c8a02bf8a8 | ||
|
|
e2572dca43 | ||
|
|
c4e0051ab2 | ||
|
|
3f35ba27fc | ||
|
|
2fa2728dbc | ||
|
|
57c082c155 | ||
|
|
86e0898920 | ||
|
|
bb09245792 | ||
|
|
6dd969129d | ||
|
|
4f982e244f |
@@ -419,6 +419,108 @@ jobs:
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
|
||||
build-slim-image:
|
||||
runs-on: ${{ matrix.runner }}
|
||||
permissions:
|
||||
contents: read
|
||||
packages: write
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- platform: linux/amd64
|
||||
runner: ubuntu-latest
|
||||
- platform: linux/arm64
|
||||
runner: ubuntu-24.04-arm
|
||||
|
||||
steps:
|
||||
# GitHub Packages requires the entire repository name to be in lowercase
|
||||
# although the repository owner has a lowercase username, this prevents some people from running actions after forking
|
||||
- name: Set repository and image name to lowercase
|
||||
run: |
|
||||
echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
|
||||
echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
|
||||
env:
|
||||
IMAGE_NAME: '${{ github.repository }}'
|
||||
|
||||
- name: Prepare
|
||||
run: |
|
||||
platform=${{ matrix.platform }}
|
||||
echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
|
||||
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Log in to the Container registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata for Docker images (slim tag)
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.FULL_IMAGE_NAME }}
|
||||
tags: |
|
||||
type=ref,event=branch
|
||||
type=ref,event=tag
|
||||
type=sha,prefix=git-
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=slim
|
||||
flavor: |
|
||||
latest=${{ github.ref == 'refs/heads/main' }}
|
||||
suffix=-slim,onlatest=true
|
||||
|
||||
- name: Extract metadata for Docker cache
|
||||
id: cache-meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.FULL_IMAGE_NAME }}
|
||||
tags: |
|
||||
type=ref,event=branch
|
||||
${{ github.ref_type == 'tag' && 'type=raw,value=main' || '' }}
|
||||
flavor: |
|
||||
prefix=cache-slim-${{ matrix.platform }}-
|
||||
latest=false
|
||||
|
||||
- name: Build Docker image (slim)
|
||||
uses: docker/build-push-action@v5
|
||||
id: build
|
||||
with:
|
||||
context: .
|
||||
push: true
|
||||
platforms: ${{ matrix.platform }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
outputs: type=image,name=${{ env.FULL_IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
|
||||
cache-from: type=registry,ref=${{ steps.cache-meta.outputs.tags }}
|
||||
cache-to: type=registry,ref=${{ steps.cache-meta.outputs.tags }},mode=max
|
||||
build-args: |
|
||||
BUILD_HASH=${{ github.sha }}
|
||||
USE_SLIM=true
|
||||
|
||||
- name: Export digest
|
||||
run: |
|
||||
mkdir -p /tmp/digests
|
||||
digest="${{ steps.build.outputs.digest }}"
|
||||
touch "/tmp/digests/${digest#sha256:}"
|
||||
|
||||
- name: Upload digest
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: digests-slim-${{ env.PLATFORM_PAIR }}
|
||||
path: /tmp/digests/*
|
||||
if-no-files-found: error
|
||||
retention-days: 1
|
||||
|
||||
merge-main-images:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [build-main-image]
|
||||
@@ -640,3 +742,59 @@ jobs:
|
||||
- name: Inspect image
|
||||
run: |
|
||||
docker buildx imagetools inspect ${{ env.FULL_IMAGE_NAME }}:${{ steps.meta.outputs.version }}
|
||||
|
||||
merge-slim-images:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [build-slim-image]
|
||||
steps:
|
||||
# GitHub Packages requires the entire repository name to be in lowercase
|
||||
# although the repository owner has a lowercase username, this prevents some people from running actions after forking
|
||||
- name: Set repository and image name to lowercase
|
||||
run: |
|
||||
echo "IMAGE_NAME=${IMAGE_NAME,,}" >>${GITHUB_ENV}
|
||||
echo "FULL_IMAGE_NAME=ghcr.io/${IMAGE_NAME,,}" >>${GITHUB_ENV}
|
||||
env:
|
||||
IMAGE_NAME: '${{ github.repository }}'
|
||||
|
||||
- name: Download digests
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
pattern: digests-slim-*
|
||||
path: /tmp/digests
|
||||
merge-multiple: true
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Log in to the Container registry
|
||||
uses: docker/login-action@v3
|
||||
with:
|
||||
registry: ${{ env.REGISTRY }}
|
||||
username: ${{ github.actor }}
|
||||
password: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
- name: Extract metadata for Docker images (default slim tag)
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
with:
|
||||
images: ${{ env.FULL_IMAGE_NAME }}
|
||||
tags: |
|
||||
type=ref,event=branch
|
||||
type=ref,event=tag
|
||||
type=sha,prefix=git-
|
||||
type=semver,pattern={{version}}
|
||||
type=semver,pattern={{major}}.{{minor}}
|
||||
type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=slim
|
||||
flavor: |
|
||||
latest=${{ github.ref == 'refs/heads/main' }}
|
||||
suffix=-slim,onlatest=true
|
||||
|
||||
- name: Create manifest list and push
|
||||
working-directory: /tmp/digests
|
||||
run: |
|
||||
docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
|
||||
$(printf '${{ env.FULL_IMAGE_NAME }}@sha256:%s ' *)
|
||||
|
||||
- name: Inspect image
|
||||
run: |
|
||||
docker buildx imagetools inspect ${{ env.FULL_IMAGE_NAME }}:${{ steps.meta.outputs.version }}
|
||||
|
||||
+172
@@ -5,6 +5,178 @@ All notable changes to this project will be documented in this file.
|
||||
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
|
||||
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [0.6.26] - 2025-08-28
|
||||
|
||||
### Added
|
||||
|
||||
- 🛂 **Granular Chat Interaction Permissions**: Added fine-grained permission controls for individual chat actions including "Continue Response", "Regenerate Response", "Rate Response", and "Delete Messages". Administrators can now configure these permissions per user group or set system defaults via environment variables, providing enhanced security and governance by preventing potential system prompt leakage through response continuation and enabling precise control over user interactions with AI responses.
|
||||
- 🧠 **Custom Reasoning Tags Configuration**: Added configurable reasoning tag detection for AI model responses, allowing administrators and users to customize how the system identifies and processes reasoning content. Users can now define custom reasoning tag pairs, use default tags like "think" and "reasoning", or disable reasoning detection entirely through the Advanced Parameters interface, providing enhanced control over AI thought process visibility.
|
||||
- 📱 **Pull-to-Refresh SupportA**: Added pull-to-refresh functionality allowing user to easily refresh the interface by pulling down on the navbar area. This resolves timeout issues that occurred when temporarily switching away from the app during long AI response generations, eliminating the need to close and relaunch the PWA.
|
||||
- 📁 **Configurable File Upload Processing Mode**: Added "process_in_background" query parameter to the file upload API endpoint, allowing clients to choose between asynchronous (default) and synchronous file processing. Setting "process_in_background=false" forces the upload request to wait until extraction and embedding complete, returning immediately usable files and simplifying integration for backend API consumers that prefer blocking calls over polling workflows.
|
||||
- 🔐 **Azure Document Intelligence DefaultAzureCredential Support**: Added support for authenticating with Azure Document Intelligence using DefaultAzureCredential in addition to API key authentication, enabling seamless integration with Azure Entra ID and managed identity authentication for enterprise Azure environments.
|
||||
- 🔐 **Authentication Bootstrapping Enhancements**: Added "ENABLE_INITIAL_ADMIN_SIGNUP" environment variable and "?form=true" URL parameter to enable initial admin user creation and forced login form display in SSO-only deployments. This resolves bootstrap issues where administrators couldn't create the first user when login forms were disabled, allowing proper initialization of SSO-configured deployments without requiring temporary configuration changes.
|
||||
- ⚡ **Query Generation Caching**: Added "ENABLE_QUERIES_CACHE" environment variable to enable request-scoped caching of generated search queries. When both web search and file retrieval are active, queries generated for web search are automatically reused for file retrieval, eliminating duplicate LLM API calls and reducing token usage and costs while maintaining search quality.
|
||||
- 🔧 **Configurable Tool Call Retry Limit**: Added "CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES" environment variable to control the maximum number of sequential tool calls allowed before safety stopping a chat session. This replaces the previous hardcoded limit of 10, enabling administrators to configure higher limits for complex workflows requiring extensive tool interactions.
|
||||
- 📦 **Slim Docker Image Variant**: Added new slim Docker image option via "USE_SLIM" build argument that excludes embedded AI models and Ollama installation, reducing image size by approximately 1GB. This variant enables faster image pulls and deployments for environments where AI models are managed externally, particularly beneficial for auto-scaling clusters and distributed deployments.
|
||||
- 🗂️ **Shift-to-Delete Functionality for Workspace Prompts**: Added keyboard shortcut support for quick prompt deletion on the Workspace Prompts page. Hold Shift and hover over any prompt to reveal a trash icon for instant deletion, bringing consistent interaction patterns across all workspace sections (Models, Tools, Functions, and now Prompts) and streamlining prompt management workflows.
|
||||
- ♿ **Accessibility Enhancements**: Enhanced user interface accessibility with improved keyboard navigation, ARIA labels, and screen reader compatibility across key platform components.
|
||||
- 📄 **Optimized PDF Export for Smaller File Size**: PDF exports are now significantly optimized, producing much smaller files for faster downloads and easier sharing or archiving of your chats and documents.
|
||||
- 📦 **Slimmed Default Install with Optional Full Dependencies**: Installing Open WebUI via pip now defaults to a slimmer package; PostgreSQL support is no longer included by default—simply use 'pip install open-webui[all]' to include all optional dependencies for full feature compatibility.
|
||||
- 🔄 **General Backend Refactoring**: Implemented various backend improvements to enhance performance, stability, and security, ensuring a more resilient and reliable platform for all users.
|
||||
- 🌐 **Localization & Internationalization Improvements**: Enhanced and expanded translations for Finnish, Spanish, Japanese, Polish, Portuguese (Brazil), and Chinese, including missing translations and typo corrections, providing a more natural and professional user experience for speakers of these languages across the entire interface.
|
||||
|
||||
### Fixed
|
||||
|
||||
- ⚠️ **Chat Error Feedback Restored**: Fixed an issue where various backend errors (tool server failures, API connection issues, malformed responses) would cause chats to load indefinitely without providing user feedback. The system now properly displays error messages when failures occur during chat generation, allowing users to understand issues and retry as needed instead of waiting indefinitely.
|
||||
- 🖼️ **Image Generation Steps Setting Visibility Fixed**: Fixed a UI issue where the "Set Steps" configuration option was incorrectly displayed for OpenAI and Gemini image generation engines that don't support this parameter. The setting is now only visible for compatible engines like ComfyUI and Automatic1111, eliminating user confusion about non-functional configuration options.
|
||||
- 📄 **Datalab Marker API Document Loader Fixed**: Fixed broken Datalab Marker API document loader functionality by correcting URL path handling for both hosted Datalab services and self-hosted Marker servers. Removed hardcoded "/marker" paths from the loader code and restored proper default URL structure, ensuring PDF and document processing works correctly with both deployment types.
|
||||
- 📋 **Citation Error Handling Improved**: Fixed an issue where malformed citation or source objects from external tools, pipes, or filters would cause JavaScript errors and make the chat interface completely unresponsive. The system now gracefully handles missing or undefined citation properties, allowing conversations to load properly even when tools generate defective citation events.
|
||||
- 👥 **Group User Add API Endpoint Fixed**: Fixed an issue where the "/api/v1/groups/id/{group_id}/users/add" API endpoint would accept requests without errors but fail to actually add users to groups. The system now properly initializes and deduplicates user ID lists, ensuring users are correctly added to and removed from groups via API calls.
|
||||
- 🛠️ **External Tool Server Error Handling Improved**: Fixed an issue where unreachable or misconfigured external tool servers would cause JavaScript errors and prevent the interface from loading properly. The system now gracefully handles connection failures, displays appropriate error messages, and filters out inaccessible servers while maintaining full functionality for working connections.
|
||||
- 📋 **Code Block Copy Button Content Fixed**: Fixed an issue where the copy button in code blocks would copy the original AI-generated code instead of any user-edited content, ensuring the copy function always captures the currently displayed code as modified by users.
|
||||
- 📄 **PDF Export Content Mismatch Fixed**: Resolved an issue where exporting a PDF of one chat while viewing another chat would incorrectly generate the PDF using the currently viewed chat's content instead of the intended chat's content. Additionally optimized the PDF generation algorithm with improved canvas slicing, better memory management, and enhanced image quality, while removing the problematic PDF export option from individual chat menus to prevent further confusion.
|
||||
- 🖱️ **Windows Sidebar Cursor Icon Corrected**: Fixed confusing cursor icons on Windows systems where sidebar toggle buttons displayed resize cursors (ew-resize) instead of appropriate pointer cursors. The sidebar buttons now show standard pointer cursors on Windows, eliminating user confusion about whether the buttons expand/collapse the sidebar or resize it.
|
||||
- 📝 **Safari IME Composition Bug Fixed**: Resolved an issue where pressing Enter while composing Chinese text using Input Method Editors (IMEs) on Safari would prematurely send messages instead of completing text composition. The system now properly detects composition states and ignores keydown events that occur immediately after composition ends, ensuring smooth multilingual text input across all browsers.
|
||||
- 🔍 **Hybrid Search Parameter Handling Fixed**: Fixed an issue where the "hybrid" parameter in collection query requests was not being properly evaluated, causing the system to ignore user-specified hybrid search preferences and only check global configuration. Additionally resolved a division by zero error that occurred in hybrid search when BM25Retriever was called with empty document lists, ensuring robust search functionality across all collection states.
|
||||
- 💬 **RTL Text Orientation in Messages Fixed**: Fixed text alignment issues in user messages and AI responses for Right-to-Left languages, ensuring proper text direction based on user language settings. Code blocks now consistently use Left-to-Right orientation regardless of the user's language preference, maintaining code readability across all supported languages.
|
||||
- 📁 **File Content Preview in Modal Restored**: Fixed an issue where clicking on uploaded files would display an empty preview modal, even when the files were successfully processed and available for AI context. File content now displays correctly in the preview modal, ensuring users can verify and review their uploaded documents as intended.
|
||||
- 🌐 **Playwright Timeout Configuration Corrected**: Fixed an issue where Playwright timeout values were incorrectly converted from milliseconds to seconds with an additional 1000x multiplier, causing excessively long web loading timeouts. The timeout parameter now correctly uses the configured millisecond values as intended, ensuring responsive web search and document loading operations.
|
||||
|
||||
### Changed
|
||||
|
||||
- 🔄 **Follow-Up Question Language Constraint Removed**: Follow-up question suggestions no longer strictly adhere to the chat's primary language setting, allowing for more flexible and diverse suggestion generation that may include questions in different languages based on conversation context and relevance rather than enforced language matching.
|
||||
|
||||
## [0.6.25] - 2025-08-22
|
||||
|
||||
### Fixed
|
||||
|
||||
- 🖼️ **Image Generation Reliability Restored**: Fixed a key issue causing image generation failures.
|
||||
- 🏆 **Reranking Functionality Restored**: Resolved errors with rerank feature.
|
||||
|
||||
## [0.6.24] - 2025-08-21
|
||||
|
||||
### Added
|
||||
|
||||
- ♿ **High Contrast Mode in Chat Messages**: Implemented enhanced High Contrast Mode support for chat messages, making text and important details easier to read and improving accessibility for users with visual preferences or requirements.
|
||||
- 🌎 **Localization & Internationalization Improvements**: Enhanced and expanded translations for a more natural and professional user experience for speakers of these languages across the entire interface.
|
||||
|
||||
### Fixed
|
||||
|
||||
- 🖼️ **ComfyUI Image Generation Restored**: Fixed a critical bug where ComfyUI-based image generation was not functioning, ensuring users can once again effortlessly create and interact with AI-generated visuals in their workflows.
|
||||
- 🛠️ **Tool Server Loading and Visibility Restored**: Resolved an issue where connected tool servers were not loading or visible, restoring seamless integration and uninterrupted access to all external and custom tools directly within the platform.
|
||||
- 🛡️ **Redis User Session Reliability**: Fixed a problem affecting the saving of user sessions in Redis, ensuring reliable login sessions, stable authentication, and secure multi-user environments.
|
||||
|
||||
## [0.6.23] - 2025-08-21
|
||||
|
||||
### Added
|
||||
|
||||
- ⚡ **Asynchronous Chat Payload Processing**: Refactored the chat completion pipeline to return a response immediately for streaming requests involving web search or tool calls. This enables users to stop ongoing generations promptly and preventing network timeouts during lengthy preprocessing phases, thus significantly improving user experience and responsiveness.
|
||||
- 📁 **Asynchronous File Upload with Polling**: Implemented an asynchronous file upload process with frontend polling to resolve gateway timeouts and improve reliability when uploading large files. This ensures that even lengthy file processing, such as embedding or transcription, does not block the user interface or lead to connection timeouts, providing a smoother experience for all file operations.
|
||||
- 📈 **Database Performance Indexes and Migration Script**: Introduced new database indexes on the "chat", "tag", and "function" tables to significantly enhance query performance for SQLite and PostgreSQL installations. For existing deployments, a new Alembic migration script is included to seamlessly apply these indexes, ensuring faster filtering and sorting operations across the platform.
|
||||
- ✨ **Enhanced Database Performance Options**: Introduced new configurable options to significantly improve database performance, especially for SQLite. This includes "DATABASE_ENABLE_SQLITE_WAL" to enable SQLite WAL (Write-Ahead Logging) mode for concurrent operations, and "DATABASE_DEDUPLICATE_INTERVAL" which, in conjunction with a new deduplication mechanism, reduces redundant updates to "user.last_active_at", minimizing write conflicts across all database types.
|
||||
- 💾 **Save Temporary Chats Button**: Introduced a new 'Save Chat' button for conversations initiated in temporary mode. This allows users to permanently save valuable temporary conversations to their chat history, providing greater flexibility and ensuring important discussions are not lost.
|
||||
- 📂 **Chat Movement Options in Menu**: Added the ability to move chats directly to folders from the chat menu. This enhances chat organization and allows users to manage their conversations more efficiently by relocating them between folders with ease.
|
||||
- 💬 **Language-Aware Follow-Up Suggestions**: Enhanced the AI's follow-up question generation to dynamically adapt to the primary language of the current chat. Follow-up prompts will now be suggested in the same language the user and AI are conversing in, ensuring more natural and contextually relevant interactions.
|
||||
- 👤 **Expanded User Profile Details**: Introduced new user profile fields including username, bio, gender, and date of birth, allowing for more comprehensive user customization and information management. This enhancement includes corresponding updates to the database schema, API, and user interface for seamless integration.
|
||||
- 👥 **Direct Navigation to User Groups from User Edit**: Enhanced the user edit modal to include a direct link to the associated user group. This allows administrators to quickly navigate from a user's profile to their group settings, streamlining user and group management workflows.
|
||||
- 🔧 **Enhanced External Tool Server Compatibility**: Improved handling of responses from external tool servers, allowing both the backend and frontend to process plain text content in addition to JSON, ensuring greater flexibility and integration with diverse tool outputs.
|
||||
- 🗣️ **Enhanced Audio Transcription Language Fallback and Deepgram Support**: Implemented a robust language fallback mechanism for both OpenAI and Deepgram Speech-to-Text (STT) API calls. If a specified language parameter is not supported by the model or provider, the system will now intelligently retry the transcription without the language parameter or with a default, ensuring greater reliability and preventing failed API calls. This also specifically adds and refines support for the audio language parameter in Deepgram API integrations.
|
||||
- ⚡ **Optimized Hybrid Search Performance for BM25 Weight Configuration**: Enhanced hybrid search to significantly improve performance when the BM25 weight is set to 0 or less. This optimization intelligently disables unnecessary collection retrieval and BM25 ranking calculations, leading to faster search results without impacting accuracy for configurations that do not utilize lexical search contributions.
|
||||
- 🔒 **Configurable Code Interpreter Module Blacklist**: Introduced the "CODE_INTERPRETER_BLACKLISTED_MODULES" environment variable, allowing administrators to specify Python modules that are forbidden from being imported or executed within the code interpreter. This significantly enhances the security posture by mitigating risks associated with arbitrary code execution, such as unauthorized data access, system manipulation, or outbound connections.
|
||||
- 🔐 **Enhanced OAuth Role Claim Handling**: Improved compatibility with diverse OAuth providers by allowing role claims to be supplied as single strings or integers, in addition to arrays. The system now automatically normalizes these single-value claims into arrays for consistent processing, streamlining integration with identity providers that format role data differently.
|
||||
- ⚙️ **Configurable Tool Call Timeout**: Introduced the "AIOHTTP_CLIENT_TIMEOUT" environment variable, allowing administrators to specify custom timeout durations for external tool calls, which is crucial for integrations with tools that have varying or extended response times.
|
||||
- 🛠️ **Improved Tool Callable Generation for Google genai SDK**: Enhanced the creation of tool callables to directly support native function calling within the Google 'genai' SDK. This refactoring ensures proper signature inference and removes extraneous parameters, enabling seamless integration for advanced AI workflows using Google's generative AI models.
|
||||
- ✨ **Dynamic Loading of 'kokoro-js'**: Implemented dynamic loading for the 'kokoro-js' library, preventing failures and improving compatibility on older iOS browsers that may not support direct imports or certain modern JavaScript APIs like 'DecompressionStream'.
|
||||
- 🖥️ **Improved Command List Visibility on Small Screens**: Resolved an issue where the top items in command lists (e.g., Knowledge Base, Models, Prompts) were hidden or overlapped by the header on smaller screen sizes or specific browser zoom levels. The command option lists now dynamically adjust their height, ensuring all items are fully visible and accessible with proper scrolling.
|
||||
- 📦 **Improved Docker Image Compatibility for Arbitrary UIDs**: Fixed issues preventing the Open WebUI container from running in environments with arbitrary User IDs (UIDs), such as OpenShift's restricted Security Context Constraints (SCC). The Dockerfile has been updated to correctly set file system permissions for "/app" and "/root" directories, ensuring they are writable by processes running with a supplemental GID 0, thus resolving permission errors for Python libraries and application caches.
|
||||
- ♿ **Accessibility Enhancements**: Significantly improved the semantic structure of chat messages by using "section", "h2", "ul", and "li" HTML tags, and enhanced screen reader compatibility by explicitly hiding decorative images with "aria-hidden" attributes. This refactoring provides clearer structural context and improves overall accessibility and web standards compliance for the conversation flow.
|
||||
- 🌐 **Localization & Internationalization Improvements**: Significantly expanded internationalization support throughout the user interface, translating numerous user-facing strings in toast messages, placeholders, and other UI elements. This, alongside continuous refinement and expansion of translations for languages including Brazilian Portuguese, Kabyle (Taqbaylit), Czech, Finnish, Chinese (Simplified), Chinese (Traditional), and German, and general fixes for several other translation files, further enhances linguistic coverage and user experience.
|
||||
|
||||
### Fixed
|
||||
|
||||
- 🛡️ **Resolved Critical OIDC SSO Login Failure**: Fixed a critical issue where OIDC Single Sign-On (SSO) logins failed due to an error in setting the authentication token as a cookie during the redirect process. This ensures reliable and seamless authentication for users utilizing OIDC providers, restoring full login functionality that was impacted by previous security hardening.
|
||||
- ⚡ **Prevented UI Blocking by Unreachable Webhooks**: Resolved a critical performance and user experience issue where synchronous webhook calls to unreachable or slow endpoints would block the entire user interface for all users. Webhook requests are now processed asynchronously using "aiohttp", ensuring that the UI remains responsive and functional even if webhook delivery encounters delays or failures.
|
||||
- 🔒 **Password Change Option Hidden for Externally Authenticated Users**: Resolved an issue where the password change dialog was visible to users authenticated via external methods (e.g., LDAP, OIDC, Trusted Header). The option to change a password in user settings is now correctly hidden for these users, as their passwords are managed externally, streamlining the user interface and preventing confusion.
|
||||
- 💬 **Resolved Temporary Chat and Permission Enforcement Issues**: Fixed a bug where temporary chats (identified by "chat_id = local") incorrectly triggered database checks, leading to 404 errors. This also resolves the issue where the 'USER_PERMISSIONS_CHAT_TEMPORARY_ENFORCED' setting was not functioning as intended, ensuring temporary chat mode now works correctly for user roles.
|
||||
- 🔐 **Admin Model Visibility for Administrators**: Private models remained visible and usable for administrators in the chat model selector, even when the intended privacy setting ("ENABLE_ADMIN_WORKSPACE_CONTENT_ACCESS" - now renamed to "BYPASS_ADMIN_ACCESS_CONTROL") was disabled. This ensures consistent enforcement of model access controls and adherence to the principle of least privilege.
|
||||
- 🔍 **Clarified Web Search Engine Label for DDGS**: Addressed user confusion and inaccurate labeling by renaming "duckduckgo" to "DDGS" (Dux Distributed Global Search) in the web search engine selector. This clarifies that the system utilizes DDGS, a metasearch library that aggregates results from various search providers, accurately reflecting its underlying functionality rather than implying exclusive use of DuckDuckGo's search engine.
|
||||
- 🛠️ **Improved Settings UI Reactivity and Visibility**: Resolved an issue where settings tabs for 'Connections' and 'Tools' did not dynamically update their visibility based on global administrative feature flags (e.g., 'enable_direct_connections'). The UI now reactively shows or hides these sections, ensuring a consistent and clear experience when administrators control feature availability.
|
||||
- 🎚️ **Restored Model and Banner Reordering Functionality**: Fixed a bug that prevented administrators from reordering models in the Admin Panel's 'Models' settings and banners in the 'Interface' settings via drag-and-drop. The sortable functionality has been restored, allowing for proper customization of display order.
|
||||
- 📝 **Restored Custom Pending User Overlay Visibility**: Fixed an issue where the custom title and description configured for pending users were not visible. The application now correctly exposes these UI configuration settings to pending users, ensuring that the custom onboarding messages are displayed as intended.
|
||||
- 📥 **Fixed Community Function Import Compatibility**: Resolved an issue that prevented the successful import of function files downloaded from openwebui.com due to schema differences. The system now correctly processes these files, allowing for seamless integration of community-contributed functions.
|
||||
- 📦 **Fixed Stale Ollama Version in Docker Images**: Resolved an issue where the Ollama installation within Docker images could become stale due to caching during the build process. The Dockerfile now includes a mechanism to invalidate the build cache for the Ollama installation step, ensuring that the latest version of Ollama is always installed.
|
||||
- 🗄️ **Improved Milvus Query Handling for Large Datasets**: Fixed a "MilvusException" that occurred when attempting to query more than 16384 entries from a Milvus collection. The query logic has been refactored to use "query_iterator()", enabling efficient fetching of larger result sets in batches and resolving the previous limitation on the number of entries that could be retrieved.
|
||||
- 🐛 **Restored Message Toolbar Icons for Empty Messages with Files**: Fixed an issue where the edit, copy, and delete icons were not displayed on user messages that contained an attached file but no text content. This ensures full interaction capabilities for all message types, allowing users to manage their messages consistently.
|
||||
- 💬 **Resolved Streaming Interruption for Kimi-Dev Models**: Fixed an issue where streaming responses from Kimi-Dev models would halt prematurely upon encountering specific 'thinking' tokens (◁think▷, ◁/think▷). The system now correctly processes these tokens, ensuring uninterrupted streaming and proper handling of hidden or collapsible thinking sections.
|
||||
- 🔍 **Enhanced Knowledge Base Search Functionality**: Improved the search capability within the 'Knowledge' section of the Workspace. Previously, searching for knowledge bases required exact term matches or starting with the first letter. Now, the search algorithm has been refined to allow broader, less exact matches, making it easier and more intuitive to find relevant knowledge bases.
|
||||
- 📝 **Resolved Chinese Input 'Enter' Key Issue (macOS & iOS Safari)**: Fixed a bug where pressing the 'Enter' key during text composition with Input Method Editors (IMEs) on macOS and iOS Safari browsers would prematurely send the message. The system now robustly handles the composition state by addressing a 'compositionend' event bug specific to Safari, ensuring a smooth and expected typing experience for users of various languages, including Chinese and Korean.
|
||||
- 🔐 **Resolved OAUTH_GROUPS_CLAIM Configuration Issue**: Fixed a bug where the "OAUTH_GROUPS_CLAIM" environment variable was not correctly parsed due to a typo in the configuration file. This ensures that OAuth group management features, including automatic group creation, now correctly utilize the specified claim from the identity provider, allowing for seamless integration with external user directories like Keycloak.
|
||||
- 🗄️ **Resolved Azure PostgreSQL pgvector Extension Permissions**: Fixed an issue preventing the creation of "pgvector" and "pgcrypto" extensions on Azure PostgreSQL Flexible Servers due to permission limitations (e.g., 'Only members of "azure_pg_admin" are allowed to use "CREATE EXTENSION"'). The extension creation process now includes a conditional check, ensuring seamless deployment and compatibility with Azure PostgreSQL environments even with restricted database user permissions.
|
||||
- 🛠️ **Improved Backend Path Resolution and Alembic Stability**: Fixed issues causing Alembic database migrations to fail due to incorrect path resolution within the application. By implementing canonical path resolution for core directories and refining Alembic configuration, the robustness and correctness of internal pathing have been significantly enhanced, ensuring reliable database operations.
|
||||
- 📊 **Resolved Arena Model Identification in Feedback History**: Fixed an issue where the model used for feedback in arena settings was incorrectly reported as 'arena-model' in the evaluation history. The system now correctly logs and displays the actual model ID that received the feedback, restoring clarity and enabling proper analysis of model performance in arena environments.
|
||||
- 🎨 **Resolved Icon Overlap in 'Her' Theme**: Fixed a visual glitch in the 'Her' theme where icons would overlap on the loading screen and certain icons appeared incongruous. The display has been corrected to ensure proper visual presentation and theme consistency.
|
||||
- 🛠️ **Resolved Model Sorting TypeError with Null Names**: Fixed a "TypeError" that occurred in the "/api/models" endpoint when sorting models with null or missing names. The model sorting logic has been improved to gracefully handle such edge cases by ensuring that model IDs and names are treated as empty strings if their values are null or undefined, preventing comparison errors and improving API stability.
|
||||
- 💬 **Resolved Silently Dropped Streaming Response Chunks**: Fixed an issue where the final partial chunks of streaming chat responses could be silently dropped, leading to incomplete message delivery. The system now reliably flush any pending delta data upon stream termination, early breaks (e.g., code interpreter tags), or connection closure, ensuring complete and accurate response delivery.
|
||||
- 📱 **Disabled Overscroll for iOS Frontend**: Fixed an issue where overscrolling was enabled on iOS devices, causing unexpected scrolling behavior over fixed or sticky elements within the PWA. Overscroll has now been disabled, providing a more native application-like experience for iOS users.
|
||||
- 📝 **Resolved Code Block Input Issue with Shift+Enter**: Fixed a bug where typing three backticks followed by a language and then pressing Shift+Enter would cause the code block prefix to disappear, preventing proper code formatting. The system now correctly preserves the code block syntax, ensuring consistent behavior for multi-line code input.
|
||||
- 🛠️ **Improved OpenAI Model List Handling for Null Names**: Fixed an edge case where some OpenAI-compatible API providers might return models with a null value for their 'name' field. This could lead to issues like broken model list sorting. The system now gracefully handles these instances by removing the null 'name' key, ensuring stable model retrieval and display.
|
||||
- 🔍 **Resolved DDGS Concurrent Request Configuration**: Fixed an issue where the configured number of concurrent requests was not being honored for the DDGS (Dux Distributed Global Search) metasearch engine. The system now correctly applies the specified concurrency setting, improving efficiency for web searches.
|
||||
- 🛠️ **Improved Tool List Synchronization in Multi-Replica Deployments**: Resolved an issue where tool updates were not consistently reflected across all instances in multi-replica environments, leading to stale tool lists for users on other replicas. The tool list in the message input menu is now automatically refreshed each time it is accessed, ensuring all users always see the most current set of available tools.
|
||||
- 🛠️ **Resolved Duplicate Tool Name Collision**: Fixed an issue where tools with identical names from different external servers were silently removed, preventing their simultaneous use. The system now correctly handles tool name collisions by internally prefixing tools with their server identifier, allowing multiple instances of similarly named tools from different servers to be active and usable by LLMs.
|
||||
- 🖼️ **Resolved Image Generation API Size Parameter Issue**: Fixed a bug where the "/api/v1/images/generations" API endpoint did not correctly apply the 'size' parameter specified in the request payload for image generation. The system now properly honors the requested image dimensions (e.g., '1980x1080'), ensuring that generated images match the user's explicit size preference rather than defaulting to settings.
|
||||
- 🗄️ **Resolved S3 Vector Upload Limitations**: Fixed an issue that prevented uploading more than 500 vectors to S3 Vector buckets due to API limitations, which resulted in a "ValidationException". S3 vector uploads are now batched in groups of 500, ensuring successful processing of larger datasets.
|
||||
- 🛠️ **Fixed Tool Installation Error During Startup**: Resolved a "NoneType" error that occurred during tool installation at startup when 'tool.user' was unexpectedly null. The system now includes a check to ensure 'tool.user' exists before attempting to access its properties, preventing crashes and ensuring robust tool initialization.
|
||||
- 🛠️ **Improved Azure OpenAI GPT-5 Parameter Handling**: Fixed an issue with Azure OpenAI SDK parameter handling to correctly support GPT-5 models. The 'max_tokens' parameter is now appropriately converted to 'max_completion_tokens' for GPT-5 models, ensuring consistent behavior and proper function execution similar to existing o-series models.
|
||||
- 🐛 **Resolved Exception with Missing Group Permissions**: Fixed an exception that occurred in the access control logic when group permission objects were missing or null. The system now correctly handles cases where groups may not have explicit permission definitions, ensuring that 'None' checks prevent errors and maintain application stability when processing user permissions.
|
||||
- 🛠️ **Improved OpenAI API Base URL Handling**: Fixed an issue where a trailing slash in the 'OPENAI_API_BASE_URL' configuration could lead to models not being detected or the endpoint failing. The system now automatically removes trailing slashes from the configured URL, ensuring robust and consistent connections to OpenAI-compatible APIs.
|
||||
- 🖼️ **Resolved S3-Compatible Storage Upload Failures**: Fixed an issue where uploads to S3-compatible storage providers would fail with an "XAmzContentSHA256Mismatch" error. The system now correctly handles checksum calculations, ensuring reliable file and image uploads to S3-compatible services.
|
||||
- 🌐 **Corrected 'Releases' Link**: Fixed an issue where the 'Releases' button in the user menu directed to an incorrect URL, now correctly linking to the Open WebUI GitHub releases page.
|
||||
- 🛠️ **Resolved Model Sorting Errors with Null or Undefined Names**: Fixed multiple "TypeError" instances that occurred when attempting to sort model lists where model names were null or undefined. The sorting logic across various UI components (including Ollama model selection, leaderboard, and admin model settings) has been made more robust by gracefully handling absent model names, preventing crashes and ensuring consistent alphabetical sorting based on available name or ID.
|
||||
- 🎨 **Resolved Banner Dismissal Issue with Iteration IDs**: Fixed a bug where dismissing banners could lead to unintended multiple banner dismissals or other incorrect behavior, especially when banners lacked unique iteration IDs. Unique IDs are now assigned during banner iteration, ensuring proper individual dismissal and consistent display behavior.
|
||||
|
||||
### Changed
|
||||
|
||||
- 🛂 **Environment Variable for Admin Access Control**: The environment variable "ENABLE_ADMIN_WORKSPACE_CONTENT_ACCESS" has been renamed to "BYPASS_ADMIN_ACCESS_CONTROL". This new name more accurately reflects its function as a control to allow administrators to bypass model access restrictions. Users are encouraged to update their configurations to use the new variable name; existing configurations using the old name will still be honored for backward compatibility.
|
||||
- 🗂️ **Core Directory Path Resolution Updated**: The internal mechanism for resolving core application directory paths ("OPEN_WEBUI_DIR", "BACKEND_DIR", "BASE_DIR") has been updated to use canonical resolution via "Path().resolve()". This change improves path reliability but may require adjustments for any external scripts or configurations that previously relied on specific non-canonical path interpretations.
|
||||
- 🗃️ **Database Performance Options**: New database performance options, "DATABASE_ENABLE_SQLITE_WAL" and "DATABASE_DEDUPLICATE_INTERVAL", are now available. If "DATABASE_ENABLE_SQLITE_WAL" is enabled, SQLite will operate in WAL mode, which may alter SQLite's file locking behavior. If "DATABASE_DEDUPLICATE_INTERVAL" is set to a non-zero value, the "user.last_active_at" timestamp will be updated less frequently, leading to slightly less real-time accuracy for this specific field but significantly reducing database write conflicts and improving overall performance. Both options are disabled by default.
|
||||
- 🌐 **Renamed Web Search Concurrency Setting**: The environment variable "WEB_SEARCH_CONCURRENT_REQUESTS" has been renamed to "WEB_LOADER_CONCURRENT_REQUESTS". This change clarifies its scope, explicitly applying to the concurrency of the web loader component (which fetches content from search results) rather than the initial search engine query. Users relying on the old environment variable name for configuring web search concurrency must update their configurations to use "WEB_LOADER_CONCURRENT_REQUESTS".
|
||||
|
||||
## [0.6.22] - 2025-08-11
|
||||
|
||||
### Added
|
||||
|
||||
- 🔗 **OpenAI API '/v1' Endpoint Compatibility**: Enhanced API compatibility by supporting requests to paths like '/v1/models', '/v1/embeddings', and '/v1/chat/completions'. This allows Open WebUI to integrate more seamlessly with tools that expect OpenAI's '/v1' API structure.
|
||||
- 🪄 **Toggle for Guided Response Regeneration Menu**: Introduced a new setting in 'Interface' settings, providing the ability to enable or disable the expanded guided response regeneration menu. This offers users more control over their chat workflow and interface preferences.
|
||||
- ✨ **General UI/UX Enhancements**: Implemented various user interface and experience improvements, including more rounded corners for cards in the Knowledge, Prompts, and Tools sections, and minor layout adjustments within the chat Navbar for improved visual consistency.
|
||||
- 🌐 **Localization & Internationalization Improvements**: Introduced support for the Kabyle (Taqbaylit) language, refined and expanded translations for Chinese, expanding the platform's linguistic coverage.
|
||||
|
||||
### Fixed
|
||||
|
||||
- 🐞 **OpenAI Error Message Propagation**: Resolved an issue where specific OpenAI API errors (e.g., 'Organization Not Verified') were obscured by generic 'JSONResponse' iterable errors. The system now correctly propagates detailed and actionable error messages from OpenAI to the user.
|
||||
- 🌲 **Pinecone Insert Issue**: Fixed a bug that prevented proper insertion of items into Pinecone vector databases.
|
||||
- 📦 **S3 Vector Issue**: Resolved a bug where s3vector functionality failed due to incorrect import paths.
|
||||
- 🏠 **Landing Page Option Setting Not Working**: Fixed an issue where the landing page option in settings was not functioning as intended.
|
||||
|
||||
## [0.6.21] - 2025-08-10
|
||||
|
||||
### Added
|
||||
|
||||
- 👥 **User Groups in Edit Modal**: Added display of user groups information in the user edit modal, allowing administrators to view and manage group memberships directly when editing a user.
|
||||
|
||||
### Fixed
|
||||
|
||||
- 🐞 **Chat Completion 'model_id' Error**: Resolved a critical issue where chat completions failed with an "undefined model_id" error after upgrading to version 0.6.20, ensuring all models now function correctly and reliably.
|
||||
- 🛠️ **Audit Log User Information Logging**: Fixed an issue where user information was not being correctly logged in the audit trail due to an unreflected function prototype change, ensuring complete logging for administrative oversight.
|
||||
- 🛠️ **OpenTelemetry Configuration Consistency**: Fixed an issue where OpenTelemetry metric and log exporters' 'insecure' settings did not correctly default to the general OpenTelemetry 'insecure' flag, ensuring consistent security configurations across all OpenTelemetry exports.
|
||||
- 📝 **Reply Input Content Display**: Fixed an issue where replying to a message incorrectly displayed '{{INPUT_CONTENT}}' instead of the actual message content, ensuring proper content display in replies.
|
||||
- 🌐 **Localization & Internationalization Improvements**: Refined and expanded translations for Catalan, Korean, Spanish and Irish, ensuring a more fluent and native experience for global users.
|
||||
|
||||
## [0.6.20] - 2025-08-10
|
||||
|
||||
### Fixed
|
||||
|
||||
- 🛠️ **Quick Actions "Add" Behavior**: Fixed a bug where using the "Add" button in Quick Actions would add the resulting message as the very first message in the chat, instead of appending it to the latest message.
|
||||
|
||||
## [0.6.19] - 2025-08-09
|
||||
|
||||
### Added
|
||||
|
||||
+31
-25
@@ -3,6 +3,7 @@
|
||||
# use build args in the docker build command with --build-arg="BUILDARG=true"
|
||||
ARG USE_CUDA=false
|
||||
ARG USE_OLLAMA=false
|
||||
ARG USE_SLIM=false
|
||||
# Tested with cu117 for CUDA 11 and cu121 for CUDA 12 (default)
|
||||
ARG USE_CUDA_VER=cu128
|
||||
# any sentence transformer model; models to use can be found at https://huggingface.co/models?library=sentence-transformers
|
||||
@@ -43,6 +44,7 @@ FROM python:3.11-slim-bookworm AS base
|
||||
ARG USE_CUDA
|
||||
ARG USE_OLLAMA
|
||||
ARG USE_CUDA_VER
|
||||
ARG USE_SLIM
|
||||
ARG USE_EMBEDDING_MODEL
|
||||
ARG USE_RERANKING_MODEL
|
||||
ARG UID
|
||||
@@ -54,6 +56,7 @@ ENV ENV=prod \
|
||||
# pass build args to the build
|
||||
USE_OLLAMA_DOCKER=${USE_OLLAMA} \
|
||||
USE_CUDA_DOCKER=${USE_CUDA} \
|
||||
USE_SLIM_DOCKER=${USE_SLIM} \
|
||||
USE_CUDA_DOCKER_VER=${USE_CUDA_VER} \
|
||||
USE_EMBEDDING_MODEL_DOCKER=${USE_EMBEDDING_MODEL} \
|
||||
USE_RERANKING_MODEL_DOCKER=${USE_RERANKING_MODEL}
|
||||
@@ -108,34 +111,19 @@ RUN echo -n 00000000-0000-0000-0000-000000000000 > $HOME/.cache/chroma/telemetry
|
||||
# Make sure the user has access to the app and root directory
|
||||
RUN chown -R $UID:$GID /app $HOME
|
||||
|
||||
RUN if [ "$USE_OLLAMA" = "true" ]; then \
|
||||
apt-get update && \
|
||||
# Install pandoc and netcat
|
||||
apt-get install -y --no-install-recommends git build-essential pandoc netcat-openbsd curl && \
|
||||
apt-get install -y --no-install-recommends gcc python3-dev && \
|
||||
# for RAG OCR
|
||||
apt-get install -y --no-install-recommends ffmpeg libsm6 libxext6 && \
|
||||
# install helper tools
|
||||
apt-get install -y --no-install-recommends curl jq && \
|
||||
# install ollama
|
||||
curl -fsSL https://ollama.com/install.sh | sh && \
|
||||
# cleanup
|
||||
rm -rf /var/lib/apt/lists/*; \
|
||||
else \
|
||||
apt-get update && \
|
||||
# Install pandoc, netcat and gcc
|
||||
apt-get install -y --no-install-recommends git build-essential pandoc gcc netcat-openbsd curl jq && \
|
||||
apt-get install -y --no-install-recommends gcc python3-dev && \
|
||||
# for RAG OCR
|
||||
apt-get install -y --no-install-recommends ffmpeg libsm6 libxext6 && \
|
||||
# cleanup
|
||||
rm -rf /var/lib/apt/lists/*; \
|
||||
fi
|
||||
# Install common system dependencies
|
||||
RUN apt-get update && \
|
||||
apt-get install -y --no-install-recommends \
|
||||
git build-essential pandoc gcc netcat-openbsd curl jq \
|
||||
python3-dev \
|
||||
ffmpeg libsm6 libxext6 \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# install python dependencies
|
||||
COPY --chown=$UID:$GID ./backend/requirements.txt ./requirements.txt
|
||||
|
||||
RUN pip3 install --no-cache-dir uv && \
|
||||
if [ "$USE_SLIM" != "true" ]; then \
|
||||
if [ "$USE_CUDA" = "true" ]; then \
|
||||
# If you use CUDA the whisper and embedding model will be downloaded on first use
|
||||
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/$USE_CUDA_DOCKER_VER --no-cache-dir && \
|
||||
@@ -150,9 +138,18 @@ RUN pip3 install --no-cache-dir uv && \
|
||||
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'])"; \
|
||||
python -c "import os; import tiktoken; tiktoken.get_encoding(os.environ['TIKTOKEN_ENCODING_NAME'])"; \
|
||||
fi; \
|
||||
chown -R $UID:$GID /app/backend/data/
|
||||
|
||||
else \
|
||||
uv pip install --system -r requirements.txt --no-cache-dir; \
|
||||
fi; \
|
||||
mkdir -p /app/backend/data && chown -R $UID:$GID /app/backend/data/
|
||||
|
||||
# Install Ollama if requested
|
||||
RUN if [ "$USE_OLLAMA" = "true" ] && [ "$USE_SLIM" != "true" ]; then \
|
||||
date +%s > /tmp/ollama_build_hash && \
|
||||
echo "Cache broken at timestamp: `cat /tmp/ollama_build_hash`" && \
|
||||
curl -fsSL https://ollama.com/install.sh | sh && \
|
||||
rm -rf /var/lib/apt/lists/*; \
|
||||
fi
|
||||
|
||||
# copy embedding weight from build
|
||||
# RUN mkdir -p /root/.cache/chroma/onnx_models/all-MiniLM-L6-v2
|
||||
@@ -170,6 +167,15 @@ EXPOSE 8080
|
||||
|
||||
HEALTHCHECK CMD curl --silent --fail http://localhost:${PORT:-8080}/health | jq -ne 'input.status == true' || exit 1
|
||||
|
||||
# Minimal, atomic permission hardening for OpenShift (arbitrary UID):
|
||||
# - Group 0 owns /app and /root
|
||||
# - Directories are group-writable and have SGID so new files inherit GID 0
|
||||
RUN set -eux; \
|
||||
chgrp -R 0 /app /root || true; \
|
||||
chmod -R g+rwX /app /root || true; \
|
||||
find /app -type d -exec chmod g+s {} + || true; \
|
||||
find /root -type d -exec chmod g+s {} + || true
|
||||
|
||||
USER $UID:$GID
|
||||
|
||||
ARG BUILD_HASH
|
||||
|
||||
@@ -70,7 +70,7 @@ Want to learn more about Open WebUI's features? Check out our [Open WebUI docume
|
||||
#### Emerald
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<!-- <tr>
|
||||
<td>
|
||||
<a href="https://n8n.io/" target="_blank">
|
||||
<img src="https://docs.openwebui.com/sponsors/logos/n8n.png" alt="n8n" style="width: 8rem; height: 8rem; border-radius: .75rem;" />
|
||||
@@ -79,7 +79,7 @@ Want to learn more about Open WebUI's features? Check out our [Open WebUI docume
|
||||
<td>
|
||||
<a href="https://n8n.io/">n8n</a> • Does your interface have a backend yet?<br>Try <a href="https://n8n.io/">n8n</a>
|
||||
</td>
|
||||
</tr>
|
||||
</tr> -->
|
||||
<tr>
|
||||
<td>
|
||||
<a href="https://tailscale.com/blog/self-host-a-local-ai-stack/?utm_source=OpenWebUI&utm_medium=paid-ad-placement&utm_campaign=OpenWebUI-Docs" target="_blank">
|
||||
@@ -90,6 +90,16 @@ Want to learn more about Open WebUI's features? Check out our [Open WebUI docume
|
||||
<a href="https://tailscale.com/blog/self-host-a-local-ai-stack/?utm_source=OpenWebUI&utm_medium=paid-ad-placement&utm_campaign=OpenWebUI-Docs">Tailscale</a> • Connect self-hosted AI to any device with Tailscale
|
||||
</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>
|
||||
<a href="https://warp.dev/open-webui" target="_blank">
|
||||
<img src="https://docs.openwebui.com/sponsors/logos/warp.png" alt="Warp" style="width: 8rem; height: 8rem; border-radius: .75rem;" />
|
||||
</a>
|
||||
</td>
|
||||
<td>
|
||||
<a href="https://warp.dev/open-webui">Warp</a> • The intelligent terminal for developers
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
---
|
||||
|
||||
@@ -10,7 +10,7 @@ script_location = migrations
|
||||
|
||||
# sys.path path, will be prepended to sys.path if present.
|
||||
# defaults to the current working directory.
|
||||
prepend_sys_path = .
|
||||
prepend_sys_path = ..
|
||||
|
||||
# timezone to use when rendering the date within the migration file
|
||||
# as well as the filename.
|
||||
|
||||
@@ -510,7 +510,7 @@ OAUTH_EMAIL_CLAIM = PersistentConfig(
|
||||
OAUTH_GROUPS_CLAIM = PersistentConfig(
|
||||
"OAUTH_GROUPS_CLAIM",
|
||||
"oauth.oidc.group_claim",
|
||||
os.environ.get("OAUTH_GROUP_CLAIM", "groups"),
|
||||
os.environ.get("OAUTH_GROUPS_CLAIM", os.environ.get("OAUTH_GROUP_CLAIM", "groups")),
|
||||
)
|
||||
|
||||
ENABLE_OAUTH_ROLE_MANAGEMENT = PersistentConfig(
|
||||
@@ -871,7 +871,7 @@ CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
||||
ENABLE_DIRECT_CONNECTIONS = PersistentConfig(
|
||||
"ENABLE_DIRECT_CONNECTIONS",
|
||||
"direct.enable",
|
||||
os.environ.get("ENABLE_DIRECT_CONNECTIONS", "True").lower() == "true",
|
||||
os.environ.get("ENABLE_DIRECT_CONNECTIONS", "False").lower() == "true",
|
||||
)
|
||||
|
||||
####################################
|
||||
@@ -953,6 +953,9 @@ GEMINI_API_BASE_URL = os.environ.get("GEMINI_API_BASE_URL", "")
|
||||
|
||||
if OPENAI_API_BASE_URL == "":
|
||||
OPENAI_API_BASE_URL = "https://api.openai.com/v1"
|
||||
else:
|
||||
if OPENAI_API_BASE_URL.endswith("/"):
|
||||
OPENAI_API_BASE_URL = OPENAI_API_BASE_URL[:-1]
|
||||
|
||||
OPENAI_API_KEYS = os.environ.get("OPENAI_API_KEYS", "")
|
||||
OPENAI_API_KEYS = OPENAI_API_KEYS if OPENAI_API_KEYS != "" else OPENAI_API_KEY
|
||||
@@ -1205,6 +1208,23 @@ USER_PERMISSIONS_CHAT_DELETE = (
|
||||
os.environ.get("USER_PERMISSIONS_CHAT_DELETE", "True").lower() == "true"
|
||||
)
|
||||
|
||||
USER_PERMISSIONS_CHAT_DELETE_MESSAGE = (
|
||||
os.environ.get("USER_PERMISSIONS_CHAT_DELETE_MESSAGE", "True").lower() == "true"
|
||||
)
|
||||
|
||||
USER_PERMISSIONS_CHAT_CONTINUE_RESPONSE = (
|
||||
os.environ.get("USER_PERMISSIONS_CHAT_CONTINUE_RESPONSE", "True").lower() == "true"
|
||||
)
|
||||
|
||||
USER_PERMISSIONS_CHAT_REGENERATE_RESPONSE = (
|
||||
os.environ.get("USER_PERMISSIONS_CHAT_REGENERATE_RESPONSE", "True").lower()
|
||||
== "true"
|
||||
)
|
||||
|
||||
USER_PERMISSIONS_CHAT_RATE_RESPONSE = (
|
||||
os.environ.get("USER_PERMISSIONS_CHAT_RATE_RESPONSE", "True").lower() == "true"
|
||||
)
|
||||
|
||||
USER_PERMISSIONS_CHAT_EDIT = (
|
||||
os.environ.get("USER_PERMISSIONS_CHAT_EDIT", "True").lower() == "true"
|
||||
)
|
||||
@@ -1287,6 +1307,10 @@ DEFAULT_USER_PERMISSIONS = {
|
||||
"params": USER_PERMISSIONS_CHAT_PARAMS,
|
||||
"file_upload": USER_PERMISSIONS_CHAT_FILE_UPLOAD,
|
||||
"delete": USER_PERMISSIONS_CHAT_DELETE,
|
||||
"delete_message": USER_PERMISSIONS_CHAT_DELETE_MESSAGE,
|
||||
"continue_response": USER_PERMISSIONS_CHAT_CONTINUE_RESPONSE,
|
||||
"regenerate_response": USER_PERMISSIONS_CHAT_REGENERATE_RESPONSE,
|
||||
"rate_response": USER_PERMISSIONS_CHAT_RATE_RESPONSE,
|
||||
"edit": USER_PERMISSIONS_CHAT_EDIT,
|
||||
"share": USER_PERMISSIONS_CHAT_SHARE,
|
||||
"export": USER_PERMISSIONS_CHAT_EXPORT,
|
||||
@@ -1355,6 +1379,14 @@ ENABLE_ADMIN_WORKSPACE_CONTENT_ACCESS = (
|
||||
os.environ.get("ENABLE_ADMIN_WORKSPACE_CONTENT_ACCESS", "True").lower() == "true"
|
||||
)
|
||||
|
||||
BYPASS_ADMIN_ACCESS_CONTROL = (
|
||||
os.environ.get(
|
||||
"BYPASS_ADMIN_ACCESS_CONTROL",
|
||||
os.environ.get("ENABLE_ADMIN_WORKSPACE_CONTENT_ACCESS", "True"),
|
||||
).lower()
|
||||
== "true"
|
||||
)
|
||||
|
||||
ENABLE_ADMIN_CHAT_ACCESS = (
|
||||
os.environ.get("ENABLE_ADMIN_CHAT_ACCESS", "True").lower() == "true"
|
||||
)
|
||||
@@ -1857,6 +1889,11 @@ CODE_INTERPRETER_JUPYTER_TIMEOUT = PersistentConfig(
|
||||
),
|
||||
)
|
||||
|
||||
CODE_INTERPRETER_BLOCKED_MODULES = [
|
||||
library.strip()
|
||||
for library in os.environ.get("CODE_INTERPRETER_BLOCKED_MODULES", "").split(",")
|
||||
if library.strip()
|
||||
]
|
||||
|
||||
DEFAULT_CODE_INTERPRETER_PROMPT = """
|
||||
#### Tools Available
|
||||
@@ -2611,6 +2648,14 @@ WEB_LOADER_ENGINE = PersistentConfig(
|
||||
os.environ.get("WEB_LOADER_ENGINE", ""),
|
||||
)
|
||||
|
||||
|
||||
WEB_LOADER_CONCURRENT_REQUESTS = PersistentConfig(
|
||||
"WEB_LOADER_CONCURRENT_REQUESTS",
|
||||
"rag.web.loader.concurrent_requests",
|
||||
int(os.getenv("WEB_LOADER_CONCURRENT_REQUESTS", "10")),
|
||||
)
|
||||
|
||||
|
||||
ENABLE_WEB_LOADER_SSL_VERIFICATION = PersistentConfig(
|
||||
"ENABLE_WEB_LOADER_SSL_VERIFICATION",
|
||||
"rag.web.loader.ssl_verification",
|
||||
|
||||
@@ -17,14 +17,17 @@ from open_webui.constants import ERROR_MESSAGES
|
||||
# Load .env file
|
||||
####################################
|
||||
|
||||
OPEN_WEBUI_DIR = Path(__file__).parent # the path containing this file
|
||||
print(OPEN_WEBUI_DIR)
|
||||
# Use .resolve() to get the canonical path, removing any '..' or '.' components
|
||||
ENV_FILE_PATH = Path(__file__).resolve()
|
||||
|
||||
BACKEND_DIR = OPEN_WEBUI_DIR.parent # the path containing this file
|
||||
BASE_DIR = BACKEND_DIR.parent # the path containing the backend/
|
||||
# OPEN_WEBUI_DIR should be the directory where env.py resides (open_webui/)
|
||||
OPEN_WEBUI_DIR = ENV_FILE_PATH.parent
|
||||
|
||||
print(BACKEND_DIR)
|
||||
print(BASE_DIR)
|
||||
# BACKEND_DIR is the parent of OPEN_WEBUI_DIR (backend/)
|
||||
BACKEND_DIR = OPEN_WEBUI_DIR.parent
|
||||
|
||||
# BASE_DIR is the parent of BACKEND_DIR (open-webui-dev/)
|
||||
BASE_DIR = BACKEND_DIR.parent
|
||||
|
||||
try:
|
||||
from dotenv import find_dotenv, load_dotenv
|
||||
@@ -336,6 +339,21 @@ else:
|
||||
except Exception:
|
||||
DATABASE_POOL_RECYCLE = 3600
|
||||
|
||||
DATABASE_ENABLE_SQLITE_WAL = (
|
||||
os.environ.get("DATABASE_ENABLE_SQLITE_WAL", "False").lower() == "true"
|
||||
)
|
||||
|
||||
DATABASE_USER_ACTIVE_STATUS_UPDATE_INTERVAL = os.environ.get(
|
||||
"DATABASE_USER_ACTIVE_STATUS_UPDATE_INTERVAL", None
|
||||
)
|
||||
if DATABASE_USER_ACTIVE_STATUS_UPDATE_INTERVAL is not None:
|
||||
try:
|
||||
DATABASE_USER_ACTIVE_STATUS_UPDATE_INTERVAL = float(
|
||||
DATABASE_USER_ACTIVE_STATUS_UPDATE_INTERVAL
|
||||
)
|
||||
except Exception:
|
||||
DATABASE_USER_ACTIVE_STATUS_UPDATE_INTERVAL = 0.0
|
||||
|
||||
RESET_CONFIG_ON_START = (
|
||||
os.environ.get("RESET_CONFIG_ON_START", "False").lower() == "true"
|
||||
)
|
||||
@@ -344,6 +362,8 @@ ENABLE_REALTIME_CHAT_SAVE = (
|
||||
os.environ.get("ENABLE_REALTIME_CHAT_SAVE", "False").lower() == "true"
|
||||
)
|
||||
|
||||
ENABLE_QUERIES_CACHE = os.environ.get("ENABLE_QUERIES_CACHE", "False").lower() == "true"
|
||||
|
||||
####################################
|
||||
# REDIS
|
||||
####################################
|
||||
@@ -384,6 +404,10 @@ except ValueError:
|
||||
####################################
|
||||
|
||||
WEBUI_AUTH = os.environ.get("WEBUI_AUTH", "True").lower() == "true"
|
||||
|
||||
ENABLE_INITIAL_ADMIN_SIGNUP = (
|
||||
os.environ.get("ENABLE_INITIAL_ADMIN_SIGNUP", "False").lower() == "true"
|
||||
)
|
||||
ENABLE_SIGNUP_PASSWORD_CONFIRMATION = (
|
||||
os.environ.get("ENABLE_SIGNUP_PASSWORD_CONFIRMATION", "False").lower() == "true"
|
||||
)
|
||||
@@ -509,6 +533,19 @@ else:
|
||||
CHAT_RESPONSE_STREAM_DELTA_CHUNK_SIZE = 1
|
||||
|
||||
|
||||
CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES = os.environ.get(
|
||||
"CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES", "10"
|
||||
)
|
||||
|
||||
if CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES == "":
|
||||
CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES = 10
|
||||
else:
|
||||
try:
|
||||
CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES = int(CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES)
|
||||
except Exception:
|
||||
CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES = 10
|
||||
|
||||
|
||||
####################################
|
||||
# WEBSOCKET SUPPORT
|
||||
####################################
|
||||
@@ -677,6 +714,7 @@ AUDIT_EXCLUDED_PATHS = [path.lstrip("/") for path in AUDIT_EXCLUDED_PATHS]
|
||||
####################################
|
||||
|
||||
ENABLE_OTEL = os.environ.get("ENABLE_OTEL", "False").lower() == "true"
|
||||
ENABLE_OTEL_TRACES = os.environ.get("ENABLE_OTEL_TRACES", "False").lower() == "true"
|
||||
ENABLE_OTEL_METRICS = os.environ.get("ENABLE_OTEL_METRICS", "False").lower() == "true"
|
||||
ENABLE_OTEL_LOGS = os.environ.get("ENABLE_OTEL_LOGS", "False").lower() == "true"
|
||||
|
||||
@@ -693,10 +731,16 @@ OTEL_EXPORTER_OTLP_INSECURE = (
|
||||
os.environ.get("OTEL_EXPORTER_OTLP_INSECURE", "False").lower() == "true"
|
||||
)
|
||||
OTEL_METRICS_EXPORTER_OTLP_INSECURE = (
|
||||
os.environ.get("OTEL_METRICS_EXPORTER_OTLP_INSECURE", "False").lower() == "true"
|
||||
os.environ.get(
|
||||
"OTEL_METRICS_EXPORTER_OTLP_INSECURE", str(OTEL_EXPORTER_OTLP_INSECURE)
|
||||
).lower()
|
||||
== "true"
|
||||
)
|
||||
OTEL_LOGS_EXPORTER_OTLP_INSECURE = (
|
||||
os.environ.get("OTEL_LOGS_EXPORTER_OTLP_INSECURE", "False").lower() == "true"
|
||||
os.environ.get(
|
||||
"OTEL_LOGS_EXPORTER_OTLP_INSECURE", str(OTEL_EXPORTER_OTLP_INSECURE)
|
||||
).lower()
|
||||
== "true"
|
||||
)
|
||||
OTEL_SERVICE_NAME = os.environ.get("OTEL_SERVICE_NAME", "open-webui")
|
||||
OTEL_RESOURCE_ATTRIBUTES = os.environ.get(
|
||||
|
||||
@@ -47,7 +47,7 @@ from open_webui.utils.misc import (
|
||||
)
|
||||
from open_webui.utils.payload import (
|
||||
apply_model_params_to_body_openai,
|
||||
apply_model_system_prompt_to_body,
|
||||
apply_system_prompt_to_body,
|
||||
)
|
||||
|
||||
|
||||
@@ -232,7 +232,7 @@ async def generate_function_chat_completion(
|
||||
"__metadata__": metadata,
|
||||
"__request__": request,
|
||||
}
|
||||
extra_params["__tools__"] = get_tools(
|
||||
extra_params["__tools__"] = await get_tools(
|
||||
request,
|
||||
tool_ids,
|
||||
user,
|
||||
@@ -253,9 +253,7 @@ async def generate_function_chat_completion(
|
||||
if params:
|
||||
system = params.pop("system", None)
|
||||
form_data = apply_model_params_to_body_openai(params, form_data)
|
||||
form_data = apply_model_system_prompt_to_body(
|
||||
system, form_data, metadata, user
|
||||
)
|
||||
form_data = apply_system_prompt_to_body(system, form_data, metadata, user)
|
||||
|
||||
pipe_id = get_pipe_id(form_data)
|
||||
function_module = get_function_module_by_id(request, pipe_id)
|
||||
|
||||
@@ -14,9 +14,10 @@ from open_webui.env import (
|
||||
DATABASE_POOL_RECYCLE,
|
||||
DATABASE_POOL_SIZE,
|
||||
DATABASE_POOL_TIMEOUT,
|
||||
DATABASE_ENABLE_SQLITE_WAL,
|
||||
)
|
||||
from peewee_migrate import Router
|
||||
from sqlalchemy import Dialect, create_engine, MetaData, types
|
||||
from sqlalchemy import Dialect, create_engine, MetaData, event, types
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
from sqlalchemy.orm import scoped_session, sessionmaker
|
||||
from sqlalchemy.pool import QueuePool, NullPool
|
||||
@@ -114,6 +115,16 @@ elif "sqlite" in SQLALCHEMY_DATABASE_URL:
|
||||
engine = create_engine(
|
||||
SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
|
||||
)
|
||||
|
||||
def on_connect(dbapi_connection, connection_record):
|
||||
cursor = dbapi_connection.cursor()
|
||||
if DATABASE_ENABLE_SQLITE_WAL:
|
||||
cursor.execute("PRAGMA journal_mode=WAL")
|
||||
else:
|
||||
cursor.execute("PRAGMA journal_mode=DELETE")
|
||||
cursor.close()
|
||||
|
||||
event.listen(engine, "connect", on_connect)
|
||||
else:
|
||||
if isinstance(DATABASE_POOL_SIZE, int):
|
||||
if DATABASE_POOL_SIZE > 0:
|
||||
|
||||
+126
-60
@@ -57,6 +57,7 @@ from open_webui.utils.logger import start_logger
|
||||
from open_webui.socket.main import (
|
||||
app as socket_app,
|
||||
periodic_usage_pool_cleanup,
|
||||
get_event_emitter,
|
||||
get_models_in_use,
|
||||
get_active_user_ids,
|
||||
)
|
||||
@@ -185,6 +186,7 @@ from open_webui.config import (
|
||||
FIRECRAWL_API_BASE_URL,
|
||||
FIRECRAWL_API_KEY,
|
||||
WEB_LOADER_ENGINE,
|
||||
WEB_LOADER_CONCURRENT_REQUESTS,
|
||||
WHISPER_MODEL,
|
||||
WHISPER_VAD_FILTER,
|
||||
WHISPER_LANGUAGE,
|
||||
@@ -327,6 +329,7 @@ from open_webui.config import (
|
||||
ENABLE_MESSAGE_RATING,
|
||||
ENABLE_USER_WEBHOOKS,
|
||||
ENABLE_EVALUATION_ARENA_MODELS,
|
||||
BYPASS_ADMIN_ACCESS_CONTROL,
|
||||
USER_PERMISSIONS,
|
||||
DEFAULT_USER_ROLE,
|
||||
PENDING_USER_OVERLAY_CONTENT,
|
||||
@@ -375,6 +378,7 @@ from open_webui.config import (
|
||||
RESPONSE_WATERMARK,
|
||||
# Admin
|
||||
ENABLE_ADMIN_CHAT_ACCESS,
|
||||
BYPASS_ADMIN_ACCESS_CONTROL,
|
||||
ENABLE_ADMIN_EXPORT,
|
||||
# Tasks
|
||||
TASK_MODEL,
|
||||
@@ -463,6 +467,7 @@ from open_webui.utils.redis import get_redis_connection
|
||||
from open_webui.tasks import (
|
||||
redis_task_command_listener,
|
||||
list_task_ids_by_item_id,
|
||||
create_task,
|
||||
stop_task,
|
||||
list_tasks,
|
||||
) # Import from tasks.py
|
||||
@@ -853,7 +858,10 @@ app.state.config.WEB_SEARCH_ENGINE = WEB_SEARCH_ENGINE
|
||||
app.state.config.WEB_SEARCH_DOMAIN_FILTER_LIST = WEB_SEARCH_DOMAIN_FILTER_LIST
|
||||
app.state.config.WEB_SEARCH_RESULT_COUNT = WEB_SEARCH_RESULT_COUNT
|
||||
app.state.config.WEB_SEARCH_CONCURRENT_REQUESTS = WEB_SEARCH_CONCURRENT_REQUESTS
|
||||
|
||||
app.state.config.WEB_LOADER_ENGINE = WEB_LOADER_ENGINE
|
||||
app.state.config.WEB_LOADER_CONCURRENT_REQUESTS = WEB_LOADER_CONCURRENT_REQUESTS
|
||||
|
||||
app.state.config.WEB_SEARCH_TRUST_ENV = WEB_SEARCH_TRUST_ENV
|
||||
app.state.config.BYPASS_WEB_SEARCH_EMBEDDING_AND_RETRIEVAL = (
|
||||
BYPASS_WEB_SEARCH_EMBEDDING_AND_RETRIEVAL
|
||||
@@ -916,14 +924,19 @@ try:
|
||||
app.state.config.RAG_EMBEDDING_MODEL,
|
||||
RAG_EMBEDDING_MODEL_AUTO_UPDATE,
|
||||
)
|
||||
|
||||
app.state.rf = get_rf(
|
||||
app.state.config.RAG_RERANKING_ENGINE,
|
||||
app.state.config.RAG_RERANKING_MODEL,
|
||||
app.state.config.RAG_EXTERNAL_RERANKER_URL,
|
||||
app.state.config.RAG_EXTERNAL_RERANKER_API_KEY,
|
||||
RAG_RERANKING_MODEL_AUTO_UPDATE,
|
||||
)
|
||||
if (
|
||||
app.state.config.ENABLE_RAG_HYBRID_SEARCH
|
||||
and not app.state.config.BYPASS_EMBEDDING_AND_RETRIEVAL
|
||||
):
|
||||
app.state.rf = get_rf(
|
||||
app.state.config.RAG_RERANKING_ENGINE,
|
||||
app.state.config.RAG_RERANKING_MODEL,
|
||||
app.state.config.RAG_EXTERNAL_RERANKER_URL,
|
||||
app.state.config.RAG_EXTERNAL_RERANKER_API_KEY,
|
||||
RAG_RERANKING_MODEL_AUTO_UPDATE,
|
||||
)
|
||||
else:
|
||||
app.state.rf = None
|
||||
except Exception as e:
|
||||
log.error(f"Error updating models: {e}")
|
||||
pass
|
||||
@@ -1261,6 +1274,7 @@ if audit_level != AuditLevel.NONE:
|
||||
|
||||
|
||||
@app.get("/api/models")
|
||||
@app.get("/api/v1/models") # Experimental: Compatibility with OpenAI API
|
||||
async def get_models(
|
||||
request: Request, refresh: bool = False, user=Depends(get_verified_user)
|
||||
):
|
||||
@@ -1280,8 +1294,12 @@ async def get_models(
|
||||
|
||||
model_info = Models.get_model_by_id(model["id"])
|
||||
if model_info:
|
||||
if user.id == model_info.user_id or has_access(
|
||||
user.id, type="read", access_control=model_info.access_control
|
||||
if (
|
||||
(user.role == "admin" and BYPASS_ADMIN_ACCESS_CONTROL)
|
||||
or user.id == model_info.user_id
|
||||
or has_access(
|
||||
user.id, type="read", access_control=model_info.access_control
|
||||
)
|
||||
):
|
||||
filtered_models.append(model)
|
||||
|
||||
@@ -1316,11 +1334,17 @@ async def get_models(
|
||||
model_order_dict = {model_id: i for i, model_id in enumerate(model_order_list)}
|
||||
# Sort models by order list priority, with fallback for those not in the list
|
||||
models.sort(
|
||||
key=lambda x: (model_order_dict.get(x["id"], float("inf")), x["name"])
|
||||
key=lambda model: (
|
||||
model_order_dict.get(model.get("id", ""), float("inf")),
|
||||
(model.get("name", "") or ""),
|
||||
)
|
||||
)
|
||||
|
||||
# Filter out models that the user does not have access to
|
||||
if user.role == "user" and not BYPASS_MODEL_ACCESS_CONTROL:
|
||||
if (
|
||||
user.role == "user"
|
||||
or (user.role == "admin" and not BYPASS_ADMIN_ACCESS_CONTROL)
|
||||
) and not BYPASS_MODEL_ACCESS_CONTROL:
|
||||
models = get_filtered_models(models, user)
|
||||
|
||||
log.debug(
|
||||
@@ -1341,6 +1365,7 @@ async def get_base_models(request: Request, user=Depends(get_admin_user)):
|
||||
|
||||
|
||||
@app.post("/api/embeddings")
|
||||
@app.post("/api/v1/embeddings") # Experimental: Compatibility with OpenAI API
|
||||
async def embeddings(
|
||||
request: Request, form_data: dict, user=Depends(get_verified_user)
|
||||
):
|
||||
@@ -1367,6 +1392,7 @@ async def embeddings(
|
||||
|
||||
|
||||
@app.post("/api/chat/completions")
|
||||
@app.post("/api/v1/chat/completions") # Experimental: Compatibility with OpenAI API
|
||||
async def chat_completion(
|
||||
request: Request,
|
||||
form_data: dict,
|
||||
@@ -1375,13 +1401,13 @@ async def chat_completion(
|
||||
if not request.app.state.MODELS:
|
||||
await get_all_models(request, user=user)
|
||||
|
||||
model_id = form_data.get("model", None)
|
||||
model_item = form_data.pop("model_item", {})
|
||||
tasks = form_data.pop("background_tasks", None)
|
||||
|
||||
metadata = {}
|
||||
try:
|
||||
if not model_item.get("direct", False):
|
||||
model_id = form_data.get("model", None)
|
||||
if model_id not in request.app.state.MODELS:
|
||||
raise Exception("Model not found")
|
||||
|
||||
@@ -1389,7 +1415,9 @@ async def chat_completion(
|
||||
model_info = Models.get_model_by_id(model_id)
|
||||
|
||||
# Check if user has access to the model
|
||||
if not BYPASS_MODEL_ACCESS_CONTROL and user.role == "user":
|
||||
if not BYPASS_MODEL_ACCESS_CONTROL and (
|
||||
user.role != "admin" or not BYPASS_ADMIN_ACCESS_CONTROL
|
||||
):
|
||||
try:
|
||||
check_model_access(user, model)
|
||||
except Exception as e:
|
||||
@@ -1409,11 +1437,15 @@ async def chat_completion(
|
||||
stream_delta_chunk_size = form_data.get("params", {}).get(
|
||||
"stream_delta_chunk_size"
|
||||
)
|
||||
reasoning_tags = form_data.get("params", {}).get("reasoning_tags")
|
||||
|
||||
# Model Params
|
||||
if model_info_params.get("stream_delta_chunk_size"):
|
||||
stream_delta_chunk_size = model_info_params.get("stream_delta_chunk_size")
|
||||
|
||||
if model_info_params.get("reasoning_tags") is not None:
|
||||
reasoning_tags = model_info_params.get("reasoning_tags")
|
||||
|
||||
metadata = {
|
||||
"user_id": user.id,
|
||||
"chat_id": form_data.pop("chat_id", None),
|
||||
@@ -1429,6 +1461,7 @@ async def chat_completion(
|
||||
"direct": model_item.get("direct", False),
|
||||
"params": {
|
||||
"stream_delta_chunk_size": stream_delta_chunk_size,
|
||||
"reasoning_tags": reasoning_tags,
|
||||
"function_calling": (
|
||||
"native"
|
||||
if (
|
||||
@@ -1441,66 +1474,89 @@ async def chat_completion(
|
||||
}
|
||||
|
||||
if metadata.get("chat_id") and (user and user.role != "admin"):
|
||||
chat = Chats.get_chat_by_id_and_user_id(metadata["chat_id"], user.id)
|
||||
if chat is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=ERROR_MESSAGES.DEFAULT(),
|
||||
)
|
||||
if metadata["chat_id"] != "local":
|
||||
chat = Chats.get_chat_by_id_and_user_id(metadata["chat_id"], user.id)
|
||||
if chat is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=ERROR_MESSAGES.DEFAULT(),
|
||||
)
|
||||
|
||||
request.state.metadata = metadata
|
||||
form_data["metadata"] = metadata
|
||||
|
||||
form_data, metadata, events = await process_chat_payload(
|
||||
request, form_data, user, metadata, model
|
||||
)
|
||||
except Exception as e:
|
||||
log.debug(f"Error processing chat payload: {e}")
|
||||
if metadata.get("chat_id") and metadata.get("message_id"):
|
||||
# Update the chat message with the error
|
||||
Chats.upsert_message_to_chat_by_id_and_message_id(
|
||||
metadata["chat_id"],
|
||||
metadata["message_id"],
|
||||
{
|
||||
"error": {"content": str(e)},
|
||||
},
|
||||
)
|
||||
|
||||
log.debug(f"Error processing chat metadata: {e}")
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=str(e),
|
||||
)
|
||||
|
||||
try:
|
||||
response = await chat_completion_handler(request, form_data, user)
|
||||
if metadata.get("chat_id") and metadata.get("message_id"):
|
||||
Chats.upsert_message_to_chat_by_id_and_message_id(
|
||||
metadata["chat_id"],
|
||||
metadata["message_id"],
|
||||
{
|
||||
"model": model_id,
|
||||
},
|
||||
async def process_chat(request, form_data, user, metadata, model):
|
||||
try:
|
||||
form_data, metadata, events = await process_chat_payload(
|
||||
request, form_data, user, metadata, model
|
||||
)
|
||||
|
||||
return await process_chat_response(
|
||||
request, response, form_data, user, metadata, model, events, tasks
|
||||
)
|
||||
except Exception as e:
|
||||
log.debug(f"Error in chat completion: {e}")
|
||||
if metadata.get("chat_id") and metadata.get("message_id"):
|
||||
# Update the chat message with the error
|
||||
Chats.upsert_message_to_chat_by_id_and_message_id(
|
||||
metadata["chat_id"],
|
||||
metadata["message_id"],
|
||||
{
|
||||
"error": {"content": str(e)},
|
||||
},
|
||||
response = await chat_completion_handler(request, form_data, user)
|
||||
if metadata.get("chat_id") and metadata.get("message_id"):
|
||||
try:
|
||||
Chats.upsert_message_to_chat_by_id_and_message_id(
|
||||
metadata["chat_id"],
|
||||
metadata["message_id"],
|
||||
{
|
||||
"model": model_id,
|
||||
},
|
||||
)
|
||||
except:
|
||||
pass
|
||||
|
||||
return await process_chat_response(
|
||||
request, response, form_data, user, metadata, model, events, tasks
|
||||
)
|
||||
except asyncio.CancelledError:
|
||||
log.info("Chat processing was cancelled")
|
||||
try:
|
||||
event_emitter = get_event_emitter(metadata)
|
||||
await event_emitter(
|
||||
{"type": "task-cancelled"},
|
||||
)
|
||||
except Exception as e:
|
||||
pass
|
||||
except Exception as e:
|
||||
log.debug(f"Error processing chat payload: {e}")
|
||||
if metadata.get("chat_id") and metadata.get("message_id"):
|
||||
# Update the chat message with the error
|
||||
try:
|
||||
Chats.upsert_message_to_chat_by_id_and_message_id(
|
||||
metadata["chat_id"],
|
||||
metadata["message_id"],
|
||||
{
|
||||
"error": {"content": str(e)},
|
||||
},
|
||||
)
|
||||
except:
|
||||
pass
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=str(e),
|
||||
)
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=str(e),
|
||||
if (
|
||||
metadata.get("session_id")
|
||||
and metadata.get("chat_id")
|
||||
and metadata.get("message_id")
|
||||
):
|
||||
# Asynchronous Chat Processing
|
||||
task_id, _ = await create_task(
|
||||
request.app.state.redis,
|
||||
process_chat(request, form_data, user, metadata, model),
|
||||
id=metadata["chat_id"],
|
||||
)
|
||||
return {"status": True, "task_id": task_id}
|
||||
else:
|
||||
return await process_chat(request, form_data, user, metadata, model)
|
||||
|
||||
|
||||
# Alias for chat_completion (Legacy)
|
||||
@@ -1701,6 +1757,16 @@ async def get_app_config(request: Request):
|
||||
}
|
||||
if user is not None and (user.role in ["admin", "user"])
|
||||
else {
|
||||
**(
|
||||
{
|
||||
"ui": {
|
||||
"pending_user_overlay_title": app.state.config.PENDING_USER_OVERLAY_TITLE,
|
||||
"pending_user_overlay_content": app.state.config.PENDING_USER_OVERLAY_CONTENT,
|
||||
}
|
||||
}
|
||||
if user and user.role == "pending"
|
||||
else {}
|
||||
),
|
||||
**(
|
||||
{
|
||||
"metadata": {
|
||||
@@ -1714,7 +1780,7 @@ async def get_app_config(request: Request):
|
||||
}
|
||||
if app.state.LICENSE_METADATA
|
||||
else {}
|
||||
)
|
||||
),
|
||||
}
|
||||
),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Add indexes
|
||||
|
||||
Revision ID: 018012973d35
|
||||
Revises: d31026856c01
|
||||
Create Date: 2025-08-13 03:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision = "018012973d35"
|
||||
down_revision = "d31026856c01"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
# Chat table indexes
|
||||
op.create_index("folder_id_idx", "chat", ["folder_id"])
|
||||
op.create_index("user_id_pinned_idx", "chat", ["user_id", "pinned"])
|
||||
op.create_index("user_id_archived_idx", "chat", ["user_id", "archived"])
|
||||
op.create_index("updated_at_user_id_idx", "chat", ["updated_at", "user_id"])
|
||||
op.create_index("folder_id_user_id_idx", "chat", ["folder_id", "user_id"])
|
||||
|
||||
# Tag table index
|
||||
op.create_index("user_id_idx", "tag", ["user_id"])
|
||||
|
||||
# Function table index
|
||||
op.create_index("is_global_idx", "function", ["is_global"])
|
||||
|
||||
|
||||
def downgrade():
|
||||
# Chat table indexes
|
||||
op.drop_index("folder_id_idx", table_name="chat")
|
||||
op.drop_index("user_id_pinned_idx", table_name="chat")
|
||||
op.drop_index("user_id_archived_idx", table_name="chat")
|
||||
op.drop_index("updated_at_user_id_idx", table_name="chat")
|
||||
op.drop_index("folder_id_user_id_idx", table_name="chat")
|
||||
|
||||
# Tag table index
|
||||
op.drop_index("user_id_idx", table_name="tag")
|
||||
|
||||
# Function table index
|
||||
|
||||
op.drop_index("is_global_idx", table_name="function")
|
||||
@@ -0,0 +1,32 @@
|
||||
"""update user table
|
||||
|
||||
Revision ID: 3af16a1c9fb6
|
||||
Revises: 018012973d35
|
||||
Create Date: 2025-08-21 02:07:18.078283
|
||||
|
||||
"""
|
||||
|
||||
from typing import Sequence, Union
|
||||
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision: str = "3af16a1c9fb6"
|
||||
down_revision: Union[str, None] = "018012973d35"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column("user", sa.Column("username", sa.String(length=50), nullable=True))
|
||||
op.add_column("user", sa.Column("bio", sa.Text(), nullable=True))
|
||||
op.add_column("user", sa.Column("gender", sa.Text(), nullable=True))
|
||||
op.add_column("user", sa.Column("date_of_birth", sa.Date(), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("user", "username")
|
||||
op.drop_column("user", "bio")
|
||||
op.drop_column("user", "gender")
|
||||
op.drop_column("user", "date_of_birth")
|
||||
@@ -73,11 +73,6 @@ class ProfileImageUrlForm(BaseModel):
|
||||
profile_image_url: str
|
||||
|
||||
|
||||
class UpdateProfileForm(BaseModel):
|
||||
profile_image_url: str
|
||||
name: str
|
||||
|
||||
|
||||
class UpdatePasswordForm(BaseModel):
|
||||
password: str
|
||||
new_password: str
|
||||
|
||||
@@ -10,7 +10,7 @@ from open_webui.models.folders import Folders
|
||||
from open_webui.env import SRC_LOG_LEVELS
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from sqlalchemy import BigInteger, Boolean, Column, String, Text, JSON
|
||||
from sqlalchemy import BigInteger, Boolean, Column, String, Text, JSON, Index
|
||||
from sqlalchemy import or_, func, select, and_, text
|
||||
from sqlalchemy.sql import exists
|
||||
from sqlalchemy.sql.expression import bindparam
|
||||
@@ -41,6 +41,20 @@ class Chat(Base):
|
||||
meta = Column(JSON, server_default="{}")
|
||||
folder_id = Column(Text, nullable=True)
|
||||
|
||||
__table_args__ = (
|
||||
# Performance indexes for common queries
|
||||
# WHERE folder_id = ...
|
||||
Index("folder_id_idx", "folder_id"),
|
||||
# WHERE user_id = ... AND pinned = ...
|
||||
Index("user_id_pinned_idx", "user_id", "pinned"),
|
||||
# WHERE user_id = ... AND archived = ...
|
||||
Index("user_id_archived_idx", "user_id", "archived"),
|
||||
# WHERE user_id = ... ORDER BY updated_at DESC
|
||||
Index("updated_at_user_id_idx", "updated_at", "user_id"),
|
||||
# WHERE folder_id = ... AND user_id = ...
|
||||
Index("folder_id_user_id_idx", "folder_id", "user_id"),
|
||||
)
|
||||
|
||||
|
||||
class ChatModel(BaseModel):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
@@ -6,7 +6,7 @@ from open_webui.internal.db import Base, JSONField, get_db
|
||||
from open_webui.models.users import Users
|
||||
from open_webui.env import SRC_LOG_LEVELS
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from sqlalchemy import BigInteger, Boolean, Column, String, Text
|
||||
from sqlalchemy import BigInteger, Boolean, Column, String, Text, Index
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
log.setLevel(SRC_LOG_LEVELS["MODELS"])
|
||||
@@ -31,6 +31,8 @@ class Function(Base):
|
||||
updated_at = Column(BigInteger)
|
||||
created_at = Column(BigInteger)
|
||||
|
||||
__table_args__ = (Index("is_global_idx", "is_global"),)
|
||||
|
||||
|
||||
class FunctionMeta(BaseModel):
|
||||
description: Optional[str] = None
|
||||
@@ -250,9 +252,7 @@ class FunctionsTable:
|
||||
|
||||
return user_settings["functions"]["valves"].get(id, {})
|
||||
except Exception as e:
|
||||
log.exception(
|
||||
f"Error getting user values by id {id} and user id {user_id}: {e}"
|
||||
)
|
||||
log.exception(f"Error getting user values by id {id} and user id {user_id}")
|
||||
return None
|
||||
|
||||
def update_user_valves_by_id_and_user_id(
|
||||
|
||||
@@ -288,13 +288,17 @@ class GroupTable:
|
||||
if not group:
|
||||
return None
|
||||
|
||||
if not group.user_ids:
|
||||
group.user_ids = []
|
||||
group_user_ids = group.user_ids
|
||||
if not group_user_ids or not isinstance(group_user_ids, list):
|
||||
group_user_ids = []
|
||||
|
||||
group_user_ids = list(set(group_user_ids)) # Deduplicate
|
||||
|
||||
for user_id in user_ids:
|
||||
if user_id not in group.user_ids:
|
||||
group.user_ids.append(user_id)
|
||||
if user_id not in group_user_ids:
|
||||
group_user_ids.append(user_id)
|
||||
|
||||
group.user_ids = group_user_ids
|
||||
group.updated_at = int(time.time())
|
||||
db.commit()
|
||||
db.refresh(group)
|
||||
@@ -312,14 +316,20 @@ class GroupTable:
|
||||
if not group:
|
||||
return None
|
||||
|
||||
if not group.user_ids:
|
||||
group_user_ids = group.user_ids
|
||||
|
||||
if not group_user_ids or not isinstance(group_user_ids, list):
|
||||
return GroupModel.model_validate(group)
|
||||
|
||||
for user_id in user_ids:
|
||||
if user_id in group.user_ids:
|
||||
group.user_ids.remove(user_id)
|
||||
group_user_ids = list(set(group_user_ids)) # Deduplicate
|
||||
|
||||
for user_id in user_ids:
|
||||
if user_id in group_user_ids:
|
||||
group_user_ids.remove(user_id)
|
||||
|
||||
group.user_ids = group_user_ids
|
||||
group.updated_at = int(time.time())
|
||||
|
||||
db.commit()
|
||||
db.refresh(group)
|
||||
return GroupModel.model_validate(group)
|
||||
|
||||
@@ -8,7 +8,7 @@ from open_webui.internal.db import Base, get_db
|
||||
|
||||
from open_webui.env import SRC_LOG_LEVELS
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from sqlalchemy import BigInteger, Column, String, JSON, PrimaryKeyConstraint
|
||||
from sqlalchemy import BigInteger, Column, String, JSON, PrimaryKeyConstraint, Index
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
log.setLevel(SRC_LOG_LEVELS["MODELS"])
|
||||
@@ -24,6 +24,11 @@ class Tag(Base):
|
||||
user_id = Column(String)
|
||||
meta = Column(JSON, nullable=True)
|
||||
|
||||
__table_args__ = (
|
||||
PrimaryKeyConstraint("id", "user_id", name="pk_id_user_id"),
|
||||
Index("user_id_idx", "user_id"),
|
||||
)
|
||||
|
||||
# Unique constraint ensuring (id, user_id) is unique, not just the `id` column
|
||||
__table_args__ = (PrimaryKeyConstraint("id", "user_id", name="pk_id_user_id"),)
|
||||
|
||||
|
||||
@@ -175,7 +175,7 @@ class ToolsTable:
|
||||
tool = db.get(Tool, id)
|
||||
return tool.valves if tool.valves else {}
|
||||
except Exception as e:
|
||||
log.exception(f"Error getting tool valves by id {id}: {e}")
|
||||
log.exception(f"Error getting tool valves by id {id}")
|
||||
return None
|
||||
|
||||
def update_tool_valves_by_id(self, id: str, valves: dict) -> Optional[ToolValves]:
|
||||
|
||||
@@ -4,14 +4,17 @@ from typing import Optional
|
||||
from open_webui.internal.db import Base, JSONField, get_db
|
||||
|
||||
|
||||
from open_webui.env import DATABASE_USER_ACTIVE_STATUS_UPDATE_INTERVAL
|
||||
from open_webui.models.chats import Chats
|
||||
from open_webui.models.groups import Groups
|
||||
from open_webui.utils.misc import throttle
|
||||
|
||||
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from sqlalchemy import BigInteger, Column, String, Text
|
||||
from sqlalchemy import BigInteger, Column, String, Text, Date
|
||||
from sqlalchemy import or_
|
||||
|
||||
import datetime
|
||||
|
||||
####################
|
||||
# User DB Schema
|
||||
@@ -23,20 +26,28 @@ class User(Base):
|
||||
|
||||
id = Column(String, primary_key=True)
|
||||
name = Column(String)
|
||||
|
||||
email = Column(String)
|
||||
username = Column(String(50), nullable=True)
|
||||
|
||||
role = Column(String)
|
||||
profile_image_url = Column(Text)
|
||||
|
||||
last_active_at = Column(BigInteger)
|
||||
updated_at = Column(BigInteger)
|
||||
created_at = Column(BigInteger)
|
||||
bio = Column(Text, nullable=True)
|
||||
gender = Column(Text, nullable=True)
|
||||
date_of_birth = Column(Date, nullable=True)
|
||||
|
||||
info = Column(JSONField, nullable=True)
|
||||
settings = Column(JSONField, nullable=True)
|
||||
|
||||
api_key = Column(String, nullable=True, unique=True)
|
||||
settings = Column(JSONField, nullable=True)
|
||||
info = Column(JSONField, nullable=True)
|
||||
|
||||
oauth_sub = Column(Text, unique=True)
|
||||
|
||||
last_active_at = Column(BigInteger)
|
||||
|
||||
updated_at = Column(BigInteger)
|
||||
created_at = Column(BigInteger)
|
||||
|
||||
|
||||
class UserSettings(BaseModel):
|
||||
ui: Optional[dict] = {}
|
||||
@@ -47,20 +58,27 @@ class UserSettings(BaseModel):
|
||||
class UserModel(BaseModel):
|
||||
id: str
|
||||
name: str
|
||||
|
||||
email: str
|
||||
username: Optional[str] = None
|
||||
|
||||
role: str = "pending"
|
||||
profile_image_url: str
|
||||
|
||||
bio: Optional[str] = None
|
||||
gender: Optional[str] = None
|
||||
date_of_birth: Optional[datetime.date] = None
|
||||
|
||||
info: Optional[dict] = None
|
||||
settings: Optional[UserSettings] = None
|
||||
|
||||
api_key: Optional[str] = None
|
||||
oauth_sub: Optional[str] = None
|
||||
|
||||
last_active_at: int # timestamp in epoch
|
||||
updated_at: int # timestamp in epoch
|
||||
created_at: int # timestamp in epoch
|
||||
|
||||
api_key: Optional[str] = None
|
||||
settings: Optional[UserSettings] = None
|
||||
info: Optional[dict] = None
|
||||
|
||||
oauth_sub: Optional[str] = None
|
||||
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
|
||||
@@ -69,6 +87,14 @@ class UserModel(BaseModel):
|
||||
####################
|
||||
|
||||
|
||||
class UpdateProfileForm(BaseModel):
|
||||
profile_image_url: str
|
||||
name: str
|
||||
bio: Optional[str] = None
|
||||
gender: Optional[str] = None
|
||||
date_of_birth: Optional[datetime.date] = None
|
||||
|
||||
|
||||
class UserListResponse(BaseModel):
|
||||
users: list[UserModel]
|
||||
total: int
|
||||
@@ -311,6 +337,7 @@ class UsersTable:
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
@throttle(DATABASE_USER_ACTIVE_STATUS_UPDATE_INTERVAL)
|
||||
def update_user_last_active_by_id(self, id: str) -> Optional[UserModel]:
|
||||
try:
|
||||
with get_db() as db:
|
||||
@@ -346,7 +373,8 @@ class UsersTable:
|
||||
user = db.query(User).filter_by(id=id).first()
|
||||
return UserModel.model_validate(user)
|
||||
# return UserModel(**user.dict())
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
print(e)
|
||||
return None
|
||||
|
||||
def update_user_settings_by_id(self, id: str, updated: dict) -> Optional[UserModel]:
|
||||
|
||||
@@ -64,7 +64,7 @@ class DatalabMarkerLoader:
|
||||
return mime_map.get(ext, "application/octet-stream")
|
||||
|
||||
def check_marker_request_status(self, request_id: str) -> dict:
|
||||
url = f"{self.api_base_url}/marker/{request_id}"
|
||||
url = f"{self.api_base_url}/{request_id}"
|
||||
headers = {"X-Api-Key": self.api_key}
|
||||
try:
|
||||
response = requests.get(url, headers=headers)
|
||||
@@ -111,7 +111,7 @@ class DatalabMarkerLoader:
|
||||
with open(self.file_path, "rb") as f:
|
||||
files = {"file": (filename, f, mime_type)}
|
||||
response = requests.post(
|
||||
f"{self.api_base_url}/marker",
|
||||
f"{self.api_base_url}",
|
||||
data=form_data,
|
||||
files=files,
|
||||
headers=headers,
|
||||
|
||||
@@ -4,6 +4,7 @@ import ftfy
|
||||
import sys
|
||||
import json
|
||||
|
||||
from azure.identity import DefaultAzureCredential
|
||||
from langchain_community.document_loaders import (
|
||||
AzureAIDocumentIntelligenceLoader,
|
||||
BSHTMLLoader,
|
||||
@@ -283,7 +284,7 @@ class Loader:
|
||||
):
|
||||
api_base_url = self.kwargs.get("DATALAB_MARKER_API_BASE_URL", "")
|
||||
if not api_base_url or api_base_url.strip() == "":
|
||||
api_base_url = "https://www.datalab.to/api/v1"
|
||||
api_base_url = "https://www.datalab.to/api/v1/marker" # https://github.com/open-webui/open-webui/pull/16867#issuecomment-3218424349
|
||||
|
||||
loader = DatalabMarkerLoader(
|
||||
file_path=file_path,
|
||||
@@ -327,7 +328,6 @@ class Loader:
|
||||
elif (
|
||||
self.engine == "document_intelligence"
|
||||
and self.kwargs.get("DOCUMENT_INTELLIGENCE_ENDPOINT") != ""
|
||||
and self.kwargs.get("DOCUMENT_INTELLIGENCE_KEY") != ""
|
||||
and (
|
||||
file_ext in ["pdf", "xls", "xlsx", "docx", "ppt", "pptx"]
|
||||
or file_content_type
|
||||
@@ -340,11 +340,18 @@ class Loader:
|
||||
]
|
||||
)
|
||||
):
|
||||
loader = AzureAIDocumentIntelligenceLoader(
|
||||
file_path=file_path,
|
||||
api_endpoint=self.kwargs.get("DOCUMENT_INTELLIGENCE_ENDPOINT"),
|
||||
api_key=self.kwargs.get("DOCUMENT_INTELLIGENCE_KEY"),
|
||||
)
|
||||
if self.kwargs.get("DOCUMENT_INTELLIGENCE_KEY") != "":
|
||||
loader = AzureAIDocumentIntelligenceLoader(
|
||||
file_path=file_path,
|
||||
api_endpoint=self.kwargs.get("DOCUMENT_INTELLIGENCE_ENDPOINT"),
|
||||
api_key=self.kwargs.get("DOCUMENT_INTELLIGENCE_KEY"),
|
||||
)
|
||||
else:
|
||||
loader = AzureAIDocumentIntelligenceLoader(
|
||||
file_path=file_path,
|
||||
api_endpoint=self.kwargs.get("DOCUMENT_INTELLIGENCE_ENDPOINT"),
|
||||
azure_credential=DefaultAzureCredential(),
|
||||
)
|
||||
elif (
|
||||
self.engine == "mistral_ocr"
|
||||
and self.kwargs.get("MISTRAL_OCR_API_KEY") != ""
|
||||
|
||||
@@ -124,12 +124,18 @@ def query_doc_with_hybrid_search(
|
||||
hybrid_bm25_weight: float,
|
||||
) -> dict:
|
||||
try:
|
||||
log.debug(f"query_doc_with_hybrid_search:doc {collection_name}")
|
||||
bm25_retriever = BM25Retriever.from_texts(
|
||||
texts=collection_result.documents[0],
|
||||
metadatas=collection_result.metadatas[0],
|
||||
)
|
||||
bm25_retriever.k = k
|
||||
if not collection_result.documents[0]:
|
||||
log.warning(f"query_doc_with_hybrid_search:no_docs {collection_name}")
|
||||
return {"documents": [], "metadatas": [], "distances": []}
|
||||
|
||||
# BM_25 required only if weight is greater than 0
|
||||
if hybrid_bm25_weight > 0:
|
||||
log.debug(f"query_doc_with_hybrid_search:doc {collection_name}")
|
||||
bm25_retriever = BM25Retriever.from_texts(
|
||||
texts=collection_result.documents[0],
|
||||
metadatas=collection_result.metadatas[0],
|
||||
)
|
||||
bm25_retriever.k = k
|
||||
|
||||
vector_search_retriever = VectorSearchRetriever(
|
||||
collection_name=collection_name,
|
||||
@@ -337,18 +343,22 @@ def query_collection_with_hybrid_search(
|
||||
# Fetch collection data once per collection sequentially
|
||||
# Avoid fetching the same data multiple times later
|
||||
collection_results = {}
|
||||
for collection_name in collection_names:
|
||||
try:
|
||||
log.debug(
|
||||
f"query_collection_with_hybrid_search:VECTOR_DB_CLIENT.get:collection {collection_name}"
|
||||
)
|
||||
collection_results[collection_name] = VECTOR_DB_CLIENT.get(
|
||||
collection_name=collection_name
|
||||
)
|
||||
except Exception as e:
|
||||
log.exception(f"Failed to fetch collection {collection_name}: {e}")
|
||||
collection_results[collection_name] = None
|
||||
|
||||
# Only retrieve entire collection if bm_25 calculation is required
|
||||
if hybrid_bm25_weight > 0:
|
||||
for collection_name in collection_names:
|
||||
try:
|
||||
log.debug(
|
||||
f"query_collection_with_hybrid_search:VECTOR_DB_CLIENT.get:collection {collection_name}"
|
||||
)
|
||||
collection_results[collection_name] = VECTOR_DB_CLIENT.get(
|
||||
collection_name=collection_name
|
||||
)
|
||||
except Exception as e:
|
||||
log.exception(f"Failed to fetch collection {collection_name}: {e}")
|
||||
collection_results[collection_name] = None
|
||||
else:
|
||||
for collection_name in collection_names:
|
||||
collection_results[collection_name] = []
|
||||
log.info(
|
||||
f"Starting hybrid search for {len(queries)} queries in {len(collection_names)} collections..."
|
||||
)
|
||||
@@ -946,6 +956,7 @@ class RerankCompressor(BaseDocumentCompressor):
|
||||
) -> Sequence[Document]:
|
||||
reranking = self.reranking_function is not None
|
||||
|
||||
scores = None
|
||||
if reranking:
|
||||
scores = self.reranking_function(
|
||||
[(query, doc.page_content) for doc in documents]
|
||||
@@ -959,22 +970,31 @@ class RerankCompressor(BaseDocumentCompressor):
|
||||
)
|
||||
scores = util.cos_sim(query_embedding, document_embedding)[0]
|
||||
|
||||
docs_with_scores = list(
|
||||
zip(documents, scores.tolist() if not isinstance(scores, list) else scores)
|
||||
)
|
||||
if self.r_score:
|
||||
docs_with_scores = [
|
||||
(d, s) for d, s in docs_with_scores if s >= self.r_score
|
||||
]
|
||||
|
||||
result = sorted(docs_with_scores, key=operator.itemgetter(1), reverse=True)
|
||||
final_results = []
|
||||
for doc, doc_score in result[: self.top_n]:
|
||||
metadata = doc.metadata
|
||||
metadata["score"] = doc_score
|
||||
doc = Document(
|
||||
page_content=doc.page_content,
|
||||
metadata=metadata,
|
||||
if scores is not None:
|
||||
docs_with_scores = list(
|
||||
zip(
|
||||
documents,
|
||||
scores.tolist() if not isinstance(scores, list) else scores,
|
||||
)
|
||||
)
|
||||
final_results.append(doc)
|
||||
return final_results
|
||||
if self.r_score:
|
||||
docs_with_scores = [
|
||||
(d, s) for d, s in docs_with_scores if s >= self.r_score
|
||||
]
|
||||
|
||||
result = sorted(docs_with_scores, key=operator.itemgetter(1), reverse=True)
|
||||
final_results = []
|
||||
for doc, doc_score in result[: self.top_n]:
|
||||
metadata = doc.metadata
|
||||
metadata["score"] = doc_score
|
||||
doc = Document(
|
||||
page_content=doc.page_content,
|
||||
metadata=metadata,
|
||||
)
|
||||
final_results.append(doc)
|
||||
return final_results
|
||||
else:
|
||||
log.warning(
|
||||
"No valid scores found, check your reranking function. Returning original documents."
|
||||
)
|
||||
return documents
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
from pymilvus import MilvusClient as Client
|
||||
from pymilvus import FieldSchema, DataType
|
||||
from pymilvus import connections, Collection
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Optional
|
||||
@@ -188,6 +190,8 @@ class MilvusClient(VectorDBBase):
|
||||
return self._result_to_search_result(result)
|
||||
|
||||
def query(self, collection_name: str, filter: dict, limit: Optional[int] = None):
|
||||
connections.connect(uri=MILVUS_URI, token=MILVUS_TOKEN, db_name=MILVUS_DB)
|
||||
|
||||
# Construct the filter string for querying
|
||||
collection_name = collection_name.replace("-", "_")
|
||||
if not self.has_collection(collection_name):
|
||||
@@ -201,72 +205,36 @@ class MilvusClient(VectorDBBase):
|
||||
for key, value in filter.items()
|
||||
]
|
||||
)
|
||||
max_limit = 16383 # The maximum number of records per request
|
||||
all_results = []
|
||||
if limit is None:
|
||||
# Milvus default limit for query if not specified is 16384, but docs mention iteration.
|
||||
# Let's set a practical high number if "all" is intended, or handle true pagination.
|
||||
# For now, if limit is None, we'll fetch in batches up to a very large number.
|
||||
# This part could be refined based on expected use cases for "get all".
|
||||
# For this function signature, None implies "as many as possible" up to Milvus limits.
|
||||
limit = (
|
||||
16384 * 10
|
||||
) # A large number to signify fetching many, will be capped by actual data or max_limit per call.
|
||||
log.info(
|
||||
f"Limit not specified for query, fetching up to {limit} results in batches."
|
||||
)
|
||||
|
||||
# Initialize offset and remaining to handle pagination
|
||||
offset = 0
|
||||
remaining = limit
|
||||
collection = Collection(f"{self.collection_prefix}_{collection_name}")
|
||||
collection.load()
|
||||
all_results = []
|
||||
|
||||
try:
|
||||
log.info(
|
||||
f"Querying collection {self.collection_prefix}_{collection_name} with filter: '{filter_string}', limit: {limit}"
|
||||
)
|
||||
# Loop until there are no more items to fetch or the desired limit is reached
|
||||
while remaining > 0:
|
||||
current_fetch = min(
|
||||
max_limit, remaining if isinstance(remaining, int) else max_limit
|
||||
)
|
||||
log.debug(
|
||||
f"Querying with offset: {offset}, current_fetch: {current_fetch}"
|
||||
)
|
||||
|
||||
results = self.client.query(
|
||||
collection_name=f"{self.collection_prefix}_{collection_name}",
|
||||
filter=filter_string,
|
||||
output_fields=[
|
||||
"id",
|
||||
"data",
|
||||
"metadata",
|
||||
], # Explicitly list needed fields. Vector not usually needed in query.
|
||||
limit=current_fetch,
|
||||
offset=offset,
|
||||
)
|
||||
iterator = collection.query_iterator(
|
||||
filter=filter_string,
|
||||
output_fields=[
|
||||
"id",
|
||||
"data",
|
||||
"metadata",
|
||||
],
|
||||
limit=limit, # Pass the limit directly; None means no limit.
|
||||
)
|
||||
|
||||
if not results:
|
||||
log.debug("No more results from query.")
|
||||
break
|
||||
|
||||
all_results.extend(results)
|
||||
results_count = len(results)
|
||||
log.debug(f"Fetched {results_count} results in this batch.")
|
||||
|
||||
if isinstance(remaining, int):
|
||||
remaining -= results_count
|
||||
|
||||
offset += results_count
|
||||
|
||||
# Break the loop if the results returned are less than the requested fetch count (means end of data)
|
||||
if results_count < current_fetch:
|
||||
log.debug(
|
||||
"Fetched less than requested, assuming end of results for this query."
|
||||
)
|
||||
while True:
|
||||
result = iterator.next()
|
||||
if not result:
|
||||
iterator.close()
|
||||
break
|
||||
all_results += result
|
||||
|
||||
log.info(f"Total results from query: {len(all_results)}")
|
||||
return self._result_to_get_result([all_results])
|
||||
|
||||
except Exception as e:
|
||||
log.exception(
|
||||
f"Error querying collection {self.collection_prefix}_{collection_name} with filter '{filter_string}' and limit {limit}: {e}"
|
||||
|
||||
@@ -111,11 +111,35 @@ class PgvectorClient(VectorDBBase):
|
||||
|
||||
try:
|
||||
# Ensure the pgvector extension is available
|
||||
self.session.execute(text("CREATE EXTENSION IF NOT EXISTS vector;"))
|
||||
# Use a conditional check to avoid permission issues on Azure PostgreSQL
|
||||
self.session.execute(
|
||||
text(
|
||||
"""
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'vector') THEN
|
||||
CREATE EXTENSION IF NOT EXISTS vector;
|
||||
END IF;
|
||||
END $$;
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
if PGVECTOR_PGCRYPTO:
|
||||
# Ensure the pgcrypto extension is available for encryption
|
||||
self.session.execute(text("CREATE EXTENSION IF NOT EXISTS pgcrypto;"))
|
||||
# Use a conditional check to avoid permission issues on Azure PostgreSQL
|
||||
self.session.execute(
|
||||
text(
|
||||
"""
|
||||
DO $$
|
||||
BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_extension WHERE extname = 'pgcrypto') THEN
|
||||
CREATE EXTENSION IF NOT EXISTS pgcrypto;
|
||||
END IF;
|
||||
END $$;
|
||||
"""
|
||||
)
|
||||
)
|
||||
|
||||
if not PGVECTOR_PGCRYPTO_KEY:
|
||||
raise ValueError(
|
||||
|
||||
@@ -32,6 +32,8 @@ from open_webui.config import (
|
||||
PINECONE_CLOUD,
|
||||
)
|
||||
from open_webui.env import SRC_LOG_LEVELS
|
||||
from open_webui.retrieval.vector.utils import stringify_metadata
|
||||
|
||||
|
||||
NO_LIMIT = 10000 # Reasonable limit to avoid overwhelming the system
|
||||
BATCH_SIZE = 100 # Recommended batch size for Pinecone operations
|
||||
@@ -183,7 +185,7 @@ class PineconeClient(VectorDBBase):
|
||||
point = {
|
||||
"id": item["id"],
|
||||
"values": item["vector"],
|
||||
"metadata": metadata,
|
||||
"metadata": stringify_metadata(metadata),
|
||||
}
|
||||
points.append(point)
|
||||
return points
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
from backend.open_webui.retrieval.vector.utils import stringify_metadata
|
||||
from open_webui.retrieval.vector.utils import stringify_metadata
|
||||
from open_webui.retrieval.vector.main import (
|
||||
VectorDBBase,
|
||||
VectorItem,
|
||||
@@ -197,13 +197,23 @@ class S3VectorClient(VectorDBBase):
|
||||
"metadata": metadata,
|
||||
}
|
||||
)
|
||||
# Insert vectors
|
||||
self.client.put_vectors(
|
||||
vectorBucketName=self.bucket_name,
|
||||
indexName=collection_name,
|
||||
vectors=vectors,
|
||||
|
||||
# Insert vectors in batches of 500 (S3 Vector API limit)
|
||||
batch_size = 500
|
||||
for i in range(0, len(vectors), batch_size):
|
||||
batch = vectors[i : i + batch_size]
|
||||
self.client.put_vectors(
|
||||
vectorBucketName=self.bucket_name,
|
||||
indexName=collection_name,
|
||||
vectors=batch,
|
||||
)
|
||||
log.info(
|
||||
f"Inserted batch {i//batch_size + 1}: {len(batch)} vectors into index '{collection_name}'."
|
||||
)
|
||||
|
||||
log.info(
|
||||
f"Completed insertion of {len(vectors)} vectors into index '{collection_name}'."
|
||||
)
|
||||
log.info(f"Inserted {len(vectors)} vectors into index '{collection_name}'.")
|
||||
except Exception as e:
|
||||
log.error(f"Error inserting vectors: {e}")
|
||||
raise
|
||||
@@ -258,16 +268,29 @@ class S3VectorClient(VectorDBBase):
|
||||
"metadata": metadata,
|
||||
}
|
||||
)
|
||||
# Upsert vectors (using put_vectors for upsert semantics)
|
||||
|
||||
# Upsert vectors in batches of 500 (S3 Vector API limit)
|
||||
batch_size = 500
|
||||
for i in range(0, len(vectors), batch_size):
|
||||
batch = vectors[i : i + batch_size]
|
||||
if i == 0: # Log sample info for first batch only
|
||||
log.info(
|
||||
f"Upserting batch 1: {len(batch)} vectors. First vector sample: key={batch[0]['key']}, data_type={type(batch[0]['data']['float32'])}, data_len={len(batch[0]['data']['float32'])}"
|
||||
)
|
||||
else:
|
||||
log.info(
|
||||
f"Upserting batch {i//batch_size + 1}: {len(batch)} vectors."
|
||||
)
|
||||
|
||||
self.client.put_vectors(
|
||||
vectorBucketName=self.bucket_name,
|
||||
indexName=collection_name,
|
||||
vectors=batch,
|
||||
)
|
||||
|
||||
log.info(
|
||||
f"Upserting {len(vectors)} vectors. First vector sample: key={vectors[0]['key']}, data_type={type(vectors[0]['data']['float32'])}, data_len={len(vectors[0]['data']['float32'])}"
|
||||
f"Completed upsert of {len(vectors)} vectors into index '{collection_name}'."
|
||||
)
|
||||
self.client.put_vectors(
|
||||
vectorBucketName=self.bucket_name,
|
||||
indexName=collection_name,
|
||||
vectors=vectors,
|
||||
)
|
||||
log.info(f"Upserted {len(vectors)} vectors into index '{collection_name}'.")
|
||||
except Exception as e:
|
||||
log.error(f"Error upserting vectors: {e}")
|
||||
raise
|
||||
|
||||
@@ -11,7 +11,10 @@ log.setLevel(SRC_LOG_LEVELS["RAG"])
|
||||
|
||||
|
||||
def search_duckduckgo(
|
||||
query: str, count: int, filter_list: Optional[list[str]] = None
|
||||
query: str,
|
||||
count: int,
|
||||
filter_list: Optional[list[str]] = None,
|
||||
concurrent_requests: Optional[int] = None,
|
||||
) -> list[SearchResult]:
|
||||
"""
|
||||
Search using DuckDuckGo's Search API and return the results as a list of SearchResult objects.
|
||||
@@ -25,6 +28,9 @@ def search_duckduckgo(
|
||||
# Use the DDGS context manager to create a DDGS object
|
||||
search_results = []
|
||||
with DDGS() as ddgs:
|
||||
if concurrent_requests:
|
||||
ddgs.threads = concurrent_requests
|
||||
|
||||
# Use the ddgs.text() method to perform the search
|
||||
try:
|
||||
search_results = ddgs.text(
|
||||
|
||||
@@ -11,7 +11,7 @@ def get_filtered_results(results, filter_list):
|
||||
return results
|
||||
filtered_results = []
|
||||
for result in results:
|
||||
url = result.get("url") or result.get("link", "")
|
||||
url = result.get("url") or result.get("link", "") or result.get("href", "")
|
||||
if not validators.url(url):
|
||||
continue
|
||||
domain = urlparse(url).netloc
|
||||
|
||||
@@ -614,7 +614,7 @@ def get_web_loader(
|
||||
WebLoaderClass = SafeWebBaseLoader
|
||||
if WEB_LOADER_ENGINE.value == "playwright":
|
||||
WebLoaderClass = SafePlaywrightURLLoader
|
||||
web_loader_args["playwright_timeout"] = PLAYWRIGHT_TIMEOUT.value * 1000
|
||||
web_loader_args["playwright_timeout"] = PLAYWRIGHT_TIMEOUT.value
|
||||
if PLAYWRIGHT_WS_URL.value:
|
||||
web_loader_args["playwright_ws_url"] = PLAYWRIGHT_WS_URL.value
|
||||
|
||||
|
||||
@@ -550,6 +550,11 @@ def transcription_handler(request, file_path, metadata):
|
||||
|
||||
metadata = metadata or {}
|
||||
|
||||
languages = [
|
||||
metadata.get("language", None) if WHISPER_LANGUAGE == "" else WHISPER_LANGUAGE,
|
||||
None, # Always fallback to None in case transcription fails
|
||||
]
|
||||
|
||||
if request.app.state.config.STT_ENGINE == "":
|
||||
if request.app.state.faster_whisper_model is None:
|
||||
request.app.state.faster_whisper_model = set_faster_whisper_model(
|
||||
@@ -561,11 +566,7 @@ def transcription_handler(request, file_path, metadata):
|
||||
file_path,
|
||||
beam_size=5,
|
||||
vad_filter=request.app.state.config.WHISPER_VAD_FILTER,
|
||||
language=(
|
||||
metadata.get("language", None)
|
||||
if WHISPER_LANGUAGE == ""
|
||||
else WHISPER_LANGUAGE
|
||||
),
|
||||
language=languages[0],
|
||||
)
|
||||
log.info(
|
||||
"Detected language '%s' with probability %f"
|
||||
@@ -585,21 +586,26 @@ def transcription_handler(request, file_path, metadata):
|
||||
elif request.app.state.config.STT_ENGINE == "openai":
|
||||
r = None
|
||||
try:
|
||||
r = requests.post(
|
||||
url=f"{request.app.state.config.STT_OPENAI_API_BASE_URL}/audio/transcriptions",
|
||||
headers={
|
||||
"Authorization": f"Bearer {request.app.state.config.STT_OPENAI_API_KEY}"
|
||||
},
|
||||
files={"file": (filename, open(file_path, "rb"))},
|
||||
data={
|
||||
for language in languages:
|
||||
payload = {
|
||||
"model": request.app.state.config.STT_MODEL,
|
||||
**(
|
||||
{"language": metadata.get("language")}
|
||||
if metadata.get("language")
|
||||
else {}
|
||||
),
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
if language:
|
||||
payload["language"] = language
|
||||
|
||||
r = requests.post(
|
||||
url=f"{request.app.state.config.STT_OPENAI_API_BASE_URL}/audio/transcriptions",
|
||||
headers={
|
||||
"Authorization": f"Bearer {request.app.state.config.STT_OPENAI_API_KEY}"
|
||||
},
|
||||
files={"file": (filename, open(file_path, "rb"))},
|
||||
data=payload,
|
||||
)
|
||||
|
||||
if r.status_code == 200:
|
||||
# Successful transcription
|
||||
break
|
||||
|
||||
r.raise_for_status()
|
||||
data = r.json()
|
||||
@@ -641,18 +647,26 @@ def transcription_handler(request, file_path, metadata):
|
||||
"Content-Type": mime,
|
||||
}
|
||||
|
||||
# Add model if specified
|
||||
params = {}
|
||||
if request.app.state.config.STT_MODEL:
|
||||
params["model"] = request.app.state.config.STT_MODEL
|
||||
for language in languages:
|
||||
params = {}
|
||||
if request.app.state.config.STT_MODEL:
|
||||
params["model"] = request.app.state.config.STT_MODEL
|
||||
|
||||
if language:
|
||||
params["language"] = language
|
||||
|
||||
# Make request to Deepgram API
|
||||
r = requests.post(
|
||||
"https://api.deepgram.com/v1/listen?smart_format=true",
|
||||
headers=headers,
|
||||
params=params,
|
||||
data=file_data,
|
||||
)
|
||||
|
||||
if r.status_code == 200:
|
||||
# Successful transcription
|
||||
break
|
||||
|
||||
# Make request to Deepgram API
|
||||
r = requests.post(
|
||||
"https://api.deepgram.com/v1/listen?smart_format=true",
|
||||
headers=headers,
|
||||
params=params,
|
||||
data=file_data,
|
||||
)
|
||||
r.raise_for_status()
|
||||
response_data = r.json()
|
||||
|
||||
|
||||
@@ -15,10 +15,9 @@ from open_webui.models.auths import (
|
||||
SigninResponse,
|
||||
SignupForm,
|
||||
UpdatePasswordForm,
|
||||
UpdateProfileForm,
|
||||
UserResponse,
|
||||
)
|
||||
from open_webui.models.users import Users
|
||||
from open_webui.models.users import Users, UpdateProfileForm
|
||||
from open_webui.models.groups import Groups
|
||||
|
||||
from open_webui.constants import ERROR_MESSAGES, WEBHOOK_MESSAGES
|
||||
@@ -30,6 +29,7 @@ from open_webui.env import (
|
||||
WEBUI_AUTH_COOKIE_SAME_SITE,
|
||||
WEBUI_AUTH_COOKIE_SECURE,
|
||||
WEBUI_AUTH_SIGNOUT_REDIRECT_URL,
|
||||
ENABLE_INITIAL_ADMIN_SIGNUP,
|
||||
SRC_LOG_LEVELS,
|
||||
)
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, status
|
||||
@@ -73,7 +73,13 @@ class SessionUserResponse(Token, UserResponse):
|
||||
permissions: Optional[dict] = None
|
||||
|
||||
|
||||
@router.get("/", response_model=SessionUserResponse)
|
||||
class SessionUserInfoResponse(SessionUserResponse):
|
||||
bio: Optional[str] = None
|
||||
gender: Optional[str] = None
|
||||
date_of_birth: Optional[datetime.date] = None
|
||||
|
||||
|
||||
@router.get("/", response_model=SessionUserInfoResponse)
|
||||
async def get_session_user(
|
||||
request: Request, response: Response, user=Depends(get_current_user)
|
||||
):
|
||||
@@ -121,6 +127,9 @@ async def get_session_user(
|
||||
"name": user.name,
|
||||
"role": user.role,
|
||||
"profile_image_url": user.profile_image_url,
|
||||
"bio": user.bio,
|
||||
"gender": user.gender,
|
||||
"date_of_birth": user.date_of_birth,
|
||||
"permissions": user_permissions,
|
||||
}
|
||||
|
||||
@@ -137,7 +146,7 @@ async def update_profile(
|
||||
if session_user:
|
||||
user = Users.update_user_by_id(
|
||||
session_user.id,
|
||||
{"profile_image_url": form_data.profile_image_url, "name": form_data.name},
|
||||
form_data.model_dump(),
|
||||
)
|
||||
if user:
|
||||
return user
|
||||
@@ -561,9 +570,10 @@ async def signup(request: Request, response: Response, form_data: SignupForm):
|
||||
not request.app.state.config.ENABLE_SIGNUP
|
||||
or not request.app.state.config.ENABLE_LOGIN_FORM
|
||||
):
|
||||
raise HTTPException(
|
||||
status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
|
||||
)
|
||||
if has_users or not ENABLE_INITIAL_ADMIN_SIGNUP:
|
||||
raise HTTPException(
|
||||
status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
|
||||
)
|
||||
else:
|
||||
if has_users:
|
||||
raise HTTPException(
|
||||
@@ -625,7 +635,7 @@ async def signup(request: Request, response: Response, form_data: SignupForm):
|
||||
)
|
||||
|
||||
if request.app.state.config.WEBHOOK_URL:
|
||||
post_webhook(
|
||||
await post_webhook(
|
||||
request.app.state.WEBUI_NAME,
|
||||
request.app.state.config.WEBHOOK_URL,
|
||||
WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
|
||||
|
||||
@@ -209,7 +209,7 @@ async def send_notification(name, webui_url, channel, message, active_user_ids):
|
||||
)
|
||||
|
||||
if webhook_url:
|
||||
post_webhook(
|
||||
await post_webhook(
|
||||
name,
|
||||
webhook_url,
|
||||
f"#{channel.name} - {webui_url}/channels/{channel.id}\n\n{message.content}",
|
||||
|
||||
@@ -36,7 +36,7 @@ router = APIRouter()
|
||||
|
||||
@router.get("/", response_model=list[ChatTitleIdResponse])
|
||||
@router.get("/list", response_model=list[ChatTitleIdResponse])
|
||||
async def get_session_user_chat_list(
|
||||
def get_session_user_chat_list(
|
||||
user=Depends(get_verified_user), page: Optional[int] = None
|
||||
):
|
||||
try:
|
||||
|
||||
@@ -9,8 +9,8 @@ from open_webui.config import BannerModel
|
||||
|
||||
from open_webui.utils.tools import (
|
||||
get_tool_server_data,
|
||||
get_tool_servers_data,
|
||||
get_tool_server_url,
|
||||
set_tool_servers,
|
||||
)
|
||||
|
||||
|
||||
@@ -114,10 +114,7 @@ async def set_tool_servers_config(
|
||||
request.app.state.config.TOOL_SERVER_CONNECTIONS = [
|
||||
connection.model_dump() for connection in form_data.TOOL_SERVER_CONNECTIONS
|
||||
]
|
||||
|
||||
request.app.state.TOOL_SERVERS = await get_tool_servers_data(
|
||||
request.app.state.config.TOOL_SERVER_CONNECTIONS
|
||||
)
|
||||
await set_tool_servers(request)
|
||||
|
||||
return {
|
||||
"TOOL_SERVER_CONNECTIONS": request.app.state.config.TOOL_SERVER_CONNECTIONS,
|
||||
|
||||
@@ -6,8 +6,10 @@ from fnmatch import fnmatch
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
from urllib.parse import quote
|
||||
import asyncio
|
||||
|
||||
from fastapi import (
|
||||
BackgroundTasks,
|
||||
APIRouter,
|
||||
Depends,
|
||||
File,
|
||||
@@ -18,6 +20,7 @@ from fastapi import (
|
||||
status,
|
||||
Query,
|
||||
)
|
||||
|
||||
from fastapi.responses import FileResponse, StreamingResponse
|
||||
from open_webui.constants import ERROR_MESSAGES
|
||||
from open_webui.env import SRC_LOG_LEVELS
|
||||
@@ -42,7 +45,6 @@ from pydantic import BaseModel
|
||||
log = logging.getLogger(__name__)
|
||||
log.setLevel(SRC_LOG_LEVELS["MODELS"])
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@@ -83,14 +85,86 @@ def has_access_to_file(
|
||||
############################
|
||||
|
||||
|
||||
def process_uploaded_file(request, file, file_path, file_item, file_metadata, user):
|
||||
try:
|
||||
if file.content_type:
|
||||
stt_supported_content_types = getattr(
|
||||
request.app.state.config, "STT_SUPPORTED_CONTENT_TYPES", []
|
||||
)
|
||||
|
||||
if any(
|
||||
fnmatch(file.content_type, content_type)
|
||||
for content_type in (
|
||||
stt_supported_content_types
|
||||
if stt_supported_content_types
|
||||
and any(t.strip() for t in stt_supported_content_types)
|
||||
else ["audio/*", "video/webm"]
|
||||
)
|
||||
):
|
||||
file_path = Storage.get_file(file_path)
|
||||
result = transcribe(request, file_path, file_metadata)
|
||||
|
||||
process_file(
|
||||
request,
|
||||
ProcessFileForm(
|
||||
file_id=file_item.id, content=result.get("text", "")
|
||||
),
|
||||
user=user,
|
||||
)
|
||||
elif (not file.content_type.startswith(("image/", "video/"))) or (
|
||||
request.app.state.config.CONTENT_EXTRACTION_ENGINE == "external"
|
||||
):
|
||||
process_file(request, ProcessFileForm(file_id=file_item.id), user=user)
|
||||
else:
|
||||
log.info(
|
||||
f"File type {file.content_type} is not provided, but trying to process anyway"
|
||||
)
|
||||
process_file(request, ProcessFileForm(file_id=file_item.id), user=user)
|
||||
|
||||
Files.update_file_data_by_id(
|
||||
file_item.id,
|
||||
{"status": "completed"},
|
||||
)
|
||||
except Exception as e:
|
||||
log.error(f"Error processing file: {file_item.id}")
|
||||
Files.update_file_data_by_id(
|
||||
file_item.id,
|
||||
{
|
||||
"status": "failed",
|
||||
"error": str(e.detail) if hasattr(e, "detail") else str(e),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/", response_model=FileModelResponse)
|
||||
def upload_file(
|
||||
request: Request,
|
||||
background_tasks: BackgroundTasks,
|
||||
file: UploadFile = File(...),
|
||||
metadata: Optional[dict | str] = Form(None),
|
||||
process: bool = Query(True),
|
||||
process_in_background: bool = Query(True),
|
||||
user=Depends(get_verified_user),
|
||||
):
|
||||
return upload_file_handler(
|
||||
request,
|
||||
file=file,
|
||||
metadata=metadata,
|
||||
process=process,
|
||||
process_in_background=process_in_background,
|
||||
user=user,
|
||||
background_tasks=background_tasks,
|
||||
)
|
||||
|
||||
|
||||
def upload_file_handler(
|
||||
request: Request,
|
||||
file: UploadFile = File(...),
|
||||
metadata: Optional[dict | str] = Form(None),
|
||||
process: bool = Query(True),
|
||||
internal: bool = False,
|
||||
process_in_background: bool = Query(True),
|
||||
user=Depends(get_verified_user),
|
||||
background_tasks: Optional[BackgroundTasks] = None,
|
||||
):
|
||||
log.info(f"file.content_type: {file.content_type}")
|
||||
|
||||
@@ -112,7 +186,7 @@ def upload_file(
|
||||
# Remove the leading dot from the file extension
|
||||
file_extension = file_extension[1:] if file_extension else ""
|
||||
|
||||
if (not internal) and request.app.state.config.ALLOWED_FILE_EXTENSIONS:
|
||||
if process and request.app.state.config.ALLOWED_FILE_EXTENSIONS:
|
||||
request.app.state.config.ALLOWED_FILE_EXTENSIONS = [
|
||||
ext for ext in request.app.state.config.ALLOWED_FILE_EXTENSIONS if ext
|
||||
]
|
||||
@@ -129,13 +203,16 @@ def upload_file(
|
||||
id = str(uuid.uuid4())
|
||||
name = filename
|
||||
filename = f"{id}_{filename}"
|
||||
tags = {
|
||||
"OpenWebUI-User-Email": user.email,
|
||||
"OpenWebUI-User-Id": user.id,
|
||||
"OpenWebUI-User-Name": user.name,
|
||||
"OpenWebUI-File-Id": id,
|
||||
}
|
||||
contents, file_path = Storage.upload_file(file.file, filename, tags)
|
||||
contents, file_path = Storage.upload_file(
|
||||
file.file,
|
||||
filename,
|
||||
{
|
||||
"OpenWebUI-User-Email": user.email,
|
||||
"OpenWebUI-User-Id": user.id,
|
||||
"OpenWebUI-User-Name": user.name,
|
||||
"OpenWebUI-File-Id": id,
|
||||
},
|
||||
)
|
||||
|
||||
file_item = Files.insert_new_file(
|
||||
user.id,
|
||||
@@ -144,6 +221,9 @@ def upload_file(
|
||||
"id": id,
|
||||
"filename": name,
|
||||
"path": file_path,
|
||||
"data": {
|
||||
**({"status": "pending"} if process else {}),
|
||||
},
|
||||
"meta": {
|
||||
"name": name,
|
||||
"content_type": file.content_type,
|
||||
@@ -153,58 +233,37 @@ def upload_file(
|
||||
}
|
||||
),
|
||||
)
|
||||
|
||||
if process:
|
||||
try:
|
||||
if file.content_type:
|
||||
stt_supported_content_types = getattr(
|
||||
request.app.state.config, "STT_SUPPORTED_CONTENT_TYPES", []
|
||||
)
|
||||
|
||||
if any(
|
||||
fnmatch(file.content_type, content_type)
|
||||
for content_type in (
|
||||
stt_supported_content_types
|
||||
if stt_supported_content_types
|
||||
and any(t.strip() for t in stt_supported_content_types)
|
||||
else ["audio/*", "video/webm"]
|
||||
)
|
||||
):
|
||||
file_path = Storage.get_file(file_path)
|
||||
result = transcribe(request, file_path, file_metadata)
|
||||
|
||||
process_file(
|
||||
request,
|
||||
ProcessFileForm(file_id=id, content=result.get("text", "")),
|
||||
user=user,
|
||||
)
|
||||
elif (not file.content_type.startswith(("image/", "video/"))) or (
|
||||
request.app.state.config.CONTENT_EXTRACTION_ENGINE == "external"
|
||||
):
|
||||
process_file(request, ProcessFileForm(file_id=id), user=user)
|
||||
else:
|
||||
log.info(
|
||||
f"File type {file.content_type} is not provided, but trying to process anyway"
|
||||
)
|
||||
process_file(request, ProcessFileForm(file_id=id), user=user)
|
||||
|
||||
file_item = Files.get_file_by_id(id=id)
|
||||
except Exception as e:
|
||||
log.exception(e)
|
||||
log.error(f"Error processing file: {file_item.id}")
|
||||
file_item = FileModelResponse(
|
||||
**{
|
||||
**file_item.model_dump(),
|
||||
"error": str(e.detail) if hasattr(e, "detail") else str(e),
|
||||
}
|
||||
if background_tasks and process_in_background:
|
||||
background_tasks.add_task(
|
||||
process_uploaded_file,
|
||||
request,
|
||||
file,
|
||||
file_path,
|
||||
file_item,
|
||||
file_metadata,
|
||||
user,
|
||||
)
|
||||
|
||||
if file_item:
|
||||
return file_item
|
||||
return {"status": True, **file_item.model_dump()}
|
||||
else:
|
||||
process_uploaded_file(
|
||||
request,
|
||||
file,
|
||||
file_path,
|
||||
file_item,
|
||||
file_metadata,
|
||||
user,
|
||||
)
|
||||
return {"status": True, **file_item.model_dump()}
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=ERROR_MESSAGES.DEFAULT("Error uploading file"),
|
||||
)
|
||||
if file_item:
|
||||
return file_item
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=ERROR_MESSAGES.DEFAULT("Error uploading file"),
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
log.exception(e)
|
||||
@@ -331,6 +390,60 @@ async def get_file_by_id(id: str, user=Depends(get_verified_user)):
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{id}/process/status")
|
||||
async def get_file_process_status(
|
||||
id: str, stream: bool = Query(False), user=Depends(get_verified_user)
|
||||
):
|
||||
file = Files.get_file_by_id(id)
|
||||
|
||||
if not file:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=ERROR_MESSAGES.NOT_FOUND,
|
||||
)
|
||||
|
||||
if (
|
||||
file.user_id == user.id
|
||||
or user.role == "admin"
|
||||
or has_access_to_file(id, "read", user)
|
||||
):
|
||||
if stream:
|
||||
MAX_FILE_PROCESSING_DURATION = 3600 * 2
|
||||
|
||||
async def event_stream(file_item):
|
||||
for _ in range(MAX_FILE_PROCESSING_DURATION):
|
||||
file_item = Files.get_file_by_id(file_item.id)
|
||||
if file_item:
|
||||
data = file_item.model_dump().get("data", {})
|
||||
status = data.get("status")
|
||||
|
||||
if status:
|
||||
event = {"status": status}
|
||||
if status == "failed":
|
||||
event["error"] = data.get("error")
|
||||
|
||||
yield f"data: {json.dumps(event)}\n\n"
|
||||
if status in ("completed", "failed"):
|
||||
break
|
||||
else:
|
||||
# Legacy
|
||||
break
|
||||
|
||||
await asyncio.sleep(0.5)
|
||||
|
||||
return StreamingResponse(
|
||||
event_stream(file),
|
||||
media_type="text/event-stream",
|
||||
)
|
||||
else:
|
||||
return {"status": file.data.get("status", "pending")}
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=ERROR_MESSAGES.NOT_FOUND,
|
||||
)
|
||||
|
||||
|
||||
############################
|
||||
# Get File Data Content By Id
|
||||
############################
|
||||
|
||||
@@ -10,11 +10,18 @@ from typing import Optional
|
||||
|
||||
from urllib.parse import quote
|
||||
import requests
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, UploadFile
|
||||
from fastapi import (
|
||||
APIRouter,
|
||||
Depends,
|
||||
HTTPException,
|
||||
Request,
|
||||
UploadFile,
|
||||
)
|
||||
|
||||
from open_webui.config import CACHE_DIR
|
||||
from open_webui.constants import ERROR_MESSAGES
|
||||
from open_webui.env import ENABLE_FORWARD_USER_INFO_HEADERS, SRC_LOG_LEVELS
|
||||
from open_webui.routers.files import upload_file
|
||||
from open_webui.routers.files import upload_file_handler
|
||||
from open_webui.utils.auth import get_admin_user, get_verified_user
|
||||
from open_webui.utils.images.comfyui import (
|
||||
ComfyUIGenerateImageForm,
|
||||
@@ -469,7 +476,13 @@ def upload_image(request, image_data, content_type, metadata, user):
|
||||
"content-type": content_type,
|
||||
},
|
||||
)
|
||||
file_item = upload_file(request, file, metadata=metadata, internal=True, user=user)
|
||||
file_item = upload_file_handler(
|
||||
request,
|
||||
file=file,
|
||||
metadata=metadata,
|
||||
process=False,
|
||||
user=user,
|
||||
)
|
||||
url = request.app.url_path_for("get_file_content_by_id", id=file_item.id)
|
||||
return url
|
||||
|
||||
@@ -483,11 +496,18 @@ async def image_generations(
|
||||
# if IMAGE_SIZE = 'auto', default WidthxHeight to the 512x512 default
|
||||
# This is only relevant when the user has set IMAGE_SIZE to 'auto' with an
|
||||
# image model other than gpt-image-1, which is warned about on settings save
|
||||
width, height = (
|
||||
tuple(map(int, request.app.state.config.IMAGE_SIZE.split("x")))
|
||||
if "x" in request.app.state.config.IMAGE_SIZE
|
||||
else (512, 512)
|
||||
)
|
||||
|
||||
size = "512x512"
|
||||
if (
|
||||
request.app.state.config.IMAGE_SIZE
|
||||
and "x" in request.app.state.config.IMAGE_SIZE
|
||||
):
|
||||
size = request.app.state.config.IMAGE_SIZE
|
||||
|
||||
if form_data.size and "x" in form_data.size:
|
||||
size = form_data.size
|
||||
|
||||
width, height = tuple(map(int, size.split("x")))
|
||||
|
||||
r = None
|
||||
try:
|
||||
|
||||
@@ -25,7 +25,7 @@ from open_webui.utils.access_control import has_access, has_permission
|
||||
|
||||
|
||||
from open_webui.env import SRC_LOG_LEVELS
|
||||
from open_webui.config import ENABLE_ADMIN_WORKSPACE_CONTENT_ACCESS
|
||||
from open_webui.config import BYPASS_ADMIN_ACCESS_CONTROL
|
||||
from open_webui.models.models import Models, ModelForm
|
||||
|
||||
|
||||
@@ -43,7 +43,7 @@ router = APIRouter()
|
||||
async def get_knowledge(user=Depends(get_verified_user)):
|
||||
knowledge_bases = []
|
||||
|
||||
if user.role == "admin" and ENABLE_ADMIN_WORKSPACE_CONTENT_ACCESS:
|
||||
if user.role == "admin" and BYPASS_ADMIN_ACCESS_CONTROL:
|
||||
knowledge_bases = Knowledges.get_knowledge_bases()
|
||||
else:
|
||||
knowledge_bases = Knowledges.get_knowledge_bases_by_user_id(user.id, "read")
|
||||
@@ -91,7 +91,7 @@ async def get_knowledge(user=Depends(get_verified_user)):
|
||||
async def get_knowledge_list(user=Depends(get_verified_user)):
|
||||
knowledge_bases = []
|
||||
|
||||
if user.role == "admin" and ENABLE_ADMIN_WORKSPACE_CONTENT_ACCESS:
|
||||
if user.role == "admin" and BYPASS_ADMIN_ACCESS_CONTROL:
|
||||
knowledge_bases = Knowledges.get_knowledge_bases()
|
||||
else:
|
||||
knowledge_bases = Knowledges.get_knowledge_bases_by_user_id(user.id, "write")
|
||||
|
||||
@@ -15,7 +15,7 @@ from fastapi import APIRouter, Depends, HTTPException, Request, status
|
||||
|
||||
from open_webui.utils.auth import get_admin_user, get_verified_user
|
||||
from open_webui.utils.access_control import has_access, has_permission
|
||||
from open_webui.config import ENABLE_ADMIN_WORKSPACE_CONTENT_ACCESS
|
||||
from open_webui.config import BYPASS_ADMIN_ACCESS_CONTROL
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -27,7 +27,7 @@ router = APIRouter()
|
||||
|
||||
@router.get("/", response_model=list[ModelUserResponse])
|
||||
async def get_models(id: Optional[str] = None, user=Depends(get_verified_user)):
|
||||
if user.role == "admin" and ENABLE_ADMIN_WORKSPACE_CONTENT_ACCESS:
|
||||
if user.role == "admin" and BYPASS_ADMIN_ACCESS_CONTROL:
|
||||
return Models.get_models()
|
||||
else:
|
||||
return Models.get_models_by_user_id(user.id)
|
||||
@@ -117,7 +117,7 @@ async def get_model_by_id(id: str, user=Depends(get_verified_user)):
|
||||
model = Models.get_model_by_id(id)
|
||||
if model:
|
||||
if (
|
||||
user.role == "admin"
|
||||
(user.role == "admin" and BYPASS_ADMIN_ACCESS_CONTROL)
|
||||
or model.user_id == user.id
|
||||
or has_access(user.id, "read", model.access_control)
|
||||
):
|
||||
|
||||
@@ -47,7 +47,7 @@ from open_webui.utils.misc import (
|
||||
from open_webui.utils.payload import (
|
||||
apply_model_params_to_body_ollama,
|
||||
apply_model_params_to_body_openai,
|
||||
apply_model_system_prompt_to_body,
|
||||
apply_system_prompt_to_body,
|
||||
)
|
||||
from open_webui.utils.auth import get_admin_user, get_verified_user
|
||||
from open_webui.utils.access_control import has_access
|
||||
@@ -329,12 +329,13 @@ def merge_ollama_models_lists(model_lists):
|
||||
for idx, model_list in enumerate(model_lists):
|
||||
if model_list is not None:
|
||||
for model in model_list:
|
||||
id = model["model"]
|
||||
if id not in merged_models:
|
||||
model["urls"] = [idx]
|
||||
merged_models[id] = model
|
||||
else:
|
||||
merged_models[id]["urls"].append(idx)
|
||||
id = model.get("model")
|
||||
if id is not None:
|
||||
if id not in merged_models:
|
||||
model["urls"] = [idx]
|
||||
merged_models[id] = model
|
||||
else:
|
||||
merged_models[id]["urls"].append(idx)
|
||||
|
||||
return list(merged_models.values())
|
||||
|
||||
@@ -415,15 +416,15 @@ async def get_all_models(request: Request, user: UserModel = None):
|
||||
try:
|
||||
loaded_models = await get_ollama_loaded_models(request, user=user)
|
||||
expires_map = {
|
||||
m["name"]: m["expires_at"]
|
||||
m["model"]: m["expires_at"]
|
||||
for m in loaded_models["models"]
|
||||
if "expires_at" in m
|
||||
}
|
||||
|
||||
for m in models["models"]:
|
||||
if m["name"] in expires_map:
|
||||
if m["model"] in expires_map:
|
||||
# Parse ISO8601 datetime with offset, get unix timestamp as int
|
||||
dt = datetime.fromisoformat(expires_map[m["name"]])
|
||||
dt = datetime.fromisoformat(expires_map[m["model"]])
|
||||
m["expires_at"] = int(dt.timestamp())
|
||||
except Exception as e:
|
||||
log.debug(f"Failed to get loaded models: {e}")
|
||||
@@ -1330,7 +1331,7 @@ async def generate_chat_completion(
|
||||
system = params.pop("system", None)
|
||||
|
||||
payload = apply_model_params_to_body_ollama(params, payload)
|
||||
payload = apply_model_system_prompt_to_body(system, payload, metadata, user)
|
||||
payload = apply_system_prompt_to_body(system, payload, metadata, user)
|
||||
|
||||
# Check if user has access to the model
|
||||
if not bypass_filter and user.role == "user":
|
||||
@@ -1519,7 +1520,7 @@ async def generate_openai_chat_completion(
|
||||
system = params.pop("system", None)
|
||||
|
||||
payload = apply_model_params_to_body_openai(params, payload)
|
||||
payload = apply_model_system_prompt_to_body(system, payload, metadata, user)
|
||||
payload = apply_system_prompt_to_body(system, payload, metadata, user)
|
||||
|
||||
# Check if user has access to the model
|
||||
if user.role == "user":
|
||||
|
||||
@@ -39,7 +39,7 @@ from open_webui.env import SRC_LOG_LEVELS
|
||||
|
||||
from open_webui.utils.payload import (
|
||||
apply_model_params_to_body_openai,
|
||||
apply_model_system_prompt_to_body,
|
||||
apply_system_prompt_to_body,
|
||||
)
|
||||
from open_webui.utils.misc import (
|
||||
convert_logit_bias_input_to_json,
|
||||
@@ -361,9 +361,18 @@ async def get_all_models_responses(request: Request, user: UserModel) -> list:
|
||||
prefix_id = api_config.get("prefix_id", None)
|
||||
tags = api_config.get("tags", [])
|
||||
|
||||
for model in (
|
||||
model_list = (
|
||||
response if isinstance(response, list) else response.get("data", [])
|
||||
):
|
||||
)
|
||||
if not isinstance(model_list, list):
|
||||
# Catch non-list responses
|
||||
model_list = []
|
||||
|
||||
for model in model_list:
|
||||
# Remove name key if its value is None #16689
|
||||
if "name" in model and model["name"] is None:
|
||||
del model["name"]
|
||||
|
||||
if prefix_id:
|
||||
model["id"] = (
|
||||
f"{prefix_id}.{model.get('id', model.get('name', ''))}"
|
||||
@@ -693,6 +702,10 @@ def get_azure_allowed_params(api_version: str) -> set[str]:
|
||||
return allowed_params
|
||||
|
||||
|
||||
def is_openai_reasoning_model(model: str) -> bool:
|
||||
return model.lower().startswith(("o1", "o3", "o4", "gpt-5"))
|
||||
|
||||
|
||||
def convert_to_azure_payload(url, payload: dict, api_version: str):
|
||||
model = payload.get("model", "")
|
||||
|
||||
@@ -700,7 +713,7 @@ def convert_to_azure_payload(url, payload: dict, api_version: str):
|
||||
allowed_params = get_azure_allowed_params(api_version)
|
||||
|
||||
# Special handling for o-series models
|
||||
if model.startswith("o") and model.endswith("-mini"):
|
||||
if is_openai_reasoning_model(model):
|
||||
# Convert max_tokens to max_completion_tokens for o-series models
|
||||
if "max_tokens" in payload:
|
||||
payload["max_completion_tokens"] = payload["max_tokens"]
|
||||
@@ -750,7 +763,7 @@ async def generate_chat_completion(
|
||||
system = params.pop("system", None)
|
||||
|
||||
payload = apply_model_params_to_body_openai(params, payload)
|
||||
payload = apply_model_system_prompt_to_body(system, payload, metadata, user)
|
||||
payload = apply_system_prompt_to_body(system, payload, metadata, user)
|
||||
|
||||
# Check if user has access to the model
|
||||
if not bypass_filter and user.role == "user":
|
||||
@@ -806,10 +819,7 @@ async def generate_chat_completion(
|
||||
key = request.app.state.config.OPENAI_API_KEYS[idx]
|
||||
|
||||
# Check if model is a reasoning model that needs special handling
|
||||
is_reasoning_model = (
|
||||
payload["model"].lower().startswith(("o1", "o3", "o4", "gpt-5"))
|
||||
)
|
||||
if is_reasoning_model:
|
||||
if is_openai_reasoning_model(payload["model"]):
|
||||
payload = openai_reasoning_model_handler(payload)
|
||||
elif "api.openai.com" not in url:
|
||||
# Remove "max_completion_tokens" from the payload for backward compatibility
|
||||
|
||||
@@ -10,7 +10,7 @@ from open_webui.models.prompts import (
|
||||
from open_webui.constants import ERROR_MESSAGES
|
||||
from open_webui.utils.auth import get_admin_user, get_verified_user
|
||||
from open_webui.utils.access_control import has_access, has_permission
|
||||
from open_webui.config import ENABLE_ADMIN_WORKSPACE_CONTENT_ACCESS
|
||||
from open_webui.config import BYPASS_ADMIN_ACCESS_CONTROL
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -21,7 +21,7 @@ router = APIRouter()
|
||||
|
||||
@router.get("/", response_model=list[PromptModel])
|
||||
async def get_prompts(user=Depends(get_verified_user)):
|
||||
if user.role == "admin" and ENABLE_ADMIN_WORKSPACE_CONTENT_ACCESS:
|
||||
if user.role == "admin" and BYPASS_ADMIN_ACCESS_CONTROL:
|
||||
prompts = Prompts.get_prompts()
|
||||
else:
|
||||
prompts = Prompts.get_prompts_by_user_id(user.id, "read")
|
||||
@@ -31,7 +31,7 @@ async def get_prompts(user=Depends(get_verified_user)):
|
||||
|
||||
@router.get("/list", response_model=list[PromptUserResponse])
|
||||
async def get_prompt_list(user=Depends(get_verified_user)):
|
||||
if user.role == "admin" and ENABLE_ADMIN_WORKSPACE_CONTENT_ACCESS:
|
||||
if user.role == "admin" and BYPASS_ADMIN_ACCESS_CONTROL:
|
||||
prompts = Prompts.get_prompts()
|
||||
else:
|
||||
prompts = Prompts.get_prompts_by_user_id(user.id, "write")
|
||||
|
||||
@@ -5,7 +5,6 @@ import os
|
||||
import shutil
|
||||
import asyncio
|
||||
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
@@ -281,6 +280,18 @@ async def update_embedding_config(
|
||||
log.info(
|
||||
f"Updating embedding model: {request.app.state.config.RAG_EMBEDDING_MODEL} to {form_data.embedding_model}"
|
||||
)
|
||||
if request.app.state.config.RAG_EMBEDDING_ENGINE == "":
|
||||
# unloads current internal embedding model and clears VRAM cache
|
||||
request.app.state.ef = None
|
||||
request.app.state.EMBEDDING_FUNCTION = None
|
||||
import gc
|
||||
|
||||
gc.collect()
|
||||
if DEVICE_TYPE == "cuda":
|
||||
import torch
|
||||
|
||||
if torch.cuda.is_available():
|
||||
torch.cuda.empty_cache()
|
||||
try:
|
||||
request.app.state.config.RAG_EMBEDDING_ENGINE = form_data.embedding_engine
|
||||
request.app.state.config.RAG_EMBEDDING_MODEL = form_data.embedding_model
|
||||
@@ -449,6 +460,7 @@ async def get_rag_config(request: Request, user=Depends(get_admin_user)):
|
||||
"WEB_SEARCH_TRUST_ENV": request.app.state.config.WEB_SEARCH_TRUST_ENV,
|
||||
"WEB_SEARCH_RESULT_COUNT": request.app.state.config.WEB_SEARCH_RESULT_COUNT,
|
||||
"WEB_SEARCH_CONCURRENT_REQUESTS": request.app.state.config.WEB_SEARCH_CONCURRENT_REQUESTS,
|
||||
"WEB_LOADER_CONCURRENT_REQUESTS": request.app.state.config.WEB_LOADER_CONCURRENT_REQUESTS,
|
||||
"WEB_SEARCH_DOMAIN_FILTER_LIST": request.app.state.config.WEB_SEARCH_DOMAIN_FILTER_LIST,
|
||||
"BYPASS_WEB_SEARCH_EMBEDDING_AND_RETRIEVAL": request.app.state.config.BYPASS_WEB_SEARCH_EMBEDDING_AND_RETRIEVAL,
|
||||
"BYPASS_WEB_SEARCH_WEB_LOADER": request.app.state.config.BYPASS_WEB_SEARCH_WEB_LOADER,
|
||||
@@ -504,6 +516,7 @@ class WebConfig(BaseModel):
|
||||
WEB_SEARCH_TRUST_ENV: Optional[bool] = None
|
||||
WEB_SEARCH_RESULT_COUNT: Optional[int] = None
|
||||
WEB_SEARCH_CONCURRENT_REQUESTS: Optional[int] = None
|
||||
WEB_LOADER_CONCURRENT_REQUESTS: Optional[int] = None
|
||||
WEB_SEARCH_DOMAIN_FILTER_LIST: Optional[List[str]] = []
|
||||
BYPASS_WEB_SEARCH_EMBEDDING_AND_RETRIEVAL: Optional[bool] = None
|
||||
BYPASS_WEB_SEARCH_WEB_LOADER: Optional[bool] = None
|
||||
@@ -651,9 +664,6 @@ async def update_rag_config(
|
||||
if form_data.ENABLE_RAG_HYBRID_SEARCH is not None
|
||||
else request.app.state.config.ENABLE_RAG_HYBRID_SEARCH
|
||||
)
|
||||
# Free up memory if hybrid search is disabled
|
||||
if not request.app.state.config.ENABLE_RAG_HYBRID_SEARCH:
|
||||
request.app.state.rf = None
|
||||
|
||||
request.app.state.config.TOP_K_RERANKER = (
|
||||
form_data.TOP_K_RERANKER
|
||||
@@ -807,6 +817,18 @@ async def update_rag_config(
|
||||
)
|
||||
|
||||
# Reranking settings
|
||||
if request.app.state.config.RAG_RERANKING_ENGINE == "":
|
||||
# Unloading the internal reranker and clear VRAM memory
|
||||
request.app.state.rf = None
|
||||
request.app.state.RERANKING_FUNCTION = None
|
||||
import gc
|
||||
|
||||
gc.collect()
|
||||
if DEVICE_TYPE == "cuda":
|
||||
import torch
|
||||
|
||||
if torch.cuda.is_available():
|
||||
torch.cuda.empty_cache()
|
||||
request.app.state.config.RAG_RERANKING_ENGINE = (
|
||||
form_data.RAG_RERANKING_ENGINE
|
||||
if form_data.RAG_RERANKING_ENGINE is not None
|
||||
@@ -836,19 +858,23 @@ async def update_rag_config(
|
||||
)
|
||||
|
||||
try:
|
||||
request.app.state.rf = get_rf(
|
||||
request.app.state.config.RAG_RERANKING_ENGINE,
|
||||
request.app.state.config.RAG_RERANKING_MODEL,
|
||||
request.app.state.config.RAG_EXTERNAL_RERANKER_URL,
|
||||
request.app.state.config.RAG_EXTERNAL_RERANKER_API_KEY,
|
||||
True,
|
||||
)
|
||||
if (
|
||||
request.app.state.config.ENABLE_RAG_HYBRID_SEARCH
|
||||
and not request.app.state.config.BYPASS_EMBEDDING_AND_RETRIEVAL
|
||||
):
|
||||
request.app.state.rf = get_rf(
|
||||
request.app.state.config.RAG_RERANKING_ENGINE,
|
||||
request.app.state.config.RAG_RERANKING_MODEL,
|
||||
request.app.state.config.RAG_EXTERNAL_RERANKER_URL,
|
||||
request.app.state.config.RAG_EXTERNAL_RERANKER_API_KEY,
|
||||
True,
|
||||
)
|
||||
|
||||
request.app.state.RERANKING_FUNCTION = get_reranking_function(
|
||||
request.app.state.config.RAG_RERANKING_ENGINE,
|
||||
request.app.state.config.RAG_RERANKING_MODEL,
|
||||
request.app.state.rf,
|
||||
)
|
||||
request.app.state.RERANKING_FUNCTION = get_reranking_function(
|
||||
request.app.state.config.RAG_RERANKING_ENGINE,
|
||||
request.app.state.config.RAG_RERANKING_MODEL,
|
||||
request.app.state.rf,
|
||||
)
|
||||
except Exception as e:
|
||||
log.error(f"Error loading reranking model: {e}")
|
||||
request.app.state.config.ENABLE_RAG_HYBRID_SEARCH = False
|
||||
@@ -916,6 +942,9 @@ async def update_rag_config(
|
||||
request.app.state.config.WEB_SEARCH_CONCURRENT_REQUESTS = (
|
||||
form_data.web.WEB_SEARCH_CONCURRENT_REQUESTS
|
||||
)
|
||||
request.app.state.config.WEB_LOADER_CONCURRENT_REQUESTS = (
|
||||
form_data.web.WEB_LOADER_CONCURRENT_REQUESTS
|
||||
)
|
||||
request.app.state.config.WEB_SEARCH_DOMAIN_FILTER_LIST = (
|
||||
form_data.web.WEB_SEARCH_DOMAIN_FILTER_LIST
|
||||
)
|
||||
@@ -1067,6 +1096,7 @@ async def update_rag_config(
|
||||
"WEB_SEARCH_TRUST_ENV": request.app.state.config.WEB_SEARCH_TRUST_ENV,
|
||||
"WEB_SEARCH_RESULT_COUNT": request.app.state.config.WEB_SEARCH_RESULT_COUNT,
|
||||
"WEB_SEARCH_CONCURRENT_REQUESTS": request.app.state.config.WEB_SEARCH_CONCURRENT_REQUESTS,
|
||||
"WEB_LOADER_CONCURRENT_REQUESTS": request.app.state.config.WEB_LOADER_CONCURRENT_REQUESTS,
|
||||
"WEB_SEARCH_DOMAIN_FILTER_LIST": request.app.state.config.WEB_SEARCH_DOMAIN_FILTER_LIST,
|
||||
"BYPASS_WEB_SEARCH_EMBEDDING_AND_RETRIEVAL": request.app.state.config.BYPASS_WEB_SEARCH_EMBEDDING_AND_RETRIEVAL,
|
||||
"BYPASS_WEB_SEARCH_WEB_LOADER": request.app.state.config.BYPASS_WEB_SEARCH_WEB_LOADER,
|
||||
@@ -1470,7 +1500,7 @@ def process_file(
|
||||
log.debug(f"text_content: {text_content}")
|
||||
Files.update_file_data_by_id(
|
||||
file.id,
|
||||
{"content": text_content},
|
||||
{"status": "completed", "content": text_content},
|
||||
)
|
||||
|
||||
hash = calculate_sha256_string(text_content)
|
||||
@@ -1624,7 +1654,7 @@ def process_web(
|
||||
loader = get_web_loader(
|
||||
form_data.url,
|
||||
verify_ssl=request.app.state.config.ENABLE_WEB_LOADER_SSL_VERIFICATION,
|
||||
requests_per_second=request.app.state.config.WEB_SEARCH_CONCURRENT_REQUESTS,
|
||||
requests_per_second=request.app.state.config.WEB_LOADER_CONCURRENT_REQUESTS,
|
||||
)
|
||||
docs = loader.load()
|
||||
content = " ".join([doc.page_content for doc in docs])
|
||||
@@ -1798,6 +1828,7 @@ def search_web(request: Request, engine: str, query: str) -> list[SearchResult]:
|
||||
query,
|
||||
request.app.state.config.WEB_SEARCH_RESULT_COUNT,
|
||||
request.app.state.config.WEB_SEARCH_DOMAIN_FILTER_LIST,
|
||||
concurrent_requests=request.app.state.config.WEB_SEARCH_CONCURRENT_REQUESTS,
|
||||
)
|
||||
elif engine == "tavily":
|
||||
if request.app.state.config.TAVILY_API_KEY:
|
||||
@@ -1971,7 +2002,7 @@ async def process_web_search(
|
||||
loader = get_web_loader(
|
||||
urls,
|
||||
verify_ssl=request.app.state.config.ENABLE_WEB_LOADER_SSL_VERIFICATION,
|
||||
requests_per_second=request.app.state.config.WEB_SEARCH_CONCURRENT_REQUESTS,
|
||||
requests_per_second=request.app.state.config.WEB_LOADER_CONCURRENT_REQUESTS,
|
||||
trust_env=request.app.state.config.WEB_SEARCH_TRUST_ENV,
|
||||
)
|
||||
docs = await loader.aload()
|
||||
@@ -2044,7 +2075,9 @@ def query_doc_handler(
|
||||
user=Depends(get_verified_user),
|
||||
):
|
||||
try:
|
||||
if request.app.state.config.ENABLE_RAG_HYBRID_SEARCH:
|
||||
if request.app.state.config.ENABLE_RAG_HYBRID_SEARCH and (
|
||||
form_data.hybrid is None or form_data.hybrid
|
||||
):
|
||||
collection_results = {}
|
||||
collection_results[form_data.collection_name] = VECTOR_DB_CLIENT.get(
|
||||
collection_name=form_data.collection_name
|
||||
@@ -2114,7 +2147,9 @@ def query_collection_handler(
|
||||
user=Depends(get_verified_user),
|
||||
):
|
||||
try:
|
||||
if request.app.state.config.ENABLE_RAG_HYBRID_SEARCH:
|
||||
if request.app.state.config.ENABLE_RAG_HYBRID_SEARCH and (
|
||||
form_data.hybrid is None or form_data.hybrid
|
||||
):
|
||||
return query_collection_with_hybrid_search(
|
||||
collection_names=form_data.collection_names,
|
||||
queries=[form_data.query],
|
||||
|
||||
@@ -198,14 +198,7 @@ async def generate_title(
|
||||
else:
|
||||
template = DEFAULT_TITLE_GENERATION_PROMPT_TEMPLATE
|
||||
|
||||
content = title_generation_template(
|
||||
template,
|
||||
form_data["messages"],
|
||||
{
|
||||
"name": user.name,
|
||||
"location": user.info.get("location") if user.info else None,
|
||||
},
|
||||
)
|
||||
content = title_generation_template(template, form_data["messages"], user)
|
||||
|
||||
max_tokens = (
|
||||
models[task_model_id].get("info", {}).get("params", {}).get("max_tokens", 1000)
|
||||
@@ -289,14 +282,7 @@ async def generate_follow_ups(
|
||||
else:
|
||||
template = DEFAULT_FOLLOW_UP_GENERATION_PROMPT_TEMPLATE
|
||||
|
||||
content = follow_up_generation_template(
|
||||
template,
|
||||
form_data["messages"],
|
||||
{
|
||||
"name": user.name,
|
||||
"location": user.info.get("location") if user.info else None,
|
||||
},
|
||||
)
|
||||
content = follow_up_generation_template(template, form_data["messages"], user)
|
||||
|
||||
payload = {
|
||||
"model": task_model_id,
|
||||
@@ -369,9 +355,7 @@ async def generate_chat_tags(
|
||||
else:
|
||||
template = DEFAULT_TAGS_GENERATION_PROMPT_TEMPLATE
|
||||
|
||||
content = tags_generation_template(
|
||||
template, form_data["messages"], {"name": user.name}
|
||||
)
|
||||
content = tags_generation_template(template, form_data["messages"], user)
|
||||
|
||||
payload = {
|
||||
"model": task_model_id,
|
||||
@@ -437,13 +421,7 @@ async def generate_image_prompt(
|
||||
else:
|
||||
template = DEFAULT_IMAGE_PROMPT_GENERATION_PROMPT_TEMPLATE
|
||||
|
||||
content = image_prompt_generation_template(
|
||||
template,
|
||||
form_data["messages"],
|
||||
user={
|
||||
"name": user.name,
|
||||
},
|
||||
)
|
||||
content = image_prompt_generation_template(template, form_data["messages"], user)
|
||||
|
||||
payload = {
|
||||
"model": task_model_id,
|
||||
@@ -492,6 +470,10 @@ async def generate_queries(
|
||||
detail=f"Query generation is disabled",
|
||||
)
|
||||
|
||||
if getattr(request.state, "cached_queries", None):
|
||||
log.info(f"Reusing cached queries: {request.state.cached_queries}")
|
||||
return request.state.cached_queries
|
||||
|
||||
if getattr(request.state, "direct", False) and hasattr(request.state, "model"):
|
||||
models = {
|
||||
request.state.model["id"]: request.state.model,
|
||||
@@ -524,9 +506,7 @@ async def generate_queries(
|
||||
else:
|
||||
template = DEFAULT_QUERY_GENERATION_PROMPT_TEMPLATE
|
||||
|
||||
content = query_generation_template(
|
||||
template, form_data["messages"], {"name": user.name}
|
||||
)
|
||||
content = query_generation_template(template, form_data["messages"], user)
|
||||
|
||||
payload = {
|
||||
"model": task_model_id,
|
||||
@@ -611,9 +591,7 @@ async def generate_autocompletion(
|
||||
else:
|
||||
template = DEFAULT_AUTOCOMPLETE_GENERATION_PROMPT_TEMPLATE
|
||||
|
||||
content = autocomplete_generation_template(
|
||||
template, prompt, messages, type, {"name": user.name}
|
||||
)
|
||||
content = autocomplete_generation_template(template, prompt, messages, type, user)
|
||||
|
||||
payload = {
|
||||
"model": task_model_id,
|
||||
@@ -675,14 +653,7 @@ async def generate_emoji(
|
||||
|
||||
template = DEFAULT_EMOJI_GENERATION_PROMPT_TEMPLATE
|
||||
|
||||
content = emoji_generation_template(
|
||||
template,
|
||||
form_data["prompt"],
|
||||
{
|
||||
"name": user.name,
|
||||
"location": user.info.get("location") if user.info else None,
|
||||
},
|
||||
)
|
||||
content = emoji_generation_template(template, form_data["prompt"], user)
|
||||
|
||||
payload = {
|
||||
"model": task_model_id,
|
||||
|
||||
@@ -19,10 +19,10 @@ from open_webui.utils.plugin import load_tool_module_by_id, replace_imports
|
||||
from open_webui.utils.tools import get_tool_specs
|
||||
from open_webui.utils.auth import get_admin_user, get_verified_user
|
||||
from open_webui.utils.access_control import has_access, has_permission
|
||||
from open_webui.utils.tools import get_tool_servers_data
|
||||
from open_webui.utils.tools import get_tool_servers
|
||||
|
||||
from open_webui.env import SRC_LOG_LEVELS
|
||||
from open_webui.config import CACHE_DIR, ENABLE_ADMIN_WORKSPACE_CONTENT_ACCESS
|
||||
from open_webui.config import CACHE_DIR, BYPASS_ADMIN_ACCESS_CONTROL
|
||||
from open_webui.constants import ERROR_MESSAGES
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ log.setLevel(SRC_LOG_LEVELS["MAIN"])
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
############################
|
||||
# GetTools
|
||||
############################
|
||||
@@ -39,23 +40,14 @@ router = APIRouter()
|
||||
|
||||
@router.get("/", response_model=list[ToolUserResponse])
|
||||
async def get_tools(request: Request, user=Depends(get_verified_user)):
|
||||
|
||||
if not request.app.state.TOOL_SERVERS:
|
||||
# If the tool servers are not set, we need to set them
|
||||
# This is done only once when the server starts
|
||||
# This is done to avoid loading the tool servers every time
|
||||
|
||||
request.app.state.TOOL_SERVERS = await get_tool_servers_data(
|
||||
request.app.state.config.TOOL_SERVER_CONNECTIONS
|
||||
)
|
||||
|
||||
tools = Tools.get_tools()
|
||||
for server in request.app.state.TOOL_SERVERS:
|
||||
|
||||
for server in await get_tool_servers(request):
|
||||
tools.append(
|
||||
ToolUserResponse(
|
||||
**{
|
||||
"id": f"server:{server['idx']}",
|
||||
"user_id": f"server:{server['idx']}",
|
||||
"id": f"server:{server.get('id')}",
|
||||
"user_id": f"server:{server.get('id')}",
|
||||
"name": server.get("openapi", {})
|
||||
.get("info", {})
|
||||
.get("title", "Tool Server"),
|
||||
@@ -65,7 +57,7 @@ async def get_tools(request: Request, user=Depends(get_verified_user)):
|
||||
.get("description", ""),
|
||||
},
|
||||
"access_control": request.app.state.config.TOOL_SERVER_CONNECTIONS[
|
||||
server["idx"]
|
||||
server.get("idx", 0)
|
||||
]
|
||||
.get("config", {})
|
||||
.get("access_control", None),
|
||||
@@ -75,7 +67,7 @@ async def get_tools(request: Request, user=Depends(get_verified_user)):
|
||||
)
|
||||
)
|
||||
|
||||
if user.role == "admin" and ENABLE_ADMIN_WORKSPACE_CONTENT_ACCESS:
|
||||
if user.role == "admin" and BYPASS_ADMIN_ACCESS_CONTROL:
|
||||
# Admin can see all tools
|
||||
return tools
|
||||
else:
|
||||
@@ -95,7 +87,7 @@ async def get_tools(request: Request, user=Depends(get_verified_user)):
|
||||
|
||||
@router.get("/list", response_model=list[ToolUserResponse])
|
||||
async def get_tool_list(user=Depends(get_verified_user)):
|
||||
if user.role == "admin" and ENABLE_ADMIN_WORKSPACE_CONTENT_ACCESS:
|
||||
if user.role == "admin" and BYPASS_ADMIN_ACCESS_CONTROL:
|
||||
tools = Tools.get_tools()
|
||||
else:
|
||||
tools = Tools.get_tools_by_user_id(user.id, "write")
|
||||
|
||||
@@ -146,6 +146,10 @@ class ChatPermissions(BaseModel):
|
||||
params: bool = True
|
||||
file_upload: bool = True
|
||||
delete: bool = True
|
||||
delete_message: bool = True
|
||||
continue_response: bool = True
|
||||
regenerate_response: bool = True
|
||||
rate_response: bool = True
|
||||
edit: bool = True
|
||||
share: bool = True
|
||||
export: bool = True
|
||||
@@ -501,3 +505,13 @@ async def delete_user_by_id(user_id: str, user=Depends(get_admin_user)):
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail=ERROR_MESSAGES.ACTION_PROHIBITED,
|
||||
)
|
||||
|
||||
|
||||
############################
|
||||
# GetUserGroupsById
|
||||
############################
|
||||
|
||||
|
||||
@router.get("/{user_id}/groups")
|
||||
async def get_user_groups_by_id(user_id: str, user=Depends(get_admin_user)):
|
||||
return Groups.get_groups_by_member_id(user_id)
|
||||
|
||||
@@ -115,7 +115,7 @@ if WEBSOCKET_MANAGER == "redis":
|
||||
|
||||
clean_up_lock = RedisLock(
|
||||
redis_url=WEBSOCKET_REDIS_URL,
|
||||
lock_name="usage_cleanup_lock",
|
||||
lock_name=f"{REDIS_KEY_PREFIX}:usage_cleanup_lock",
|
||||
timeout_secs=WEBSOCKET_REDIS_LOCK_TIMEOUT,
|
||||
redis_sentinels=redis_sentinels,
|
||||
redis_cluster=WEBSOCKET_REDIS_CLUSTER,
|
||||
@@ -266,7 +266,9 @@ async def connect(sid, environ, auth):
|
||||
user = Users.get_user_by_id(data["id"])
|
||||
|
||||
if user:
|
||||
SESSION_POOL[sid] = user.model_dump()
|
||||
SESSION_POOL[sid] = user.model_dump(
|
||||
exclude=["date_of_birth", "bio", "gender"]
|
||||
)
|
||||
if user.id in USER_POOL:
|
||||
USER_POOL[user.id] = USER_POOL[user.id] + [sid]
|
||||
else:
|
||||
@@ -288,7 +290,7 @@ async def user_join(sid, data):
|
||||
if not user:
|
||||
return
|
||||
|
||||
SESSION_POOL[sid] = user.model_dump()
|
||||
SESSION_POOL[sid] = user.model_dump(exclude=["date_of_birth", "bio", "gender"])
|
||||
if user.id in USER_POOL:
|
||||
USER_POOL[user.id] = USER_POOL[user.id] + [sid]
|
||||
else:
|
||||
@@ -703,6 +705,42 @@ def get_event_emitter(request_info, update_db=True):
|
||||
},
|
||||
)
|
||||
|
||||
if "type" in event_data and event_data["type"] == "files":
|
||||
message = Chats.get_message_by_id_and_message_id(
|
||||
request_info["chat_id"],
|
||||
request_info["message_id"],
|
||||
)
|
||||
|
||||
files = event_data.get("data", {}).get("files", [])
|
||||
files.extend(message.get("files", []))
|
||||
|
||||
Chats.upsert_message_to_chat_by_id_and_message_id(
|
||||
request_info["chat_id"],
|
||||
request_info["message_id"],
|
||||
{
|
||||
"files": files,
|
||||
},
|
||||
)
|
||||
|
||||
if event_data.get("type") in ["source", "citation"]:
|
||||
data = event_data.get("data", {})
|
||||
if data.get("type") == None:
|
||||
message = Chats.get_message_by_id_and_message_id(
|
||||
request_info["chat_id"],
|
||||
request_info["message_id"],
|
||||
)
|
||||
|
||||
sources = message.get("sources", [])
|
||||
sources.append(data)
|
||||
|
||||
Chats.upsert_message_to_chat_by_id_and_message_id(
|
||||
request_info["chat_id"],
|
||||
request_info["message_id"],
|
||||
{
|
||||
"sources": sources,
|
||||
},
|
||||
)
|
||||
|
||||
return __event_emitter__
|
||||
|
||||
|
||||
|
||||
@@ -112,6 +112,9 @@ class S3StorageProvider(StorageProvider):
|
||||
"use_accelerate_endpoint": S3_USE_ACCELERATE_ENDPOINT,
|
||||
"addressing_style": S3_ADDRESSING_STYLE,
|
||||
},
|
||||
# KIT change - see https://github.com/boto/boto3/issues/4400#issuecomment-2600742103∆
|
||||
request_checksum_calculation="when_required",
|
||||
response_checksum_validation="when_required",
|
||||
)
|
||||
|
||||
# If access key and secret are provided, use them for authentication
|
||||
|
||||
@@ -60,8 +60,7 @@ def get_permissions(
|
||||
|
||||
# Combine permissions from all user groups
|
||||
for group in user_groups:
|
||||
group_permissions = group.permissions or {}
|
||||
permissions = combine_permissions(permissions, group_permissions)
|
||||
permissions = combine_permissions(permissions, group.permissions or {})
|
||||
|
||||
# Ensure all fields from default_permissions are present and filled in
|
||||
permissions = fill_missing_permissions(permissions, default_permissions)
|
||||
@@ -96,8 +95,7 @@ def has_permission(
|
||||
user_groups = Groups.get_groups_by_member_id(user_id)
|
||||
|
||||
for group in user_groups:
|
||||
group_permissions = group.permissions
|
||||
if get_permission(group_permissions, permission_hierarchy):
|
||||
if get_permission(group.permissions or {}, permission_hierarchy):
|
||||
return True
|
||||
|
||||
# Check default permissions afterward if the group permissions don't allow it
|
||||
|
||||
@@ -195,7 +195,7 @@ class AuditLoggingMiddleware:
|
||||
|
||||
try:
|
||||
user = get_current_user(
|
||||
request, None, get_http_authorization_cred(auth_header)
|
||||
request, None, None, get_http_authorization_cred(auth_header)
|
||||
)
|
||||
return user
|
||||
except Exception as e:
|
||||
|
||||
@@ -3,6 +3,7 @@ import logging
|
||||
import sys
|
||||
import os
|
||||
import base64
|
||||
import textwrap
|
||||
|
||||
import asyncio
|
||||
from aiocache import cached
|
||||
@@ -19,7 +20,7 @@ from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
|
||||
from fastapi import Request, HTTPException
|
||||
from starlette.responses import Response, StreamingResponse
|
||||
from starlette.responses import Response, StreamingResponse, JSONResponse
|
||||
|
||||
|
||||
from open_webui.models.chats import Chats
|
||||
@@ -73,6 +74,7 @@ from open_webui.utils.misc import (
|
||||
add_or_update_user_message,
|
||||
get_last_user_message,
|
||||
get_last_assistant_message,
|
||||
get_system_message,
|
||||
prepend_to_first_user_message_content,
|
||||
convert_logit_bias_input_to_json,
|
||||
)
|
||||
@@ -83,21 +85,23 @@ from open_webui.utils.filter import (
|
||||
process_filter_functions,
|
||||
)
|
||||
from open_webui.utils.code_interpreter import execute_code_jupyter
|
||||
from open_webui.utils.payload import apply_model_system_prompt_to_body
|
||||
from open_webui.utils.payload import apply_system_prompt_to_body
|
||||
|
||||
from open_webui.tasks import create_task
|
||||
|
||||
from open_webui.config import (
|
||||
CACHE_DIR,
|
||||
DEFAULT_TOOLS_FUNCTION_CALLING_PROMPT_TEMPLATE,
|
||||
DEFAULT_CODE_INTERPRETER_PROMPT,
|
||||
CODE_INTERPRETER_BLOCKED_MODULES,
|
||||
)
|
||||
from open_webui.env import (
|
||||
SRC_LOG_LEVELS,
|
||||
GLOBAL_LOG_LEVEL,
|
||||
CHAT_RESPONSE_STREAM_DELTA_CHUNK_SIZE,
|
||||
CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES,
|
||||
BYPASS_MODEL_ACCESS_CONTROL,
|
||||
ENABLE_REALTIME_CHAT_SAVE,
|
||||
ENABLE_QUERIES_CACHE,
|
||||
)
|
||||
from open_webui.constants import TASKS
|
||||
|
||||
@@ -107,6 +111,20 @@ log = logging.getLogger(__name__)
|
||||
log.setLevel(SRC_LOG_LEVELS["MAIN"])
|
||||
|
||||
|
||||
DEFAULT_REASONING_TAGS = [
|
||||
("<think>", "</think>"),
|
||||
("<thinking>", "</thinking>"),
|
||||
("<reason>", "</reason>"),
|
||||
("<reasoning>", "</reasoning>"),
|
||||
("<thought>", "</thought>"),
|
||||
("<Thought>", "</Thought>"),
|
||||
("<|begin_of_thought|>", "<|end_of_thought|>"),
|
||||
("◁think▷", "◁/think▷"),
|
||||
]
|
||||
DEFAULT_SOLUTION_TAGS = [("<|begin_of_solution|>", "<|end_of_solution|>")]
|
||||
DEFAULT_CODE_INTERPRETER_TAGS = [("<code_interpreter>", "</code_interpreter>")]
|
||||
|
||||
|
||||
async def chat_completion_tools_handler(
|
||||
request: Request, body: dict, extra_params: dict, user: UserModel, models, tools
|
||||
) -> tuple[dict, dict]:
|
||||
@@ -388,6 +406,9 @@ async def chat_web_search_handler(
|
||||
except Exception as e:
|
||||
queries = [response]
|
||||
|
||||
if ENABLE_QUERIES_CACHE:
|
||||
request.state.cached_queries = queries
|
||||
|
||||
except Exception as e:
|
||||
log.exception(e)
|
||||
queries = [user_message]
|
||||
@@ -687,6 +708,7 @@ def apply_params_to_form_data(form_data, model):
|
||||
"stream_response": bool,
|
||||
"stream_delta_chunk_size": int,
|
||||
"function_calling": str,
|
||||
"reasoning_tags": list,
|
||||
"system": str,
|
||||
}
|
||||
|
||||
@@ -736,6 +758,15 @@ async def process_chat_payload(request, form_data, user, metadata, model):
|
||||
form_data = apply_params_to_form_data(form_data, model)
|
||||
log.debug(f"form_data: {form_data}")
|
||||
|
||||
system_message = get_system_message(form_data.get("messages", []))
|
||||
if system_message:
|
||||
try:
|
||||
form_data = apply_system_prompt_to_body(
|
||||
system_message.get("content"), form_data, metadata, user
|
||||
)
|
||||
except:
|
||||
pass
|
||||
|
||||
event_emitter = get_event_emitter(metadata)
|
||||
event_call = get_event_call(metadata)
|
||||
|
||||
@@ -777,7 +808,7 @@ async def process_chat_payload(request, form_data, user, metadata, model):
|
||||
|
||||
if folder and folder.data:
|
||||
if "system_prompt" in folder.data:
|
||||
form_data = apply_model_system_prompt_to_body(
|
||||
form_data = apply_system_prompt_to_body(
|
||||
folder.data["system_prompt"], form_data, metadata, user
|
||||
)
|
||||
if "files" in folder.data:
|
||||
@@ -908,7 +939,7 @@ async def process_chat_payload(request, form_data, user, metadata, model):
|
||||
tools_dict = {}
|
||||
|
||||
if tool_ids:
|
||||
tools_dict = get_tools(
|
||||
tools_dict = await get_tools(
|
||||
request,
|
||||
tool_ids,
|
||||
user,
|
||||
@@ -989,25 +1020,24 @@ async def process_chat_payload(request, form_data, user, metadata, model):
|
||||
if prompt is None:
|
||||
raise Exception("No user message found")
|
||||
|
||||
if context_string == "":
|
||||
if request.app.state.config.RELEVANCE_THRESHOLD == 0:
|
||||
log.debug(
|
||||
f"With a 0 relevancy threshold for RAG, the context cannot be empty"
|
||||
)
|
||||
else:
|
||||
if context_string != "":
|
||||
# Workaround for Ollama 2.0+ system prompt issue
|
||||
# TODO: replace with add_or_update_system_message
|
||||
if model.get("owned_by") == "ollama":
|
||||
form_data["messages"] = prepend_to_first_user_message_content(
|
||||
rag_template(
|
||||
request.app.state.config.RAG_TEMPLATE, context_string, prompt
|
||||
request.app.state.config.RAG_TEMPLATE,
|
||||
context_string,
|
||||
prompt,
|
||||
),
|
||||
form_data["messages"],
|
||||
)
|
||||
else:
|
||||
form_data["messages"] = add_or_update_system_message(
|
||||
rag_template(
|
||||
request.app.state.config.RAG_TEMPLATE, context_string, prompt
|
||||
request.app.state.config.RAG_TEMPLATE,
|
||||
context_string,
|
||||
prompt,
|
||||
),
|
||||
form_data["messages"],
|
||||
)
|
||||
@@ -1254,91 +1284,118 @@ async def process_chat_response(
|
||||
# Non-streaming response
|
||||
if not isinstance(response, StreamingResponse):
|
||||
if event_emitter:
|
||||
if "error" in response:
|
||||
error = response["error"].get("detail", response["error"])
|
||||
Chats.upsert_message_to_chat_by_id_and_message_id(
|
||||
metadata["chat_id"],
|
||||
metadata["message_id"],
|
||||
{
|
||||
"error": {"content": error},
|
||||
},
|
||||
)
|
||||
if isinstance(response, dict) or isinstance(response, JSONResponse):
|
||||
|
||||
if "selected_model_id" in response:
|
||||
Chats.upsert_message_to_chat_by_id_and_message_id(
|
||||
metadata["chat_id"],
|
||||
metadata["message_id"],
|
||||
{
|
||||
"selectedModelId": response["selected_model_id"],
|
||||
},
|
||||
)
|
||||
if isinstance(response, JSONResponse) and isinstance(
|
||||
response.body, bytes
|
||||
):
|
||||
try:
|
||||
response_data = json.loads(response.body.decode("utf-8"))
|
||||
except json.JSONDecodeError:
|
||||
response_data = {"error": {"detail": "Invalid JSON response"}}
|
||||
else:
|
||||
response_data = response
|
||||
|
||||
choices = response.get("choices", [])
|
||||
if choices and choices[0].get("message", {}).get("content"):
|
||||
content = response["choices"][0]["message"]["content"]
|
||||
|
||||
if content:
|
||||
|
||||
await event_emitter(
|
||||
{
|
||||
"type": "chat:completion",
|
||||
"data": response,
|
||||
}
|
||||
)
|
||||
|
||||
title = Chats.get_chat_title_by_id(metadata["chat_id"])
|
||||
|
||||
await event_emitter(
|
||||
{
|
||||
"type": "chat:completion",
|
||||
"data": {
|
||||
"done": True,
|
||||
"content": content,
|
||||
"title": title,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
# Save message in the database
|
||||
if "error" in response_data:
|
||||
error = response_data["error"].get("detail", response_data["error"])
|
||||
Chats.upsert_message_to_chat_by_id_and_message_id(
|
||||
metadata["chat_id"],
|
||||
metadata["message_id"],
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": content,
|
||||
"error": {"content": error},
|
||||
},
|
||||
)
|
||||
if isinstance(error, str) or isinstance(error, dict):
|
||||
await event_emitter(
|
||||
{
|
||||
"type": "chat:message:error",
|
||||
"data": {"error": {"content": error}},
|
||||
},
|
||||
)
|
||||
|
||||
if "selected_model_id" in response_data:
|
||||
Chats.upsert_message_to_chat_by_id_and_message_id(
|
||||
metadata["chat_id"],
|
||||
metadata["message_id"],
|
||||
{
|
||||
"selectedModelId": response_data["selected_model_id"],
|
||||
},
|
||||
)
|
||||
|
||||
# Send a webhook notification if the user is not active
|
||||
if not get_active_status_by_user_id(user.id):
|
||||
webhook_url = Users.get_user_webhook_url_by_id(user.id)
|
||||
if webhook_url:
|
||||
post_webhook(
|
||||
request.app.state.WEBUI_NAME,
|
||||
webhook_url,
|
||||
f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
|
||||
{
|
||||
"action": "chat",
|
||||
"message": content,
|
||||
choices = response_data.get("choices", [])
|
||||
if choices and choices[0].get("message", {}).get("content"):
|
||||
content = response_data["choices"][0]["message"]["content"]
|
||||
|
||||
if content:
|
||||
await event_emitter(
|
||||
{
|
||||
"type": "chat:completion",
|
||||
"data": response_data,
|
||||
}
|
||||
)
|
||||
|
||||
title = Chats.get_chat_title_by_id(metadata["chat_id"])
|
||||
|
||||
await event_emitter(
|
||||
{
|
||||
"type": "chat:completion",
|
||||
"data": {
|
||||
"done": True,
|
||||
"content": content,
|
||||
"title": title,
|
||||
"url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
|
||||
},
|
||||
)
|
||||
}
|
||||
)
|
||||
|
||||
await background_tasks_handler()
|
||||
# Save message in the database
|
||||
Chats.upsert_message_to_chat_by_id_and_message_id(
|
||||
metadata["chat_id"],
|
||||
metadata["message_id"],
|
||||
{
|
||||
"role": "assistant",
|
||||
"content": content,
|
||||
},
|
||||
)
|
||||
|
||||
if events and isinstance(events, list) and isinstance(response, dict):
|
||||
extra_response = {}
|
||||
for event in events:
|
||||
if isinstance(event, dict):
|
||||
extra_response.update(event)
|
||||
else:
|
||||
extra_response[event] = True
|
||||
# Send a webhook notification if the user is not active
|
||||
if not get_active_status_by_user_id(user.id):
|
||||
webhook_url = Users.get_user_webhook_url_by_id(user.id)
|
||||
if webhook_url:
|
||||
await post_webhook(
|
||||
request.app.state.WEBUI_NAME,
|
||||
webhook_url,
|
||||
f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
|
||||
{
|
||||
"action": "chat",
|
||||
"message": content,
|
||||
"title": title,
|
||||
"url": f"{request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}",
|
||||
},
|
||||
)
|
||||
|
||||
response = {
|
||||
**extra_response,
|
||||
**response,
|
||||
}
|
||||
await background_tasks_handler()
|
||||
|
||||
if events and isinstance(events, list):
|
||||
extra_response = {}
|
||||
for event in events:
|
||||
if isinstance(event, dict):
|
||||
extra_response.update(event)
|
||||
else:
|
||||
extra_response[event] = True
|
||||
|
||||
response_data = {
|
||||
**extra_response,
|
||||
**response_data,
|
||||
}
|
||||
|
||||
if isinstance(response, dict):
|
||||
response = response_data
|
||||
if isinstance(response, JSONResponse):
|
||||
response = JSONResponse(
|
||||
content=response_data,
|
||||
headers=response.headers,
|
||||
status_code=response.status_code,
|
||||
)
|
||||
|
||||
return response
|
||||
else:
|
||||
@@ -1600,9 +1657,13 @@ async def process_chat_response(
|
||||
|
||||
match = re.search(start_tag_pattern, content)
|
||||
if match:
|
||||
attr_content = (
|
||||
match.group(1) if match.group(1) else ""
|
||||
) # Ensure it's not None
|
||||
try:
|
||||
attr_content = (
|
||||
match.group(1) if match.group(1) else ""
|
||||
) # Ensure it's not None
|
||||
except:
|
||||
attr_content = ""
|
||||
|
||||
attributes = extract_attributes(
|
||||
attr_content
|
||||
) # Extract attributes safely
|
||||
@@ -1772,27 +1833,23 @@ async def process_chat_response(
|
||||
}
|
||||
]
|
||||
|
||||
# We might want to disable this by default
|
||||
DETECT_REASONING = True
|
||||
DETECT_SOLUTION = True
|
||||
reasoning_tags_param = metadata.get("params", {}).get("reasoning_tags")
|
||||
DETECT_REASONING_TAGS = reasoning_tags_param is not False
|
||||
DETECT_CODE_INTERPRETER = metadata.get("features", {}).get(
|
||||
"code_interpreter", False
|
||||
)
|
||||
|
||||
reasoning_tags = [
|
||||
("<think>", "</think>"),
|
||||
("<thinking>", "</thinking>"),
|
||||
("<reason>", "</reason>"),
|
||||
("<reasoning>", "</reasoning>"),
|
||||
("<thought>", "</thought>"),
|
||||
("<Thought>", "</Thought>"),
|
||||
("<|begin_of_thought|>", "<|end_of_thought|>"),
|
||||
("◁think▷", "◁/think▷"),
|
||||
]
|
||||
|
||||
code_interpreter_tags = [("<code_interpreter>", "</code_interpreter>")]
|
||||
|
||||
solution_tags = [("<|begin_of_solution|>", "<|end_of_solution|>")]
|
||||
reasoning_tags = []
|
||||
if DETECT_REASONING_TAGS:
|
||||
if (
|
||||
isinstance(reasoning_tags_param, list)
|
||||
and len(reasoning_tags_param) == 2
|
||||
):
|
||||
reasoning_tags = [
|
||||
(reasoning_tags_param[0], reasoning_tags_param[1])
|
||||
]
|
||||
else:
|
||||
reasoning_tags = DEFAULT_REASONING_TAGS
|
||||
|
||||
try:
|
||||
for event in events:
|
||||
@@ -1826,6 +1883,21 @@ async def process_chat_response(
|
||||
or 1
|
||||
),
|
||||
)
|
||||
last_delta_data = None
|
||||
|
||||
async def flush_pending_delta_data(threshold: int = 0):
|
||||
nonlocal delta_count
|
||||
nonlocal last_delta_data
|
||||
|
||||
if delta_count >= threshold and last_delta_data:
|
||||
await event_emitter(
|
||||
{
|
||||
"type": "chat:completion",
|
||||
"data": last_delta_data,
|
||||
}
|
||||
)
|
||||
delta_count = 0
|
||||
last_delta_data = None
|
||||
|
||||
async for line in response.body_iterator:
|
||||
line = line.decode("utf-8") if isinstance(line, bytes) else line
|
||||
@@ -1866,6 +1938,12 @@ async def process_chat_response(
|
||||
"selectedModelId": model_id,
|
||||
},
|
||||
)
|
||||
await event_emitter(
|
||||
{
|
||||
"type": "chat:completion",
|
||||
"data": data,
|
||||
}
|
||||
)
|
||||
else:
|
||||
choices = data.get("choices", [])
|
||||
if not choices:
|
||||
@@ -2023,7 +2101,7 @@ async def process_chat_response(
|
||||
content_blocks[-1]["content"] + value
|
||||
)
|
||||
|
||||
if DETECT_REASONING:
|
||||
if DETECT_REASONING_TAGS:
|
||||
content, content_blocks, _ = (
|
||||
tag_content_handler(
|
||||
"reasoning",
|
||||
@@ -2033,11 +2111,20 @@ async def process_chat_response(
|
||||
)
|
||||
)
|
||||
|
||||
content, content_blocks, _ = (
|
||||
tag_content_handler(
|
||||
"solution",
|
||||
DEFAULT_SOLUTION_TAGS,
|
||||
content,
|
||||
content_blocks,
|
||||
)
|
||||
)
|
||||
|
||||
if DETECT_CODE_INTERPRETER:
|
||||
content, content_blocks, end = (
|
||||
tag_content_handler(
|
||||
"code_interpreter",
|
||||
code_interpreter_tags,
|
||||
DEFAULT_CODE_INTERPRETER_TAGS,
|
||||
content,
|
||||
content_blocks,
|
||||
)
|
||||
@@ -2046,16 +2133,6 @@ async def process_chat_response(
|
||||
if end:
|
||||
break
|
||||
|
||||
if DETECT_SOLUTION:
|
||||
content, content_blocks, _ = (
|
||||
tag_content_handler(
|
||||
"solution",
|
||||
solution_tags,
|
||||
content,
|
||||
content_blocks,
|
||||
)
|
||||
)
|
||||
|
||||
if ENABLE_REALTIME_CHAT_SAVE:
|
||||
# Save message in the database
|
||||
Chats.upsert_message_to_chat_by_id_and_message_id(
|
||||
@@ -2076,14 +2153,9 @@ async def process_chat_response(
|
||||
|
||||
if delta:
|
||||
delta_count += 1
|
||||
last_delta_data = data
|
||||
if delta_count >= delta_chunk_size:
|
||||
await event_emitter(
|
||||
{
|
||||
"type": "chat:completion",
|
||||
"data": data,
|
||||
}
|
||||
)
|
||||
delta_count = 0
|
||||
await flush_pending_delta_data(delta_chunk_size)
|
||||
else:
|
||||
await event_emitter(
|
||||
{
|
||||
@@ -2098,6 +2170,7 @@ async def process_chat_response(
|
||||
else:
|
||||
log.debug(f"Error: {e}")
|
||||
continue
|
||||
await flush_pending_delta_data()
|
||||
|
||||
if content_blocks:
|
||||
# Clean up the last text block
|
||||
@@ -2134,10 +2207,12 @@ async def process_chat_response(
|
||||
|
||||
await stream_body_handler(response, form_data)
|
||||
|
||||
MAX_TOOL_CALL_RETRIES = 10
|
||||
tool_call_retries = 0
|
||||
|
||||
while len(tool_calls) > 0 and tool_call_retries < MAX_TOOL_CALL_RETRIES:
|
||||
while (
|
||||
len(tool_calls) > 0
|
||||
and tool_call_retries < CHAT_RESPONSE_MAX_TOOL_CALL_RETRIES
|
||||
):
|
||||
|
||||
tool_call_retries += 1
|
||||
|
||||
@@ -2335,6 +2410,27 @@ async def process_chat_response(
|
||||
try:
|
||||
if content_blocks[-1]["attributes"].get("type") == "code":
|
||||
code = content_blocks[-1]["content"]
|
||||
if CODE_INTERPRETER_BLOCKED_MODULES:
|
||||
blocking_code = textwrap.dedent(
|
||||
f"""
|
||||
import builtins
|
||||
|
||||
BLOCKED_MODULES = {CODE_INTERPRETER_BLOCKED_MODULES}
|
||||
|
||||
_real_import = builtins.__import__
|
||||
def restricted_import(name, globals=None, locals=None, fromlist=(), level=0):
|
||||
if name.split('.')[0] in BLOCKED_MODULES:
|
||||
importer_name = globals.get('__name__') if globals else None
|
||||
if importer_name == '__main__':
|
||||
raise ImportError(
|
||||
f"Direct import of module {{name}} is restricted."
|
||||
)
|
||||
return _real_import(name, globals, locals, fromlist, level)
|
||||
|
||||
builtins.__import__ = restricted_import
|
||||
"""
|
||||
)
|
||||
code = blocking_code + "\n" + code
|
||||
|
||||
if (
|
||||
request.app.state.config.CODE_INTERPRETER_ENGINE
|
||||
@@ -2500,7 +2596,7 @@ async def process_chat_response(
|
||||
if not get_active_status_by_user_id(user.id):
|
||||
webhook_url = Users.get_user_webhook_url_by_id(user.id)
|
||||
if webhook_url:
|
||||
post_webhook(
|
||||
await post_webhook(
|
||||
request.app.state.WEBUI_NAME,
|
||||
webhook_url,
|
||||
f"{title} - {request.app.state.config.WEBUI_URL}/c/{metadata['chat_id']}\n\n{content}",
|
||||
@@ -2537,13 +2633,7 @@ async def process_chat_response(
|
||||
if response.background is not None:
|
||||
await response.background()
|
||||
|
||||
# background_tasks.add_task(response_handler, response, events)
|
||||
task_id, _ = await create_task(
|
||||
request.app.state.redis,
|
||||
response_handler(response, events),
|
||||
id=metadata["chat_id"],
|
||||
)
|
||||
return {"status": True, "task_id": task_id}
|
||||
return await response_handler(response, events)
|
||||
|
||||
else:
|
||||
# Fallback to the original response
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import hashlib
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
import logging
|
||||
@@ -478,3 +479,46 @@ def convert_logit_bias_input_to_json(user_input):
|
||||
bias = 100 if bias > 100 else -100 if bias < -100 else bias
|
||||
logit_bias_json[token] = bias
|
||||
return json.dumps(logit_bias_json)
|
||||
|
||||
|
||||
def freeze(value):
|
||||
"""
|
||||
Freeze a value to make it hashable.
|
||||
"""
|
||||
if isinstance(value, dict):
|
||||
return frozenset((k, freeze(v)) for k, v in value.items())
|
||||
elif isinstance(value, list):
|
||||
return tuple(freeze(v) for v in value)
|
||||
return value
|
||||
|
||||
|
||||
def throttle(interval: float = 10.0):
|
||||
"""
|
||||
Decorator to prevent a function from being called more than once within a specified duration.
|
||||
If the function is called again within the duration, it returns None. To avoid returning
|
||||
different types, the return type of the function should be Optional[T].
|
||||
|
||||
:param interval: Duration in seconds to wait before allowing the function to be called again.
|
||||
"""
|
||||
|
||||
def decorator(func):
|
||||
last_calls = {}
|
||||
lock = threading.Lock()
|
||||
|
||||
def wrapper(*args, **kwargs):
|
||||
if interval is None:
|
||||
return func(*args, **kwargs)
|
||||
|
||||
key = (args, freeze(kwargs))
|
||||
now = time.time()
|
||||
if now - last_calls.get(key, 0) < interval:
|
||||
return None
|
||||
with lock:
|
||||
if now - last_calls.get(key, 0) < interval:
|
||||
return None
|
||||
last_calls[key] = now
|
||||
return func(*args, **kwargs)
|
||||
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
|
||||
@@ -115,7 +115,13 @@ class OAuthManager:
|
||||
nested_claims = oauth_claim.split(".")
|
||||
for nested_claim in nested_claims:
|
||||
claim_data = claim_data.get(nested_claim, {})
|
||||
oauth_roles = claim_data if isinstance(claim_data, list) else []
|
||||
|
||||
oauth_roles = []
|
||||
|
||||
if isinstance(claim_data, list):
|
||||
oauth_roles = claim_data
|
||||
if isinstance(claim_data, str) or isinstance(claim_data, int):
|
||||
oauth_roles = [str(claim_data)]
|
||||
|
||||
log.debug(f"Oauth Roles claim: {oauth_claim}")
|
||||
log.debug(f"User roles from oauth: {oauth_roles}")
|
||||
@@ -355,7 +361,11 @@ class OAuthManager:
|
||||
log.warning(f"OAuth callback error: {e}")
|
||||
raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_CRED)
|
||||
user_data: UserInfo = token.get("userinfo")
|
||||
if not user_data or auth_manager_config.OAUTH_EMAIL_CLAIM not in user_data:
|
||||
if (
|
||||
(not user_data)
|
||||
or (auth_manager_config.OAUTH_EMAIL_CLAIM not in user_data)
|
||||
or (auth_manager_config.OAUTH_USERNAME_CLAIM not in user_data)
|
||||
):
|
||||
user_data: UserInfo = await client.userinfo(token=token)
|
||||
if not user_data:
|
||||
log.warning(f"OAuth callback failed, user data is missing: {token}")
|
||||
@@ -498,7 +508,7 @@ class OAuthManager:
|
||||
)
|
||||
|
||||
if auth_manager_config.WEBHOOK_URL:
|
||||
post_webhook(
|
||||
await post_webhook(
|
||||
WEBUI_NAME,
|
||||
auth_manager_config.WEBHOOK_URL,
|
||||
WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
|
||||
@@ -525,7 +535,15 @@ class OAuthManager:
|
||||
default_permissions=request.app.state.config.USER_PERMISSIONS,
|
||||
)
|
||||
|
||||
redirect_base_url = str(request.app.state.config.WEBUI_URL or request.base_url)
|
||||
if redirect_base_url.endswith("/"):
|
||||
redirect_base_url = redirect_base_url[:-1]
|
||||
redirect_url = f"{redirect_base_url}/auth"
|
||||
|
||||
response = RedirectResponse(url=redirect_url, headers=response.headers)
|
||||
|
||||
# Set the cookie token
|
||||
# Redirect back to the frontend with the JWT token
|
||||
response.set_cookie(
|
||||
key="token",
|
||||
value=jwt_token,
|
||||
@@ -543,11 +561,4 @@ class OAuthManager:
|
||||
samesite=WEBUI_AUTH_COOKIE_SAME_SITE,
|
||||
secure=WEBUI_AUTH_COOKIE_SECURE,
|
||||
)
|
||||
# Redirect back to the frontend with the JWT token
|
||||
|
||||
redirect_base_url = str(request.app.state.config.WEBUI_URL or request.base_url)
|
||||
if redirect_base_url.endswith("/"):
|
||||
redirect_base_url = redirect_base_url[:-1]
|
||||
redirect_url = f"{redirect_base_url}/auth"
|
||||
|
||||
return RedirectResponse(url=redirect_url, headers=response.headers)
|
||||
return response
|
||||
|
||||
@@ -9,7 +9,7 @@ import json
|
||||
|
||||
|
||||
# inplace function: form_data is modified
|
||||
def apply_model_system_prompt_to_body(
|
||||
def apply_system_prompt_to_body(
|
||||
system: Optional[str], form_data: dict, metadata: Optional[dict] = None, user=None
|
||||
) -> dict:
|
||||
if not system:
|
||||
@@ -22,15 +22,7 @@ def apply_model_system_prompt_to_body(
|
||||
system = prompt_variables_template(system, variables)
|
||||
|
||||
# Legacy (API Usage)
|
||||
if user:
|
||||
template_params = {
|
||||
"user_name": user.name,
|
||||
"user_location": user.info.get("location") if user.info else None,
|
||||
}
|
||||
else:
|
||||
template_params = {}
|
||||
|
||||
system = prompt_template(system, **template_params)
|
||||
system = prompt_template(system, user)
|
||||
|
||||
form_data["messages"] = add_or_update_system_message(
|
||||
system, form_data.get("messages", [])
|
||||
@@ -71,6 +63,7 @@ def remove_open_webui_params(params: dict) -> dict:
|
||||
"stream_response": bool,
|
||||
"stream_delta_chunk_size": int,
|
||||
"function_calling": str,
|
||||
"reasoning_tags": list,
|
||||
"system": str,
|
||||
}
|
||||
|
||||
|
||||
@@ -260,7 +260,7 @@ def install_tool_and_function_dependencies():
|
||||
all_dependencies += f"{dependencies}, "
|
||||
for tool in tool_list:
|
||||
# Only install requirements for admin tools
|
||||
if tool.user.role == "admin":
|
||||
if tool.user and tool.user.role == "admin":
|
||||
frontmatter = extract_frontmatter(replace_imports(tool.content))
|
||||
if dependencies := frontmatter.get("requirements"):
|
||||
all_dependencies += f"{dependencies}, "
|
||||
|
||||
@@ -2,7 +2,7 @@ import logging
|
||||
import math
|
||||
import re
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
from typing import Optional, Any
|
||||
import uuid
|
||||
|
||||
|
||||
@@ -38,9 +38,46 @@ def prompt_variables_template(template: str, variables: dict[str, str]) -> str:
|
||||
return template
|
||||
|
||||
|
||||
def prompt_template(
|
||||
template: str, user_name: Optional[str] = None, user_location: Optional[str] = None
|
||||
) -> str:
|
||||
def prompt_template(template: str, user: Optional[Any] = None) -> str:
|
||||
|
||||
USER_VARIABLES = {}
|
||||
|
||||
if user:
|
||||
if hasattr(user, "model_dump"):
|
||||
user = user.model_dump()
|
||||
|
||||
if isinstance(user, dict):
|
||||
user_info = user.get("info", {}) or {}
|
||||
birth_date = user.get("date_of_birth")
|
||||
age = None
|
||||
|
||||
if birth_date:
|
||||
try:
|
||||
# If birth_date is str, convert to datetime
|
||||
if isinstance(birth_date, str):
|
||||
birth_date = datetime.strptime(birth_date, "%Y-%m-%d")
|
||||
|
||||
today = datetime.now()
|
||||
age = (
|
||||
today.year
|
||||
- birth_date.year
|
||||
- (
|
||||
(today.month, today.day)
|
||||
< (birth_date.month, birth_date.day)
|
||||
)
|
||||
)
|
||||
except Exception as e:
|
||||
pass
|
||||
|
||||
USER_VARIABLES = {
|
||||
"name": str(user.get("name")),
|
||||
"location": str(user_info.get("location")),
|
||||
"bio": str(user.get("bio")),
|
||||
"gender": str(user.get("gender")),
|
||||
"birth_date": str(birth_date),
|
||||
"age": str(age),
|
||||
}
|
||||
|
||||
# Get the current date
|
||||
current_date = datetime.now()
|
||||
|
||||
@@ -56,19 +93,20 @@ def prompt_template(
|
||||
)
|
||||
template = template.replace("{{CURRENT_WEEKDAY}}", formatted_weekday)
|
||||
|
||||
if user_name:
|
||||
# Replace {{USER_NAME}} in the template with the user's name
|
||||
template = template.replace("{{USER_NAME}}", user_name)
|
||||
else:
|
||||
# Replace {{USER_NAME}} in the template with "Unknown"
|
||||
template = template.replace("{{USER_NAME}}", "Unknown")
|
||||
|
||||
if user_location:
|
||||
# Replace {{USER_LOCATION}} in the template with the current location
|
||||
template = template.replace("{{USER_LOCATION}}", user_location)
|
||||
else:
|
||||
# Replace {{USER_LOCATION}} in the template with "Unknown"
|
||||
template = template.replace("{{USER_LOCATION}}", "Unknown")
|
||||
template = template.replace("{{USER_NAME}}", USER_VARIABLES.get("name", "Unknown"))
|
||||
template = template.replace("{{USER_BIO}}", USER_VARIABLES.get("bio", "Unknown"))
|
||||
template = template.replace(
|
||||
"{{USER_GENDER}}", USER_VARIABLES.get("gender", "Unknown")
|
||||
)
|
||||
template = template.replace(
|
||||
"{{USER_BIRTH_DATE}}", USER_VARIABLES.get("birth_date", "Unknown")
|
||||
)
|
||||
template = template.replace(
|
||||
"{{USER_AGE}}", str(USER_VARIABLES.get("age", "Unknown"))
|
||||
)
|
||||
template = template.replace(
|
||||
"{{USER_LOCATION}}", USER_VARIABLES.get("location", "Unknown")
|
||||
)
|
||||
|
||||
return template
|
||||
|
||||
@@ -189,90 +227,56 @@ def rag_template(template: str, context: str, query: str):
|
||||
|
||||
|
||||
def title_generation_template(
|
||||
template: str, messages: list[dict], user: Optional[dict] = None
|
||||
template: str, messages: list[dict], user: Optional[Any] = None
|
||||
) -> str:
|
||||
|
||||
prompt = get_last_user_message(messages)
|
||||
template = replace_prompt_variable(template, prompt)
|
||||
template = replace_messages_variable(template, messages)
|
||||
|
||||
template = prompt_template(
|
||||
template,
|
||||
**(
|
||||
{"user_name": user.get("name"), "user_location": user.get("location")}
|
||||
if user
|
||||
else {}
|
||||
),
|
||||
)
|
||||
template = prompt_template(template, user)
|
||||
|
||||
return template
|
||||
|
||||
|
||||
def follow_up_generation_template(
|
||||
template: str, messages: list[dict], user: Optional[dict] = None
|
||||
template: str, messages: list[dict], user: Optional[Any] = None
|
||||
) -> str:
|
||||
prompt = get_last_user_message(messages)
|
||||
template = replace_prompt_variable(template, prompt)
|
||||
template = replace_messages_variable(template, messages)
|
||||
|
||||
template = prompt_template(
|
||||
template,
|
||||
**(
|
||||
{"user_name": user.get("name"), "user_location": user.get("location")}
|
||||
if user
|
||||
else {}
|
||||
),
|
||||
)
|
||||
template = prompt_template(template, user)
|
||||
return template
|
||||
|
||||
|
||||
def tags_generation_template(
|
||||
template: str, messages: list[dict], user: Optional[dict] = None
|
||||
template: str, messages: list[dict], user: Optional[Any] = None
|
||||
) -> str:
|
||||
prompt = get_last_user_message(messages)
|
||||
template = replace_prompt_variable(template, prompt)
|
||||
template = replace_messages_variable(template, messages)
|
||||
|
||||
template = prompt_template(
|
||||
template,
|
||||
**(
|
||||
{"user_name": user.get("name"), "user_location": user.get("location")}
|
||||
if user
|
||||
else {}
|
||||
),
|
||||
)
|
||||
template = prompt_template(template, user)
|
||||
return template
|
||||
|
||||
|
||||
def image_prompt_generation_template(
|
||||
template: str, messages: list[dict], user: Optional[dict] = None
|
||||
template: str, messages: list[dict], user: Optional[Any] = None
|
||||
) -> str:
|
||||
prompt = get_last_user_message(messages)
|
||||
template = replace_prompt_variable(template, prompt)
|
||||
template = replace_messages_variable(template, messages)
|
||||
|
||||
template = prompt_template(
|
||||
template,
|
||||
**(
|
||||
{"user_name": user.get("name"), "user_location": user.get("location")}
|
||||
if user
|
||||
else {}
|
||||
),
|
||||
)
|
||||
template = prompt_template(template, user)
|
||||
return template
|
||||
|
||||
|
||||
def emoji_generation_template(
|
||||
template: str, prompt: str, user: Optional[dict] = None
|
||||
template: str, prompt: str, user: Optional[Any] = None
|
||||
) -> str:
|
||||
template = replace_prompt_variable(template, prompt)
|
||||
template = prompt_template(
|
||||
template,
|
||||
**(
|
||||
{"user_name": user.get("name"), "user_location": user.get("location")}
|
||||
if user
|
||||
else {}
|
||||
),
|
||||
)
|
||||
template = prompt_template(template, user)
|
||||
|
||||
return template
|
||||
|
||||
@@ -282,38 +286,24 @@ def autocomplete_generation_template(
|
||||
prompt: str,
|
||||
messages: Optional[list[dict]] = None,
|
||||
type: Optional[str] = None,
|
||||
user: Optional[dict] = None,
|
||||
user: Optional[Any] = None,
|
||||
) -> str:
|
||||
template = template.replace("{{TYPE}}", type if type else "")
|
||||
template = replace_prompt_variable(template, prompt)
|
||||
template = replace_messages_variable(template, messages)
|
||||
|
||||
template = prompt_template(
|
||||
template,
|
||||
**(
|
||||
{"user_name": user.get("name"), "user_location": user.get("location")}
|
||||
if user
|
||||
else {}
|
||||
),
|
||||
)
|
||||
template = prompt_template(template, user)
|
||||
return template
|
||||
|
||||
|
||||
def query_generation_template(
|
||||
template: str, messages: list[dict], user: Optional[dict] = None
|
||||
template: str, messages: list[dict], user: Optional[Any] = None
|
||||
) -> str:
|
||||
prompt = get_last_user_message(messages)
|
||||
template = replace_prompt_variable(template, prompt)
|
||||
template = replace_messages_variable(template, messages)
|
||||
|
||||
template = prompt_template(
|
||||
template,
|
||||
**(
|
||||
{"user_name": user.get("name"), "user_location": user.get("location")}
|
||||
if user
|
||||
else {}
|
||||
),
|
||||
)
|
||||
template = prompt_template(template, user)
|
||||
return template
|
||||
|
||||
|
||||
|
||||
@@ -17,6 +17,7 @@ from open_webui.env import (
|
||||
OTEL_SERVICE_NAME,
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT,
|
||||
OTEL_EXPORTER_OTLP_INSECURE,
|
||||
ENABLE_OTEL_TRACES,
|
||||
ENABLE_OTEL_METRICS,
|
||||
OTEL_BASIC_AUTH_USERNAME,
|
||||
OTEL_BASIC_AUTH_PASSWORD,
|
||||
@@ -27,29 +28,30 @@ from open_webui.env import (
|
||||
def setup(app: FastAPI, db_engine: Engine):
|
||||
# set up trace
|
||||
resource = Resource.create(attributes={SERVICE_NAME: OTEL_SERVICE_NAME})
|
||||
trace.set_tracer_provider(TracerProvider(resource=resource))
|
||||
if ENABLE_OTEL_TRACES:
|
||||
trace.set_tracer_provider(TracerProvider(resource=resource))
|
||||
|
||||
# Add basic auth header only if both username and password are not empty
|
||||
headers = []
|
||||
if OTEL_BASIC_AUTH_USERNAME and OTEL_BASIC_AUTH_PASSWORD:
|
||||
auth_string = f"{OTEL_BASIC_AUTH_USERNAME}:{OTEL_BASIC_AUTH_PASSWORD}"
|
||||
auth_header = b64encode(auth_string.encode()).decode()
|
||||
headers = [("authorization", f"Basic {auth_header}")]
|
||||
# Add basic auth header only if both username and password are not empty
|
||||
headers = []
|
||||
if OTEL_BASIC_AUTH_USERNAME and OTEL_BASIC_AUTH_PASSWORD:
|
||||
auth_string = f"{OTEL_BASIC_AUTH_USERNAME}:{OTEL_BASIC_AUTH_PASSWORD}"
|
||||
auth_header = b64encode(auth_string.encode()).decode()
|
||||
headers = [("authorization", f"Basic {auth_header}")]
|
||||
|
||||
# otlp export
|
||||
if OTEL_OTLP_SPAN_EXPORTER == "http":
|
||||
exporter = HttpOTLPSpanExporter(
|
||||
endpoint=OTEL_EXPORTER_OTLP_ENDPOINT,
|
||||
headers=headers,
|
||||
)
|
||||
else:
|
||||
exporter = OTLPSpanExporter(
|
||||
endpoint=OTEL_EXPORTER_OTLP_ENDPOINT,
|
||||
insecure=OTEL_EXPORTER_OTLP_INSECURE,
|
||||
headers=headers,
|
||||
)
|
||||
trace.get_tracer_provider().add_span_processor(BatchSpanProcessor(exporter))
|
||||
Instrumentor(app=app, db_engine=db_engine).instrument()
|
||||
# otlp export
|
||||
if OTEL_OTLP_SPAN_EXPORTER == "http":
|
||||
exporter = HttpOTLPSpanExporter(
|
||||
endpoint=OTEL_EXPORTER_OTLP_ENDPOINT,
|
||||
headers=headers,
|
||||
)
|
||||
else:
|
||||
exporter = OTLPSpanExporter(
|
||||
endpoint=OTEL_EXPORTER_OTLP_ENDPOINT,
|
||||
insecure=OTEL_EXPORTER_OTLP_INSECURE,
|
||||
headers=headers,
|
||||
)
|
||||
trace.get_tracer_provider().add_span_processor(BatchSpanProcessor(exporter))
|
||||
Instrumentor(app=app, db_engine=db_engine).instrument()
|
||||
|
||||
# set up metrics only if enabled
|
||||
if ENABLE_OTEL_METRICS:
|
||||
|
||||
@@ -5,6 +5,7 @@ import inspect
|
||||
import aiohttp
|
||||
import asyncio
|
||||
import yaml
|
||||
import json
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic.fields import FieldInfo
|
||||
@@ -38,6 +39,7 @@ from open_webui.models.users import UserModel
|
||||
from open_webui.utils.plugin import load_tool_module_by_id
|
||||
from open_webui.env import (
|
||||
SRC_LOG_LEVELS,
|
||||
AIOHTTP_CLIENT_TIMEOUT,
|
||||
AIOHTTP_CLIENT_TIMEOUT_TOOL_SERVER_DATA,
|
||||
AIOHTTP_CLIENT_SESSION_TOOL_SERVER_SSL,
|
||||
)
|
||||
@@ -55,19 +57,38 @@ def get_async_tool_function_and_apply_extra_params(
|
||||
extra_params = {k: v for k, v in extra_params.items() if k in sig.parameters}
|
||||
partial_func = partial(function, **extra_params)
|
||||
|
||||
# Remove the 'frozen' keyword arguments from the signature
|
||||
# python-genai uses the signature to infer the tool properties for native function calling
|
||||
parameters = []
|
||||
for name, parameter in sig.parameters.items():
|
||||
# Exclude keyword arguments that are frozen
|
||||
if name in extra_params:
|
||||
continue
|
||||
# Keep remaining parameters
|
||||
parameters.append(parameter)
|
||||
|
||||
new_sig = inspect.Signature(
|
||||
parameters=parameters, return_annotation=sig.return_annotation
|
||||
)
|
||||
|
||||
if inspect.iscoroutinefunction(function):
|
||||
update_wrapper(partial_func, function)
|
||||
return partial_func
|
||||
# wrap the functools.partial as python-genai has trouble with it
|
||||
# https://github.com/googleapis/python-genai/issues/907
|
||||
async def new_function(*args, **kwargs):
|
||||
return await partial_func(*args, **kwargs)
|
||||
|
||||
else:
|
||||
# Make it a coroutine function
|
||||
# Make it a coroutine function when it is not already
|
||||
async def new_function(*args, **kwargs):
|
||||
return partial_func(*args, **kwargs)
|
||||
|
||||
update_wrapper(new_function, function)
|
||||
return new_function
|
||||
update_wrapper(new_function, function)
|
||||
new_function.__signature__ = new_sig
|
||||
|
||||
return new_function
|
||||
|
||||
|
||||
def get_tools(
|
||||
async def get_tools(
|
||||
request: Request, tool_ids: list[str], user: UserModel, extra_params: dict
|
||||
) -> dict[str, dict]:
|
||||
tools_dict = {}
|
||||
@@ -76,18 +97,24 @@ def get_tools(
|
||||
tool = Tools.get_tool_by_id(tool_id)
|
||||
if tool is None:
|
||||
if tool_id.startswith("server:"):
|
||||
server_idx = int(tool_id.split(":")[1])
|
||||
tool_server_connection = (
|
||||
request.app.state.config.TOOL_SERVER_CONNECTIONS[server_idx]
|
||||
)
|
||||
server_id = tool_id.split(":")[1]
|
||||
|
||||
tool_server_data = None
|
||||
for server in request.app.state.TOOL_SERVERS:
|
||||
if server["idx"] == server_idx:
|
||||
for server in await get_tool_servers(request):
|
||||
if server["id"] == server_id:
|
||||
tool_server_data = server
|
||||
break
|
||||
assert tool_server_data is not None
|
||||
specs = tool_server_data.get("specs", [])
|
||||
|
||||
if tool_server_data is None:
|
||||
log.warning(f"Tool server data not found for {server_id}")
|
||||
continue
|
||||
|
||||
tool_server_idx = tool_server_data.get("idx", 0)
|
||||
tool_server_connection = (
|
||||
request.app.state.config.TOOL_SERVER_CONNECTIONS[tool_server_idx]
|
||||
)
|
||||
|
||||
specs = tool_server_data.get("specs", [])
|
||||
for spec in specs:
|
||||
function_name = spec["name"]
|
||||
|
||||
@@ -126,14 +153,15 @@ def get_tools(
|
||||
"spec": spec,
|
||||
}
|
||||
|
||||
# TODO: if collision, prepend toolkit name
|
||||
if function_name in tools_dict:
|
||||
# Handle function name collisions
|
||||
while function_name in tools_dict:
|
||||
log.warning(
|
||||
f"Tool {function_name} already exists in another tools!"
|
||||
)
|
||||
log.warning(f"Discarding {tool_id}.{function_name}")
|
||||
else:
|
||||
tools_dict[function_name] = tool_dict
|
||||
# Prepend server ID to function name
|
||||
function_name = f"{server_id}_{function_name}"
|
||||
|
||||
tools_dict[function_name] = tool_dict
|
||||
else:
|
||||
continue
|
||||
else:
|
||||
@@ -193,14 +221,15 @@ def get_tools(
|
||||
},
|
||||
}
|
||||
|
||||
# TODO: if collision, prepend toolkit name
|
||||
if function_name in tools_dict:
|
||||
# Handle function name collisions
|
||||
while function_name in tools_dict:
|
||||
log.warning(
|
||||
f"Tool {function_name} already exists in another tools!"
|
||||
)
|
||||
log.warning(f"Discarding {tool_id}.{function_name}")
|
||||
else:
|
||||
tools_dict[function_name] = tool_dict
|
||||
# Prepend tool ID to function name
|
||||
function_name = f"{tool_id}_{function_name}"
|
||||
|
||||
tools_dict[function_name] = tool_dict
|
||||
|
||||
return tools_dict
|
||||
|
||||
@@ -283,15 +312,15 @@ def convert_function_to_pydantic_model(func: Callable) -> type[BaseModel]:
|
||||
|
||||
field_defs = {}
|
||||
for name, param in parameters.items():
|
||||
|
||||
type_hint = type_hints.get(name, Any)
|
||||
default_value = param.default if param.default is not param.empty else ...
|
||||
|
||||
param_description = function_param_descriptions.get(name, None)
|
||||
|
||||
if param_description:
|
||||
field_defs[name] = type_hint, Field(
|
||||
default_value, description=param_description
|
||||
field_defs[name] = (
|
||||
type_hint,
|
||||
Field(default_value, description=param_description),
|
||||
)
|
||||
else:
|
||||
field_defs[name] = type_hint, default_value
|
||||
@@ -442,6 +471,34 @@ def convert_openapi_to_tool_payload(openapi_spec):
|
||||
return tool_payload
|
||||
|
||||
|
||||
async def set_tool_servers(request: Request):
|
||||
request.app.state.TOOL_SERVERS = await get_tool_servers_data(
|
||||
request.app.state.config.TOOL_SERVER_CONNECTIONS
|
||||
)
|
||||
|
||||
if request.app.state.redis is not None:
|
||||
await request.app.state.redis.set(
|
||||
"tool_servers", json.dumps(request.app.state.TOOL_SERVERS)
|
||||
)
|
||||
|
||||
return request.app.state.TOOL_SERVERS
|
||||
|
||||
|
||||
async def get_tool_servers(request: Request):
|
||||
tool_servers = []
|
||||
if request.app.state.redis is not None:
|
||||
try:
|
||||
tool_servers = json.loads(await request.app.state.redis.get("tool_servers"))
|
||||
request.app.state.TOOL_SERVERS = tool_servers
|
||||
except Exception as e:
|
||||
log.error(f"Error fetching tool_servers from Redis: {e}")
|
||||
|
||||
if not tool_servers:
|
||||
tool_servers = await set_tool_servers(request)
|
||||
|
||||
return tool_servers
|
||||
|
||||
|
||||
async def get_tool_server_data(token: str, url: str) -> Dict[str, Any]:
|
||||
headers = {
|
||||
"Accept": "application/json",
|
||||
@@ -505,11 +562,16 @@ async def get_tool_servers_data(
|
||||
token = server.get("key", "")
|
||||
elif auth_type == "session":
|
||||
token = session_token
|
||||
server_entries.append((idx, server, full_url, info, token))
|
||||
|
||||
id = info.get("id")
|
||||
if not id:
|
||||
id = str(idx)
|
||||
|
||||
server_entries.append((id, idx, server, full_url, info, token))
|
||||
|
||||
# Create async tasks to fetch data
|
||||
tasks = [
|
||||
get_tool_server_data(token, url) for (_, _, url, _, token) in server_entries
|
||||
get_tool_server_data(token, url) for (_, _, _, url, _, token) in server_entries
|
||||
]
|
||||
|
||||
# Execute tasks concurrently
|
||||
@@ -517,7 +579,7 @@ async def get_tool_servers_data(
|
||||
|
||||
# Build final results with index and server metadata
|
||||
results = []
|
||||
for (idx, server, url, info, _), response in zip(server_entries, responses):
|
||||
for (id, idx, server, url, info, _), response in zip(server_entries, responses):
|
||||
if isinstance(response, Exception):
|
||||
log.error(f"Failed to connect to {url} OpenAPI tool server")
|
||||
continue
|
||||
@@ -535,6 +597,7 @@ async def get_tool_servers_data(
|
||||
|
||||
results.append(
|
||||
{
|
||||
"id": str(id),
|
||||
"idx": idx,
|
||||
"url": server.get("url"),
|
||||
"openapi": openapi_data,
|
||||
@@ -613,7 +676,9 @@ async def execute_tool_server(
|
||||
if token:
|
||||
headers["Authorization"] = f"Bearer {token}"
|
||||
|
||||
async with aiohttp.ClientSession(trust_env=True) as session:
|
||||
async with aiohttp.ClientSession(
|
||||
trust_env=True, timeout=aiohttp.ClientTimeout(total=AIOHTTP_CLIENT_TIMEOUT)
|
||||
) as session:
|
||||
request_method = getattr(session, http_method.lower())
|
||||
|
||||
if http_method in ["post", "put", "patch"]:
|
||||
@@ -626,7 +691,13 @@ async def execute_tool_server(
|
||||
if response.status >= 400:
|
||||
text = await response.text()
|
||||
raise Exception(f"HTTP error {response.status}: {text}")
|
||||
return await response.json()
|
||||
|
||||
try:
|
||||
response_data = await response.json()
|
||||
except Exception:
|
||||
response_data = await response.text()
|
||||
|
||||
return response_data
|
||||
else:
|
||||
async with request_method(
|
||||
final_url,
|
||||
@@ -636,7 +707,13 @@ async def execute_tool_server(
|
||||
if response.status >= 400:
|
||||
text = await response.text()
|
||||
raise Exception(f"HTTP error {response.status}: {text}")
|
||||
return await response.json()
|
||||
|
||||
try:
|
||||
response_data = await response.json()
|
||||
except Exception:
|
||||
response_data = await response.text()
|
||||
|
||||
return response_data
|
||||
|
||||
except Exception as err:
|
||||
error = str(err)
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import json
|
||||
import logging
|
||||
import aiohttp
|
||||
|
||||
import requests
|
||||
from open_webui.config import WEBUI_FAVICON_URL
|
||||
from open_webui.env import SRC_LOG_LEVELS, VERSION
|
||||
|
||||
@@ -9,7 +9,7 @@ log = logging.getLogger(__name__)
|
||||
log.setLevel(SRC_LOG_LEVELS["WEBHOOK"])
|
||||
|
||||
|
||||
def post_webhook(name: str, url: str, message: str, event_data: dict) -> bool:
|
||||
async def post_webhook(name: str, url: str, message: str, event_data: dict) -> bool:
|
||||
try:
|
||||
log.debug(f"post_webhook: {url}, {message}, {event_data}")
|
||||
payload = {}
|
||||
@@ -51,9 +51,12 @@ def post_webhook(name: str, url: str, message: str, event_data: dict) -> bool:
|
||||
payload = {**event_data}
|
||||
|
||||
log.debug(f"payload: {payload}")
|
||||
r = requests.post(url, json=payload)
|
||||
r.raise_for_status()
|
||||
log.debug(f"r.text: {r.text}")
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.post(url, json=payload) as r:
|
||||
r_text = await r.text()
|
||||
r.raise_for_status()
|
||||
log.debug(f"r.text: {r_text}")
|
||||
|
||||
return True
|
||||
except Exception as e:
|
||||
log.exception(e)
|
||||
|
||||
@@ -42,7 +42,7 @@ asgiref==3.8.1
|
||||
# AI libraries
|
||||
openai
|
||||
anthropic
|
||||
google-genai==1.28.0
|
||||
google-genai==1.32.0
|
||||
google-generativeai==0.8.5
|
||||
tiktoken
|
||||
|
||||
@@ -102,7 +102,6 @@ PyJWT[crypto]==2.10.1
|
||||
authlib==1.6.1
|
||||
|
||||
black==25.1.0
|
||||
langfuse==2.44.0
|
||||
youtube-transcript-api==1.1.0
|
||||
pytube==15.0.0
|
||||
|
||||
|
||||
Generated
+2
-2
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "open-webui",
|
||||
"version": "0.6.19",
|
||||
"version": "0.6.26",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "open-webui",
|
||||
"version": "0.6.19",
|
||||
"version": "0.6.26",
|
||||
"dependencies": {
|
||||
"@azure/msal-browser": "^4.5.0",
|
||||
"@codemirror/lang-javascript": "^6.2.2",
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "open-webui",
|
||||
"version": "0.6.19",
|
||||
"version": "0.6.26",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "npm run pyodide:fetch && vite dev --host",
|
||||
|
||||
+30
-27
@@ -7,7 +7,7 @@ authors = [
|
||||
license = { file = "LICENSE" }
|
||||
dependencies = [
|
||||
"fastapi==0.115.7",
|
||||
"uvicorn[standard]==0.34.2",
|
||||
"uvicorn[standard]==0.35.0",
|
||||
"pydantic==2.11.7",
|
||||
"python-multipart==0.0.20",
|
||||
|
||||
@@ -15,6 +15,10 @@ dependencies = [
|
||||
"python-jose==3.4.0",
|
||||
"passlib[bcrypt]==1.7.4",
|
||||
"cryptography",
|
||||
"bcrypt==4.3.0",
|
||||
"argon2-cffi==23.1.0",
|
||||
"PyJWT[crypto]==2.10.1",
|
||||
"authlib==1.6.1",
|
||||
|
||||
"requests==2.32.4",
|
||||
"aiohttp==3.12.15",
|
||||
@@ -28,31 +32,24 @@ dependencies = [
|
||||
"alembic==1.14.0",
|
||||
"peewee==3.18.1",
|
||||
"peewee-migrate==1.12.2",
|
||||
"psycopg2-binary==2.9.9",
|
||||
"pgvector==0.4.0",
|
||||
"PyMySQL==1.1.1",
|
||||
"bcrypt==4.3.0",
|
||||
|
||||
"pymongo",
|
||||
"redis",
|
||||
"boto3==1.40.5",
|
||||
|
||||
"argon2-cffi==23.1.0",
|
||||
"APScheduler==3.10.4",
|
||||
|
||||
"pycrdt==0.12.25",
|
||||
"redis",
|
||||
|
||||
"PyMySQL==1.1.1",
|
||||
"boto3==1.40.5",
|
||||
|
||||
"APScheduler==3.10.4",
|
||||
"RestrictedPython==8.0",
|
||||
|
||||
"loguru==0.7.3",
|
||||
"asgiref==3.8.1",
|
||||
|
||||
"tiktoken",
|
||||
"openai",
|
||||
"anthropic",
|
||||
"google-genai==1.28.0",
|
||||
"google-genai==1.32.0",
|
||||
"google-generativeai==0.8.5",
|
||||
"tiktoken",
|
||||
|
||||
"langchain==0.3.26",
|
||||
"langchain-community==0.3.26",
|
||||
@@ -100,14 +97,9 @@ dependencies = [
|
||||
"rank-bm25==0.2.2",
|
||||
|
||||
"onnxruntime==1.20.1",
|
||||
|
||||
"faster-whisper==1.1.1",
|
||||
|
||||
"PyJWT[crypto]==2.10.1",
|
||||
"authlib==1.6.1",
|
||||
|
||||
"black==25.1.0",
|
||||
"langfuse==2.44.0",
|
||||
"youtube-transcript-api==1.1.0",
|
||||
"pytube==15.0.0",
|
||||
|
||||
@@ -118,9 +110,7 @@ dependencies = [
|
||||
"google-auth-httplib2",
|
||||
"google-auth-oauthlib",
|
||||
|
||||
"docker~=7.1.0",
|
||||
"pytest~=8.3.2",
|
||||
"pytest-docker~=3.1.1",
|
||||
|
||||
|
||||
"googleapis-common-protos==1.63.2",
|
||||
"google-cloud-storage==2.19.0",
|
||||
@@ -131,12 +121,8 @@ dependencies = [
|
||||
"ldap3==2.9.1",
|
||||
|
||||
"firecrawl-py==1.12.0",
|
||||
|
||||
"tencentcloud-sdk-python==3.0.1336",
|
||||
|
||||
"gcp-storage-emulator>=2024.8.3",
|
||||
|
||||
"moto[s3]>=5.0.26",
|
||||
|
||||
"oracledb>=3.2.0",
|
||||
"posthog==5.4.0",
|
||||
|
||||
@@ -154,6 +140,23 @@ classifiers = [
|
||||
"Topic :: Multimedia",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
postgres = [
|
||||
"psycopg2-binary==2.9.9",
|
||||
"pgvector==0.4.0",
|
||||
]
|
||||
|
||||
all = [
|
||||
"pymongo",
|
||||
"psycopg2-binary==2.9.9",
|
||||
"pgvector==0.4.0",
|
||||
"moto[s3]>=5.0.26",
|
||||
"gcp-storage-emulator>=2024.8.3",
|
||||
"docker~=7.1.0",
|
||||
"pytest~=8.3.2",
|
||||
"pytest-docker~=3.1.1",
|
||||
]
|
||||
|
||||
[project.scripts]
|
||||
open-webui = "open_webui:app"
|
||||
|
||||
|
||||
@@ -86,6 +86,10 @@
|
||||
|
||||
document.addEventListener('DOMContentLoaded', function () {
|
||||
const splash = document.getElementById('splash-screen');
|
||||
if (document.documentElement.classList.contains('her')) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (splash) splash.prepend(logo);
|
||||
});
|
||||
})();
|
||||
@@ -167,6 +171,7 @@
|
||||
<style type="text/css" nonce="">
|
||||
html {
|
||||
overflow-y: hidden !important;
|
||||
overscroll-behavior-y: none;
|
||||
}
|
||||
|
||||
#splash-screen {
|
||||
|
||||
@@ -393,7 +393,7 @@ export const addUser = async (
|
||||
return res;
|
||||
};
|
||||
|
||||
export const updateUserProfile = async (token: string, name: string, profileImageUrl: string) => {
|
||||
export const updateUserProfile = async (token: string, profile: object) => {
|
||||
let error = null;
|
||||
|
||||
const res = await fetch(`${WEBUI_API_BASE_URL}/auths/update/profile`, {
|
||||
@@ -403,8 +403,7 @@ export const updateUserProfile = async (token: string, name: string, profileImag
|
||||
...(token && { authorization: `Bearer ${token}` })
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name: name,
|
||||
profile_image_url: profileImageUrl
|
||||
...profile
|
||||
})
|
||||
})
|
||||
.then(async (res) => {
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { WEBUI_API_BASE_URL } from '$lib/constants';
|
||||
import { splitStream } from '$lib/utils';
|
||||
|
||||
export const uploadFile = async (token: string, file: File, metadata?: object | null) => {
|
||||
const data = new FormData();
|
||||
@@ -31,6 +32,75 @@ export const uploadFile = async (token: string, file: File, metadata?: object |
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (res) {
|
||||
const status = await getFileProcessStatus(token, res.id);
|
||||
|
||||
if (status && status.ok) {
|
||||
const reader = status.body
|
||||
.pipeThrough(new TextDecoderStream())
|
||||
.pipeThrough(splitStream('\n'))
|
||||
.getReader();
|
||||
|
||||
while (true) {
|
||||
const { value, done } = await reader.read();
|
||||
if (done) {
|
||||
break;
|
||||
}
|
||||
|
||||
try {
|
||||
let lines = value.split('\n');
|
||||
|
||||
for (const line of lines) {
|
||||
if (line !== '') {
|
||||
console.log(line);
|
||||
if (line === 'data: [DONE]') {
|
||||
console.log(line);
|
||||
} else {
|
||||
let data = JSON.parse(line.replace(/^data: /, ''));
|
||||
console.log(data);
|
||||
|
||||
if (data?.error) {
|
||||
console.error(data.error);
|
||||
res.error = data.error;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.log(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return res;
|
||||
};
|
||||
|
||||
export const getFileProcessStatus = async (token: string, id: string) => {
|
||||
const queryParams = new URLSearchParams();
|
||||
queryParams.append('stream', 'true');
|
||||
|
||||
let error = null;
|
||||
const res = await fetch(`${WEBUI_API_BASE_URL}/files/${id}/process/status?${queryParams}`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
authorization: `Bearer ${token}`
|
||||
}
|
||||
}).catch((err) => {
|
||||
error = err.detail;
|
||||
console.error(err);
|
||||
return null;
|
||||
});
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return res;
|
||||
};
|
||||
|
||||
|
||||
+18
-9
@@ -347,25 +347,20 @@ export const getToolServerData = async (token: string, url: string) => {
|
||||
return data;
|
||||
};
|
||||
|
||||
export const getToolServersData = async (i18n, servers: object[]) => {
|
||||
export const getToolServersData = async (servers: object[]) => {
|
||||
return (
|
||||
await Promise.all(
|
||||
servers
|
||||
.filter((server) => server?.config?.enable)
|
||||
.map(async (server) => {
|
||||
let error = null;
|
||||
const data = await getToolServerData(
|
||||
(server?.auth_type ?? 'bearer') === 'bearer' ? server?.key : localStorage.token,
|
||||
(server?.path ?? '').includes('://')
|
||||
? server?.path
|
||||
: `${server?.url}${(server?.path ?? '').startsWith('/') ? '' : '/'}${server?.path}`
|
||||
).catch((err) => {
|
||||
toast.error(
|
||||
i18n.t(`Failed to connect to {{URL}} OpenAPI tool server`, {
|
||||
URL: (server?.path ?? '').includes('://')
|
||||
? server?.path
|
||||
: `${server?.url}${(server?.path ?? '').startsWith('/') ? '' : '/'}${server?.path}`
|
||||
})
|
||||
);
|
||||
error = err;
|
||||
return null;
|
||||
});
|
||||
|
||||
@@ -377,6 +372,13 @@ export const getToolServersData = async (i18n, servers: object[]) => {
|
||||
info: info,
|
||||
specs: specs
|
||||
};
|
||||
} else if (error) {
|
||||
return {
|
||||
error,
|
||||
url: server?.url
|
||||
};
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
})
|
||||
)
|
||||
@@ -480,7 +482,14 @@ export const executeToolServer = async (
|
||||
throw new Error(`HTTP error! Status: ${res.status}. Message: ${resText}`);
|
||||
}
|
||||
|
||||
return await res.json();
|
||||
let responseData;
|
||||
try {
|
||||
responseData = await res.json();
|
||||
} catch (err) {
|
||||
responseData = await res.text();
|
||||
}
|
||||
|
||||
return responseData;
|
||||
} catch (err: any) {
|
||||
error = err.message;
|
||||
console.error('API Request Error:', error);
|
||||
|
||||
@@ -234,7 +234,7 @@ export const getOllamaModels = async (token: string = '', urlIdx: null | number
|
||||
return (res?.models ?? [])
|
||||
.map((model) => ({ id: model.model, name: model.name ?? model.model, ...model }))
|
||||
.sort((a, b) => {
|
||||
return a.name.localeCompare(b.name);
|
||||
return (a?.name ?? a?.id ?? '').localeCompare(b?.name ?? b?.id ?? '');
|
||||
});
|
||||
};
|
||||
|
||||
|
||||
@@ -379,7 +379,7 @@ export const generateOpenAIChatCompletion = async (
|
||||
return res.json();
|
||||
})
|
||||
.catch((err) => {
|
||||
error = `${err?.detail ?? err}`;
|
||||
error = err?.detail ?? err;
|
||||
return null;
|
||||
});
|
||||
|
||||
|
||||
@@ -443,3 +443,30 @@ export const updateUserById = async (token: string, userId: string, user: UserUp
|
||||
|
||||
return res;
|
||||
};
|
||||
|
||||
export const getUserGroupsById = async (token: string, userId: string) => {
|
||||
let error = null;
|
||||
|
||||
const res = await fetch(`${WEBUI_API_BASE_URL}/users/${userId}/groups`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer ${token}`
|
||||
}
|
||||
})
|
||||
.then(async (res) => {
|
||||
if (!res.ok) throw await res.json();
|
||||
return res.json();
|
||||
})
|
||||
.catch((err) => {
|
||||
console.error(err);
|
||||
error = err.detail;
|
||||
return null;
|
||||
});
|
||||
|
||||
if (error) {
|
||||
throw error;
|
||||
}
|
||||
|
||||
return res;
|
||||
};
|
||||
|
||||
@@ -108,7 +108,7 @@
|
||||
|
||||
if (!ollama && !url) {
|
||||
loading = false;
|
||||
toast.error('URL is required');
|
||||
toast.error($i18n.t('URL is required'));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -116,20 +116,20 @@
|
||||
if (!apiVersion) {
|
||||
loading = false;
|
||||
|
||||
toast.error('API Version is required');
|
||||
toast.error($i18n.t('API Version is required'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!key) {
|
||||
loading = false;
|
||||
|
||||
toast.error('Key is required');
|
||||
toast.error($i18n.t('Key is required'));
|
||||
return;
|
||||
}
|
||||
|
||||
if (modelIds.length === 0) {
|
||||
loading = false;
|
||||
toast.error('Deployment names are required');
|
||||
toast.error($i18n.t('Deployment names are required for Azure OpenAI'));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,6 +35,7 @@
|
||||
|
||||
let accessControl = {};
|
||||
|
||||
let id = '';
|
||||
let name = '';
|
||||
let description = '';
|
||||
|
||||
@@ -76,6 +77,7 @@
|
||||
access_control: accessControl
|
||||
},
|
||||
info: {
|
||||
id,
|
||||
name,
|
||||
description
|
||||
}
|
||||
@@ -106,6 +108,7 @@
|
||||
access_control: accessControl
|
||||
},
|
||||
info: {
|
||||
id: id,
|
||||
name: name,
|
||||
description: description
|
||||
}
|
||||
@@ -121,6 +124,7 @@
|
||||
key = '';
|
||||
auth_type = 'bearer';
|
||||
|
||||
id = '';
|
||||
name = '';
|
||||
description = '';
|
||||
|
||||
@@ -136,6 +140,7 @@
|
||||
auth_type = connection?.auth_type ?? 'bearer';
|
||||
key = connection?.key ?? '';
|
||||
|
||||
id = connection.info?.id ?? '';
|
||||
name = connection.info?.name ?? '';
|
||||
description = connection.info?.description ?? '';
|
||||
|
||||
@@ -278,8 +283,8 @@
|
||||
class={`w-full text-sm bg-transparent pr-5 ${($settings?.highContrastMode ?? false) ? 'placeholder:text-gray-700 dark:placeholder:text-gray-100' : 'outline-hidden placeholder:text-gray-300 dark:placeholder:text-gray-700'}`}
|
||||
bind:value={auth_type}
|
||||
>
|
||||
<option value="bearer">Bearer</option>
|
||||
<option value="session">Session</option>
|
||||
<option value="bearer">{$i18n.t('Bearer')}</option>
|
||||
<option value="session">{$i18n.t('Session')}</option>
|
||||
</select>
|
||||
</div>
|
||||
|
||||
@@ -306,12 +311,36 @@
|
||||
<hr class=" border-gray-100 dark:border-gray-700/10 my-2.5 w-full" />
|
||||
|
||||
<div class="flex gap-2">
|
||||
<div class="flex flex-col w-full">
|
||||
<label
|
||||
for="enter-id"
|
||||
class={`mb-0.5 text-xs ${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100' : 'text-gray-500'}`}
|
||||
>{$i18n.t('ID')}
|
||||
<span class="text-xs text-gray-200 dark:text-gray-800 ml-0.5"
|
||||
>{$i18n.t('Optional')}</span
|
||||
>
|
||||
</label>
|
||||
|
||||
<div class="flex-1">
|
||||
<input
|
||||
id="enter-id"
|
||||
class={`w-full text-sm bg-transparent ${($settings?.highContrastMode ?? false) ? 'placeholder:text-gray-700 dark:placeholder:text-gray-100' : 'outline-hidden placeholder:text-gray-300 dark:placeholder:text-gray-700'}`}
|
||||
type="text"
|
||||
bind:value={id}
|
||||
placeholder={$i18n.t('Enter ID')}
|
||||
autocomplete="off"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="flex gap-2 mt-2">
|
||||
<div class="flex flex-col w-full">
|
||||
<label
|
||||
for="enter-name"
|
||||
class={`mb-0.5 text-xs" ${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100' : 'text-gray-500'}`}
|
||||
>{$i18n.t('Name')}</label
|
||||
>
|
||||
class={`mb-0.5 text-xs ${($settings?.highContrastMode ?? false) ? 'text-gray-800 dark:text-gray-100' : 'text-gray-500'}`}
|
||||
>{$i18n.t('Name')}
|
||||
</label>
|
||||
|
||||
<div class="flex-1">
|
||||
<input
|
||||
|
||||
@@ -115,7 +115,7 @@
|
||||
if (a.rating === '-' && b.rating !== '-') return 1;
|
||||
if (b.rating === '-' && a.rating !== '-') return -1;
|
||||
if (a.rating !== '-' && b.rating !== '-') return b.rating - a.rating;
|
||||
return a.name.localeCompare(b.name);
|
||||
return (a?.name ?? a?.id ?? '').localeCompare(b?.name ?? b?.id ?? '');
|
||||
});
|
||||
|
||||
loadingLeaderboard = false;
|
||||
|
||||
@@ -105,7 +105,7 @@
|
||||
sessionStorage.function = JSON.stringify({
|
||||
..._function,
|
||||
id: `${_function.id}_clone`,
|
||||
name: `${_function.name} (Clone)`
|
||||
name: `${_function.name} (${$i18n.t('Clone')})`
|
||||
});
|
||||
goto('/admin/functions/create');
|
||||
}
|
||||
@@ -626,7 +626,12 @@
|
||||
const _functions = JSON.parse(event.target.result);
|
||||
console.log(_functions);
|
||||
|
||||
for (const func of _functions) {
|
||||
for (let func of _functions) {
|
||||
if ('function' in func) {
|
||||
// Required for Community JSON import
|
||||
func = func.function;
|
||||
}
|
||||
|
||||
const res = await createNewFunction(localStorage.token, func).catch((error) => {
|
||||
toast.error(`${error}`);
|
||||
return null;
|
||||
@@ -650,7 +655,7 @@
|
||||
>
|
||||
<div class="text-sm text-gray-500">
|
||||
<div class=" bg-yellow-500/20 text-yellow-700 dark:text-yellow-200 rounded-lg px-4 py-3">
|
||||
<div>Please carefully review the following warnings:</div>
|
||||
<div>{$i18n.t('Please carefully review the following warnings:')}</div>
|
||||
|
||||
<ul class=" mt-1 list-disc pl-4 text-xs">
|
||||
<li>{$i18n.t('Functions allow arbitrary code execution.')}</li>
|
||||
|
||||
@@ -215,13 +215,13 @@
|
||||
<select
|
||||
class="dark:bg-gray-900 cursor-pointer w-fit pr-8 rounded-sm px-2 p-1 text-xs bg-transparent outline-hidden text-right"
|
||||
bind:value={STT_ENGINE}
|
||||
placeholder="Select an engine"
|
||||
placeholder={$i18n.t('Select an engine')}
|
||||
>
|
||||
<option value="">{$i18n.t('Whisper (Local)')}</option>
|
||||
<option value="openai">OpenAI</option>
|
||||
<option value="openai">{$i18n.t('OpenAI')}</option>
|
||||
<option value="web">{$i18n.t('Web API')}</option>
|
||||
<option value="deepgram">Deepgram</option>
|
||||
<option value="azure">Azure AI Speech</option>
|
||||
<option value="deepgram">{$i18n.t('Deepgram')}</option>
|
||||
<option value="azure">{$i18n.t('Azure AI Speech')}</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
@@ -250,7 +250,7 @@
|
||||
list="model-list"
|
||||
class="w-full rounded-lg py-2 px-4 text-sm bg-gray-50 dark:text-gray-300 dark:bg-gray-850 outline-hidden"
|
||||
bind:value={STT_MODEL}
|
||||
placeholder="Select a model"
|
||||
placeholder={$i18n.t('Select a model')}
|
||||
/>
|
||||
|
||||
<datalist id="model-list">
|
||||
@@ -275,7 +275,7 @@
|
||||
<input
|
||||
class="w-full rounded-lg py-2 px-4 text-sm bg-gray-50 dark:text-gray-300 dark:bg-gray-850 outline-hidden"
|
||||
bind:value={STT_MODEL}
|
||||
placeholder="Select a model (optional)"
|
||||
placeholder={$i18n.t('Select a model (optional)')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -424,7 +424,7 @@
|
||||
<select
|
||||
class=" dark:bg-gray-900 w-fit pr-8 cursor-pointer rounded-sm px-2 p-1 text-xs bg-transparent outline-hidden text-right"
|
||||
bind:value={TTS_ENGINE}
|
||||
placeholder="Select a mode"
|
||||
placeholder={$i18n.t('Select a mode')}
|
||||
on:change={async (e) => {
|
||||
await updateConfigHandler();
|
||||
await getVoices();
|
||||
@@ -539,7 +539,7 @@
|
||||
list="model-list"
|
||||
class="w-full rounded-lg py-2 px-4 text-sm bg-gray-50 dark:text-gray-300 dark:bg-gray-850 outline-hidden"
|
||||
bind:value={TTS_MODEL}
|
||||
placeholder="CMU ARCTIC speaker embedding name"
|
||||
placeholder={$i18n.t('CMU ARCTIC speaker embedding name')}
|
||||
/>
|
||||
|
||||
<datalist id="model-list">
|
||||
@@ -581,7 +581,7 @@
|
||||
list="voice-list"
|
||||
class="w-full rounded-lg py-2 px-4 text-sm bg-gray-50 dark:text-gray-300 dark:bg-gray-850 outline-hidden"
|
||||
bind:value={TTS_VOICE}
|
||||
placeholder="Select a voice"
|
||||
placeholder={$i18n.t('Select a voice')}
|
||||
/>
|
||||
|
||||
<datalist id="voice-list">
|
||||
@@ -600,7 +600,7 @@
|
||||
list="tts-model-list"
|
||||
class="w-full rounded-lg py-2 px-4 text-sm bg-gray-50 dark:text-gray-300 dark:bg-gray-850 outline-hidden"
|
||||
bind:value={TTS_MODEL}
|
||||
placeholder="Select a model"
|
||||
placeholder={$i18n.t('Select a model')}
|
||||
/>
|
||||
|
||||
<datalist id="tts-model-list">
|
||||
@@ -622,7 +622,7 @@
|
||||
list="voice-list"
|
||||
class="w-full rounded-lg py-2 px-4 text-sm bg-gray-50 dark:text-gray-300 dark:bg-gray-850 outline-hidden"
|
||||
bind:value={TTS_VOICE}
|
||||
placeholder="Select a voice"
|
||||
placeholder={$i18n.t('Select a voice')}
|
||||
/>
|
||||
|
||||
<datalist id="voice-list">
|
||||
@@ -641,7 +641,7 @@
|
||||
list="tts-model-list"
|
||||
class="w-full rounded-lg py-2 px-4 text-sm bg-gray-50 dark:text-gray-300 dark:bg-gray-850 outline-hidden"
|
||||
bind:value={TTS_MODEL}
|
||||
placeholder="Select a model"
|
||||
placeholder={$i18n.t('Select a model')}
|
||||
/>
|
||||
|
||||
<datalist id="tts-model-list">
|
||||
@@ -663,7 +663,7 @@
|
||||
list="voice-list"
|
||||
class="w-full rounded-lg py-2 px-4 text-sm bg-gray-50 dark:text-gray-300 dark:bg-gray-850 outline-hidden"
|
||||
bind:value={TTS_VOICE}
|
||||
placeholder="Select a voice"
|
||||
placeholder={$i18n.t('Select a voice')}
|
||||
/>
|
||||
|
||||
<datalist id="voice-list">
|
||||
@@ -690,7 +690,7 @@
|
||||
list="tts-model-list"
|
||||
class="w-full rounded-lg py-2 px-4 text-sm bg-gray-50 dark:text-gray-300 dark:bg-gray-850 outline-hidden"
|
||||
bind:value={TTS_AZURE_SPEECH_OUTPUT_FORMAT}
|
||||
placeholder="Select a output format"
|
||||
placeholder={$i18n.t('Select an output format')}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
@@ -704,7 +704,7 @@
|
||||
<div class="flex items-center relative">
|
||||
<select
|
||||
class="dark:bg-gray-900 w-fit pr-8 cursor-pointer rounded-sm px-2 p-1 text-xs bg-transparent outline-hidden text-right"
|
||||
aria-label="Select how to split message text for TTS requests"
|
||||
aria-label={$i18n.t('Select how to split message text for TTS requests')}
|
||||
bind:value={TTS_SPLIT_ON}
|
||||
>
|
||||
{#each Object.values(TTS_RESPONSE_SPLIT) as split}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
import { getOllamaConfig, updateOllamaConfig } from '$lib/apis/ollama';
|
||||
import { getOpenAIConfig, updateOpenAIConfig, getOpenAIModels } from '$lib/apis/openai';
|
||||
import { getModels as _getModels } from '$lib/apis';
|
||||
import { getModels as _getModels, getBackendConfig } from '$lib/apis';
|
||||
import { getConnectionsConfig, setConnectionsConfig } from '$lib/apis/configs';
|
||||
|
||||
import { config, models, settings, user } from '$lib/stores';
|
||||
@@ -114,6 +114,7 @@
|
||||
if (res) {
|
||||
toast.success($i18n.t('Connections settings updated'));
|
||||
await models.set(await getModels());
|
||||
await config.set(await getBackendConfig());
|
||||
}
|
||||
};
|
||||
|
||||
@@ -198,6 +199,8 @@
|
||||
updateOllamaHandler();
|
||||
|
||||
dispatch('save');
|
||||
|
||||
await config.set(await getBackendConfig());
|
||||
};
|
||||
</script>
|
||||
|
||||
|
||||
@@ -76,7 +76,7 @@
|
||||
);
|
||||
|
||||
if (res) {
|
||||
toast.success('Config imported successfully');
|
||||
toast.success($i18n.t('Config imported successfully'));
|
||||
}
|
||||
e.target.value = null;
|
||||
};
|
||||
|
||||
@@ -185,10 +185,9 @@
|
||||
|
||||
if (
|
||||
RAGConfig.CONTENT_EXTRACTION_ENGINE === 'document_intelligence' &&
|
||||
(RAGConfig.DOCUMENT_INTELLIGENCE_ENDPOINT === '' ||
|
||||
RAGConfig.DOCUMENT_INTELLIGENCE_KEY === '')
|
||||
RAGConfig.DOCUMENT_INTELLIGENCE_ENDPOINT === ''
|
||||
) {
|
||||
toast.error($i18n.t('Document Intelligence endpoint and key required.'));
|
||||
toast.error($i18n.t('Document Intelligence endpoint required.'));
|
||||
return;
|
||||
}
|
||||
if (
|
||||
@@ -644,6 +643,7 @@
|
||||
<SensitiveInput
|
||||
placeholder={$i18n.t('Enter Document Intelligence Key')}
|
||||
bind:value={RAGConfig.DOCUMENT_INTELLIGENCE_KEY}
|
||||
required={false}
|
||||
/>
|
||||
</div>
|
||||
{:else if RAGConfig.CONTENT_EXTRACTION_ENGINE === 'mistral_ocr'}
|
||||
@@ -746,7 +746,7 @@
|
||||
<select
|
||||
class="dark:bg-gray-900 w-fit pr-8 rounded-sm px-2 p-1 text-xs bg-transparent outline-hidden text-right"
|
||||
bind:value={embeddingEngine}
|
||||
placeholder="Select an embedding model engine"
|
||||
placeholder={$i18n.t('Select an embedding model engine')}
|
||||
on:change={(e) => {
|
||||
if (e.target.value === 'ollama') {
|
||||
embeddingModel = '';
|
||||
@@ -762,7 +762,7 @@
|
||||
<option value="">{$i18n.t('Default (SentenceTransformers)')}</option>
|
||||
<option value="ollama">{$i18n.t('Ollama')}</option>
|
||||
<option value="openai">{$i18n.t('OpenAI')}</option>
|
||||
<option value="azure_openai">Azure OpenAI</option>
|
||||
<option value="azure_openai">{$i18n.t('Azure OpenAI')}</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
@@ -811,7 +811,7 @@
|
||||
<div class="flex gap-2">
|
||||
<input
|
||||
class="flex-1 w-full text-sm bg-transparent outline-hidden"
|
||||
placeholder="Version"
|
||||
placeholder={$i18n.t('Version')}
|
||||
bind:value={AzureOpenAIVersion}
|
||||
required
|
||||
/>
|
||||
@@ -947,7 +947,7 @@
|
||||
<select
|
||||
class="dark:bg-gray-900 w-fit pr-8 rounded-sm px-2 p-1 text-xs bg-transparent outline-hidden text-right"
|
||||
bind:value={RAGConfig.RAG_RERANKING_ENGINE}
|
||||
placeholder="Select a reranking model engine"
|
||||
placeholder={$i18n.t('Select a reranking model engine')}
|
||||
on:change={(e) => {
|
||||
if (e.target.value === 'external') {
|
||||
RAGConfig.RAG_RERANKING_MODEL = '';
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
});
|
||||
|
||||
if (evaluationConfig) {
|
||||
toast.success('Settings saved successfully');
|
||||
toast.success($i18n.t('Settings saved successfully!'));
|
||||
models.set(
|
||||
await getModels(
|
||||
localStorage.token,
|
||||
|
||||
@@ -62,7 +62,7 @@
|
||||
|
||||
if (!name || !id) {
|
||||
loading = false;
|
||||
toast.error('Name and ID are required, please fill them out');
|
||||
toast.error($i18n.t('Name and ID are required, please fill them out'));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -70,7 +70,7 @@
|
||||
if ($models.find((model) => model.name === name)) {
|
||||
loading = false;
|
||||
name = '';
|
||||
toast.error('Model name already exists, please choose a different one');
|
||||
toast.error($i18n.t('Model name already exists, please choose a different one'));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -290,7 +290,7 @@
|
||||
<select
|
||||
class="dark:bg-gray-900 w-fit pr-8 rounded-sm px-2 text-xs bg-transparent outline-hidden text-right"
|
||||
bind:value={adminConfig.DEFAULT_USER_ROLE}
|
||||
placeholder="Select a role"
|
||||
placeholder={$i18n.t('Select a role')}
|
||||
>
|
||||
<option value="pending">{$i18n.t('pending')}</option>
|
||||
<option value="user">{$i18n.t('user')}</option>
|
||||
@@ -587,7 +587,7 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="flex justify-between items-center text-xs">
|
||||
<div class=" font-medium">Validate certificate</div>
|
||||
<div class=" font-medium">{$i18n.t('Validate certificate')}</div>
|
||||
|
||||
<div class="mt-1">
|
||||
<Switch bind:state={LDAP_SERVER.validate_cert} />
|
||||
|
||||
@@ -143,7 +143,7 @@
|
||||
|
||||
if (config?.comfyui?.COMFYUI_WORKFLOW) {
|
||||
if (!validateJSON(config.comfyui.COMFYUI_WORKFLOW)) {
|
||||
toast.error('Invalid JSON format for ComfyUI Workflow.');
|
||||
toast.error($i18n.t('Invalid JSON format for ComfyUI Workflow.'));
|
||||
loading = false;
|
||||
return;
|
||||
}
|
||||
@@ -566,10 +566,10 @@
|
||||
</div>
|
||||
</div>
|
||||
<div class="">
|
||||
<Tooltip content="Input Key (e.g. text, unet_name, steps)">
|
||||
<Tooltip content={$i18n.t('Input Key (e.g. text, unet_name, steps)')}>
|
||||
<input
|
||||
class="py-1 px-3 w-24 text-xs text-center bg-transparent outline-hidden border-r border-gray-50 dark:border-gray-850"
|
||||
placeholder="Key"
|
||||
placeholder={$i18n.t('Key')}
|
||||
bind:value={node.key}
|
||||
required
|
||||
/>
|
||||
@@ -578,12 +578,12 @@
|
||||
|
||||
<div class="w-full">
|
||||
<Tooltip
|
||||
content="Comma separated Node Ids (e.g. 1 or 1,2)"
|
||||
content={$i18n.t('Comma separated Node Ids (e.g. 1 or 1,2)')}
|
||||
placement="top-start"
|
||||
>
|
||||
<input
|
||||
class="w-full py-1 px-4 text-xs bg-transparent outline-hidden"
|
||||
placeholder="Node Ids"
|
||||
placeholder={$i18n.t('Node Ids')}
|
||||
bind:value={node.node_ids}
|
||||
/>
|
||||
</Tooltip>
|
||||
@@ -650,7 +650,7 @@
|
||||
list="model-list"
|
||||
class="w-full rounded-lg py-2 px-4 text-sm bg-gray-50 dark:text-gray-300 dark:bg-gray-850 outline-hidden"
|
||||
bind:value={imageGenerationConfig.MODEL}
|
||||
placeholder="Select a model"
|
||||
placeholder={$i18n.t('Select a model')}
|
||||
required
|
||||
/>
|
||||
|
||||
@@ -682,21 +682,23 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<div class=" mb-2.5 text-sm font-medium">{$i18n.t('Set Steps')}</div>
|
||||
<div class="flex w-full">
|
||||
<div class="flex-1 mr-2">
|
||||
<Tooltip content={$i18n.t('Enter Number of Steps (e.g. 50)')} placement="top-start">
|
||||
<input
|
||||
class="w-full rounded-lg py-2 px-4 text-sm bg-gray-50 dark:text-gray-300 dark:bg-gray-850 outline-hidden"
|
||||
placeholder={$i18n.t('Enter Number of Steps (e.g. 50)')}
|
||||
bind:value={imageGenerationConfig.IMAGE_STEPS}
|
||||
required
|
||||
/>
|
||||
</Tooltip>
|
||||
{#if ['comfyui', 'automatic1111', ''].includes(config?.engine)}
|
||||
<div>
|
||||
<div class=" mb-2.5 text-sm font-medium">{$i18n.t('Set Steps')}</div>
|
||||
<div class="flex w-full">
|
||||
<div class="flex-1 mr-2">
|
||||
<Tooltip content={$i18n.t('Enter Number of Steps (e.g. 50)')} placement="top-start">
|
||||
<input
|
||||
class="w-full rounded-lg py-2 px-4 text-sm bg-gray-50 dark:text-gray-300 dark:bg-gray-850 outline-hidden"
|
||||
placeholder={$i18n.t('Enter Number of Steps (e.g. 50)')}
|
||||
bind:value={imageGenerationConfig.IMAGE_STEPS}
|
||||
required
|
||||
/>
|
||||
</Tooltip>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
{/if}
|
||||
{/if}
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -42,7 +42,7 @@
|
||||
}
|
||||
|
||||
if (bannerListElement) {
|
||||
sortable = Sortable.create(bannerListElement, {
|
||||
sortable = new Sortable(bannerListElement, {
|
||||
animation: 150,
|
||||
handle: '.item-handle',
|
||||
onUpdate: async (event) => {
|
||||
|
||||
@@ -63,7 +63,7 @@
|
||||
// return (b.is_active ?? true) - (a.is_active ?? true);
|
||||
// }
|
||||
// If both models' active states are the same, sort alphabetically
|
||||
return a.name.localeCompare(b.name);
|
||||
return (a?.name ?? a?.id ?? '').localeCompare(b?.name ?? b?.id ?? '');
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -437,7 +437,7 @@
|
||||
...$MODEL_DOWNLOAD_POOL
|
||||
});
|
||||
await deleteModel(localStorage.token, model);
|
||||
toast.success(`${model} download has been canceled`);
|
||||
toast.success($i18n.t('{{model}} download has been canceled', { model: model }));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -31,9 +31,9 @@
|
||||
}
|
||||
|
||||
if (modelListElement) {
|
||||
sortable = Sortable.create(modelListElement, {
|
||||
sortable = new Sortable(modelListElement, {
|
||||
animation: 150,
|
||||
handle: '.item-handle',
|
||||
handle: '.model-item-handle',
|
||||
onUpdate: async (event) => {
|
||||
positionChangeHandler();
|
||||
}
|
||||
@@ -44,11 +44,11 @@
|
||||
|
||||
{#if modelIds.length > 0}
|
||||
<div class="flex flex-col -translate-x-1" bind:this={modelListElement}>
|
||||
{#each modelIds as modelId, modelIdx (modelId)}
|
||||
{#each modelIds as modelId, modelIdx (`${modelId}-${modelIdx}`)}
|
||||
<div class=" flex gap-2 w-full justify-between items-center" id="model-item-{modelId}">
|
||||
<Tooltip content={modelId} placement="top-start">
|
||||
<div class="flex items-center gap-1">
|
||||
<EllipsisVertical className="size-4 cursor-move item-handle" />
|
||||
<EllipsisVertical className="size-4 cursor-move model-item-handle" />
|
||||
|
||||
<div class=" text-sm flex-1 py-1 rounded-lg">
|
||||
{#if $models.find((model) => model.id === modelId)}
|
||||
|
||||
@@ -152,7 +152,7 @@
|
||||
const res = await uploadPipeline(localStorage.token, file, selectedPipelinesUrlIdx).catch(
|
||||
(error) => {
|
||||
console.error(error);
|
||||
toast.error('Something went wrong :/');
|
||||
toast.error($i18n.t('Something went wrong :/'));
|
||||
return null;
|
||||
}
|
||||
);
|
||||
@@ -410,10 +410,10 @@
|
||||
</div>
|
||||
|
||||
<div class="mt-2 text-xs text-gray-500">
|
||||
<span class=" font-semibold dark:text-gray-200">Warning:</span> Pipelines are a plugin
|
||||
system with arbitrary code execution —
|
||||
<span class=" font-semibold dark:text-gray-200">{$i18n.t('Warning:')}</span>
|
||||
{$i18n.t('Pipelines are a plugin system with arbitrary code execution —')}
|
||||
<span class=" font-medium dark:text-gray-400"
|
||||
>don't fetch random pipelines from sources you don't trust.</span
|
||||
>{$i18n.t("don't fetch random pipelines from sources you don't trust.")}</span
|
||||
>
|
||||
</div>
|
||||
</div>
|
||||
@@ -514,7 +514,7 @@
|
||||
{:else if (valves_spec.properties[property]?.type ?? null) === 'boolean'}
|
||||
<div class="flex justify-between items-center">
|
||||
<div class="text-xs text-gray-500">
|
||||
{valves[property] ? 'Enabled' : 'Disabled'}
|
||||
{valves[property] ? $i18n.t('Enabled') : $i18n.t('Disabled')}
|
||||
</div>
|
||||
|
||||
<div class=" pr-2">
|
||||
@@ -540,12 +540,12 @@
|
||||
<Spinner className="size-5" />
|
||||
{/if}
|
||||
{:else}
|
||||
<div>No valves</div>
|
||||
<div>{$i18n.t('No valves')}</div>
|
||||
{/if}
|
||||
</div>
|
||||
</div>
|
||||
{:else if pipelines.length === 0}
|
||||
<div>Pipelines Not Detected</div>
|
||||
<div>{$i18n.t('Pipelines Not Detected')}</div>
|
||||
{/if}
|
||||
{:else}
|
||||
<div class="flex justify-center">
|
||||
|
||||
@@ -119,7 +119,11 @@
|
||||
>
|
||||
<option disabled selected value="">{$i18n.t('Select a engine')}</option>
|
||||
{#each webSearchEngines as engine}
|
||||
<option value={engine}>{engine}</option>
|
||||
{#if engine === 'duckduckgo' || engine === 'ddgs'}
|
||||
<option value={engine}>DDGS</option>
|
||||
{:else}
|
||||
<option value={engine}>{engine}</option>
|
||||
{/if}
|
||||
{/each}
|
||||
</select>
|
||||
</div>
|
||||
@@ -471,11 +475,11 @@
|
||||
/>
|
||||
|
||||
<datalist id="perplexity-model-list">
|
||||
<option value="sonar">Sonar</option>
|
||||
<option value="sonar-pro">Sonar Pro</option>
|
||||
<option value="sonar-reasoning">Sonar Reasoning</option>
|
||||
<option value="sonar-reasoning-pro">Sonar Reasoning Pro</option>
|
||||
<option value="sonar-deep-research">Sonar Deep Research</option>
|
||||
<option value="sonar">{$i18n.t('Sonar')}</option>
|
||||
<option value="sonar-pro">{$i18n.t('Sonar Pro')}</option>
|
||||
<option value="sonar-reasoning">{$i18n.t('Sonar Reasoning')}</option>
|
||||
<option value="sonar-reasoning-pro">{$i18n.t('Sonar Reasoning Pro')}</option>
|
||||
<option value="sonar-deep-research">{$i18n.t('Sonar Deep Research')}</option>
|
||||
</datalist>
|
||||
</div>
|
||||
</div>
|
||||
@@ -489,9 +493,9 @@
|
||||
class="w-full rounded-lg py-2 px-4 text-sm bg-gray-50 dark:text-gray-300 dark:bg-gray-850 outline-hidden"
|
||||
bind:value={webConfig.PERPLEXITY_SEARCH_CONTEXT_USAGE}
|
||||
>
|
||||
<option value="low">Low</option>
|
||||
<option value="medium">Medium</option>
|
||||
<option value="high">High</option>
|
||||
<option value="low">{$i18n.t('Low')}</option>
|
||||
<option value="medium">{$i18n.t('Medium')}</option>
|
||||
<option value="high">{$i18n.t('High')}</option>
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
@@ -551,6 +555,19 @@
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
{:else if webConfig.WEB_SEARCH_ENGINE === 'ddgs' || webConfig.WEB_SEARCH_ENGINE === 'duckduckgo'}
|
||||
<div class="w-full mb-2.5">
|
||||
<div class=" self-center text-xs font-medium mb-1">
|
||||
{$i18n.t('Concurrent Requests')}
|
||||
</div>
|
||||
|
||||
<input
|
||||
class="w-full rounded-lg py-2 px-4 text-sm bg-gray-50 dark:text-gray-300 dark:bg-gray-850 outline-hidden"
|
||||
placeholder={$i18n.t('Concurrent Requests')}
|
||||
bind:value={webConfig.WEB_SEARCH_CONCURRENT_REQUESTS}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
{:else if webConfig.WEB_SEARCH_ENGINE === 'external'}
|
||||
<div class="mb-2.5 flex w-full flex-col">
|
||||
<div>
|
||||
@@ -600,19 +617,6 @@
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class="w-full">
|
||||
<div class=" self-center text-xs font-medium mb-1">
|
||||
{$i18n.t('Concurrent Requests')}
|
||||
</div>
|
||||
|
||||
<input
|
||||
class="w-full rounded-lg py-2 px-4 text-sm bg-gray-50 dark:text-gray-300 dark:bg-gray-850 outline-hidden"
|
||||
placeholder={$i18n.t('Concurrent Requests')}
|
||||
bind:value={webConfig.WEB_SEARCH_CONCURRENT_REQUESTS}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -849,6 +853,19 @@
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="mb-2.5 w-full">
|
||||
<div class=" self-center text-xs font-medium mb-1">
|
||||
{$i18n.t('Concurrent Requests')}
|
||||
</div>
|
||||
|
||||
<input
|
||||
class="w-full rounded-lg py-2 px-4 text-sm bg-gray-50 dark:text-gray-300 dark:bg-gray-850 outline-hidden"
|
||||
placeholder={$i18n.t('Concurrent Requests')}
|
||||
bind:value={webConfig.WEB_LOADER_CONCURRENT_REQUESTS}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div class=" mb-2.5 flex w-full justify-between">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
{$i18n.t('Youtube Language')}
|
||||
|
||||
@@ -71,6 +71,10 @@
|
||||
params: true,
|
||||
file_upload: true,
|
||||
delete: true,
|
||||
delete_message: true,
|
||||
continue_response: true,
|
||||
regenerate_response: true,
|
||||
rate_response: true,
|
||||
edit: true,
|
||||
share: true,
|
||||
export: true,
|
||||
@@ -213,9 +217,9 @@
|
||||
{:else}
|
||||
<div>
|
||||
<div class=" flex items-center gap-3 justify-between text-xs uppercase px-1 font-bold">
|
||||
<div class="w-full basis-3/5">Group</div>
|
||||
<div class="w-full basis-3/5">{$i18n.t('Group')}</div>
|
||||
|
||||
<div class="w-full basis-2/5 text-right">Users</div>
|
||||
<div class="w-full basis-2/5 text-right">{$i18n.t('Users')}</div>
|
||||
</div>
|
||||
|
||||
<hr class="mt-1.5 border-gray-100 dark:border-gray-850" />
|
||||
|
||||
@@ -53,6 +53,10 @@
|
||||
params: true,
|
||||
file_upload: true,
|
||||
delete: true,
|
||||
delete_message: true,
|
||||
continue_response: true,
|
||||
regenerate_response: true,
|
||||
rate_response: true,
|
||||
edit: true,
|
||||
share: true,
|
||||
export: true,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<script>
|
||||
import { toast } from 'svelte-sonner';
|
||||
import { getContext } from 'svelte';
|
||||
import { onMount, getContext } from 'svelte';
|
||||
|
||||
const i18n = getContext('i18n');
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
import User from '$lib/components/icons/User.svelte';
|
||||
import UserCircleSolid from '$lib/components/icons/UserCircleSolid.svelte';
|
||||
import GroupModal from './EditGroupModal.svelte';
|
||||
import { querystringValue } from '$lib/utils';
|
||||
|
||||
export let users = [];
|
||||
export let group = {
|
||||
@@ -44,6 +45,13 @@
|
||||
setGroups();
|
||||
}
|
||||
};
|
||||
|
||||
onMount(() => {
|
||||
const groupId = querystringValue('id');
|
||||
if (groupId && groupId === group.id) {
|
||||
showEdit = true;
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<GroupModal
|
||||
|
||||
@@ -26,6 +26,10 @@
|
||||
params: true,
|
||||
file_upload: true,
|
||||
delete: true,
|
||||
delete_message: true,
|
||||
continue_response: true,
|
||||
regenerate_response: true,
|
||||
rate_response: true,
|
||||
edit: true,
|
||||
share: true,
|
||||
export: true,
|
||||
@@ -158,7 +162,7 @@
|
||||
<select
|
||||
class="w-full bg-transparent outline-hidden py-0.5 text-sm"
|
||||
bind:value={permissions.model.default_id}
|
||||
placeholder="Select a model"
|
||||
placeholder={$i18n.t('Select a model')}
|
||||
>
|
||||
<option value="" disabled selected>{$i18n.t('Select a model')}</option>
|
||||
{#each permissions.model.filter ? $models.filter( (model) => filterModelIds.includes(model.id) ) : $models.filter((model) => model.id) as model}
|
||||
@@ -292,6 +296,14 @@
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class=" flex w-full justify-between my-2 pr-2">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
{$i18n.t('Allow Chat Edit')}
|
||||
</div>
|
||||
|
||||
<Switch bind:state={permissions.chat.edit} />
|
||||
</div>
|
||||
|
||||
<div class=" flex w-full justify-between my-2 pr-2">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
{$i18n.t('Allow Chat Delete')}
|
||||
@@ -302,10 +314,34 @@
|
||||
|
||||
<div class=" flex w-full justify-between my-2 pr-2">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
{$i18n.t('Allow Chat Edit')}
|
||||
{$i18n.t('Allow Delete Messages')}
|
||||
</div>
|
||||
|
||||
<Switch bind:state={permissions.chat.edit} />
|
||||
<Switch bind:state={permissions.chat.delete_message} />
|
||||
</div>
|
||||
|
||||
<div class=" flex w-full justify-between my-2 pr-2">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
{$i18n.t('Allow Continue Response')}
|
||||
</div>
|
||||
|
||||
<Switch bind:state={permissions.chat.continue_response} />
|
||||
</div>
|
||||
|
||||
<div class=" flex w-full justify-between my-2 pr-2">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
{$i18n.t('Allow Regenerate Response')}
|
||||
</div>
|
||||
|
||||
<Switch bind:state={permissions.chat.regenerate_response} />
|
||||
</div>
|
||||
|
||||
<div class=" flex w-full justify-between my-2 pr-2">
|
||||
<div class=" self-center text-xs font-medium">
|
||||
{$i18n.t('Allow Rate Response')}
|
||||
</div>
|
||||
|
||||
<Switch bind:state={permissions.chat.rate_response} />
|
||||
</div>
|
||||
|
||||
<div class=" flex w-full justify-between my-2 pr-2">
|
||||
|
||||
@@ -166,12 +166,12 @@
|
||||
{#if total > $config?.license_metadata?.seats}
|
||||
<span class="text-lg font-medium text-red-500"
|
||||
>{total} of {$config?.license_metadata?.seats}
|
||||
<span class="text-sm font-normal">available users</span></span
|
||||
<span class="text-sm font-normal">{$i18n.t('available users')}</span></span
|
||||
>
|
||||
{:else}
|
||||
<span class="text-lg font-medium text-gray-500 dark:text-gray-300"
|
||||
>{total} of {$config?.license_metadata?.seats}
|
||||
<span class="text-sm font-normal">available users</span></span
|
||||
<span class="text-sm font-normal">{$i18n.t('available users')}</span></span
|
||||
>
|
||||
{/if}
|
||||
{:else}
|
||||
|
||||
@@ -104,7 +104,9 @@
|
||||
}
|
||||
}
|
||||
|
||||
toast.success(`Successfully imported ${userCount} users.`);
|
||||
toast.success(
|
||||
$i18n.t('Successfully imported {{userCount}} users.', { userCount: userCount })
|
||||
);
|
||||
inputFiles = null;
|
||||
const uploadInputElement = document.getElementById('upload-user-csv-input');
|
||||
|
||||
|
||||
@@ -4,7 +4,9 @@
|
||||
import { createEventDispatcher } from 'svelte';
|
||||
import { onMount, getContext } from 'svelte';
|
||||
|
||||
import { updateUserById } from '$lib/apis/users';
|
||||
import { goto } from '$app/navigation';
|
||||
|
||||
import { updateUserById, getUserGroupsById } from '$lib/apis/users';
|
||||
|
||||
import Modal from '$lib/components/common/Modal.svelte';
|
||||
import localizedFormat from 'dayjs/plugin/localizedFormat';
|
||||
@@ -27,6 +29,8 @@
|
||||
password: ''
|
||||
};
|
||||
|
||||
let userGroups: any[] | null = null;
|
||||
|
||||
const submitHandler = async () => {
|
||||
const res = await updateUserById(localStorage.token, selectedUser.id, _user).catch((error) => {
|
||||
toast.error(`${error}`);
|
||||
@@ -38,10 +42,21 @@
|
||||
}
|
||||
};
|
||||
|
||||
const loadUserGroups = async () => {
|
||||
if (!selectedUser?.id) return;
|
||||
userGroups = null;
|
||||
|
||||
userGroups = await getUserGroupsById(localStorage.token, selectedUser.id).catch((error) => {
|
||||
toast.error(`${error}`);
|
||||
return null;
|
||||
});
|
||||
};
|
||||
|
||||
onMount(() => {
|
||||
if (selectedUser) {
|
||||
_user = selectedUser;
|
||||
_user.password = '';
|
||||
loadUserGroups();
|
||||
}
|
||||
});
|
||||
</script>
|
||||
@@ -106,6 +121,30 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{#if userGroups}
|
||||
<div class="flex flex-col w-full text-sm">
|
||||
<div class="mb-1 text-xs text-gray-500">{$i18n.t('User Groups')}</div>
|
||||
|
||||
{#if userGroups.length}
|
||||
<div class="flex flex-wrap gap-1 my-0.5 -mx-1">
|
||||
{#each userGroups as userGroup}
|
||||
<span class="px-2 py-0.5 rounded-full bg-gray-100 dark:bg-gray-850 text-xs">
|
||||
<a
|
||||
href={'/admin/users/groups?id=' + userGroup.id}
|
||||
on:click|preventDefault={() =>
|
||||
goto('/admin/users/groups?id=' + userGroup.id)}
|
||||
>
|
||||
{userGroup.name}
|
||||
</a>
|
||||
</span>
|
||||
{/each}
|
||||
</div>
|
||||
{:else}
|
||||
<span>-</span>
|
||||
{/if}
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
<div class="flex flex-col w-full">
|
||||
<div class=" mb-1 text-xs text-gray-500">{$i18n.t('Email')}</div>
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
blobToFile,
|
||||
compressImage,
|
||||
extractInputVariables,
|
||||
getAge,
|
||||
getCurrentDateTime,
|
||||
getFormattedDate,
|
||||
getFormattedTime,
|
||||
@@ -31,6 +32,7 @@
|
||||
import FilesOverlay from '../chat/MessageInput/FilesOverlay.svelte';
|
||||
import Commands from '../chat/MessageInput/Commands.svelte';
|
||||
import InputVariablesModal from '../chat/MessageInput/InputVariablesModal.svelte';
|
||||
import { getSessionUser } from '$lib/apis/auths';
|
||||
|
||||
export let placeholder = $i18n.t('Send a Message');
|
||||
|
||||
@@ -116,11 +118,47 @@
|
||||
text = text.replaceAll('{{USER_LOCATION}}', String(location));
|
||||
}
|
||||
|
||||
const sessionUser = await getSessionUser(localStorage.token);
|
||||
|
||||
if (text.includes('{{USER_NAME}}')) {
|
||||
const name = $user?.name || 'User';
|
||||
const name = sessionUser?.name || 'User';
|
||||
text = text.replaceAll('{{USER_NAME}}', name);
|
||||
}
|
||||
|
||||
if (text.includes('{{USER_BIO}}')) {
|
||||
const bio = sessionUser?.bio || '';
|
||||
|
||||
if (bio) {
|
||||
text = text.replaceAll('{{USER_BIO}}', bio);
|
||||
}
|
||||
}
|
||||
|
||||
if (text.includes('{{USER_GENDER}}')) {
|
||||
const gender = sessionUser?.gender || '';
|
||||
|
||||
if (gender) {
|
||||
text = text.replaceAll('{{USER_GENDER}}', gender);
|
||||
}
|
||||
}
|
||||
|
||||
if (text.includes('{{USER_BIRTH_DATE}}')) {
|
||||
const birthDate = sessionUser?.date_of_birth || '';
|
||||
|
||||
if (birthDate) {
|
||||
text = text.replaceAll('{{USER_BIRTH_DATE}}', birthDate);
|
||||
}
|
||||
}
|
||||
|
||||
if (text.includes('{{USER_AGE}}')) {
|
||||
const birthDate = sessionUser?.date_of_birth || '';
|
||||
|
||||
if (birthDate) {
|
||||
// calculate age using date
|
||||
const age = getAge(birthDate);
|
||||
text = text.replaceAll('{{USER_AGE}}', age);
|
||||
}
|
||||
}
|
||||
|
||||
if (text.includes('{{USER_LANGUAGE}}')) {
|
||||
const language = localStorage.getItem('locale') || 'en-US';
|
||||
text = text.replaceAll('{{USER_LANGUAGE}}', language);
|
||||
|
||||
@@ -59,7 +59,7 @@
|
||||
>
|
||||
<div class="w-full flex justify-center py-1 text-xs animate-pulse items-center gap-2">
|
||||
<Spinner className=" size-4" />
|
||||
<div class=" ">Loading...</div>
|
||||
<div class=" ">{$i18n.t('Loading...')}</div>
|
||||
</div>
|
||||
</Loader>
|
||||
{:else if !thread}
|
||||
@@ -84,7 +84,7 @@
|
||||
</div>
|
||||
{:else}
|
||||
<div class="flex justify-center text-xs items-center gap-2 py-5">
|
||||
<div class=" ">Start of the channel</div>
|
||||
<div class=" ">{$i18n.t('Start of the channel')}</div>
|
||||
</div>
|
||||
{/if}
|
||||
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
<script lang="ts">
|
||||
import { DropdownMenu } from 'bits-ui';
|
||||
import { getContext } from 'svelte';
|
||||
|
||||
const i18n = getContext('i18n');
|
||||
|
||||
import { flyAndScale } from '$lib/utils/transitions';
|
||||
import { WEBUI_BASE_URL } from '$lib/constants';
|
||||
@@ -76,7 +79,7 @@
|
||||
</div>
|
||||
|
||||
<div class=" -translate-y-[1px]">
|
||||
<span class="text-xs"> Active </span>
|
||||
<span class="text-xs"> {$i18n.t('Active')} </span>
|
||||
</div>
|
||||
{:else}
|
||||
<div>
|
||||
@@ -86,7 +89,7 @@
|
||||
</div>
|
||||
|
||||
<div class=" -translate-y-[1px]">
|
||||
<span class="text-xs"> Away </span>
|
||||
<span class="text-xs"> {$i18n.t('Away')} </span>
|
||||
</div>
|
||||
{/if}
|
||||
</div>
|
||||
|
||||
@@ -1,11 +1,18 @@
|
||||
<script lang="ts">
|
||||
import { DropdownMenu } from 'bits-ui';
|
||||
import VirtualList from '@sveltejs/svelte-virtual-list';
|
||||
|
||||
import { getContext } from 'svelte';
|
||||
|
||||
import { flyAndScale } from '$lib/utils/transitions';
|
||||
import { WEBUI_BASE_URL } from '$lib/constants';
|
||||
|
||||
import Tooltip from '$lib/components/common/Tooltip.svelte';
|
||||
|
||||
import emojiGroups from '$lib/emoji-groups.json';
|
||||
import emojiShortCodes from '$lib/emoji-shortcodes.json';
|
||||
import Tooltip from '$lib/components/common/Tooltip.svelte';
|
||||
import VirtualList from '@sveltejs/svelte-virtual-list';
|
||||
import { WEBUI_BASE_URL } from '$lib/constants';
|
||||
|
||||
const i18n = getContext('i18n');
|
||||
|
||||
export let onClose = () => {};
|
||||
export let onSubmit = (name) => {};
|
||||
@@ -118,14 +125,16 @@
|
||||
<input
|
||||
type="text"
|
||||
class="w-full text-sm bg-transparent outline-hidden"
|
||||
placeholder="Search all emojis"
|
||||
placeholder={$i18n.t('Search all emojis')}
|
||||
bind:value={search}
|
||||
/>
|
||||
</div>
|
||||
<!-- Virtualized Emoji List -->
|
||||
<div class="w-full flex justify-start h-96 overflow-y-auto px-3 pb-3 text-sm">
|
||||
{#if emojiRows.length === 0}
|
||||
<div class="text-center text-xs text-gray-500 dark:text-gray-400">No results</div>
|
||||
<div class="text-center text-xs text-gray-500 dark:text-gray-400">
|
||||
{$i18n.t('No results')}
|
||||
</div>
|
||||
{:else}
|
||||
<div class="w-full flex ml-0.5">
|
||||
<VirtualList rowHeight={ROW_HEIGHT} items={emojiRows} height={384} let:item>
|
||||
|
||||
@@ -8,9 +8,11 @@
|
||||
import XMark from '$lib/components/icons/XMark.svelte';
|
||||
import MessageInput from './MessageInput.svelte';
|
||||
import Messages from './Messages.svelte';
|
||||
import { onDestroy, onMount, tick } from 'svelte';
|
||||
import { onDestroy, onMount, tick, getContext } from 'svelte';
|
||||
import { toast } from 'svelte-sonner';
|
||||
|
||||
const i18n = getContext('i18n');
|
||||
|
||||
export let threadId = null;
|
||||
export let channel = null;
|
||||
|
||||
@@ -158,7 +160,7 @@
|
||||
{#if channel}
|
||||
<div class="flex flex-col w-full h-full bg-gray-50 dark:bg-gray-850">
|
||||
<div class="flex items-center justify-between px-3.5 pt-3">
|
||||
<div class=" font-medium text-lg">Thread</div>
|
||||
<div class=" font-medium text-lg">{$i18n.t('Thread')}</div>
|
||||
|
||||
<div>
|
||||
<button
|
||||
|
||||
@@ -204,7 +204,10 @@
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class=" w-full h-full relative flex flex-col bg-gray-50 dark:bg-gray-850">
|
||||
<div
|
||||
class=" w-full h-full relative flex flex-col bg-gray-50 dark:bg-gray-850"
|
||||
id="artifacts-container"
|
||||
>
|
||||
<div class="w-full h-full flex flex-col flex-1 relative">
|
||||
{#if contents.length > 0}
|
||||
<div
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user