Compare commits

..

866 Commits

Author SHA1 Message Date
Timothy Jaeryang Baek be5534c655 Merge pull request #2376 from open-webui/dev
Create and publish Docker images with specific build args / build-main-image (linux/amd64) (push) Waiting to run
Create and publish Docker images with specific build args / build-main-image (linux/arm64) (push) Waiting to run
Create and publish Docker images with specific build args / build-cuda-image (linux/amd64) (push) Waiting to run
Create and publish Docker images with specific build args / build-cuda-image (linux/arm64) (push) Waiting to run
Create and publish Docker images with specific build args / build-ollama-image (linux/amd64) (push) Waiting to run
Create and publish Docker images with specific build args / build-ollama-image (linux/arm64) (push) Waiting to run
Create and publish Docker images with specific build args / merge-main-images (push) Blocked by required conditions
Create and publish Docker images with specific build args / merge-cuda-images (push) Blocked by required conditions
Create and publish Docker images with specific build args / merge-ollama-images (push) Blocked by required conditions
0.1.125
2024-05-19 10:16:36 -10:00
Timothy J. Baek bcc2bab623 refac 2024-05-19 13:15:41 -07:00
Timothy J. Baek 0260c714d9 refac 2024-05-19 13:11:56 -07:00
Timothy Jaeryang Baek 009e85d56e Merge pull request #2394 from Yanyutin753/tem-tran
 add translations in shortcut
2024-05-19 09:20:55 -10:00
Timothy J. Baek 4d27ecef1e fix 2024-05-19 12:06:58 -07:00
Timothy J. Baek 6e6302a4a2 fix 2024-05-19 12:00:10 -07:00
Timothy J. Baek 2abbc9092e fix 2024-05-19 11:54:55 -07:00
Timothy J. Baek 4922b65753 Update Personalization.svelte 2024-05-19 11:51:32 -07:00
Timothy J. Baek 8163902ad1 fix: styling 2024-05-19 11:43:13 -07:00
Yanyutin753 0f4492114f fix Fomat & Build Frontend 2024-05-20 01:11:50 +08:00
Yanyutin753 bb6b363875 add translations in shortcut 2024-05-20 01:11:50 +08:00
Timothy J. Baek e36be75754 Update CodeBlock.svelte 2024-05-19 10:07:43 -07:00
Timothy J. Baek ec93fd15c3 Update CHANGELOG.md 2024-05-19 09:48:22 -07:00
Timothy J. Baek 5961fc84f4 feat: seaborn added to pyodide
Co-Authored-By: Silentoplayz <50341825+Silentoplayz@users.noreply.github.com>
2024-05-19 09:46:43 -07:00
Timothy J. Baek a5fa881d4a Update CHANGELOG.md
Co-Authored-By: Silentoplayz <50341825+Silentoplayz@users.noreply.github.com>
2024-05-19 09:34:47 -07:00
Timothy J. Baek 4fe237da58 Update CHANGELOG.md
Co-Authored-By: Silentoplayz <50341825+Silentoplayz@users.noreply.github.com>
2024-05-19 09:30:56 -07:00
Timothy J. Baek 6139d775ef feat: clear memory 2024-05-19 09:26:24 -07:00
Timothy J. Baek 8f83f51c68 chore: format 2024-05-19 09:18:30 -07:00
Timothy J. Baek 4754e5c062 doc: changelog 2024-05-19 09:17:11 -07:00
Timothy J. Baek 5b08dc56af chore: format 2024-05-19 09:01:48 -07:00
Timothy J. Baek 8ec3934599 fix: memory 2024-05-19 08:53:28 -07:00
Timothy J. Baek 0d07d10bd8 fix 2024-05-19 08:47:37 -07:00
Timothy J. Baek bbdfcd18e1 fix 2024-05-19 08:46:39 -07:00
Timothy J. Baek febab58821 feat: memory integration 2024-05-19 08:40:46 -07:00
Timothy J. Baek 2638ae6a93 chore: format 2024-05-19 08:15:44 -07:00
Timothy J. Baek a8c4588fb5 feat: memory integration 2024-05-19 08:14:04 -07:00
Timothy J. Baek 288d8a3e32 feat: memory backend 2024-05-19 08:00:07 -07:00
Timothy J. Baek 1fb5ef99e2 refac 2024-05-19 07:40:54 -07:00
Timothy J. Baek ae35c68956 refac: styling 2024-05-19 07:37:14 -07:00
Timothy J. Baek 9ff74038b5 refac: styling 2024-05-19 07:32:19 -07:00
Timothy J. Baek 8c64f0627c fix: styling 2024-05-19 07:05:38 -07:00
Timothy J. Baek 5376525777 refac 2024-05-19 06:51:32 -07:00
Timothy J. Baek 82bd1eb155 refac 2024-05-19 06:51:21 -07:00
Timothy J. Baek 120f8d7786 refac: regenerate behaviour 2024-05-19 05:53:43 -07:00
Timothy Jaeryang Baek b9b25f872d Merge pull request #2391 from que-nguyen/dev
Fixed translation errors in Vietnamese locale file
2024-05-19 02:36:31 -10:00
Timothy Jaeryang Baek 123620bcc4 Merge branch 'dev' into dev 2024-05-19 02:36:18 -10:00
Timothy J. Baek dbdf83c55f refac: styling 2024-05-19 05:22:09 -07:00
Timothy J. Baek 066789d423 refac: pyodide worker error handling 2024-05-19 05:19:48 -07:00
Timothy J. Baek 78cbdbc63f fix: code block execution 2024-05-19 05:16:31 -07:00
Timothy J. Baek d2249921aa refac: styling 2024-05-19 05:06:13 -07:00
Timothy J. Baek f8815b0749 chore: format 2024-05-19 05:01:57 -07:00
Timothy J. Baek 68104358d0 fix: many model regeneration 2024-05-19 05:01:29 -07:00
Timothy J. Baek 676a4dffd0 feat: many model interaction ui 2024-05-19 04:46:35 -07:00
Timothy Jaeryang Baek 0ede1d1483 Merge pull request #2388 from Yanyutin753/uploadImage
 Expend upload image file types
2024-05-19 01:40:08 -10:00
Yanyutin753 c5f13cfdda Expend upload image file types 2024-05-19 19:10:00 +08:00
Que Nguyen 99dd81d700 "Fixed translation errors in Vietnamese locale file
Fixed translation errors in Vietnamese locale file locales/vi-VN/translation.json.
2024-05-19 16:24:40 +07:00
Timothy J. Baek 22d23afbaf feat: memory ui frontend 2024-05-19 00:17:40 -07:00
Timothy J. Baek b521a06b5f fix: styling
Co-Authored-By: Jannik S. <69747628+jannikstdl@users.noreply.github.com>
2024-05-19 00:14:23 -07:00
Timothy Jaeryang Baek 6d2785d58a Merge pull request #2384 from kostich/main
Update Serbian translation
2024-05-18 21:11:17 -10:00
Марко М. Костић (Marko M. Kostić) 3cd0141957 Update Serbian translation 2024-05-19 09:02:30 +02:00
Timothy Jaeryang Baek 4edef53169 Merge pull request #2374 from Silentoplayz/Silentoplayz-Ineedtonamethesebetter
Update pull_request_template.md once more
2024-05-18 13:13:23 -10:00
Timothy J. Baek 9a92ae78c8 fix: hide show username interface option 2024-05-18 16:11:28 -07:00
Timothy J. Baek 8dac4e91a5 fix: share chat issue 2024-05-18 15:23:36 -07:00
Timothy J. Baek 1e6ddb2fb3 chore: format 2024-05-18 15:02:47 -07:00
Silentoplayz e5207e098e Update pull_request_template.md
Note to first-time contributors to open a discussion post before submitting a PR
2024-05-18 21:46:38 +00:00
Timothy J. Baek 1b6700425a fix 2024-05-18 14:29:39 -07:00
Timothy J. Baek 8766d2699a refac: include packages 2024-05-18 14:28:16 -07:00
Timothy J. Baek 7f90d813bd feat: more libs for pyodide 2024-05-18 14:24:32 -07:00
Timothy J. Baek a8b92e5e9d fix: display username in shared chats 2024-05-18 14:19:48 -07:00
Silentoplayz 0349c86448 Update pull_request_template.md
Added Screenshots or Videos section
2024-05-18 21:17:42 +00:00
Timothy J. Baek 75491b2f87 fix: rtl styling 2024-05-18 14:04:35 -07:00
Timothy Jaeryang Baek 9e60d03911 Merge pull request #2318 from idomamia/feat/rtl-layout-chat-support
Add RTL layout chat support
2024-05-18 10:57:35 -10:00
Timothy Jaeryang Baek 04925407b2 Merge pull request #2369 from kostich/main
Adds the Serbian translation
2024-05-18 10:54:40 -10:00
Timothy J. Baek a121ae2c5d chore: format 2024-05-18 13:54:13 -07:00
Timothy Jaeryang Baek 86eafdf5e4 Merge pull request #2370 from sime2408/feature/translation-croatian
translation to croatian
2024-05-18 10:47:41 -10:00
Timothy Jaeryang Baek 12d59b6184 Merge pull request #2366 from cheahjs/refac/pyscript-npm
refac: fetch pyodide deps at build time, not checked into git
2024-05-18 10:47:34 -10:00
Timothy Jaeryang Baek 6f6b18e727 Merge pull request #2368 from cheahjs/fix/case-insensitive-model-search
fix: case insensitive model search
2024-05-18 10:44:07 -10:00
sime2408 719a8a9327 translation to croatian 2024-05-18 21:31:44 +02:00
Марко М. Костић (Marko M. Kostić) b8b9cab529 More fixes 2024-05-18 17:29:41 +02:00
Марко М. Костић (Marko M. Kostić) 8a0fa0b493 Fix translation 2024-05-18 17:27:40 +02:00
Марко М. Костић (Marko M. Kostić) 0176edd4c7 Initial Serbian Translation 2024-05-18 14:56:08 +02:00
Jun Siang Cheah f9587032de fix: case insensitive model search 2024-05-18 19:59:29 +08:00
Марко М. Костић (Marko M. Kostić) 4e43d31604 Initial new translation 2024-05-18 13:39:48 +02:00
Ido Henri Mamia 27c59d985f Merge branch 'dev' into feat/rtl-layout-chat-support 2024-05-18 13:58:53 +03:00
Jun Siang Cheah 781c904c91 refac: fetch pyodide deps at build time, not checked into git 2024-05-18 14:30:42 +08:00
Timothy J. Baek 400bfa5a02 fix: rag config.json 2024-05-17 19:53:38 -07:00
Timothy J. Baek 7facfa33d0 fix: litellm model filtering 2024-05-17 19:47:52 -07:00
Timothy J. Baek 3aa6b0fea9 fix: model filter issue 2024-05-17 19:11:14 -07:00
Timothy Jaeryang Baek 3890ea1490 Merge pull request #2240 from justinh-rahb/i18n-punjabi
Add Punjabi (India) language
2024-05-17 08:18:00 -10:00
Timothy J. Baek af5b2ddb01 fix: typo 2024-05-17 11:17:17 -07:00
Timothy J. Baek 5b2369da5d fix: #2332 2024-05-17 10:56:16 -07:00
Timothy J. Baek 014e52c072 fix: connection timeout 2024-05-17 10:49:12 -07:00
Timothy J. Baek fa54eb687e refac: switch styling 2024-05-17 10:45:50 -07:00
Timothy J. Baek 8181ae3918 fix 2024-05-17 10:35:33 -07:00
Timothy J. Baek cdbabdfa5a refac 2024-05-17 10:30:22 -07:00
Justin Hayes 400deb90b4 Reverting to mispelling from source 2024-05-17 10:55:23 -04:00
Justin Hayes 2c44443f93 Added new strings 2024-05-17 10:52:23 -04:00
Ido Henri Mamia e5d574307e Merge branch 'dev' of https://github.com/open-webui/open-webui into feat/rtl-layout-chat-support 2024-05-17 13:04:03 +03:00
Ido Henri Mamia 92c694e8ac Fix arrows to be in LTR layout for all layouts 2024-05-17 13:00:31 +03:00
Timothy J. Baek 6e19e46b07 refac: styling 2024-05-16 23:20:21 -10:00
Timothy J. Baek aa9f3d0632 refac: styling 2024-05-16 23:19:31 -10:00
Timothy J. Baek 85b2a63b6d fix: matplotlib 2024-05-16 23:15:39 -10:00
Timothy J. Baek ef300248ba feat: matplotlib support 2024-05-16 22:54:37 -10:00
Timothy J. Baek 548160c739 refac: time limit to 60sec 2024-05-16 22:39:46 -10:00
Timothy J. Baek a4630a9825 feat: code execution time limit 2024-05-16 22:39:07 -10:00
Timothy J. Baek c7221983a5 fix: input prompt message 2024-05-16 21:09:53 -10:00
Timothy J. Baek c7e1d3dbc7 fix 2024-05-16 21:03:59 -10:00
Timothy J. Baek 5e3c801c44 refac: no output 2024-05-16 20:53:50 -10:00
Timothy J. Baek b27b035caa refac: disable run button when code is running 2024-05-16 20:47:13 -10:00
Timothy Jaeryang Baek a2933bf89d Merge pull request #2328 from cheahjs/fix/image-gen-after-config-refac
fix: image generation broken by config persistence
2024-05-16 20:39:21 -10:00
Timothy J. Baek 302a17b3ed feat: code input support 2024-05-16 20:35:25 -10:00
Timothy J. Baek 01a656cc80 feat: numpy, pandas support 2024-05-16 20:25:55 -10:00
Jun Siang Cheah 51a41c8db4 fix: image generation broken by config persistence 2024-05-17 13:52:48 +08:00
Timothy J. Baek 6dedf9885f fix: code execution error handling 2024-05-16 19:30:09 -10:00
Timothy J. Baek 4efb8638ff refac 2024-05-16 19:22:10 -10:00
Timothy J. Baek 8f8ce26948 refac: migrated to pyodide from pyscript 2024-05-16 19:21:08 -10:00
Timothy J. Baek 0a9092156c chore: format 2024-05-16 18:21:19 -10:00
Timothy Jaeryang Baek 4950feded4 Merge pull request #2325 from open-webui/pyscript
feat: python code execution
2024-05-16 18:18:03 -10:00
Timothy Jaeryang Baek 7db4baeffa Merge pull request #2322 from cheahjs/feat/unsupported-nonroot-images
feat: optional UID/GID docker build args
2024-05-16 18:13:46 -10:00
Timothy J. Baek 18a7634f5c fix: python code execution 2024-05-16 18:05:43 -10:00
Timothy J. Baek 325fd2b97b refac: styling 2024-05-16 17:55:27 -10:00
Timothy J. Baek 1140036f20 feat: python error handling 2024-05-16 17:55:07 -10:00
Timothy J. Baek 58a13aec7e feat: python code execution 2024-05-16 17:49:28 -10:00
Jun Siang Cheah 1dc80786c1 feat: optional UID/GID docker build args 2024-05-17 09:44:52 +08:00
Timothy J. Baek ba61f87a2f feat: settings personalization tab ui 2024-05-16 14:25:48 -10:00
Ido Henri Mamia 34dd32d48f Merge branch 'dev' of https://github.com/open-webui/open-webui into feat/rtl-layout-chat-support 2024-05-17 01:22:46 +03:00
Ido Henri Mamia 3f4eb6caa2 Merge branch 'dev' of https://github.com/open-webui/open-webui into feat/rtl-layout-chat-support 2024-05-17 01:22:23 +03:00
Ido Henri Mamia 2e77ad87cc Make the margin and avatar support both LTR and RTL 2024-05-16 23:29:33 +03:00
Ido Henri Mamia 97f1d1665a Add to the i18n the chat direction text 2024-05-16 23:28:44 +03:00
Ido Henri Mamia 4ccb5d39c7 Code blocks should be in LTR layout for all layouts 2024-05-16 23:27:33 +03:00
Ido Henri Mamia 16b218e686 Add layout direction to all the chat components 2024-05-16 23:26:36 +03:00
Ido Henri Mamia a3a832a935 Add chat direction toggle button in the interface settings 2024-05-16 23:22:30 +03:00
Ido Henri Mamia 9c389df727 Add chat direction to the settings store 2024-05-16 23:14:54 +03:00
Timothy J. Baek e29a999dc9 fix: add user modal error handling 2024-05-15 19:01:02 -10:00
Justin Hayes b423e442d7 run i18next-parser 2024-05-15 23:23:29 -04:00
Justin Hayes d7ce488c42 Add newline 2024-05-15 23:12:46 -04:00
Justin Hayes e7a7caf911 Add pa-IN to languages.json 2024-05-15 23:12:45 -04:00
Justin Hayes 4a549f0c76 Add Punjabi (India) translations 2024-05-15 23:12:45 -04:00
Timothy Jaeryang Baek e979584298 Merge pull request #2296 from ChasLui/dev
feat: Add Chinese Simplified Translation
2024-05-15 17:06:56 -10:00
Timothy Jaeryang Baek 19203a8ed7 Merge pull request #2295 from cheahjs/fix/missing-jq
fix: add missing jq in non-ollama images
2024-05-15 17:06:46 -10:00
ChasLui 630c4d8bc6 fix: i18n zh-CN 2024-05-16 11:02:27 +08:00
Jun Siang Cheah b6d36ab638 fix: add missing jq in non-ollama images 2024-05-16 10:45:00 +08:00
Timothy J. Baek e6d20df463 refac: styling 2024-05-15 16:42:55 -10:00
Timothy J. Baek de0f31680c Update General.svelte
#2292
2024-05-15 15:24:57 -10:00
Timothy J. Baek 39f91e39a7 feat: openwebui community backward compatibility 2024-05-15 14:40:52 -10:00
Timothy J. Baek 967277f1d5 refac: styling 2024-05-15 12:55:13 -10:00
Timothy J. Baek f7fcf95689 Update UserMessage.svelte
c
2024-05-15 12:42:43 -10:00
Timothy J. Baek f2378be6f9 feat: toggleable chat bubble 2024-05-15 12:39:41 -10:00
Timothy J. Baek db158fc9e1 Update Dockerfile 2024-05-15 08:44:10 -10:00
Timothy Jaeryang Baek e30166118c Merge pull request #2264 from iits-jonathan-rohde/fix/share-chat-reactive-loop
fix: prevent loop when fetching shared chat id
2024-05-15 08:40:40 -10:00
Timothy Jaeryang Baek 9381113f60 Update Menu.svelte 2024-05-15 13:40:25 -05:00
Timothy Jaeryang Baek 85dbdd23fc Merge branch 'dev' into fix/share-chat-reactive-loop 2024-05-15 08:38:59 -10:00
Timothy Jaeryang Baek ea812a3bb8 Merge pull request #2281 from cheahjs/fix/settings-cypress
fix: settings cypress test after style changes
2024-05-15 08:34:17 -10:00
Timothy J. Baek 240cbda06c fix: draggable items in sidebar 2024-05-15 08:27:52 -10:00
Timothy J. Baek d4c193060e fix: styling 2024-05-15 08:20:36 -10:00
Timothy J. Baek 7d62993007 refac: healthcheck endpoint 2024-05-15 08:17:18 -10:00
Timothy J. Baek 8f5c671e4c refac: sidebar breakpoint 2024-05-15 08:13:14 -10:00
Jun Siang Cheah 8d4c9c77bf fix: settings cypress test after style changes 2024-05-15 23:49:26 +08:00
Timothy J. Baek b263e24e56 refac: styling 2024-05-15 00:19:10 -10:00
Timothy J. Baek 290b4e56c8 fix: styling 2024-05-14 23:57:32 -10:00
Timothy J. Baek cf9dbea370 fix: styling 2024-05-14 23:50:50 -10:00
Timothy J. Baek 0722e4b690 refac: user message styling 2024-05-14 23:45:27 -10:00
Timothy J. Baek 308a2e1de0 refac: styling 2024-05-14 22:22:15 -10:00
Timothy J. Baek 13019acce6 refac: styling 2024-05-14 22:09:32 -10:00
Timothy J. Baek aaaef3efd8 fix: unselectable sidebar
Co-Authored-By: Javier Leandro Arancibia <arancibiajav@gmail.com>
Co-Authored-By: Maksym Dmukhovskyy <25328501+maxdyy@users.noreply.github.com>
2024-05-14 21:29:22 -10:00
Timothy J. Baek 5079d5ec87 refac: styling 2024-05-14 21:26:54 -10:00
Timothy J. Baek 1d98099099 refac: admin panel styling 2024-05-14 20:48:46 -10:00
Timothy J. Baek e9decf2dda refac: styling 2024-05-14 20:31:22 -10:00
Timothy J. Baek 210456e424 refac: styling 2024-05-14 20:21:22 -10:00
Timothy J. Baek c45bb64de7 refac: styling 2024-05-14 20:16:22 -10:00
Jonathan Rohde ea6f1a0e57 Merge branch 'dev' into fix/share-chat-reactive-loop 2024-05-15 07:59:45 +02:00
Timothy J. Baek a57a01a598 refac: navbar styling 2024-05-14 14:50:24 -10:00
Timothy J. Baek 170361c27e refac: styling 2024-05-14 14:39:48 -10:00
Timothy J. Baek c489d473b9 refac: styling 2024-05-14 14:38:37 -10:00
Timothy J. Baek de75679ffb fix: sidebar model selector issue 2024-05-14 12:26:53 -10:00
Timothy J. Baek ad67339426 fix: sidebar 2024-05-14 12:17:56 -10:00
Timothy J. Baek d88cc6007c refac: styling 2024-05-14 12:15:01 -10:00
Timothy J. Baek 370f182430 refac: styling 2024-05-14 12:11:57 -10:00
Timothy J. Baek 39fdd95a0c refac: styling 2024-05-14 12:09:30 -10:00
Timothy Jaeryang Baek e6ff5af38a Merge pull request #2267 from maxdyy/fix/it-translation-update
fix: added missing translations for italian it-IT
2024-05-14 08:41:13 -10:00
Timothy Jaeryang Baek 767ae3be5b Merge pull request #2161 from cheahjs/fix/handlebars-harden
feat: add {{prompt:middletruncate:<length>}} to title gen
2024-05-14 08:21:39 -10:00
Timothy Jaeryang Baek 564a3a293f Merge branch 'dev' into fix/handlebars-harden 2024-05-14 08:21:26 -10:00
Maksym Dmukhovskyy 9ad4605e57 fix: added missing translations for italian 2024-05-14 20:56:04 +04:00
Jonathan Rohde 33b9629164 fix: prevent loop when fetching shared chat id 2024-05-14 16:19:37 +02:00
Timothy Jaeryang Baek 2290eefcb0 Merge pull request #2249 from cheahjs/fix/config-refac-broken
fix: rag, chat deletion, and webhook after config persistence change
2024-05-13 21:07:17 -10:00
Jun Siang Cheah 5369023e34 fix: rag, chat deletion, and webhook after config persistence change 2024-05-14 14:30:15 +08:00
Timothy Jaeryang Baek 233dcb2d95 Merge pull request #2242 from bo3bdo/main
Update Arabic language
2024-05-13 14:34:15 -10:00
Timothy Jaeryang Baek edbe5673c5 Merge branch 'dev' into main 2024-05-13 14:33:51 -10:00
HAMAD ABDULLA 1114f9625b Update translation.json 2024-05-14 01:59:17 +03:00
HAMAD ABDULLA f42819c6ad Update Arabic language 2024-05-14 01:49:04 +03:00
Timothy Jaeryang Baek 8b0144cd06 Merge pull request #2156 from cheahjs/feat/save-config
feat: save UI config changes to config.json
2024-05-13 11:45:30 -10:00
Timothy J. Baek 0c033b5b7b refac: rename 2024-05-13 11:32:21 -10:00
Timothy J. Baek 7e0d3496b5 fix: 1st #2208 2024-05-13 11:27:58 -10:00
Timothy Jaeryang Baek 1888327a79 Merge pull request #2150 from derek-palmer/docker-compose-version-obsolete
Removed version syntax as its no longer needed per Docker Docs
2024-05-13 10:59:54 -10:00
Timothy Jaeryang Baek fabcbc300f Merge pull request #2211 from arsaboo/header
chore: add HTTP-Referer and X-Title headers for Open WebUI
2024-05-13 10:58:48 -10:00
Timothy Jaeryang Baek 4f87512bbc Merge pull request #2236 from akx/error-page-fix
fix: load i18n before showing error page
2024-05-13 10:58:31 -10:00
Timothy J. Baek b5c759a059 chore: format 2024-05-13 10:56:30 -10:00
Aarni Koskela df167d8785 fix: load i18n for /error page 2024-05-13 18:00:30 +03:00
Alok Saboo bd82334647 chore: add additional headers only for Openrouter 2024-05-13 08:28:24 -04:00
Timothy Jaeryang Baek 8e5f96e4c3 Merge pull request #2157 from joecryptotoo/healthcheck
add healthcheck to docker
2024-05-12 14:28:59 -10:00
Timothy Jaeryang Baek 88a94cc50d Merge pull request #2183 from cheahjs/fix/streaming-error
feat: better handle openai errors, add error message to message
2024-05-12 14:28:13 -10:00
Timothy Jaeryang Baek ba13321728 Merge pull request #2186 from cheahjs/fix/windows-prettier
fix: prettier scripts work on windows
2024-05-12 14:27:48 -10:00
Timothy Jaeryang Baek 4756511aea Merge pull request #2192 from xraysight/fix/pl-translation-update
fix: added missing translations and corrected some spelling errors
2024-05-12 14:27:14 -10:00
Timothy Jaeryang Baek 543f2652c2 Merge branch 'dev' into fix/pl-translation-update 2024-05-12 14:27:00 -10:00
Timothy Jaeryang Baek 4bd999af81 Merge pull request #2196 from Silentoplayz/PR-template-update
style: update pull_request_template.md again
2024-05-12 14:26:11 -10:00
Timothy Jaeryang Baek 807be35d9f Merge pull request #2195 from not-a-ethan/not-a-ethan-patch-1
Fixed some formatting and a link
2024-05-12 14:25:26 -10:00
Timothy Jaeryang Baek 4997c8259b Merge pull request #2201 from liorkesos/main
Hebrew language support
2024-05-12 14:23:56 -10:00
Timothy Jaeryang Baek 227a3a0d86 Merge pull request #2202 from aguvener/dev
fix: tr_TR translation synchronized with the latest updates.
2024-05-12 14:23:40 -10:00
Timothy Jaeryang Baek e483aae1b8 Merge branch 'dev' into dev 2024-05-12 14:23:33 -10:00
Timothy Jaeryang Baek 7b864d967d Merge pull request #2203 from simonaszilinskas/patch-2
Addition of the Lithuanian language
2024-05-12 14:20:23 -10:00
Timothy Jaeryang Baek ca985cdb07 Merge pull request #2154 from Yanyutin753/citation-translate
🎖️Added translations for Citation and No source available
2024-05-12 14:19:42 -10:00
Timothy Jaeryang Baek eb87de9a63 Merge pull request #2124 from tcztzy/main
changed: replace deprecated `on_event` with `lifespan`
2024-05-12 14:18:35 -10:00
Alok Saboo 6671e5f170 chore: add HTTP-Referer and X-Title headers for Open WebUI 2024-05-12 14:05:38 -04:00
Simonas 5e5473c792 Create and fill translation.json for Lithuanian 2024-05-12 15:13:41 +02:00
aguvener 09357b6e81 fix: update tr_TR translation with the latest updates. 2024-05-12 12:50:03 +03:00
aguvener b63aca534b Update translation.json 2024-05-12 12:41:08 +03:00
Lior Kesos 31cb6c9857 Adding hebrew translation 2024-05-12 10:59:47 +03:00
Jun Siang Cheah 5d64822c84 refac: rename WrappedConfig to PersistedConfig 2024-05-12 13:28:40 +08:00
Silentoplayz 8e94db0d1b Update pull_request_template.md
Update Open WebUI pull request template to the latest version, striving to follow KeepaChangelog and Conventional Commits guidelines.
2024-05-12 02:38:40 +00:00
Ethan 4fa8d2aa5a Fixed link/formatting 2024-05-12 01:33:49 +00:00
bulek 3a4f3e97e7 Added missing translations and corrected some spelling errors 2024-05-11 21:31:31 +02:00
Jun Siang Cheah 55060045da feat: add .gitignore to .prettierignore 2024-05-11 23:55:06 +08:00
Jun Siang Cheah e3e037e187 fix: windows invocations of prettier 2024-05-11 17:43:53 +08:00
Jun Siang Cheah 3113825895 feat: better handle openai errors, add error message to message 2024-05-11 16:34:04 +08:00
Yanyutin753 d2954f8eb6 feat format 2024-05-11 09:33:31 +08:00
Jun Siang Cheah a789b785b4 feat: add unit tests for prompt templates 2024-05-10 20:41:22 +08:00
Jun Siang Cheah 34a6d55505 feat: add {{prompt:middletruncate:<length>}} to title gen
also harden the replacement logic
2024-05-10 20:17:41 +08:00
Jun Siang Cheah a0dceb06a5 fix: nested WrappedConfig breaks things 2024-05-10 15:20:22 +08:00
Jun Siang Cheah 298e6848b3 feat: switch to config proxy, remove config_get/set 2024-05-10 15:03:24 +08:00
Jun Siang Cheah f712c90019 feat: raise an exception if a WrappedConfig is used as a response 2024-05-10 14:18:39 +08:00
Jun Siang Cheah 058eb76568 feat: save UI config changes to config.json 2024-05-10 13:51:50 +08:00
Yanyutin753 a374405911 🎖️Added translations for Citation and No source available 2024-05-10 12:23:12 +08:00
joecryptotoo ef8070d35d added healthcheck 2024-05-09 12:25:26 -07:00
Derek Palmer (Creative) 93aea0a4d4 Removed version synatax as its no longer needed per Docker Docs 2024-05-09 14:54:26 -04:00
Timothy J. Baek 9a95767062 Merge branch 'dev' of https://github.com/open-webui/open-webui into dev 2024-05-08 23:20:53 -10:00
Timothy J. Baek c1fc7bc764 fix: citation styling 2024-05-09 00:36:29 -07:00
Timothy J. Baek 038b6af813 refac: user menu 2024-05-09 00:34:57 -07:00
Tang Ziya 1d9c745b35 fix: replace deprecated on_event with lifespan 2024-05-09 12:04:09 +08:00
Timothy Jaeryang Baek df3675aaf7 Merge pull request #2104 from Silentoplayz/translation-update
Updated uk-UA/translation.json
2024-05-08 17:42:07 -07:00
Timothy J. Baek 685ee9b714 chore: format 2024-05-08 17:41:55 -07:00
Timothy Jaeryang Baek 90503be2ed Merge pull request #2118 from open-webui/dev
fix
2024-05-08 17:17:38 -07:00
Timothy J. Baek 26ee547f71 fix 2024-05-08 17:17:21 -07:00
Timothy Jaeryang Baek 734e62b865 Merge pull request #2117 from open-webui/dev
fix
2024-05-08 17:16:09 -07:00
Timothy J. Baek 01e020d1ad fix 2024-05-08 17:15:54 -07:00
Timothy Jaeryang Baek 943c49a07a Merge pull request #2116 from open-webui/dev
fix
2024-05-08 16:43:08 -07:00
Timothy J. Baek 88e8f31c07 fix: webui_auth permission issue 2024-05-08 16:42:41 -07:00
Timothy J. Baek 1c2aa10796 refac: disable enable_signup if webui_auth false 2024-05-08 16:33:34 -07:00
Timothy Jaeryang Baek 78c2f16c3c Merge pull request #2115 from open-webui/dev
enhancement: youtu.be url support
2024-05-08 16:30:41 -07:00
Timothy J. Baek bcd5853ce7 enhancement: youtu.be url support 2024-05-08 16:29:25 -07:00
Timothy Jaeryang Baek 61ffbf5b5b Merge pull request #2114 from open-webui/dev
fix: trusted header
2024-05-08 16:20:43 -07:00
Timothy J. Baek 58cfa5b9c1 fix: trusted header 2024-05-08 16:19:59 -07:00
Silentoplayz b3c5ebb323 Updated uk-UA/translation.json 2024-05-08 20:06:52 +00:00
Timothy Jaeryang Baek 9f2b846ea7 Merge pull request #2101 from open-webui/dev
doc
2024-05-08 11:31:31 -07:00
Timothy J. Baek 1b2b05d2ea Update README.md 2024-05-08 11:29:42 -07:00
Timothy J. Baek 0db71e97bb Update README.md 2024-05-08 11:28:42 -07:00
Timothy J. Baek c6053476ca Update dependabot.yml 2024-05-08 11:02:26 -07:00
Timothy Jaeryang Baek b8d7fdf16e Merge pull request #1965 from open-webui/dev
Create and publish Docker images with specific build args / build-main-image (linux/amd64) (push) Waiting to run
Create and publish Docker images with specific build args / build-main-image (linux/arm64) (push) Waiting to run
Create and publish Docker images with specific build args / build-cuda-image (linux/amd64) (push) Waiting to run
Create and publish Docker images with specific build args / build-cuda-image (linux/arm64) (push) Waiting to run
Create and publish Docker images with specific build args / build-ollama-image (linux/amd64) (push) Waiting to run
Create and publish Docker images with specific build args / build-ollama-image (linux/arm64) (push) Waiting to run
Create and publish Docker images with specific build args / merge-main-images (push) Blocked by required conditions
Create and publish Docker images with specific build args / merge-cuda-images (push) Blocked by required conditions
Create and publish Docker images with specific build args / merge-ollama-images (push) Blocked by required conditions
0.1.124
2024-05-08 10:54:33 -07:00
Timothy J. Baek b44ae536b9 Update CHANGELOG.md 2024-05-08 10:53:38 -07:00
Timothy J. Baek c99e351688 Update CHANGELOG.md 2024-05-08 10:52:44 -07:00
Timothy J. Baek 37abc1513c doc: fix 2024-05-08 10:52:20 -07:00
Timothy J. Baek 73689bb26c doc: changelog 2024-05-08 10:51:51 -07:00
Timothy J. Baek 06cbe337de feat: youtube loader language env var 2024-05-08 10:51:29 -07:00
Timothy J. Baek d3822f782c feat: non-english youtube support 2024-05-08 10:47:05 -07:00
Timothy J. Baek 87daf122db refac: styling 2024-05-08 09:43:49 -07:00
Timothy J. Baek 6023f86cf7 chore: format 2024-05-08 09:34:36 -07:00
Timothy J. Baek c40e634391 feat: better error message 2024-05-08 09:30:14 -07:00
Timothy J. Baek 01472c071b feat: support webui_auth false
#929
2024-05-08 08:40:18 -07:00
Timothy Jaeryang Baek 0d633c0d17 Merge pull request #2079 from akx/fi
feat: add Finnish localization 🇫🇮
2024-05-08 08:04:44 -07:00
Timothy Jaeryang Baek 84ea10ab45 Merge pull request #2061 from AnkurSachdeva22/main
Added Hindi Translation and language JSON updated
2024-05-08 08:04:16 -07:00
Timothy Jaeryang Baek 675328c881 Merge pull request #2002 from Yanyutin753/addAudio
🤩 Added custom openai tts models and role variables
2024-05-08 08:03:20 -07:00
Timothy Jaeryang Baek 421a964a9b Merge pull request #2082 from cheahjs/fix/reword-secret-key
fix: reword WEBUI_SECRET_KEY generation log line
2024-05-08 08:02:49 -07:00
Jun Siang Cheah ceecfb66a5 fix: reword WEBUI_SECRET_KEY generation log line 2024-05-08 20:03:03 +08:00
Aarni Koskela 20c4ada998 feat: add Finnish localization 🇫🇮 2024-05-08 13:33:25 +03:00
AnkurSachdeva22 9fefddd844 Merge branch 'main' of https://github.com/AnkurSachdeva22/open-webui-hindi 2024-05-08 14:32:32 +05:30
AnkurSachdeva22 7dade0715d language.json sorted by language code 2024-05-08 14:25:28 +05:30
Timothy J. Baek 9c190b56ae feat: /v1/models endpoint added for ollama proxy 2024-05-07 23:34:12 -07:00
Timothy J. Baek 72675ec15f refac: citation styling 2024-05-07 23:13:37 -07:00
Timothy Jaeryang Baek 1ea91f9060 Merge pull request #2067 from cheahjs/feat/dependabot-updates
feat: update dependabot for python and github actions
2024-05-07 22:43:21 -07:00
Jun Siang Cheah 34632b7aac fix: formatting 2024-05-08 10:50:55 +08:00
Jun Siang Cheah 2969918d19 feat: enable dependabot for github actions 2024-05-08 10:48:54 +08:00
Jun Siang Cheah 32f74c9fc7 fix: don't group dependabot updates because of conflicts 2024-05-08 10:47:59 +08:00
Ankur 0ed5405571 Merge branch 'dev' into main 2024-05-08 04:54:14 +05:30
AnkurSachdeva22 6d99ef8b4b Hindi Translation file Added and language JSON updated 2024-05-08 01:39:30 +05:30
Timothy J. Baek c63176402c chore: format 2024-05-07 11:41:17 -07:00
Timothy J. Baek ea69c24bf7 fix: allow message switch during regeneration
Co-Authored-By: Pandazki <onlrrr@gmail.com>
2024-05-07 11:39:32 -07:00
Timothy Jaeryang Baek a32a752791 Merge pull request #2049 from ihavecoke/main
Adjust text formatting per Chinese copywriting guidelines
2024-05-07 11:05:13 -07:00
Timothy Jaeryang Baek 68c182db96 Merge branch 'dev' into main 2024-05-07 11:05:00 -07:00
Timothy Jaeryang Baek 876853f2b0 Merge pull request #2040 from akx/uuid4
fix: do not use hardware ID in document ID generation
2024-05-07 11:02:21 -07:00
Timothy Jaeryang Baek 838c6f8217 Merge pull request #2033 from jannikstdl/update-chat-timestamp-locale
Update chat timestamp locale
2024-05-07 11:00:40 -07:00
Timothy Jaeryang Baek 1b5d88d0c0 Merge branch 'dev' into update-chat-timestamp-locale 2024-05-07 11:00:31 -07:00
Timothy Jaeryang Baek 39bc3b508c Merge pull request #2032 from jannikstdl/update-de-locale
Added new translation strings + more missing i18n keys
2024-05-07 10:59:40 -07:00
Timothy Jaeryang Baek 5661de3221 Merge pull request #2039 from akx/py-requirement-fixes
chore: Small Python requirement fixes
2024-05-07 10:47:44 -07:00
Timothy Jaeryang Baek 3f14d8bf0b Merge pull request #2038 from akx/pr-branch
doc: note PRs should target `dev`
2024-05-07 10:47:15 -07:00
ihavecoke 242e70d181 Adjust text formatting per Chinese copywriting guidelines
Refined text formatting to follow the recommendations from: https://sparanoid.com/note/chinese-copywriting-guidelines/
2024-05-07 23:47:47 +08:00
Jannik Streidl 7ce157a8b8 fix german spelling 2024-05-07 12:00:03 +02:00
Jannik Streidl a2d0f9ce1d fix german spelling 2024-05-07 11:56:41 +02:00
Jannik Streidl 06683f5ac0 changed german spelling 2024-05-07 11:54:34 +02:00
Jannik Streidl 9f4a71029f more keys 2024-05-07 11:44:35 +02:00
Jannik Streidl cc72341861 found more tooltops without i18n keys 2024-05-07 11:34:15 +02:00
Aarni Koskela 61bb1f1dc8 fix: do not use hardware ID in document ID generation 2024-05-07 11:42:05 +03:00
Aarni Koskela cbd1929f36 chore: remove uuid requirement (it's a standard library module) 2024-05-07 11:39:01 +03:00
Aarni Koskela 3723f42f1d chore: remove duplicate requirements 2024-05-07 11:39:01 +03:00
Aarni Koskela 03955d6a42 chore: pin youtube-transcript-api like the rest 2024-05-07 11:39:01 +03:00
Aarni Koskela d27f80542c doc: note PRs should target dev 2024-05-07 11:18:40 +03:00
Jannik Streidl f32094dd41 Added keys as comments so they dont get removed by the parser 2024-05-07 09:15:23 +02:00
Jannik Streidl 3404b8dd13 added some missing keys 2024-05-07 08:43:25 +02:00
Jannik Streidl 11dcbb2e15 fix Submit button not beeing a i18n key 2024-05-07 08:18:58 +02:00
Jannik Streidl 8d5f35a404 addition 2024-05-07 08:11:48 +02:00
Jannik Streidl 755dd85a20 Added localisation for the new chat timestamps 2024-05-07 07:59:09 +02:00
Jannik Streidl 55321a3b12 Added new translation strings + 1 i18n kkey 2024-05-07 07:34:42 +02:00
Timothy Jaeryang Baek ab43bd17f6 Merge pull request #2030 from 0xThresh/remove-helm
Remove Helm charts, which have moved to a separate repo
2024-05-06 20:35:45 -07:00
0xThresh.eth bfb8b08723 Remove Helm charts, which have moved to a separate repo 2024-05-06 20:39:10 -06:00
Timothy J. Baek 04a9115254 feat: esc image preview 2024-05-06 19:12:43 -07:00
Timothy J. Baek 7874bea5f4 fix: code block rendering issue 2024-05-06 19:04:36 -07:00
Timothy J. Baek e3a49c8e9b fix: styling 2024-05-06 18:50:50 -07:00
Timothy J. Baek f58eb0d266 feat: browser search engine support 2024-05-06 17:29:16 -07:00
Yanyutin753 5d6517c537 update the name 2024-05-07 08:28:34 +08:00
Timothy J. Baek 66e7e577df refac: citation styling 2024-05-06 17:02:04 -07:00
Timothy J. Baek 9b59039388 refac: styling 2024-05-06 17:00:50 -07:00
Timothy J. Baek 9aa689ea56 feat: title trim quotation marks 2024-05-06 16:59:54 -07:00
Timothy J. Baek 7f617225a0 refac: styling 2024-05-06 16:29:57 -07:00
Timothy J. Baek bf604bc07c refac: styling 2024-05-06 16:19:48 -07:00
Timothy J. Baek 485469683e chore: format 2024-05-06 16:18:11 -07:00
Timothy Jaeryang Baek e98cb45238 Merge pull request #2011 from cheahjs/feat/rag-citations
feat: show RAG query results as citations
2024-05-06 16:17:08 -07:00
Timothy J. Baek c84e0aa2a3 fix: .env load 2024-05-06 16:16:26 -07:00
Timothy J. Baek aef2a514d1 refac: citation rendering 2024-05-06 16:16:26 -07:00
Timothy J. Baek 64ed0d1089 refac: include source name to citation 2024-05-06 16:16:26 -07:00
Timothy J. Baek 4c490132ba refac: styling 2024-05-06 16:16:26 -07:00
Timothy J. Baek 38590da0b1 fix: styling 2024-05-06 16:16:26 -07:00
Timothy J. Baek e70cdf118b refac: styling 2024-05-06 16:16:26 -07:00
Jun Siang Cheah 4c6567c46f feat: group citations by source 2024-05-06 16:16:26 -07:00
Jun Siang Cheah c3425f3bf1 fix: update translation files 2024-05-06 16:16:26 -07:00
Jun Siang Cheah 2571f3c43b fix: remove stray debug logs 2024-05-06 16:14:10 -07:00
Jun Siang Cheah 0872bea790 feat: show RAG query results as citations 2024-05-06 16:14:10 -07:00
Timothy Jaeryang Baek ba09fcd548 Merge pull request #2026 from cheahjs/fix/integration-test-wait-ollama
fix: wait for Ollama to come up in integration test
2024-05-06 16:01:32 -07:00
Jun Siang Cheah 546d553803 fix: wait for Ollama to come up in integration test 2024-05-07 06:17:10 +08:00
Timothy J. Baek aa0bf79330 chore: format 2024-05-06 14:51:53 -07:00
Timothy J. Baek cecb87b8c2 feat: web_loader_ssl_verification setting 2024-05-06 14:50:55 -07:00
Timothy J. Baek 07b39d1cb9 refac: document settings 2024-05-06 14:36:36 -07:00
Timothy J. Baek 95f579cabe feat: rag ssl verification env var
Co-Authored-By: Tobias Steidle <tobias.steidle@softwaredev.de>
2024-05-06 13:12:08 -07:00
Timothy J. Baek 7f1acf9c2d chore: format 2024-05-06 12:58:24 -07:00
Timothy Jaeryang Baek 6fa88854e3 Merge pull request #1874 from jannikstdl/update-i18n
Added some i18n keys & updated german locale
2024-05-06 12:57:42 -07:00
Jannik Streidl 2dcd9e75a1 resetted parser - only new keys 2024-05-06 21:10:46 +02:00
Yanyutin753 5f7188b480 fix python test 2024-05-06 15:33:29 +08:00
Yanyutin753 761c66a8d8 🤩 Added custom openai tts models and role variables 2024-05-06 15:23:27 +08:00
Timothy Jaeryang Baek 0334ab7c5d Merge pull request #2001 from cheahjs/feat/limit-title-gen-tokens
feat: restrict title gen output to 50 tokens
2024-05-06 00:05:53 -07:00
Jannik Streidl e31cf08188 merged conflicts in PL locale 2024-05-06 08:57:18 +02:00
Jun Siang Cheah b8c97fa012 feat: restrict title gen output to 50 tokens 2024-05-06 14:46:50 +08:00
Timothy J. Baek e92311b4eb fix: image download issue
Co-Authored-By: Clivia <132346501+Yanyutin753@users.noreply.github.com>
2024-05-05 22:46:22 -07:00
Timothy J. Baek 594f2f264f chore: formatting 2024-05-04 14:53:21 -07:00
Timothy Jaeryang Baek c2f429425e Merge pull request #1973 from bo3bdo/main
Adding language Arabic
2024-05-04 14:52:35 -07:00
HAMAD ABDULLA 2fec591b59 Update translation.json 2024-05-05 00:39:04 +03:00
HAMAD ABDULLA 9c1f224219 Update translation.json 2024-05-04 23:30:16 +03:00
Timothy J. Baek af1d8470cd fix: disable template variables in prompt 2024-05-04 13:21:35 -07:00
Timothy J. Baek 3a2f1d56c8 fix: promptTemplate infinite loop 2024-05-04 13:11:58 -07:00
Timothy J. Baek a341cfe3fd refac: getTimeRange 2024-05-04 12:59:23 -07:00
Timothy J. Baek 36d8442c92 fix: chat list time range 2024-05-04 12:53:01 -07:00
HAMAD ABDULLA cb2e989408 Adding language Arabic
The translation has been added and the previous errors have been corrected. i hope i good now. Thank you
2024-05-04 22:15:02 +03:00
Timothy J. Baek c0fbf1e7d0 refac: styling 2024-05-04 02:11:23 -07:00
Timothy J. Baek 1c39e5cff9 refac: styling 2024-05-04 02:05:09 -07:00
Timothy J. Baek 24c0dbec0d fix: pending permission issue 2024-05-04 01:31:08 -07:00
Timothy J. Baek 0a8dae633b refac: styling 2024-05-04 01:24:43 -07:00
Timothy J. Baek 53dae39042 feat: chat list group by time range 2024-05-04 01:23:02 -07:00
Timothy J. Baek 84ec58873a fix: tag delete issue 2024-05-03 17:27:48 -07:00
Timothy J. Baek d4db3dd593 fix: tag delete issue 2024-05-03 16:18:11 -07:00
Timothy J. Baek fa3c7bc218 fix 2024-05-03 15:34:08 -07:00
Timothy J. Baek facb6edfdc refac: chat tags 2024-05-03 15:25:41 -07:00
Timothy J. Baek e8085f80a7 fix: litellm warning message
>:(
2024-05-03 15:07:12 -07:00
Timothy J. Baek ecde76270c chore: format 2024-05-03 14:25:40 -07:00
Timothy J. Baek 70ae053a46 fix: ascii art issue
#1918
2024-05-03 14:23:38 -07:00
Timothy J. Baek 3e6b94dbc1 fix: sidebar handle 2024-05-03 14:10:00 -07:00
Timothy Jaeryang Baek e3a3a034c1 Merge pull request #1944 from aguvener/dev
fix: tr_TR translation synchronized with the latest updates.
2024-05-03 14:05:07 -07:00
Timothy Jaeryang Baek 46027cc390 Merge branch 'dev' into dev 2024-05-03 14:04:54 -07:00
Timothy Jaeryang Baek e4c77628be Merge pull request #1946 from Yanyutin753/shortcuts-dev
add Symbol startup instructions in ShortcutsModal
2024-05-03 14:03:44 -07:00
Timothy J. Baek ecfb6891f6 refac 2024-05-03 14:03:22 -07:00
Yanyutin753 115c3a38a7 add Symbol startup prompt startup instructions in ShortcutsModal 2024-05-03 17:49:58 +08:00
aguvener 9d8c23b3b2 fix: synchronized with the latest updates. 2024-05-03 11:01:37 +03:00
Timothy Jaeryang Baek 30b053116d Merge pull request #1942 from open-webui/dev
fix: drag and drop styling issue
2024-05-03 00:16:59 -07:00
Timothy J. Baek 0921317b2b fix: drag and drop styling issue 2024-05-03 00:16:43 -07:00
Timothy Jaeryang Baek f1963c95c9 Merge pull request #1937 from open-webui/dev
fix: selector styling issue
2024-05-02 18:56:44 -07:00
Timothy J. Baek c2c89525bb fix: selector styling issue 2024-05-02 18:56:19 -07:00
Timothy Jaeryang Baek 47565065f6 Merge pull request #1936 from open-webui/dev
fix: styling issue
2024-05-02 18:50:48 -07:00
Timothy J. Baek ecc841c57d fix: styling issue 2024-05-02 18:50:20 -07:00
Timothy Jaeryang Baek eaaa75387f Merge pull request #1933 from open-webui/dev
fix: selector styling
2024-05-02 17:14:59 -07:00
Timothy J. Baek 61a8f73291 fix: selector styling 2024-05-02 17:14:33 -07:00
Timothy Jaeryang Baek 9df4227db4 Merge pull request #1930 from open-webui/dev
fix
2024-05-02 16:00:05 -07:00
Timothy J. Baek 683e6ca337 fix 2024-05-02 15:59:45 -07:00
Timothy Jaeryang Baek b1eb08b44a Merge pull request #1929 from open-webui/dev
fix
2024-05-02 15:56:02 -07:00
Timothy J. Baek 989a4d3165 fix 2024-05-02 15:55:42 -07:00
Timothy Jaeryang Baek 443a256f72 Merge pull request #1928 from open-webui/dev
fix: image gen
2024-05-02 15:54:50 -07:00
Timothy J. Baek 482f010d22 fix: image gen 2024-05-02 15:54:31 -07:00
Timothy Jaeryang Baek fc86b20350 Merge pull request #1926 from open-webui/dev
fix
2024-05-02 15:48:49 -07:00
Timothy J. Baek 1f98c091f0 fix 2024-05-02 15:48:18 -07:00
Timothy Jaeryang Baek dc187d35a1 Merge pull request #1925 from open-webui/dev
refac: mobile detection
2024-05-02 15:44:54 -07:00
Timothy J. Baek e0908f9f26 refac: mobile detection 2024-05-02 15:44:31 -07:00
Timothy Jaeryang Baek 75911f6e4e Merge pull request #1920 from open-webui/dev
fix
2024-05-02 15:11:46 -07:00
Timothy J. Baek a2ebbd02ad fix: styling 2024-05-02 15:11:20 -07:00
Timothy J. Baek a19d4267f7 fix: integration test 2024-05-02 14:20:53 -07:00
Timothy Jaeryang Baek 444f20198a Merge pull request #1917 from open-webui/dev
fix: selector input issue
2024-05-02 13:26:08 -07:00
Timothy J. Baek a79618ee3e fix: selector input issue 2024-05-02 13:25:44 -07:00
Timothy Jaeryang Baek 38ff3209ad Merge pull request #1881 from open-webui/dev
Create and publish Docker images with specific build args / build-main-image (linux/arm64) (push) Waiting to run
Create and publish Docker images with specific build args / build-ollama-image (linux/amd64) (push) Waiting to run
Create and publish Docker images with specific build args / build-ollama-image (linux/arm64) (push) Waiting to run
Create and publish Docker images with specific build args / merge-main-images (push) Blocked by required conditions
Create and publish Docker images with specific build args / merge-ollama-images (push) Blocked by required conditions
Create and publish Docker images with specific build args / build-main-image (linux/amd64) (push) Failing after 54s
Create and publish Docker images with specific build args / build-cuda-image (linux/amd64) (push) Failing after 1m2s
Create and publish Docker images with specific build args / build-cuda-image (linux/arm64) (push) Failing after 58s
Create and publish Docker images with specific build args / merge-cuda-images (push) Has been skipped
0.1.123
2024-05-02 13:10:28 -07:00
Timothy J. Baek 2789102d27 Update chat.cy.ts 2024-05-02 12:54:28 -07:00
Timothy J. Baek c1f88eb0ad Update chat.cy.ts 2024-05-02 12:49:25 -07:00
Jannik Streidl e57c0c301c resolved conflicts #2 2024-05-02 21:46:24 +02:00
Timothy J. Baek 5cf621396d refac: navbar selector styling 2024-05-02 12:33:04 -07:00
Timothy J. Baek 2bece7b4c5 fix: styling 2024-05-02 03:16:08 -07:00
Timothy J. Baek 7a96893093 refac: mobile device detection 2024-05-02 03:11:56 -07:00
Timothy J. Baek 180fd44a4d refac: gesture sensitivity 2024-05-02 03:02:15 -07:00
Timothy J. Baek a2edd2d911 refac: styling 2024-05-02 02:59:05 -07:00
Timothy J. Baek e6cf552aad refac: styling 2024-05-02 02:54:33 -07:00
Timothy J. Baek be6cc1c53a chore: format 2024-05-02 02:48:56 -07:00
Timothy J. Baek f50ffc07d7 doc: changelog 2024-05-02 02:47:16 -07:00
Timothy Jaeryang Baek e700552f93 Merge pull request #1905 from 7a6ac0/r_score_type
fix: change r_score type to float
2024-05-02 02:22:59 -07:00
Timothy J. Baek d680d52b85 feat:'@' model support 2024-05-02 02:20:57 -07:00
Timothy J. Baek bf35297e4a refac: default role updated to user for add user modal 2024-05-02 01:35:00 -07:00
Timothy J. Baek c91b9af0e0 Create logo.png 2024-05-02 01:21:44 -07:00
Timothy J. Baek 82a61e72e1 refac: hide model set as default button 2024-05-02 01:15:58 -07:00
Timothy J. Baek 52fb09ff95 fix: chat input variable styling issue 2024-05-02 00:48:07 -07:00
Timothy J. Baek 572cd22b4d feat: prompt variables from suggestions 2024-05-02 00:45:04 -07:00
Timothy J. Baek 9ee39aa07f chore: format 2024-05-02 00:35:50 -07:00
Timothy J. Baek 372284b419 refac 2024-05-02 00:34:07 -07:00
Timothy J. Baek 714bdca3f3 refac: styling 2024-05-02 00:23:32 -07:00
Timothy J. Baek 5613af032d fix: styling 2024-05-02 00:07:04 -07:00
Timothy J. Baek 8fb5e22e43 refac: placeholder fade in effect 2024-05-01 23:41:12 -07:00
Timothy J. Baek b19e05669e fix: styling 2024-05-01 23:11:16 -07:00
Timothy J. Baek 35b5d5ba35 refac: suggestions scroll snap 2024-05-01 23:01:00 -07:00
Timothy J. Baek 84cd1b8cb8 refac: styling 2024-05-01 22:55:42 -07:00
tabacoWang fffd283b0c fix:
fix: Change the type from int to float
2024-05-02 13:45:19 +08:00
Timothy J. Baek 6d378844ae refac: styling 2024-05-01 22:39:09 -07:00
Timothy J. Baek 68cfccedee feat: super-admin (first one to signup) 2024-05-01 19:59:05 -07:00
Timothy J. Baek a433315346 feat: disable all actions for admins 2024-05-01 19:50:23 -07:00
Timothy J. Baek 77cc3b5470 feat: disable admin chatlist by default 2024-05-01 19:47:54 -07:00
Timothy J. Baek dc412d21f7 refac: scrollbar styling 2024-05-01 19:37:12 -07:00
Timothy J. Baek 96d9d3447b fix: pwa icon
#1886
2024-05-01 19:32:36 -07:00
Timothy J. Baek aed078b580 chore: format 2024-05-01 19:30:03 -07:00
Timothy J. Baek 33c337785c chore: i18n format 2024-05-01 19:29:11 -07:00
Timothy J. Baek 20a6dbbe65 feat: csv bulk import 2024-05-01 19:28:35 -07:00
Timothy J. Baek bd3b5f1edb feat: csv user import frontend 2024-05-01 19:02:25 -07:00
Timothy J. Baek e5703a588f fix: styling 2024-05-01 18:13:45 -07:00
Timothy J. Baek 3431a93499 fix: safari styling 2024-05-01 18:10:49 -07:00
Timothy J. Baek 8745091a16 chore: i18n 2024-05-01 18:07:29 -07:00
Timothy J. Baek e6bcdba5ad feat: add user from admin panel 2024-05-01 18:06:02 -07:00
Timothy J. Baek 96af34f240 chore: i18n 2024-05-01 17:56:39 -07:00
Timothy J. Baek b7fcf14f6e refac: styling 2024-05-01 17:55:18 -07:00
Timothy J. Baek ebc6a269d3 chore: i18n 2024-05-01 17:20:21 -07:00
Timothy J. Baek 0595c04909 feat: youtube rag 2024-05-01 17:17:00 -07:00
Timothy J. Baek e60c87d750 fix: delete chat shortcut 2024-05-01 16:08:06 -07:00
Timothy J. Baek d5bcae6182 chore: format 2024-05-01 15:41:39 -07:00
Timothy Jaeryang Baek dbc3aa7234 Merge pull request #1892 from Joakim-T/patch-1
Patch 1
2024-05-01 15:01:18 -07:00
Joakim e626fb2dbf Update languages.json
Moved sv-SE to correct position alphabetically
2024-05-01 20:42:50 +02:00
Joakim 34be6de4d8 Update translation.json sv-SE
Minor changes to Swedish translations
2024-05-01 14:43:12 +02:00
Joakim 20be93217b Update languages.json to add sv-SE
Swedish translation
2024-05-01 14:35:17 +02:00
Joakim c580d29a5d Create translation.json for sv-SE
Translation to Swedish
2024-05-01 14:30:16 +02:00
Timothy Jaeryang Baek f337ddb267 Merge pull request #1880 from Silentoplayz/saynototelemetry
feat: Added Environment Variable ANONYMIZED_TELEMETRY=false
2024-04-30 21:19:35 -07:00
Timothy J. Baek 1e05caf809 fix: response profile image 2024-04-30 17:10:12 -07:00
Timothy J. Baek 44884a8886 feat: randomised suggestion 2024-04-30 17:07:03 -07:00
Timothy J. Baek a01fd15812 refac: sidebar styling 2024-04-30 16:58:07 -07:00
Timothy J. Baek d513629984 fix: styling 2024-04-30 16:55:32 -07:00
Timothy J. Baek f1acf68bd0 fix: styling 2024-04-30 16:52:19 -07:00
Timothy J. Baek 3c9fc7858b fix: styling 2024-04-30 16:34:29 -07:00
Timothy J. Baek bf2ff47df0 refac: styling 2024-04-30 16:00:44 -07:00
Timothy J. Baek 6318282873 refac: styling 2024-04-30 15:31:50 -07:00
Timothy J. Baek 3043e43418 refac: styling 2024-04-30 15:18:58 -07:00
Timothy J. Baek 595ebd11ac refac: styling 2024-04-30 15:17:05 -07:00
Timothy J. Baek 1157b8e12d refac: styling 2024-04-30 15:12:58 -07:00
Timothy J. Baek f653944849 refac: snap-center removed 2024-04-30 15:11:17 -07:00
Timothy J. Baek 01c077da3d refac 2024-04-30 15:10:39 -07:00
Timothy J. Baek 27ff386115 fix: horizontal scroll issue on mobile
#1854
2024-04-30 15:08:34 -07:00
Timothy J. Baek 35437fb3a3 refac: styling 2024-04-30 14:58:11 -07:00
Timothy J. Baek 18e5c2e4cb refac: styling 2024-04-30 14:56:06 -07:00
Timothy Jaeryang Baek 2674656b49 Merge pull request #1884 from cheahjs/feat/freeze-py-and-dependabot
feat: pin all python packages and setup dependabot
2024-04-30 14:22:46 -07:00
Jun Siang Cheah fe56c0a7ac feat: add dependabot config for keeping python packages updated 2024-04-30 21:23:52 +01:00
Jun Siang Cheah ddac5284fe feat: specify versions for python packages 2024-04-30 21:21:00 +01:00
Silentoplayz b2020383dd Update Dockerfile
fix
2024-04-30 20:05:11 +00:00
Silentoplayz 563377a58a fix 2024-04-30 20:04:30 +00:00
Timothy Jaeryang Baek eadb671414 Merge pull request #1882 from cheahjs/feat/harden-streaming-parser
feat: use spec compliant SSE parser for OpenAI responses
2024-04-30 13:02:44 -07:00
Jun Siang Cheah b3ccabd2fe fix: add missing type for splitLargeChunks 2024-04-30 20:56:58 +01:00
Jun Siang Cheah e8bf596959 feat: switch OpenAI SSE parsing to eventsource-parser 2024-04-30 20:56:58 +01:00
Timothy J. Baek abc9b6b3f3 fix: version pinning 2024-04-30 12:41:35 -07:00
Timothy J. Baek 79bbc2be23 chore: formatting 2024-04-30 12:34:56 -07:00
Silentoplayz b763535c92 Added: Environment Variable ANONYMIZED_TELEMETRY=False to .env.example & Dockerfile files to prevent/disable the creation of telemetry_user_id file created by Chroma in Docker installation methods. 2024-04-30 19:10:44 +00:00
Timothy Jaeryang Baek de62153d49 Merge pull request #1815 from Yanyutin753/new-dev
 expend the image format type after the file is downloaded
2024-04-30 11:52:30 -07:00
Timothy J. Baek 80413a7628 refac 2024-04-30 11:52:08 -07:00
Timothy Jaeryang Baek 3f0fae1d10 Merge pull request #1868 from Yanyutin753/rag-dev
📌 fixed a bug where RAG would not reply after not reading the file correctly
2024-04-30 11:40:47 -07:00
Jannik Streidl dd52ea9d3d added and improved some german translations 2024-04-30 11:39:14 +02:00
Jannik Streidl 30d1048099 resolved the conflicts 😍 2024-04-30 11:33:05 +02:00
Jannik Streidl 142f82bae5 Added some i18n keys & updated german locale 2024-04-30 10:46:16 +02:00
Yanyutin753 c0bb32d768 📌 fixed a bug where RAG would not reply after not reading the file correctly 2024-04-30 13:51:30 +08:00
Timothy J. Baek 5e168e6fef refac: remove num_ctx limit 2024-04-29 16:10:57 -07:00
Timothy Jaeryang Baek 4bf6e64c35 Merge pull request #1865 from cheahjs/feat/run-i18n-in-ci
feat: run i18next in CI to format and catch translations diffs
2024-04-29 15:54:38 -07:00
Timothy Jaeryang Baek 1afc49c1e4 Merge pull request #1862 from cheahjs/feat/filter-local-rag-fetch
feat: add ENABLE_LOCAL_WEB_FETCH to protect against SSRF attacks
2024-04-29 15:51:17 -07:00
Timothy Jaeryang Baek eebabd84ef Merge pull request #1864 from cheahjs/fix/format
fix: formatting
2024-04-29 15:48:03 -07:00
Timothy Jaeryang Baek 6b04380c85 Merge pull request #1863 from cheahjs/fix/make-dev-executable
fix: make backend/fix.sh executable
2024-04-29 15:47:44 -07:00
Timothy Jaeryang Baek f3199c6510 Merge pull request #1858 from buroa/buroa/fixes
fix: various rag api calls and ui cleanup
2024-04-29 15:46:29 -07:00
Timothy Jaeryang Baek c523126bae Merge pull request #1853 from domsleee/fix/modal-closing-on-mouseup
fix: modal should not close when dragging from inside of modal
2024-04-29 15:45:46 -07:00
Jun Siang Cheah 45f34924b0 feat: run i18next in CI to format and catch translations diffs 2024-04-29 21:10:37 +01:00
Jun Siang Cheah 25af07a0c7 fix: formatting 2024-04-29 21:07:06 +01:00
Jun Siang Cheah bac28222fb fix: make backend/fix.sh executable 2024-04-29 21:01:54 +01:00
Jun Siang Cheah 1c4e63f71e feat: add ENABLE_LOCAL_WEB_FETCH to protect against SSRF attacks 2024-04-29 20:55:17 +01:00
Timothy J. Baek e8abaa8bea fix: styling 2024-04-29 12:08:36 -07:00
Steven Kreitzer 5b8fd14470 fix: various api rag results 2024-04-29 12:17:36 -05:00
Dom Slee d4339fe769 fix: modal should not close when dragging from inside of modal 2024-04-29 18:30:12 +10:00
Timothy J. Baek 877ed69004 refac: token length limit 2024-04-29 00:36:09 -07:00
Timothy Jaeryang Baek e360d57203 Merge pull request #1839 from cheahjs/fix/fluid-setting-not-reflecting-current-setting
fix: fluid stream setting not reflecting current state on load
2024-04-29 00:31:37 -07:00
Timothy Jaeryang Baek 0235b0f6f3 Merge pull request #1838 from Maximilian-Pichler/german-locale
German locale
2024-04-29 00:21:42 -07:00
Timothy Jaeryang Baek a128dfa06b Merge branch 'dev' into german-locale 2024-04-29 00:21:08 -07:00
Timothy Jaeryang Baek ffc91ba6b6 Merge pull request #1841 from Yanyutin753/translate
🎖️Added translations for Fluidly stream large external response chunks and OLED Dark
2024-04-29 00:20:02 -07:00
Yanyutin753 24c000739c 🎖️Added translations for Fluidly stream large external response chunks 2024-04-29 10:26:16 +08:00
Yanyutin753 00367ef23e 🎖️Added translations for Fluidly stream large external response chunks 2024-04-29 10:04:34 +08:00
Jun Siang Cheah 527a0b329b fix: fluid stream setting not reflecting current state on load 2024-04-29 00:06:32 +01:00
Maximilian Pichler 2e4bba2374 Update translation.json 2024-04-28 22:54:20 +02:00
Maximilian Pichler 4cafea0b97 Merge branch 'dev' into german-locale 2024-04-28 22:48:33 +02:00
Maximilian Pichler cfc9cc8a10 Merge pull request #2 from jannikstdl/german-locale
German locale -  ran i18n parser
2024-04-28 21:58:18 +02:00
Timothy Jaeryang Baek c7fa024b8f Merge pull request #1807 from insoutt/improve-es-lang
Improve 'es' translations
2024-04-28 10:27:40 -07:00
Timothy Jaeryang Baek cc50746043 Merge pull request #1821 from Yanyutin753/translate
🎖️Added translations for Playground and Archived Chats
2024-04-28 10:26:33 -07:00
Timothy Jaeryang Baek bf0ea4dc5a Merge pull request #1830 from cheahjs/feat/db-migration-tests
feat: add tests for db migration on sqlite and postgres
2024-04-28 10:26:17 -07:00
Timothy Jaeryang Baek 9ddc243c52 Merge pull request #1829 from cheahjs/fix/fluid-streaming-background
fix: fluid streaming was "pausing" when tab was not visible
2024-04-28 10:24:30 -07:00
Timothy J. Baek 9832e6edba enhancement: OpenAI API
api.together.xyz, api.replicate.com
2024-04-28 10:20:40 -07:00
Jannik Streidl afc78b0277 ran i18n parser to add the new translation keys 2024-04-28 18:47:12 +02:00
Jun Siang Cheah f561e94244 fix: refactor db migration tests 2024-04-28 17:00:31 +01:00
Jun Siang Cheah eed6c7194b fix: disable mysql tests 2024-04-28 16:55:53 +01:00
Jun Siang Cheah 167b5712ea feat: add tests for db migration on sqlite, postgres, and mysql 2024-04-28 16:55:16 +01:00
Timothy Jaeryang Baek 7bc17da534 Merge pull request #1825 from cheahjs/feat/allow-backend-to-run-without-frontend 2024-04-28 08:53:18 -07:00
Timothy Jaeryang Baek 24497592a8 Merge pull request #1827 from justinh-rahb/update-litellm 2024-04-28 08:52:31 -07:00
Jun Siang Cheah ed9e99e946 fix: fluid streaming was "pausing" when tab was not visible 2024-04-28 16:51:36 +01:00
Justin Hayes d42517b7ed Update LiteLLM (and Gunicorn) 2024-04-28 11:43:57 -04:00
Maximilian Pichler 93d4f987e7 Merge pull request #1 from jannikstdl/german-locale
German locale additions
2024-04-28 17:24:56 +02:00
Jun Siang Cheah 6a1d60b1b3 feat: warn but not exit if frontend build does not exist 2024-04-28 16:03:30 +01:00
Jannik Streidl 19843e39fd Added more german translations + added more i18n keys 2024-04-28 14:39:06 +02:00
Yanyutin753 ec18489723 🎖️Added translations for Playground and Archived Chats 2024-04-28 19:53:27 +08:00
Maximilian Pichler 9130428a55 Update translation.json 2024-04-28 13:12:41 +02:00
Maximilian Pichler 236ec28491 Update translation.json
added and corrected some translations
2024-04-28 12:58:13 +02:00
Timothy J. Baek f070e8b7f9 chore: format 2024-04-27 21:02:15 -07:00
Yanyutin753 3321a1b922 expend the image format type after the file is downloaded 2024-04-28 12:00:52 +08:00
Timothy Jaeryang Baek f935acc6bf Merge pull request #1813 from open-webui/doge
feat: much wow doge
2024-04-27 20:55:10 -07:00
Timothy J. Baek 6d90d130bd feat: doge i18n response message profile image 2024-04-27 20:54:31 -07:00
Timothy J. Baek bfd33ec0df feat: doge i18n placeholder 2024-04-27 20:53:42 -07:00
Timothy Jaeryang Baek 9af6c5300b Merge pull request #1811 from open-webui/doge
feat: doge i18n
2024-04-27 20:48:20 -07:00
Timothy J. Baek 5c887d0709 feat: doge translation 2024-04-27 20:46:52 -07:00
Timothy Jaeryang Baek c9589e2118 Merge pull request #1810 from open-webui/dev
fix: wording
2024-04-27 20:11:10 -07:00
Timothy J. Baek 75cbbbe52d fix: wording 2024-04-27 20:10:20 -07:00
Timothy Jaeryang Baek 0455b80604 Merge pull request #1809 from open-webui/dev
fix
2024-04-27 20:07:26 -07:00
Timothy J. Baek 71a75bccf5 fix 2024-04-27 20:06:07 -07:00
Timothy Jaeryang Baek 97609970b2 Merge pull request #1806 from open-webui/dev
fix
2024-04-27 19:46:05 -07:00
Timothy J. Baek 48ed701960 fix 2024-04-27 19:44:36 -07:00
Timothy Jaeryang Baek d401d77cbd Merge pull request #1805 from open-webui/dev
fix
2024-04-27 19:42:51 -07:00
Timothy J. Baek 5e97c9927b fix 2024-04-27 19:42:19 -07:00
insoutt 76660f3e44 Improve translation 2024-04-27 21:01:25 -05:00
Timothy Jaeryang Baek 92c98eda2e Merge pull request #1781 from open-webui/dev
Create and publish Docker images with specific build args / build-main-image (linux/arm64) (push) Waiting to run
Create and publish Docker images with specific build args / build-cuda-image (linux/arm64) (push) Waiting to run
Create and publish Docker images with specific build args / build-ollama-image (linux/arm64) (push) Waiting to run
Create and publish Docker images with specific build args / merge-main-images (push) Blocked by required conditions
Create and publish Docker images with specific build args / merge-cuda-images (push) Blocked by required conditions
Create and publish Docker images with specific build args / merge-ollama-images (push) Blocked by required conditions
Create and publish Docker images with specific build args / build-cuda-image (linux/amd64) (push) Failing after 58s
Create and publish Docker images with specific build args / build-main-image (linux/amd64) (push) Has been skipped
Create and publish Docker images with specific build args / build-ollama-image (linux/amd64) (push) Failing after 57s
0.1.122
2024-04-27 18:29:10 -07:00
Timothy J. Baek 85df019c2a refac: styling 2024-04-27 21:20:43 -04:00
Timothy J. Baek 2fceeb120b refac: wording 2024-04-27 21:18:15 -04:00
Timothy J. Baek 8aa47ea6bc fix 2024-04-27 21:17:19 -04:00
Timothy J. Baek 704f7e369c Update app.html 2024-04-27 21:14:08 -04:00
Timothy J. Baek e4dd613ed1 chore: formatting 2024-04-27 21:12:21 -04:00
Timothy J. Baek 63494a3717 Update CHANGELOG.md 2024-04-27 21:11:59 -04:00
Timothy J. Baek 5898550101 doc: changelog 2024-04-27 21:07:43 -04:00
Timothy J. Baek f1d2340861 enhancement: disable submit via enter on mobile 2024-04-27 20:53:52 -04:00
Timothy J. Baek e71ef42155 fix: stop seq backslash issue 2024-04-27 20:46:34 -04:00
Timothy J. Baek 7f3daa19cd fix: stop seq backslash issue
#1747
2024-04-27 20:45:09 -04:00
Timothy J. Baek ebeaa24e9d refac 2024-04-27 19:48:46 -04:00
Timothy J. Baek e2447dd0a7 refac: better layout loading 2024-04-27 19:47:11 -04:00
Timothy J. Baek 2feba8af94 fix: font fallback issue
#1556
2024-04-27 19:42:55 -04:00
Timothy Jaeryang Baek 386fc040b1 Merge pull request #1802 from Yanyutin753/tem-dev
feat added environment variables and sync.yml
2024-04-27 16:39:45 -07:00
Timothy J. Baek 9094536d37 feat: user last active 2024-04-27 19:38:51 -04:00
Yanyutin753 02b8a4cf11 Merge branch 'tem-dev' of https://github.com/Yanyutin753/open-webui into tem-dev 2024-04-28 07:21:36 +08:00
Yanyutin753 849a0b973d recompose the name of environment variables 2024-04-28 07:21:01 +08:00
Timothy J. Baek 01c4647dfc fix: ollama version string issue
#1800
2024-04-27 19:19:47 -04:00
Timothy Jaeryang Baek 07c110a1fc Delete .github/workflows/sync.yml 2024-04-27 18:06:40 -05:00
Timothy J. Baek 85e94cc259 chore: removed unused frontend dependency 2024-04-27 19:04:57 -04:00
Timothy J. Baek f0da5b9ea4 refac 2024-04-27 19:02:37 -04:00
Timothy J. Baek 9ef843d492 refac: splash screen 2024-04-27 18:59:20 -04:00
Yanyutin753 b0245a7eff feat added environment variables and sync.yml 2024-04-28 06:54:26 +08:00
Timothy J. Baek 975e078f4d Update app.html 2024-04-27 18:51:59 -04:00
Timothy J. Baek 979c4290f7 feat: splash screen support 2024-04-27 18:50:26 -04:00
Timothy J. Baek bcf78b4efa feat: show user chats in admin panel 2024-04-27 18:24:59 -04:00
Timothy J. Baek 098ac18762 refac: naming 2024-04-27 18:15:32 -04:00
Timothy J. Baek 4ea2eb7939 refac 2024-04-27 18:14:15 -04:00
Timothy J. Baek 10f27ebacf refac: naming 2024-04-27 18:12:57 -04:00
Timothy J. Baek 7b913ea032 chore: formatting 2024-04-27 17:38:48 -04:00
Timothy J. Baek d63e52600d refac: styling 2024-04-27 17:35:20 -04:00
Timothy J. Baek 4ca7c8d548 fix: styling 2024-04-27 17:31:19 -04:00
Timothy Jaeryang Baek 69d32a94ab Merge pull request #1616 from Entaigner/patch-1
Chose between "docker-compose" and "docker compose" in Makefile
2024-04-27 14:29:15 -07:00
Timothy Jaeryang Baek 1c14b54eb9 Merge pull request #1666 from Silentoplayz/Silentoplayz-update-PR-template.md
Update Pull Request Template to Improve Checklist and Format
2024-04-27 14:28:44 -07:00
Timothy Jaeryang Baek c1b97a723f Update pull_request_template.md 2024-04-27 16:28:14 -05:00
Timothy Jaeryang Baek e2534e3703 Merge pull request #1794 from cheahjs/feat/external-chromadb
feat: add ability to configure a HTTP ChromaDB client
2024-04-27 14:24:45 -07:00
Timothy Jaeryang Baek 2f8164d75f Merge pull request #1798 from cheahjs/feat/abort-openai-responses-on-stop
feat: abort openai text completion when stopping responses
2024-04-27 14:15:14 -07:00
Timothy Jaeryang Baek 8215a2023e Merge pull request #1799 from karaketir16/patch-1
fix: docker gpus option "all" support in run-compose.sh
2024-04-27 14:14:30 -07:00
Jun Siang Cheah c095a7c291 feat: abort openai text completion when stopping responses 2024-04-27 21:53:47 +01:00
Osman Karaketir 57d178456a fix: docker gpus option "all" support
"docker --gpus=all" is a valid and mostly used command. regex updated to match this.
2024-04-27 23:50:07 +03:00
Timothy Jaeryang Baek c1d85f8a6f Merge pull request #1791 from cheahjs/feat/external-db-support
feat: add support for using postgres for the backend DB
2024-04-27 12:48:56 -07:00
Timothy Jaeryang Baek 29a750c4ca Merge pull request #1788 from cheahjs/feat/cypress-tests
feat: add basic cypress test as initial work towards e2e tests
2024-04-27 12:45:24 -07:00
Timothy Jaeryang Baek db5c4be674 Merge pull request #1795 from cheahjs/fix/openai-handle-carriage-returns
fix: handle carriage returns in OpenAI streams
2024-04-27 12:43:33 -07:00
Timothy Jaeryang Baek 6fbddb0702 Merge pull request #1797 from cheahjs/feat/allow-overriding-host-in-docker
feat: add HOST to the backend start script
2024-04-27 12:42:06 -07:00
Timothy J. Baek ce9a5d12e0 refac: rag pipeline 2024-04-27 15:38:50 -04:00
Jun Siang Cheah c19429848b feat: add HOST to the backend start script 2024-04-27 20:20:48 +01:00
Timothy J. Baek 8f1563a7a5 fix: typo 2024-04-27 15:03:49 -04:00
Timothy J. Baek 2325660520 chore: formatting 2024-04-27 15:03:05 -04:00
Timothy J. Baek 9be56d68e0 refac: naming convention 2024-04-27 15:02:57 -04:00
Timothy Jaeryang Baek 99a43cc998 Merge pull request #1792 from insoutt/hide-sidebar-on-resize
Hide the sidebar when resizing the window
2024-04-27 11:59:44 -07:00
Jun Siang Cheah be038ab878 fix: handle carriage returns in OpenAI streams 2024-04-27 19:07:41 +01:00
Jun Siang Cheah 8df7db1e17 feat: add ability to configure a HTTP ChromaDB client 2024-04-27 18:52:35 +01:00
insoutt 0c79ac0479 Hide sidevar when screen is resized to less than 1024 pixels 2024-04-27 10:16:39 -05:00
Jun Siang Cheah 47a33acfeb feat: show error toast if trying to download db on external db 2024-04-27 15:53:31 +01:00
Jun Siang Cheah e91a49c455 feat: add support for using postgres for the backend DB 2024-04-27 15:33:20 +01:00
Jun Siang Cheah 730befce45 feat: add basic cypress test as initial work towards e2e tests 2024-04-27 14:10:10 +01:00
Timothy J. Baek f8f9f27ae8 chore: comment 2024-04-26 22:44:10 -04:00
Timothy J. Baek 790a305c55 chore: disable unmaintained themes 2024-04-26 22:33:39 -04:00
Timothy J. Baek f63866b72a feat: loading indicator 2024-04-26 17:43:42 -04:00
Timothy J. Baek b22415d456 feat: litellm opt-out support 2024-04-26 17:19:50 -04:00
Timothy J. Baek dbf7b15539 refac: naming convention
MODEL_FILTER_ENABLED -> ENABLE_MODEL_FILTER
2024-04-26 17:17:18 -04:00
Timothy J. Baek c5eac5a1c7 fix: webui name 2024-04-26 17:00:25 -04:00
Timothy J. Baek e399b38654 Update languages.json 2024-04-26 16:58:46 -04:00
Timothy Jaeryang Baek b040a55591 Merge pull request #1783 from srizon/main
Added language support for Bangla (bn-BD)
2024-04-26 13:57:37 -07:00
Mamun Srizon 2968312b1c Finished remaining translation for Bangla (bn-BD) 2024-04-27 01:54:41 +06:00
Timothy J. Baek 8c97476140 chore: formatting 2024-04-26 14:49:03 -04:00
Timothy Jaeryang Baek 543707eefd Merge pull request #1756 from buroa/buroa/toggle-hybrid
feat: toggle hybrid search
2024-04-26 11:48:44 -07:00
Timothy J. Baek cebf733b9d refac: naming convention 2024-04-26 14:41:39 -04:00
Timothy Jaeryang Baek 81fb53e757 Merge pull request #1780 from cheahjs/fix/harden-streaming
fix: harden openai streaming parsing
2024-04-26 11:06:20 -07:00
Timothy Jaeryang Baek add5269b89 Merge pull request #1773 from Rmaan/fix-openrouter-streaming
Fixed OpenRouter heart beats breaking streaming
2024-04-26 11:05:52 -07:00
Jun Siang Cheah 615e9e348f fix: do not error out if OpenAI response has no delta 2024-04-26 18:42:43 +01:00
Jun Siang Cheah 510afab37c fix: catch any errors parsing openai sse events 2024-04-26 18:38:25 +01:00
Timothy Jaeryang Baek e9ba8d74d2 Merge pull request #1761 from Menghuan1918/dev
Improved translation quality for Simplified Chinese
2024-04-26 10:05:27 -07:00
Timothy Jaeryang Baek ddf06329a5 Merge pull request #1734 from darlanalves/env-docs-dir
feat: allow a docs directory coming from env
2024-04-26 09:59:34 -07:00
Mamun Srizon cac03fbcb1 Adding bn-BD for Bangla-Bangladesh language support 2024-04-26 22:35:19 +06:00
Arman Ordookhani 4ad7ef84a4 add else 2024-04-26 15:45:29 +02:00
Arman Ordookhani 7449634290 Fix OpenRouter hearbeats breaking streaming 2024-04-26 15:37:18 +02:00
Steven Kreitzer 69822e4c25 fix: sort ranking hybrid 2024-04-26 07:56:41 -05:00
Menghuan1918 7bc6a87697 Improved translation quality for Simplified Chinese 2024-04-26 13:06:16 +08:00
Steven Kreitzer 9755cd5baa feat: toggle hybrid search 2024-04-25 17:51:38 -05:00
Timothy J. Baek 984dbf13ab revert: original rag pipeline 2024-04-25 17:03:00 -04:00
Timothy Jaeryang Baek 7d88689f51 Merge pull request #1741 from domsleee/katex-render-performance
fix: Improve katex render performance in responses
2024-04-25 13:40:27 -07:00
Timothy J. Baek dcb92f7f74 refac: naming convention 2024-04-25 16:40:15 -04:00
Timothy Jaeryang Baek 02a241f831 Merge pull request #1753 from djismgaming/spanish-translation-v2
translation to Spanish of a new string
2024-04-25 13:37:07 -07:00
Timothy Jaeryang Baek fafaf48cb5 Merge pull request #1744 from aguvener/dev
fix: tr_TR translation synchronized with the latest updates.
2024-04-25 13:36:43 -07:00
Timothy Jaeryang Baek 6b4f344b96 Merge pull request #1748 from velaton618/main
Ukrainian translation update
2024-04-25 13:36:30 -07:00
Timothy Jaeryang Baek 5ee2f1729a Merge pull request #1693 from buroa/buroa/hybrid-search
feat: hybrid search with reranking
2024-04-25 13:12:18 -07:00
Ismael 15657627a6 small word change in Spanish translation 2024-04-25 14:51:17 -04:00
Steven Kreitzer 1c1d2c254d fix: query collection api call 2024-04-25 13:38:18 -05:00
Steven Kreitzer 72090fab88 chore: update log line 2024-04-25 13:28:31 -05:00
Steven Kreitzer e92680a566 chore: update changelog.md 2024-04-25 13:23:59 -05:00
Ismael 66f6123d76 translation to spanish of a new string 2024-04-25 13:43:01 -04:00
Steven Kreitzer c9c9660459 fix: address comment in pr #1687 2024-04-25 07:50:42 -05:00
velaton f9adfc50e4 Update translation.json
Changed to a word that is much more common
2024-04-25 17:26:56 +08:00
aguvener ad1b461b6c fix: synchronized with the latest updates. 2024-04-25 10:16:27 +03:00
Timothy J. Baek 232de33a86 fix: toast 2024-04-24 21:50:04 -04:00
Steven Kreitzer d5f60b119c Merge branch 'dev' into buroa/hybrid-search 2024-04-24 20:37:19 -05:00
Timothy Jaeryang Baek 1092ee9c1c Merge pull request #1739 from open-webui/dev
fix
2024-04-24 18:24:39 -07:00
Timothy J. Baek 7075837849 fix: missing import 2024-04-24 21:24:17 -04:00
Timothy Jaeryang Baek b508f184ee Merge pull request #1738 from open-webui/main
dev
2024-04-24 18:23:15 -07:00
Dom Slee 06a6136671 fix: improve katex render performance in responses 2024-04-25 11:14:37 +10:00
Darlan Alves 89e8813188 feat: allow a docs directory coming from env
Current config assumes /data/docs to be part of the current data directory.

This allows DOCS_DIR to be mounted from a different path outside of DATA_DIR, or falls back to the previous behaviour if DOCS_DIR is not in the environment
2024-04-25 00:40:39 +02:00
Timothy Jaeryang Baek 488f448f04 Merge pull request #1732 from dannyl1u/fix/chat-link 2024-04-24 14:36:13 -07:00
Danny Liu 95295061d0 fix: config var not defined 2024-04-24 14:31:03 -07:00
Steven Kreitzer adb009f388 Merge branch 'dev' into buroa/hybrid-search 2024-04-24 14:51:49 -05:00
Timothy Jaeryang Baek 748cb7d446 Merge pull request #1654 from open-webui/dev
Create and publish Docker images with specific build args / build-main-image (linux/amd64) (push) Failing after 47s
Create and publish Docker images with specific build args / build-main-image (linux/arm64) (push) Failing after 56s
Create and publish Docker images with specific build args / merge-main-images (push) Has been skipped
Create and publish Docker images with specific build args / build-cuda-image (linux/amd64) (push) Failing after 53s
Create and publish Docker images with specific build args / build-cuda-image (linux/arm64) (push) Failing after 49s
Create and publish Docker images with specific build args / merge-cuda-images (push) Has been skipped
Create and publish Docker images with specific build args / build-ollama-image (linux/amd64) (push) Failing after 1m3s
Create and publish Docker images with specific build args / build-ollama-image (linux/arm64) (push) Failing after 47s
Create and publish Docker images with specific build args / merge-ollama-images (push) Has been skipped
0.1.121
2024-04-24 12:31:01 -07:00
Timothy J. Baek 348186c405 Update CHANGELOG.md 2024-04-24 15:28:50 -04:00
Timothy J. Baek 08f7c2fd63 chore: format 2024-04-24 15:24:21 -04:00
Timothy J. Baek ed326f02c0 doc: changelog 2024-04-24 15:23:09 -04:00
Timothy Jaeryang Baek 1ec668f697 Merge pull request #1718 from velaton618/patch-1 2024-04-24 10:10:00 -07:00
Timothy Jaeryang Baek b591891464 Merge pull request #1704 from cheahjs/feat/litellm-config 2024-04-24 10:09:34 -07:00
Steven Kreitzer c0259aad67 feat: hybrid search and reranking support 2024-04-24 07:55:10 -05:00
velaton e318f92177 Update translation.json
Fixed some grammar mistakes
2024-04-24 17:12:02 +08:00
Silentoplayz 53b277e575 Update pull_request_template.md
fix
2024-04-24 06:02:25 +00:00
Timothy J. Baek 589de36af7 fix: #1705 2024-04-23 15:56:09 -04:00
Jun Siang Cheah 5245d037ac fix: harden litellm exec command to prevent unintended commands
logic was previously to split on space for arguments, but if any of the user controlled variables LITELLM_PROXY_HOST or DATA_DIR had spaces in them, this would not behave correctly.
2024-04-23 19:25:43 +01:00
Jun Siang Cheah 58bead0398 fix: DATA_DIR was not respected when loading litellm configs 2024-04-23 19:22:41 +01:00
Jun Siang Cheah 9e9306fd2b feat: add LITELLM_PROXY_HOST to configure address litellm listens on 2024-04-23 19:19:16 +01:00
Jun Siang Cheah 0ea9e19d79 feat: add LITELLM_PROXY_PORT to configure internal proxy port 2024-04-23 19:14:01 +01:00
Timothy Jaeryang Baek 86bc0c8c73 Merge pull request #1703 from Axodouble/patch-2
Fixed a single translation key for nl-NL
2024-04-23 11:02:40 -07:00
Axodouble 858f5ae1fe Fixed a single translation key for nl-NL
Fixed a single translation key.
2024-04-23 17:46:17 +02:00
Timothy J. Baek cc3312157b refac: model download 2024-04-23 07:36:46 -04:00
Timothy J. Baek 4809d363b3 Update manifest.json 2024-04-23 07:21:20 -04:00
Timothy J. Baek b1d204fdd4 feat: allow custom model name 2024-04-23 07:20:24 -04:00
Silentoplayz 29c6b253ca Update pull_request_template.md
Okay, no warning then.
2024-04-23 11:17:32 +00:00
Silentoplayz 4a536484a6 Update pull_request_template.md
Added failure to follow template warning
Made more concise
2024-04-23 11:14:54 +00:00
Timothy J. Baek 25d09363df feat: editable openai url for images 2024-04-23 07:14:31 -04:00
Timothy J. Baek aa489be53b Update config.py 2024-04-23 06:58:57 -04:00
Timothy J. Baek e3d253b040 feat: image env var 2024-04-23 06:53:04 -04:00
Steven Kreitzer db801aee79 Merge branch 'dev' into buroa/hybrid-search 2024-04-22 18:35:32 -05:00
Steven Kreitzer 4e0b32b505 feat: hybrid search 2024-04-22 18:33:43 -05:00
Timothy Jaeryang Baek 2d7d6cfffc Merge pull request #1630 from cheahjs/feat/split-large-chunks
feat: split large openai responses into smaller chunks
2024-04-22 13:56:26 -07:00
Timothy Jaeryang Baek ef5af1e273 Merge pull request #1686 from cheahjs/feat/add-store-types
feat: add types to some frontend stores
2024-04-22 13:55:57 -07:00
Timothy Jaeryang Baek 0546ad58be Merge pull request #1687 from buroa/buroa/huggingface-embeddings
feat: move to native `sentence_transformers`
2024-04-22 13:55:34 -07:00
Steven Kreitzer f3e5700d49 feat: move to native sentence_transformer 2024-04-22 14:20:41 -05:00
Jun Siang Cheah ed13da8aba feat: add types to some frontend stores 2024-04-22 20:08:32 +01:00
Timothy Jaeryang Baek 48e37973a3 Merge pull request #1688 from cheahjs/feat/disable-all-users-export
feat: add ALLOW_ADMIN_EXPORT to disable exporting of chats and the db
2024-04-22 11:57:44 -07:00
Jun Siang Cheah e2a8ad5fca address comments, rename to ENABLE_ADMIN_EXPORT 2024-04-22 19:55:46 +01:00
Jun Siang Cheah 190b934ab5 feat: add ALLOW_ADMIN_EXPORT to disable exporting of chats and the db 2024-04-22 19:44:24 +01:00
Timothy Jaeryang Baek 1e76dbc9a0 Merge pull request #1665 from dannyl1u/fix/html-br-tag-escaped
fix: <br> is not escaped in output text
2024-04-22 07:55:52 -07:00
Timothy J. Baek b3da09f52c chore: pl-PL renamed 2024-04-22 09:53:01 -05:00
Timothy J. Baek 4ab5050379 chore: pl-pl rm 2024-04-22 09:52:34 -05:00
Silentoplayz a615308111 Update pull_request_template.md
Fix
2024-04-22 07:19:09 +00:00
Danny Liu 40c1b49e6d chore: run format 2024-04-22 00:17:43 -07:00
Danny Liu 8e94618c51 fix: <br> is not escaped in output text 2024-04-22 00:16:05 -07:00
Silentoplayz dcb32f78fe Update pull_request_template.md
Overhaul
2024-04-22 07:11:59 +00:00
Timothy Jaeryang Baek 83efebe06b Merge pull request #1657 from open-webui/main
dev
2024-04-21 17:28:51 -07:00
Timothy J. Baek e6fad5ccb0 fix: safari copy share link issue 2024-04-21 19:28:16 -05:00
Timothy J. Baek 424141d1da fix: copy share link 2024-04-21 19:09:59 -05:00
Timothy J. Baek 4651db8c09 refac: litellm model name validation 2024-04-21 18:25:53 -05:00
Timothy Jaeryang Baek 5997774ab8 Merge pull request #1653 from open-webui/litellm-as-subprocess
fix: litellm as subprocess
2024-04-21 15:40:59 -07:00
Timothy J. Baek 760c62739a refac: improved error handling 2024-04-21 17:37:59 -05:00
Timothy J. Baek e627b8bf21 feat: litellm model add/delete 2024-04-21 17:26:22 -05:00
Timothy J. Baek 31124d9deb feat: litellm config update 2024-04-21 16:10:01 -05:00
Timothy Jaeryang Baek 56c93bc2ac Merge branch 'dev' into litellm-as-subprocess 2024-04-21 12:58:19 -07:00
Timothy J. Baek f83eb7326f Update requirements.txt 2024-04-21 14:44:28 -05:00
Timothy J. Baek 8422d3ea79 Update requirements.txt 2024-04-21 14:43:51 -05:00
Timothy J. Baek 77426266d2 refac: port number update 2024-04-21 14:32:45 -05:00
Timothy J. Baek 7d4f9134bc refac: styling 2024-04-21 13:24:46 -05:00
Timothy Jaeryang Baek 4d8ba5c7f0 Merge pull request #1651 from open-webui/dev
fix
2024-04-21 11:20:19 -07:00
Timothy J. Baek 4148d70ec0 fix 2024-04-21 13:19:48 -05:00
Timothy J. Baek 6f6be2c03f fix: styling 2024-04-21 13:16:45 -05:00
Timothy J. Baek bfdefbf6e7 fix: archived chats modal styling 2024-04-21 13:02:26 -05:00
Timothy Jaeryang Baek 063dabbf4a Merge pull request #1650 from open-webui/dev
fix
2024-04-21 10:55:29 -07:00
Timothy J. Baek 302c5074e9 revert: litellm bump 2024-04-21 12:50:14 -05:00
Timothy Jaeryang Baek f202a95661 Merge pull request #1647 from dyamagishi/comfyui_ws_schema
fix: Websocket Connection failed with ComfyUI server over HTTPS
2024-04-21 10:49:29 -07:00
Timothy Jaeryang Baek e82d9c873b Merge pull request #1644 from Entaigner/patch-6
Bugfix: FileReader can't be reused so init one per image
2024-04-21 10:47:24 -07:00
dyamagishi 489c45ffdf fix: Update websocket protocol based on the original schema. 2024-04-22 01:19:34 +09:00
Jun Siang Cheah 81b7cdfed7 fix: add typescript types for models 2024-04-21 11:41:18 +01:00
Jun Siang Cheah 67df928c7a feat: make chunk splitting a configurable option 2024-04-21 11:00:33 +01:00
Entaigner 743bbae5d1 Bugfix: FileReader can't be resused so init one per image 2024-04-21 11:54:30 +02:00
Timothy J. Baek 2717fe7c20 fix 2024-04-21 02:00:03 -05:00
Timothy J. Baek 51191168bc feat: restart subprocess route 2024-04-21 01:51:38 -05:00
Timothy J. Baek a59fb6b9eb fix 2024-04-21 01:47:35 -05:00
Timothy J. Baek 3c382d4c6c refac: close subprocess gracefully 2024-04-21 01:46:09 -05:00
Timothy J. Baek 8651bec915 pwned :) 2024-04-21 01:22:02 -05:00
Timothy J. Baek a41b195f46 DO NOT TRACK ME >:( 2024-04-21 01:13:24 -05:00
Timothy J. Baek 5e458d490a fix: run litellm as subprocess 2024-04-21 00:52:27 -05:00
Timothy J. Baek 948f2e913e chore: litellm bump 2024-04-20 23:53:08 -05:00
Timothy Jaeryang Baek aa4b2cc36f Merge pull request #1638 from Silentoplayz/patch-1
Update README.md
2024-04-20 20:56:05 -07:00
Timothy Jaeryang Baek df7517f9c4 Merge pull request #1639 from open-webui/dev
fix
2024-04-20 20:53:29 -07:00
Timothy J. Baek 98369fba22 fix 2024-04-20 22:53:00 -05:00
Silentoplayz 7a1f1d36a1 Update README.md
Updated features list
2024-04-21 03:12:48 +00:00
Timothy Jaeryang Baek 040ea70585 Merge pull request #1637 from open-webui/dev
fix
2024-04-20 19:15:58 -07:00
Timothy J. Baek 1cf4fa96c1 fix 2024-04-20 21:15:39 -05:00
Timothy Jaeryang Baek d19143dd2b Merge pull request #1636 from open-webui/dev
fix: multiuser duplicate tag issue
2024-04-20 19:13:20 -07:00
Timothy J. Baek fe3291acb5 fix: multiuser duplicate tag issue 2024-04-20 21:12:59 -05:00
Timothy Jaeryang Baek 9873cad3d6 Merge pull request #1635 from open-webui/dev
fix: settings getModels issue
2024-04-20 18:50:14 -07:00
Timothy J. Baek 1e919abda3 fix: settings getModels issue 2024-04-20 20:49:16 -05:00
Timothy Jaeryang Baek c533ed91f5 Merge pull request #1634 from open-webui/dev
fix
2024-04-20 18:37:36 -07:00
Timothy J. Baek 38321355d3 fix 2024-04-20 20:37:18 -05:00
Timothy Jaeryang Baek 22c50f62cb Merge pull request #1631 from open-webui/dev
Create and publish Docker images with specific build args / build-main-image (linux/amd64) (push) Failing after 49s
Create and publish Docker images with specific build args / build-main-image (linux/arm64) (push) Failing after 51s
Create and publish Docker images with specific build args / merge-main-images (push) Has been skipped
Create and publish Docker images with specific build args / build-cuda-image (linux/amd64) (push) Failing after 54s
Create and publish Docker images with specific build args / build-cuda-image (linux/arm64) (push) Failing after 53s
Create and publish Docker images with specific build args / merge-cuda-images (push) Has been skipped
Create and publish Docker images with specific build args / build-ollama-image (linux/amd64) (push) Failing after 55s
Create and publish Docker images with specific build args / build-ollama-image (linux/arm64) (push) Failing after 51s
Create and publish Docker images with specific build args / merge-ollama-images (push) Has been skipped
0.1.120
2024-04-20 17:41:00 -07:00
Timothy J. Baek eefe01454f refac: include archived flag in exports 2024-04-20 19:32:32 -05:00
Timothy J. Baek 74dd9b561a revert: export chats to include archived chats 2024-04-20 19:24:58 -05:00
Timothy J. Baek 2fd2f792d6 refac 2024-04-20 19:20:46 -05:00
Timothy J. Baek 93bd20b854 doc: changelog 2024-04-20 19:15:11 -05:00
Timothy J. Baek 291c7595c4 refac 2024-04-20 19:15:04 -05:00
Timothy J. Baek 68de49e533 fix: feedback area scroll into view 2024-04-20 19:10:05 -05:00
Timothy J. Baek d6a0805966 refac: audio settings 2024-04-20 19:01:46 -05:00
Timothy J. Baek a5f8e87f3f feat: archived chat link 2024-04-20 18:50:41 -05:00
Timothy J. Baek 45ecaaf392 feat: unarchive 2024-04-20 18:47:20 -05:00
Timothy J. Baek 4c221eabef refac 2024-04-20 18:29:14 -05:00
Timothy J. Baek b12edb4a7a refac: replace timestamp field 2024-04-20 18:24:18 -05:00
Timothy J. Baek 50e8979c00 Update README.md 2024-04-20 17:40:55 -05:00
Timothy J. Baek 459a41774e Update bug_report.md 2024-04-20 17:11:03 -05:00
Timothy J. Baek fbd520bf07 feat: archive chat 2024-04-20 17:03:39 -05:00
Timothy J. Baek 00b01c973e feat: archive button 2024-04-20 16:13:16 -05:00
Timothy Jaeryang Baek f04164378a Merge pull request #1632 from cheahjs/fix/error-object-object
fix: use model name when outputting error message
2024-04-20 14:05:23 -07:00
Timothy J. Baek c468df2f71 feat: env var for audio 2024-04-20 16:04:16 -05:00
Timothy J. Baek fa9593b4e8 refac: openai error message 2024-04-20 16:01:25 -05:00
Timothy J. Baek cbd18ec63c feat: external openai tts support 2024-04-20 16:00:24 -05:00
Jun Siang Cheah 7e5bda6016 fix: use model name when outputting error message 2024-04-20 21:24:02 +01:00
Timothy J. Baek 713934edb6 refac 2024-04-20 15:21:52 -05:00
Timothy J. Baek 710850e442 refac: audio 2024-04-20 15:15:59 -05:00
Timothy J. Baek 2a10438b4d feat: share from chat menu 2024-04-20 14:40:06 -05:00
Jun Siang Cheah efa258c695 feat: split large openai responses into smaller chunkers 2024-04-20 20:34:23 +01:00
Timothy J. Baek 7eb14437ff feat: shortcut 2024-04-20 14:26:27 -05:00
Timothy J. Baek 9451726ee6 feat: save edited message shortcut 2024-04-20 14:24:19 -05:00
Timothy J. Baek 97d68a6a05 feat: multiple files input
Co-Authored-By: Entaigner <61445450+entaigner@users.noreply.github.com>
2024-04-20 13:41:16 -05:00
Timothy Jaeryang Baek cd79afb425 Merge pull request #1624 from que-nguyen/dev
Add i18n translation for feedback reasons
2024-04-20 11:35:19 -07:00
Timothy J. Baek b79596332a chore: format 2024-04-20 13:35:01 -05:00
Timothy Jaeryang Baek 21cc6ebcb7 Merge pull request #1623 from que-nguyen/main
Fix hover and selected state issues for reason buttons in light theme.
2024-04-20 11:33:43 -07:00
Timothy Jaeryang Baek 80ecea980e Merge pull request #1622 from giga-t/main
Added Georgian Language (ka-GE)
2024-04-20 11:33:07 -07:00
Timothy Jaeryang Baek 4c8932d71c Merge pull request #1621 from Entaigner/patch-4
Tagged chat suggestion placeholders for translation (settings>interface)
2024-04-20 11:32:41 -07:00
Que Nguyen 7a5a3c45e0 Merge branch 'open-webui:dev' into dev 2024-04-20 13:26:49 +07:00
Que Nguyen 3df03fa3fe Add i18n translation for feedback reasons 2024-04-20 11:51:11 +07:00
Que Nguyen 77ec9dd1f2 Fix hover and selected state issues for reason buttons in light theme. 2024-04-20 11:03:47 +07:00
Giga 22b694e0fd Update translation.json
fixed one word.
2024-04-19 23:26:23 +02:00
Giga 5e9ace1c6e Add files via upload
Added Georgian translation (ka-GE).
2024-04-19 23:24:19 +02:00
Entaigner 76bd77bc56 Enable translation for chat suggestion placeholders (settings>interface) 2024-04-19 23:13:17 +02:00
Entaigner 4570f6fb0e Chose between "docker-compose" and "docker compose" in confirm_remove.sh 2024-04-19 20:19:24 +02:00
Entaigner e1e66f708f Chose between "docker-compose" and "docker compose" in Makefile 2024-04-19 19:30:25 +02:00
Timothy J. Baek a4083f43cb fix: safari copy link issue 2024-04-19 06:34:55 -05:00
Timothy Jaeryang Baek b67f80f7a4 Merge pull request #1600 from Fusseldieb/patch-1 2024-04-18 06:30:33 -07:00
Valentino Stillhardt a53c1cfc77 Fixed translated author name 2024-04-18 09:40:38 -03:00
Valentino Stillhardt b788514a10 Fixed translated author name 2024-04-18 09:38:26 -03:00
Valentino Stillhardt 5f16ec077a Fixed malformed time format 2024-04-18 09:34:03 -03:00
Valentino Stillhardt 941dc41c3d Fixed translated variable names and malformed date string 2024-04-18 09:28:10 -03:00
Valentino Stillhardt 44f9e930d2 Fixed malformed date string 2024-04-18 09:26:54 -03:00
Valentino Stillhardt c235a3d539 Fixed translated variable names 2024-04-18 09:25:39 -03:00
Valentino Stillhardt e720afacfa Fixed translated variable names 2024-04-18 09:24:29 -03:00
Valentino Stillhardt b352732b43 Fixed translated variable names 2024-04-18 09:19:55 -03:00
Valentino Stillhardt 0caf04617e Fixed translated variable name
"w" as in "week" was translated into "s" (as in "semana"), which is obviously wrong.
2024-04-18 09:17:35 -03:00
Timothy Jaeryang Baek e0ebd7aeaf Merge pull request #1590 from open-webui/dev
dev
2024-04-17 13:23:58 -07:00
Timothy Jaeryang Baek 2ffe55f128 Merge pull request #1584 from pkrolkgp/patch-2
Update translation.json
2024-04-17 13:22:59 -07:00
Timothy Jaeryang Baek 9d73f22aff Merge pull request #1586 from Fusseldieb/patch-1
Fixed malformed date string (again)
2024-04-17 13:22:38 -07:00
Timothy J. Baek 9dad7e7c9a fix 2024-04-17 15:22:21 -05:00
Valentino Stillhardt b5372bf715 Fixed malformed date string 2024-04-17 11:08:02 -03:00
pkrolkgp 20a3db975d Update translation.json
fix translated variable names to original
2024-04-17 12:28:32 +00:00
Timothy Jaeryang Baek 851754700a Merge pull request #1555 from open-webui/dev
Create and publish Docker images with specific build args / build-main-image (linux/amd64) (push) Failing after 59s
Create and publish Docker images with specific build args / build-main-image (linux/arm64) (push) Failing after 1m7s
Create and publish Docker images with specific build args / merge-main-images (push) Has been skipped
Create and publish Docker images with specific build args / build-cuda-image (linux/amd64) (push) Failing after 53s
Create and publish Docker images with specific build args / build-cuda-image (linux/arm64) (push) Failing after 1m0s
Create and publish Docker images with specific build args / merge-cuda-images (push) Has been skipped
Create and publish Docker images with specific build args / build-ollama-image (linux/amd64) (push) Failing after 52s
Create and publish Docker images with specific build args / build-ollama-image (linux/arm64) (push) Failing after 1m1s
Create and publish Docker images with specific build args / merge-ollama-images (push) Has been skipped
0.1.119
2024-04-16 15:12:52 -07:00
Timothy J. Baek 375056f8dc refac: wording 2024-04-16 17:11:05 -05:00
Timothy J. Baek 236e2c040c refac 2024-04-16 17:08:50 -05:00
Timothy J. Baek cf811edefb doc: changelog 2024-04-16 17:06:16 -05:00
Timothy J. Baek f6e839611b refac 2024-04-16 17:03:12 -05:00
Timothy J. Baek 2a79c30657 refac 2024-04-16 16:51:01 -05:00
Timothy J. Baek d882cb41ac chore: unused var 2024-04-16 16:43:19 -05:00
Timothy J. Baek 323b9adc63 feat: chat menu tag 2024-04-16 16:31:06 -05:00
Timothy J. Baek 3488b7f006 refac: changelog modal close behaviour 2024-04-16 16:01:12 -05:00
Timothy J. Baek daed66f7c6 feat: sidebar swipe support 2024-04-16 15:57:14 -05:00
Timothy Jaeryang Baek b219906fa3 Merge pull request #1580 from djismgaming/spanish-translation-update
Small fixes to the Spanish translation
2024-04-16 13:42:41 -07:00
Ismael a556e39651 little word fix 2024-04-16 16:30:13 -04:00
Ismael b35316177b translation, into Spanish, of imported strings from English 2024-04-16 16:24:27 -04:00
Ismael 3ed509c5d3 added new strings from English to be translated to Spanish 2024-04-16 16:15:23 -04:00
Ismael 6699f0c339 small fixes to the spanish translation 2024-04-16 15:59:33 -04:00
Timothy J. Baek 9dbd223b4e fix: formatting 2024-04-16 14:32:27 -05:00
Timothy J. Baek 11e0aaa32f revert 2024-04-16 14:32:02 -05:00
Timothy J. Baek 9aea0fb03d Update translation.json 2024-04-16 14:25:45 -05:00
Timothy J. Baek b51922809b Update languages.json 2024-04-16 14:24:15 -05:00
Timothy J. Baek 314b5b5f6c fix 2024-04-16 14:23:57 -05:00
Timothy Jaeryang Baek 7c0c11b776 Merge pull request #1573 from pkrolkgp/patch-1
Create translation.json for polish language
2024-04-16 12:18:14 -07:00
Timothy Jaeryang Baek 44ad7c4132 Merge pull request #1577 from justinh-rahb/pip2uv2
Switch `pip3` to `uv` in Dockerfile
2024-04-16 12:17:47 -07:00
Justin Hayes 748a930a5f Replace pip3 with uv 2024-04-16 09:57:32 -04:00
pkrolkgp dba45acbda Create translation.json for polish language
Created polish language translation
2024-04-16 12:09:57 +00:00
Timothy J. Baek ac7bb03cb3 chore: formatting 2024-04-14 20:19:16 -04:00
Timothy J. Baek 1be60c9729 chore: version bump 2024-04-14 20:13:00 -04:00
Timothy Jaeryang Baek 54a4b7db14 Merge pull request #1554 from open-webui/external-embeddings
feat: external embeddings
2024-04-14 16:57:57 -07:00
Timothy J. Baek 741ed5dc4c fix 2024-04-14 19:56:33 -04:00
Timothy J. Baek b1b72441bb feat: openai embeddings integration 2024-04-14 19:48:15 -04:00
Timothy J. Baek b48e73fa43 feat: openai embeddings support 2024-04-14 19:15:39 -04:00
Timothy Jaeryang Baek 2e0def73eb Merge pull request #1553 from open-webui/external-embeddings
feat: external embeddings support
2024-04-14 15:48:15 -07:00
Timothy J. Baek 36ce157907 fix: integration 2024-04-14 18:47:45 -04:00
Timothy J. Baek 9cdb5bf9fe feat: frontend integration 2024-04-14 18:31:40 -04:00
Timothy J. Baek 2952e61167 feat: external embeddings support 2024-04-14 17:55:00 -04:00
Timothy Jaeryang Baek 8b10b058e5 Merge pull request #1539 from cheahjs/feat/customizable-title-prompt-length
feat: add {{prompt:start:length}} and {{prompt:end:length}} to title gen
2024-04-14 14:04:39 -07:00
Timothy J. Baek 0c441b588c refac: naming convention 2024-04-14 17:04:24 -04:00
Timothy Jaeryang Baek a938ffb586 Merge branch 'dev' into feat/customizable-title-prompt-length 2024-04-14 14:02:53 -07:00
Timothy Jaeryang Baek b5d882606a Merge pull request #1499 from lainedfles/whisper_auto_update
feat: introduce Whisper model auto-update control.
2024-04-14 13:58:17 -07:00
Timothy Jaeryang Baek d9ce1d3ea3 Merge pull request #1544 from lainedfles/generation_info_approximate_total
feat: human readable Generation Info total
2024-04-14 13:57:23 -07:00
Timothy J. Baek 9091513c39 fix 2024-04-14 16:52:59 -04:00
Timothy J. Baek 0f5ecafc57 fix: api usage issue 2024-04-14 16:51:13 -04:00
Timothy J. Baek 98c16776f8 refac: styling 2024-04-14 16:41:58 -04:00
Timothy J. Baek 91dda2401d Update Selector.svelte 2024-04-14 16:29:27 -04:00
Timothy Jaeryang Baek 6238495d61 Merge pull request #1395 from 7a6ac0/admin_pagination
feat: admin panel user list pagination
2024-04-14 13:23:36 -07:00
Timothy J. Baek 0708a3d75e fix: styling 2024-04-14 16:23:13 -04:00
Timothy J. Baek b25e3ed364 refac 2024-04-14 16:19:46 -04:00
Timothy J. Baek 1fa3bf6793 fix: semi-lazy load 2024-04-14 15:44:19 -04:00
Self Denial b93337e62f Format fix 2024-04-13 22:41:22 -06:00
Self Denial d2d255228c Format fix 2024-04-13 22:39:10 -06:00
Self Denial 23b674ddda feat: human readable Generation Info total
Add new function to convert nanoseconds into `approximate_total:` for *Generation Info* tooltip.
2024-04-13 22:27:00 -06:00
Timothy Jaeryang Baek 0d3ce18a61 Merge pull request #1543 from lainedfles/fix-pr-1500 2024-04-13 19:04:31 -07:00
Self Denial 067c94810a Fix open-webui/open-webui#1500
Looks like the convention update per commit 0981fae161 missed `config.py`.
2024-04-13 19:55:43 -06:00
Timothy Jaeryang Baek 916ce9bc4f Merge pull request #1500 from lainedfles/config-image-generation-enabled
feat: add IMAGE_GENERATION_ENABLED env var
2024-04-13 14:51:01 -07:00
Timothy J. Baek 0981fae161 refac: convention 2024-04-13 14:50:45 -07:00
Timothy J. Baek 2649d29a3e fix: manifest.json issue 2024-04-13 14:42:38 -07:00
Timothy J. Baek 838778aa3e fix: typo 2024-04-13 14:40:54 -07:00
Timothy Jaeryang Baek 8c8388ea9f Merge pull request #1516 from que-nguyen/main
Update locales/vi-VN/translation.json
2024-04-13 14:39:27 -07:00
Timothy Jaeryang Baek b40054c54d Merge pull request #1534 from lainedfles/ollama-pull-qol
feat: small change to support ollama pull QOL
2024-04-13 14:39:13 -07:00
Jun Siang Cheah fffd42e4d7 fix: replace all instances of prompt:start and prompt:end 2024-04-13 18:44:49 +01:00
Jun Siang Cheah db817fcf29 feat: add {{prompt:start:length}} and {{prompt:end:length}} to title gen 2024-04-13 18:26:50 +01:00
Self Denial faa5884150 Use log.warning instead of log.debug 2024-04-13 03:18:13 -06:00
Self Denial 922628c1ee feat: small change to support ollama pull QOL
Use regex replace during trim "sanitize" to support `ollama run ` or `ollama pull ` syntax.
2024-04-13 03:04:11 -06:00
Timothy Jaeryang Baek 8e30948de9 Merge pull request #1532 from dariothornhill/1478-remove-trailing-slash
fix(helm): remove trailing slash
2024-04-13 00:06:29 -07:00
Dario Thornhill e08c144f0b fix(helm): remove trailing slash
The trailing `/` causes requests to be written with `//` and results in 404 responses from the ollama service.

This results in ollama models being unusable. Removing the training slash here resolves the issue.
2024-04-13 07:32:28 +02:00
Timothy Jaeryang Baek 51afb1e378 Merge pull request #1523 from 7a6ac0/call_before_defining
fix: Invoke the function before it is defined
2024-04-12 13:31:40 -07:00
tabacoWang c49cc3fa86 fix: Invoke the function before it is defined 2024-04-12 17:27:40 +08:00
Que Nguyen e17d66eb61 Update locales/vi-VN/translation.json
Fixed translation errors in Vietnamese locale file `locales/vi-VN/translation.json`
2024-04-12 09:44:40 +07:00
Timothy Jaeryang Baek d6260fd20c Merge pull request #1514 from JanSolo1/EMBBEDING-MODELS-COMMENT-FIX
Comment fix config.py ln 412
2024-04-11 18:53:12 -07:00
JanSolo1 79a4abc3ec Comment spelling mistake fix 2024-04-12 00:44:44 +02:00
JanSolo1 6623ecb302 Comment fix config.py ln 412 2024-04-12 00:36:48 +02:00
Timothy Jaeryang Baek 18a3f06a62 Merge pull request #1505 from Fusseldieb/patch-1
Fixed malformed date format
2024-04-11 09:55:28 -07:00
Valentino Stillhardt 1d8496eabb Fixed malformed date format 2024-04-11 10:58:46 -03:00
tabacoWang 8a9cf44dbc feat: combine with search result 2024-04-11 14:00:28 +08:00
tabacoWang 872ea83c50 feat: admin panel user list pagination 2024-04-11 14:00:28 +08:00
Self Denial ff01398812 Format fix 2024-04-10 23:39:11 -06:00
Self Denial 3b8ea55bc8 Add IMAGE_GENERATION_ENABLED env var
With default of `False`.
2024-04-10 23:21:12 -06:00
Self Denial 81c8717d75 Format fix 2024-04-10 20:44:44 -06:00
Self Denial 429242b4d3 Introduce Whisper model auto-update control.
* Introduce WHISPER_MODEL_AUTO_UPDATE env var
* Pass local_files_only to WhisperModel()
* Handle cases where auto-update is disabled but model is non-existent
2024-04-10 20:30:00 -06:00
251 changed files with 29393 additions and 8442 deletions
+2 -1
View File
@@ -10,7 +10,8 @@ OPENAI_API_KEY=''
# DO NOT TRACK
SCARF_NO_ANALYTICS=true
DO_NOT_TRACK=true
ANONYMIZED_TELEMETRY=false
# Use locally bundled version of the LiteLLM cost map json
# to avoid repetitive startup connections
LITELLM_LOCAL_MODEL_COST_MAP="True"
LITELLM_LOCAL_MODEL_COST_MAP="True"
+1
View File
@@ -4,6 +4,7 @@ module.exports = {
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:svelte/recommended',
'plugin:cypress/recommended',
'prettier'
],
parser: '@typescript-eslint/parser',
+3
View File
@@ -24,6 +24,9 @@ assignees: ''
## Environment
- **Open WebUI Version:** [e.g., 0.1.120]
- **Ollama (if applicable):** [e.g., 0.1.30, 0.1.32-rc1]
- **Operating System:** [e.g., Windows 10, macOS Big Sur, Ubuntu 20.04]
- **Browser (if applicable):** [e.g., Chrome 100.0, Firefox 98.0]
+11
View File
@@ -0,0 +1,11 @@
version: 2
updates:
- package-ecosystem: pip
directory: '/backend'
schedule:
interval: weekly
- package-ecosystem: 'github-actions'
directory: '/'
schedule:
# Check for updates to GitHub Actions every week
interval: 'weekly'
+57 -17
View File
@@ -1,32 +1,72 @@
## Pull Request Checklist
# Pull Request Checklist
- [ ] **Description:** Briefly describe the changes in this pull request.
### Note to first-time contributors: Please open a discussion post in [Discussions](https://github.com/open-webui/open-webui/discussions) and describe your changes before submitting a pull request.
**Before submitting, make sure you've checked the following:**
- [ ] **Target branch:** Please verify that the pull request targets the `dev` branch.
- [ ] **Description:** Provide a concise description of the changes made in this pull request.
- [ ] **Changelog:** Ensure a changelog entry following the format of [Keep a Changelog](https://keepachangelog.com/) is added at the bottom of the PR description.
- [ ] **Documentation:** Have you updated relevant documentation?
- [ ] **Documentation:** Have you updated relevant documentation [Open WebUI Docs](https://github.com/open-webui/docs), or other documentation sources?
- [ ] **Dependencies:** Are there any new dependencies? Have you updated the dependency versions in the documentation?
- [ ] **Testing:** Have you written and run sufficient tests for validating the changes?
- [ ] **Code review:** Have you performed a self-review of your code, addressing any coding standard issues and ensuring adherence to the project's coding standards?
- [ ] **Label:** To cleary categorize this pull request, assign a relevant label to the pull request title, using one of the following:
- **BREAKING CHANGE**: Significant changes that may affect compatibility
- **build**: Changes that affect the build system or external dependencies
- **ci**: Changes to our continuous integration processes or workflows
- **chore**: Refactor, cleanup, or other non-functional code changes
- **docs**: Documentation update or addition
- **feat**: Introduces a new feature or enhancement to the codebase
- **fix**: Bug fix or error correction
- **i18n**: Internationalization or localization changes
- **perf**: Performance improvement
- **refactor**: Code restructuring for better maintainability, readability, or scalability
- **style**: Changes that do not affect the meaning of the code (white-space, formatting, missing semi-colons, etc.)
- **test**: Adding missing tests or correcting existing tests
- **WIP**: Work in progress, a temporary label for incomplete or ongoing work
---
# Changelog Entry
## Description
### Description
[Insert a brief description of the changes made in this pull request]
---
### Changelog Entry
- [Concisely describe the changes made in this pull request, including any relevant motivation and impact (e.g., fixing a bug, adding a feature, or improving performance)]
### Added
- [List any new features or additions]
### Fixed
- [List any fixes or corrections]
- [List any new features, functionalities, or additions]
### Changed
- [List any changes or updates]
- [List any changes, updates, refactorings, or optimizations]
### Deprecated
- [List any deprecated functionality or features that have been removed]
### Removed
- [List any removed features or files]
- [List any removed features, files, or functionalities]
### Fixed
- [List any fixes, corrections, or bug fixes]
### Security
- [List any new or updated security-related changes, including vulnerability fixes]
### Breaking Changes
- **BREAKING CHANGE**: [List any breaking changes affecting compatibility or functionality]
---
### Additional Information
- [Insert any additional context, notes, or explanations for the changes]
- [Reference any related issues, commits, or other relevant information]
### Screenshots or Videos
- [Attach any relevant screenshots or videos demonstrating the changes]
@@ -29,8 +29,29 @@ jobs:
- name: Format Frontend
run: npm run format
- name: Run i18next
run: npm run i18n:parse
- name: Check for Changes After Format
run: git diff --exit-code
- name: Build Frontend
run: npm run build
test-frontend:
name: 'Frontend Unit Tests'
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: '20'
- name: Install Dependencies
run: npm ci
- name: Run vitest
run: npm run test:frontend
+195
View File
@@ -0,0 +1,195 @@
name: Integration Test
on:
push:
branches:
- main
- dev
pull_request:
branches:
- main
- dev
jobs:
cypress-run:
name: Run Cypress Integration Tests
runs-on: ubuntu-latest
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Build and run Compose Stack
run: |
docker compose --file docker-compose.yaml --file docker-compose.api.yaml up --detach --build
- name: Wait for Ollama to be up
timeout-minutes: 5
run: |
until curl --output /dev/null --silent --fail http://localhost:11434; do
printf '.'
sleep 1
done
echo "Service is up!"
- name: Preload Ollama model
run: |
docker exec ollama ollama pull qwen:0.5b-chat-v1.5-q2_K
- name: Cypress run
uses: cypress-io/github-action@v6
with:
browser: chrome
wait-on: 'http://localhost:3000'
config: baseUrl=http://localhost:3000
- uses: actions/upload-artifact@v4
if: always()
name: Upload Cypress videos
with:
name: cypress-videos
path: cypress/videos
if-no-files-found: ignore
- name: Extract Compose logs
if: always()
run: |
docker compose logs > compose-logs.txt
- uses: actions/upload-artifact@v4
if: always()
name: Upload Compose logs
with:
name: compose-logs
path: compose-logs.txt
if-no-files-found: ignore
migration_test:
name: Run Migration Tests
runs-on: ubuntu-latest
services:
postgres:
image: postgres
env:
POSTGRES_PASSWORD: postgres
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
ports:
- 5432:5432
# mysql:
# image: mysql
# env:
# MYSQL_ROOT_PASSWORD: mysql
# MYSQL_DATABASE: mysql
# options: >-
# --health-cmd "mysqladmin ping -h localhost"
# --health-interval 10s
# --health-timeout 5s
# --health-retries 5
# ports:
# - 3306:3306
steps:
- name: Checkout Repository
uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- name: Set up uv
uses: yezz123/setup-uv@v4
with:
uv-venv: venv
- name: Activate virtualenv
run: |
. venv/bin/activate
echo PATH=$PATH >> $GITHUB_ENV
- name: Install dependencies
run: |
uv pip install -r backend/requirements.txt
- name: Test backend with SQLite
id: sqlite
env:
WEBUI_SECRET_KEY: secret-key
GLOBAL_LOG_LEVEL: debug
run: |
cd backend
uvicorn main:app --port "8080" --forwarded-allow-ips '*' &
UVICORN_PID=$!
# Wait up to 20 seconds for the server to start
for i in {1..20}; do
curl -s http://localhost:8080/api/config > /dev/null && break
sleep 1
if [ $i -eq 20 ]; then
echo "Server failed to start"
kill -9 $UVICORN_PID
exit 1
fi
done
# Check that the server is still running after 5 seconds
sleep 5
if ! kill -0 $UVICORN_PID; then
echo "Server has stopped"
exit 1
fi
- name: Test backend with Postgres
if: success() || steps.sqlite.conclusion == 'failure'
env:
WEBUI_SECRET_KEY: secret-key
GLOBAL_LOG_LEVEL: debug
DATABASE_URL: postgresql://postgres:postgres@localhost:5432/postgres
run: |
cd backend
uvicorn main:app --port "8081" --forwarded-allow-ips '*' &
UVICORN_PID=$!
# Wait up to 20 seconds for the server to start
for i in {1..20}; do
curl -s http://localhost:8081/api/config > /dev/null && break
sleep 1
if [ $i -eq 20 ]; then
echo "Server failed to start"
kill -9 $UVICORN_PID
exit 1
fi
done
# Check that the server is still running after 5 seconds
sleep 5
if ! kill -0 $UVICORN_PID; then
echo "Server has stopped"
exit 1
fi
# - name: Test backend with MySQL
# if: success() || steps.sqlite.conclusion == 'failure' || steps.postgres.conclusion == 'failure'
# env:
# WEBUI_SECRET_KEY: secret-key
# GLOBAL_LOG_LEVEL: debug
# DATABASE_URL: mysql://root:mysql@localhost:3306/mysql
# run: |
# cd backend
# uvicorn main:app --port "8083" --forwarded-allow-ips '*' &
# UVICORN_PID=$!
# # Wait up to 20 seconds for the server to start
# for i in {1..20}; do
# curl -s http://localhost:8083/api/config > /dev/null && break
# sleep 1
# if [ $i -eq 20 ]; then
# echo "Server failed to start"
# kill -9 $UVICORN_PID
# exit 1
# fi
# done
# # Check that the server is still running after 5 seconds
# sleep 5
# if ! kill -0 $UVICORN_PID; then
# echo "Server has stopped"
# exit 1
# fi
+9 -1
View File
@@ -16,6 +16,10 @@ __pycache__/
# C extensions
*.so
# Pyodide distribution
static/pyodide/*
!static/pyodide/pyodide-lock.json
# Distribution / packaging
.Python
build/
@@ -297,4 +301,8 @@ dist
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
.pnp.*
# cypress artifacts
cypress/videos
cypress/screenshots
+306 -6
View File
@@ -1,3 +1,11 @@
# Ignore files for PNPM, NPM and YARN
pnpm-lock.yaml
package-lock.json
yarn.lock
kubernetes/
# Copy of .gitignore
.DS_Store
node_modules
/build
@@ -6,11 +14,303 @@ node_modules
.env
.env.*
!.env.example
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class
# Ignore files for PNPM, NPM and YARN
pnpm-lock.yaml
package-lock.json
yarn.lock
# C extensions
*.so
# Ignore kubernetes files
kubernetes
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
#poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
.idea/
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*
# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
# Runtime data
pids
*.pid
*.seed
*.pid.lock
# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov
# Coverage directory used by tools like istanbul
coverage
*.lcov
# nyc test coverage
.nyc_output
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt
# Bower dependency directory (https://bower.io/)
bower_components
# node-waf configuration
.lock-wscript
# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release
# Dependency directories
node_modules/
jspm_packages/
# Snowpack dependency directory (https://snowpack.dev/)
web_modules/
# TypeScript cache
*.tsbuildinfo
# Optional npm cache directory
.npm
# Optional eslint cache
.eslintcache
# Optional stylelint cache
.stylelintcache
# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/
# Optional REPL history
.node_repl_history
# Output of 'npm pack'
*.tgz
# Yarn Integrity file
.yarn-integrity
# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local
# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache
# Next.js build output
.next
out
# Nuxt.js build / generate output
.nuxt
dist
# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public
# vuepress build output
.vuepress/dist
# vuepress v2.x temp and cache directory
.temp
.cache
# Docusaurus cache and generated files
.docusaurus
# Serverless directories
.serverless/
# FuseBox cache
.fusebox/
# DynamoDB Local files
.dynamodb/
# TernJS port file
.tern-port
# Stores VSCode versions used for testing VSCode extensions
.vscode-test
# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*
# cypress artifacts
cypress/videos
cypress/screenshots
/static/*
+140
View File
@@ -5,6 +5,146 @@ 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.1.125] - 2024-05-19
### Added
- **🔄 Updated UI**: Chat interface revamped with chat bubbles. Easily switch back to the old style via settings > interface > chat bubble UI.
- **📂 Enhanced Sidebar UI**: Model files, documents, prompts, and playground merged into Workspace for streamlined access.
- **🚀 Improved Many Model Interaction**: All responses now displayed simultaneously for a smoother experience.
- **🐍 Python Code Execution**: Execute Python code locally in the browser with libraries like 'requests', 'beautifulsoup4', 'numpy', 'pandas', 'seaborn', 'matplotlib', 'scikit-learn', 'scipy', 'regex'.
- **🧠 Experimental Memory Feature**: Manually input personal information you want LLMs to remember via settings > personalization > memory.
- **💾 Persistent Settings**: Settings now saved as config.json for convenience.
- **🩺 Health Check Endpoint**: Added for Docker deployment.
- **↕️ RTL Support**: Toggle chat direction via settings > interface > chat direction.
- **🖥️ PowerPoint Support**: RAG pipeline now supports PowerPoint documents.
- **🌐 Language Updates**: Ukrainian, Turkish, Arabic, Chinese, Serbian, Vietnamese updated; Punjabi added.
### Changed
- **👤 Shared Chat Update**: Shared chat now includes creator user information.
## [0.1.124] - 2024-05-08
### Added
- **🖼️ Improved Chat Sidebar**: Now conveniently displays time ranges and organizes chats by today, yesterday, and more.
- **📜 Citations in RAG Feature**: Easily track the context fed to the LLM with added citations in the RAG feature.
- **🔒 Auth Disable Option**: Introducing the ability to disable authentication. Set 'WEBUI_AUTH' to False to disable authentication. Note: Only applicable for fresh installations without existing users.
- **📹 Enhanced YouTube RAG Pipeline**: Now supports non-English videos for an enriched experience.
- **🔊 Specify OpenAI TTS Models**: Customize your TTS experience by specifying OpenAI TTS models.
- **🔧 Additional Environment Variables**: Discover more environment variables in our comprehensive documentation at Open WebUI Documentation (https://docs.openwebui.com).
- **🌐 Language Support**: Arabic, Finnish, and Hindi added; Improved support for German, Vietnamese, and Chinese.
### Fixed
- **🛠️ Model Selector Styling**: Addressed styling issues for improved user experience.
- **⚠️ Warning Messages**: Resolved backend warning messages.
### Changed
- **📝 Title Generation**: Limited output to 50 tokens.
- **📦 Helm Charts**: Removed Helm charts, now available in a separate repository (https://github.com/open-webui/helm-charts).
## [0.1.123] - 2024-05-02
### Added
- **🎨 New Landing Page Design**: Refreshed design for a more modern look and optimized use of screen space.
- **📹 Youtube RAG Pipeline**: Introduces dedicated RAG pipeline for Youtube videos, enabling interaction with video transcriptions directly.
- **🔧 Enhanced Admin Panel**: Streamlined user management with options to add users directly or in bulk via CSV import.
- **👥 '@' Model Integration**: Easily switch to specific models during conversations; old collaborative chat feature phased out.
- **🌐 Language Enhancements**: Swedish translation added, plus improvements to German, Spanish, and the addition of Doge translation.
### Fixed
- **🗑️ Delete Chat Shortcut**: Addressed issue where shortcut wasn't functioning.
- **🖼️ Modal Closing Bug**: Resolved unexpected closure of modal when dragging from within.
- **✏️ Edit Button Styling**: Fixed styling inconsistency with edit buttons.
- **🌐 Image Generation Compatibility Issue**: Rectified image generation compatibility issue with third-party APIs.
- **📱 iOS PWA Icon Fix**: Corrected iOS PWA home screen icon shape.
- **🔍 Scroll Gesture Bug**: Adjusted gesture sensitivity to prevent accidental activation when scrolling through code on mobile; now requires scrolling from the leftmost side to open the sidebar.
### Changed
- **🔄 Unlimited Context Length**: Advanced settings now allow unlimited max context length (previously limited to 16000).
- **👑 Super Admin Assignment**: The first signup is automatically assigned a super admin role, unchangeable by other admins.
- **🛡️ Admin User Restrictions**: User action buttons from the admin panel are now disabled for users with admin roles.
- **🔝 Default Model Selector**: Set as default model option now exclusively available on the landing page.
## [0.1.122] - 2024-04-27
### Added
- **🌟 Enhanced RAG Pipeline**: Now with hybrid searching via 'BM25', reranking powered by 'CrossEncoder', and configurable relevance score thresholds.
- **🛢️ External Database Support**: Seamlessly connect to custom SQLite or Postgres databases using the 'DATABASE_URL' environment variable.
- **🌐 Remote ChromaDB Support**: Introducing the capability to connect to remote ChromaDB servers.
- **👨‍💼 Improved Admin Panel**: Admins can now conveniently check users' chat lists and last active status directly from the admin panel.
- **🎨 Splash Screen**: Introducing a loading splash screen for a smoother user experience.
- **🌍 Language Support Expansion**: Added support for Bangla (bn-BD), along with enhancements to Chinese, Spanish, and Ukrainian translations.
- **💻 Improved LaTeX Rendering Performance**: Enjoy faster rendering times for LaTeX equations.
- **🔧 More Environment Variables**: Explore additional environment variables in our documentation (https://docs.openwebui.com), including the 'ENABLE_LITELLM' option to manage memory usage.
### Fixed
- **🔧 Ollama Compatibility**: Resolved errors occurring when Ollama server version isn't an integer, such as SHA builds or RCs.
- **🐛 Various OpenAI API Issues**: Addressed several issues related to the OpenAI API.
- **🛑 Stop Sequence Issue**: Fixed the problem where the stop sequence with a backslash '\' was not functioning.
- **🔤 Font Fallback**: Corrected font fallback issue.
### Changed
- **⌨️ Prompt Input Behavior on Mobile**: Enter key prompt submission disabled on mobile devices for improved user experience.
## [0.1.121] - 2024-04-24
### Fixed
- **🔧 Translation Issues**: Addressed various translation discrepancies.
- **🔒 LiteLLM Security Fix**: Updated LiteLLM version to resolve a security vulnerability.
- **🖥️ HTML Tag Display**: Rectified the issue where the '< br >' tag wasn't displaying correctly.
- **🔗 WebSocket Connection**: Resolved the failure of WebSocket connection under HTTPS security for ComfyUI server.
- **📜 FileReader Optimization**: Implemented FileReader initialization per image in multi-file drag & drop to ensure reusability.
- **🏷️ Tag Display**: Corrected tag display inconsistencies.
- **📦 Archived Chat Styling**: Fixed styling issues in archived chat.
- **🔖 Safari Copy Button Bug**: Addressed the bug where the copy button failed to copy links in Safari.
## [0.1.120] - 2024-04-20
### Added
- **📦 Archive Chat Feature**: Easily archive chats with a new sidebar button, and access archived chats via the profile button > archived chats.
- **🔊 Configurable Text-to-Speech Endpoint**: Customize your Text-to-Speech experience with configurable OpenAI endpoints.
- **🛠️ Improved Error Handling**: Enhanced error message handling for connection failures.
- **⌨️ Enhanced Shortcut**: When editing messages, use ctrl/cmd+enter to save and submit, and esc to close.
- **🌐 Language Support**: Added support for Georgian and enhanced translations for Portuguese and Vietnamese.
### Fixed
- **🔧 Model Selector**: Resolved issue where default model selection was not saving.
- **🔗 Share Link Copy Button**: Fixed bug where the copy button wasn't copying links in Safari.
- **🎨 Light Theme Styling**: Addressed styling issue with the light theme.
## [0.1.119] - 2024-04-16
### Added
- **🌟 Enhanced RAG Embedding Support**: Ollama, and OpenAI models can now be used for RAG embedding model.
- **🔄 Seamless Integration**: Copy 'ollama run <model name>' directly from Ollama page to easily select and pull models.
- **🏷️ Tagging Feature**: Add tags to chats directly via the sidebar chat menu.
- **📱 Mobile Accessibility**: Swipe left and right on mobile to effortlessly open and close the sidebar.
- **🔍 Improved Navigation**: Admin panel now supports pagination for user list.
- **🌍 Additional Language Support**: Added Polish language support.
### Fixed
- **🌍 Language Enhancements**: Vietnamese and Spanish translations have been improved.
- **🔧 Helm Fixes**: Resolved issues with Helm trailing slash and manifest.json.
### Changed
- **🐳 Docker Optimization**: Updated docker image build process to utilize 'uv' for significantly faster builds compared to 'pip3'.
## [0.1.118] - 2024-04-10
### Added
+71 -39
View File
@@ -8,8 +8,12 @@ ARG USE_CUDA_VER=cu121
# any sentence transformer model; models to use can be found at https://huggingface.co/models?library=sentence-transformers
# Leaderboard: https://huggingface.co/spaces/mteb/leaderboard
# for better performance and multilangauge support use "intfloat/multilingual-e5-large" (~2.5GB) or "intfloat/multilingual-e5-base" (~1.5GB)
# IMPORTANT: If you change the default model (all-MiniLM-L6-v2) and vice versa, you aren't able to use RAG Chat with your previous documents loaded in the WebUI! You need to re-embed them.
ARG USE_EMBEDDING_MODEL=all-MiniLM-L6-v2
# IMPORTANT: If you change the embedding model (sentence-transformers/all-MiniLM-L6-v2) and vice versa, you aren't able to use RAG Chat with your previous documents loaded in the WebUI! You need to re-embed them.
ARG USE_EMBEDDING_MODEL=sentence-transformers/all-MiniLM-L6-v2
ARG USE_RERANKING_MODEL=""
# Override at your own risk - non-root configurations are untested
ARG UID=0
ARG GID=0
######## WebUI frontend ########
FROM --platform=$BUILDPLATFORM node:21-alpine3.19 as build
@@ -30,6 +34,9 @@ ARG USE_CUDA
ARG USE_OLLAMA
ARG USE_CUDA_VER
ARG USE_EMBEDDING_MODEL
ARG USE_RERANKING_MODEL
ARG UID
ARG GID
## Basis ##
ENV ENV=prod \
@@ -38,7 +45,8 @@ ENV ENV=prod \
USE_OLLAMA_DOCKER=${USE_OLLAMA} \
USE_CUDA_DOCKER=${USE_CUDA} \
USE_CUDA_DOCKER_VER=${USE_CUDA_VER} \
USE_EMBEDDING_MODEL_DOCKER=${USE_EMBEDDING_MODEL}
USE_EMBEDDING_MODEL_DOCKER=${USE_EMBEDDING_MODEL} \
USE_RERANKING_MODEL_DOCKER=${USE_RERANKING_MODEL}
## Basis URL Config ##
ENV OLLAMA_BASE_URL="/ollama" \
@@ -48,7 +56,8 @@ ENV OLLAMA_BASE_URL="/ollama" \
ENV OPENAI_API_KEY="" \
WEBUI_SECRET_KEY="" \
SCARF_NO_ANALYTICS=true \
DO_NOT_TRACK=true
DO_NOT_TRACK=true \
ANONYMIZED_TELEMETRY=false
# Use locally bundled version of the LiteLLM cost map json
# to avoid repetitive startup connections
@@ -62,48 +71,67 @@ ENV WHISPER_MODEL="base" \
## RAG Embedding model settings ##
ENV RAG_EMBEDDING_MODEL="$USE_EMBEDDING_MODEL_DOCKER" \
RAG_EMBEDDING_MODEL_DIR="/app/backend/data/cache/embedding/models" \
RAG_RERANKING_MODEL="$USE_RERANKING_MODEL_DOCKER" \
SENTENCE_TRANSFORMERS_HOME="/app/backend/data/cache/embedding/models"
## Hugging Face download cache ##
ENV HF_HOME="/app/backend/data/cache/embedding/models"
#### Other models ##########################################################
WORKDIR /app/backend
ENV HOME /root
# Create user and group if not root
RUN if [ $UID -ne 0 ]; then \
if [ $GID -ne 0 ]; then \
addgroup --gid $GID app; \
fi; \
adduser --uid $UID --gid $GID --home $HOME --disabled-password --no-create-home app; \
fi
RUN mkdir -p $HOME/.cache/chroma
RUN echo -n 00000000-0000-0000-0000-000000000000 > $HOME/.cache/chroma/telemetry_user_id
# 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 pandoc netcat-openbsd && \
# for RAG OCR
apt-get install -y --no-install-recommends ffmpeg libsm6 libxext6 && \
# install helper tools
apt-get install -y --no-install-recommends curl && \
# install ollama
curl -fsSL https://ollama.com/install.sh | sh && \
# cleanup
rm -rf /var/lib/apt/lists/*; \
apt-get update && \
# Install pandoc and netcat
apt-get install -y --no-install-recommends pandoc netcat-openbsd curl && \
# 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 and netcat
apt-get install -y --no-install-recommends pandoc netcat-openbsd && \
# for RAG OCR
apt-get install -y --no-install-recommends ffmpeg libsm6 libxext6 && \
# cleanup
rm -rf /var/lib/apt/lists/*; \
apt-get update && \
# Install pandoc and netcat
apt-get install -y --no-install-recommends pandoc netcat-openbsd curl jq && \
# for RAG OCR
apt-get install -y --no-install-recommends ffmpeg libsm6 libxext6 && \
# cleanup
rm -rf /var/lib/apt/lists/*; \
fi
# install python dependencies
COPY ./backend/requirements.txt ./requirements.txt
COPY --chown=$UID:$GID ./backend/requirements.txt ./requirements.txt
RUN 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 && \
pip3 install -r requirements.txt --no-cache-dir && \
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; from chromadb.utils import embedding_functions; sentence_transformer_ef = embedding_functions.SentenceTransformerEmbeddingFunction(model_name=os.environ['RAG_EMBEDDING_MODEL'], device='cpu')"; \
RUN pip3 install uv && \
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 && \
uv pip install --system -r requirements.txt --no-cache-dir && \
python -c "import os; from sentence_transformers import SentenceTransformer; SentenceTransformer(os.environ['RAG_EMBEDDING_MODEL'], device='cpu')" && \
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'])"; \
else \
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu --no-cache-dir && \
pip3 install -r requirements.txt --no-cache-dir && \
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; from chromadb.utils import embedding_functions; sentence_transformer_ef = embedding_functions.SentenceTransformerEmbeddingFunction(model_name=os.environ['RAG_EMBEDDING_MODEL'], device='cpu')"; \
pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu --no-cache-dir && \
uv pip install --system -r requirements.txt --no-cache-dir && \
python -c "import os; from sentence_transformers import SentenceTransformer; SentenceTransformer(os.environ['RAG_EMBEDDING_MODEL'], device='cpu')" && \
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'])"; \
fi
@@ -113,13 +141,17 @@ RUN if [ "$USE_CUDA" = "true" ]; then \
# COPY --from=build /app/onnx /root/.cache/chroma/onnx_models/all-MiniLM-L6-v2/onnx
# copy built frontend files
COPY --from=build /app/build /app/build
COPY --from=build /app/CHANGELOG.md /app/CHANGELOG.md
COPY --from=build /app/package.json /app/package.json
COPY --chown=$UID:$GID --from=build /app/build /app/build
COPY --chown=$UID:$GID --from=build /app/CHANGELOG.md /app/CHANGELOG.md
COPY --chown=$UID:$GID --from=build /app/package.json /app/package.json
# copy backend files
COPY ./backend .
COPY --chown=$UID:$GID ./backend .
EXPOSE 8080
CMD [ "bash", "start.sh"]
HEALTHCHECK CMD curl --silent --fail http://localhost:8080/health | jq -e '.status == true' || exit 1
USER $UID:$GID
CMD [ "bash", "start.sh"]
+14 -8
View File
@@ -1,27 +1,33 @@
ifneq ($(shell which docker-compose 2>/dev/null),)
DOCKER_COMPOSE := docker-compose
else
DOCKER_COMPOSE := docker compose
endif
install:
@docker-compose up -d
$(DOCKER_COMPOSE) up -d
remove:
@chmod +x confirm_remove.sh
@./confirm_remove.sh
start:
@docker-compose start
$(DOCKER_COMPOSE) start
startAndBuild:
docker-compose up -d --build
$(DOCKER_COMPOSE) up -d --build
stop:
@docker-compose stop
$(DOCKER_COMPOSE) stop
update:
# Calls the LLM update script
chmod +x update_ollama_models.sh
@./update_ollama_models.sh
@git pull
@docker-compose down
$(DOCKER_COMPOSE) down
# Make sure the ollama-webui container is stopped before rebuilding
@docker stop open-webui || true
@docker-compose up --build -d
@docker-compose start
$(DOCKER_COMPOSE) up --build -d
$(DOCKER_COMPOSE) start
+76 -20
View File
@@ -25,22 +25,28 @@ Open WebUI is an extensible, feature-rich, and user-friendly self-hosted WebUI d
- 🚀 **Effortless Setup**: Install seamlessly using Docker or Kubernetes (kubectl, kustomize or helm) for a hassle-free experience.
- 🌈 **Theme Customization**: Choose from a variety of themes to personalize your Open WebUI experience.
- 💻 **Code Syntax Highlighting**: Enjoy enhanced code readability with our syntax highlighting feature.
- ✒️🔢 **Full Markdown and LaTeX Support**: Elevate your LLM experience with comprehensive Markdown and LaTeX capabilities for enriched interaction.
- 📚 **Local RAG Integration**: Dive into the future of chat interactions with the groundbreaking Retrieval Augmented Generation (RAG) support. This feature seamlessly integrates document interactions into your chat experience. You can load documents directly into the chat or add files to your document library, effortlessly accessing them using `#` command in the prompt. In its alpha phase, occasional issues may arise as we actively refine and enhance this feature to ensure optimal performance and reliability.
- 🔍 **RAG Embedding Support**: Change the RAG embedding model directly in document settings, enhancing document processing. This feature supports Ollama and OpenAI models.
- 🌐 **Web Browsing Capability**: Seamlessly integrate websites into your chat experience using the `#` command followed by the URL. This feature allows you to incorporate web content directly into your conversations, enhancing the richness and depth of your interactions.
- 📜 **Prompt Preset Support**: Instantly access preset prompts using the `/` command in the chat input. Load predefined conversation starters effortlessly and expedite your interactions. Effortlessly import prompts through [Open WebUI Community](https://openwebui.com/) integration.
- 👍👎 **RLHF Annotation**: Empower your messages by rating them with thumbs up and thumbs down, facilitating the creation of datasets for Reinforcement Learning from Human Feedback (RLHF). Utilize your messages to train or fine-tune models, all while ensuring the confidentiality of locally saved data.
- 👍👎 **RLHF Annotation**: Empower your messages by rating them with thumbs up and thumbs down, followed by the option to provide textual feedback, facilitating the creation of datasets for Reinforcement Learning from Human Feedback (RLHF). Utilize your messages to train or fine-tune models, all while ensuring the confidentiality of locally saved data.
- 🏷️ **Conversation Tagging**: Effortlessly categorize and locate specific chats for quick reference and streamlined data collection.
- 📥🗑️ **Download/Delete Models**: Easily download or remove models directly from the web UI.
- 🔄 **Update All Ollama Models**: Easily update locally installed models all at once with a convenient button, streamlining model management.
- ⬆️ **GGUF File Model Creation**: Effortlessly create Ollama models by uploading GGUF files directly from the web UI. Streamlined process with options to upload from your machine or download GGUF files from Hugging Face.
- 🤖 **Multiple Model Support**: Seamlessly switch between different chat models for diverse interactions.
@@ -53,28 +59,42 @@ Open WebUI is an extensible, feature-rich, and user-friendly self-hosted WebUI d
- 💬 **Collaborative Chat**: Harness the collective intelligence of multiple models by seamlessly orchestrating group conversations. Use the `@` command to specify the model, enabling dynamic and diverse dialogues within your chat interface. Immerse yourself in the collective intelligence woven into your chat environment.
- 🗨️ **Local Chat Sharing**: Generate and share chat links seamlessly between users, enhancing collaboration and communication.
- 🔄 **Regeneration History Access**: Easily revisit and explore your entire regeneration history.
- 📜 **Chat History**: Effortlessly access and manage your conversation history.
- 📬 **Archive Chats**: Effortlessly store away completed conversations with LLMs for future reference, maintaining a tidy and clutter-free chat interface while allowing for easy retrieval and reference.
- 📤📥 **Import/Export Chat History**: Seamlessly move your chat data in and out of the platform.
- 🗣️ **Voice Input Support**: Engage with your model through voice interactions; enjoy the convenience of talking to your model directly. Additionally, explore the option for sending voice input automatically after 3 seconds of silence for a streamlined experience.
- 🔊 **Configurable Text-to-Speech Endpoint**: Customize your Text-to-Speech experience with configurable OpenAI endpoints.
- ⚙️ **Fine-Tuned Control with Advanced Parameters**: Gain a deeper level of control by adjusting parameters such as temperature and defining your system prompts to tailor the conversation to your specific preferences and needs.
- 🎨🤖 **Image Generation Integration**: Seamlessly incorporate image generation capabilities using AUTOMATIC1111 API (local) and DALL-E, enriching your chat experience with dynamic visual content.
- 🎨🤖 **Image Generation Integration**: Seamlessly incorporate image generation capabilities using options such as AUTOMATIC1111 API (local), ComfyUI (local), and DALL-E, enriching your chat experience with dynamic visual content.
- 🤝 **OpenAI API Integration**: Effortlessly integrate OpenAI-compatible API for versatile conversations alongside Ollama models. Customize the API Base URL to link with **LMStudio, Mistral, OpenRouter, and more**.
-**Multiple OpenAI-Compatible API Support**: Seamlessly integrate and customize various OpenAI-compatible APIs, enhancing the versatility of your chat interactions.
- 🔑 **API Key Generation Support**: Generate secret keys to leverage Open WebUI with OpenAI libraries, simplifying integration and development.
- 🔗 **External Ollama Server Connection**: Seamlessly link to an external Ollama server hosted on a different address by configuring the environment variable.
- 🔀 **Multiple Ollama Instance Load Balancing**: Effortlessly distribute chat requests across multiple Ollama instances for enhanced performance and reliability.
- 👥 **Multi-User Management**: Easily oversee and administer users via our intuitive admin panel, streamlining user management processes.
- 🔗 **Webhook Integration**: Subscribe to new user sign-up events via webhook (compatible with Google Chat and Microsoft Teams), providing real-time notifications and automation capabilities.
- 🛡️ **Model Whitelisting**: Admins can whitelist models for users with the 'user' role, enhancing security and access control.
- 📧 **Trusted Email Authentication**: Authenticate using a trusted email header, adding an additional layer of security and authentication.
- 🔐 **Role-Based Access Control (RBAC)**: Ensure secure access with restricted permissions; only authorized individuals can access your Ollama, and exclusive model creation/pulling rights are reserved for administrators.
- 🔒 **Backend Reverse Proxy Support**: Bolster security through direct communication between Open WebUI backend and Ollama. This key feature eliminates the need to expose Ollama over LAN. Requests made to the '/ollama/api' route from the web UI are seamlessly redirected to Ollama from the backend, enhancing overall system security.
@@ -100,22 +120,66 @@ Don't forget to explore our sibling project, [Open WebUI Community](https://open
> [!TIP]
> If you wish to utilize Open WebUI with Ollama included or CUDA acceleration, we recommend utilizing our official images tagged with either `:cuda` or `:ollama`. To enable CUDA, you must install the [Nvidia CUDA container toolkit](https://docs.nvidia.com/dgx/nvidia-container-runtime-upgrade/) on your Linux/WSL system.
**If Ollama is on your computer**, use this command:
### Installation with Default Configuration
```bash
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
```
- **If Ollama is on your computer**, use this command:
**If Ollama is on a Different Server**, use this command:
```bash
docker run -d -p 3000:8080 --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
```
To connect to Ollama on another server, change the `OLLAMA_BASE_URL` to the server's URL:
- **If Ollama is on a Different Server**, use this command:
```bash
docker run -d -p 3000:8080 -e OLLAMA_BASE_URL=https://example.com -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
```
To connect to Ollama on another server, change the `OLLAMA_BASE_URL` to the server's URL:
```bash
docker run -d -p 3000:8080 -e OLLAMA_BASE_URL=https://example.com -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
```
- **To run Open WebUI with Nvidia GPU support**, use this command:
```bash
docker run -d -p 3000:8080 --gpus all --add-host=host.docker.internal:host-gateway -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:cuda
```
### Installation for OpenAI API Usage Only
- **If you're only using OpenAI API**, use this command:
```bash
docker run -d -p 3000:8080 -e OPENAI_API_KEY=your_secret_key -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:main
```
### Installing Open WebUI with Bundled Ollama Support
This installation method uses a single container image that bundles Open WebUI with Ollama, allowing for a streamlined setup via a single command. Choose the appropriate command based on your hardware setup:
- **With GPU Support**:
Utilize GPU resources by running the following command:
```bash
docker run -d -p 3000:8080 --gpus=all -v ollama:/root/.ollama -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:ollama
```
- **For CPU Only**:
If you're not using a GPU, use this command instead:
```bash
docker run -d -p 3000:8080 -v ollama:/root/.ollama -v open-webui:/app/backend/data --name open-webui --restart always ghcr.io/open-webui/open-webui:ollama
```
Both commands facilitate a built-in, hassle-free installation of both Open WebUI and Ollama, ensuring that you can get everything up and running swiftly.
After installation, you can access Open WebUI at [http://localhost:3000](http://localhost:3000). Enjoy! 😄
### Other Installation Methods
We offer various installation alternatives, including non-Docker native installation methods, Docker Compose, Kustomize, and Helm. Visit our [Open WebUI Documentation](https://docs.openwebui.com/getting-started/) or join our [Discord community](https://discord.gg/5rJgQTnV4s) for comprehensive guidance.
### Troubleshooting
Encountering connection issues? Our [Open WebUI Documentation](https://docs.openwebui.com/troubleshooting/) has got you covered. For further assistance and to join our vibrant community, visit the [Open WebUI Discord](https://discord.gg/5rJgQTnV4s).
#### Open WebUI: Server Connection Error
If you're experiencing connection issues, its often due to the WebUI docker container not being able to reach the Ollama server at 127.0.0.1:11434 (host.docker.internal:11434) inside the container . Use the `--network=host` flag in your docker command to resolve this. Note that the port changes from 3000 to 8080, resulting in the link: `http://localhost:8080`.
@@ -126,14 +190,6 @@ If you're experiencing connection issues, its often due to the WebUI docker c
docker run -d --network=host -v open-webui:/app/backend/data -e OLLAMA_BASE_URL=http://127.0.0.1:11434 --name open-webui --restart always ghcr.io/open-webui/open-webui:main
```
### Other Installation Methods
We offer various installation alternatives, including non-Docker methods, Docker Compose, Kustomize, and Helm. Visit our [Open WebUI Documentation](https://docs.openwebui.com/getting-started/) or join our [Discord community](https://discord.gg/5rJgQTnV4s) for comprehensive guidance.
### Troubleshooting
Encountering connection issues? Our [Open WebUI Documentation](https://docs.openwebui.com/getting-started/troubleshooting/) has got you covered. For further assistance and to join our vibrant community, visit the [Open WebUI Discord](https://discord.gg/5rJgQTnV4s).
### Keeping Your Docker Installation Up-to-Date
In case you want to update your local Docker installation to the latest version, you can do it with [Watchtower](https://containrrr.dev/watchtower/):
@@ -185,4 +241,4 @@ If you have any questions, suggestions, or need assistance, please open an issue
---
Created by [Timothy J. Baek](https://github.com/tjbck) - Let's make Open Web UI even more amazing together! 💪
Created by [Timothy J. Baek](https://github.com/tjbck) - Let's make Open WebUI even more amazing together! 💪
+138 -7
View File
@@ -10,8 +10,19 @@ from fastapi import (
File,
Form,
)
from fastapi.responses import StreamingResponse, JSONResponse, FileResponse
from fastapi.middleware.cors import CORSMiddleware
from faster_whisper import WhisperModel
from pydantic import BaseModel
import requests
import hashlib
from pathlib import Path
import json
from constants import ERROR_MESSAGES
from utils.utils import (
@@ -28,7 +39,13 @@ from config import (
UPLOAD_DIR,
WHISPER_MODEL,
WHISPER_MODEL_DIR,
WHISPER_MODEL_AUTO_UPDATE,
DEVICE_TYPE,
AUDIO_OPENAI_API_BASE_URL,
AUDIO_OPENAI_API_KEY,
AUDIO_OPENAI_API_MODEL,
AUDIO_OPENAI_API_VOICE,
AppConfig,
)
log = logging.getLogger(__name__)
@@ -43,12 +60,114 @@ app.add_middleware(
allow_headers=["*"],
)
app.state.config = AppConfig()
app.state.config.OPENAI_API_BASE_URL = AUDIO_OPENAI_API_BASE_URL
app.state.config.OPENAI_API_KEY = AUDIO_OPENAI_API_KEY
app.state.config.OPENAI_API_MODEL = AUDIO_OPENAI_API_MODEL
app.state.config.OPENAI_API_VOICE = AUDIO_OPENAI_API_VOICE
# setting device type for whisper model
whisper_device_type = DEVICE_TYPE if DEVICE_TYPE and DEVICE_TYPE == "cuda" else "cpu"
log.info(f"whisper_device_type: {whisper_device_type}")
SPEECH_CACHE_DIR = Path(CACHE_DIR).joinpath("./audio/speech/")
SPEECH_CACHE_DIR.mkdir(parents=True, exist_ok=True)
@app.post("/transcribe")
class OpenAIConfigUpdateForm(BaseModel):
url: str
key: str
model: str
speaker: str
@app.get("/config")
async def get_openai_config(user=Depends(get_admin_user)):
return {
"OPENAI_API_BASE_URL": app.state.config.OPENAI_API_BASE_URL,
"OPENAI_API_KEY": app.state.config.OPENAI_API_KEY,
"OPENAI_API_MODEL": app.state.config.OPENAI_API_MODEL,
"OPENAI_API_VOICE": app.state.config.OPENAI_API_VOICE,
}
@app.post("/config/update")
async def update_openai_config(
form_data: OpenAIConfigUpdateForm, user=Depends(get_admin_user)
):
if form_data.key == "":
raise HTTPException(status_code=400, detail=ERROR_MESSAGES.API_KEY_NOT_FOUND)
app.state.config.OPENAI_API_BASE_URL = form_data.url
app.state.config.OPENAI_API_KEY = form_data.key
app.state.config.OPENAI_API_MODEL = form_data.model
app.state.config.OPENAI_API_VOICE = form_data.speaker
return {
"status": True,
"OPENAI_API_BASE_URL": app.state.config.OPENAI_API_BASE_URL,
"OPENAI_API_KEY": app.state.config.OPENAI_API_KEY,
"OPENAI_API_MODEL": app.state.config.OPENAI_API_MODEL,
"OPENAI_API_VOICE": app.state.config.OPENAI_API_VOICE,
}
@app.post("/speech")
async def speech(request: Request, user=Depends(get_verified_user)):
body = await request.body()
name = hashlib.sha256(body).hexdigest()
file_path = SPEECH_CACHE_DIR.joinpath(f"{name}.mp3")
file_body_path = SPEECH_CACHE_DIR.joinpath(f"{name}.json")
# Check if the file already exists in the cache
if file_path.is_file():
return FileResponse(file_path)
headers = {}
headers["Authorization"] = f"Bearer {app.state.config.OPENAI_API_KEY}"
headers["Content-Type"] = "application/json"
r = None
try:
r = requests.post(
url=f"{app.state.config.OPENAI_API_BASE_URL}/audio/speech",
data=body,
headers=headers,
stream=True,
)
r.raise_for_status()
# Save the streaming content to a file
with open(file_path, "wb") as f:
for chunk in r.iter_content(chunk_size=8192):
f.write(chunk)
with open(file_body_path, "w") as f:
json.dump(json.loads(body.decode("utf-8")), f)
# Return the saved file
return FileResponse(file_path)
except Exception as e:
log.exception(e)
error_detail = "Open WebUI: Server Connection Error"
if r is not None:
try:
res = r.json()
if "error" in res:
error_detail = f"External: {res['error']['message']}"
except:
error_detail = f"External: {e}"
raise HTTPException(
status_code=r.status_code if r != None else 500,
detail=error_detail,
)
@app.post("/transcriptions")
def transcribe(
file: UploadFile = File(...),
user=Depends(get_current_user),
@@ -69,12 +188,24 @@ def transcribe(
f.write(contents)
f.close()
model = WhisperModel(
WHISPER_MODEL,
device=whisper_device_type,
compute_type="int8",
download_root=WHISPER_MODEL_DIR,
)
whisper_kwargs = {
"model_size_or_path": WHISPER_MODEL,
"device": whisper_device_type,
"compute_type": "int8",
"download_root": WHISPER_MODEL_DIR,
"local_files_only": not WHISPER_MODEL_AUTO_UPDATE,
}
log.debug(f"whisper_kwargs: {whisper_kwargs}")
try:
model = WhisperModel(**whisper_kwargs)
except:
log.warning(
"WhisperModel initialization failed, attempting download with local_files_only=False"
)
whisper_kwargs["local_files_only"] = False
model = WhisperModel(**whisper_kwargs)
segments, info = model.transcribe(file_path, beam_size=5)
log.info(
+164 -96
View File
@@ -24,12 +24,26 @@ from utils.misc import calculate_sha256
from typing import Optional
from pydantic import BaseModel
from pathlib import Path
import mimetypes
import uuid
import base64
import json
import logging
from config import SRC_LOG_LEVELS, CACHE_DIR, AUTOMATIC1111_BASE_URL, COMFYUI_BASE_URL
from config import (
SRC_LOG_LEVELS,
CACHE_DIR,
IMAGE_GENERATION_ENGINE,
ENABLE_IMAGE_GENERATION,
AUTOMATIC1111_BASE_URL,
COMFYUI_BASE_URL,
IMAGES_OPENAI_API_BASE_URL,
IMAGES_OPENAI_API_KEY,
IMAGE_GENERATION_MODEL,
IMAGE_SIZE,
IMAGE_STEPS,
AppConfig,
)
log = logging.getLogger(__name__)
@@ -47,24 +61,31 @@ app.add_middleware(
allow_headers=["*"],
)
app.state.ENGINE = ""
app.state.ENABLED = False
app.state.config = AppConfig()
app.state.OPENAI_API_KEY = ""
app.state.MODEL = ""
app.state.config.ENGINE = IMAGE_GENERATION_ENGINE
app.state.config.ENABLED = ENABLE_IMAGE_GENERATION
app.state.config.OPENAI_API_BASE_URL = IMAGES_OPENAI_API_BASE_URL
app.state.config.OPENAI_API_KEY = IMAGES_OPENAI_API_KEY
app.state.config.MODEL = IMAGE_GENERATION_MODEL
app.state.AUTOMATIC1111_BASE_URL = AUTOMATIC1111_BASE_URL
app.state.COMFYUI_BASE_URL = COMFYUI_BASE_URL
app.state.config.AUTOMATIC1111_BASE_URL = AUTOMATIC1111_BASE_URL
app.state.config.COMFYUI_BASE_URL = COMFYUI_BASE_URL
app.state.IMAGE_SIZE = "512x512"
app.state.IMAGE_STEPS = 50
app.state.config.IMAGE_SIZE = IMAGE_SIZE
app.state.config.IMAGE_STEPS = IMAGE_STEPS
@app.get("/config")
async def get_config(request: Request, user=Depends(get_admin_user)):
return {"engine": app.state.ENGINE, "enabled": app.state.ENABLED}
return {
"engine": app.state.config.ENGINE,
"enabled": app.state.config.ENABLED,
}
class ConfigUpdateForm(BaseModel):
@@ -74,9 +95,12 @@ class ConfigUpdateForm(BaseModel):
@app.post("/config/update")
async def update_config(form_data: ConfigUpdateForm, user=Depends(get_admin_user)):
app.state.ENGINE = form_data.engine
app.state.ENABLED = form_data.enabled
return {"engine": app.state.ENGINE, "enabled": app.state.ENABLED}
app.state.config.ENGINE = form_data.engine
app.state.config.ENABLED = form_data.enabled
return {
"engine": app.state.config.ENGINE,
"enabled": app.state.config.ENABLED,
}
class EngineUrlUpdateForm(BaseModel):
@@ -87,8 +111,8 @@ class EngineUrlUpdateForm(BaseModel):
@app.get("/url")
async def get_engine_url(user=Depends(get_admin_user)):
return {
"AUTOMATIC1111_BASE_URL": app.state.AUTOMATIC1111_BASE_URL,
"COMFYUI_BASE_URL": app.state.COMFYUI_BASE_URL,
"AUTOMATIC1111_BASE_URL": app.state.config.AUTOMATIC1111_BASE_URL,
"COMFYUI_BASE_URL": app.state.config.COMFYUI_BASE_URL,
}
@@ -98,54 +122,60 @@ async def update_engine_url(
):
if form_data.AUTOMATIC1111_BASE_URL == None:
app.state.AUTOMATIC1111_BASE_URL = AUTOMATIC1111_BASE_URL
app.state.config.AUTOMATIC1111_BASE_URL = AUTOMATIC1111_BASE_URL
else:
url = form_data.AUTOMATIC1111_BASE_URL.strip("/")
try:
r = requests.head(url)
app.state.AUTOMATIC1111_BASE_URL = url
app.state.config.AUTOMATIC1111_BASE_URL = url
except Exception as e:
raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(e))
if form_data.COMFYUI_BASE_URL == None:
app.state.COMFYUI_BASE_URL = COMFYUI_BASE_URL
app.state.config.COMFYUI_BASE_URL = COMFYUI_BASE_URL
else:
url = form_data.COMFYUI_BASE_URL.strip("/")
try:
r = requests.head(url)
app.state.COMFYUI_BASE_URL = url
app.state.config.COMFYUI_BASE_URL = url
except Exception as e:
raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(e))
return {
"AUTOMATIC1111_BASE_URL": app.state.AUTOMATIC1111_BASE_URL,
"COMFYUI_BASE_URL": app.state.COMFYUI_BASE_URL,
"AUTOMATIC1111_BASE_URL": app.state.config.AUTOMATIC1111_BASE_URL,
"COMFYUI_BASE_URL": app.state.config.COMFYUI_BASE_URL,
"status": True,
}
class OpenAIKeyUpdateForm(BaseModel):
class OpenAIConfigUpdateForm(BaseModel):
url: str
key: str
@app.get("/key")
async def get_openai_key(user=Depends(get_admin_user)):
return {"OPENAI_API_KEY": app.state.OPENAI_API_KEY}
@app.get("/openai/config")
async def get_openai_config(user=Depends(get_admin_user)):
return {
"OPENAI_API_BASE_URL": app.state.config.OPENAI_API_BASE_URL,
"OPENAI_API_KEY": app.state.config.OPENAI_API_KEY,
}
@app.post("/key/update")
async def update_openai_key(
form_data: OpenAIKeyUpdateForm, user=Depends(get_admin_user)
@app.post("/openai/config/update")
async def update_openai_config(
form_data: OpenAIConfigUpdateForm, user=Depends(get_admin_user)
):
if form_data.key == "":
raise HTTPException(status_code=400, detail=ERROR_MESSAGES.API_KEY_NOT_FOUND)
app.state.OPENAI_API_KEY = form_data.key
app.state.config.OPENAI_API_BASE_URL = form_data.url
app.state.config.OPENAI_API_KEY = form_data.key
return {
"OPENAI_API_KEY": app.state.OPENAI_API_KEY,
"status": True,
"OPENAI_API_BASE_URL": app.state.config.OPENAI_API_BASE_URL,
"OPENAI_API_KEY": app.state.config.OPENAI_API_KEY,
}
@@ -155,7 +185,7 @@ class ImageSizeUpdateForm(BaseModel):
@app.get("/size")
async def get_image_size(user=Depends(get_admin_user)):
return {"IMAGE_SIZE": app.state.IMAGE_SIZE}
return {"IMAGE_SIZE": app.state.config.IMAGE_SIZE}
@app.post("/size/update")
@@ -164,9 +194,9 @@ async def update_image_size(
):
pattern = r"^\d+x\d+$" # Regular expression pattern
if re.match(pattern, form_data.size):
app.state.IMAGE_SIZE = form_data.size
app.state.config.IMAGE_SIZE = form_data.size
return {
"IMAGE_SIZE": app.state.IMAGE_SIZE,
"IMAGE_SIZE": app.state.config.IMAGE_SIZE,
"status": True,
}
else:
@@ -182,7 +212,7 @@ class ImageStepsUpdateForm(BaseModel):
@app.get("/steps")
async def get_image_size(user=Depends(get_admin_user)):
return {"IMAGE_STEPS": app.state.IMAGE_STEPS}
return {"IMAGE_STEPS": app.state.config.IMAGE_STEPS}
@app.post("/steps/update")
@@ -190,9 +220,9 @@ async def update_image_size(
form_data: ImageStepsUpdateForm, user=Depends(get_admin_user)
):
if form_data.steps >= 0:
app.state.IMAGE_STEPS = form_data.steps
app.state.config.IMAGE_STEPS = form_data.steps
return {
"IMAGE_STEPS": app.state.IMAGE_STEPS,
"IMAGE_STEPS": app.state.config.IMAGE_STEPS,
"status": True,
}
else:
@@ -205,14 +235,14 @@ async def update_image_size(
@app.get("/models")
def get_models(user=Depends(get_current_user)):
try:
if app.state.ENGINE == "openai":
if app.state.config.ENGINE == "openai":
return [
{"id": "dall-e-2", "name": "DALL·E 2"},
{"id": "dall-e-3", "name": "DALL·E 3"},
]
elif app.state.ENGINE == "comfyui":
elif app.state.config.ENGINE == "comfyui":
r = requests.get(url=f"{app.state.COMFYUI_BASE_URL}/object_info")
r = requests.get(url=f"{app.state.config.COMFYUI_BASE_URL}/object_info")
info = r.json()
return list(
@@ -224,7 +254,7 @@ def get_models(user=Depends(get_current_user)):
else:
r = requests.get(
url=f"{app.state.AUTOMATIC1111_BASE_URL}/sdapi/v1/sd-models"
url=f"{app.state.config.AUTOMATIC1111_BASE_URL}/sdapi/v1/sd-models"
)
models = r.json()
return list(
@@ -234,23 +264,29 @@ def get_models(user=Depends(get_current_user)):
)
)
except Exception as e:
app.state.ENABLED = False
app.state.config.ENABLED = False
raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(e))
@app.get("/models/default")
async def get_default_model(user=Depends(get_admin_user)):
try:
if app.state.ENGINE == "openai":
return {"model": app.state.MODEL if app.state.MODEL else "dall-e-2"}
elif app.state.ENGINE == "comfyui":
return {"model": app.state.MODEL if app.state.MODEL else ""}
if app.state.config.ENGINE == "openai":
return {
"model": (
app.state.config.MODEL if app.state.config.MODEL else "dall-e-2"
)
}
elif app.state.config.ENGINE == "comfyui":
return {"model": (app.state.config.MODEL if app.state.config.MODEL else "")}
else:
r = requests.get(url=f"{app.state.AUTOMATIC1111_BASE_URL}/sdapi/v1/options")
r = requests.get(
url=f"{app.state.config.AUTOMATIC1111_BASE_URL}/sdapi/v1/options"
)
options = r.json()
return {"model": options["sd_model_checkpoint"]}
except Exception as e:
app.state.ENABLED = False
app.state.config.ENABLED = False
raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(e))
@@ -259,20 +295,20 @@ class UpdateModelForm(BaseModel):
def set_model_handler(model: str):
if app.state.ENGINE == "openai":
app.state.MODEL = model
return app.state.MODEL
if app.state.ENGINE == "comfyui":
app.state.MODEL = model
return app.state.MODEL
if app.state.config.ENGINE in ["openai", "comfyui"]:
app.state.config.MODEL = model
return app.state.config.MODEL
else:
r = requests.get(url=f"{app.state.AUTOMATIC1111_BASE_URL}/sdapi/v1/options")
r = requests.get(
url=f"{app.state.config.AUTOMATIC1111_BASE_URL}/sdapi/v1/options"
)
options = r.json()
if model != options["sd_model_checkpoint"]:
options["sd_model_checkpoint"] = model
r = requests.post(
url=f"{app.state.AUTOMATIC1111_BASE_URL}/sdapi/v1/options", json=options
url=f"{app.state.config.AUTOMATIC1111_BASE_URL}/sdapi/v1/options",
json=options,
)
return options
@@ -295,35 +331,61 @@ class GenerateImageForm(BaseModel):
def save_b64_image(b64_str):
image_id = str(uuid.uuid4())
file_path = IMAGE_CACHE_DIR.joinpath(f"{image_id}.png")
try:
# Split the base64 string to get the actual image data
img_data = base64.b64decode(b64_str)
image_id = str(uuid.uuid4())
# Write the image data to a file
with open(file_path, "wb") as f:
f.write(img_data)
if "," in b64_str:
header, encoded = b64_str.split(",", 1)
mime_type = header.split(";")[0]
img_data = base64.b64decode(encoded)
image_format = mimetypes.guess_extension(mime_type)
image_filename = f"{image_id}{image_format}"
file_path = IMAGE_CACHE_DIR / f"{image_filename}"
with open(file_path, "wb") as f:
f.write(img_data)
return image_filename
else:
image_filename = f"{image_id}.png"
file_path = IMAGE_CACHE_DIR.joinpath(image_filename)
img_data = base64.b64decode(b64_str)
# Write the image data to a file
with open(file_path, "wb") as f:
f.write(img_data)
return image_filename
return image_id
except Exception as e:
log.error(f"Error saving image: {e}")
log.exception(f"Error saving image: {e}")
return None
def save_url_image(url):
image_id = str(uuid.uuid4())
file_path = IMAGE_CACHE_DIR.joinpath(f"{image_id}.png")
try:
r = requests.get(url)
r.raise_for_status()
if r.headers["content-type"].split("/")[0] == "image":
with open(file_path, "wb") as image_file:
image_file.write(r.content)
mime_type = r.headers["content-type"]
image_format = mimetypes.guess_extension(mime_type)
if not image_format:
raise ValueError("Could not determine image type from MIME type")
image_filename = f"{image_id}{image_format}"
file_path = IMAGE_CACHE_DIR.joinpath(f"{image_filename}")
with open(file_path, "wb") as image_file:
for chunk in r.iter_content(chunk_size=8192):
image_file.write(chunk)
return image_filename
else:
log.error(f"Url does not point to an image.")
return None
return image_id
except Exception as e:
log.exception(f"Error saving image: {e}")
return None
@@ -335,26 +397,32 @@ def generate_image(
user=Depends(get_current_user),
):
width, height = tuple(map(int, app.state.IMAGE_SIZE.split("x")))
width, height = tuple(map(int, app.state.config.IMAGE_SIZE.split("x")))
r = None
try:
if app.state.ENGINE == "openai":
if app.state.config.ENGINE == "openai":
headers = {}
headers["Authorization"] = f"Bearer {app.state.OPENAI_API_KEY}"
headers["Authorization"] = f"Bearer {app.state.config.OPENAI_API_KEY}"
headers["Content-Type"] = "application/json"
data = {
"model": app.state.MODEL if app.state.MODEL != "" else "dall-e-2",
"model": (
app.state.config.MODEL
if app.state.config.MODEL != ""
else "dall-e-2"
),
"prompt": form_data.prompt,
"n": form_data.n,
"size": form_data.size if form_data.size else app.state.IMAGE_SIZE,
"size": (
form_data.size if form_data.size else app.state.config.IMAGE_SIZE
),
"response_format": "b64_json",
}
r = requests.post(
url=f"https://api.openai.com/v1/images/generations",
url=f"{app.state.config.OPENAI_API_BASE_URL}/images/generations",
json=data,
headers=headers,
)
@@ -365,16 +433,16 @@ def generate_image(
images = []
for image in res["data"]:
image_id = save_b64_image(image["b64_json"])
images.append({"url": f"/cache/image/generations/{image_id}.png"})
file_body_path = IMAGE_CACHE_DIR.joinpath(f"{image_id}.json")
image_filename = save_b64_image(image["b64_json"])
images.append({"url": f"/cache/image/generations/{image_filename}"})
file_body_path = IMAGE_CACHE_DIR.joinpath(f"{image_filename}.json")
with open(file_body_path, "w") as f:
json.dump(data, f)
return images
elif app.state.ENGINE == "comfyui":
elif app.state.config.ENGINE == "comfyui":
data = {
"prompt": form_data.prompt,
@@ -383,28 +451,28 @@ def generate_image(
"n": form_data.n,
}
if app.state.IMAGE_STEPS != None:
data["steps"] = app.state.IMAGE_STEPS
if app.state.config.IMAGE_STEPS is not None:
data["steps"] = app.state.config.IMAGE_STEPS
if form_data.negative_prompt != None:
if form_data.negative_prompt is not None:
data["negative_prompt"] = form_data.negative_prompt
data = ImageGenerationPayload(**data)
res = comfyui_generate_image(
app.state.MODEL,
app.state.config.MODEL,
data,
user.id,
app.state.COMFYUI_BASE_URL,
app.state.config.COMFYUI_BASE_URL,
)
log.debug(f"res: {res}")
images = []
for image in res["data"]:
image_id = save_url_image(image["url"])
images.append({"url": f"/cache/image/generations/{image_id}.png"})
file_body_path = IMAGE_CACHE_DIR.joinpath(f"{image_id}.json")
image_filename = save_url_image(image["url"])
images.append({"url": f"/cache/image/generations/{image_filename}"})
file_body_path = IMAGE_CACHE_DIR.joinpath(f"{image_filename}.json")
with open(file_body_path, "w") as f:
json.dump(data.model_dump(exclude_none=True), f)
@@ -422,14 +490,14 @@ def generate_image(
"height": height,
}
if app.state.IMAGE_STEPS != None:
data["steps"] = app.state.IMAGE_STEPS
if app.state.config.IMAGE_STEPS is not None:
data["steps"] = app.state.config.IMAGE_STEPS
if form_data.negative_prompt != None:
if form_data.negative_prompt is not None:
data["negative_prompt"] = form_data.negative_prompt
r = requests.post(
url=f"{app.state.AUTOMATIC1111_BASE_URL}/sdapi/v1/txt2img",
url=f"{app.state.config.AUTOMATIC1111_BASE_URL}/sdapi/v1/txt2img",
json=data,
)
@@ -440,9 +508,9 @@ def generate_image(
images = []
for image in res["images"]:
image_id = save_b64_image(image)
images.append({"url": f"/cache/image/generations/{image_id}.png"})
file_body_path = IMAGE_CACHE_DIR.joinpath(f"{image_id}.json")
image_filename = save_b64_image(image)
images.append({"url": f"/cache/image/generations/{image_filename}"})
file_body_path = IMAGE_CACHE_DIR.joinpath(f"{image_filename}.json")
with open(file_body_path, "w") as f:
json.dump({**data, "info": res["info"]}, f)
+2 -2
View File
@@ -195,7 +195,7 @@ class ImageGenerationPayload(BaseModel):
def comfyui_generate_image(
model: str, payload: ImageGenerationPayload, client_id, base_url
):
host = base_url.replace("http://", "").replace("https://", "")
ws_url = base_url.replace("http://", "ws://").replace("https://", "wss://")
comfyui_prompt = json.loads(COMFYUI_DEFAULT_PROMPT)
@@ -217,7 +217,7 @@ def comfyui_generate_image(
try:
ws = websocket.WebSocket()
ws.connect(f"ws://{host}/ws?clientId={client_id}")
ws.connect(f"{ws_url}/ws?clientId={client_id}")
log.info("WebSocket connection established.")
except Exception as e:
log.exception(f"Failed to connect to WebSocket server: {e}")
+340 -61
View File
@@ -1,100 +1,379 @@
import sys
from contextlib import asynccontextmanager
from fastapi import FastAPI, Depends, HTTPException
from fastapi.routing import APIRoute
from fastapi.middleware.cors import CORSMiddleware
import logging
from litellm.proxy.proxy_server import ProxyConfig, initialize
from litellm.proxy.proxy_server import app
from fastapi import FastAPI, Request, Depends, status, Response
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.responses import StreamingResponse
import json
import time
import requests
from utils.utils import get_http_authorization_cred, get_current_user
from pydantic import BaseModel, ConfigDict
from typing import Optional, List
from utils.utils import get_verified_user, get_current_user, get_admin_user
from config import SRC_LOG_LEVELS, ENV
from constants import MESSAGES
import os
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["LITELLM"])
from config import (
MODEL_FILTER_ENABLED,
ENABLE_LITELLM,
ENABLE_MODEL_FILTER,
MODEL_FILTER_LIST,
DATA_DIR,
LITELLM_PROXY_PORT,
LITELLM_PROXY_HOST,
)
import warnings
warnings.simplefilter("ignore")
from litellm.utils import get_llm_provider
import asyncio
import subprocess
import yaml
@asynccontextmanager
async def lifespan(app: FastAPI):
log.info("startup_event")
# TODO: Check config.yaml file and create one
asyncio.create_task(start_litellm_background())
yield
app = FastAPI(lifespan=lifespan)
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
proxy_config = ProxyConfig()
LITELLM_CONFIG_DIR = f"{DATA_DIR}/litellm/config.yaml"
with open(LITELLM_CONFIG_DIR, "r") as file:
litellm_config = yaml.safe_load(file)
async def config():
router, model_list, general_settings = await proxy_config.load_config(
router=None, config_file_path="./data/litellm/config.yaml"
)
await initialize(config="./data/litellm/config.yaml", telemetry=False)
app.state.ENABLE_MODEL_FILTER = ENABLE_MODEL_FILTER.value
app.state.MODEL_FILTER_LIST = MODEL_FILTER_LIST.value
async def startup():
await config()
app.state.ENABLE = ENABLE_LITELLM
app.state.CONFIG = litellm_config
# Global variable to store the subprocess reference
background_process = None
CONFLICT_ENV_VARS = [
# Uvicorn uses PORT, so LiteLLM might use it as well
"PORT",
# LiteLLM uses DATABASE_URL for Prisma connections
"DATABASE_URL",
]
@app.on_event("startup")
async def on_startup():
await startup()
app.state.MODEL_FILTER_ENABLED = MODEL_FILTER_ENABLED
app.state.MODEL_FILTER_LIST = MODEL_FILTER_LIST
@app.middleware("http")
async def auth_middleware(request: Request, call_next):
auth_header = request.headers.get("Authorization", "")
request.state.user = None
async def run_background_process(command):
global background_process
log.info("run_background_process")
try:
user = get_current_user(get_http_authorization_cred(auth_header))
log.debug(f"user: {user}")
request.state.user = user
# Log the command to be executed
log.info(f"Executing command: {command}")
# Filter environment variables known to conflict with litellm
env = {k: v for k, v in os.environ.items() if k not in CONFLICT_ENV_VARS}
# Execute the command and create a subprocess
process = await asyncio.create_subprocess_exec(
*command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, env=env
)
background_process = process
log.info("Subprocess started successfully.")
# Capture STDERR for debugging purposes
stderr_output = await process.stderr.read()
stderr_text = stderr_output.decode().strip()
if stderr_text:
log.info(f"Subprocess STDERR: {stderr_text}")
# log.info output line by line
async for line in process.stdout:
log.info(line.decode().strip())
# Wait for the process to finish
returncode = await process.wait()
log.info(f"Subprocess exited with return code {returncode}")
except Exception as e:
return JSONResponse(status_code=400, content={"detail": str(e)})
response = await call_next(request)
return response
log.error(f"Failed to start subprocess: {e}")
raise # Optionally re-raise the exception if you want it to propagate
class ModifyModelsResponseMiddleware(BaseHTTPMiddleware):
async def dispatch(
self, request: Request, call_next: RequestResponseEndpoint
) -> Response:
async def start_litellm_background():
log.info("start_litellm_background")
# Command to run in the background
command = [
"litellm",
"--port",
str(LITELLM_PROXY_PORT),
"--host",
LITELLM_PROXY_HOST,
"--telemetry",
"False",
"--config",
LITELLM_CONFIG_DIR,
]
response = await call_next(request)
user = request.state.user
await run_background_process(command)
if "/models" in request.url.path:
if isinstance(response, StreamingResponse):
# Read the content of the streaming response
body = b""
async for chunk in response.body_iterator:
body += chunk
data = json.loads(body.decode("utf-8"))
async def shutdown_litellm_background():
log.info("shutdown_litellm_background")
global background_process
if background_process:
background_process.terminate()
await background_process.wait() # Ensure the process has terminated
log.info("Subprocess terminated")
background_process = None
if app.state.MODEL_FILTER_ENABLED:
if user and user.role == "user":
data["data"] = list(
filter(
lambda model: model["id"]
in app.state.MODEL_FILTER_LIST,
data["data"],
)
@app.get("/")
async def get_status():
return {"status": True}
async def restart_litellm():
"""
Endpoint to restart the litellm background service.
"""
log.info("Requested restart of litellm service.")
try:
# Shut down the existing process if it is running
await shutdown_litellm_background()
log.info("litellm service shutdown complete.")
# Restart the background service
asyncio.create_task(start_litellm_background())
log.info("litellm service restart complete.")
return {
"status": "success",
"message": "litellm service restarted successfully.",
}
except Exception as e:
log.info(f"Error restarting litellm service: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)
)
@app.get("/restart")
async def restart_litellm_handler(user=Depends(get_admin_user)):
return await restart_litellm()
@app.get("/config")
async def get_config(user=Depends(get_admin_user)):
return app.state.CONFIG
class LiteLLMConfigForm(BaseModel):
general_settings: Optional[dict] = None
litellm_settings: Optional[dict] = None
model_list: Optional[List[dict]] = None
router_settings: Optional[dict] = None
model_config = ConfigDict(protected_namespaces=())
@app.post("/config/update")
async def update_config(form_data: LiteLLMConfigForm, user=Depends(get_admin_user)):
app.state.CONFIG = form_data.model_dump(exclude_none=True)
with open(LITELLM_CONFIG_DIR, "w") as file:
yaml.dump(app.state.CONFIG, file)
await restart_litellm()
return app.state.CONFIG
@app.get("/models")
@app.get("/v1/models")
async def get_models(user=Depends(get_current_user)):
if app.state.ENABLE:
while not background_process:
await asyncio.sleep(0.1)
url = f"http://localhost:{LITELLM_PROXY_PORT}/v1"
r = None
try:
r = requests.request(method="GET", url=f"{url}/models")
r.raise_for_status()
data = r.json()
if app.state.ENABLE_MODEL_FILTER:
if user and user.role == "user":
data["data"] = list(
filter(
lambda model: model["id"] in app.state.MODEL_FILTER_LIST,
data["data"],
)
)
# Modified Flag
data["modified"] = True
return JSONResponse(content=data)
return data
except Exception as e:
return response
log.exception(e)
error_detail = "Open WebUI: Server Connection Error"
if r is not None:
try:
res = r.json()
if "error" in res:
error_detail = f"External: {res['error']}"
except:
error_detail = f"External: {e}"
return {
"data": [
{
"id": model["model_name"],
"object": "model",
"created": int(time.time()),
"owned_by": "openai",
}
for model in app.state.CONFIG["model_list"]
],
"object": "list",
}
else:
return {
"data": [],
"object": "list",
}
app.add_middleware(ModifyModelsResponseMiddleware)
@app.get("/model/info")
async def get_model_list(user=Depends(get_admin_user)):
return {"data": app.state.CONFIG["model_list"]}
class AddLiteLLMModelForm(BaseModel):
model_name: str
litellm_params: dict
model_config = ConfigDict(protected_namespaces=())
@app.post("/model/new")
async def add_model_to_config(
form_data: AddLiteLLMModelForm, user=Depends(get_admin_user)
):
try:
get_llm_provider(model=form_data.model_name)
app.state.CONFIG["model_list"].append(form_data.model_dump())
with open(LITELLM_CONFIG_DIR, "w") as file:
yaml.dump(app.state.CONFIG, file)
await restart_litellm()
return {"message": MESSAGES.MODEL_ADDED(form_data.model_name)}
except Exception as e:
print(e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e)
)
class DeleteLiteLLMModelForm(BaseModel):
id: str
@app.post("/model/delete")
async def delete_model_from_config(
form_data: DeleteLiteLLMModelForm, user=Depends(get_admin_user)
):
app.state.CONFIG["model_list"] = [
model
for model in app.state.CONFIG["model_list"]
if model["model_name"] != form_data.id
]
with open(LITELLM_CONFIG_DIR, "w") as file:
yaml.dump(app.state.CONFIG, file)
await restart_litellm()
return {"message": MESSAGES.MODEL_DELETED(form_data.id)}
@app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
async def proxy(path: str, request: Request, user=Depends(get_verified_user)):
body = await request.body()
url = f"http://localhost:{LITELLM_PROXY_PORT}"
target_url = f"{url}/{path}"
headers = {}
# headers["Authorization"] = f"Bearer {key}"
headers["Content-Type"] = "application/json"
r = None
try:
r = requests.request(
method=request.method,
url=target_url,
data=body,
headers=headers,
stream=True,
)
r.raise_for_status()
# Check if response is SSE
if "text/event-stream" in r.headers.get("Content-Type", ""):
return StreamingResponse(
r.iter_content(chunk_size=8192),
status_code=r.status_code,
headers=dict(r.headers),
)
else:
response_data = r.json()
return response_data
except Exception as e:
log.exception(e)
error_detail = "Open WebUI: Server Connection Error"
if r is not None:
try:
res = r.json()
if "error" in res:
error_detail = f"External: {res['error']['message'] if 'message' in res['error'] else res['error']}"
except:
error_detail = f"External: {e}"
raise HTTPException(
status_code=r.status_code if r else 500, detail=error_detail
)
+207 -46
View File
@@ -16,6 +16,7 @@ from fastapi.concurrency import run_in_threadpool
from pydantic import BaseModel, ConfigDict
import os
import re
import copy
import random
import requests
@@ -24,21 +25,28 @@ import uuid
import aiohttp
import asyncio
import logging
import time
from urllib.parse import urlparse
from typing import Optional, List, Union
from apps.web.models.users import Users
from constants import ERROR_MESSAGES
from utils.utils import decode_token, get_current_user, get_admin_user
from utils.utils import (
decode_token,
get_current_user,
get_verified_user,
get_admin_user,
)
from config import (
SRC_LOG_LEVELS,
OLLAMA_BASE_URLS,
MODEL_FILTER_ENABLED,
ENABLE_MODEL_FILTER,
MODEL_FILTER_LIST,
UPLOAD_DIR,
AppConfig,
)
from utils.misc import calculate_sha256
@@ -54,11 +62,12 @@ app.add_middleware(
allow_headers=["*"],
)
app.state.config = AppConfig()
app.state.MODEL_FILTER_ENABLED = MODEL_FILTER_ENABLED
app.state.MODEL_FILTER_LIST = MODEL_FILTER_LIST
app.state.config.ENABLE_MODEL_FILTER = ENABLE_MODEL_FILTER
app.state.config.MODEL_FILTER_LIST = MODEL_FILTER_LIST
app.state.OLLAMA_BASE_URLS = OLLAMA_BASE_URLS
app.state.config.OLLAMA_BASE_URLS = OLLAMA_BASE_URLS
app.state.MODELS = {}
@@ -89,7 +98,7 @@ async def get_status():
@app.get("/urls")
async def get_ollama_api_urls(user=Depends(get_admin_user)):
return {"OLLAMA_BASE_URLS": app.state.OLLAMA_BASE_URLS}
return {"OLLAMA_BASE_URLS": app.state.config.OLLAMA_BASE_URLS}
class UrlUpdateForm(BaseModel):
@@ -98,10 +107,10 @@ class UrlUpdateForm(BaseModel):
@app.post("/urls/update")
async def update_ollama_api_url(form_data: UrlUpdateForm, user=Depends(get_admin_user)):
app.state.OLLAMA_BASE_URLS = form_data.urls
app.state.config.OLLAMA_BASE_URLS = form_data.urls
log.info(f"app.state.OLLAMA_BASE_URLS: {app.state.OLLAMA_BASE_URLS}")
return {"OLLAMA_BASE_URLS": app.state.OLLAMA_BASE_URLS}
log.info(f"app.state.config.OLLAMA_BASE_URLS: {app.state.config.OLLAMA_BASE_URLS}")
return {"OLLAMA_BASE_URLS": app.state.config.OLLAMA_BASE_URLS}
@app.get("/cancel/{request_id}")
@@ -115,8 +124,9 @@ async def cancel_ollama_request(request_id: str, user=Depends(get_current_user))
async def fetch_url(url):
timeout = aiohttp.ClientTimeout(total=5)
try:
async with aiohttp.ClientSession() as session:
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.get(url) as response:
return await response.json()
except Exception as e:
@@ -146,7 +156,7 @@ def merge_models_lists(model_lists):
async def get_all_models():
log.info("get_all_models()")
tasks = [fetch_url(f"{url}/api/tags") for url in app.state.OLLAMA_BASE_URLS]
tasks = [fetch_url(f"{url}/api/tags") for url in app.state.config.OLLAMA_BASE_URLS]
responses = await asyncio.gather(*tasks)
models = {
@@ -163,23 +173,24 @@ async def get_all_models():
@app.get("/api/tags")
@app.get("/api/tags/{url_idx}")
async def get_ollama_tags(
url_idx: Optional[int] = None, user=Depends(get_current_user)
url_idx: Optional[int] = None, user=Depends(get_verified_user)
):
if url_idx == None:
models = await get_all_models()
if app.state.MODEL_FILTER_ENABLED:
if app.state.config.ENABLE_MODEL_FILTER:
if user.role == "user":
models["models"] = list(
filter(
lambda model: model["name"] in app.state.MODEL_FILTER_LIST,
lambda model: model["name"]
in app.state.config.MODEL_FILTER_LIST,
models["models"],
)
)
return models
return models
else:
url = app.state.OLLAMA_BASE_URLS[url_idx]
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
try:
r = requests.request(method="GET", url=f"{url}/api/tags")
r.raise_for_status()
@@ -209,14 +220,18 @@ async def get_ollama_versions(url_idx: Optional[int] = None):
if url_idx == None:
# returns lowest version
tasks = [fetch_url(f"{url}/api/version") for url in app.state.OLLAMA_BASE_URLS]
tasks = [
fetch_url(f"{url}/api/version") for url in app.state.config.OLLAMA_BASE_URLS
]
responses = await asyncio.gather(*tasks)
responses = list(filter(lambda x: x is not None, responses))
if len(responses) > 0:
lowest_version = min(
responses,
key=lambda x: tuple(map(int, x["version"].split("-")[0].split("."))),
key=lambda x: tuple(
map(int, re.sub(r"^v|-.*", "", x["version"]).split("."))
),
)
return {"version": lowest_version["version"]}
@@ -226,7 +241,7 @@ async def get_ollama_versions(url_idx: Optional[int] = None):
detail=ERROR_MESSAGES.OLLAMA_NOT_FOUND,
)
else:
url = app.state.OLLAMA_BASE_URLS[url_idx]
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
try:
r = requests.request(method="GET", url=f"{url}/api/version")
r.raise_for_status()
@@ -258,7 +273,7 @@ class ModelNameForm(BaseModel):
async def pull_model(
form_data: ModelNameForm, url_idx: int = 0, user=Depends(get_admin_user)
):
url = app.state.OLLAMA_BASE_URLS[url_idx]
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
log.info(f"url: {url}")
r = None
@@ -346,7 +361,7 @@ async def push_model(
detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.name),
)
url = app.state.OLLAMA_BASE_URLS[url_idx]
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
log.debug(f"url: {url}")
r = None
@@ -408,7 +423,7 @@ async def create_model(
form_data: CreateModelForm, url_idx: int = 0, user=Depends(get_admin_user)
):
log.debug(f"form_data: {form_data}")
url = app.state.OLLAMA_BASE_URLS[url_idx]
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
log.info(f"url: {url}")
r = None
@@ -481,7 +496,7 @@ async def copy_model(
detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.source),
)
url = app.state.OLLAMA_BASE_URLS[url_idx]
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
log.info(f"url: {url}")
try:
@@ -528,7 +543,7 @@ async def delete_model(
detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.name),
)
url = app.state.OLLAMA_BASE_URLS[url_idx]
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
log.info(f"url: {url}")
try:
@@ -560,7 +575,7 @@ async def delete_model(
@app.post("/api/show")
async def show_model_info(form_data: ModelNameForm, user=Depends(get_current_user)):
async def show_model_info(form_data: ModelNameForm, user=Depends(get_verified_user)):
if form_data.name not in app.state.MODELS:
raise HTTPException(
status_code=400,
@@ -568,7 +583,7 @@ async def show_model_info(form_data: ModelNameForm, user=Depends(get_current_use
)
url_idx = random.choice(app.state.MODELS[form_data.name]["urls"])
url = app.state.OLLAMA_BASE_URLS[url_idx]
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
log.info(f"url: {url}")
try:
@@ -609,18 +624,23 @@ class GenerateEmbeddingsForm(BaseModel):
async def generate_embeddings(
form_data: GenerateEmbeddingsForm,
url_idx: Optional[int] = None,
user=Depends(get_current_user),
user=Depends(get_verified_user),
):
if url_idx == None:
if form_data.model in app.state.MODELS:
url_idx = random.choice(app.state.MODELS[form_data.model]["urls"])
model = form_data.model
if ":" not in model:
model = f"{model}:latest"
if model in app.state.MODELS:
url_idx = random.choice(app.state.MODELS[model]["urls"])
else:
raise HTTPException(
status_code=400,
detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
)
url = app.state.OLLAMA_BASE_URLS[url_idx]
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
log.info(f"url: {url}")
try:
@@ -649,6 +669,60 @@ async def generate_embeddings(
)
def generate_ollama_embeddings(
form_data: GenerateEmbeddingsForm,
url_idx: Optional[int] = None,
):
log.info(f"generate_ollama_embeddings {form_data}")
if url_idx == None:
model = form_data.model
if ":" not in model:
model = f"{model}:latest"
if model in app.state.MODELS:
url_idx = random.choice(app.state.MODELS[model]["urls"])
else:
raise HTTPException(
status_code=400,
detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
)
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
log.info(f"url: {url}")
try:
r = requests.request(
method="POST",
url=f"{url}/api/embeddings",
data=form_data.model_dump_json(exclude_none=True).encode(),
)
r.raise_for_status()
data = r.json()
log.info(f"generate_ollama_embeddings {data}")
if "embedding" in data:
return data["embedding"]
else:
raise "Something went wrong :/"
except Exception as e:
log.exception(e)
error_detail = "Open WebUI: Server Connection Error"
if r is not None:
try:
res = r.json()
if "error" in res:
error_detail = f"Ollama: {res['error']}"
except:
error_detail = f"Ollama: {e}"
raise error_detail
class GenerateCompletionForm(BaseModel):
model: str
prompt: str
@@ -668,19 +742,24 @@ class GenerateCompletionForm(BaseModel):
async def generate_completion(
form_data: GenerateCompletionForm,
url_idx: Optional[int] = None,
user=Depends(get_current_user),
user=Depends(get_verified_user),
):
if url_idx == None:
if form_data.model in app.state.MODELS:
url_idx = random.choice(app.state.MODELS[form_data.model]["urls"])
model = form_data.model
if ":" not in model:
model = f"{model}:latest"
if model in app.state.MODELS:
url_idx = random.choice(app.state.MODELS[model]["urls"])
else:
raise HTTPException(
status_code=400,
detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
)
url = app.state.OLLAMA_BASE_URLS[url_idx]
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
log.info(f"url: {url}")
r = None
@@ -766,19 +845,24 @@ class GenerateChatCompletionForm(BaseModel):
async def generate_chat_completion(
form_data: GenerateChatCompletionForm,
url_idx: Optional[int] = None,
user=Depends(get_current_user),
user=Depends(get_verified_user),
):
if url_idx == None:
if form_data.model in app.state.MODELS:
url_idx = random.choice(app.state.MODELS[form_data.model]["urls"])
model = form_data.model
if ":" not in model:
model = f"{model}:latest"
if model in app.state.MODELS:
url_idx = random.choice(app.state.MODELS[model]["urls"])
else:
raise HTTPException(
status_code=400,
detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
)
url = app.state.OLLAMA_BASE_URLS[url_idx]
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
log.info(f"url: {url}")
r = None
@@ -870,19 +954,24 @@ class OpenAIChatCompletionForm(BaseModel):
async def generate_openai_chat_completion(
form_data: OpenAIChatCompletionForm,
url_idx: Optional[int] = None,
user=Depends(get_current_user),
user=Depends(get_verified_user),
):
if url_idx == None:
if form_data.model in app.state.MODELS:
url_idx = random.choice(app.state.MODELS[form_data.model]["urls"])
model = form_data.model
if ":" not in model:
model = f"{model}:latest"
if model in app.state.MODELS:
url_idx = random.choice(app.state.MODELS[model]["urls"])
else:
raise HTTPException(
status_code=400,
detail=ERROR_MESSAGES.MODEL_NOT_FOUND(form_data.model),
)
url = app.state.OLLAMA_BASE_URLS[url_idx]
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
log.info(f"url: {url}")
r = None
@@ -949,6 +1038,76 @@ async def generate_openai_chat_completion(
)
@app.get("/v1/models")
@app.get("/v1/models/{url_idx}")
async def get_openai_models(
url_idx: Optional[int] = None,
user=Depends(get_verified_user),
):
if url_idx == None:
models = await get_all_models()
if app.state.config.ENABLE_MODEL_FILTER:
if user.role == "user":
models["models"] = list(
filter(
lambda model: model["name"]
in app.state.config.MODEL_FILTER_LIST,
models["models"],
)
)
return {
"data": [
{
"id": model["model"],
"object": "model",
"created": int(time.time()),
"owned_by": "openai",
}
for model in models["models"]
],
"object": "list",
}
else:
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
try:
r = requests.request(method="GET", url=f"{url}/api/tags")
r.raise_for_status()
models = r.json()
return {
"data": [
{
"id": model["model"],
"object": "model",
"created": int(time.time()),
"owned_by": "openai",
}
for model in models["models"]
],
"object": "list",
}
except Exception as e:
log.exception(e)
error_detail = "Open WebUI: Server Connection Error"
if r is not None:
try:
res = r.json()
if "error" in res:
error_detail = f"Ollama: {res['error']}"
except:
error_detail = f"Ollama: {e}"
raise HTTPException(
status_code=r.status_code if r else 500,
detail=error_detail,
)
class UrlForm(BaseModel):
url: str
@@ -1046,7 +1205,7 @@ async def download_model(
if url_idx == None:
url_idx = 0
url = app.state.OLLAMA_BASE_URLS[url_idx]
url = app.state.config.OLLAMA_BASE_URLS[url_idx]
file_name = parse_huggingface_url(form_data.url)
@@ -1065,7 +1224,7 @@ async def download_model(
def upload_model(file: UploadFile = File(...), url_idx: Optional[int] = None):
if url_idx == None:
url_idx = 0
ollama_url = app.state.OLLAMA_BASE_URLS[url_idx]
ollama_url = app.state.config.OLLAMA_BASE_URLS[url_idx]
file_path = f"{UPLOAD_DIR}/{file.filename}"
@@ -1130,7 +1289,7 @@ def upload_model(file: UploadFile = File(...), url_idx: Optional[int] = None):
# async def upload_model(file: UploadFile = File(), url_idx: Optional[int] = None):
# if url_idx == None:
# url_idx = 0
# url = app.state.OLLAMA_BASE_URLS[url_idx]
# url = app.state.config.OLLAMA_BASE_URLS[url_idx]
# file_location = os.path.join(UPLOAD_DIR, file.filename)
# total_size = file.size
@@ -1164,8 +1323,10 @@ def upload_model(file: UploadFile = File(...), url_idx: Optional[int] = None):
@app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
async def deprecated_proxy(path: str, request: Request, user=Depends(get_current_user)):
url = app.state.OLLAMA_BASE_URLS[0]
async def deprecated_proxy(
path: str, request: Request, user=Depends(get_verified_user)
):
url = app.state.config.OLLAMA_BASE_URLS[0]
target_url = f"{url}/{path}"
body = await request.body()
+67 -31
View File
@@ -21,11 +21,13 @@ from utils.utils import (
)
from config import (
SRC_LOG_LEVELS,
ENABLE_OPENAI_API,
OPENAI_API_BASE_URLS,
OPENAI_API_KEYS,
CACHE_DIR,
MODEL_FILTER_ENABLED,
ENABLE_MODEL_FILTER,
MODEL_FILTER_LIST,
AppConfig,
)
from typing import List, Optional
@@ -45,11 +47,16 @@ app.add_middleware(
allow_headers=["*"],
)
app.state.MODEL_FILTER_ENABLED = MODEL_FILTER_ENABLED
app.state.MODEL_FILTER_LIST = MODEL_FILTER_LIST
app.state.OPENAI_API_BASE_URLS = OPENAI_API_BASE_URLS
app.state.OPENAI_API_KEYS = OPENAI_API_KEYS
app.state.config = AppConfig()
app.state.config.ENABLE_MODEL_FILTER = ENABLE_MODEL_FILTER
app.state.config.MODEL_FILTER_LIST = MODEL_FILTER_LIST
app.state.config.ENABLE_OPENAI_API = ENABLE_OPENAI_API
app.state.config.OPENAI_API_BASE_URLS = OPENAI_API_BASE_URLS
app.state.config.OPENAI_API_KEYS = OPENAI_API_KEYS
app.state.MODELS = {}
@@ -65,6 +72,21 @@ async def check_url(request: Request, call_next):
return response
@app.get("/config")
async def get_config(user=Depends(get_admin_user)):
return {"ENABLE_OPENAI_API": app.state.config.ENABLE_OPENAI_API}
class OpenAIConfigForm(BaseModel):
enable_openai_api: Optional[bool] = None
@app.post("/config/update")
async def update_config(form_data: OpenAIConfigForm, user=Depends(get_admin_user)):
app.state.config.ENABLE_OPENAI_API = form_data.enable_openai_api
return {"ENABLE_OPENAI_API": app.state.config.ENABLE_OPENAI_API}
class UrlsUpdateForm(BaseModel):
urls: List[str]
@@ -75,31 +97,32 @@ class KeysUpdateForm(BaseModel):
@app.get("/urls")
async def get_openai_urls(user=Depends(get_admin_user)):
return {"OPENAI_API_BASE_URLS": app.state.OPENAI_API_BASE_URLS}
return {"OPENAI_API_BASE_URLS": app.state.config.OPENAI_API_BASE_URLS}
@app.post("/urls/update")
async def update_openai_urls(form_data: UrlsUpdateForm, user=Depends(get_admin_user)):
app.state.OPENAI_API_BASE_URLS = form_data.urls
return {"OPENAI_API_BASE_URLS": app.state.OPENAI_API_BASE_URLS}
await get_all_models()
app.state.config.OPENAI_API_BASE_URLS = form_data.urls
return {"OPENAI_API_BASE_URLS": app.state.config.OPENAI_API_BASE_URLS}
@app.get("/keys")
async def get_openai_keys(user=Depends(get_admin_user)):
return {"OPENAI_API_KEYS": app.state.OPENAI_API_KEYS}
return {"OPENAI_API_KEYS": app.state.config.OPENAI_API_KEYS}
@app.post("/keys/update")
async def update_openai_key(form_data: KeysUpdateForm, user=Depends(get_admin_user)):
app.state.OPENAI_API_KEYS = form_data.keys
return {"OPENAI_API_KEYS": app.state.OPENAI_API_KEYS}
app.state.config.OPENAI_API_KEYS = form_data.keys
return {"OPENAI_API_KEYS": app.state.config.OPENAI_API_KEYS}
@app.post("/audio/speech")
async def speech(request: Request, user=Depends(get_verified_user)):
idx = None
try:
idx = app.state.OPENAI_API_BASE_URLS.index("https://api.openai.com/v1")
idx = app.state.config.OPENAI_API_BASE_URLS.index("https://api.openai.com/v1")
body = await request.body()
name = hashlib.sha256(body).hexdigest()
@@ -113,13 +136,15 @@ async def speech(request: Request, user=Depends(get_verified_user)):
return FileResponse(file_path)
headers = {}
headers["Authorization"] = f"Bearer {app.state.OPENAI_API_KEYS[idx]}"
headers["Authorization"] = f"Bearer {app.state.config.OPENAI_API_KEYS[idx]}"
headers["Content-Type"] = "application/json"
if "openrouter.ai" in app.state.config.OPENAI_API_BASE_URLS[idx]:
headers["HTTP-Referer"] = "https://openwebui.com/"
headers["X-Title"] = "Open WebUI"
r = None
try:
r = requests.post(
url=f"{app.state.OPENAI_API_BASE_URLS[idx]}/audio/speech",
url=f"{app.state.config.OPENAI_API_BASE_URLS[idx]}/audio/speech",
data=body,
headers=headers,
stream=True,
@@ -158,11 +183,15 @@ async def speech(request: Request, user=Depends(get_verified_user)):
async def fetch_url(url, key):
timeout = aiohttp.ClientTimeout(total=5)
try:
headers = {"Authorization": f"Bearer {key}"}
async with aiohttp.ClientSession() as session:
async with session.get(url, headers=headers) as response:
return await response.json()
if key != "":
headers = {"Authorization": f"Bearer {key}"}
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.get(url, headers=headers) as response:
return await response.json()
else:
return None
except Exception as e:
# Handle connection error here
log.error(f"Connection error: {e}")
@@ -170,6 +199,7 @@ async def fetch_url(url, key):
def merge_models_lists(model_lists):
log.info(f"merge_models_lists {model_lists}")
merged_list = []
for idx, models in enumerate(model_lists):
@@ -178,7 +208,8 @@ def merge_models_lists(model_lists):
[
{**model, "urlIdx": idx}
for model in models
if "api.openai.com" not in app.state.OPENAI_API_BASE_URLS[idx]
if "api.openai.com"
not in app.state.config.OPENAI_API_BASE_URLS[idx]
or "gpt" in model["id"]
]
)
@@ -189,23 +220,28 @@ def merge_models_lists(model_lists):
async def get_all_models():
log.info("get_all_models()")
if len(app.state.OPENAI_API_KEYS) == 1 and app.state.OPENAI_API_KEYS[0] == "":
if (
len(app.state.config.OPENAI_API_KEYS) == 1
and app.state.config.OPENAI_API_KEYS[0] == ""
) or not app.state.config.ENABLE_OPENAI_API:
models = {"data": []}
else:
tasks = [
fetch_url(f"{url}/models", app.state.OPENAI_API_KEYS[idx])
for idx, url in enumerate(app.state.OPENAI_API_BASE_URLS)
fetch_url(f"{url}/models", app.state.config.OPENAI_API_KEYS[idx])
for idx, url in enumerate(app.state.config.OPENAI_API_BASE_URLS)
]
responses = await asyncio.gather(*tasks)
log.info(f"get_all_models:responses() {responses}")
models = {
"data": merge_models_lists(
list(
map(
lambda response: (
response["data"]
if response and "data" in response
else None
if (response and "data" in response)
else (response if isinstance(response, list) else None)
),
responses,
)
@@ -224,18 +260,18 @@ async def get_all_models():
async def get_models(url_idx: Optional[int] = None, user=Depends(get_current_user)):
if url_idx == None:
models = await get_all_models()
if app.state.MODEL_FILTER_ENABLED:
if app.state.config.ENABLE_MODEL_FILTER:
if user.role == "user":
models["data"] = list(
filter(
lambda model: model["id"] in app.state.MODEL_FILTER_LIST,
lambda model: model["id"] in app.state.config.MODEL_FILTER_LIST,
models["data"],
)
)
return models
return models
else:
url = app.state.OPENAI_API_BASE_URLS[url_idx]
url = app.state.config.OPENAI_API_BASE_URLS[url_idx]
r = None
@@ -299,8 +335,8 @@ async def proxy(path: str, request: Request, user=Depends(get_verified_user)):
except json.JSONDecodeError as e:
log.error("Error loading request body into a dictionary:", e)
url = app.state.OPENAI_API_BASE_URLS[idx]
key = app.state.OPENAI_API_KEYS[idx]
url = app.state.config.OPENAI_API_BASE_URLS[idx]
key = app.state.config.OPENAI_API_KEYS[idx]
target_url = f"{url}/{path}"
@@ -341,7 +377,7 @@ async def proxy(path: str, request: Request, user=Depends(get_verified_user)):
try:
res = r.json()
if "error" in res:
error_detail = f"External: {res['error']}"
error_detail = f"External: {res['error']['message'] if 'message' in res['error'] else res['error']}"
except:
error_detail = f"External: {e}"
+417 -83
View File
@@ -13,7 +13,6 @@ import os, shutil, logging, re
from pathlib import Path
from typing import List
from chromadb.utils import embedding_functions
from chromadb.utils.batch_utils import create_batches
from langchain_community.document_loaders import (
@@ -29,15 +28,22 @@ from langchain_community.document_loaders import (
UnstructuredXMLLoader,
UnstructuredRSTLoader,
UnstructuredExcelLoader,
YoutubeLoader,
)
from langchain.text_splitter import RecursiveCharacterTextSplitter
import validators
import urllib.parse
import socket
from pydantic import BaseModel
from typing import Optional
import mimetypes
import uuid
import json
import sentence_transformers
from apps.web.models.documents import (
Documents,
@@ -45,7 +51,14 @@ from apps.web.models.documents import (
DocumentResponse,
)
from apps.rag.utils import query_doc, query_collection, get_embedding_model_path
from apps.rag.utils import (
get_model_path,
get_embedding_function,
query_doc,
query_doc_with_hybrid_search,
query_collection,
query_collection_with_hybrid_search,
)
from utils.misc import (
calculate_sha256,
@@ -54,17 +67,34 @@ from utils.misc import (
extract_folders_after_data_docs,
)
from utils.utils import get_current_user, get_admin_user
from config import (
ENV,
SRC_LOG_LEVELS,
UPLOAD_DIR,
DOCS_DIR,
RAG_TOP_K,
RAG_RELEVANCE_THRESHOLD,
RAG_EMBEDDING_ENGINE,
RAG_EMBEDDING_MODEL,
RAG_EMBEDDING_MODEL_AUTO_UPDATE,
RAG_EMBEDDING_MODEL_TRUST_REMOTE_CODE,
ENABLE_RAG_HYBRID_SEARCH,
ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION,
RAG_RERANKING_MODEL,
PDF_EXTRACT_IMAGES,
RAG_RERANKING_MODEL_AUTO_UPDATE,
RAG_RERANKING_MODEL_TRUST_REMOTE_CODE,
RAG_OPENAI_API_BASE_URL,
RAG_OPENAI_API_KEY,
DEVICE_TYPE,
CHROMA_CLIENT,
CHUNK_SIZE,
CHUNK_OVERLAP,
RAG_TEMPLATE,
ENABLE_RAG_LOCAL_WEB_FETCH,
YOUTUBE_LOADER_LANGUAGE,
AppConfig,
)
from constants import ERROR_MESSAGES
@@ -74,29 +104,85 @@ log.setLevel(SRC_LOG_LEVELS["RAG"])
app = FastAPI()
app.state.PDF_EXTRACT_IMAGES = False
app.state.CHUNK_SIZE = CHUNK_SIZE
app.state.CHUNK_OVERLAP = CHUNK_OVERLAP
app.state.RAG_TEMPLATE = RAG_TEMPLATE
app.state.config = AppConfig()
app.state.config.TOP_K = RAG_TOP_K
app.state.config.RELEVANCE_THRESHOLD = RAG_RELEVANCE_THRESHOLD
app.state.config.ENABLE_RAG_HYBRID_SEARCH = ENABLE_RAG_HYBRID_SEARCH
app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION = (
ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION
)
app.state.config.CHUNK_SIZE = CHUNK_SIZE
app.state.config.CHUNK_OVERLAP = CHUNK_OVERLAP
app.state.config.RAG_EMBEDDING_ENGINE = RAG_EMBEDDING_ENGINE
app.state.config.RAG_EMBEDDING_MODEL = RAG_EMBEDDING_MODEL
app.state.config.RAG_RERANKING_MODEL = RAG_RERANKING_MODEL
app.state.config.RAG_TEMPLATE = RAG_TEMPLATE
app.state.RAG_EMBEDDING_MODEL = RAG_EMBEDDING_MODEL
app.state.config.OPENAI_API_BASE_URL = RAG_OPENAI_API_BASE_URL
app.state.config.OPENAI_API_KEY = RAG_OPENAI_API_KEY
app.state.config.PDF_EXTRACT_IMAGES = PDF_EXTRACT_IMAGES
app.state.TOP_K = 4
app.state.config.YOUTUBE_LOADER_LANGUAGE = YOUTUBE_LOADER_LANGUAGE
app.state.YOUTUBE_LOADER_TRANSLATION = None
app.state.sentence_transformer_ef = (
embedding_functions.SentenceTransformerEmbeddingFunction(
model_name=get_embedding_model_path(
app.state.RAG_EMBEDDING_MODEL, RAG_EMBEDDING_MODEL_AUTO_UPDATE
),
device=DEVICE_TYPE,
)
def update_embedding_model(
embedding_model: str,
update_model: bool = False,
):
if embedding_model and app.state.config.RAG_EMBEDDING_ENGINE == "":
app.state.sentence_transformer_ef = sentence_transformers.SentenceTransformer(
get_model_path(embedding_model, update_model),
device=DEVICE_TYPE,
trust_remote_code=RAG_EMBEDDING_MODEL_TRUST_REMOTE_CODE,
)
else:
app.state.sentence_transformer_ef = None
def update_reranking_model(
reranking_model: str,
update_model: bool = False,
):
if reranking_model:
app.state.sentence_transformer_rf = sentence_transformers.CrossEncoder(
get_model_path(reranking_model, update_model),
device=DEVICE_TYPE,
trust_remote_code=RAG_RERANKING_MODEL_TRUST_REMOTE_CODE,
)
else:
app.state.sentence_transformer_rf = None
update_embedding_model(
app.state.config.RAG_EMBEDDING_MODEL,
RAG_EMBEDDING_MODEL_AUTO_UPDATE,
)
update_reranking_model(
app.state.config.RAG_RERANKING_MODEL,
RAG_RERANKING_MODEL_AUTO_UPDATE,
)
app.state.EMBEDDING_FUNCTION = get_embedding_function(
app.state.config.RAG_EMBEDDING_ENGINE,
app.state.config.RAG_EMBEDDING_MODEL,
app.state.sentence_transformer_ef,
app.state.config.OPENAI_API_KEY,
app.state.config.OPENAI_API_BASE_URL,
)
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
@@ -110,7 +196,7 @@ class CollectionNameForm(BaseModel):
collection_name: Optional[str] = "test"
class StoreWebForm(CollectionNameForm):
class UrlForm(CollectionNameForm):
url: str
@@ -118,50 +204,82 @@ class StoreWebForm(CollectionNameForm):
async def get_status():
return {
"status": True,
"chunk_size": app.state.CHUNK_SIZE,
"chunk_overlap": app.state.CHUNK_OVERLAP,
"template": app.state.RAG_TEMPLATE,
"embedding_model": app.state.RAG_EMBEDDING_MODEL,
"chunk_size": app.state.config.CHUNK_SIZE,
"chunk_overlap": app.state.config.CHUNK_OVERLAP,
"template": app.state.config.RAG_TEMPLATE,
"embedding_engine": app.state.config.RAG_EMBEDDING_ENGINE,
"embedding_model": app.state.config.RAG_EMBEDDING_MODEL,
"reranking_model": app.state.config.RAG_RERANKING_MODEL,
}
@app.get("/embedding/model")
async def get_embedding_model(user=Depends(get_admin_user)):
@app.get("/embedding")
async def get_embedding_config(user=Depends(get_admin_user)):
return {
"status": True,
"embedding_model": app.state.RAG_EMBEDDING_MODEL,
"embedding_engine": app.state.config.RAG_EMBEDDING_ENGINE,
"embedding_model": app.state.config.RAG_EMBEDDING_MODEL,
"openai_config": {
"url": app.state.config.OPENAI_API_BASE_URL,
"key": app.state.config.OPENAI_API_KEY,
},
}
@app.get("/reranking")
async def get_reraanking_config(user=Depends(get_admin_user)):
return {
"status": True,
"reranking_model": app.state.config.RAG_RERANKING_MODEL,
}
class OpenAIConfigForm(BaseModel):
url: str
key: str
class EmbeddingModelUpdateForm(BaseModel):
openai_config: Optional[OpenAIConfigForm] = None
embedding_engine: str
embedding_model: str
@app.post("/embedding/model/update")
async def update_embedding_model(
@app.post("/embedding/update")
async def update_embedding_config(
form_data: EmbeddingModelUpdateForm, user=Depends(get_admin_user)
):
log.info(
f"Updating embedding model: {app.state.RAG_EMBEDDING_MODEL} to {form_data.embedding_model}"
f"Updating embedding model: {app.state.config.RAG_EMBEDDING_MODEL} to {form_data.embedding_model}"
)
try:
sentence_transformer_ef = (
embedding_functions.SentenceTransformerEmbeddingFunction(
model_name=get_embedding_model_path(form_data.embedding_model, True),
device=DEVICE_TYPE,
)
)
app.state.config.RAG_EMBEDDING_ENGINE = form_data.embedding_engine
app.state.config.RAG_EMBEDDING_MODEL = form_data.embedding_model
app.state.RAG_EMBEDDING_MODEL = form_data.embedding_model
app.state.sentence_transformer_ef = sentence_transformer_ef
if app.state.config.RAG_EMBEDDING_ENGINE in ["ollama", "openai"]:
if form_data.openai_config != None:
app.state.config.OPENAI_API_BASE_URL = form_data.openai_config.url
app.state.config.OPENAI_API_KEY = form_data.openai_config.key
update_embedding_model(app.state.config.RAG_EMBEDDING_MODEL)
app.state.EMBEDDING_FUNCTION = get_embedding_function(
app.state.config.RAG_EMBEDDING_ENGINE,
app.state.config.RAG_EMBEDDING_MODEL,
app.state.sentence_transformer_ef,
app.state.config.OPENAI_API_KEY,
app.state.config.OPENAI_API_BASE_URL,
)
return {
"status": True,
"embedding_model": app.state.RAG_EMBEDDING_MODEL,
"embedding_engine": app.state.config.RAG_EMBEDDING_ENGINE,
"embedding_model": app.state.config.RAG_EMBEDDING_MODEL,
"openai_config": {
"url": app.state.config.OPENAI_API_BASE_URL,
"key": app.state.config.OPENAI_API_KEY,
},
}
except Exception as e:
log.exception(f"Problem updating embedding model: {e}")
raise HTTPException(
@@ -170,14 +288,47 @@ async def update_embedding_model(
)
class RerankingModelUpdateForm(BaseModel):
reranking_model: str
@app.post("/reranking/update")
async def update_reranking_config(
form_data: RerankingModelUpdateForm, user=Depends(get_admin_user)
):
log.info(
f"Updating reranking model: {app.state.config.RAG_RERANKING_MODEL} to {form_data.reranking_model}"
)
try:
app.state.config.RAG_RERANKING_MODEL = form_data.reranking_model
update_reranking_model(app.state.config.RAG_RERANKING_MODEL), True
return {
"status": True,
"reranking_model": app.state.config.RAG_RERANKING_MODEL,
}
except Exception as e:
log.exception(f"Problem updating reranking model: {e}")
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=ERROR_MESSAGES.DEFAULT(e),
)
@app.get("/config")
async def get_rag_config(user=Depends(get_admin_user)):
return {
"status": True,
"pdf_extract_images": app.state.PDF_EXTRACT_IMAGES,
"pdf_extract_images": app.state.config.PDF_EXTRACT_IMAGES,
"chunk": {
"chunk_size": app.state.CHUNK_SIZE,
"chunk_overlap": app.state.CHUNK_OVERLAP,
"chunk_size": app.state.config.CHUNK_SIZE,
"chunk_overlap": app.state.config.CHUNK_OVERLAP,
},
"web_loader_ssl_verification": app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION,
"youtube": {
"language": app.state.config.YOUTUBE_LOADER_LANGUAGE,
"translation": app.state.YOUTUBE_LOADER_TRANSLATION,
},
}
@@ -187,23 +338,67 @@ class ChunkParamUpdateForm(BaseModel):
chunk_overlap: int
class YoutubeLoaderConfig(BaseModel):
language: List[str]
translation: Optional[str] = None
class ConfigUpdateForm(BaseModel):
pdf_extract_images: bool
chunk: ChunkParamUpdateForm
pdf_extract_images: Optional[bool] = None
chunk: Optional[ChunkParamUpdateForm] = None
web_loader_ssl_verification: Optional[bool] = None
youtube: Optional[YoutubeLoaderConfig] = None
@app.post("/config/update")
async def update_rag_config(form_data: ConfigUpdateForm, user=Depends(get_admin_user)):
app.state.PDF_EXTRACT_IMAGES = form_data.pdf_extract_images
app.state.CHUNK_SIZE = form_data.chunk.chunk_size
app.state.CHUNK_OVERLAP = form_data.chunk.chunk_overlap
app.state.config.PDF_EXTRACT_IMAGES = (
form_data.pdf_extract_images
if form_data.pdf_extract_images is not None
else app.state.config.PDF_EXTRACT_IMAGES
)
app.state.config.CHUNK_SIZE = (
form_data.chunk.chunk_size
if form_data.chunk is not None
else app.state.config.CHUNK_SIZE
)
app.state.config.CHUNK_OVERLAP = (
form_data.chunk.chunk_overlap
if form_data.chunk is not None
else app.state.config.CHUNK_OVERLAP
)
app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION = (
form_data.web_loader_ssl_verification
if form_data.web_loader_ssl_verification != None
else app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION
)
app.state.config.YOUTUBE_LOADER_LANGUAGE = (
form_data.youtube.language
if form_data.youtube is not None
else app.state.config.YOUTUBE_LOADER_LANGUAGE
)
app.state.YOUTUBE_LOADER_TRANSLATION = (
form_data.youtube.translation
if form_data.youtube is not None
else app.state.YOUTUBE_LOADER_TRANSLATION
)
return {
"status": True,
"pdf_extract_images": app.state.PDF_EXTRACT_IMAGES,
"pdf_extract_images": app.state.config.PDF_EXTRACT_IMAGES,
"chunk": {
"chunk_size": app.state.CHUNK_SIZE,
"chunk_overlap": app.state.CHUNK_OVERLAP,
"chunk_size": app.state.config.CHUNK_SIZE,
"chunk_overlap": app.state.config.CHUNK_OVERLAP,
},
"web_loader_ssl_verification": app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION,
"youtube": {
"language": app.state.config.YOUTUBE_LOADER_LANGUAGE,
"translation": app.state.YOUTUBE_LOADER_TRANSLATION,
},
}
@@ -212,7 +407,7 @@ async def update_rag_config(form_data: ConfigUpdateForm, user=Depends(get_admin_
async def get_rag_template(user=Depends(get_current_user)):
return {
"status": True,
"template": app.state.RAG_TEMPLATE,
"template": app.state.config.RAG_TEMPLATE,
}
@@ -220,29 +415,47 @@ async def get_rag_template(user=Depends(get_current_user)):
async def get_query_settings(user=Depends(get_admin_user)):
return {
"status": True,
"template": app.state.RAG_TEMPLATE,
"k": app.state.TOP_K,
"template": app.state.config.RAG_TEMPLATE,
"k": app.state.config.TOP_K,
"r": app.state.config.RELEVANCE_THRESHOLD,
"hybrid": app.state.config.ENABLE_RAG_HYBRID_SEARCH,
}
class QuerySettingsForm(BaseModel):
k: Optional[int] = None
r: Optional[float] = None
template: Optional[str] = None
hybrid: Optional[bool] = None
@app.post("/query/settings/update")
async def update_query_settings(
form_data: QuerySettingsForm, user=Depends(get_admin_user)
):
app.state.RAG_TEMPLATE = form_data.template if form_data.template else RAG_TEMPLATE
app.state.TOP_K = form_data.k if form_data.k else 4
return {"status": True, "template": app.state.RAG_TEMPLATE}
app.state.config.RAG_TEMPLATE = (
form_data.template if form_data.template else RAG_TEMPLATE
)
app.state.config.TOP_K = form_data.k if form_data.k else 4
app.state.config.RELEVANCE_THRESHOLD = form_data.r if form_data.r else 0.0
app.state.config.ENABLE_RAG_HYBRID_SEARCH = (
form_data.hybrid if form_data.hybrid else False
)
return {
"status": True,
"template": app.state.config.RAG_TEMPLATE,
"k": app.state.config.TOP_K,
"r": app.state.config.RELEVANCE_THRESHOLD,
"hybrid": app.state.config.ENABLE_RAG_HYBRID_SEARCH,
}
class QueryDocForm(BaseModel):
collection_name: str
query: str
k: Optional[int] = None
r: Optional[float] = None
hybrid: Optional[bool] = None
@app.post("/query/doc")
@@ -250,14 +463,25 @@ def query_doc_handler(
form_data: QueryDocForm,
user=Depends(get_current_user),
):
try:
return query_doc(
collection_name=form_data.collection_name,
query=form_data.query,
k=form_data.k if form_data.k else app.state.TOP_K,
embedding_function=app.state.sentence_transformer_ef,
)
if app.state.config.ENABLE_RAG_HYBRID_SEARCH:
return query_doc_with_hybrid_search(
collection_name=form_data.collection_name,
query=form_data.query,
embedding_function=app.state.EMBEDDING_FUNCTION,
k=form_data.k if form_data.k else app.state.config.TOP_K,
reranking_function=app.state.sentence_transformer_rf,
r=(
form_data.r if form_data.r else app.state.config.RELEVANCE_THRESHOLD
),
)
else:
return query_doc(
collection_name=form_data.collection_name,
query=form_data.query,
embedding_function=app.state.EMBEDDING_FUNCTION,
k=form_data.k if form_data.k else app.state.config.TOP_K,
)
except Exception as e:
log.exception(e)
raise HTTPException(
@@ -270,6 +494,8 @@ class QueryCollectionsForm(BaseModel):
collection_names: List[str]
query: str
k: Optional[int] = None
r: Optional[float] = None
hybrid: Optional[bool] = None
@app.post("/query/collection")
@@ -277,19 +503,43 @@ def query_collection_handler(
form_data: QueryCollectionsForm,
user=Depends(get_current_user),
):
return query_collection(
collection_names=form_data.collection_names,
query=form_data.query,
k=form_data.k if form_data.k else app.state.TOP_K,
embedding_function=app.state.sentence_transformer_ef,
)
@app.post("/web")
def store_web(form_data: StoreWebForm, user=Depends(get_current_user)):
# "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
try:
loader = WebBaseLoader(form_data.url)
if app.state.config.ENABLE_RAG_HYBRID_SEARCH:
return query_collection_with_hybrid_search(
collection_names=form_data.collection_names,
query=form_data.query,
embedding_function=app.state.EMBEDDING_FUNCTION,
k=form_data.k if form_data.k else app.state.config.TOP_K,
reranking_function=app.state.sentence_transformer_rf,
r=(
form_data.r if form_data.r else app.state.config.RELEVANCE_THRESHOLD
),
)
else:
return query_collection(
collection_names=form_data.collection_names,
query=form_data.query,
embedding_function=app.state.EMBEDDING_FUNCTION,
k=form_data.k if form_data.k else app.state.config.TOP_K,
)
except Exception as e:
log.exception(e)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=ERROR_MESSAGES.DEFAULT(e),
)
@app.post("/youtube")
def store_youtube_video(form_data: UrlForm, user=Depends(get_current_user)):
try:
loader = YoutubeLoader.from_youtube_url(
form_data.url,
add_video_info=True,
language=app.state.config.YOUTUBE_LOADER_LANGUAGE,
translation=app.state.YOUTUBE_LOADER_TRANSLATION,
)
data = loader.load()
collection_name = form_data.collection_name
@@ -310,16 +560,77 @@ def store_web(form_data: StoreWebForm, user=Depends(get_current_user)):
)
@app.post("/web")
def store_web(form_data: UrlForm, user=Depends(get_current_user)):
# "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
try:
loader = get_web_loader(
form_data.url,
verify_ssl=app.state.config.ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION,
)
data = loader.load()
collection_name = form_data.collection_name
if collection_name == "":
collection_name = calculate_sha256_string(form_data.url)[:63]
store_data_in_vector_db(data, collection_name, overwrite=True)
return {
"status": True,
"collection_name": collection_name,
"filename": form_data.url,
}
except Exception as e:
log.exception(e)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=ERROR_MESSAGES.DEFAULT(e),
)
def get_web_loader(url: str, verify_ssl: bool = True):
# Check if the URL is valid
if isinstance(validators.url(url), validators.ValidationError):
raise ValueError(ERROR_MESSAGES.INVALID_URL)
if not ENABLE_RAG_LOCAL_WEB_FETCH:
# Local web fetch is disabled, filter out any URLs that resolve to private IP addresses
parsed_url = urllib.parse.urlparse(url)
# Get IPv4 and IPv6 addresses
ipv4_addresses, ipv6_addresses = resolve_hostname(parsed_url.hostname)
# Check if any of the resolved addresses are private
# This is technically still vulnerable to DNS rebinding attacks, as we don't control WebBaseLoader
for ip in ipv4_addresses:
if validators.ipv4(ip, private=True):
raise ValueError(ERROR_MESSAGES.INVALID_URL)
for ip in ipv6_addresses:
if validators.ipv6(ip, private=True):
raise ValueError(ERROR_MESSAGES.INVALID_URL)
return WebBaseLoader(url, verify_ssl=verify_ssl)
def resolve_hostname(hostname):
# Get address information
addr_info = socket.getaddrinfo(hostname, None)
# Extract IP addresses from address information
ipv4_addresses = [info[4][0] for info in addr_info if info[0] == socket.AF_INET]
ipv6_addresses = [info[4][0] for info in addr_info if info[0] == socket.AF_INET6]
return ipv4_addresses, ipv6_addresses
def store_data_in_vector_db(data, collection_name, overwrite: bool = False) -> bool:
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=app.state.CHUNK_SIZE,
chunk_overlap=app.state.CHUNK_OVERLAP,
chunk_size=app.state.config.CHUNK_SIZE,
chunk_overlap=app.state.config.CHUNK_OVERLAP,
add_start_index=True,
)
docs = text_splitter.split_documents(data)
if len(docs) > 0:
log.info(f"store_data_in_vector_db {docs}")
return store_docs_in_vector_db(docs, collection_name, overwrite), None
else:
raise ValueError(ERROR_MESSAGES.EMPTY_CONTENT)
@@ -329,8 +640,8 @@ def store_text_in_vector_db(
text, metadata, collection_name, overwrite: bool = False
) -> bool:
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=app.state.CHUNK_SIZE,
chunk_overlap=app.state.CHUNK_OVERLAP,
chunk_size=app.state.config.CHUNK_SIZE,
chunk_overlap=app.state.config.CHUNK_OVERLAP,
add_start_index=True,
)
docs = text_splitter.create_documents([text], metadatas=[metadata])
@@ -338,6 +649,7 @@ def store_text_in_vector_db(
def store_docs_in_vector_db(docs, collection_name, overwrite: bool = False) -> bool:
log.info(f"store_docs_in_vector_db {docs} {collection_name}")
texts = [doc.page_content for doc in docs]
metadatas = [doc.metadata for doc in docs]
@@ -349,15 +661,24 @@ def store_docs_in_vector_db(docs, collection_name, overwrite: bool = False) -> b
log.info(f"deleting existing collection {collection_name}")
CHROMA_CLIENT.delete_collection(name=collection_name)
collection = CHROMA_CLIENT.create_collection(
name=collection_name,
embedding_function=app.state.sentence_transformer_ef,
collection = CHROMA_CLIENT.create_collection(name=collection_name)
embedding_func = get_embedding_function(
app.state.config.RAG_EMBEDDING_ENGINE,
app.state.config.RAG_EMBEDDING_MODEL,
app.state.sentence_transformer_ef,
app.state.config.OPENAI_API_KEY,
app.state.config.OPENAI_API_BASE_URL,
)
embedding_texts = list(map(lambda x: x.replace("\n", " "), texts))
embeddings = embedding_func(embedding_texts)
for batch in create_batches(
api=CHROMA_CLIENT,
ids=[str(uuid.uuid1()) for _ in texts],
ids=[str(uuid.uuid4()) for _ in texts],
metadatas=metadatas,
embeddings=embeddings,
documents=texts,
):
collection.add(*batch)
@@ -421,7 +742,9 @@ def get_loader(filename: str, file_content_type: str, file_path: str):
]
if file_ext == "pdf":
loader = PyPDFLoader(file_path, extract_images=app.state.PDF_EXTRACT_IMAGES)
loader = PyPDFLoader(
file_path, extract_images=app.state.config.PDF_EXTRACT_IMAGES
)
elif file_ext == "csv":
loader = CSVLoader(file_path)
elif file_ext == "rst":
@@ -629,3 +952,14 @@ def reset(user=Depends(get_admin_user)) -> bool:
log.exception(e)
return True
if ENV == "dev":
@app.get("/ef")
async def get_embeddings():
return {"result": app.state.EMBEDDING_FUNCTION("hello world")}
@app.get("/ef/{text}")
async def get_embeddings_text(text: str):
return {"result": app.state.EMBEDDING_FUNCTION(text)}
+372 -82
View File
@@ -1,99 +1,189 @@
import os
import re
import logging
import requests
from typing import List
from apps.ollama.main import (
generate_ollama_embeddings,
GenerateEmbeddingsForm,
)
from huggingface_hub import snapshot_download
from langchain_core.documents import Document
from langchain_community.retrievers import BM25Retriever
from langchain.retrievers import (
ContextualCompressionRetriever,
EnsembleRetriever,
)
from typing import Optional
from config import SRC_LOG_LEVELS, CHROMA_CLIENT
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["RAG"])
def query_doc(collection_name: str, query: str, k: int, embedding_function):
def query_doc(
collection_name: str,
query: str,
embedding_function,
k: int,
):
try:
# if you use docker use the model from the environment variable
collection = CHROMA_CLIENT.get_collection(
name=collection_name,
embedding_function=embedding_function,
)
collection = CHROMA_CLIENT.get_collection(name=collection_name)
query_embeddings = embedding_function(query)
result = collection.query(
query_texts=[query],
query_embeddings=[query_embeddings],
n_results=k,
)
log.info(f"query_doc:result {result}")
return result
except Exception as e:
raise e
def merge_and_sort_query_results(query_results, k):
def query_doc_with_hybrid_search(
collection_name: str,
query: str,
embedding_function,
k: int,
reranking_function,
r: float,
):
try:
collection = CHROMA_CLIENT.get_collection(name=collection_name)
documents = collection.get() # get all documents
bm25_retriever = BM25Retriever.from_texts(
texts=documents.get("documents"),
metadatas=documents.get("metadatas"),
)
bm25_retriever.k = k
chroma_retriever = ChromaRetriever(
collection=collection,
embedding_function=embedding_function,
top_n=k,
)
ensemble_retriever = EnsembleRetriever(
retrievers=[bm25_retriever, chroma_retriever], weights=[0.5, 0.5]
)
compressor = RerankCompressor(
embedding_function=embedding_function,
top_n=k,
reranking_function=reranking_function,
r_score=r,
)
compression_retriever = ContextualCompressionRetriever(
base_compressor=compressor, base_retriever=ensemble_retriever
)
result = compression_retriever.invoke(query)
result = {
"distances": [[d.metadata.get("score") for d in result]],
"documents": [[d.page_content for d in result]],
"metadatas": [[d.metadata for d in result]],
}
log.info(f"query_doc_with_hybrid_search:result {result}")
return result
except Exception as e:
raise e
def merge_and_sort_query_results(query_results, k, reverse=False):
# Initialize lists to store combined data
combined_ids = []
combined_distances = []
combined_metadatas = []
combined_documents = []
combined_metadatas = []
# Combine data from each dictionary
for data in query_results:
combined_ids.extend(data["ids"][0])
combined_distances.extend(data["distances"][0])
combined_metadatas.extend(data["metadatas"][0])
combined_documents.extend(data["documents"][0])
combined_metadatas.extend(data["metadatas"][0])
# Create a list of tuples (distance, id, metadata, document)
combined = list(
zip(combined_distances, combined_ids, combined_metadatas, combined_documents)
)
# Create a list of tuples (distance, document, metadata)
combined = list(zip(combined_distances, combined_documents, combined_metadatas))
# Sort the list based on distances
combined.sort(key=lambda x: x[0])
combined.sort(key=lambda x: x[0], reverse=reverse)
# Unzip the sorted list
sorted_distances, sorted_ids, sorted_metadatas, sorted_documents = zip(*combined)
# We don't have anything :-(
if not combined:
sorted_distances = []
sorted_documents = []
sorted_metadatas = []
else:
# Unzip the sorted list
sorted_distances, sorted_documents, sorted_metadatas = zip(*combined)
# Slicing the lists to include only k elements
sorted_distances = list(sorted_distances)[:k]
sorted_ids = list(sorted_ids)[:k]
sorted_metadatas = list(sorted_metadatas)[:k]
sorted_documents = list(sorted_documents)[:k]
# Slicing the lists to include only k elements
sorted_distances = list(sorted_distances)[:k]
sorted_documents = list(sorted_documents)[:k]
sorted_metadatas = list(sorted_metadatas)[:k]
# Create the output dictionary
merged_query_results = {
"ids": [sorted_ids],
result = {
"distances": [sorted_distances],
"metadatas": [sorted_metadatas],
"documents": [sorted_documents],
"embeddings": None,
"uris": None,
"data": None,
"metadatas": [sorted_metadatas],
}
return merged_query_results
return result
def query_collection(
collection_names: List[str], query: str, k: int, embedding_function
collection_names: List[str],
query: str,
embedding_function,
k: int,
):
results = []
for collection_name in collection_names:
try:
# if you use docker use the model from the environment variable
collection = CHROMA_CLIENT.get_collection(
name=collection_name,
result = query_doc(
collection_name=collection_name,
query=query,
k=k,
embedding_function=embedding_function,
)
result = collection.query(
query_texts=[query],
n_results=k,
)
results.append(result)
except:
pass
return merge_and_sort_query_results(results, k=k)
return merge_and_sort_query_results(results, k)
def query_collection_with_hybrid_search(
collection_names: List[str],
query: str,
embedding_function,
k: int,
reranking_function,
r: float,
):
results = []
for collection_name in collection_names:
try:
result = query_doc_with_hybrid_search(
collection_name=collection_name,
query=query,
embedding_function=embedding_function,
k=k,
reranking_function=reranking_function,
r=r,
)
results.append(result)
except:
pass
return merge_and_sort_query_results(results, k=k, reverse=True)
def rag_template(template: str, context: str, query: str):
@@ -102,8 +192,53 @@ def rag_template(template: str, context: str, query: str):
return template
def rag_messages(docs, messages, template, k, embedding_function):
log.debug(f"docs: {docs}")
def get_embedding_function(
embedding_engine,
embedding_model,
embedding_function,
openai_key,
openai_url,
):
if embedding_engine == "":
return lambda query: embedding_function.encode(query).tolist()
elif embedding_engine in ["ollama", "openai"]:
if embedding_engine == "ollama":
func = lambda query: generate_ollama_embeddings(
GenerateEmbeddingsForm(
**{
"model": embedding_model,
"prompt": query,
}
)
)
elif embedding_engine == "openai":
func = lambda query: generate_openai_embeddings(
model=embedding_model,
text=query,
key=openai_key,
url=openai_url,
)
def generate_multiple(query, f):
if isinstance(query, list):
return [f(q) for q in query]
else:
return f(query)
return lambda query: generate_multiple(query, func)
def rag_messages(
docs,
messages,
template,
embedding_function,
k,
reranking_function,
r,
hybrid_search,
):
log.debug(f"docs: {docs} {messages} {embedding_function} {reranking_function}")
last_user_message_idx = None
for i in range(len(messages) - 1, -1, -1):
@@ -130,40 +265,74 @@ def rag_messages(docs, messages, template, k, embedding_function):
content_type = None
query = ""
extracted_collections = []
relevant_contexts = []
for doc in docs:
context = None
collection_names = (
doc["collection_names"]
if doc["type"] == "collection"
else [doc["collection_name"]]
)
collection_names = set(collection_names).difference(extracted_collections)
if not collection_names:
log.debug(f"skipping {doc} as it has already been extracted")
continue
try:
if doc["type"] == "collection":
context = query_collection(
collection_names=doc["collection_names"],
query=query,
k=k,
embedding_function=embedding_function,
)
elif doc["type"] == "text":
if doc["type"] == "text":
context = doc["content"]
else:
context = query_doc(
collection_name=doc["collection_name"],
query=query,
k=k,
embedding_function=embedding_function,
)
if hybrid_search:
context = query_collection_with_hybrid_search(
collection_names=collection_names,
query=query,
embedding_function=embedding_function,
k=k,
reranking_function=reranking_function,
r=r,
)
else:
context = query_collection(
collection_names=collection_names,
query=query,
embedding_function=embedding_function,
k=k,
)
except Exception as e:
log.exception(e)
context = None
relevant_contexts.append(context)
if context:
relevant_contexts.append({**context, "source": doc})
log.debug(f"relevant_contexts: {relevant_contexts}")
extracted_collections.extend(collection_names)
context_string = ""
citations = []
for context in relevant_contexts:
if context:
context_string += " ".join(context["documents"][0]) + "\n"
try:
if "documents" in context:
context_string += "\n\n".join(
[text for text in context["documents"][0] if text is not None]
)
if "metadatas" in context:
citations.append(
{
"source": context["source"],
"document": context["documents"][0],
"metadata": context["metadatas"][0],
}
)
except Exception as e:
log.exception(e)
context_string = context_string.strip()
ra_content = rag_template(
template=template,
@@ -171,6 +340,8 @@ def rag_messages(docs, messages, template, k, embedding_function):
query=query,
)
log.debug(f"ra_content: {ra_content}")
if content_type == "list":
new_content = []
for content_item in user_message["content"]:
@@ -189,44 +360,163 @@ def rag_messages(docs, messages, template, k, embedding_function):
messages[last_user_message_idx] = new_user_message
return messages
return messages, citations
def get_embedding_model_path(
embedding_model: str, update_embedding_model: bool = False
):
def get_model_path(model: str, update_model: bool = False):
# Construct huggingface_hub kwargs with local_files_only to return the snapshot path
cache_dir = os.getenv("SENTENCE_TRANSFORMERS_HOME")
local_files_only = not update_embedding_model
local_files_only = not update_model
snapshot_kwargs = {
"cache_dir": cache_dir,
"local_files_only": local_files_only,
}
log.debug(f"embedding_model: {embedding_model}")
log.debug(f"model: {model}")
log.debug(f"snapshot_kwargs: {snapshot_kwargs}")
# Inspiration from upstream sentence_transformers
if (
os.path.exists(embedding_model)
or ("\\" in embedding_model or embedding_model.count("/") > 1)
os.path.exists(model)
or ("\\" in model or model.count("/") > 1)
and local_files_only
):
# If fully qualified path exists, return input, else set repo_id
return embedding_model
elif "/" not in embedding_model:
return model
elif "/" not in model:
# Set valid repo_id for model short-name
embedding_model = "sentence-transformers" + "/" + embedding_model
model = "sentence-transformers" + "/" + model
snapshot_kwargs["repo_id"] = embedding_model
snapshot_kwargs["repo_id"] = model
# Attempt to query the huggingface_hub library to determine the local path and/or to update
try:
embedding_model_repo_path = snapshot_download(**snapshot_kwargs)
log.debug(f"embedding_model_repo_path: {embedding_model_repo_path}")
return embedding_model_repo_path
model_repo_path = snapshot_download(**snapshot_kwargs)
log.debug(f"model_repo_path: {model_repo_path}")
return model_repo_path
except Exception as e:
log.exception(f"Cannot determine embedding model snapshot path: {e}")
return embedding_model
log.exception(f"Cannot determine model snapshot path: {e}")
return model
def generate_openai_embeddings(
model: str, text: str, key: str, url: str = "https://api.openai.com/v1"
):
try:
r = requests.post(
f"{url}/embeddings",
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {key}",
},
json={"input": text, "model": model},
)
r.raise_for_status()
data = r.json()
if "data" in data:
return data["data"][0]["embedding"]
else:
raise "Something went wrong :/"
except Exception as e:
print(e)
return None
from typing import Any
from langchain_core.retrievers import BaseRetriever
from langchain_core.callbacks import CallbackManagerForRetrieverRun
class ChromaRetriever(BaseRetriever):
collection: Any
embedding_function: Any
top_n: int
def _get_relevant_documents(
self,
query: str,
*,
run_manager: CallbackManagerForRetrieverRun,
) -> List[Document]:
query_embeddings = self.embedding_function(query)
results = self.collection.query(
query_embeddings=[query_embeddings],
n_results=self.top_n,
)
ids = results["ids"][0]
metadatas = results["metadatas"][0]
documents = results["documents"][0]
results = []
for idx in range(len(ids)):
results.append(
Document(
metadata=metadatas[idx],
page_content=documents[idx],
)
)
return results
import operator
from typing import Optional, Sequence
from langchain_core.documents import BaseDocumentCompressor, Document
from langchain_core.callbacks import Callbacks
from langchain_core.pydantic_v1 import Extra
from sentence_transformers import util
class RerankCompressor(BaseDocumentCompressor):
embedding_function: Any
top_n: int
reranking_function: Any
r_score: float
class Config:
extra = Extra.forbid
arbitrary_types_allowed = True
def compress_documents(
self,
documents: Sequence[Document],
query: str,
callbacks: Optional[Callbacks] = None,
) -> Sequence[Document]:
reranking = self.reranking_function is not None
if reranking:
scores = self.reranking_function.predict(
[(query, doc.page_content) for doc in documents]
)
else:
query_embedding = self.embedding_function(query)
document_embedding = self.embedding_function(
[doc.page_content for doc in documents]
)
scores = util.cos_sim(query_embedding, document_embedding)[0]
docs_with_scores = list(zip(documents, scores.tolist()))
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
+5 -4
View File
@@ -1,6 +1,7 @@
from peewee import *
from peewee_migrate import Router
from config import SRC_LOG_LEVELS, DATA_DIR
from playhouse.db_url import connect
from config import SRC_LOG_LEVELS, DATA_DIR, DATABASE_URL
import os
import logging
@@ -11,12 +12,12 @@ log.setLevel(SRC_LOG_LEVELS["DB"])
if os.path.exists(f"{DATA_DIR}/ollama.db"):
# Rename the file
os.rename(f"{DATA_DIR}/ollama.db", f"{DATA_DIR}/webui.db")
log.info("File renamed successfully.")
log.info("Database migrated from Ollama-WebUI successfully.")
else:
pass
DB = SqliteDatabase(f"{DATA_DIR}/webui.db")
DB = connect(DATABASE_URL)
log.info(f"Connected to a {DB.__class__.__name__} database.")
router = Router(DB, migrate_dir="apps/web/internal/migrations", logger=log)
router.run()
DB.connect(reuse_if_open=True)
@@ -37,6 +37,18 @@ with suppress(ImportError):
def migrate(migrator: Migrator, database: pw.Database, *, fake=False):
"""Write your migrations here."""
# We perform different migrations for SQLite and other databases
# This is because SQLite is very loose with enforcing its schema, and trying to migrate other databases like SQLite
# will require per-database SQL queries.
# Instead, we assume that because external DB support was added at a later date, it is safe to assume a newer base
# schema instead of trying to migrate from an older schema.
if isinstance(database, pw.SqliteDatabase):
migrate_sqlite(migrator, database, fake=fake)
else:
migrate_external(migrator, database, fake=fake)
def migrate_sqlite(migrator: Migrator, database: pw.Database, *, fake=False):
@migrator.create_model
class Auth(pw.Model):
id = pw.CharField(max_length=255, unique=True)
@@ -53,7 +65,7 @@ def migrate(migrator: Migrator, database: pw.Database, *, fake=False):
user_id = pw.CharField(max_length=255)
title = pw.CharField()
chat = pw.TextField()
timestamp = pw.DateField()
timestamp = pw.BigIntegerField()
class Meta:
table_name = "chat"
@@ -64,7 +76,7 @@ def migrate(migrator: Migrator, database: pw.Database, *, fake=False):
tag_name = pw.CharField(max_length=255)
chat_id = pw.CharField(max_length=255)
user_id = pw.CharField(max_length=255)
timestamp = pw.DateField()
timestamp = pw.BigIntegerField()
class Meta:
table_name = "chatidtag"
@@ -78,7 +90,7 @@ def migrate(migrator: Migrator, database: pw.Database, *, fake=False):
filename = pw.CharField()
content = pw.TextField(null=True)
user_id = pw.CharField(max_length=255)
timestamp = pw.DateField()
timestamp = pw.BigIntegerField()
class Meta:
table_name = "document"
@@ -89,7 +101,7 @@ def migrate(migrator: Migrator, database: pw.Database, *, fake=False):
tag_name = pw.CharField(max_length=255, unique=True)
user_id = pw.CharField(max_length=255)
modelfile = pw.TextField()
timestamp = pw.DateField()
timestamp = pw.BigIntegerField()
class Meta:
table_name = "modelfile"
@@ -101,7 +113,7 @@ def migrate(migrator: Migrator, database: pw.Database, *, fake=False):
user_id = pw.CharField(max_length=255)
title = pw.CharField()
content = pw.TextField()
timestamp = pw.DateField()
timestamp = pw.BigIntegerField()
class Meta:
table_name = "prompt"
@@ -123,7 +135,100 @@ def migrate(migrator: Migrator, database: pw.Database, *, fake=False):
email = pw.CharField(max_length=255)
role = pw.CharField(max_length=255)
profile_image_url = pw.CharField(max_length=255)
timestamp = pw.DateField()
timestamp = pw.BigIntegerField()
class Meta:
table_name = "user"
def migrate_external(migrator: Migrator, database: pw.Database, *, fake=False):
@migrator.create_model
class Auth(pw.Model):
id = pw.CharField(max_length=255, unique=True)
email = pw.CharField(max_length=255)
password = pw.TextField()
active = pw.BooleanField()
class Meta:
table_name = "auth"
@migrator.create_model
class Chat(pw.Model):
id = pw.CharField(max_length=255, unique=True)
user_id = pw.CharField(max_length=255)
title = pw.TextField()
chat = pw.TextField()
timestamp = pw.BigIntegerField()
class Meta:
table_name = "chat"
@migrator.create_model
class ChatIdTag(pw.Model):
id = pw.CharField(max_length=255, unique=True)
tag_name = pw.CharField(max_length=255)
chat_id = pw.CharField(max_length=255)
user_id = pw.CharField(max_length=255)
timestamp = pw.BigIntegerField()
class Meta:
table_name = "chatidtag"
@migrator.create_model
class Document(pw.Model):
id = pw.AutoField()
collection_name = pw.CharField(max_length=255, unique=True)
name = pw.CharField(max_length=255, unique=True)
title = pw.TextField()
filename = pw.TextField()
content = pw.TextField(null=True)
user_id = pw.CharField(max_length=255)
timestamp = pw.BigIntegerField()
class Meta:
table_name = "document"
@migrator.create_model
class Modelfile(pw.Model):
id = pw.AutoField()
tag_name = pw.CharField(max_length=255, unique=True)
user_id = pw.CharField(max_length=255)
modelfile = pw.TextField()
timestamp = pw.BigIntegerField()
class Meta:
table_name = "modelfile"
@migrator.create_model
class Prompt(pw.Model):
id = pw.AutoField()
command = pw.CharField(max_length=255, unique=True)
user_id = pw.CharField(max_length=255)
title = pw.TextField()
content = pw.TextField()
timestamp = pw.BigIntegerField()
class Meta:
table_name = "prompt"
@migrator.create_model
class Tag(pw.Model):
id = pw.CharField(max_length=255, unique=True)
name = pw.CharField(max_length=255)
user_id = pw.CharField(max_length=255)
data = pw.TextField(null=True)
class Meta:
table_name = "tag"
@migrator.create_model
class User(pw.Model):
id = pw.CharField(max_length=255, unique=True)
name = pw.CharField(max_length=255)
email = pw.CharField(max_length=255)
role = pw.CharField(max_length=255)
profile_image_url = pw.TextField()
timestamp = pw.BigIntegerField()
class Meta:
table_name = "user"
@@ -0,0 +1,46 @@
"""Peewee migrations -- 002_add_local_sharing.py.
Some examples (model - class or model name)::
> Model = migrator.orm['table_name'] # Return model in current state by name
> Model = migrator.ModelClass # Return model in current state by name
> migrator.sql(sql) # Run custom SQL
> migrator.run(func, *args, **kwargs) # Run python function with the given args
> migrator.create_model(Model) # Create a model (could be used as decorator)
> migrator.remove_model(model, cascade=True) # Remove a model
> migrator.add_fields(model, **fields) # Add fields to a model
> migrator.change_fields(model, **fields) # Change fields
> migrator.remove_fields(model, *field_names, cascade=True)
> migrator.rename_field(model, old_field_name, new_field_name)
> migrator.rename_table(model, new_table_name)
> migrator.add_index(model, *col_names, unique=False)
> migrator.add_not_null(model, *field_names)
> migrator.add_default(model, field_name, default)
> migrator.add_constraint(model, name, sql)
> migrator.drop_index(model, *col_names)
> migrator.drop_not_null(model, *field_names)
> migrator.drop_constraints(model, *constraints)
"""
from contextlib import suppress
import peewee as pw
from peewee_migrate import Migrator
with suppress(ImportError):
import playhouse.postgres_ext as pw_pext
def migrate(migrator: Migrator, database: pw.Database, *, fake=False):
"""Write your migrations here."""
migrator.add_fields("chat", archived=pw.BooleanField(default=False))
def rollback(migrator: Migrator, database: pw.Database, *, fake=False):
"""Write your rollback migrations here."""
migrator.remove_fields("chat", "archived")
@@ -0,0 +1,130 @@
"""Peewee migrations -- 002_add_local_sharing.py.
Some examples (model - class or model name)::
> Model = migrator.orm['table_name'] # Return model in current state by name
> Model = migrator.ModelClass # Return model in current state by name
> migrator.sql(sql) # Run custom SQL
> migrator.run(func, *args, **kwargs) # Run python function with the given args
> migrator.create_model(Model) # Create a model (could be used as decorator)
> migrator.remove_model(model, cascade=True) # Remove a model
> migrator.add_fields(model, **fields) # Add fields to a model
> migrator.change_fields(model, **fields) # Change fields
> migrator.remove_fields(model, *field_names, cascade=True)
> migrator.rename_field(model, old_field_name, new_field_name)
> migrator.rename_table(model, new_table_name)
> migrator.add_index(model, *col_names, unique=False)
> migrator.add_not_null(model, *field_names)
> migrator.add_default(model, field_name, default)
> migrator.add_constraint(model, name, sql)
> migrator.drop_index(model, *col_names)
> migrator.drop_not_null(model, *field_names)
> migrator.drop_constraints(model, *constraints)
"""
from contextlib import suppress
import peewee as pw
from peewee_migrate import Migrator
with suppress(ImportError):
import playhouse.postgres_ext as pw_pext
def migrate(migrator: Migrator, database: pw.Database, *, fake=False):
"""Write your migrations here."""
if isinstance(database, pw.SqliteDatabase):
migrate_sqlite(migrator, database, fake=fake)
else:
migrate_external(migrator, database, fake=fake)
def migrate_sqlite(migrator: Migrator, database: pw.Database, *, fake=False):
# Adding fields created_at and updated_at to the 'chat' table
migrator.add_fields(
"chat",
created_at=pw.DateTimeField(null=True), # Allow null for transition
updated_at=pw.DateTimeField(null=True), # Allow null for transition
)
# Populate the new fields from an existing 'timestamp' field
migrator.sql(
"UPDATE chat SET created_at = timestamp, updated_at = timestamp WHERE timestamp IS NOT NULL"
)
# Now that the data has been copied, remove the original 'timestamp' field
migrator.remove_fields("chat", "timestamp")
# Update the fields to be not null now that they are populated
migrator.change_fields(
"chat",
created_at=pw.DateTimeField(null=False),
updated_at=pw.DateTimeField(null=False),
)
def migrate_external(migrator: Migrator, database: pw.Database, *, fake=False):
# Adding fields created_at and updated_at to the 'chat' table
migrator.add_fields(
"chat",
created_at=pw.BigIntegerField(null=True), # Allow null for transition
updated_at=pw.BigIntegerField(null=True), # Allow null for transition
)
# Populate the new fields from an existing 'timestamp' field
migrator.sql(
"UPDATE chat SET created_at = timestamp, updated_at = timestamp WHERE timestamp IS NOT NULL"
)
# Now that the data has been copied, remove the original 'timestamp' field
migrator.remove_fields("chat", "timestamp")
# Update the fields to be not null now that they are populated
migrator.change_fields(
"chat",
created_at=pw.BigIntegerField(null=False),
updated_at=pw.BigIntegerField(null=False),
)
def rollback(migrator: Migrator, database: pw.Database, *, fake=False):
"""Write your rollback migrations here."""
if isinstance(database, pw.SqliteDatabase):
rollback_sqlite(migrator, database, fake=fake)
else:
rollback_external(migrator, database, fake=fake)
def rollback_sqlite(migrator: Migrator, database: pw.Database, *, fake=False):
# Recreate the timestamp field initially allowing null values for safe transition
migrator.add_fields("chat", timestamp=pw.DateTimeField(null=True))
# Copy the earliest created_at date back into the new timestamp field
# This assumes created_at was originally a copy of timestamp
migrator.sql("UPDATE chat SET timestamp = created_at")
# Remove the created_at and updated_at fields
migrator.remove_fields("chat", "created_at", "updated_at")
# Finally, alter the timestamp field to not allow nulls if that was the original setting
migrator.change_fields("chat", timestamp=pw.DateTimeField(null=False))
def rollback_external(migrator: Migrator, database: pw.Database, *, fake=False):
# Recreate the timestamp field initially allowing null values for safe transition
migrator.add_fields("chat", timestamp=pw.BigIntegerField(null=True))
# Copy the earliest created_at date back into the new timestamp field
# This assumes created_at was originally a copy of timestamp
migrator.sql("UPDATE chat SET timestamp = created_at")
# Remove the created_at and updated_at fields
migrator.remove_fields("chat", "created_at", "updated_at")
# Finally, alter the timestamp field to not allow nulls if that was the original setting
migrator.change_fields("chat", timestamp=pw.BigIntegerField(null=False))
@@ -0,0 +1,130 @@
"""Peewee migrations -- 006_migrate_timestamps_and_charfields.py.
Some examples (model - class or model name)::
> Model = migrator.orm['table_name'] # Return model in current state by name
> Model = migrator.ModelClass # Return model in current state by name
> migrator.sql(sql) # Run custom SQL
> migrator.run(func, *args, **kwargs) # Run python function with the given args
> migrator.create_model(Model) # Create a model (could be used as decorator)
> migrator.remove_model(model, cascade=True) # Remove a model
> migrator.add_fields(model, **fields) # Add fields to a model
> migrator.change_fields(model, **fields) # Change fields
> migrator.remove_fields(model, *field_names, cascade=True)
> migrator.rename_field(model, old_field_name, new_field_name)
> migrator.rename_table(model, new_table_name)
> migrator.add_index(model, *col_names, unique=False)
> migrator.add_not_null(model, *field_names)
> migrator.add_default(model, field_name, default)
> migrator.add_constraint(model, name, sql)
> migrator.drop_index(model, *col_names)
> migrator.drop_not_null(model, *field_names)
> migrator.drop_constraints(model, *constraints)
"""
from contextlib import suppress
import peewee as pw
from peewee_migrate import Migrator
with suppress(ImportError):
import playhouse.postgres_ext as pw_pext
def migrate(migrator: Migrator, database: pw.Database, *, fake=False):
"""Write your migrations here."""
# Alter the tables with timestamps
migrator.change_fields(
"chatidtag",
timestamp=pw.BigIntegerField(),
)
migrator.change_fields(
"document",
timestamp=pw.BigIntegerField(),
)
migrator.change_fields(
"modelfile",
timestamp=pw.BigIntegerField(),
)
migrator.change_fields(
"prompt",
timestamp=pw.BigIntegerField(),
)
migrator.change_fields(
"user",
timestamp=pw.BigIntegerField(),
)
# Alter the tables with varchar to text where necessary
migrator.change_fields(
"auth",
password=pw.TextField(),
)
migrator.change_fields(
"chat",
title=pw.TextField(),
)
migrator.change_fields(
"document",
title=pw.TextField(),
filename=pw.TextField(),
)
migrator.change_fields(
"prompt",
title=pw.TextField(),
)
migrator.change_fields(
"user",
profile_image_url=pw.TextField(),
)
def rollback(migrator: Migrator, database: pw.Database, *, fake=False):
"""Write your rollback migrations here."""
if isinstance(database, pw.SqliteDatabase):
# Alter the tables with timestamps
migrator.change_fields(
"chatidtag",
timestamp=pw.DateField(),
)
migrator.change_fields(
"document",
timestamp=pw.DateField(),
)
migrator.change_fields(
"modelfile",
timestamp=pw.DateField(),
)
migrator.change_fields(
"prompt",
timestamp=pw.DateField(),
)
migrator.change_fields(
"user",
timestamp=pw.DateField(),
)
migrator.change_fields(
"auth",
password=pw.CharField(max_length=255),
)
migrator.change_fields(
"chat",
title=pw.CharField(),
)
migrator.change_fields(
"document",
title=pw.CharField(),
filename=pw.CharField(),
)
migrator.change_fields(
"prompt",
title=pw.CharField(),
)
migrator.change_fields(
"user",
profile_image_url=pw.CharField(),
)
@@ -0,0 +1,79 @@
"""Peewee migrations -- 002_add_local_sharing.py.
Some examples (model - class or model name)::
> Model = migrator.orm['table_name'] # Return model in current state by name
> Model = migrator.ModelClass # Return model in current state by name
> migrator.sql(sql) # Run custom SQL
> migrator.run(func, *args, **kwargs) # Run python function with the given args
> migrator.create_model(Model) # Create a model (could be used as decorator)
> migrator.remove_model(model, cascade=True) # Remove a model
> migrator.add_fields(model, **fields) # Add fields to a model
> migrator.change_fields(model, **fields) # Change fields
> migrator.remove_fields(model, *field_names, cascade=True)
> migrator.rename_field(model, old_field_name, new_field_name)
> migrator.rename_table(model, new_table_name)
> migrator.add_index(model, *col_names, unique=False)
> migrator.add_not_null(model, *field_names)
> migrator.add_default(model, field_name, default)
> migrator.add_constraint(model, name, sql)
> migrator.drop_index(model, *col_names)
> migrator.drop_not_null(model, *field_names)
> migrator.drop_constraints(model, *constraints)
"""
from contextlib import suppress
import peewee as pw
from peewee_migrate import Migrator
with suppress(ImportError):
import playhouse.postgres_ext as pw_pext
def migrate(migrator: Migrator, database: pw.Database, *, fake=False):
"""Write your migrations here."""
# Adding fields created_at and updated_at to the 'user' table
migrator.add_fields(
"user",
created_at=pw.BigIntegerField(null=True), # Allow null for transition
updated_at=pw.BigIntegerField(null=True), # Allow null for transition
last_active_at=pw.BigIntegerField(null=True), # Allow null for transition
)
# Populate the new fields from an existing 'timestamp' field
migrator.sql(
'UPDATE "user" SET created_at = timestamp, updated_at = timestamp, last_active_at = timestamp WHERE timestamp IS NOT NULL'
)
# Now that the data has been copied, remove the original 'timestamp' field
migrator.remove_fields("user", "timestamp")
# Update the fields to be not null now that they are populated
migrator.change_fields(
"user",
created_at=pw.BigIntegerField(null=False),
updated_at=pw.BigIntegerField(null=False),
last_active_at=pw.BigIntegerField(null=False),
)
def rollback(migrator: Migrator, database: pw.Database, *, fake=False):
"""Write your rollback migrations here."""
# Recreate the timestamp field initially allowing null values for safe transition
migrator.add_fields("user", timestamp=pw.BigIntegerField(null=True))
# Copy the earliest created_at date back into the new timestamp field
# This assumes created_at was originally a copy of timestamp
migrator.sql('UPDATE "user" SET timestamp = created_at')
# Remove the created_at and updated_at fields
migrator.remove_fields("user", "created_at", "updated_at", "last_active_at")
# Finally, alter the timestamp field to not allow nulls if that was the original setting
migrator.change_fields("user", timestamp=pw.BigIntegerField(null=False))
@@ -0,0 +1,53 @@
"""Peewee migrations -- 002_add_local_sharing.py.
Some examples (model - class or model name)::
> Model = migrator.orm['table_name'] # Return model in current state by name
> Model = migrator.ModelClass # Return model in current state by name
> migrator.sql(sql) # Run custom SQL
> migrator.run(func, *args, **kwargs) # Run python function with the given args
> migrator.create_model(Model) # Create a model (could be used as decorator)
> migrator.remove_model(model, cascade=True) # Remove a model
> migrator.add_fields(model, **fields) # Add fields to a model
> migrator.change_fields(model, **fields) # Change fields
> migrator.remove_fields(model, *field_names, cascade=True)
> migrator.rename_field(model, old_field_name, new_field_name)
> migrator.rename_table(model, new_table_name)
> migrator.add_index(model, *col_names, unique=False)
> migrator.add_not_null(model, *field_names)
> migrator.add_default(model, field_name, default)
> migrator.add_constraint(model, name, sql)
> migrator.drop_index(model, *col_names)
> migrator.drop_not_null(model, *field_names)
> migrator.drop_constraints(model, *constraints)
"""
from contextlib import suppress
import peewee as pw
from peewee_migrate import Migrator
with suppress(ImportError):
import playhouse.postgres_ext as pw_pext
def migrate(migrator: Migrator, database: pw.Database, *, fake=False):
@migrator.create_model
class Memory(pw.Model):
id = pw.CharField(max_length=255, unique=True)
user_id = pw.CharField(max_length=255)
content = pw.TextField(null=False)
updated_at = pw.BigIntegerField(null=False)
created_at = pw.BigIntegerField(null=False)
class Meta:
table_name = "memory"
def rollback(migrator: Migrator, database: pw.Database, *, fake=False):
"""Write your rollback migrations here."""
migrator.remove_model("memory")
+18 -9
View File
@@ -9,6 +9,7 @@ from apps.web.routers import (
modelfiles,
prompts,
configs,
memories,
utils,
)
from config import (
@@ -21,22 +22,27 @@ from config import (
USER_PERMISSIONS,
WEBHOOK_URL,
WEBUI_AUTH_TRUSTED_EMAIL_HEADER,
JWT_EXPIRES_IN,
AppConfig,
)
app = FastAPI()
origins = ["*"]
app.state.ENABLE_SIGNUP = ENABLE_SIGNUP
app.state.JWT_EXPIRES_IN = "-1"
app.state.config = AppConfig()
app.state.DEFAULT_MODELS = DEFAULT_MODELS
app.state.DEFAULT_PROMPT_SUGGESTIONS = DEFAULT_PROMPT_SUGGESTIONS
app.state.DEFAULT_USER_ROLE = DEFAULT_USER_ROLE
app.state.USER_PERMISSIONS = USER_PERMISSIONS
app.state.WEBHOOK_URL = WEBHOOK_URL
app.state.config.ENABLE_SIGNUP = ENABLE_SIGNUP
app.state.config.JWT_EXPIRES_IN = JWT_EXPIRES_IN
app.state.config.DEFAULT_MODELS = DEFAULT_MODELS
app.state.config.DEFAULT_PROMPT_SUGGESTIONS = DEFAULT_PROMPT_SUGGESTIONS
app.state.config.DEFAULT_USER_ROLE = DEFAULT_USER_ROLE
app.state.config.USER_PERMISSIONS = USER_PERMISSIONS
app.state.config.WEBHOOK_URL = WEBHOOK_URL
app.state.AUTH_TRUSTED_EMAIL_HEADER = WEBUI_AUTH_TRUSTED_EMAIL_HEADER
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
@@ -48,9 +54,12 @@ app.add_middleware(
app.include_router(auths.router, prefix="/auths", tags=["auths"])
app.include_router(users.router, prefix="/users", tags=["users"])
app.include_router(chats.router, prefix="/chats", tags=["chats"])
app.include_router(documents.router, prefix="/documents", tags=["documents"])
app.include_router(modelfiles.router, prefix="/modelfiles", tags=["modelfiles"])
app.include_router(prompts.router, prefix="/prompts", tags=["prompts"])
app.include_router(memories.router, prefix="/memories", tags=["memories"])
app.include_router(configs.router, prefix="/configs", tags=["configs"])
app.include_router(utils.router, prefix="/utils", tags=["utils"])
@@ -61,6 +70,6 @@ async def get_status():
return {
"status": True,
"auth": WEBUI_AUTH,
"default_models": app.state.DEFAULT_MODELS,
"default_prompt_suggestions": app.state.DEFAULT_PROMPT_SUGGESTIONS,
"default_models": app.state.config.DEFAULT_MODELS,
"default_prompt_suggestions": app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
}
+5 -1
View File
@@ -23,7 +23,7 @@ log.setLevel(SRC_LOG_LEVELS["MODELS"])
class Auth(Model):
id = CharField(unique=True)
email = CharField()
password = CharField()
password = TextField()
active = BooleanField()
class Meta:
@@ -89,6 +89,10 @@ class SignupForm(BaseModel):
profile_image_url: Optional[str] = "/user.png"
class AddUserForm(SignupForm):
role: Optional[str] = "pending"
class AuthsTable:
def __init__(self, db):
self.db = db
+74 -26
View File
@@ -17,10 +17,14 @@ from apps.web.internal.db import DB
class Chat(Model):
id = CharField(unique=True)
user_id = CharField()
title = CharField()
title = TextField()
chat = TextField() # Save Chat JSON as Text
timestamp = DateField()
created_at = BigIntegerField()
updated_at = BigIntegerField()
share_id = CharField(null=True, unique=True)
archived = BooleanField(default=False)
class Meta:
database = DB
@@ -31,8 +35,12 @@ class ChatModel(BaseModel):
user_id: str
title: str
chat: str
timestamp: int # timestamp in epoch
created_at: int # timestamp in epoch
updated_at: int # timestamp in epoch
share_id: Optional[str] = None
archived: bool = False
####################
@@ -53,13 +61,17 @@ class ChatResponse(BaseModel):
user_id: str
title: str
chat: dict
timestamp: int # timestamp in epoch
updated_at: int # timestamp in epoch
created_at: int # timestamp in epoch
share_id: Optional[str] = None # id of the chat to be shared
archived: bool
class ChatTitleIdResponse(BaseModel):
id: str
title: str
updated_at: int
created_at: int
class ChatTable:
@@ -77,7 +89,8 @@ class ChatTable:
form_data.chat["title"] if "title" in form_data.chat else "New Chat"
),
"chat": json.dumps(form_data.chat),
"timestamp": int(time.time()),
"created_at": int(time.time()),
"updated_at": int(time.time()),
}
)
@@ -89,7 +102,7 @@ class ChatTable:
query = Chat.update(
chat=json.dumps(chat),
title=chat["title"] if "title" in chat else "New Chat",
timestamp=int(time.time()),
updated_at=int(time.time()),
).where(Chat.id == id)
query.execute()
@@ -111,7 +124,8 @@ class ChatTable:
"user_id": f"shared-{chat_id}",
"title": chat.title,
"chat": chat.chat,
"timestamp": int(time.time()),
"created_at": chat.created_at,
"updated_at": int(time.time()),
}
)
shared_result = Chat.create(**shared_chat.model_dump())
@@ -163,40 +177,55 @@ class ChatTable:
except:
return None
def get_chat_lists_by_user_id(
def toggle_chat_archive_by_id(self, id: str) -> Optional[ChatModel]:
try:
chat = self.get_chat_by_id(id)
query = Chat.update(
archived=(not chat.archived),
).where(Chat.id == id)
query.execute()
chat = Chat.get(Chat.id == id)
return ChatModel(**model_to_dict(chat))
except:
return None
def get_archived_chat_list_by_user_id(
self, user_id: str, skip: int = 0, limit: int = 50
) -> List[ChatModel]:
return [
ChatModel(**model_to_dict(chat))
for chat in Chat.select()
.where(Chat.archived == True)
.where(Chat.user_id == user_id)
.order_by(Chat.timestamp.desc())
.order_by(Chat.updated_at.desc())
# .limit(limit)
# .offset(skip)
]
def get_chat_lists_by_chat_ids(
def get_chat_list_by_user_id(
self, user_id: str, skip: int = 0, limit: int = 50
) -> List[ChatModel]:
return [
ChatModel(**model_to_dict(chat))
for chat in Chat.select()
.where(Chat.archived == False)
.where(Chat.user_id == user_id)
.order_by(Chat.updated_at.desc())
# .limit(limit)
# .offset(skip)
]
def get_chat_list_by_chat_ids(
self, chat_ids: List[str], skip: int = 0, limit: int = 50
) -> List[ChatModel]:
return [
ChatModel(**model_to_dict(chat))
for chat in Chat.select()
.where(Chat.archived == False)
.where(Chat.id.in_(chat_ids))
.order_by(Chat.timestamp.desc())
]
def get_all_chats(self) -> List[ChatModel]:
return [
ChatModel(**model_to_dict(chat))
for chat in Chat.select().order_by(Chat.timestamp.desc())
]
def get_all_chats_by_user_id(self, user_id: str) -> List[ChatModel]:
return [
ChatModel(**model_to_dict(chat))
for chat in Chat.select()
.where(Chat.user_id == user_id)
.order_by(Chat.timestamp.desc())
.order_by(Chat.updated_at.desc())
]
def get_chat_by_id(self, id: str) -> Optional[ChatModel]:
@@ -228,9 +257,28 @@ class ChatTable:
def get_chats(self, skip: int = 0, limit: int = 50) -> List[ChatModel]:
return [
ChatModel(**model_to_dict(chat))
for chat in Chat.select().limit(limit).offset(skip)
for chat in Chat.select().order_by(Chat.updated_at.desc())
# .limit(limit).offset(skip)
]
def get_chats_by_user_id(self, user_id: str) -> List[ChatModel]:
return [
ChatModel(**model_to_dict(chat))
for chat in Chat.select()
.where(Chat.user_id == user_id)
.order_by(Chat.updated_at.desc())
# .limit(limit).offset(skip)
]
def delete_chat_by_id(self, id: str) -> bool:
try:
query = Chat.delete().where((Chat.id == id))
query.execute() # Remove the rows, return number of rows removed.
return True and self.delete_shared_chat_by_chat_id(id)
except:
return False
def delete_chat_by_id_and_user_id(self, id: str, user_id: str) -> bool:
try:
query = Chat.delete().where((Chat.id == id) & (Chat.user_id == user_id))
+3 -3
View File
@@ -25,11 +25,11 @@ log.setLevel(SRC_LOG_LEVELS["MODELS"])
class Document(Model):
collection_name = CharField(unique=True)
name = CharField(unique=True)
title = CharField()
filename = CharField()
title = TextField()
filename = TextField()
content = TextField(null=True)
user_id = CharField()
timestamp = DateField()
timestamp = BigIntegerField()
class Meta:
database = DB
+118
View File
@@ -0,0 +1,118 @@
from pydantic import BaseModel
from peewee import *
from playhouse.shortcuts import model_to_dict
from typing import List, Union, Optional
from apps.web.internal.db import DB
from apps.web.models.chats import Chats
import time
import uuid
####################
# Memory DB Schema
####################
class Memory(Model):
id = CharField(unique=True)
user_id = CharField()
content = TextField()
updated_at = BigIntegerField()
created_at = BigIntegerField()
class Meta:
database = DB
class MemoryModel(BaseModel):
id: str
user_id: str
content: str
updated_at: int # timestamp in epoch
created_at: int # timestamp in epoch
####################
# Forms
####################
class MemoriesTable:
def __init__(self, db):
self.db = db
self.db.create_tables([Memory])
def insert_new_memory(
self,
user_id: str,
content: str,
) -> Optional[MemoryModel]:
id = str(uuid.uuid4())
memory = MemoryModel(
**{
"id": id,
"user_id": user_id,
"content": content,
"created_at": int(time.time()),
"updated_at": int(time.time()),
}
)
result = Memory.create(**memory.model_dump())
if result:
return memory
else:
return None
def get_memories(self) -> List[MemoryModel]:
try:
memories = Memory.select()
return [MemoryModel(**model_to_dict(memory)) for memory in memories]
except:
return None
def get_memories_by_user_id(self, user_id: str) -> List[MemoryModel]:
try:
memories = Memory.select().where(Memory.user_id == user_id)
return [MemoryModel(**model_to_dict(memory)) for memory in memories]
except:
return None
def get_memory_by_id(self, id) -> Optional[MemoryModel]:
try:
memory = Memory.get(Memory.id == id)
return MemoryModel(**model_to_dict(memory))
except:
return None
def delete_memory_by_id(self, id: str) -> bool:
try:
query = Memory.delete().where(Memory.id == id)
query.execute() # Remove the rows, return number of rows removed.
return True
except:
return False
def delete_memories_by_user_id(self, user_id: str) -> bool:
try:
query = Memory.delete().where(Memory.user_id == user_id)
query.execute()
return True
except:
return False
def delete_memory_by_id_and_user_id(self, id: str, user_id: str) -> bool:
try:
query = Memory.delete().where(Memory.id == id, Memory.user_id == user_id)
query.execute()
return True
except:
return False
Memories = MemoriesTable(DB)
+1 -1
View File
@@ -20,7 +20,7 @@ class Modelfile(Model):
tag_name = CharField(unique=True)
user_id = CharField()
modelfile = TextField()
timestamp = DateField()
timestamp = BigIntegerField()
class Meta:
database = DB
+2 -2
View File
@@ -19,9 +19,9 @@ import json
class Prompt(Model):
command = CharField(unique=True)
user_id = CharField()
title = CharField()
title = TextField()
content = TextField()
timestamp = DateField()
timestamp = BigIntegerField()
class Meta:
database = DB
+7 -3
View File
@@ -35,7 +35,7 @@ class ChatIdTag(Model):
tag_name = CharField()
chat_id = CharField()
user_id = CharField()
timestamp = DateField()
timestamp = BigIntegerField()
class Meta:
database = DB
@@ -136,7 +136,9 @@ class TagTable:
return [
TagModel(**model_to_dict(tag))
for tag in Tag.select().where(Tag.name.in_(tag_names))
for tag in Tag.select()
.where(Tag.user_id == user_id)
.where(Tag.name.in_(tag_names))
]
def get_tags_by_chat_id_and_user_id(
@@ -151,7 +153,9 @@ class TagTable:
return [
TagModel(**model_to_dict(tag))
for tag in Tag.select().where(Tag.name.in_(tag_names))
for tag in Tag.select()
.where(Tag.user_id == user_id)
.where(Tag.name.in_(tag_names))
]
def get_chat_ids_by_tag_name_and_user_id(
+31 -4
View File
@@ -18,8 +18,12 @@ class User(Model):
name = CharField()
email = CharField()
role = CharField()
profile_image_url = CharField()
timestamp = DateField()
profile_image_url = TextField()
last_active_at = BigIntegerField()
updated_at = BigIntegerField()
created_at = BigIntegerField()
api_key = CharField(null=True, unique=True)
class Meta:
@@ -32,7 +36,11 @@ class UserModel(BaseModel):
email: str
role: str = "pending"
profile_image_url: str
timestamp: int # timestamp in epoch
last_active_at: int # timestamp in epoch
updated_at: int # timestamp in epoch
created_at: int # timestamp in epoch
api_key: Optional[str] = None
@@ -73,7 +81,9 @@ class UsersTable:
"email": email,
"role": role,
"profile_image_url": profile_image_url,
"timestamp": int(time.time()),
"last_active_at": int(time.time()),
"created_at": int(time.time()),
"updated_at": int(time.time()),
}
)
result = User.create(**user.model_dump())
@@ -113,6 +123,13 @@ class UsersTable:
def get_num_users(self) -> Optional[int]:
return User.select().count()
def get_first_user(self) -> UserModel:
try:
user = User.select().order_by(User.created_at).first()
return UserModel(**model_to_dict(user))
except:
return None
def update_user_role_by_id(self, id: str, role: str) -> Optional[UserModel]:
try:
query = User.update(role=role).where(User.id == id)
@@ -137,6 +154,16 @@ class UsersTable:
except:
return None
def update_user_last_active_by_id(self, id: str) -> Optional[UserModel]:
try:
query = User.update(last_active_at=int(time.time())).where(User.id == id)
query.execute()
user = User.get(User.id == id)
return UserModel(**model_to_dict(user))
except:
return None
def update_user_by_id(self, id: str, updated: dict) -> Optional[UserModel]:
try:
query = User.update(**updated).where(User.id == id)
+84 -18
View File
@@ -1,14 +1,19 @@
from fastapi import Request
import logging
from fastapi import Request, UploadFile, File
from fastapi import Depends, HTTPException, status
from fastapi import APIRouter
from pydantic import BaseModel
import re
import uuid
import csv
from apps.web.models.auths import (
SigninForm,
SignupForm,
AddUserForm,
UpdateProfileForm,
UpdatePasswordForm,
UserResponse,
@@ -28,7 +33,7 @@ from utils.utils import (
from utils.misc import parse_duration, validate_email_format
from utils.webhook import post_webhook
from constants import ERROR_MESSAGES, WEBHOOK_MESSAGES
from config import WEBUI_AUTH_TRUSTED_EMAIL_HEADER
from config import WEBUI_AUTH, WEBUI_AUTH_TRUSTED_EMAIL_HEADER
router = APIRouter()
@@ -113,13 +118,29 @@ async def signin(request: Request, form_data: SigninForm):
),
)
user = Auths.authenticate_user_by_trusted_header(trusted_email)
elif WEBUI_AUTH == False:
admin_email = "admin@localhost"
admin_password = "admin"
if Users.get_user_by_email(admin_email.lower()):
user = Auths.authenticate_user(admin_email.lower(), admin_password)
else:
if Users.get_num_users() != 0:
raise HTTPException(400, detail=ERROR_MESSAGES.EXISTING_USERS)
await signup(
request,
SignupForm(email=admin_email, password=admin_password, name="User"),
)
user = Auths.authenticate_user(admin_email.lower(), admin_password)
else:
user = Auths.authenticate_user(form_data.email.lower(), form_data.password)
if user:
token = create_token(
data={"id": user.id},
expires_delta=parse_duration(request.app.state.JWT_EXPIRES_IN),
expires_delta=parse_duration(request.app.state.config.JWT_EXPIRES_IN),
)
return {
@@ -142,7 +163,7 @@ async def signin(request: Request, form_data: SigninForm):
@router.post("/signup", response_model=SigninResponse)
async def signup(request: Request, form_data: SignupForm):
if not request.app.state.ENABLE_SIGNUP:
if not request.app.state.config.ENABLE_SIGNUP and WEBUI_AUTH:
raise HTTPException(
status.HTTP_403_FORBIDDEN, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
)
@@ -159,7 +180,7 @@ async def signup(request: Request, form_data: SignupForm):
role = (
"admin"
if Users.get_num_users() == 0
else request.app.state.DEFAULT_USER_ROLE
else request.app.state.config.DEFAULT_USER_ROLE
)
hashed = get_password_hash(form_data.password)
user = Auths.insert_new_auth(
@@ -173,13 +194,13 @@ async def signup(request: Request, form_data: SignupForm):
if user:
token = create_token(
data={"id": user.id},
expires_delta=parse_duration(request.app.state.JWT_EXPIRES_IN),
expires_delta=parse_duration(request.app.state.config.JWT_EXPIRES_IN),
)
# response.set_cookie(key='token', value=token, httponly=True)
if request.app.state.WEBHOOK_URL:
if request.app.state.config.WEBHOOK_URL:
post_webhook(
request.app.state.WEBHOOK_URL,
request.app.state.config.WEBHOOK_URL,
WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
{
"action": "signup",
@@ -203,6 +224,51 @@ async def signup(request: Request, form_data: SignupForm):
raise HTTPException(500, detail=ERROR_MESSAGES.DEFAULT(err))
############################
# AddUser
############################
@router.post("/add", response_model=SigninResponse)
async def add_user(form_data: AddUserForm, user=Depends(get_admin_user)):
if not validate_email_format(form_data.email.lower()):
raise HTTPException(
status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.INVALID_EMAIL_FORMAT
)
if Users.get_user_by_email(form_data.email.lower()):
raise HTTPException(400, detail=ERROR_MESSAGES.EMAIL_TAKEN)
try:
print(form_data)
hashed = get_password_hash(form_data.password)
user = Auths.insert_new_auth(
form_data.email.lower(),
hashed,
form_data.name,
form_data.profile_image_url,
form_data.role,
)
if user:
token = create_token(data={"id": user.id})
return {
"token": token,
"token_type": "Bearer",
"id": user.id,
"email": user.email,
"name": user.name,
"role": user.role,
"profile_image_url": user.profile_image_url,
}
else:
raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_USER_ERROR)
except Exception as err:
raise HTTPException(500, detail=ERROR_MESSAGES.DEFAULT(err))
############################
# ToggleSignUp
############################
@@ -210,13 +276,13 @@ async def signup(request: Request, form_data: SignupForm):
@router.get("/signup/enabled", response_model=bool)
async def get_sign_up_status(request: Request, user=Depends(get_admin_user)):
return request.app.state.ENABLE_SIGNUP
return request.app.state.config.ENABLE_SIGNUP
@router.get("/signup/enabled/toggle", response_model=bool)
async def toggle_sign_up(request: Request, user=Depends(get_admin_user)):
request.app.state.ENABLE_SIGNUP = not request.app.state.ENABLE_SIGNUP
return request.app.state.ENABLE_SIGNUP
request.app.state.config.ENABLE_SIGNUP = not request.app.state.config.ENABLE_SIGNUP
return request.app.state.config.ENABLE_SIGNUP
############################
@@ -226,7 +292,7 @@ async def toggle_sign_up(request: Request, user=Depends(get_admin_user)):
@router.get("/signup/user/role")
async def get_default_user_role(request: Request, user=Depends(get_admin_user)):
return request.app.state.DEFAULT_USER_ROLE
return request.app.state.config.DEFAULT_USER_ROLE
class UpdateRoleForm(BaseModel):
@@ -238,8 +304,8 @@ async def update_default_user_role(
request: Request, form_data: UpdateRoleForm, user=Depends(get_admin_user)
):
if form_data.role in ["pending", "user", "admin"]:
request.app.state.DEFAULT_USER_ROLE = form_data.role
return request.app.state.DEFAULT_USER_ROLE
request.app.state.config.DEFAULT_USER_ROLE = form_data.role
return request.app.state.config.DEFAULT_USER_ROLE
############################
@@ -249,7 +315,7 @@ async def update_default_user_role(
@router.get("/token/expires")
async def get_token_expires_duration(request: Request, user=Depends(get_admin_user)):
return request.app.state.JWT_EXPIRES_IN
return request.app.state.config.JWT_EXPIRES_IN
class UpdateJWTExpiresDurationForm(BaseModel):
@@ -266,10 +332,10 @@ async def update_token_expires_duration(
# Check if the input string matches the pattern
if re.match(pattern, form_data.duration):
request.app.state.JWT_EXPIRES_IN = form_data.duration
return request.app.state.JWT_EXPIRES_IN
request.app.state.config.JWT_EXPIRES_IN = form_data.duration
return request.app.state.config.JWT_EXPIRES_IN
else:
return request.app.state.JWT_EXPIRES_IN
return request.app.state.config.JWT_EXPIRES_IN
############################
+144 -86
View File
@@ -28,7 +28,7 @@ from apps.web.models.tags import (
from constants import ERROR_MESSAGES
from config import SRC_LOG_LEVELS
from config import SRC_LOG_LEVELS, ENABLE_ADMIN_EXPORT
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["MODELS"])
@@ -36,27 +36,98 @@ log.setLevel(SRC_LOG_LEVELS["MODELS"])
router = APIRouter()
############################
# GetChats
# GetChatList
############################
@router.get("/", response_model=List[ChatTitleIdResponse])
async def get_user_chats(
@router.get("/list", response_model=List[ChatTitleIdResponse])
async def get_session_user_chat_list(
user=Depends(get_current_user), skip: int = 0, limit: int = 50
):
return Chats.get_chat_lists_by_user_id(user.id, skip, limit)
return Chats.get_chat_list_by_user_id(user.id, skip, limit)
############################
# GetAllChats
# DeleteAllChats
############################
@router.delete("/", response_model=bool)
async def delete_all_user_chats(request: Request, user=Depends(get_current_user)):
if (
user.role == "user"
and not request.app.state.config.USER_PERMISSIONS["chat"]["deletion"]
):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
)
result = Chats.delete_chats_by_user_id(user.id)
return result
############################
# GetUserChatList
############################
@router.get("/list/user/{user_id}", response_model=List[ChatTitleIdResponse])
async def get_user_chat_list_by_user_id(
user_id: str, user=Depends(get_admin_user), skip: int = 0, limit: int = 50
):
return Chats.get_chat_list_by_user_id(user_id, skip, limit)
############################
# GetArchivedChats
############################
@router.get("/archived", response_model=List[ChatTitleIdResponse])
async def get_archived_session_user_chat_list(
user=Depends(get_current_user), skip: int = 0, limit: int = 50
):
return Chats.get_archived_chat_list_by_user_id(user.id, skip, limit)
############################
# GetSharedChatById
############################
@router.get("/share/{share_id}", response_model=Optional[ChatResponse])
async def get_shared_chat_by_id(share_id: str, user=Depends(get_current_user)):
if user.role == "pending":
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
)
if user.role == "user":
chat = Chats.get_chat_by_share_id(share_id)
elif user.role == "admin":
chat = Chats.get_chat_by_id(share_id)
if chat:
return ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)})
else:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
)
############################
# GetChats
############################
@router.get("/all", response_model=List[ChatResponse])
async def get_all_user_chats(user=Depends(get_current_user)):
async def get_user_chats(user=Depends(get_current_user)):
return [
ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)})
for chat in Chats.get_all_chats_by_user_id(user.id)
for chat in Chats.get_chats_by_user_id(user.id)
]
@@ -67,9 +138,14 @@ async def get_all_user_chats(user=Depends(get_current_user)):
@router.get("/all/db", response_model=List[ChatResponse])
async def get_all_user_chats_in_db(user=Depends(get_admin_user)):
if not ENABLE_ADMIN_EXPORT:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
)
return [
ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)})
for chat in Chats.get_all_chats()
for chat in Chats.get_chats()
]
@@ -90,6 +166,38 @@ async def create_new_chat(form_data: ChatForm, user=Depends(get_current_user)):
)
############################
# GetChatsByTags
############################
class TagNameForm(BaseModel):
name: str
skip: Optional[int] = 0
limit: Optional[int] = 50
@router.post("/tags", response_model=List[ChatTitleIdResponse])
async def get_user_chat_list_by_tag_name(
form_data: TagNameForm, user=Depends(get_current_user)
):
print(form_data)
chat_ids = [
chat_id_tag.chat_id
for chat_id_tag in Tags.get_chat_ids_by_tag_name_and_user_id(
form_data.name, user.id
)
]
chats = Chats.get_chat_list_by_chat_ids(chat_ids, form_data.skip, form_data.limit)
if len(chats) == 0:
Tags.delete_tag_by_tag_name_and_user_id(form_data.name, user.id)
return chats
############################
# GetAllTags
############################
@@ -107,28 +215,6 @@ async def get_all_tags(user=Depends(get_current_user)):
)
############################
# GetChatsByTags
############################
@router.get("/tags/tag/{tag_name}", response_model=List[ChatTitleIdResponse])
async def get_user_chats_by_tag_name(
tag_name: str, user=Depends(get_current_user), skip: int = 0, limit: int = 50
):
chat_ids = [
chat_id_tag.chat_id
for chat_id_tag in Tags.get_chat_ids_by_tag_name_and_user_id(tag_name, user.id)
]
chats = Chats.get_chat_lists_by_chat_ids(chat_ids, skip, limit)
if len(chats) == 0:
Tags.delete_tag_by_tag_name_and_user_id(tag_name, user.id)
return chats
############################
# GetChatById
############################
@@ -176,17 +262,35 @@ async def update_chat_by_id(
@router.delete("/{id}", response_model=bool)
async def delete_chat_by_id(request: Request, id: str, user=Depends(get_current_user)):
if (
user.role == "user"
and not request.app.state.USER_PERMISSIONS["chat"]["deletion"]
):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
)
if user.role == "admin":
result = Chats.delete_chat_by_id(id)
return result
else:
if not request.app.state.config.USER_PERMISSIONS["chat"]["deletion"]:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
)
result = Chats.delete_chat_by_id_and_user_id(id, user.id)
return result
result = Chats.delete_chat_by_id_and_user_id(id, user.id)
return result
############################
# ArchiveChat
############################
@router.get("/{id}/archive", response_model=Optional[ChatResponse])
async def archive_chat_by_id(id: str, user=Depends(get_current_user)):
chat = Chats.get_chat_by_id_and_user_id(id, user.id)
if chat:
chat = Chats.toggle_chat_archive_by_id(id)
return ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)})
else:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.DEFAULT()
)
############################
@@ -244,31 +348,6 @@ async def delete_shared_chat_by_id(id: str, user=Depends(get_current_user)):
)
############################
# GetSharedChatById
############################
@router.get("/share/{share_id}", response_model=Optional[ChatResponse])
async def get_shared_chat_by_id(share_id: str, user=Depends(get_current_user)):
if user.role == "pending":
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
)
if user.role == "user":
chat = Chats.get_chat_by_share_id(share_id)
elif user.role == "admin":
chat = Chats.get_chat_by_id(share_id)
if chat:
return ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)})
else:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
)
############################
# GetChatTagsById
############################
@@ -349,24 +428,3 @@ async def delete_all_chat_tags_by_id(id: str, user=Depends(get_current_user)):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, detail=ERROR_MESSAGES.NOT_FOUND
)
############################
# DeleteAllChats
############################
@router.delete("/", response_model=bool)
async def delete_all_user_chats(request: Request, user=Depends(get_current_user)):
if (
user.role == "user"
and not request.app.state.USER_PERMISSIONS["chat"]["deletion"]
):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
)
result = Chats.delete_chats_by_user_id(user.id)
return result
+4 -4
View File
@@ -44,8 +44,8 @@ class SetDefaultSuggestionsForm(BaseModel):
async def set_global_default_models(
request: Request, form_data: SetDefaultModelsForm, user=Depends(get_admin_user)
):
request.app.state.DEFAULT_MODELS = form_data.models
return request.app.state.DEFAULT_MODELS
request.app.state.config.DEFAULT_MODELS = form_data.models
return request.app.state.config.DEFAULT_MODELS
@router.post("/default/suggestions", response_model=List[PromptSuggestion])
@@ -55,5 +55,5 @@ async def set_global_default_suggestions(
user=Depends(get_admin_user),
):
data = form_data.model_dump()
request.app.state.DEFAULT_PROMPT_SUGGESTIONS = data["suggestions"]
return request.app.state.DEFAULT_PROMPT_SUGGESTIONS
request.app.state.config.DEFAULT_PROMPT_SUGGESTIONS = data["suggestions"]
return request.app.state.config.DEFAULT_PROMPT_SUGGESTIONS
+145
View File
@@ -0,0 +1,145 @@
from fastapi import Response, Request
from fastapi import Depends, FastAPI, HTTPException, status
from datetime import datetime, timedelta
from typing import List, Union, Optional
from fastapi import APIRouter
from pydantic import BaseModel
import logging
from apps.web.models.memories import Memories, MemoryModel
from utils.utils import get_verified_user
from constants import ERROR_MESSAGES
from config import SRC_LOG_LEVELS, CHROMA_CLIENT
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["MODELS"])
router = APIRouter()
@router.get("/ef")
async def get_embeddings(request: Request):
return {"result": request.app.state.EMBEDDING_FUNCTION("hello world")}
############################
# GetMemories
############################
@router.get("/", response_model=List[MemoryModel])
async def get_memories(user=Depends(get_verified_user)):
return Memories.get_memories_by_user_id(user.id)
############################
# AddMemory
############################
class AddMemoryForm(BaseModel):
content: str
@router.post("/add", response_model=Optional[MemoryModel])
async def add_memory(
request: Request, form_data: AddMemoryForm, user=Depends(get_verified_user)
):
memory = Memories.insert_new_memory(user.id, form_data.content)
memory_embedding = request.app.state.EMBEDDING_FUNCTION(memory.content)
collection = CHROMA_CLIENT.get_or_create_collection(name=f"user-memory-{user.id}")
collection.upsert(
documents=[memory.content],
ids=[memory.id],
embeddings=[memory_embedding],
metadatas=[{"created_at": memory.created_at}],
)
return memory
############################
# QueryMemory
############################
class QueryMemoryForm(BaseModel):
content: str
@router.post("/query")
async def query_memory(
request: Request, form_data: QueryMemoryForm, user=Depends(get_verified_user)
):
query_embedding = request.app.state.EMBEDDING_FUNCTION(form_data.content)
collection = CHROMA_CLIENT.get_or_create_collection(name=f"user-memory-{user.id}")
results = collection.query(
query_embeddings=[query_embedding],
n_results=1, # how many results to return
)
return results
############################
# ResetMemoryFromVectorDB
############################
@router.get("/reset", response_model=bool)
async def reset_memory_from_vector_db(
request: Request, user=Depends(get_verified_user)
):
CHROMA_CLIENT.delete_collection(f"user-memory-{user.id}")
collection = CHROMA_CLIENT.get_or_create_collection(name=f"user-memory-{user.id}")
memories = Memories.get_memories_by_user_id(user.id)
for memory in memories:
memory_embedding = request.app.state.EMBEDDING_FUNCTION(memory.content)
collection.upsert(
documents=[memory.content],
ids=[memory.id],
embeddings=[memory_embedding],
)
return True
############################
# DeleteMemoriesByUserId
############################
@router.delete("/user", response_model=bool)
async def delete_memory_by_user_id(user=Depends(get_verified_user)):
result = Memories.delete_memories_by_user_id(user.id)
if result:
try:
CHROMA_CLIENT.delete_collection(f"user-memory-{user.id}")
except Exception as e:
log.error(e)
return True
return False
############################
# DeleteMemoryById
############################
@router.delete("/{memory_id}", response_model=bool)
async def delete_memory_by_id(memory_id: str, user=Depends(get_verified_user)):
result = Memories.delete_memory_by_id_and_user_id(memory_id, user.id)
if result:
collection = CHROMA_CLIENT.get_or_create_collection(
name=f"user-memory-{user.id}"
)
collection.delete(ids=[memory_id])
return True
return False
+41 -5
View File
@@ -11,8 +11,9 @@ import logging
from apps.web.models.users import UserModel, UserUpdateForm, UserRoleUpdateForm, Users
from apps.web.models.auths import Auths
from apps.web.models.chats import Chats
from utils.utils import get_current_user, get_password_hash, get_admin_user
from utils.utils import get_verified_user, get_password_hash, get_admin_user
from constants import ERROR_MESSAGES
from config import SRC_LOG_LEVELS
@@ -39,15 +40,15 @@ async def get_users(skip: int = 0, limit: int = 50, user=Depends(get_admin_user)
@router.get("/permissions/user")
async def get_user_permissions(request: Request, user=Depends(get_admin_user)):
return request.app.state.USER_PERMISSIONS
return request.app.state.config.USER_PERMISSIONS
@router.post("/permissions/user")
async def update_user_permissions(
request: Request, form_data: dict, user=Depends(get_admin_user)
):
request.app.state.USER_PERMISSIONS = form_data
return request.app.state.USER_PERMISSIONS
request.app.state.config.USER_PERMISSIONS = form_data
return request.app.state.config.USER_PERMISSIONS
############################
@@ -58,7 +59,7 @@ async def update_user_permissions(
@router.post("/update/role", response_model=Optional[UserModel])
async def update_user_role(form_data: UserRoleUpdateForm, user=Depends(get_admin_user)):
if user.id != form_data.id:
if user.id != form_data.id and form_data.id != Users.get_first_user().id:
return Users.update_user_role_by_id(form_data.id, form_data.role)
raise HTTPException(
@@ -67,6 +68,41 @@ async def update_user_role(form_data: UserRoleUpdateForm, user=Depends(get_admin
)
############################
# GetUserById
############################
class UserResponse(BaseModel):
name: str
profile_image_url: str
@router.get("/{user_id}", response_model=UserResponse)
async def get_user_by_id(user_id: str, user=Depends(get_verified_user)):
if user_id.startswith("shared-"):
chat_id = user_id.replace("shared-", "")
chat = Chats.get_chat_by_id(chat_id)
if chat:
user_id = chat.user_id
else:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=ERROR_MESSAGES.USER_NOT_FOUND,
)
user = Users.get_user_by_id(user_id)
if user:
return UserResponse(name=user.name, profile_image_url=user.profile_image_url)
else:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=ERROR_MESSAGES.USER_NOT_FOUND,
)
############################
# UpdateUserById
############################
+14 -4
View File
@@ -1,5 +1,6 @@
from fastapi import APIRouter, UploadFile, File, Response
from fastapi import Depends, HTTPException, status
from peewee import SqliteDatabase
from starlette.responses import StreamingResponse, FileResponse
from pydantic import BaseModel
@@ -7,11 +8,11 @@ from pydantic import BaseModel
from fpdf import FPDF
import markdown
from apps.web.internal.db import DB
from utils.utils import get_admin_user
from utils.misc import calculate_sha256, get_gravatar_url
from config import OLLAMA_BASE_URLS, DATA_DIR, UPLOAD_DIR
from config import OLLAMA_BASE_URLS, DATA_DIR, UPLOAD_DIR, ENABLE_ADMIN_EXPORT
from constants import ERROR_MESSAGES
from typing import List
@@ -91,9 +92,18 @@ async def download_chat_as_pdf(
@router.get("/db/download")
async def download_db(user=Depends(get_admin_user)):
if not ENABLE_ADMIN_EXPORT:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
)
if not isinstance(DB, SqliteDatabase):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=ERROR_MESSAGES.DB_NOT_SQLITE,
)
return FileResponse(
f"{DATA_DIR}/webui.db",
DB.database,
media_type="application/octet-stream",
filename="webui.db",
)
+474 -97
View File
@@ -5,6 +5,7 @@ import chromadb
from chromadb import Settings
from base64 import b64encode
from bs4 import BeautifulSoup
from typing import TypeVar, Generic, Union
from pathlib import Path
import json
@@ -17,17 +18,68 @@ import shutil
from secrets import token_bytes
from constants import ERROR_MESSAGES
####################################
# Load .env file
####################################
try:
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv("../.env"))
except ImportError:
log.warning("dotenv not installed, skipping...")
print("dotenv not installed, skipping...")
####################################
# LOGGING
####################################
log_levels = ["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"]
GLOBAL_LOG_LEVEL = os.environ.get("GLOBAL_LOG_LEVEL", "").upper()
if GLOBAL_LOG_LEVEL in log_levels:
logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL, force=True)
else:
GLOBAL_LOG_LEVEL = "INFO"
log = logging.getLogger(__name__)
log.info(f"GLOBAL_LOG_LEVEL: {GLOBAL_LOG_LEVEL}")
log_sources = [
"AUDIO",
"COMFYUI",
"CONFIG",
"DB",
"IMAGES",
"LITELLM",
"MAIN",
"MODELS",
"OLLAMA",
"OPENAI",
"RAG",
"WEBHOOK",
]
SRC_LOG_LEVELS = {}
for source in log_sources:
log_env_var = source + "_LOG_LEVEL"
SRC_LOG_LEVELS[source] = os.environ.get(log_env_var, "").upper()
if SRC_LOG_LEVELS[source] not in log_levels:
SRC_LOG_LEVELS[source] = GLOBAL_LOG_LEVEL
log.info(f"{log_env_var}: {SRC_LOG_LEVELS[source]}")
log.setLevel(SRC_LOG_LEVELS["CONFIG"])
WEBUI_NAME = os.environ.get("WEBUI_NAME", "Open WebUI")
if WEBUI_NAME != "Open WebUI":
WEBUI_NAME += " (Open WebUI)"
WEBUI_URL = os.environ.get("WEBUI_URL", "http://localhost:3000")
WEBUI_FAVICON_URL = "https://openwebui.com/favicon.png"
####################################
# ENV (dev,test,prod)
####################################
@@ -101,6 +153,13 @@ for version in soup.find_all("h2"):
CHANGELOG = changelog_json
####################################
# WEBUI_VERSION
####################################
WEBUI_VERSION = os.environ.get("WEBUI_VERSION", "v1.0.0-alpha.100")
####################################
# DATA/FRONTEND BUILD DIR
####################################
@@ -114,54 +173,119 @@ try:
except:
CONFIG_DATA = {}
####################################
# Config helpers
####################################
def save_config():
try:
with open(f"{DATA_DIR}/config.json", "w") as f:
json.dump(CONFIG_DATA, f, indent="\t")
except Exception as e:
log.exception(e)
def get_config_value(config_path: str):
path_parts = config_path.split(".")
cur_config = CONFIG_DATA
for key in path_parts:
if key in cur_config:
cur_config = cur_config[key]
else:
return None
return cur_config
T = TypeVar("T")
class PersistentConfig(Generic[T]):
def __init__(self, env_name: str, config_path: str, env_value: T):
self.env_name = env_name
self.config_path = config_path
self.env_value = env_value
self.config_value = get_config_value(config_path)
if self.config_value is not None:
log.info(f"'{env_name}' loaded from config.json")
self.value = self.config_value
else:
self.value = env_value
def __str__(self):
return str(self.value)
@property
def __dict__(self):
raise TypeError(
"PersistentConfig object cannot be converted to dict, use config_get or .value instead."
)
def __getattribute__(self, item):
if item == "__dict__":
raise TypeError(
"PersistentConfig object cannot be converted to dict, use config_get or .value instead."
)
return super().__getattribute__(item)
def save(self):
# Don't save if the value is the same as the env value and the config value
if self.env_value == self.value:
if self.config_value == self.value:
return
log.info(f"Saving '{self.env_name}' to config.json")
path_parts = self.config_path.split(".")
config = CONFIG_DATA
for key in path_parts[:-1]:
if key not in config:
config[key] = {}
config = config[key]
config[path_parts[-1]] = self.value
save_config()
self.config_value = self.value
class AppConfig:
_state: dict[str, PersistentConfig]
def __init__(self):
super().__setattr__("_state", {})
def __setattr__(self, key, value):
if isinstance(value, PersistentConfig):
self._state[key] = value
else:
self._state[key].value = value
self._state[key].save()
def __getattr__(self, key):
return self._state[key].value
####################################
# WEBUI_AUTH (Required for security)
####################################
WEBUI_AUTH = os.environ.get("WEBUI_AUTH", "True").lower() == "true"
WEBUI_AUTH_TRUSTED_EMAIL_HEADER = os.environ.get(
"WEBUI_AUTH_TRUSTED_EMAIL_HEADER", None
)
JWT_EXPIRES_IN = PersistentConfig(
"JWT_EXPIRES_IN", "auth.jwt_expiry", os.environ.get("JWT_EXPIRES_IN", "-1")
)
####################################
# Static DIR
####################################
STATIC_DIR = str(Path(os.getenv("STATIC_DIR", "./static")).resolve())
shutil.copyfile(f"{FRONTEND_BUILD_DIR}/favicon.png", f"{STATIC_DIR}/favicon.png")
####################################
# LOGGING
####################################
log_levels = ["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"]
GLOBAL_LOG_LEVEL = os.environ.get("GLOBAL_LOG_LEVEL", "").upper()
if GLOBAL_LOG_LEVEL in log_levels:
logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL, force=True)
frontend_favicon = f"{FRONTEND_BUILD_DIR}/favicon.png"
if os.path.exists(frontend_favicon):
shutil.copyfile(frontend_favicon, f"{STATIC_DIR}/favicon.png")
else:
GLOBAL_LOG_LEVEL = "INFO"
log = logging.getLogger(__name__)
log.info(f"GLOBAL_LOG_LEVEL: {GLOBAL_LOG_LEVEL}")
log_sources = [
"AUDIO",
"COMFYUI",
"CONFIG",
"DB",
"IMAGES",
"LITELLM",
"MAIN",
"MODELS",
"OLLAMA",
"OPENAI",
"RAG",
"WEBHOOK",
]
SRC_LOG_LEVELS = {}
for source in log_sources:
log_env_var = source + "_LOG_LEVEL"
SRC_LOG_LEVELS[source] = os.environ.get(log_env_var, "").upper()
if SRC_LOG_LEVELS[source] not in log_levels:
SRC_LOG_LEVELS[source] = GLOBAL_LOG_LEVEL
log.info(f"{log_env_var}: {SRC_LOG_LEVELS[source]}")
log.setLevel(SRC_LOG_LEVELS["CONFIG"])
logging.warning(f"Frontend favicon not found at {frontend_favicon}")
####################################
# CUSTOM_NAME
@@ -191,9 +315,6 @@ if CUSTOM_NAME:
except Exception as e:
log.exception(e)
pass
else:
if WEBUI_NAME != "Open WebUI":
WEBUI_NAME += " (Open WebUI)"
####################################
@@ -216,7 +337,7 @@ Path(CACHE_DIR).mkdir(parents=True, exist_ok=True)
# Docs DIR
####################################
DOCS_DIR = f"{DATA_DIR}/docs"
DOCS_DIR = os.getenv("DOCS_DIR", f"{DATA_DIR}/docs")
Path(DOCS_DIR).mkdir(parents=True, exist_ok=True)
@@ -288,12 +409,22 @@ OLLAMA_BASE_URLS = os.environ.get("OLLAMA_BASE_URLS", "")
OLLAMA_BASE_URLS = OLLAMA_BASE_URLS if OLLAMA_BASE_URLS != "" else OLLAMA_BASE_URL
OLLAMA_BASE_URLS = [url.strip() for url in OLLAMA_BASE_URLS.split(";")]
OLLAMA_BASE_URLS = PersistentConfig(
"OLLAMA_BASE_URLS", "ollama.base_urls", OLLAMA_BASE_URLS
)
####################################
# OPENAI_API
####################################
ENABLE_OPENAI_API = PersistentConfig(
"ENABLE_OPENAI_API",
"openai.enable",
os.environ.get("ENABLE_OPENAI_API", "True").lower() == "true",
)
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "")
OPENAI_API_BASE_URL = os.environ.get("OPENAI_API_BASE_URL", "")
@@ -305,7 +436,9 @@ OPENAI_API_KEYS = os.environ.get("OPENAI_API_KEYS", "")
OPENAI_API_KEYS = OPENAI_API_KEYS if OPENAI_API_KEYS != "" else OPENAI_API_KEY
OPENAI_API_KEYS = [url.strip() for url in OPENAI_API_KEYS.split(";")]
OPENAI_API_KEYS = PersistentConfig(
"OPENAI_API_KEYS", "openai.api_keys", OPENAI_API_KEYS
)
OPENAI_API_BASE_URLS = os.environ.get("OPENAI_API_BASE_URLS", "")
OPENAI_API_BASE_URLS = (
@@ -316,21 +449,42 @@ OPENAI_API_BASE_URLS = [
url.strip() if url != "" else "https://api.openai.com/v1"
for url in OPENAI_API_BASE_URLS.split(";")
]
OPENAI_API_BASE_URLS = PersistentConfig(
"OPENAI_API_BASE_URLS", "openai.api_base_urls", OPENAI_API_BASE_URLS
)
OPENAI_API_KEY = ""
try:
OPENAI_API_KEY = OPENAI_API_KEYS.value[
OPENAI_API_BASE_URLS.value.index("https://api.openai.com/v1")
]
except:
pass
OPENAI_API_BASE_URL = "https://api.openai.com/v1"
####################################
# WEBUI
####################################
ENABLE_SIGNUP = os.environ.get("ENABLE_SIGNUP", "True").lower() == "true"
DEFAULT_MODELS = os.environ.get("DEFAULT_MODELS", None)
ENABLE_SIGNUP = PersistentConfig(
"ENABLE_SIGNUP",
"ui.enable_signup",
(
False
if not WEBUI_AUTH
else os.environ.get("ENABLE_SIGNUP", "True").lower() == "true"
),
)
DEFAULT_MODELS = PersistentConfig(
"DEFAULT_MODELS", "ui.default_models", os.environ.get("DEFAULT_MODELS", None)
)
DEFAULT_PROMPT_SUGGESTIONS = (
CONFIG_DATA["ui"]["prompt_suggestions"]
if "ui" in CONFIG_DATA
and "prompt_suggestions" in CONFIG_DATA["ui"]
and type(CONFIG_DATA["ui"]["prompt_suggestions"]) is list
else [
DEFAULT_PROMPT_SUGGESTIONS = PersistentConfig(
"DEFAULT_PROMPT_SUGGESTIONS",
"ui.prompt_suggestions",
[
{
"title": ["Help me study", "vocabulary for a college entrance exam"],
"content": "Help me study vocabulary: write a sentence for me to fill in the blank, and I'll try to pick the correct option.",
@@ -347,40 +501,54 @@ DEFAULT_PROMPT_SUGGESTIONS = (
"title": ["Show me a code snippet", "of a website's sticky header"],
"content": "Show me a code snippet of a website's sticky header in CSS and JavaScript.",
},
]
{
"title": [
"Explain options trading",
"if I'm familiar with buying and selling stocks",
],
"content": "Explain options trading in simple terms if I'm familiar with buying and selling stocks.",
},
{
"title": ["Overcome procrastination", "give me tips"],
"content": "Could you start by asking me about instances when I procrastinate the most and then give me some suggestions to overcome it?",
},
],
)
DEFAULT_USER_ROLE = os.getenv("DEFAULT_USER_ROLE", "pending")
DEFAULT_USER_ROLE = PersistentConfig(
"DEFAULT_USER_ROLE",
"ui.default_user_role",
os.getenv("DEFAULT_USER_ROLE", "pending"),
)
USER_PERMISSIONS_CHAT_DELETION = (
os.environ.get("USER_PERMISSIONS_CHAT_DELETION", "True").lower() == "true"
)
USER_PERMISSIONS = {"chat": {"deletion": USER_PERMISSIONS_CHAT_DELETION}}
MODEL_FILTER_ENABLED = os.environ.get("MODEL_FILTER_ENABLED", "False").lower() == "true"
MODEL_FILTER_LIST = os.environ.get("MODEL_FILTER_LIST", "")
MODEL_FILTER_LIST = [model.strip() for model in MODEL_FILTER_LIST.split(";")]
WEBHOOK_URL = os.environ.get("WEBHOOK_URL", "")
####################################
# WEBUI_VERSION
####################################
WEBUI_VERSION = os.environ.get("WEBUI_VERSION", "v1.0.0-alpha.100")
####################################
# WEBUI_AUTH (Required for security)
####################################
WEBUI_AUTH = True
WEBUI_AUTH_TRUSTED_EMAIL_HEADER = os.environ.get(
"WEBUI_AUTH_TRUSTED_EMAIL_HEADER", None
USER_PERMISSIONS = PersistentConfig(
"USER_PERMISSIONS",
"ui.user_permissions",
{"chat": {"deletion": USER_PERMISSIONS_CHAT_DELETION}},
)
ENABLE_MODEL_FILTER = PersistentConfig(
"ENABLE_MODEL_FILTER",
"model_filter.enable",
os.environ.get("ENABLE_MODEL_FILTER", "False").lower() == "true",
)
MODEL_FILTER_LIST = os.environ.get("MODEL_FILTER_LIST", "")
MODEL_FILTER_LIST = PersistentConfig(
"MODEL_FILTER_LIST",
"model_filter.list",
[model.strip() for model in MODEL_FILTER_LIST.split(";")],
)
WEBHOOK_URL = PersistentConfig(
"WEBHOOK_URL", "webhook_url", os.environ.get("WEBHOOK_URL", "")
)
ENABLE_ADMIN_EXPORT = os.environ.get("ENABLE_ADMIN_EXPORT", "True").lower() == "true"
####################################
# WEBUI_SECRET_KEY
####################################
@@ -400,16 +568,106 @@ if WEBUI_AUTH and WEBUI_SECRET_KEY == "":
####################################
CHROMA_DATA_PATH = f"{DATA_DIR}/vector_db"
# this uses the model defined in the Dockerfile ENV variable. If you dont use docker or docker based deployments such as k8s, the default embedding model will be used (all-MiniLM-L6-v2)
RAG_EMBEDDING_MODEL = os.environ.get("RAG_EMBEDDING_MODEL", "all-MiniLM-L6-v2")
log.info(f"Embedding model set: {RAG_EMBEDDING_MODEL}"),
CHROMA_TENANT = os.environ.get("CHROMA_TENANT", chromadb.DEFAULT_TENANT)
CHROMA_DATABASE = os.environ.get("CHROMA_DATABASE", chromadb.DEFAULT_DATABASE)
CHROMA_HTTP_HOST = os.environ.get("CHROMA_HTTP_HOST", "")
CHROMA_HTTP_PORT = int(os.environ.get("CHROMA_HTTP_PORT", "8000"))
# Comma-separated list of header=value pairs
CHROMA_HTTP_HEADERS = os.environ.get("CHROMA_HTTP_HEADERS", "")
if CHROMA_HTTP_HEADERS:
CHROMA_HTTP_HEADERS = dict(
[pair.split("=") for pair in CHROMA_HTTP_HEADERS.split(",")]
)
else:
CHROMA_HTTP_HEADERS = None
CHROMA_HTTP_SSL = os.environ.get("CHROMA_HTTP_SSL", "false").lower() == "true"
# this uses the model defined in the Dockerfile ENV variable. If you dont use docker or docker based deployments such as k8s, the default embedding model will be used (sentence-transformers/all-MiniLM-L6-v2)
RAG_TOP_K = PersistentConfig(
"RAG_TOP_K", "rag.top_k", int(os.environ.get("RAG_TOP_K", "5"))
)
RAG_RELEVANCE_THRESHOLD = PersistentConfig(
"RAG_RELEVANCE_THRESHOLD",
"rag.relevance_threshold",
float(os.environ.get("RAG_RELEVANCE_THRESHOLD", "0.0")),
)
ENABLE_RAG_HYBRID_SEARCH = PersistentConfig(
"ENABLE_RAG_HYBRID_SEARCH",
"rag.enable_hybrid_search",
os.environ.get("ENABLE_RAG_HYBRID_SEARCH", "").lower() == "true",
)
ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION = PersistentConfig(
"ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION",
"rag.enable_web_loader_ssl_verification",
os.environ.get("ENABLE_RAG_WEB_LOADER_SSL_VERIFICATION", "True").lower() == "true",
)
RAG_EMBEDDING_ENGINE = PersistentConfig(
"RAG_EMBEDDING_ENGINE",
"rag.embedding_engine",
os.environ.get("RAG_EMBEDDING_ENGINE", ""),
)
PDF_EXTRACT_IMAGES = PersistentConfig(
"PDF_EXTRACT_IMAGES",
"rag.pdf_extract_images",
os.environ.get("PDF_EXTRACT_IMAGES", "False").lower() == "true",
)
RAG_EMBEDDING_MODEL = PersistentConfig(
"RAG_EMBEDDING_MODEL",
"rag.embedding_model",
os.environ.get("RAG_EMBEDDING_MODEL", "sentence-transformers/all-MiniLM-L6-v2"),
)
log.info(f"Embedding model set: {RAG_EMBEDDING_MODEL.value}"),
RAG_EMBEDDING_MODEL_AUTO_UPDATE = (
os.environ.get("RAG_EMBEDDING_MODEL_AUTO_UPDATE", "").lower() == "true"
)
RAG_EMBEDDING_MODEL_TRUST_REMOTE_CODE = (
os.environ.get("RAG_EMBEDDING_MODEL_TRUST_REMOTE_CODE", "").lower() == "true"
)
# device type ebbeding models - "cpu" (default), "cuda" (nvidia gpu required) or "mps" (apple silicon) - choosing this right can lead to better performance
RAG_RERANKING_MODEL = PersistentConfig(
"RAG_RERANKING_MODEL",
"rag.reranking_model",
os.environ.get("RAG_RERANKING_MODEL", ""),
)
if RAG_RERANKING_MODEL.value != "":
log.info(f"Reranking model set: {RAG_RERANKING_MODEL.value}"),
RAG_RERANKING_MODEL_AUTO_UPDATE = (
os.environ.get("RAG_RERANKING_MODEL_AUTO_UPDATE", "").lower() == "true"
)
RAG_RERANKING_MODEL_TRUST_REMOTE_CODE = (
os.environ.get("RAG_RERANKING_MODEL_TRUST_REMOTE_CODE", "").lower() == "true"
)
if CHROMA_HTTP_HOST != "":
CHROMA_CLIENT = chromadb.HttpClient(
host=CHROMA_HTTP_HOST,
port=CHROMA_HTTP_PORT,
headers=CHROMA_HTTP_HEADERS,
ssl=CHROMA_HTTP_SSL,
tenant=CHROMA_TENANT,
database=CHROMA_DATABASE,
settings=Settings(allow_reset=True, anonymized_telemetry=False),
)
else:
CHROMA_CLIENT = chromadb.PersistentClient(
path=CHROMA_DATA_PATH,
settings=Settings(allow_reset=True, anonymized_telemetry=False),
tenant=CHROMA_TENANT,
database=CHROMA_DATABASE,
)
# device type embedding models - "cpu" (default), "cuda" (nvidia gpu required) or "mps" (apple silicon) - choosing this right can lead to better performance
USE_CUDA = os.environ.get("USE_CUDA_DOCKER", "false")
if USE_CUDA.lower() == "true":
@@ -417,16 +675,16 @@ if USE_CUDA.lower() == "true":
else:
DEVICE_TYPE = "cpu"
CHROMA_CLIENT = chromadb.PersistentClient(
path=CHROMA_DATA_PATH,
settings=Settings(allow_reset=True, anonymized_telemetry=False),
CHUNK_SIZE = PersistentConfig(
"CHUNK_SIZE", "rag.chunk_size", int(os.environ.get("CHUNK_SIZE", "1500"))
)
CHUNK_OVERLAP = PersistentConfig(
"CHUNK_OVERLAP",
"rag.chunk_overlap",
int(os.environ.get("CHUNK_OVERLAP", "100")),
)
CHUNK_SIZE = 1500
CHUNK_OVERLAP = 100
RAG_TEMPLATE = """Use the following context as your learned knowledge, inside <context></context> XML tags.
DEFAULT_RAG_TEMPLATE = """Use the following context as your learned knowledge, inside <context></context> XML tags.
<context>
[context]
</context>
@@ -436,21 +694,140 @@ When answer to user:
- If you don't know when you are not sure, ask for clarification.
Avoid mentioning that you obtained the information from the context.
And answer according to the language of the user's question.
Given the context information, answer the query.
Query: [query]"""
RAG_TEMPLATE = PersistentConfig(
"RAG_TEMPLATE",
"rag.template",
os.environ.get("RAG_TEMPLATE", DEFAULT_RAG_TEMPLATE),
)
RAG_OPENAI_API_BASE_URL = PersistentConfig(
"RAG_OPENAI_API_BASE_URL",
"rag.openai_api_base_url",
os.getenv("RAG_OPENAI_API_BASE_URL", OPENAI_API_BASE_URL),
)
RAG_OPENAI_API_KEY = PersistentConfig(
"RAG_OPENAI_API_KEY",
"rag.openai_api_key",
os.getenv("RAG_OPENAI_API_KEY", OPENAI_API_KEY),
)
ENABLE_RAG_LOCAL_WEB_FETCH = (
os.getenv("ENABLE_RAG_LOCAL_WEB_FETCH", "False").lower() == "true"
)
YOUTUBE_LOADER_LANGUAGE = PersistentConfig(
"YOUTUBE_LOADER_LANGUAGE",
"rag.youtube_loader_language",
os.getenv("YOUTUBE_LOADER_LANGUAGE", "en").split(","),
)
####################################
# Transcribe
####################################
WHISPER_MODEL = os.getenv("WHISPER_MODEL", "base")
WHISPER_MODEL_DIR = os.getenv("WHISPER_MODEL_DIR", f"{CACHE_DIR}/whisper/models")
WHISPER_MODEL_AUTO_UPDATE = (
os.environ.get("WHISPER_MODEL_AUTO_UPDATE", "").lower() == "true"
)
####################################
# Images
####################################
AUTOMATIC1111_BASE_URL = os.getenv("AUTOMATIC1111_BASE_URL", "")
COMFYUI_BASE_URL = os.getenv("COMFYUI_BASE_URL", "")
IMAGE_GENERATION_ENGINE = PersistentConfig(
"IMAGE_GENERATION_ENGINE",
"image_generation.engine",
os.getenv("IMAGE_GENERATION_ENGINE", ""),
)
ENABLE_IMAGE_GENERATION = PersistentConfig(
"ENABLE_IMAGE_GENERATION",
"image_generation.enable",
os.environ.get("ENABLE_IMAGE_GENERATION", "").lower() == "true",
)
AUTOMATIC1111_BASE_URL = PersistentConfig(
"AUTOMATIC1111_BASE_URL",
"image_generation.automatic1111.base_url",
os.getenv("AUTOMATIC1111_BASE_URL", ""),
)
COMFYUI_BASE_URL = PersistentConfig(
"COMFYUI_BASE_URL",
"image_generation.comfyui.base_url",
os.getenv("COMFYUI_BASE_URL", ""),
)
IMAGES_OPENAI_API_BASE_URL = PersistentConfig(
"IMAGES_OPENAI_API_BASE_URL",
"image_generation.openai.api_base_url",
os.getenv("IMAGES_OPENAI_API_BASE_URL", OPENAI_API_BASE_URL),
)
IMAGES_OPENAI_API_KEY = PersistentConfig(
"IMAGES_OPENAI_API_KEY",
"image_generation.openai.api_key",
os.getenv("IMAGES_OPENAI_API_KEY", OPENAI_API_KEY),
)
IMAGE_SIZE = PersistentConfig(
"IMAGE_SIZE", "image_generation.size", os.getenv("IMAGE_SIZE", "512x512")
)
IMAGE_STEPS = PersistentConfig(
"IMAGE_STEPS", "image_generation.steps", int(os.getenv("IMAGE_STEPS", 50))
)
IMAGE_GENERATION_MODEL = PersistentConfig(
"IMAGE_GENERATION_MODEL",
"image_generation.model",
os.getenv("IMAGE_GENERATION_MODEL", ""),
)
####################################
# Audio
####################################
AUDIO_OPENAI_API_BASE_URL = PersistentConfig(
"AUDIO_OPENAI_API_BASE_URL",
"audio.openai.api_base_url",
os.getenv("AUDIO_OPENAI_API_BASE_URL", OPENAI_API_BASE_URL),
)
AUDIO_OPENAI_API_KEY = PersistentConfig(
"AUDIO_OPENAI_API_KEY",
"audio.openai.api_key",
os.getenv("AUDIO_OPENAI_API_KEY", OPENAI_API_KEY),
)
AUDIO_OPENAI_API_MODEL = PersistentConfig(
"AUDIO_OPENAI_API_MODEL",
"audio.openai.api_model",
os.getenv("AUDIO_OPENAI_API_MODEL", "tts-1"),
)
AUDIO_OPENAI_API_VOICE = PersistentConfig(
"AUDIO_OPENAI_API_VOICE",
"audio.openai.api_voice",
os.getenv("AUDIO_OPENAI_API_VOICE", "alloy"),
)
####################################
# LiteLLM
####################################
ENABLE_LITELLM = os.environ.get("ENABLE_LITELLM", "True").lower() == "true"
LITELLM_PROXY_PORT = int(os.getenv("LITELLM_PROXY_PORT", "14365"))
if LITELLM_PROXY_PORT < 0 or LITELLM_PROXY_PORT > 65535:
raise ValueError("Invalid port number for LITELLM_PROXY_PORT")
LITELLM_PROXY_HOST = os.getenv("LITELLM_PROXY_HOST", "127.0.0.1")
####################################
# Database
####################################
DATABASE_URL = os.environ.get("DATABASE_URL", f"sqlite:///{DATA_DIR}/webui.db")
+13
View File
@@ -3,6 +3,10 @@ from enum import Enum
class MESSAGES(str, Enum):
DEFAULT = lambda msg="": f"{msg if msg else ''}"
MODEL_ADDED = lambda model="": f"The model '{model}' has been added successfully."
MODEL_DELETED = (
lambda model="": f"The model '{model}' has been deleted successfully."
)
class WEBHOOK_MESSAGES(str, Enum):
@@ -38,6 +42,9 @@ class ERROR_MESSAGES(str, Enum):
"The password provided is incorrect. Please check for typos and try again."
)
INVALID_TRUSTED_HEADER = "Your provider has not provided a trusted header. Please contact your administrator for assistance."
EXISTING_USERS = "You can't turn off authentication because there are existing users. If you want to disable WEBUI_AUTH, make sure your web interface doesn't have any existing users and is a fresh installation."
UNAUTHORIZED = "401 Unauthorized"
ACCESS_PROHIBITED = "You do not have permission to access this resource. Please contact your administrator for assistance."
ACTION_PROHIBITED = (
@@ -65,3 +72,9 @@ class ERROR_MESSAGES(str, Enum):
CREATE_API_KEY_ERROR = "Oops! Something went wrong while creating your API key. Please try again later. If the issue persists, contact support for assistance."
EMPTY_CONTENT = "The content provided is empty. Please ensure that there is text or data present before proceeding."
DB_NOT_SQLITE = "This feature is only available when running with SQLite databases."
INVALID_URL = (
"Oops! The URL you provided is invalid. Please double-check and try again."
)
+12
View File
@@ -18,6 +18,18 @@
{
"title": ["Show me a code snippet", "of a website's sticky header"],
"content": "Show me a code snippet of a website's sticky header in CSS and JavaScript."
},
{
"title": ["Explain options trading", "if I'm familiar with buying and selling stocks"],
"content": "Explain options trading in simple terms if I'm familiar with buying and selling stocks."
},
{
"title": ["Overcome procrastination", "give me tips"],
"content": "Could you start by asking me about instances when I procrastinate the most and then give me some suggestions to overcome it?"
},
{
"title": ["Grammar check", "rewrite it for better readability "],
"content": "Check the following sentence for grammar and clarity: \"[sentence]\". Rewrite it for better readability while maintaining its original meaning."
}
]
}
Regular → Executable
View File
+151 -45
View File
@@ -1,3 +1,4 @@
from contextlib import asynccontextmanager
from bs4 import BeautifulSoup
import json
import markdown
@@ -15,17 +16,24 @@ from fastapi.middleware.wsgi import WSGIMiddleware
from fastapi.middleware.cors import CORSMiddleware
from starlette.exceptions import HTTPException as StarletteHTTPException
from starlette.middleware.base import BaseHTTPMiddleware
from starlette.responses import StreamingResponse, Response
from apps.ollama.main import app as ollama_app
from apps.openai.main import app as openai_app
from apps.litellm.main import app as litellm_app, startup as litellm_app_startup
from apps.litellm.main import (
app as litellm_app,
start_litellm_background,
shutdown_litellm_background,
)
from apps.audio.main import app as audio_app
from apps.images.main import app as images_app
from apps.rag.main import app as rag_app
from apps.web.main import app as webui_app
import asyncio
from pydantic import BaseModel
from typing import List
@@ -36,17 +44,22 @@ from apps.rag.utils import rag_messages
from config import (
CONFIG_DATA,
WEBUI_NAME,
WEBUI_URL,
WEBUI_AUTH,
ENV,
VERSION,
CHANGELOG,
FRONTEND_BUILD_DIR,
CACHE_DIR,
STATIC_DIR,
MODEL_FILTER_ENABLED,
ENABLE_LITELLM,
ENABLE_MODEL_FILTER,
MODEL_FILTER_LIST,
GLOBAL_LOG_LEVEL,
SRC_LOG_LEVELS,
WEBHOOK_URL,
ENABLE_ADMIN_EXPORT,
AppConfig,
)
from constants import ERROR_MESSAGES
@@ -67,7 +80,7 @@ class SPAStaticFiles(StaticFiles):
print(
f"""
rf"""
___ __ __ _ _ _ ___
/ _ \ _ __ ___ _ __ \ \ / /__| |__ | | | |_ _|
| | | | '_ \ / _ \ '_ \ \ \ /\ / / _ \ '_ \| | | || |
@@ -81,18 +94,45 @@ https://github.com/open-webui/open-webui
"""
)
app = FastAPI(docs_url="/docs" if ENV == "dev" else None, redoc_url=None)
app.state.MODEL_FILTER_ENABLED = MODEL_FILTER_ENABLED
app.state.MODEL_FILTER_LIST = MODEL_FILTER_LIST
@asynccontextmanager
async def lifespan(app: FastAPI):
if ENABLE_LITELLM:
asyncio.create_task(start_litellm_background())
yield
if ENABLE_LITELLM:
await shutdown_litellm_background()
app.state.WEBHOOK_URL = WEBHOOK_URL
app = FastAPI(
docs_url="/docs" if ENV == "dev" else None, redoc_url=None, lifespan=lifespan
)
app.state.config = AppConfig()
app.state.config.ENABLE_MODEL_FILTER = ENABLE_MODEL_FILTER
app.state.config.MODEL_FILTER_LIST = MODEL_FILTER_LIST
app.state.config.WEBHOOK_URL = WEBHOOK_URL
origins = ["*"]
# Custom middleware to add security headers
# class SecurityHeadersMiddleware(BaseHTTPMiddleware):
# async def dispatch(self, request: Request, call_next):
# response: Response = await call_next(request)
# response.headers["Cross-Origin-Opener-Policy"] = "same-origin"
# response.headers["Cross-Origin-Embedder-Policy"] = "require-corp"
# return response
# app.add_middleware(SecurityHeadersMiddleware)
class RAGMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
return_citations = False
if request.method == "POST" and (
"/api/chat" in request.url.path or "/chat/completions" in request.url.path
):
@@ -105,20 +145,29 @@ class RAGMiddleware(BaseHTTPMiddleware):
# Parse string to JSON
data = json.loads(body_str) if body_str else {}
return_citations = data.get("citations", False)
if "citations" in data:
del data["citations"]
# Example: Add a new key-value pair or modify existing ones
# data["modified"] = True # Example modification
if "docs" in data:
data = {**data}
data["messages"] = rag_messages(
data["docs"],
data["messages"],
rag_app.state.RAG_TEMPLATE,
rag_app.state.TOP_K,
rag_app.state.sentence_transformer_ef,
data["messages"], citations = rag_messages(
docs=data["docs"],
messages=data["messages"],
template=rag_app.state.config.RAG_TEMPLATE,
embedding_function=rag_app.state.EMBEDDING_FUNCTION,
k=rag_app.state.config.TOP_K,
reranking_function=rag_app.state.sentence_transformer_rf,
r=rag_app.state.config.RELEVANCE_THRESHOLD,
hybrid_search=rag_app.state.config.ENABLE_RAG_HYBRID_SEARCH,
)
del data["docs"]
log.debug(f"data['messages']: {data['messages']}")
log.debug(
f"data['messages']: {data['messages']}, citations: {citations}"
)
modified_body_bytes = json.dumps(data).encode("utf-8")
@@ -136,11 +185,36 @@ class RAGMiddleware(BaseHTTPMiddleware):
]
response = await call_next(request)
if return_citations:
# Inject the citations into the response
if isinstance(response, StreamingResponse):
# If it's a streaming response, inject it as SSE event or NDJSON line
content_type = response.headers.get("Content-Type")
if "text/event-stream" in content_type:
return StreamingResponse(
self.openai_stream_wrapper(response.body_iterator, citations),
)
if "application/x-ndjson" in content_type:
return StreamingResponse(
self.ollama_stream_wrapper(response.body_iterator, citations),
)
return response
async def _receive(self, body: bytes):
return {"type": "http.request", "body": body, "more_body": False}
async def openai_stream_wrapper(self, original_generator, citations):
yield f"data: {json.dumps({'citations': citations})}\n\n"
async for data in original_generator:
yield data
async def ollama_stream_wrapper(self, original_generator, citations):
yield f"{json.dumps({'citations': citations})}\n"
async for data in original_generator:
yield data
app.add_middleware(RAGMiddleware)
@@ -164,14 +238,15 @@ async def check_url(request: Request, call_next):
return response
@app.on_event("startup")
async def on_startup():
await litellm_app_startup()
@app.middleware("http")
async def update_embedding_function(request: Request, call_next):
response = await call_next(request)
if "/embedding/update" in request.url.path:
webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
return response
app.mount("/api/v1", webui_app)
app.mount("/litellm/api", litellm_app)
app.mount("/ollama", ollama_app)
app.mount("/openai/api", openai_app)
@@ -179,6 +254,10 @@ app.mount("/images/api/v1", images_app)
app.mount("/audio/api/v1", audio_app)
app.mount("/rag/api/v1", rag_app)
app.mount("/api/v1", webui_app)
webui_app.state.EMBEDDING_FUNCTION = rag_app.state.EMBEDDING_FUNCTION
@app.get("/api/config")
async def get_app_config():
@@ -193,19 +272,21 @@ async def get_app_config():
"status": True,
"name": WEBUI_NAME,
"version": VERSION,
"auth": WEBUI_AUTH,
"default_locale": default_locale,
"images": images_app.state.ENABLED,
"default_models": webui_app.state.DEFAULT_MODELS,
"default_prompt_suggestions": webui_app.state.DEFAULT_PROMPT_SUGGESTIONS,
"images": images_app.state.config.ENABLED,
"default_models": webui_app.state.config.DEFAULT_MODELS,
"default_prompt_suggestions": webui_app.state.config.DEFAULT_PROMPT_SUGGESTIONS,
"trusted_header_auth": bool(webui_app.state.AUTH_TRUSTED_EMAIL_HEADER),
"admin_export_enabled": ENABLE_ADMIN_EXPORT,
}
@app.get("/api/config/model/filter")
async def get_model_filter_config(user=Depends(get_admin_user)):
return {
"enabled": app.state.MODEL_FILTER_ENABLED,
"models": app.state.MODEL_FILTER_LIST,
"enabled": app.state.config.ENABLE_MODEL_FILTER,
"models": app.state.config.MODEL_FILTER_LIST,
}
@@ -218,28 +299,28 @@ class ModelFilterConfigForm(BaseModel):
async def update_model_filter_config(
form_data: ModelFilterConfigForm, user=Depends(get_admin_user)
):
app.state.MODEL_FILTER_ENABLED = form_data.enabled
app.state.MODEL_FILTER_LIST = form_data.models
app.state.config.ENABLE_MODEL_FILTER = form_data.enabled
app.state.config.MODEL_FILTER_LIST = form_data.models
ollama_app.state.MODEL_FILTER_ENABLED = app.state.MODEL_FILTER_ENABLED
ollama_app.state.MODEL_FILTER_LIST = app.state.MODEL_FILTER_LIST
ollama_app.state.config.ENABLE_MODEL_FILTER = app.state.config.ENABLE_MODEL_FILTER
ollama_app.state.config.MODEL_FILTER_LIST = app.state.config.MODEL_FILTER_LIST
openai_app.state.MODEL_FILTER_ENABLED = app.state.MODEL_FILTER_ENABLED
openai_app.state.MODEL_FILTER_LIST = app.state.MODEL_FILTER_LIST
openai_app.state.config.ENABLE_MODEL_FILTER = app.state.config.ENABLE_MODEL_FILTER
openai_app.state.config.MODEL_FILTER_LIST = app.state.config.MODEL_FILTER_LIST
litellm_app.state.MODEL_FILTER_ENABLED = app.state.MODEL_FILTER_ENABLED
litellm_app.state.MODEL_FILTER_LIST = app.state.MODEL_FILTER_LIST
litellm_app.state.ENABLE_MODEL_FILTER = app.state.config.ENABLE_MODEL_FILTER
litellm_app.state.MODEL_FILTER_LIST = app.state.config.MODEL_FILTER_LIST
return {
"enabled": app.state.MODEL_FILTER_ENABLED,
"models": app.state.MODEL_FILTER_LIST,
"enabled": app.state.config.ENABLE_MODEL_FILTER,
"models": app.state.config.MODEL_FILTER_LIST,
}
@app.get("/api/webhook")
async def get_webhook_url(user=Depends(get_admin_user)):
return {
"url": app.state.WEBHOOK_URL,
"url": app.state.config.WEBHOOK_URL,
}
@@ -249,12 +330,12 @@ class UrlForm(BaseModel):
@app.post("/api/webhook")
async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
app.state.WEBHOOK_URL = form_data.url
app.state.config.WEBHOOK_URL = form_data.url
webui_app.state.WEBHOOK_URL = app.state.WEBHOOK_URL
webui_app.state.WEBHOOK_URL = app.state.config.WEBHOOK_URL
return {
"url": app.state.WEBHOOK_URL,
"url": app.state.config.WEBHOOK_URL,
}
@@ -299,15 +380,40 @@ async def get_manifest_json():
"background_color": "#343541",
"theme_color": "#343541",
"orientation": "portrait-primary",
"icons": [{"src": "/favicon.png", "type": "image/png", "sizes": "844x884"}],
"icons": [{"src": "/static/logo.png", "type": "image/png", "sizes": "500x500"}],
}
@app.get("/opensearch.xml")
async def get_opensearch_xml():
xml_content = rf"""
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/" xmlns:moz="http://www.mozilla.org/2006/browser/search/">
<ShortName>{WEBUI_NAME}</ShortName>
<Description>Search {WEBUI_NAME}</Description>
<InputEncoding>UTF-8</InputEncoding>
<Image width="16" height="16" type="image/x-icon">{WEBUI_URL}/favicon.png</Image>
<Url type="text/html" method="get" template="{WEBUI_URL}/?q={"{searchTerms}"}"/>
<moz:SearchForm>{WEBUI_URL}</moz:SearchForm>
</OpenSearchDescription>
"""
return Response(content=xml_content, media_type="application/xml")
@app.get("/health")
async def healthcheck():
return {"status": True}
app.mount("/static", StaticFiles(directory=STATIC_DIR), name="static")
app.mount("/cache", StaticFiles(directory=CACHE_DIR), name="cache")
app.mount(
"/",
SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
name="spa-static-files",
)
if os.path.exists(FRONTEND_BUILD_DIR):
app.mount(
"/",
SPAStaticFiles(directory=FRONTEND_BUILD_DIR, html=True),
name="spa-static-files",
)
else:
log.warning(
f"Frontend build directory not found at '{FRONTEND_BUILD_DIR}'. Serving API only."
)
+49 -42
View File
@@ -1,53 +1,60 @@
fastapi
uvicorn[standard]
pydantic
python-multipart
fastapi==0.109.2
uvicorn[standard]==0.22.0
pydantic==2.7.1
python-multipart==0.0.9
flask
flask_cors
Flask==3.0.3
Flask-Cors==4.0.0
python-socketio
python-jose
passlib[bcrypt]
uuid
python-socketio==5.11.2
python-jose==3.3.0
passlib[bcrypt]==1.7.4
requests
aiohttp
peewee
peewee-migrate
bcrypt
requests==2.31.0
aiohttp==3.9.5
peewee==3.17.3
peewee-migrate==1.12.2
psycopg2-binary==2.9.9
PyMySQL==1.1.0
bcrypt==4.1.2
litellm==1.30.7
boto3
litellm[proxy]==1.35.28
argon2-cffi
apscheduler
google-generativeai
boto3==1.34.95
langchain
langchain-community
fake_useragent
chromadb
sentence_transformers
pypdf
docx2txt
unstructured
markdown
pypandoc
pandas
openpyxl
pyxlsb
xlrd
argon2-cffi==23.1.0
APScheduler==3.10.4
google-generativeai==0.5.2
opencv-python-headless
rapidocr-onnxruntime
langchain==0.1.16
langchain-community==0.0.34
langchain-chroma==0.1.0
fpdf2
fake-useragent==1.5.1
chromadb==0.4.24
sentence-transformers==2.7.0
pypdf==4.2.0
docx2txt==0.8
unstructured==0.11.8
Markdown==3.6
pypandoc==1.13
pandas==2.2.2
openpyxl==3.1.2
pyxlsb==1.0.10
xlrd==2.0.1
validators==0.28.1
faster-whisper
opencv-python-headless==4.9.0.80
rapidocr-onnxruntime==1.2.3
PyJWT
pyjwt[crypto]
fpdf2==2.7.8
rank-bm25==0.2.2
black
langfuse
faster-whisper==1.0.1
PyJWT[crypto]==2.8.0
black==24.4.2
langfuse==2.27.3
youtube-transcript-api==0.6.2
pytube
+3 -2
View File
@@ -6,8 +6,9 @@ cd "$SCRIPT_DIR" || exit
KEY_FILE=.webui_secret_key
PORT="${PORT:-8080}"
HOST="${HOST:-0.0.0.0}"
if test "$WEBUI_SECRET_KEY $WEBUI_JWT_SECRET_KEY" = " "; then
echo "No WEBUI_SECRET_KEY provided"
echo "Loading WEBUI_SECRET_KEY from file, not provided as an environment variable."
if ! [ -e "$KEY_FILE" ]; then
echo "Generating WEBUI_SECRET_KEY"
@@ -29,4 +30,4 @@ if [ "$USE_CUDA_DOCKER" = "true" ]; then
export LD_LIBRARY_PATH="$LD_LIBRARY_PATH:/usr/local/lib/python3.11/site-packages/torch/lib:/usr/local/lib/python3.11/site-packages/nvidia/cudnn/lib"
fi
WEBUI_SECRET_KEY="$WEBUI_SECRET_KEY" exec uvicorn main:app --host 0.0.0.0 --port "$PORT" --forwarded-allow-ips '*'
WEBUI_SECRET_KEY="$WEBUI_SECRET_KEY" exec uvicorn main:app --host "$HOST" --port "$PORT" --forwarded-allow-ips '*'
+2 -2
View File
@@ -7,13 +7,13 @@ SET "SCRIPT_DIR=%~dp0"
cd /d "%SCRIPT_DIR%" || exit /b
SET "KEY_FILE=.webui_secret_key"
SET "PORT=%PORT:8080%"
IF "%PORT%"=="" SET PORT=8080
SET "WEBUI_SECRET_KEY=%WEBUI_SECRET_KEY%"
SET "WEBUI_JWT_SECRET_KEY=%WEBUI_JWT_SECRET_KEY%"
:: Check if WEBUI_SECRET_KEY and WEBUI_JWT_SECRET_KEY are not set
IF "%WEBUI_SECRET_KEY%%WEBUI_JWT_SECRET_KEY%" == " " (
echo No WEBUI_SECRET_KEY provided
echo Loading WEBUI_SECRET_KEY from file, not provided as an environment variable.
IF NOT EXIST "%KEY_FILE%" (
echo Generating WEBUI_SECRET_KEY
Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.0 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

+1
View File
@@ -0,0 +1 @@
Name,Email,Password,Role
1 Name Email Password Role
Binary file not shown.

After

Width:  |  Height:  |  Size: 6.0 KiB

+4 -3
View File
@@ -38,9 +38,10 @@ def calculate_sha256_string(string):
def validate_email_format(email: str) -> bool:
if not re.match(r"[^@]+@[^@]+\.[^@]+", email):
return False
return True
if email.endswith("@localhost"):
return True
return bool(re.match(r"[^@]+@[^@]+\.[^@]+", email))
def sanitize_filename(file_name):
+6
View File
@@ -89,6 +89,8 @@ def get_current_user(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=ERROR_MESSAGES.INVALID_TOKEN,
)
else:
Users.update_user_last_active_by_id(user.id)
return user
else:
raise HTTPException(
@@ -99,11 +101,15 @@ def get_current_user(
def get_current_user_by_api_key(api_key: str):
user = Users.get_user_by_api_key(api_key)
if user is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=ERROR_MESSAGES.INVALID_TOKEN,
)
else:
Users.update_user_last_active_by_id(user.id)
return user
+6 -1
View File
@@ -2,7 +2,12 @@
echo "Warning: This will remove all containers and volumes, including persistent data. Do you want to continue? [Y/N]"
read ans
if [ "$ans" == "Y" ] || [ "$ans" == "y" ]; then
docker-compose down -v
command docker-compose 2>/dev/null
if [ "$?" == "0" ]; then
docker-compose down -v
else
docker compose down -v
fi
else
echo "Operation cancelled."
fi
+8
View File
@@ -0,0 +1,8 @@
import { defineConfig } from 'cypress';
export default defineConfig({
e2e: {
baseUrl: 'http://localhost:8080'
},
video: true
});
+78
View File
@@ -0,0 +1,78 @@
// eslint-disable-next-line @typescript-eslint/triple-slash-reference
/// <reference path="../support/index.d.ts" />
// These tests run through the chat flow.
describe('Settings', () => {
// Wait for 2 seconds after all tests to fix an issue with Cypress's video recording missing the last few frames
after(() => {
// eslint-disable-next-line cypress/no-unnecessary-waiting
cy.wait(2000);
});
beforeEach(() => {
// Login as the admin user
cy.loginAdmin();
// Visit the home page
cy.visit('/');
});
context('Ollama', () => {
it('user can select a model', () => {
// Click on the model selector
cy.get('button[aria-label="Select a model"]').click();
// Select the first model
cy.get('button[aria-label="model-item"]').first().click();
});
it('user can perform text chat', () => {
// Click on the model selector
cy.get('button[aria-label="Select a model"]').click();
// Select the first model
cy.get('button[aria-label="model-item"]').first().click();
// Type a message
cy.get('#chat-textarea').type('Hi, what can you do? A single sentence only please.', {
force: true
});
// Send the message
cy.get('button[type="submit"]').click();
// User's message should be visible
cy.get('.chat-user').should('exist');
// Wait for the response
cy.get('.chat-assistant', { timeout: 120_000 }) // .chat-assistant is created after the first token is received
.find('div[aria-label="Generation Info"]', { timeout: 120_000 }) // Generation Info is created after the stop token is received
.should('exist');
});
it('user can share chat', () => {
// Click on the model selector
cy.get('button[aria-label="Select a model"]').click();
// Select the first model
cy.get('button[aria-label="model-item"]').first().click();
// Type a message
cy.get('#chat-textarea').type('Hi, what can you do? A single sentence only please.', {
force: true
});
// Send the message
cy.get('button[type="submit"]').click();
// User's message should be visible
cy.get('.chat-user').should('exist');
// Wait for the response
cy.get('.chat-assistant', { timeout: 120_000 }) // .chat-assistant is created after the first token is received
.find('div[aria-label="Generation Info"]', { timeout: 120_000 }) // Generation Info is created after the stop token is received
.should('exist');
// spy on requests
const spy = cy.spy();
cy.intercept('GET', '/api/v1/chats/*', spy);
// Open context menu
cy.get('#chat-context-menu-button').click();
// Click share button
cy.get('#chat-share-button').click();
// Check if the share dialog is visible
cy.get('#copy-and-share-chat-button').should('exist');
cy.wrap({}, { timeout: 5000 }).should(() => {
// Check if the request was made twice (once for to replace chat object and once more due to change event)
expect(spy).to.be.callCount(2);
});
});
});
});
+52
View File
@@ -0,0 +1,52 @@
// eslint-disable-next-line @typescript-eslint/triple-slash-reference
/// <reference path="../support/index.d.ts" />
import { adminUser } from '../support/e2e';
// These tests assume the following defaults:
// 1. No users exist in the database or that the test admin user is an admin
// 2. Language is set to English
// 3. The default role for new users is 'pending'
describe('Registration and Login', () => {
// Wait for 2 seconds after all tests to fix an issue with Cypress's video recording missing the last few frames
after(() => {
// eslint-disable-next-line cypress/no-unnecessary-waiting
cy.wait(2000);
});
beforeEach(() => {
cy.visit('/');
});
it('should register a new user as pending', () => {
const userName = `Test User - ${Date.now()}`;
const userEmail = `cypress-${Date.now()}@example.com`;
// Toggle from sign in to sign up
cy.contains('Sign up').click();
// Fill out the form
cy.get('input[autocomplete="name"]').type(userName);
cy.get('input[autocomplete="email"]').type(userEmail);
cy.get('input[type="password"]').type('password');
// Submit the form
cy.get('button[type="submit"]').click();
// Wait until the user is redirected to the home page
cy.contains(userName);
// Expect the user to be pending
cy.contains('Check Again');
});
it('can login with the admin user', () => {
// Fill out the form
cy.get('input[autocomplete="email"]').type(adminUser.email);
cy.get('input[type="password"]').type(adminUser.password);
// Submit the form
cy.get('button[type="submit"]').click();
// Wait until the user is redirected to the home page
cy.contains(adminUser.name);
// Dismiss the changelog dialog if it is visible
cy.getAllLocalStorage().then((ls) => {
if (!ls['version']) {
cy.get('button').contains("Okay, Let's Go!").click();
}
});
});
});
+84
View File
@@ -0,0 +1,84 @@
// eslint-disable-next-line @typescript-eslint/triple-slash-reference
/// <reference path="../support/index.d.ts" />
import { adminUser } from '../support/e2e';
// These tests run through the various settings pages, ensuring that the user can interact with them as expected
describe('Settings', () => {
// Wait for 2 seconds after all tests to fix an issue with Cypress's video recording missing the last few frames
after(() => {
// eslint-disable-next-line cypress/no-unnecessary-waiting
cy.wait(2000);
});
beforeEach(() => {
// Login as the admin user
cy.loginAdmin();
// Visit the home page
cy.visit('/');
// Click on the user menu
cy.get('button[aria-label="User Menu"]').click();
// Click on the settings link
cy.get('button').contains('Settings').click();
});
context('General', () => {
it('user can open the General modal and hit save', () => {
cy.get('button').contains('General').click();
cy.get('button').contains('Save').click();
});
});
context('Connections', () => {
it('user can open the Connections modal and hit save', () => {
cy.get('button').contains('Connections').click();
cy.get('button').contains('Save').click();
});
});
context('Models', () => {
it('user can open the Models modal', () => {
cy.get('button').contains('Models').click();
});
});
context('Interface', () => {
it('user can open the Interface modal and hit save', () => {
cy.get('button').contains('Interface').click();
cy.get('button').contains('Save').click();
});
});
context('Audio', () => {
it('user can open the Audio modal and hit save', () => {
cy.get('button').contains('Audio').click();
cy.get('button').contains('Save').click();
});
});
context('Images', () => {
it('user can open the Images modal and hit save', () => {
cy.get('button').contains('Images').click();
// Currently fails because the backend requires a valid URL
// cy.get('button').contains('Save').click();
});
});
context('Chats', () => {
it('user can open the Chats modal', () => {
cy.get('button').contains('Chats').click();
});
});
context('Account', () => {
it('user can open the Account modal and hit save', () => {
cy.get('button').contains('Account').click();
cy.get('button').contains('Save').click();
});
});
context('About', () => {
it('user can open the About modal', () => {
cy.get('button').contains('About').click();
});
});
});
+73
View File
@@ -0,0 +1,73 @@
/// <reference types="cypress" />
export const adminUser = {
name: 'Admin User',
email: 'admin@example.com',
password: 'password'
};
const login = (email: string, password: string) => {
return cy.session(
email,
() => {
// Visit auth page
cy.visit('/auth');
// Fill out the form
cy.get('input[autocomplete="email"]').type(email);
cy.get('input[type="password"]').type(password);
// Submit the form
cy.get('button[type="submit"]').click();
// Wait until the user is redirected to the home page
cy.get('#chat-search').should('exist');
// Get the current version to skip the changelog dialog
if (localStorage.getItem('version') === null) {
cy.get('button').contains("Okay, Let's Go!").click();
}
},
{
validate: () => {
cy.request({
method: 'GET',
url: '/api/v1/auths/',
headers: {
Authorization: 'Bearer ' + localStorage.getItem('token')
}
});
}
}
);
};
const register = (name: string, email: string, password: string) => {
return cy
.request({
method: 'POST',
url: '/api/v1/auths/signup',
body: {
name: name,
email: email,
password: password
},
failOnStatusCode: false
})
.then((response) => {
expect(response.status).to.be.oneOf([200, 400]);
});
};
const registerAdmin = () => {
return register(adminUser.name, adminUser.email, adminUser.password);
};
const loginAdmin = () => {
return login(adminUser.email, adminUser.password);
};
Cypress.Commands.add('login', (email, password) => login(email, password));
Cypress.Commands.add('register', (name, email, password) => register(name, email, password));
Cypress.Commands.add('registerAdmin', () => registerAdmin());
Cypress.Commands.add('loginAdmin', () => loginAdmin());
before(() => {
cy.registerAdmin();
});
+11
View File
@@ -0,0 +1,11 @@
// load the global Cypress types
/// <reference types="cypress" />
declare namespace Cypress {
interface Chainable {
login(email: string, password: string): Chainable<Element>;
register(name: string, email: string, password: string): Chainable<Element>;
registerAdmin(): Chainable<Element>;
loginAdmin(): Chainable<Element>;
}
}
+7
View File
@@ -0,0 +1,7 @@
{
"extends": "../tsconfig.json",
"compilerOptions": {
"inlineSourceMap": true,
"sourceMap": false
}
}
-2
View File
@@ -1,5 +1,3 @@
version: '3.8'
services:
ollama:
# Expose Ollama API outside the container stack
-2
View File
@@ -1,5 +1,3 @@
version: '3.8'
services:
ollama:
volumes:
-2
View File
@@ -1,5 +1,3 @@
version: '3.8'
services:
ollama:
# GPU support
-2
View File
@@ -1,5 +1,3 @@
version: '3.8'
services:
ollama:
volumes:
+2 -2
View File
@@ -17,7 +17,7 @@ If your issue or contribution pertains directly to the core Ollama technology, p
### 🚨 Reporting Issues
Noticed something off? Have an idea? Check our [Issues tab](https://github.com/open-webui/oopen-webui/issues) to see if it's already been reported or suggested. If not, feel free to open a new issue. When reporting an issue, please follow our issue templates. These templates are designed to ensure that all necessary details are provided from the start, enabling us to address your concerns more efficiently.
Noticed something off? Have an idea? Check our [Issues tab](https://github.com/open-webui/open-webui/issues) to see if it's already been reported or suggested. If not, feel free to open a new issue. When reporting an issue, please follow our issue templates. These templates are designed to ensure that all necessary details are provided from the start, enabling us to address your concerns more efficiently.
> [!IMPORTANT]
>
@@ -54,7 +54,7 @@ Help us make Open WebUI more accessible by improving documentation, writing tuto
Help us make Open WebUI available to a wider audience. In this section, we'll guide you through the process of adding new translations to the project.
We use JSON files to store translations. You can find the existing translation files in the `src/lib/i18n/locales` directory. Each directory corresponds to a specific language, for example, `en-US` for English (US), `fr-FR` for French (France) and so on. You can refer to [ISO 639 Language Codes][http://www.lingoes.net/en/translator/langcode.htm] to find the appropriate code for a specific language.
We use JSON files to store translations. You can find the existing translation files in the `src/lib/i18n/locales` directory. Each directory corresponds to a specific language, for example, `en-US` for English (US), `fr-FR` for French (France) and so on. You can refer to [ISO 639 Language Codes](http://www.lingoes.net/en/translator/langcode.htm) to find the appropriate code for a specific language.
To add a new language:
-1
View File
@@ -1 +0,0 @@
values-minikube.yaml
-21
View File
@@ -1,21 +0,0 @@
apiVersion: v2
name: open-webui
version: 1.0.0
appVersion: "latest"
home: https://www.openwebui.com/
icon: https://raw.githubusercontent.com/open-webui/open-webui/main/static/favicon.png
description: "Open WebUI: A User-Friendly Web Interface for Chat Interactions 👋"
keywords:
- llm
- chat
- web-ui
sources:
- https://github.com/open-webui/open-webui/tree/main/kubernetes/helm
- https://hub.docker.com/r/ollama/ollama
- https://github.com/open-webui/open-webui/pkgs/container/open-webui
annotations:
licenses: MIT
+4
View File
@@ -0,0 +1,4 @@
# Helm Charts
Open WebUI Helm Charts are now hosted in a separate repo, which can be found here: https://github.com/open-webui/helm-charts
The charts are released at https://helm.openwebui.com.
-51
View File
@@ -1,51 +0,0 @@
{{- define "open-webui.name" -}}
{{- default .Chart.Name .Values.nameOverride | trunc 63 | trimSuffix "-" }}
{{- end -}}
{{- define "ollama.name" -}}
ollama
{{- end -}}
{{- define "ollama.url" -}}
{{- if .Values.ollama.externalHost }}
{{- printf .Values.ollama.externalHost }}
{{- else }}
{{- printf "http://%s.%s.svc.cluster.local:%d/" (include "ollama.name" .) (.Release.Namespace) (.Values.ollama.service.port | int) }}
{{- end }}
{{- end }}
{{- define "chart.name" -}}
{{- printf "%s-%s" .Chart.Name .Chart.Version | replace "+" "_" | trunc 63 | trimSuffix "-" }}
{{- end }}
{{- define "base.labels" -}}
helm.sh/chart: {{ include "chart.name" . }}
{{- if .Chart.AppVersion }}
app.kubernetes.io/version: {{ .Chart.AppVersion | quote }}
{{- end }}
app.kubernetes.io/managed-by: {{ .Release.Service }}
{{- end }}
{{- define "base.selectorLabels" -}}
app.kubernetes.io/instance: {{ .Release.Name }}
{{- end -}}
{{- define "open-webui.selectorLabels" -}}
{{ include "base.selectorLabels" . }}
app.kubernetes.io/component: {{ .Chart.Name }}
{{- end }}
{{- define "open-webui.labels" -}}
{{ include "base.labels" . }}
{{ include "open-webui.selectorLabels" . }}
{{- end }}
{{- define "ollama.selectorLabels" -}}
{{ include "base.selectorLabels" . }}
app.kubernetes.io/component: {{ include "ollama.name" . }}
{{- end }}
{{- define "ollama.labels" -}}
{{ include "base.labels" . }}
{{ include "ollama.selectorLabels" . }}
{{- end }}
@@ -1,23 +0,0 @@
{{- if not .Values.ollama.externalHost }}
apiVersion: v1
kind: Service
metadata:
name: {{ include "ollama.name" . }}
labels:
{{- include "ollama.labels" . | nindent 4 }}
{{- with .Values.ollama.service.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
selector:
{{- include "ollama.selectorLabels" . | nindent 4 }}
{{- with .Values.ollama.service }}
type: {{ .type }}
ports:
- protocol: TCP
name: http
port: {{ .port }}
targetPort: http
{{- end }}
{{- end }}
@@ -1,98 +0,0 @@
{{- if not .Values.ollama.externalHost }}
apiVersion: apps/v1
kind: StatefulSet
metadata:
name: {{ include "ollama.name" . }}
labels:
{{- include "ollama.labels" . | nindent 4 }}
{{- with .Values.ollama.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
serviceName: {{ include "ollama.name" . }}
replicas: {{ .Values.ollama.replicaCount }}
selector:
matchLabels:
{{- include "ollama.selectorLabels" . | nindent 6 }}
template:
metadata:
labels:
{{- include "ollama.labels" . | nindent 8 }}
{{- with .Values.ollama.podAnnotations }}
annotations:
{{- toYaml . | nindent 8 }}
{{- end }}
spec:
enableServiceLinks: false
automountServiceAccountToken: false
{{- with .Values.ollama.runtimeClassName }}
runtimeClassName: {{ . }}
{{- end }}
containers:
- name: {{ include "ollama.name" . }}
{{- with .Values.ollama.image }}
image: {{ .repository }}:{{ .tag }}
imagePullPolicy: {{ .pullPolicy }}
{{- end }}
tty: true
ports:
- name: http
containerPort: {{ .Values.ollama.service.containerPort }}
env:
{{- if .Values.ollama.gpu.enabled }}
- name: PATH
value: /usr/local/nvidia/bin:/usr/local/cuda/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
- name: LD_LIBRARY_PATH
value: /usr/local/nvidia/lib:/usr/local/nvidia/lib64
- name: NVIDIA_DRIVER_CAPABILITIES
value: compute,utility
{{- end }}
{{- with .Values.ollama.resources }}
resources: {{- toYaml . | nindent 10 }}
{{- end }}
volumeMounts:
- name: data
mountPath: /root/.ollama
{{- with .Values.ollama.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- with .Values.ollama.tolerations }}
tolerations:
{{- toYaml . | nindent 8 }}
{{- end }}
volumes:
{{- if and .Values.ollama.persistence.enabled .Values.ollama.persistence.existingClaim }}
- name: data
persistentVolumeClaim:
claimName: {{ .Values.ollama.persistence.existingClaim }}
{{- else if not .Values.ollama.persistence.enabled }}
- name: data
emptyDir: {}
{{- else if and .Values.ollama.persistence.enabled (not .Values.ollama.persistence.existingClaim) }}
[]
volumeClaimTemplates:
- metadata:
name: data
labels:
{{- include "ollama.selectorLabels" . | nindent 8 }}
{{- with .Values.ollama.persistence.annotations }}
annotations:
{{- toYaml . | nindent 8 }}
{{- end }}
spec:
accessModes:
{{- range .Values.ollama.persistence.accessModes }}
- {{ . | quote }}
{{- end }}
resources:
requests:
storage: {{ .Values.ollama.persistence.size | quote }}
storageClassName: {{ .Values.ollama.persistence.storageClass }}
{{- with .Values.ollama.persistence.selector }}
selector:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- end }}
{{- end }}
@@ -1,62 +0,0 @@
apiVersion: apps/v1
kind: Deployment
metadata:
name: {{ include "open-webui.name" . }}
labels:
{{- include "open-webui.labels" . | nindent 4 }}
{{- with .Values.webui.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
replicas: {{ .Values.webui.replicaCount }}
selector:
matchLabels:
{{- include "open-webui.selectorLabels" . | nindent 6 }}
template:
metadata:
labels:
{{- include "open-webui.labels" . | nindent 8 }}
{{- with .Values.webui.podAnnotations }}
annotations:
{{- toYaml . | nindent 8 }}
{{- end }}
spec:
enableServiceLinks: false
automountServiceAccountToken: false
containers:
- name: {{ .Chart.Name }}
{{- with .Values.webui.image }}
image: {{ .repository }}:{{ .tag | default $.Chart.AppVersion }}
imagePullPolicy: {{ .pullPolicy }}
{{- end }}
ports:
- name: http
containerPort: {{ .Values.webui.service.containerPort }}
{{- with .Values.webui.resources }}
resources: {{- toYaml . | nindent 10 }}
{{- end }}
volumeMounts:
- name: data
mountPath: /app/backend/data
env:
- name: OLLAMA_BASE_URL
value: {{ include "ollama.url" . | quote }}
tty: true
{{- with .Values.webui.nodeSelector }}
nodeSelector:
{{- toYaml . | nindent 8 }}
{{- end }}
volumes:
{{- if and .Values.webui.persistence.enabled .Values.webui.persistence.existingClaim }}
- name: data
persistentVolumeClaim:
claimName: {{ .Values.webui.persistence.existingClaim }}
{{- else if not .Values.webui.persistence.enabled }}
- name: data
emptyDir: {}
{{- else if and .Values.webui.persistence.enabled (not .Values.webui.persistence.existingClaim) }}
- name: data
persistentVolumeClaim:
claimName: {{ include "open-webui.name" . }}
{{- end }}
@@ -1,33 +0,0 @@
{{- if .Values.webui.ingress.enabled }}
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: {{ include "open-webui.name" . }}
labels:
{{- include "open-webui.labels" . | nindent 4 }}
{{- with .Values.webui.ingress.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
{{- with .Values.webui.ingress.class }}
ingressClassName: {{ . }}
{{- end }}
{{- if .Values.webui.ingress.tls }}
tls:
- hosts:
- {{ .Values.webui.ingress.host | quote }}
secretName: {{ default (printf "%s-tls" .Release.Name) .Values.webui.ingress.existingSecret }}
{{- end }}
rules:
- host: {{ .Values.webui.ingress.host }}
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: {{ include "open-webui.name" . }}
port:
name: http
{{- end }}
-27
View File
@@ -1,27 +0,0 @@
{{- if and .Values.webui.persistence.enabled (not .Values.webui.persistence.existingClaim) }}
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
name: {{ include "open-webui.name" . }}
labels:
{{- include "open-webui.selectorLabels" . | nindent 4 }}
{{- with .Values.webui.persistence.annotations }}
annotations:
{{- toYaml . | nindent 8 }}
{{- end }}
spec:
accessModes:
{{- range .Values.webui.persistence.accessModes }}
- {{ . | quote }}
{{- end }}
resources:
requests:
storage: {{ .Values.webui.persistence.size }}
{{- if .Values.webui.persistence.storageClass }}
storageClassName: {{ .Values.webui.persistence.storageClass }}
{{- end }}
{{- with .Values.webui.persistence.selector }}
selector:
{{- toYaml . | nindent 4 }}
{{- end }}
{{- end }}
@@ -1,29 +0,0 @@
apiVersion: v1
kind: Service
metadata:
name: {{ include "open-webui.name" . }}
labels:
{{- include "open-webui.labels" . | nindent 4 }}
{{- with .Values.webui.service.labels }}
{{- toYaml . | nindent 4 }}
{{- end }}
{{- with .Values.webui.service.annotations }}
annotations:
{{- toYaml . | nindent 4 }}
{{- end }}
spec:
selector:
{{- include "open-webui.selectorLabels" . | nindent 4 }}
type: {{ .Values.webui.service.type | default "ClusterIP" }}
ports:
- protocol: TCP
name: http
port: {{ .Values.webui.service.port }}
targetPort: http
{{- if .Values.webui.service.nodePort }}
nodePort: {{ .Values.webui.service.nodePort | int }}
{{- end }}
{{- if .Values.webui.service.loadBalancerClass }}
loadBalancerClass: {{ .Values.webui.service.loadBalancerClass | quote }}
{{- end }}
-27
View File
@@ -1,27 +0,0 @@
ollama:
resources:
requests:
cpu: "2000m"
memory: "2Gi"
limits:
cpu: "4000m"
memory: "4Gi"
nvidia.com/gpu: "0"
service:
type: ClusterIP
gpu:
enabled: false
webui:
resources:
requests:
cpu: "500m"
memory: "500Mi"
limits:
cpu: "1000m"
memory: "1Gi"
ingress:
enabled: true
host: open-webui.minikube.local
service:
type: NodePort
-75
View File
@@ -1,75 +0,0 @@
nameOverride: ""
ollama:
externalHost: ""
annotations: {}
podAnnotations: {}
replicaCount: 1
image:
repository: ollama/ollama
tag: latest
pullPolicy: Always
resources: {}
persistence:
enabled: true
size: 30Gi
existingClaim: ""
accessModes:
- ReadWriteOnce
storageClass: ""
selector: {}
annotations: {}
nodeSelector: {}
# -- If using a special runtime container such as nvidia, set it here.
runtimeClassName: ""
tolerations:
- key: nvidia.com/gpu
operator: Exists
effect: NoSchedule
service:
type: ClusterIP
annotations: {}
port: 80
containerPort: 11434
gpu:
# -- Enable additional ENV values to help Ollama discover GPU usage
enabled: false
webui:
annotations: {}
podAnnotations: {}
replicaCount: 1
image:
repository: ghcr.io/open-webui/open-webui
tag: ""
pullPolicy: Always
resources: {}
ingress:
enabled: false
class: ""
# -- Use appropriate annotations for your Ingress controller, e.g., for NGINX:
# nginx.ingress.kubernetes.io/rewrite-target: /
annotations: {}
host: ""
tls: false
existingSecret: ""
persistence:
enabled: true
size: 2Gi
existingClaim: ""
# -- If using multiple replicas, you must update accessModes to ReadWriteMany
accessModes:
- ReadWriteOnce
storageClass: ""
selector: {}
annotations: {}
nodeSelector: {}
tolerations: []
service:
type: ClusterIP
annotations: {}
port: 80
containerPort: 8080
nodePort: ""
labels: {}
loadBalancerClass: ""
+2746 -165
View File
File diff suppressed because it is too large Load Diff
+15 -7
View File
@@ -1,10 +1,10 @@
{
"name": "open-webui",
"version": "0.1.118",
"version": "0.1.125",
"private": true,
"scripts": {
"dev": "vite dev --host",
"build": "vite build",
"dev": "npm run pyodide:fetch && vite dev --host",
"build": "npm run pyodide:fetch && vite build",
"preview": "vite preview",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
@@ -12,9 +12,12 @@
"lint:frontend": "eslint . --fix",
"lint:types": "npm run check",
"lint:backend": "pylint backend/",
"format": "prettier --plugin-search-dir --write '**/*.{js,ts,svelte,css,md,html,json}'",
"format": "prettier --plugin-search-dir --write \"**/*.{js,ts,svelte,css,md,html,json}\"",
"format:backend": "black . --exclude \"/venv/\"",
"i18n:parse": "i18next --config i18next-parser.config.ts && prettier --write 'src/lib/i18n/**/*.{js,json}'"
"i18n:parse": "i18next --config i18next-parser.config.ts && prettier --write \"src/lib/i18n/**/*.{js,json}\"",
"cy:open": "cypress open",
"test:frontend": "vitest",
"pyodide:fetch": "node scripts/prepare-pyodide.js"
},
"devDependencies": {
"@sveltejs/adapter-auto": "^2.0.0",
@@ -25,8 +28,10 @@
"@typescript-eslint/eslint-plugin": "^6.17.0",
"@typescript-eslint/parser": "^6.17.0",
"autoprefixer": "^10.4.16",
"cypress": "^13.8.1",
"eslint": "^8.56.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-cypress": "^3.0.2",
"eslint-plugin-svelte": "^2.30.0",
"i18next-parser": "^8.13.0",
"postcss": "^8.4.31",
@@ -38,14 +43,17 @@
"tailwindcss": "^3.3.3",
"tslib": "^2.4.1",
"typescript": "^5.0.0",
"vite": "^4.4.2"
"vite": "^4.4.2",
"vitest": "^1.6.0"
},
"type": "module",
"dependencies": {
"@pyscript/core": "^0.4.32",
"@sveltejs/adapter-node": "^1.3.1",
"async": "^3.2.5",
"bits-ui": "^0.19.7",
"dayjs": "^1.11.10",
"eventsource-parser": "^1.1.2",
"file-saver": "^2.0.5",
"highlight.js": "^11.9.0",
"i18next": "^23.10.0",
@@ -53,9 +61,9 @@
"i18next-resources-to-backend": "^1.2.0",
"idb": "^7.1.1",
"js-sha256": "^0.10.1",
"jspdf": "^2.5.1",
"katex": "^0.16.9",
"marked": "^9.1.0",
"pyodide": "^0.26.0-alpha.4",
"svelte-sonner": "^0.3.19",
"tippy.js": "^6.3.7",
"uuid": "^9.0.1"
+2 -1
View File
@@ -82,6 +82,7 @@ usage() {
echo "Examples:"
echo " $0 --drop"
echo " $0 --enable-gpu[count=1]"
echo " $0 --enable-gpu[count=all]"
echo " $0 --enable-api[port=11435]"
echo " $0 --enable-gpu[count=1] --enable-api[port=12345] --webui[port=3000]"
echo " $0 --enable-gpu[count=1] --enable-api[port=12345] --webui[port=3000] --data[folder=./ollama-data]"
@@ -160,7 +161,7 @@ else
if [[ $enable_gpu == true ]]; then
# Validate and process command-line arguments
if [[ -n $gpu_count ]]; then
if ! [[ $gpu_count =~ ^[0-9]+$ ]]; then
if ! [[ $gpu_count =~ ^([0-9]+|all)$ ]]; then
echo "Invalid GPU count: $gpu_count"
exit 1
fi
+39
View File
@@ -0,0 +1,39 @@
const packages = [
'requests',
'beautifulsoup4',
'numpy',
'pandas',
'matplotlib',
'scikit-learn',
'scipy',
'regex',
'seaborn'
];
import { loadPyodide } from 'pyodide';
import { writeFile, copyFile, readdir } from 'fs/promises';
async function downloadPackages() {
console.log('Setting up pyodide + micropip');
const pyodide = await loadPyodide({
packageCacheDir: 'static/pyodide'
});
await pyodide.loadPackage('micropip');
const micropip = pyodide.pyimport('micropip');
console.log('Downloading Pyodide packages:', packages);
await micropip.install(packages);
console.log('Pyodide packages downloaded, freezing into lock file');
const lockFile = await micropip.freeze();
await writeFile('static/pyodide/pyodide-lock.json', lockFile);
}
async function copyPyodide() {
console.log('Copying Pyodide files into static directory');
// Copy all files from node_modules/pyodide to static/pyodide
for await (const entry of await readdir('node_modules/pyodide')) {
await copyFile(`node_modules/pyodide/${entry}`, `static/pyodide/${entry}`);
}
}
await downloadPackages();
await copyPyodide();
+29
View File
@@ -82,3 +82,32 @@ select {
.katex-mathml {
display: none;
}
.scrollbar-hidden:active::-webkit-scrollbar-thumb,
.scrollbar-hidden:focus::-webkit-scrollbar-thumb,
.scrollbar-hidden:hover::-webkit-scrollbar-thumb {
visibility: visible;
}
.scrollbar-hidden::-webkit-scrollbar-thumb {
visibility: hidden;
}
.scrollbar-none::-webkit-scrollbar {
display: none; /* for Chrome, Safari and Opera */
}
.scrollbar-none {
-ms-overflow-style: none; /* IE and Edge */
scrollbar-width: none; /* Firefox */
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
/* display: none; <- Crashes Chrome on hover */
-webkit-appearance: none;
margin: 0; /* <-- Apparently some margin are still there even though it's hidden */
}
input[type='number'] {
-moz-appearance: textfield; /* Firefox */
}
+45 -1
View File
@@ -3,9 +3,16 @@
<head>
<meta charset="utf-8" />
<link rel="icon" href="%sveltekit.assets%/favicon.png" />
<link rel="manifest" href="%sveltekit.assets%/manifest.json" />
<link rel="manifest" href="%sveltekit.assets%/manifest.json" crossorigin="use-credentials" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<meta name="robots" content="noindex,nofollow" />
<link
rel="search"
type="application/opensearchdescription+xml"
title="Open WebUI"
href="/opensearch.xml"
/>
<script>
// On page load or when changing themes, best to add inline in `head` to avoid FOUC
(() => {
@@ -43,9 +50,46 @@
})();
</script>
<title>Open WebUI</title>
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
<div style="display: contents">%sveltekit.body%</div>
<div
id="splash-screen"
style="
position: fixed;
z-index: 100;
background: #fff;
top: 0;
left: 0;
width: 100%;
height: 100%;
"
>
<style type="text/css" nonce="">
html {
overflow-y: scroll !important;
}
</style>
<img
style="
position: absolute;
width: 6rem;
height: 6rem;
top: 46%;
left: 50%;
margin: -40px 0 0 -40px;
"
src="/logo.svg"
/>
<!-- <span style="position: absolute; bottom: 32px; left: 50%; margin: -36px 0 0 -36px">
Footer content
</span> -->
</div>
</body>
</html>
+103 -1
View File
@@ -1,11 +1,75 @@
import { AUDIO_API_BASE_URL } from '$lib/constants';
export const getAudioConfig = async (token: string) => {
let error = null;
const res = await fetch(`${AUDIO_API_BASE_URL}/config`, {
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.log(err);
error = err.detail;
return null;
});
if (error) {
throw error;
}
return res;
};
type OpenAIConfigForm = {
url: string;
key: string;
model: string;
speaker: string;
};
export const updateAudioConfig = async (token: string, payload: OpenAIConfigForm) => {
let error = null;
const res = await fetch(`${AUDIO_API_BASE_URL}/config/update`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify({
...payload
})
})
.then(async (res) => {
if (!res.ok) throw await res.json();
return res.json();
})
.catch((err) => {
console.log(err);
error = err.detail;
return null;
});
if (error) {
throw error;
}
return res;
};
export const transcribeAudio = async (token: string, file: File) => {
const data = new FormData();
data.append('file', file);
let error = null;
const res = await fetch(`${AUDIO_API_BASE_URL}/transcribe`, {
const res = await fetch(`${AUDIO_API_BASE_URL}/transcriptions`, {
method: 'POST',
headers: {
Accept: 'application/json',
@@ -29,3 +93,41 @@ export const transcribeAudio = async (token: string, file: File) => {
return res;
};
export const synthesizeOpenAISpeech = async (
token: string = '',
speaker: string = 'alloy',
text: string = '',
model: string = 'tts-1'
) => {
let error = null;
const res = await fetch(`${AUDIO_API_BASE_URL}/speech`, {
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: model,
input: text,
voice: speaker
})
})
.then(async (res) => {
if (!res.ok) throw await res.json();
return res;
})
.catch((err) => {
error = err.detail;
console.log(err);
return null;
});
if (error) {
throw error;
}
return res;
};
+39
View File
@@ -95,6 +95,45 @@ export const userSignUp = async (
return res;
};
export const addUser = async (
token: string,
name: string,
email: string,
password: string,
role: string = 'pending'
) => {
let error = null;
const res = await fetch(`${WEBUI_API_BASE_URL}/auths/add`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
...(token && { authorization: `Bearer ${token}` })
},
body: JSON.stringify({
name: name,
email: email,
password: password,
role: role
})
})
.then(async (res) => {
if (!res.ok) throw await res.json();
return res.json();
})
.catch((err) => {
console.log(err);
error = err.detail;
return null;
});
if (error) {
throw error;
}
return res;
};
export const updateUserProfile = async (token: string, name: string, profileImageUrl: string) => {
let error = null;
+111 -4
View File
@@ -1,4 +1,5 @@
import { WEBUI_API_BASE_URL } from '$lib/constants';
import { getTimeRange } from '$lib/utils';
export const createNewChat = async (token: string, chat: object) => {
let error = null;
@@ -59,6 +60,74 @@ export const getChatList = async (token: string = '') => {
throw error;
}
return res.map((chat) => ({
...chat,
time_range: getTimeRange(chat.updated_at)
}));
};
export const getChatListByUserId = async (token: string = '', userId: string) => {
let error = null;
const res = await fetch(`${WEBUI_API_BASE_URL}/chats/list/user/${userId}`, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
...(token && { authorization: `Bearer ${token}` })
}
})
.then(async (res) => {
if (!res.ok) throw await res.json();
return res.json();
})
.then((json) => {
return json;
})
.catch((err) => {
error = err;
console.log(err);
return null;
});
if (error) {
throw error;
}
return res.map((chat) => ({
...chat,
time_range: getTimeRange(chat.updated_at)
}));
};
export const getArchivedChatList = async (token: string = '') => {
let error = null;
const res = await fetch(`${WEBUI_API_BASE_URL}/chats/archived`, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
...(token && { authorization: `Bearer ${token}` })
}
})
.then(async (res) => {
if (!res.ok) throw await res.json();
return res.json();
})
.then((json) => {
return json;
})
.catch((err) => {
error = err;
console.log(err);
return null;
});
if (error) {
throw error;
}
return res;
};
@@ -158,13 +227,16 @@ export const getAllChatTags = async (token: string) => {
export const getChatListByTagName = async (token: string = '', tagName: string) => {
let error = null;
const res = await fetch(`${WEBUI_API_BASE_URL}/chats/tags/tag/${tagName}`, {
method: 'GET',
const res = await fetch(`${WEBUI_API_BASE_URL}/chats/tags`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
...(token && { authorization: `Bearer ${token}` })
}
},
body: JSON.stringify({
name: tagName
})
})
.then(async (res) => {
if (!res.ok) throw await res.json();
@@ -183,7 +255,10 @@ export const getChatListByTagName = async (token: string = '', tagName: string)
throw error;
}
return res;
return res.map((chat) => ({
...chat,
time_range: getTimeRange(chat.updated_at)
}));
};
export const getChatById = async (token: string, id: string) => {
@@ -282,6 +357,38 @@ export const shareChatById = async (token: string, id: string) => {
return res;
};
export const archiveChatById = async (token: string, id: string) => {
let error = null;
const res = await fetch(`${WEBUI_API_BASE_URL}/chats/${id}/archive`, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
...(token && { authorization: `Bearer ${token}` })
}
})
.then(async (res) => {
if (!res.ok) throw await res.json();
return res.json();
})
.then((json) => {
return json;
})
.catch((err) => {
error = err;
console.log(err);
return null;
});
if (error) {
throw error;
}
return res;
};
export const deleteSharedChatById = async (token: string, id: string) => {
let error = null;
+7 -6
View File
@@ -72,10 +72,10 @@ export const updateImageGenerationConfig = async (
return res;
};
export const getOpenAIKey = async (token: string = '') => {
export const getOpenAIConfig = async (token: string = '') => {
let error = null;
const res = await fetch(`${IMAGES_API_BASE_URL}/key`, {
const res = await fetch(`${IMAGES_API_BASE_URL}/openai/config`, {
method: 'GET',
headers: {
Accept: 'application/json',
@@ -101,13 +101,13 @@ export const getOpenAIKey = async (token: string = '') => {
throw error;
}
return res.OPENAI_API_KEY;
return res;
};
export const updateOpenAIKey = async (token: string = '', key: string) => {
export const updateOpenAIConfig = async (token: string = '', url: string, key: string) => {
let error = null;
const res = await fetch(`${IMAGES_API_BASE_URL}/key/update`, {
const res = await fetch(`${IMAGES_API_BASE_URL}/openai/config/update`, {
method: 'POST',
headers: {
Accept: 'application/json',
@@ -115,6 +115,7 @@ export const updateOpenAIKey = async (token: string = '', key: string) => {
...(token && { authorization: `Bearer ${token}` })
},
body: JSON.stringify({
url: url,
key: key
})
})
@@ -136,7 +137,7 @@ export const updateOpenAIKey = async (token: string = '', key: string) => {
throw error;
}
return res.OPENAI_API_KEY;
return res;
};
export const getImageGenerationEngineUrls = async (token: string = '') => {
+155
View File
@@ -0,0 +1,155 @@
import { WEBUI_API_BASE_URL } from '$lib/constants';
export const getMemories = async (token: string) => {
let error = null;
const res = await fetch(`${WEBUI_API_BASE_URL}/memories`, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
authorization: `Bearer ${token}`
}
})
.then(async (res) => {
if (!res.ok) throw await res.json();
return res.json();
})
.catch((err) => {
error = err.detail;
console.log(err);
return null;
});
if (error) {
throw error;
}
return res;
};
export const addNewMemory = async (token: string, content: string) => {
let error = null;
const res = await fetch(`${WEBUI_API_BASE_URL}/memories/add`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
authorization: `Bearer ${token}`
},
body: JSON.stringify({
content: content
})
})
.then(async (res) => {
if (!res.ok) throw await res.json();
return res.json();
})
.catch((err) => {
error = err.detail;
console.log(err);
return null;
});
if (error) {
throw error;
}
return res;
};
export const queryMemory = async (token: string, content: string) => {
let error = null;
const res = await fetch(`${WEBUI_API_BASE_URL}/memories/query`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
authorization: `Bearer ${token}`
},
body: JSON.stringify({
content: content
})
})
.then(async (res) => {
if (!res.ok) throw await res.json();
return res.json();
})
.catch((err) => {
error = err.detail;
console.log(err);
return null;
});
if (error) {
throw error;
}
return res;
};
export const deleteMemoryById = async (token: string, id: string) => {
let error = null;
const res = await fetch(`${WEBUI_API_BASE_URL}/memories/${id}`, {
method: 'DELETE',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
authorization: `Bearer ${token}`
}
})
.then(async (res) => {
if (!res.ok) throw await res.json();
return res.json();
})
.then((json) => {
return json;
})
.catch((err) => {
error = err.detail;
console.log(err);
return null;
});
if (error) {
throw error;
}
return res;
};
export const deleteMemoriesByUserId = async (token: string) => {
let error = null;
const res = await fetch(`${WEBUI_API_BASE_URL}/memories/user`, {
method: 'DELETE',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
authorization: `Bearer ${token}`
}
})
.then(async (res) => {
if (!res.ok) throw await res.json();
return res.json();
})
.then((json) => {
return json;
})
.catch((err) => {
error = err.detail;
console.log(err);
return null;
});
if (error) {
throw error;
}
return res;
};
+34 -3
View File
@@ -1,4 +1,5 @@
import { OLLAMA_API_BASE_URL } from '$lib/constants';
import { promptTemplate } from '$lib/utils';
export const getOllamaUrls = async (token: string = '') => {
let error = null;
@@ -144,7 +145,7 @@ export const generateTitle = async (
) => {
let error = null;
template = template.replace(/{{prompt}}/g, prompt);
template = promptTemplate(template, prompt);
console.log(template);
@@ -158,7 +159,11 @@ export const generateTitle = async (
body: JSON.stringify({
model: model,
prompt: template,
stream: false
stream: false,
options: {
// Restrict the number of tokens generated to 50
num_predict: 50
}
})
})
.then(async (res) => {
@@ -177,7 +182,7 @@ export const generateTitle = async (
throw error;
}
return res?.response ?? 'New Chat';
return res?.response.replace(/["']/g, '') ?? 'New Chat';
};
export const generatePrompt = async (token: string = '', model: string, conversation: string) => {
@@ -219,6 +224,32 @@ export const generatePrompt = async (token: string = '', model: string, conversa
return res;
};
export const generateEmbeddings = async (token: string = '', model: string, text: string) => {
let error = null;
const res = await fetch(`${OLLAMA_API_BASE_URL}/api/embeddings`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify({
model: model,
prompt: text
})
}).catch((err) => {
error = err;
return null;
});
if (error) {
throw error;
}
return res;
};
export const generateTextCompletion = async (token: string = '', model: string, text: string) => {
let error = null;
+80 -7
View File
@@ -1,4 +1,72 @@
import { OPENAI_API_BASE_URL } from '$lib/constants';
import { promptTemplate } from '$lib/utils';
export const getOpenAIConfig = async (token: string = '') => {
let error = null;
const res = await fetch(`${OPENAI_API_BASE_URL}/config`, {
method: 'GET',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
...(token && { authorization: `Bearer ${token}` })
}
})
.then(async (res) => {
if (!res.ok) throw await res.json();
return res.json();
})
.catch((err) => {
console.log(err);
if ('detail' in err) {
error = err.detail;
} else {
error = 'Server connection failed';
}
return null;
});
if (error) {
throw error;
}
return res;
};
export const updateOpenAIConfig = async (token: string = '', enable_openai_api: boolean) => {
let error = null;
const res = await fetch(`${OPENAI_API_BASE_URL}/config/update`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
...(token && { authorization: `Bearer ${token}` })
},
body: JSON.stringify({
enable_openai_api: enable_openai_api
})
})
.then(async (res) => {
if (!res.ok) throw await res.json();
return res.json();
})
.catch((err) => {
console.log(err);
if ('detail' in err) {
error = err.detail;
} else {
error = 'Server connection failed';
}
return null;
});
if (error) {
throw error;
}
return res;
};
export const getOpenAIUrls = async (token: string = '') => {
let error = null;
@@ -210,10 +278,12 @@ export const generateOpenAIChatCompletion = async (
token: string = '',
body: object,
url: string = OPENAI_API_BASE_URL
) => {
): Promise<[Response | null, AbortController]> => {
const controller = new AbortController();
let error = null;
const res = await fetch(`${url}/chat/completions`, {
signal: controller.signal,
method: 'POST',
headers: {
Authorization: `Bearer ${token}`,
@@ -230,13 +300,14 @@ export const generateOpenAIChatCompletion = async (
throw error;
}
return res;
return [res, controller];
};
export const synthesizeOpenAISpeech = async (
token: string = '',
speaker: string = 'alloy',
text: string = ''
text: string = '',
model: string = 'tts-1'
) => {
let error = null;
@@ -247,7 +318,7 @@ export const synthesizeOpenAISpeech = async (
'Content-Type': 'application/json'
},
body: JSON.stringify({
model: 'tts-1',
model: model,
input: text,
voice: speaker
})
@@ -273,7 +344,7 @@ export const generateTitle = async (
) => {
let error = null;
template = template.replace(/{{prompt}}/g, prompt);
template = promptTemplate(template, prompt);
console.log(template);
@@ -292,7 +363,9 @@ export const generateTitle = async (
content: template
}
],
stream: false
stream: false,
// Restricting the max tokens to 50 to avoid long titles
max_tokens: 50
})
})
.then(async (res) => {
@@ -311,5 +384,5 @@ export const generateTitle = async (
throw error;
}
return res?.choices[0]?.message?.content ?? 'New Chat';
return res?.choices[0]?.message?.content.replace(/["']/g, '') ?? 'New Chat';
};
+113 -6
View File
@@ -32,9 +32,16 @@ type ChunkConfigForm = {
chunk_overlap: number;
};
type YoutubeConfigForm = {
language: string[];
translation?: string | null;
};
type RAGConfigForm = {
pdf_extract_images: boolean;
chunk: ChunkConfigForm;
pdf_extract_images?: boolean;
chunk?: ChunkConfigForm;
web_loader_ssl_verification?: boolean;
youtube?: YoutubeConfigForm;
};
export const updateRAGConfig = async (token: string, payload: RAGConfigForm) => {
@@ -123,6 +130,7 @@ export const getQuerySettings = async (token: string) => {
type QuerySettings = {
k: number | null;
r: number | null;
template: string | null;
};
@@ -220,6 +228,37 @@ export const uploadWebToVectorDB = async (token: string, collection_name: string
return res;
};
export const uploadYoutubeTranscriptionToVectorDB = async (token: string, url: string) => {
let error = null;
const res = await fetch(`${RAG_API_BASE_URL}/youtube`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
authorization: `Bearer ${token}`
},
body: JSON.stringify({
url: url
})
})
.then(async (res) => {
if (!res.ok) throw await res.json();
return res.json();
})
.catch((err) => {
error = err.detail;
console.log(err);
return null;
});
if (error) {
throw error;
}
return res;
};
export const queryDoc = async (
token: string,
collection_name: string,
@@ -346,10 +385,10 @@ export const resetVectorDB = async (token: string) => {
return res;
};
export const getEmbeddingModel = async (token: string) => {
export const getEmbeddingConfig = async (token: string) => {
let error = null;
const res = await fetch(`${RAG_API_BASE_URL}/embedding/model`, {
const res = await fetch(`${RAG_API_BASE_URL}/embedding`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
@@ -373,14 +412,82 @@ export const getEmbeddingModel = async (token: string) => {
return res;
};
type OpenAIConfigForm = {
key: string;
url: string;
};
type EmbeddingModelUpdateForm = {
openai_config?: OpenAIConfigForm;
embedding_engine: string;
embedding_model: string;
};
export const updateEmbeddingModel = async (token: string, payload: EmbeddingModelUpdateForm) => {
export const updateEmbeddingConfig = async (token: string, payload: EmbeddingModelUpdateForm) => {
let error = null;
const res = await fetch(`${RAG_API_BASE_URL}/embedding/model/update`, {
const res = await fetch(`${RAG_API_BASE_URL}/embedding/update`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify({
...payload
})
})
.then(async (res) => {
if (!res.ok) throw await res.json();
return res.json();
})
.catch((err) => {
console.log(err);
error = err.detail;
return null;
});
if (error) {
throw error;
}
return res;
};
export const getRerankingConfig = async (token: string) => {
let error = null;
const res = await fetch(`${RAG_API_BASE_URL}/reranking`, {
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.log(err);
error = err.detail;
return null;
});
if (error) {
throw error;
}
return res;
};
type RerankingModelUpdateForm = {
reranking_model: string;
};
export const updateRerankingConfig = async (token: string, payload: RerankingModelUpdateForm) => {
let error = null;
const res = await fetch(`${RAG_API_BASE_URL}/reranking/update`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
+102
View File
@@ -0,0 +1,102 @@
import { EventSourceParserStream } from 'eventsource-parser/stream';
import type { ParsedEvent } from 'eventsource-parser';
type TextStreamUpdate = {
done: boolean;
value: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
citations?: any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
error?: any;
};
// createOpenAITextStream takes a responseBody with a SSE response,
// and returns an async generator that emits delta updates with large deltas chunked into random sized chunks
export async function createOpenAITextStream(
responseBody: ReadableStream<Uint8Array>,
splitLargeDeltas: boolean
): Promise<AsyncGenerator<TextStreamUpdate>> {
const eventStream = responseBody
.pipeThrough(new TextDecoderStream())
.pipeThrough(new EventSourceParserStream())
.getReader();
let iterator = openAIStreamToIterator(eventStream);
if (splitLargeDeltas) {
iterator = streamLargeDeltasAsRandomChunks(iterator);
}
return iterator;
}
async function* openAIStreamToIterator(
reader: ReadableStreamDefaultReader<ParsedEvent>
): AsyncGenerator<TextStreamUpdate> {
while (true) {
const { value, done } = await reader.read();
if (done) {
yield { done: true, value: '' };
break;
}
if (!value) {
continue;
}
const data = value.data;
if (data.startsWith('[DONE]')) {
yield { done: true, value: '' };
break;
}
try {
const parsedData = JSON.parse(data);
console.log(parsedData);
if (parsedData.error) {
yield { done: true, value: '', error: parsedData.error };
break;
}
if (parsedData.citations) {
yield { done: false, value: '', citations: parsedData.citations };
continue;
}
yield { done: false, value: parsedData.choices?.[0]?.delta?.content ?? '' };
} catch (e) {
console.error('Error extracting delta from SSE event:', e);
}
}
}
// streamLargeDeltasAsRandomChunks will chunk large deltas (length > 5) into random sized chunks between 1-3 characters
// This is to simulate a more fluid streaming, even though some providers may send large chunks of text at once
async function* streamLargeDeltasAsRandomChunks(
iterator: AsyncGenerator<TextStreamUpdate>
): AsyncGenerator<TextStreamUpdate> {
for await (const textStreamUpdate of iterator) {
if (textStreamUpdate.done) {
yield textStreamUpdate;
return;
}
if (textStreamUpdate.citations) {
yield textStreamUpdate;
continue;
}
let content = textStreamUpdate.value;
if (content.length < 5) {
yield { done: false, value: content };
continue;
}
while (content != '') {
const chunkSize = Math.min(Math.floor(Math.random() * 3) + 1, content.length);
const chunk = content.slice(0, chunkSize);
yield { done: false, value: chunk };
// Do not sleep if the tab is hidden
// Timers are throttled to 1s in hidden tabs
if (document?.visibilityState !== 'hidden') {
await sleep(5);
}
content = content.slice(chunkSize);
}
}
}
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+27
View File
@@ -115,6 +115,33 @@ export const getUsers = async (token: string) => {
return res ? res : [];
};
export const getUserById = async (token: string, userId: string) => {
let error = null;
const res = await fetch(`${WEBUI_API_BASE_URL}/users/${userId}`, {
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.log(err);
error = err.detail;
return null;
});
if (error) {
throw error;
}
return res;
};
export const deleteUserById = async (token: string, userId: string) => {
let error = null;
+7 -3
View File
@@ -83,9 +83,9 @@ export const downloadDatabase = async (token: string) => {
Authorization: `Bearer ${token}`
}
})
.then((response) => {
.then(async (response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
throw await response.json();
}
return response.blob();
})
@@ -100,7 +100,11 @@ export const downloadDatabase = async (token: string) => {
})
.catch((err) => {
console.log(err);
error = err;
error = err.detail;
return null;
});
if (error) {
throw error;
}
};
+5 -6
View File
@@ -22,7 +22,7 @@
</script>
<Modal bind:show>
<div class="px-5 py-4 dark:text-gray-300">
<div class="px-5 pt-4 dark:text-gray-300 text-gray-700">
<div class="flex justify-between items-start">
<div class="text-xl font-bold">
{$i18n.t('Whats New in')}
@@ -32,6 +32,7 @@
<button
class="self-center"
on:click={() => {
localStorage.version = $config.version;
show = false;
}}
>
@@ -56,10 +57,8 @@
</div>
</div>
<hr class=" dark:border-gray-800" />
<div class=" w-full p-4 px-5">
<div class=" overflow-y-scroll max-h-80">
<div class=" w-full p-4 px-5 text-gray-700 dark:text-gray-100">
<div class=" overflow-y-scroll max-h-80 scrollbar-hidden">
<div class="mb-3">
{#if changelog}
{#each Object.keys(changelog) as version}
@@ -109,7 +108,7 @@
localStorage.version = $config.version;
show = false;
}}
class=" px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-gray-100 transition rounded"
class=" px-4 py-2 bg-emerald-700 hover:bg-emerald-800 text-gray-100 transition rounded-lg"
>
<span class="relative">{$i18n.t("Okay, Let's Go!")}</span>
</button>

Some files were not shown because too many files have changed in this diff Show More