Compare commits

...

1053 Commits

Author SHA1 Message Date
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
velaton e318f92177 Update translation.json
Fixed some grammar mistakes
2024-04-24 17:12:02 +08: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
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
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
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
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
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
Timothy Jaeryang Baek 0399a69b73 Merge pull request #1498 from open-webui/dev
Create and publish Docker images with specific build args / build-main-image (linux/amd64) (push) Failing after 1m4s
Create and publish Docker images with specific build args / build-main-image (linux/arm64) (push) Failing after 1m10s
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 1m8s
Create and publish Docker images with specific build args / build-cuda-image (linux/arm64) (push) Failing after 59s
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 1m1s
Create and publish Docker images with specific build args / build-ollama-image (linux/arm64) (push) Failing after 1m6s
Create and publish Docker images with specific build args / merge-ollama-images (push) Has been skipped
Update CHANGELOG.md
2024-04-10 15:41:12 -07:00
Timothy J. Baek 9e726a32e6 Update CHANGELOG.md 2024-04-10 15:40:47 -07:00
Timothy Jaeryang Baek 78284e49d7 Merge pull request #1488 from open-webui/dev
0.1.118
2024-04-10 15:38:47 -07:00
Timothy J. Baek 64a6db4b55 Update package-lock.json 2024-04-10 15:38:15 -07:00
Timothy J. Baek 16c9042318 chore: formatting 2024-04-10 15:36:43 -07:00
Timothy J. Baek 7a47ba14f7 doc: changelog 2024-04-10 15:35:32 -07:00
Timothy Jaeryang Baek 988123a2c8 Merge pull request #1496 from cheahjs/fix/missing-ollama-cuda-tags
fix: missing ollama cuda tags
2024-04-10 13:01:45 -07:00
Jun Siang Cheah 3a661fda1a fix: missing ollama/cuda tags from #1495 2024-04-10 20:58:26 +01:00
Timothy Jaeryang Baek a85e93f1f9 Merge pull request #1495 from cheahjs/feat/parallelize-docker-build
feat: parallelize docker build
2024-04-10 12:53:37 -07:00
Jun Siang Cheah 7050d53718 build ollama and cuda tags 2024-04-10 20:41:36 +01:00
Jun Siang Cheah cd91d8a987 run apt install first for better potential layer caching 2024-04-10 20:25:52 +01:00
Jun Siang Cheah eddaa7fa89 cross compile node 2024-04-10 20:25:52 +01:00
Jun Siang Cheah 550fc63ebd feat: parallelize x86/arm docker builds 2024-04-10 20:25:52 +01:00
Timothy J. Baek 57a81d70c1 Update README.md 2024-04-10 01:34:25 -07:00
Timothy J. Baek 295472fca1 chore: formatting 2024-04-10 01:27:19 -07:00
Timothy J. Baek a3e41db8d7 chore: formatting 2024-04-10 01:26:23 -07:00
Timothy Jaeryang Baek 546efe0d7b Merge pull request #1489 from jannikstdl/patch-1
README.md Dockersection formatting and wording fix
2024-04-10 01:23:16 -07:00
Jannik S 27f01b0bc8 Update README.md 2024-04-10 10:20:52 +02:00
Jannik S 62ec2651ba README.md Dockersection formatting and wording fix 2024-04-10 10:14:54 +02:00
Timothy Jaeryang Baek b9cadff16b Merge pull request #1419 from lainedfles/embedding-model-fix-and-manual-update
feat: improve embedding model update & resolve network dependency
2024-04-10 01:10:07 -07:00
Timothy J. Baek c0d273f162 refac 2024-04-10 01:06:57 -07:00
Timothy J. Baek 098ba6ea4e refac: frontend 2024-04-10 01:01:42 -07:00
Timothy J. Baek 582d11f191 refac: RAG_EMBEDDING_MODEL_PATH removed 2024-04-10 00:59:05 -07:00
Timothy J. Baek cb2158a794 fix 2024-04-10 00:51:16 -07:00
Timothy J. Baek abfcceecef refac 2024-04-10 00:46:09 -07:00
Timothy J. Baek f4b87ecb23 refac 2024-04-10 00:33:45 -07:00
Timothy J. Baek 48aad65514 refac 2024-04-09 23:54:20 -07:00
Timothy J. Baek cbb21a148d fix: async version check 2024-04-09 23:03:05 -07:00
Timothy Jaeryang Baek 2f6e683163 Merge pull request #1476 from buroa/dev
fix: support batching chromadb
2024-04-09 22:53:51 -07:00
Timothy Jaeryang Baek 1448c32fdf Merge pull request #1472 from shivaraj-bh/static-dir
feat: configurable `STATIC_DIR`; fix: mount `CACHE_DIR` to the `/cache` endpoint
2024-04-09 22:53:21 -07:00
Timothy J. Baek 0a3b99b94a chore: docker build workflow 2024-04-09 20:46:42 -07:00
Steven Kreitzer 0bae789d39 fix: support batching chromadb 2024-04-09 10:13:29 -05:00
shivaraj-bh 304bf9d9b1 feat: configurable STATIC_DIR; fix: mount CACHE_DIR to the /cache endpoint 2024-04-09 16:04:55 +05:30
Timothy Jaeryang Baek 839efa4443 Merge pull request #1464 from jmferrer/allow-using-external-ollama
Allow using external ollama service.
2024-04-08 22:19:41 -07:00
Timothy Jaeryang Baek 0a488c783f Merge pull request #1466 from jmferrer/make-chart-idempotent
Make chart idempotent.
2024-04-08 22:19:03 -07:00
jmferrerm d6275ee941 Make chart idempotent. 2024-04-09 07:02:45 +02:00
jmferrerm 2da7dd67ea Allow using external ollama service. 2024-04-09 06:43:08 +02:00
lainedfles 506a061387 Merge branch 'dev' into embedding-model-fix-and-manual-update 2024-04-08 14:57:54 -06:00
Timothy J. Baek 1a2971ae7b Update docker-build.yaml 2024-04-08 13:36:50 -07:00
Timothy J. Baek da9a54288e fix: styling 2024-04-08 03:11:00 -07:00
Timothy J. Baek 28c8b5841c fix: styling 2024-04-08 03:10:31 -07:00
Timothy J. Baek e48cdf63d9 feat: better annotation 2024-04-08 03:08:30 -07:00
Timothy J. Baek a649dc80c0 Update Dockerfile 2024-04-08 01:40:03 -07:00
Timothy Jaeryang Baek 733d69425e Merge pull request #1457 from aguvener/patch-1
fix: wording translation
2024-04-08 00:43:49 -07:00
Timothy Jaeryang Baek e844e7f708 Merge pull request #1165 from jannikstdl/dockerfile-optimisation
refac: Dockerfile
2024-04-08 00:43:08 -07:00
Jannik S 3b3d0cce1e Merge branch 'dev' into dockerfile-optimisation 2024-04-08 09:15:00 +02:00
aguvener b07641e58a fix: wording translation 2024-04-08 10:01:39 +03:00
Timothy J. Baek 72110c293a refac: admin panel styling 2024-04-07 01:52:58 -07:00
Timothy J. Baek f64ac3269f fix: share chat permission issue 2024-04-07 01:21:12 -07:00
Timothy J. Baek eb5ed905eb feat: close dragged overlay with esc 2024-04-07 01:03:16 -07:00
Timothy J. Baek 4207f80ce9 feat: close model on esc 2024-04-07 00:57:23 -07:00
Timothy J. Baek 073aecd427 refac: styling 2024-04-07 00:31:59 -07:00
Timothy Jaeryang Baek 3e1c679f2d Merge pull request #1435 from cheahjs/fix/build-docker-tag
feat: trigger docker build after release
2024-04-07 00:29:49 -07:00
Timothy J. Baek 47aeab81d8 refac: styling 2024-04-07 00:05:13 -07:00
Timothy J. Baek f4e165d028 chore: comments removed 2024-04-07 00:00:50 -07:00
Timothy Jaeryang Baek 02d3fb427b Merge pull request #1386 from dannyl1u/feat/profile-image-initials
feat: default profile image with user initials
2024-04-06 23:59:20 -07:00
Timothy J. Baek 117e07b0d4 Update languages.json 2024-04-06 23:57:55 -07:00
Timothy J. Baek efa6aa4b4c Update languages.json 2024-04-06 23:53:01 -07:00
Timothy J. Baek c73e8916ed chore: formatting 2024-04-06 23:52:02 -07:00
Timothy J. Baek df2cb16086 refac: styling 2024-04-06 23:49:25 -07:00
Timothy J. Baek f267f3f7b0 refac 2024-04-06 23:16:29 -07:00
Timothy Jaeryang Baek 8d8075e81f Merge pull request #1447 from sammcj/en-international
feat(i18n): add international English (en-GB) localisation
2024-04-06 22:44:06 -07:00
Timothy J. Baek 0a403eb129 Update languages.json 2024-04-06 22:43:48 -07:00
Sam McLeod f74642df1b feat(i18n): add international English (en-GB) localisation 2024-04-07 13:57:04 +10:00
Timothy Jaeryang Baek 782cce7c44 Merge pull request #1340 from joequant/main
allow version to work with -rc tag
2024-04-06 18:57:41 -07:00
Timothy J. Baek 395ca82175 refac: '-rc' tag handling 2024-04-06 18:55:51 -07:00
Danny Liu 663b5adaf2 Merge pull request #3 from lainedfles/feat/profile-image-initials
Fix: Restore Gravatar functionality, add button initials, toast duration
2024-04-06 16:37:09 -07:00
Self Denial 924ebf035b Fix: Restore Gravatar functionality, add button initials, toast duration
- Restore Gravatar functionality
- Add new button for "Use Initials"
- Set both buttons to use text-left class
- Update toast property autoClose to duration (wrong library, my bad!)
- Update toast messages to clarify that this isn't "Gravatar" but "avatar"
- Add i18n text to en-US/translation.json
2024-04-06 16:04:05 -06:00
Timothy Jaeryang Baek fafb8cd263 Merge pull request #1439 from justinh-rahb/rocm-compose
Add AMD Docker Compose config file
2024-04-06 13:33:21 -07:00
Timothy J. Baek 8110a872d5 fix: wording 2024-04-06 13:29:39 -07:00
Timothy Jaeryang Baek 331fe04df7 Merge pull request #1445 from open-webui/dev
dev
2024-04-06 13:21:15 -07:00
Timothy Jaeryang Baek aed4763bfe Merge pull request #1443 from aguvener/main
feat: Added tr-TR translation
2024-04-06 13:15:44 -07:00
aguvener 8d0f3fbde9 added tr-TR to languages.json 2024-04-06 19:03:59 +03:00
aguvener 318d4d1ce1 Create translation.json
Created Turkish translation file
2024-04-06 19:00:23 +03:00
Self Denial ec530ac9f8 format fix 2024-04-06 04:38:34 -06:00
Self Denial 11741ea7f0 Tooltip info & warn. Detect file path during update. Add translation.
* Tooltips added to show full model name and warning regarding vector storage
* Send toast error and return early if more than a single front slash is detected
* Extend toast duration for model update action
* Add i18n en_US translation
* Remove commented code copied from existing function
2024-04-06 04:22:48 -06:00
Danny Liu bee0338763 captalize Initial for improved clarity 2024-04-06 02:23:32 -07:00
Timothy Jaeryang Baek 073f06d449 refac: cleaner tag 2024-04-06 04:06:47 -05:00
Timothy J. Baek 5a787ab2c5 refac: pdf styling 2024-04-06 02:04:28 -07:00
Timothy J. Baek 81dbc65853 refac: pdf generation 2024-04-06 01:54:59 -07:00
Danny Liu 8a7075c3bf style: npm run format 2024-04-06 01:13:22 -07:00
Danny Liu 78565e554b notify user with toast.info() + update toast message 2024-04-06 01:12:51 -07:00
Danny Liu 7081755e19 Merge pull request #2 from lainedfles/feat/profile-image-initials-fixes
Feat/profile image initials fixes
2024-04-06 01:12:11 -07:00
Self Denial cf54adf5c4 Toast error consistency 2024-04-05 23:01:48 -06:00
Self Denial ae9922a2cd Re-word account creation error to be more descriptive 2024-04-05 22:58:40 -06:00
Self Denial bad7dca51e Move login page toast error to the bottom of page and enable i18n for translation 2024-04-05 22:43:42 -06:00
Self Denial 69716a5cec Revert "omit canvas spoofing toast.error for signups"
This reverts commit 1af62a70f0.
2024-04-05 22:31:40 -06:00
Danny Liu 1af62a70f0 omit canvas spoofing toast.error for signups 2024-04-05 21:16:48 -07:00
Danny Liu 5694f16624 style: run npm run format 2024-04-05 21:02:02 -07:00
Danny Liu a68b95c95f Merge pull request #1 from lainedfles/feat/profile-image-initials-rfp
Feat/profile image initials with fix for rfp & canvas spoofing
2024-04-05 21:00:48 -07:00
Justin Hayes f34b9733e3 Add Docker tag variables 2024-04-05 23:48:16 -04:00
Justin Hayes 8db03f3ab2 Add variables 2024-04-05 23:46:20 -04:00
Timothy Jaeryang Baek d001d7afb1 Merge pull request #1436 from lainedfles/feat/litellm-local-cost-map
Use locally bundled version of the LiteLLM cost map json
2024-04-05 17:26:20 -07:00
Timothy Jaeryang Baek 183b84beae Merge pull request #1438 from MurielLima/main
feat: translate portuguese brazil
2024-04-05 17:24:14 -07:00
Justin Hayes 075dddf3d3 Add AMD docker compose file 2024-04-05 20:11:33 -04:00
Muriel.Lima 7d64ada43e feat: translate portuguese brazil 2024-04-05 19:45:10 -03:00
Self Denial 802eb3beec Use locally bundled version of the LiteLLM cost map json
Intended to avoid repetitive startup connections by setting `LITELLM_LOCAL_MODEL_COST_MAP="True"`
2024-04-05 16:27:31 -06:00
Self Denial ac9308dbed Introduce canvasPixelTest() intended to validate canvas functionality
Browsers and plugins that spoof canvas data produce corrupt images. In attempt to mitigate:

* Add canvasPixelTest() to test a single pixel and test the RGB values
* Test canvasPixelTest() inside generateInitialsImage() and use default `/user.png` if failure detected
* Call canvasPixelTest() directly within settings to avoid setting an invalid image
* Use toast.error() with 10 second autoClose
2024-04-05 16:04:00 -06:00
Jun Siang Cheah b7ced4e4f1 feat: trigger docker build after release 2024-04-05 20:29:11 +01:00
Jannik S 536fd347b9 Merge pull request #4 from lainedfles/dockerfile-optimisation-dev
Set cudnn LD_LIBRARY_PATH to fix whisper inference
2024-04-05 08:23:06 +02:00
Danny Liu c8f7bb990c code style: npm run format 2024-04-04 20:07:52 -07:00
Danny Liu b8790200e9 refac: code style 2024-04-04 20:05:39 -07:00
Danny Liu 4200ad111c handle names with trailing whitespace 2024-04-04 19:56:23 -07:00
Self Denial 0f90332e61 Set cudnn LD_LIBRARY_PATH to fix whisper inference 2024-04-04 20:08:14 -06:00
Timothy Jaeryang Baek f87805b46f Merge pull request #1424 from open-webui/dev
fix
2024-04-04 17:40:53 -07:00
Timothy Jaeryang Baek 7a7d1931d9 Merge pull request #1423 from slash-proc/fix_helm_ollama_base_url
remove deprecated /api from ollama base url
2024-04-04 17:39:21 -07:00
Timothy J. Baek e61e1b079f fix: file upload issue 2024-04-04 17:38:59 -07:00
Doug Danat 7813c3316f remove deprecated /api from ollama base url 2024-04-04 23:57:32 +02:00
Danny Liu ac470e64e0 npm run format 2024-04-04 13:26:00 -07:00
Danny Liu c52cc46d2c feat: initial avatar set to first letter of firstname, first letter of lastname 2024-04-04 13:23:59 -07:00
Danny Liu a2bd9b8639 style: npm run format 2024-04-04 12:10:45 -07:00
Danny Liu 0c43897f3d refac: move generateInitialsImage function to utils 2024-04-04 12:09:07 -07:00
Danny Liu 4195af4942 pass generated profile image in signup api call 2024-04-04 12:08:20 -07:00
Self Denial 9f82f5abba Formatting... 2024-04-04 12:09:48 -06:00
Self Denial 075fbedb02 More format fixes 2024-04-04 12:07:42 -06:00
Self Denial bcf79c8366 Format fixes 2024-04-04 12:02:48 -06:00
Self Denial 3b66aa55c0 Improve embedding model update & resolve network dependency
* Add config variable RAG_EMBEDDING_MODEL_AUTO_UPDATE to control update behavior
* Add RAG utils embedding_model_get_path() function to output the filesystem path in addition to update of the model using huggingface_hub
* Update and utilize existing RAG functions in main: get_embedding_model() & update_embedding_model()
* Add GUI setting to execute manual update process
2024-04-04 11:01:23 -06:00
Danny Liu 3b06096c52 run npm run lint:backend 2024-04-04 01:10:51 -07:00
Jannik Streidl a602089b64 Added preload if embedding model in CUDA mode 2024-04-04 10:06:29 +02:00
Danny Liu 8d1db9a1c0 feat: api endpoint to receive profile_image_uirl on signup 2024-04-03 22:36:27 -07:00
Timothy Jaeryang Baek 46774aa5cd Merge pull request #1416 from open-webui/dev
Create and publish a Docker image / build-and-push-image (push) Failing after 56s
0.1.117
2024-04-03 21:43:17 -07:00
Timothy J. Baek 62392aa88a Update CHANGELOG.md 2024-04-03 21:37:15 -07:00
Timothy J. Baek c32d41b47f refac: about 2024-04-03 21:24:57 -07:00
Timothy Jaeryang Baek 9404b6135a Merge pull request #1401 from theasp/add-dynamic-manifest
feat: Allow overriding application name in manifest.json
2024-04-03 20:45:51 -07:00
Timothy J. Baek 8caad59cb4 feat: allow webui name customisation 2024-04-03 20:45:23 -07:00
Timothy J. Baek 21132420d8 Update Dockerfile 2024-04-03 20:44:18 -07:00
Timothy J. Baek c89070797c refac 2024-04-03 20:43:55 -07:00
Timothy J. Baek 1f85354856 feat: stylised pdf 2024-04-03 20:35:32 -07:00
Timothy J. Baek bfd066cc2f fix: share chat modal 2024-04-03 19:45:08 -07:00
Timothy J. Baek 000bea84ae feat: chat pdf download 2024-04-03 19:30:25 -07:00
Timothy J. Baek 944efd2cd8 feat: sanitise response content 2024-04-03 10:57:58 -07:00
Timothy J. Baek 4a09342a71 chore: npm audit fix 2024-04-03 10:26:24 -07:00
Timothy Jaeryang Baek aad13607c0 Merge pull request #1403 from helmanofer/main
Added boto3 to  requirements.txt
2024-04-03 10:21:02 -07:00
Timothy Jaeryang Baek 1509c2c2ee Merge pull request #1406 from jannikstdl/fix-whitemode-onhover
Fix hover in whitemode
2024-04-03 10:20:04 -07:00
Timothy Jaeryang Baek d94bc21ac8 Merge pull request #1408 from Mmx233/main
fix: manually check the docs' filename
2024-04-03 10:19:10 -07:00
Mmx233 947c392f72 fix: manually check the docs' filename 2024-04-03 23:37:13 +08:00
Jannik Streidl 15d24a6a11 Fix hover in whitemode 2024-04-03 16:00:06 +02:00
Ofer Helman a3d6343dbe Update requirements.txt 2024-04-03 16:27:49 +03:00
Jannik Streidl ca8fd8af1d Merge branch 'dockerfile-optimisation' of https://github.com/jannikstdl/open-webui into dockerfile-optimisation 2024-04-03 11:44:18 +02:00
Jannik Streidl d0d01c95f9 possible fix for format-backend check 2024-04-03 11:43:13 +02:00
Jannik S f669c0e78e Merge branch 'dev' into dockerfile-optimisation 2024-04-03 11:37:46 +02:00
Jannik Streidl 33ad2381aa README instructions and build fixes 2024-04-03 11:34:25 +02:00
Ofer Helman 14fcf4d267 Update requirements.txt
In case of using bedrock with litellm import boto3 exception is raised
2024-04-03 11:44:01 +03:00
Andrew Phillips 83ad488e31 Do not use hardcoded manifest.json
Generate manifest.json dynamically, using MANIFEST_NAME and
MANIFEST_SHORT_NAME from the environment.
2024-04-02 16:08:10 -03:00
Timothy Jaeryang Baek fa61e738c3 Merge pull request #1306 from vaayne/feature/support_auth_by_api_key
Feature/support auth by api key
2024-04-02 10:09:27 -07:00
Timothy J. Baek 0aa4d305c7 chore: print statement removed 2024-04-02 10:07:44 -07:00
Timothy J. Baek 1066096b33 fix 2024-04-02 10:06:58 -07:00
Timothy J. Baek 398b2076cd refac 2024-04-02 10:05:53 -07:00
Timothy J. Baek fb516ea694 refac: styling 2024-04-02 09:58:34 -07:00
Timothy J. Baek b35cc36e19 chore: formatting 2024-04-02 09:42:45 -07:00
Timothy J. Baek 6d1ce99537 revert: auth page 2024-04-02 09:40:36 -07:00
Timothy J. Baek 7c5f6d71b3 refac 2024-04-02 09:39:55 -07:00
Timothy J. Baek e49e04c56a chore: formatting 2024-04-02 09:33:27 -07:00
Timothy J. Baek da8646cae9 refac 2024-04-02 09:27:35 -07:00
Timothy J. Baek ba0523cd69 refac: api_key field moved to user 2024-04-02 09:23:55 -07:00
Timothy J. Baek 38c34b4444 fix: import 2024-04-02 09:18:36 -07:00
Timothy J. Baek b11af9ea0e fix 2024-04-02 09:18:15 -07:00
Timothy Jaeryang Baek 56369fea3a Merge branch 'dev' into feature/support_auth_by_api_key 2024-04-02 09:12:19 -07:00
Timothy Jaeryang Baek 24fb77759e Merge pull request #1347 from cheahjs/feat/trusted-email-header
feat: allow authenticating with a trusted email header
2024-04-02 09:11:25 -07:00
Timothy Jaeryang Baek f9106cf394 Merge pull request #1364 from cheahjs/feat/local-sharing
feat: add local sharing of chats
2024-04-02 09:10:15 -07:00
Timothy J. Baek 807a60cccf fix: styling 2024-04-02 09:01:15 -07:00
Timothy J. Baek ac4675900e Merge branch 'feat/local-sharing' of https://github.com/cheahjs/open-webui-fork into pr/1364 2024-04-02 08:58:38 -07:00
Timothy J. Baek f7a1fc207a refac: wording 2024-04-02 08:58:03 -07:00
Timothy J. Baek b9b1d64bd5 refac: styling 2024-04-02 08:58:03 -07:00
Timothy J. Baek 7e6a00b009 refac: share chat page 2024-04-02 08:58:03 -07:00
Timothy J. Baek 5aad328040 refac: toast message wording 2024-04-02 08:58:03 -07:00
Timothy J. Baek 03a7f88dca chore: remove print statement 2024-04-02 08:58:03 -07:00
Timothy J. Baek f61869d90d fix: cascade shared chat delete 2024-04-02 08:58:03 -07:00
Timothy J. Baek 95505bc4c1 feat: chat cascade delete 2024-04-02 08:58:03 -07:00
Timothy J. Baek eca59f759d fix: share chat modal 2024-04-02 08:58:03 -07:00
Timothy J. Baek 9975cb17a9 feat: update shared chat 2024-04-02 08:58:03 -07:00
Timothy J. Baek 0b823f90e6 feat: delete shared chat link 2024-04-02 08:58:03 -07:00
Timothy J. Baek c0fff4c69f fix: typo 2024-04-02 08:58:03 -07:00
Timothy J. Baek 180dd3966b refac: share chat routes 2024-04-02 08:58:03 -07:00
Timothy J. Baek e4d101e550 fix: delete shared chat by id 2024-04-02 08:58:03 -07:00
Timothy J. Baek 88c5b7f495 refac: share chat model 2024-04-02 08:58:03 -07:00
Timothy J. Baek 4e9ca31146 Update chats.py 2024-04-02 08:58:03 -07:00
Timothy J. Baek 48e7376336 refac: shared chat user id 2024-04-02 08:58:03 -07:00
Timothy J. Baek 488301f150 Update 001_initial_schema.py 2024-04-02 08:58:03 -07:00
Timothy J. Baek 287c95e72d refac: dedicated shared chat page 2024-04-02 08:58:03 -07:00
Timothy J. Baek af5a7a35c0 refac: copy to clipboard message 2024-04-02 08:58:03 -07:00
Timothy J. Baek 5faa05a117 refac: share chat modal styling update 2024-04-02 08:58:03 -07:00
Jun Siang Cheah e273a99153 feat: migrate db schema for local sharing 2024-04-02 08:58:03 -07:00
Jun Siang Cheah 151055590d feat: add ability to run db migrations 2024-04-02 08:58:03 -07:00
Jun Siang Cheah 7978adbf45 feat: add frontend support for locally sharing chats 2024-04-02 08:58:03 -07:00
Jun Siang Cheah 94976e5ed3 feat: add backend functions for sharing chats 2024-04-02 08:58:03 -07:00
Timothy J. Baek 3a1d747677 refac: wording 2024-04-02 08:18:47 -07:00
Timothy J. Baek 7121465eda refac: styling 2024-04-02 08:12:55 -07:00
Timothy J. Baek 52e83891b4 refac: share chat page 2024-04-02 08:11:48 -07:00
Timothy J. Baek 456a78ada9 refac: toast message wording 2024-04-02 08:01:45 -07:00
Timothy J. Baek cd60dbe08c chore: remove print statement 2024-04-02 08:00:47 -07:00
Timothy J. Baek a0d932b986 fix: cascade shared chat delete 2024-04-02 08:00:26 -07:00
Timothy J. Baek 10cad60566 feat: chat cascade delete 2024-04-02 07:55:56 -07:00
Timothy J. Baek c6296e5108 fix: share chat modal 2024-04-02 07:45:33 -07:00
Timothy J. Baek dd9cbd0ab9 feat: update shared chat 2024-04-02 07:42:37 -07:00
Timothy J. Baek 865c268312 feat: delete shared chat link 2024-04-02 07:16:25 -07:00
Timothy J. Baek dcac8a773b fix: typo 2024-04-02 07:06:07 -07:00
Timothy J. Baek 96d75dfc1b refac: share chat routes 2024-04-02 07:04:29 -07:00
Timothy J. Baek 49428eb7ef fix: delete shared chat by id 2024-04-02 07:04:04 -07:00
Timothy J. Baek 6c0e3972dc refac: share chat model 2024-04-02 06:42:57 -07:00
Timothy J. Baek 458c317736 Update chats.py 2024-04-02 06:36:02 -07:00
Timothy J. Baek 98f68b8b08 refac: shared chat user id 2024-04-02 06:33:59 -07:00
Timothy J. Baek b76e934140 Update 001_initial_schema.py 2024-04-02 06:27:11 -07:00
Timothy J. Baek 0cdcc2deb6 refac: dedicated shared chat page 2024-04-02 06:17:51 -07:00
Timothy J. Baek 58992d592c refac: copy to clipboard message 2024-04-02 06:14:54 -07:00
Timothy J. Baek 04e172deac refac: share chat modal styling update 2024-04-02 06:12:45 -07:00
Jannik Streidl 9bcb37ea10 fixes and updates 2024-04-02 14:47:52 +02:00
Timothy J. Baek a363c1f2f1 fix: styling 2024-04-02 04:37:35 -07:00
Timothy Jaeryang Baek 6425e794f6 Merge pull request #1394 from Axodouble/patch-1
Update Dutch nl-NL translations again.
2024-04-02 03:40:26 -07:00
Timothy Jaeryang Baek f340178bb7 Merge pull request #1396 from open-webui/main
dev
2024-04-02 03:39:09 -07:00
Timothy J. Baek aa6c8b1bfd feat: ascii art on startup 2024-04-02 03:03:55 -07:00
Axodouble d1ca6b50d9 Update Dutch nl-NL translations again.
Updated all translations to have a Dutch translation.
2024-04-02 11:51:58 +02:00
Jannik S 099b1d066b Revert "Merge Updates & Dockerfile improvements" (#3)
This reverts commit 9763d885be.
2024-04-02 11:28:04 +02:00
lainedfles 9763d885be Merge Updates & Dockerfile improvements 2024-04-02 11:25:20 +02:00
Timothy J. Baek 57530d87f6 feat: /ollama head route 2024-04-02 02:03:13 -07:00
Timothy J. Baek 2c030218f8 fix: latex dollar sign issue 2024-04-01 19:25:47 -07:00
Danny Liu 6bb299ae25 run npm run format 2024-04-01 16:26:05 -07:00
Danny Liu a0a064f4c8 update initals avatar if user changes name 2024-04-01 16:23:54 -07:00
Danny Liu 40e1e212d4 feat: default profile image with user initials 2024-04-01 16:11:28 -07:00
Timothy J. Baek 5558514ff1 fix 2024-04-01 15:23:12 -07:00
Timothy Jaeryang Baek 83c7633acb Merge pull request from GHSA-9pgh-j74g-qj6m
Suggested mitigation for KL-CAN-2024-002.
2024-04-01 15:21:56 -07:00
Timothy Jaeryang Baek 6c3f2f8d38 Merge pull request #1382 from open-webui/main
dev
2024-04-01 14:16:35 -07:00
Timothy J. Baek d72653cdea fix: download allowed hosts 2024-04-01 14:01:05 -07:00
KoreLogic Disclosures 6c96361402 Suggested mitigation for KL-CAN-2024-002. 2024-04-01 15:55:14 -05:00
Timothy Jaeryang Baek 554e56687c Merge pull request from GHSA-39wr-r5vm-3jxj
fix: allowed hosts
2024-04-01 13:27:01 -07:00
Timothy J. Baek 77b1edcd0f fix: allowed hosts 2024-04-01 13:24:48 -07:00
Jun Siang Cheah d667faea33 feat: migrate db schema for local sharing 2024-04-01 11:13:02 +01:00
Jun Siang Cheah 4cb2cc62d2 feat: add ability to run db migrations 2024-04-01 11:12:46 +01:00
Timothy J. Baek 698bfcf87f fix: navbar styling 2024-04-01 01:48:44 -07:00
Timothy Jaeryang Baek edeff20e1d Merge pull request #1374 from open-webui/dev
fix
2024-03-31 21:04:43 -07:00
Timothy J. Baek eda157e303 fix: openai issue 2024-03-31 21:02:29 -07:00
Timothy J. Baek 653a0ff02f fix: katex overflow issue 2024-03-31 19:50:46 -07:00
Timothy Jaeryang Baek 8175a323e9 Merge pull request #1372 from cheahjs/chore/update-npm-format-scripts
chore: add format:backend to npm scripts
2024-03-31 15:34:51 -07:00
Jun Siang Cheah 11850b75c8 chore: add format:backend npm script to match ci 2024-03-31 22:13:39 +01:00
Jun Siang Cheah 562e40a7bd Merge branch 'dev' into feat/trusted-email-header 2024-03-31 22:08:58 +01:00
Jun Siang Cheah 0e3b7a11e3 chore: python formatting 2024-03-31 22:07:43 +01:00
Jun Siang Cheah 196f91d68c feat: add frontend support for locally sharing chats 2024-03-31 22:03:28 +01:00
Jun Siang Cheah bfbfdae1c5 feat: add backend functions for sharing chats 2024-03-31 22:02:40 +01:00
Timothy J. Baek a6c154d839 feat: rag context logging 2024-03-31 14:02:31 -07:00
Timothy Jaeryang Baek 7563619e26 Merge pull request #1368 from Patrice-Gaudicheau/fix/data-dir-handling
Update of main.py
2024-03-31 14:00:39 -07:00
Timothy J. Baek 1b5c92d66c revert: prompt suggestion change 2024-03-31 13:59:39 -07:00
Timothy Jaeryang Baek 2f23325c90 Merge branch 'dev' into fix/data-dir-handling 2024-03-31 13:57:34 -07:00
Patrice-Gaudicheau cef676429f Spellchecking 2024-03-31 22:50:17 +02:00
Timothy Jaeryang Baek a0935dec60 Merge branch 'dev' into feature/support_auth_by_api_key 2024-03-31 13:48:36 -07:00
Timothy Jaeryang Baek 587a8c5992 Merge pull request #1370 from lainedfles/logging-improvements
Improve logging.
2024-03-31 13:46:37 -07:00
Timothy J. Baek 4ddb7e124e fix: error message 2024-03-31 13:40:57 -07:00
Patrice-Gaudicheau 68cfdd89c4 Small simplification 2024-03-31 22:35:44 +02:00
Self Denial 144c9059a3 Improve logging. Move print() statements to appropiate log().
Add COMFYUI and WEBHOOK logging and associated environment variable
control. Add WEBHOOK payload & request debug logs.
2024-03-31 13:17:29 -06:00
Patrice-Gaudicheau ee38b3c84d Enhance DATA_DIR handling in main.py and docker-compose configuration 2024-03-31 20:43:09 +02:00
Timothy Jaeryang Baek 86aa2ca6cb Merge pull request #1363 from open-webui/dev
fix
2024-03-31 02:28:20 -07:00
Timothy J. Baek 1d7ca44017 fix: config data issue 2024-03-31 02:27:03 -07:00
Timothy J. Baek 174c082c69 chore: frontend formatting 2024-03-31 02:04:15 -07:00
Timothy J. Baek bbb63104ea chore: frontend format 2024-03-31 02:01:42 -07:00
Timothy J. Baek 43832d165f chore: frontend formatting 2024-03-31 01:59:10 -07:00
Timothy J. Baek d630485051 chore: delete test.json 2024-03-31 01:57:21 -07:00
Timothy J. Baek 784572590f chore: frontend i18n formatting 2024-03-31 01:54:54 -07:00
Timothy J. Baek 90a03c331d refac: ci 2024-03-31 01:51:13 -07:00
Timothy J. Baek b391ad12ae refac: format backend ci 2024-03-31 01:47:53 -07:00
Timothy J. Baek 6c2eb814ed Update format-backend.yaml 2024-03-31 01:43:52 -07:00
Timothy Jaeryang Baek 3b0cb7945f Merge pull request #1362 from open-webui/dev
Create and publish a Docker image / build-and-push-image (push) Failing after 52s
0.1.116
2024-03-31 01:17:32 -07:00
Timothy J. Baek 46a181042b Update CHANGELOG.md 2024-03-31 01:17:03 -07:00
Timothy J. Baek 5af8d0612a chore: py formatting 2024-03-31 01:13:39 -07:00
Timothy J. Baek d4fabeee3c doc: changelog
Co-Authored-By: 深度学习机器 <wuzsgdutee@163.com>
2024-03-31 01:11:18 -07:00
Timothy J. Baek e47d6ce1f6 refac: return only last 5 changelog 2024-03-31 01:10:57 -07:00
Timothy J. Baek 15f4153fda fix: openai isseu 2024-03-29 18:24:30 -07:00
Timothy J. Baek 1371e66ed9 fix: litellm title generation issue 2024-03-29 18:14:05 -07:00
Timothy J. Baek 2fbb92aceb fix: tag validation 2024-03-29 18:00:08 -07:00
Timothy J. Baek f96beeee8f fix: litellm issue 2024-03-29 17:55:40 -07:00
Timothy J. Baek 0c367412c3 feat: navbar ui update 2024-03-29 17:20:07 -07:00
Jun Siang Cheah 150152ddbd fix: accidental indent during format changed logic 2024-03-29 21:04:30 +00:00
Timothy J. Baek 12287f8680 chore: code formatting 2024-03-29 13:06:18 -07:00
Timothy J. Baek 047c9fe82c fix: styling 2024-03-29 13:02:38 -07:00
Timothy Jaeryang Baek ce20f05ef1 Merge pull request #1343 from asedmammad/fix/add-model-selector-to-playground
fix: Add new model selector to playground
2024-03-29 12:44:31 -07:00
Timothy J. Baek 242311aee1 fix: styling 2024-03-29 12:44:16 -07:00
Timothy Jaeryang Baek bbc34d9be5 Merge pull request #1339 from asedmammad/feat/chat-autocomplete-tags
feat: Chat autocomplete tags
2024-03-29 12:41:15 -07:00
Timothy Jaeryang Baek 09da5e71e2 Merge pull request #1348 from cheahjs/fix/format-actions-enforce
fix: enforce formatters on GitHub Actions
2024-03-29 12:12:40 -07:00
Timothy J. Baek 74638bbd6e fix: config json backward compatibility issue 2024-03-28 21:15:05 -07:00
Jun Siang Cheah f34fe49bdd fix: enforce formatters on GitHub Actions 2024-03-28 23:46:11 +00:00
Ased Mammad 50089710f3 fix: Add new model selector to playground 2024-03-29 00:19:53 +03:30
Joseph C Wang c9f17ecb3a allow version to work with -rc tag 2024-03-29 01:44:37 +08:00
Ased Mammad 4bf38e5287 feat: Add autocomplete to chat tags 2024-03-28 21:07:34 +03:30
Jun Siang Cheah 50f6addd6f feat: auto signup/login with WEBUI_AUTH_TRUSTED_EMAIL_HEADER 2024-03-28 10:34:57 +00:00
Timothy J. Baek c42cb438f9 fix: litellm model filter issue 2024-03-28 02:45:56 -07:00
Timothy J. Baek b93bdfb222 fix: theme issue 2024-03-28 02:44:16 -07:00
Timothy Jaeryang Baek c85a2e8cd4 Merge pull request #1329 from ConnorsApps/fix-pvc-storage-class
fix: Helm Chart storageClassName typo
2024-03-27 23:55:01 -07:00
Timothy Jaeryang Baek 46e3208cde Merge pull request #1325 from dannyl1u/feat/oled-dark-theme
feat: OLED dark theme
2024-03-27 23:54:07 -07:00
Timothy Jaeryang Baek c6bb0ded5e Merge pull request #1313 from asedmammad/feat/i18n-navigator-config
feat: Configurable i18n default translation language
2024-03-27 23:52:26 -07:00
Timothy J. Baek d187b1615a fix: language ordering 2024-03-27 23:51:26 -07:00
Timothy Jaeryang Baek 5e24e03fe5 Merge pull request #1323 from shing100/feat/ko-KR_translation
feat: add ko-KR translation
2024-03-27 23:50:35 -07:00
Timothy Jaeryang Baek 2fcc4aec4b Merge pull request #1316 from ryankupk/svelte-warnings
Update svelte.config.js to suppress unused CSS selector warnings
2024-03-27 23:49:42 -07:00
Danny Liu 67865fc5ad dynamically adjust --color-gray-950 value for OLED black sidebar 2024-03-27 22:39:47 -07:00
ConnorsApps 9ad097d265 fix: pvc storageClassName typo 2024-03-27 20:35:21 -04:00
Danny Liu 572eefe181 use 🌃 emoji for oled-dark option 2024-03-27 16:19:57 -07:00
Danny Liu cf44209730 refac: code style 2024-03-27 16:19:02 -07:00
Danny Liu dfeadf9595 ordering of themes in select menu, group dark themes together 2024-03-27 16:05:37 -07:00
Danny Liu 25c71d8ac2 Update theme options and persist OLED dark theme if selected 2024-03-27 16:04:34 -07:00
Timothy J. Baek 19d2121252 fix: docker issue 2024-03-27 13:08:43 -07:00
Danny Liu c24d9d3bea Add 'oled' theme option to themes list 2024-03-27 11:23:00 -07:00
Danny Liu 976c714063 feat: OLED dark theme 2024-03-27 10:50:30 -07:00
Lim Geun f87d5d3d9b add ko-KR translation 2024-03-27 23:05:45 +09:00
Jun Siang Cheah 29f13f34d3 feat: add WEBUI_AUTH_TRUSTED_EMAIL_HEADER for authenticating users by a trusted header
This is very yolo code, use at your own risk
2024-03-27 09:28:03 +00:00
Timothy Jaeryang Baek 7d45d2762f Merge pull request #1311 from AndrewRyanChama/arc/openaitick
Add wait for tick before scrolling down in openai
2024-03-26 21:51:04 -07:00
Timothy Jaeryang Baek e5408995d8 Merge pull request #1305 from changchiyou/feat/Teams_Incoming_Webhook
enhance: support Teams Incoming Webhook
2024-03-26 21:43:54 -07:00
changchiyou d69dfb7c8b feat: support google chat webhook
https://github.com/open-webui/open-webui/pull/1305/\#issuecomment-2021151237
2024-03-27 10:25:57 +08:00
ryankupk addee2f248 Update svelte.config.js to suppress unused CSS selector warnings 2024-03-26 23:07:01 +00:00
Ased Mammad 0c021e42f5 rename config key to default_locale 2024-03-26 23:15:51 +03:30
Ased Mammad 64e6003627 refac: Remove translation values for en-US
Translation values for en-US are not necessary, the keys will be
used as fallback.
2024-03-26 23:04:01 +03:30
Ased Mammad 26121c5d88 wip: Set default language from config 2024-03-26 23:01:23 +03:30
Andrew Ryan d245b756a3 Add wait for tick before scrolling down in openai
We had this wait on ollama but not for openai, causing it to fail
to scroll down in certain cases.

This fixes the issue.
2024-03-26 11:46:22 -07:00
liu.vaayne b4b56f9c85 frontend support api key 2024-03-26 18:24:14 +08:00
liu.vaayne 81e928030f backend support api key 2024-03-26 18:22:17 +08:00
Chris 0b62bbb52e Merge branch 'dev' into feat/Teams_Incoming_Webhook 2024-03-26 16:59:42 +08:00
Timothy J. Baek cb364f0ac7 feat: focus search input by default 2024-03-26 01:51:24 -07:00
Timothy J. Baek d12a7247bc fix: missing import 2024-03-26 01:47:33 -07:00
Timothy J. Baek 941bb7c603 refac: chat[id] page 2024-03-26 01:45:25 -07:00
Timothy J. Baek 3edc547389 feat: title auto generation for external models 2024-03-26 00:59:57 -07:00
changchiyou 427ca4e3f5 refactor: dynamically swap activitySubtitle and activityImage if CUSTOM_NAME has been set 2024-03-26 15:45:36 +08:00
changchiyou 5eac5c54f8 feat: Teams MessageCard
refer to https://learn.microsoft.com/en-us/microsoftteams/platform/webhooks-and-connectors/how-to/connectors-using\?tabs\=cURL\#example-of-connector-message
2024-03-26 15:04:17 +08:00
Timothy Jaeryang Baek a1fc2f4df0 Merge pull request #1292 from ddanat-smm/dev
Add htm/html support for RAG documents
2024-03-25 23:51:20 -07:00
Timothy J. Baek 3688955c77 fix: encoding issue 2024-03-25 23:50:52 -07:00
Timothy J. Baek 6307adfba1 feat: better error handling 2024-03-25 23:47:08 -07:00
Timothy Jaeryang Baek 4f78acaa5c Merge pull request #1299 from jannikstdl/k8s-pvc-naming-fix
K8s fixes
2024-03-25 23:20:39 -07:00
Timothy J. Baek 7f405c74cd refac: rename 2024-03-25 23:20:16 -07:00
Timothy J. Baek 5d6cee0c58 feat: model selector w/ more info 2024-03-25 14:04:46 -07:00
Jannik S af366cf732 fix 2024-03-25 21:50:58 +01:00
Timothy J. Baek 32cb5f3ceb feat: external model info 2024-03-25 13:46:06 -07:00
Jannik S eecc7f3529 Deleted unused checks 2024-03-25 21:32:21 +01:00
Jannik S 8962d948cd Check if running on K8s to correctly allocate Ollama Base URL 2024-03-25 21:21:32 +01:00
Doug Danat c91a5d8b1f switch to using BeautifulSoup HTML loader so title is also captured 2024-03-25 11:26:18 +01:00
Doug Danat 77f4ffddc1 add htm/html to supported extensions in ui 2024-03-25 11:21:34 +01:00
Doug Danat 784a6ec85e include html langchain loader for RAG 2024-03-25 09:50:53 +01:00
Timothy J. Baek eb004ccfc2 refac: icon update 2024-03-24 23:28:25 -07:00
Timothy J. Baek c6f9e74477 feat: external model icon 2024-03-24 23:26:00 -07:00
Timothy J. Baek 302bd11b33 fix: pull model from selector 2024-03-24 23:11:55 -07:00
Timothy J. Baek c19ea89a1d feat: model download from model selector 2024-03-24 23:03:26 -07:00
Timothy Jaeryang Baek 9560f9196d Merge pull request #1283 from pazoff/dev
Fix spelling
2024-03-24 20:30:14 -05:00
Plamen Vatev 42bb1ec089 Fix spelling 2024-03-25 02:31:47 +02:00
Timothy Jaeryang Baek ac294a74e7 Merge pull request #1277 from open-webui/dev
Create and publish a Docker image / build-and-push-image (push) Failing after 1m1s
0.1.115
2024-03-24 18:20:08 -05:00
Timothy J. Baek 4c9598918a doc: changelog
Co-Author: Fixed the upload experimental feature
Co-Authored-By: rob <64106559+kroonen@users.noreply.github.com>
2024-03-24 16:12:07 -07:00
Timothy Jaeryang Baek ffa168211e Merge pull request #1237 from lainedfles/debug_print
Migrate to python logging module with env var control.
2024-03-24 18:04:27 -05:00
Timothy Jaeryang Baek 371dfc1143 Merge branch 'dev' into debug_print 2024-03-24 18:04:03 -05:00
Timothy Jaeryang Baek a1faa307b1 Merge pull request #1272 from anuraagdjain/feat/cancel-model-download
feat: cancel model download
2024-03-24 18:00:57 -05:00
Timothy J. Baek a4c4a0370e refac: transition 2024-03-24 15:55:03 -07:00
Timothy J. Baek 3e0aa29683 refac: transition 2024-03-24 15:43:03 -07:00
Timothy J. Baek df21a92542 fix: select 2024-03-24 15:31:09 -07:00
Timothy J. Baek b218b02d93 feat: custom model selector 2024-03-24 15:28:36 -07:00
Timothy J. Baek ff8a55a861 refac: rag api 2024-03-24 00:41:41 -07:00
Timothy J. Baek 7e0ea8f77d feat: RAG text ingestion(store) api 2024-03-24 00:40:27 -07:00
Jannik S c91c95431d Changed allocation in webui-deployment.yaml 2024-03-24 08:18:28 +01:00
Jannik S 1d64d31275 Updated PVC naming 2024-03-24 08:17:38 +01:00
Timothy J. Baek c2d6d3230b refac: reset vector db 2024-03-23 20:50:57 -07:00
Timothy J. Baek 8d108060d5 refac: styling 2024-03-23 18:08:33 -07:00
Timothy J. Baek 5cb6e9b0b4 refac: styling 2024-03-23 18:07:42 -07:00
Timothy J. Baek cea74eaf52 feat: light mode theme update 2024-03-23 18:05:36 -07:00
Timothy Jaeryang Baek adf9ccb5eb Merge pull request #1275 from open-webui/comfyui
feat: comfyui support
2024-03-23 19:01:51 -05:00
Timothy J. Baek 98624a406f feat: comfyui integration 2024-03-23 17:01:13 -07:00
Timothy J. Baek 862c96fcef feat: comfyui support 2024-03-23 15:38:59 -07:00
Timothy J. Baek cbaaacfb75 fix: styling 2024-03-23 13:36:11 -07:00
Timothy Jaeryang Baek 3e0d9ad74f Merge branch 'dev' into feat/cancel-model-download 2024-03-23 15:16:06 -05:00
Timothy J. Baek e008738f30 feat: cancel download from backend 2024-03-23 13:12:54 -07:00
Timothy J. Baek 244f34c24e refac: cancel download 2024-03-23 13:12:23 -07:00
Timothy J. Baek 642ca5a94a refac: ui 2024-03-23 12:46:06 -07:00
Timothy J. Baek 85187deb4b fix: languages order 2024-03-23 12:43:31 -07:00
Timothy Jaeryang Baek 3305ac5928 Merge pull request #1269 from pazoff/dev
added Italian, Portuguese and Japanese translations
2024-03-23 14:34:54 -05:00
Timothy Jaeryang Baek 51a4e49ae1 Merge pull request #1247 from changchiyou/enhance/zh_TW_translation
Enhance/zh tw translation
2024-03-23 14:34:28 -05:00
Timothy Jaeryang Baek 6c9f552733 Merge pull request #1271 from Axodouble/main
Added nl-NL (Dutch) Translations.
2024-03-23 14:33:54 -05:00
Anuraag Jain 7e6d499486 refac: remove conosle.log 2024-03-23 21:00:01 +02:00
Anuraag Jain d291821bf3 refac: delete button UI 2024-03-23 20:56:18 +02:00
Anuraag Jain 45311bfa15 Merge branch 'main' into feat/cancel-model-download
# Conflicts:
#	src/lib/components/chat/Settings/Models.svelte
2024-03-23 18:10:35 +02:00
changchiyou b03f4371d6 enhance: setting 2024-03-23 23:55:42 +08:00
Axodouble f662aab9e8 Finished Dutch translation. 2024-03-23 13:05:13 +01:00
Axodouble 129253d90d Added partial Dutch (Netherlands, NL) translations. 2024-03-23 12:23:05 +01:00
changchiyou 2d1b67561b enhance: routes/auth 2024-03-23 17:13:43 +08:00
changchiyou dca3dbbce6 enhance: admin 2024-03-23 17:07:35 +08:00
changchiyou e9f1a714e8 enhance: playground 2024-03-23 16:19:14 +08:00
Plamen Vatev d5b5155c20 add ja-JP (Japanese) translation 2024-03-23 07:29:07 +02:00
Plamen Vatev 6e79530e0e add Japanese translation 2024-03-23 07:27:24 +02:00
Plamen Vatev b0a2eb31ee add Portuguese translation 2024-03-23 07:00:40 +02:00
Plamen Vatev c0549498bf add Portuguese translation 2024-03-23 07:00:08 +02:00
Plamen Vatev f8a922e966 Merge branch 'open-webui:dev' into dev 2024-03-23 06:52:51 +02:00
Timothy J. Baek 5c1e3a460e fix: remove aiofiles dependency 2024-03-22 21:47:53 -07:00
Plamen Vatev bc04553a7c add Italian translation 2024-03-23 06:28:26 +02:00
Plamen Vatev c296e9061e add Italian translation 2024-03-23 06:22:53 +02:00
changchiyou e14ad508c9 enhance: e9a198d8ed 2024-03-23 10:14:47 +08:00
changchiyou e9a198d8ed enhance: routes/documents & components/documents/Settings/General.svelte 2024-03-23 10:12:11 +08:00
changchiyou cb0e858c04 enhance: routes/prompts 2024-03-23 09:44:56 +08:00
Timothy Jaeryang Baek 848d2382bc Merge pull request #1267 from Michelklingler/langfuse_dependency
Added langfuse dependency to the requierements.txt file.
2024-03-22 16:36:21 -05:00
Timothy Jaeryang Baek 106727109e Merge pull request #1258 from que-nguyen/main
Fixed Vietnamese translation for improved language quality
2024-03-22 16:20:39 -05:00
Timothy Jaeryang Baek c97051e6eb Merge pull request #1262 from pazoff/dev
Fixed spelling in Bulgarian translation
2024-03-22 16:20:11 -05:00
Michel K 4140e1b84a Added langfuse dependency to the requierements.txt file. 2024-03-22 14:01:39 -04:00
Plamen Vatev fe8a3ac2d7 Fix spelling 2024-03-22 17:49:25 +02:00
Jannik Streidl fdef2abdfb cuda fix 2024-03-22 12:48:48 +01:00
Jannik Streidl fc4e762b05 ENV fix 2024-03-22 10:57:41 +01:00
changchiyou b5111c4b34 enhance: routes/modelfiles
- `Modelfile` is a proprietary term of Ollama. `模型文件` is the Simplified Chinese translation used in their community but not common used in zh-TW community.
- `Prompt`'s better zh-TW translation is `提示詞`(refert to https://docs.aws.amazon.com/zh_tw/bedrock/latest/userguide/what-is-prompt-engineering.html ) instead of `提示`, which is easily misunderstood as a verb `建議`
2024-03-22 17:17:22 +08:00
Jannik Streidl c08631d6ff updates docker-build action 2024-03-22 10:05:20 +01:00
Jannik Streidl 3f973fe77f i need coffee 2024-03-22 09:57:17 +01:00
Jannik Streidl 953d05428e grammar 2024-03-22 09:55:46 +01:00
Jannik Streidl 6dc4b748fb added comments 2024-03-22 09:50:01 +01:00
Jannik Streidl fde0139bf7 All in one Dockerfile for including Ollama 2024-03-22 09:31:35 +01:00
Timothy J. Baek 92cc87d908 fix: ollama upload url 2024-03-22 00:58:38 -07:00
Timothy J. Baek 9e37d6edcc refac: gguf upload ui 2024-03-22 00:55:59 -07:00
Timothy J. Baek 77ec296ac3 chore: print removed 2024-03-22 00:11:17 -07:00
Timothy J. Baek bc80f1438c fix: ollama gguf upload 2024-03-22 00:10:55 -07:00
Timothy J. Baek af4caec4f5 refac: ollama gguf upload 2024-03-21 23:45:00 -07:00
Que Nguyen c5e9ceeb06 Merge branch 'open-webui:main' into main 2024-03-22 10:43:03 +07:00
Que Nguyen 47a04a7e3c Fixed Vietnamese translation for improved language quality 2024-03-22 10:42:38 +07:00
Timothy Jaeryang Baek c54fb92263 Merge pull request #1249 from pazoff/dev
added Bulgarian Translation
2024-03-21 16:29:25 -05:00
Timothy J. Baek f3c113cb04 fix: languages order 2024-03-21 14:29:05 -07:00
Plamen Vatev 5f26b2a9e3 added bg-BG (Bulgarian) 2024-03-21 17:43:31 +02:00
Plamen Vatev 8935dca279 added Bulgarian Translation 2024-03-21 17:14:59 +02:00
changchiyou f675a18b05 enhance: i18n's zh-TW translation for About.svelte 2024-03-21 19:38:42 +08:00
Self Denial f74f2ea765 Merge conflicts 2024-03-21 00:14:13 -06:00
Timothy J. Baek afa591afb2 Create Dockerfile-ollama 2024-03-20 20:58:23 -07:00
Timothy Jaeryang Baek 5a90e90c0b Merge pull request #1241 from 7a6ac0/duplicate_def
fix: delete duplicate function
2024-03-20 22:01:13 -05:00
Timothy Jaeryang Baek 2fa94956f4 Merge pull request #1209 from open-webui/dev
Create and publish a Docker image / build-and-push-image (push) Failing after 59s
0.1.114
2024-03-20 21:34:22 -05:00
Timothy J. Baek 8e52ba8b91 refac: auth required for litellm in dev 2024-03-20 19:33:27 -07:00
Timothy J. Baek ed0d4b5a2a chore: comment clean up 2024-03-20 19:32:25 -07:00
tabaco.wang a1412d0b55 fix: delete duplicate function 2024-03-21 10:31:25 +08:00
Timothy J. Baek 1a240e103e doc: changelog 2024-03-20 19:31:15 -07:00
Timothy J. Baek 93c90dc186 feat: litellm model filter support 2024-03-20 19:28:33 -07:00
Timothy J. Baek 8cb7127fbc doc: changelog 2024-03-20 19:01:20 -07:00
Timothy J. Baek 4b91ac352a chore: i18n alphabetically ordering 2024-03-20 18:52:24 -07:00
Timothy Jaeryang Baek 09dc3b7b67 Merge pull request #1226 from marionguyen/main
Added Vietnamese translation files
2024-03-20 20:49:27 -05:00
Timothy J. Baek bdc51b45ec Update translation.json 2024-03-20 18:49:08 -07:00
Timothy Jaeryang Baek 6313a98287 Merge branch 'dev' into main 2024-03-20 20:48:26 -05:00
Timothy Jaeryang Baek ae347bb5e7 Merge pull request #1239 from open-webui/webhook
feat: webhook
2024-03-20 20:47:46 -05:00
Timothy J. Baek fa65be2ad2 refac: post webhook 2024-03-20 18:47:13 -07:00
Timothy J. Baek 2481e48a3a feat: webhook settings frontend 2024-03-20 18:35:54 -07:00
Timothy J. Baek 2c6e2d5e8a feat: webhook backend 2024-03-20 18:35:02 -07:00
Self Denial e6dd0bfbe0 Migrate to python logging module with env var control. 2024-03-20 17:11:36 -06:00
Joseph Young 2588da0e27 Update PyTorch wheel source to CUDA 11.8
Modified the Dockerfile to install PyTorch, torchvision, and torchaudio from a CUDA 11.8 specific wheel URL. This ensures compatibility with the CUDA version in our environment and potentially improves performance and stability for GPU-accelerated operations.
2024-03-20 18:33:34 -04:00
Joseph Young 8ce48dc7d1 Fix typo in Dockerfile comment for model recommendation
Okay, this was driving my OCD crazy.

Corrected a spelling error in the Dockerfile's comment section to enhance documentation clarity. The typo 'persormance' was updated to 'performance,' ensuring accurate guidance on using multilingual sentence transformer models for better performance and language support.
2024-03-20 18:28:57 -04:00
Joseph Young 9bea40bd40 Adding the missing env variable
ENV RAG_EMBEDDING_MODEL_DEVICE_TYPE="cuda"
2024-03-20 18:16:11 -04:00
Jannik Streidl 9a8a48b879 gh build action for the different build args 2024-03-20 09:05:38 +01:00
Jannik Streidl 1f6739337b docker improvements & changed universal device type env for different models used 2024-03-20 08:44:09 +01:00
Que Nguyen b22ed64770 Added Vietnamese translation files 2024-03-20 11:31:44 +07:00
Timothy Jaeryang Baek 16fe0ee167 Merge pull request #1151 from changchiyou/feat/custom_default_user_permissions_chat_deletion
Feat/custom default user permissions chat deletion
2024-03-19 16:23:23 -05:00
Timothy J. Baek 87344adf29 refac 2024-03-19 14:21:46 -07:00
Timothy J. Baek 349fd0c87d refac: config.json 2024-03-19 14:03:46 -07:00
Timothy Jaeryang Baek d4a11ca33f Merge pull request #1220 from justinh-rahb/fix-messsage
Fix spelling
2024-03-19 15:17:06 -05:00
Justin Hayes bd84ee0c6a Fix spelling 2024-03-19 15:06:45 -04:00
Timothy J. Baek a9e411fdb9 fix: languages 2024-03-19 11:46:48 -07:00
Timothy Jaeryang Baek de8de7e008 Merge pull request #1217 from justinh-rahb/french
French (Canada) translations added, some French (France) strings updated/changed
2024-03-19 13:45:53 -05:00
Timothy Jaeryang Baek 63edaae8d8 Merge pull request #1219 from djismgaming/spanish-translation
Spanish translation
2024-03-19 13:44:47 -05:00
Timothy Jaeryang Baek d3cf9a7535 Merge pull request #1215 from granludo/main
Added Catalan translation
2024-03-19 13:42:53 -05:00
Ismael 7c8727151e spanish translation of the webui 2024-03-19 14:12:04 -04:00
Justin Hayes c3f805b809 Fix capitalization of words 2024-03-19 12:24:12 -04:00
Justin Hayes 8508319c23 Revert "Change some fr-FR strings"
This reverts commit b21091bc01.
2024-03-19 12:07:16 -04:00
Justin Hayes b9382f7051 Update languages.json 2024-03-19 11:51:52 -04:00
Justin Hayes 53fb3d9c3e Add fr-CA translations.json 2024-03-19 11:51:36 -04:00
Justin Hayes b21091bc01 Change some fr-FR strings 2024-03-19 11:51:21 -04:00
Ludo (Marc Alier) 4de591b930 added catalan to "languages.json" added proper code "ca-ES" 2024-03-19 15:26:02 +01:00
Ludo (Marc Alier) 492d4f3403 Added Catalan translation 2024-03-19 11:27:46 +01:00
Timothy J. Baek 0b163c2c2d Update translation.json 2024-03-19 00:30:44 -07:00
Timothy Jaeryang Baek 7bb8e91edb Merge pull request #1207 from officialsahyaboutorabi/patch-4
Update languages.json
2024-03-19 02:28:53 -05:00
Timothy Jaeryang Baek 49faff497e Merge pull request #1206 from officialsahyaboutorabi/patch-3
Create translation.json
2024-03-19 02:28:14 -05:00
Timothy Jaeryang Baek 33888ffaf8 Merge pull request #1205 from adan89lion/patch-1
Enhance Traditional Chinese translation
2024-03-19 02:27:17 -05:00
officialsahyaboutorabi b10eb0dacc Update languages.json 2024-03-19 16:14:34 +11:00
officialsahyaboutorabi 7f197a70f9 Create translation.json
For Russian language.
2024-03-19 16:13:20 +11:00
Ismael 61b4ab1e63 spanish translation of the webui 2024-03-18 22:44:38 -04:00
Ismael 51342179ad feat: Add support for Spanish language option in WebUI Settings 2024-03-18 22:44:05 -04:00
Seohyun Joo f1925841e2 Enhance Traditional Chinese translation
Correct some machine translation mistakes, and convert Mainland China's regional expression to Taiwan.
2024-03-19 10:17:54 +08:00
Timothy J. Baek e86db74333 refac: stream default value 2024-03-18 18:14:05 -07:00
Timothy J. Baek c569280806 fix: styling 2024-03-18 17:46:16 -07:00
Timothy J. Baek bc5d322cbb fix: add doc modal styling 2024-03-18 17:03:08 -07:00
Timothy Jaeryang Baek d865b9fe59 Merge pull request #1199 from open-webui/dev
fix: openai proxy issue
2024-03-18 13:04:53 -05:00
Timothy J. Baek b188143f01 fix: openai proxy issue 2024-03-18 11:04:22 -07:00
Timothy Jaeryang Baek 621719c6ac Merge pull request #1187 from open-webui/dev
Create and publish a Docker image / build-and-push-image (push) Failing after 59s
0.1.113
2024-03-18 13:02:46 -05:00
Timothy J. Baek ec9895a14a fix: openai proxy issue 2024-03-18 11:02:09 -07:00
Timothy J. Baek 212e051683 doc: changelog 2024-03-18 11:00:38 -07:00
Timothy J. Baek 47081011d6 doc: readme 2024-03-18 10:51:45 -07:00
Timothy J. Baek c94d72bca8 fix: sidebar menu 2024-03-18 10:49:39 -07:00
Timothy Jaeryang Baek c3dd11de16 Merge pull request #1196 from fbirlik/patch-autoscrolldisable
fix: auto scroll fails to stop with small scroll amounts
2024-03-18 11:57:34 -05:00
Timothy Jaeryang Baek 1f0dcb4fce Merge pull request #1115 from dannyl1u/feat/system-wide-theme
feat: system os light/dark mode option 🔦
2024-03-18 11:55:45 -05:00
Jannik Streidl 132d741c55 set default to cpu 2024-03-18 17:09:43 +01:00
Jannik Streidl 5abe0089cb cuda support 2024-03-18 17:08:34 +01:00
Timothy J. Baek 1bfcd801b7 fix: multiple openai issue 2024-03-18 01:11:48 -07:00
Timothy J. Baek 19f69c821f refac: code convention 2024-03-18 00:31:43 -07:00
Timothy J. Baek 8f8a68e002 refac: unnecessary code 2024-03-18 00:30:08 -07:00
Timothy J. Baek 94c845d71f refac 2024-03-18 00:27:48 -07:00
Firat Birlik adbcb06892 fix: auto scroll fails to stop with small scroll amounts 2024-03-18 00:08:45 -05:00
Joseph Young c5948d3e2c Updated Dockerfile for CUDA backend
Enabled NVIDIA CUDA backend build stage in the Dockerfile for enhanced performance with GPU support. Moved the environment variable defining the device type for the embedding and TTS models to be shared between CPU and GPU configurations. The default device type for CPU build is now explicitly set to "cpu", while the CUDA build retains "cuda", ensuring clarity and performance optimization across different hardware setups.
2024-03-17 22:50:52 -04:00
Joseph Young c004ecdccc Refactor Dockerfile for CPU and CUDA builds
Switched to Chainguard images as base for both CPU and CUDA backend builds for improved security and compatibility. Replaced Ubuntu base with Chainguard's Python image for the CPU builds and PyTorch CUDA image for GPU acceleration, resolving python requirements conflicts. Updated package installation commands to align with the new Redhat-compatible base images. The Dockerfile now installs only the necessary dependencies, as Python is provided by the base image.

These changes will facilitate a more secure and streamlined build process with better dependency management across different platforms.
2024-03-17 17:03:43 -04:00
Danny Liu 3c01932a78 run prettier 2024-03-17 01:00:38 -07:00
Danny Liu a57586a2b7 use IIFE in app.html to prevent FOUC 2024-03-17 00:25:33 -07:00
Danny Liu 41cb6d7a54 remove duplicate "System" in select menu 2024-03-17 00:06:59 -07:00
Danny Liu 549408d808 Add setContext import to +layout.svelte 2024-03-16 23:59:09 -07:00
Danny Liu f25a967a0b add system theme ⚙️ option to select menu 2024-03-16 23:54:18 -07:00
Danny Liu f55dae3027 fix merge conflict 2024-03-16 23:27:08 -07:00
Joseph Young e3b1cbbb86 Parametrize CUDA_VERSION in Dockerfile
Standardized CUDA_VERSION as a global ARG to ensure consistency and facilitate version updates across the Dockerfile. This change allows the CUDA version to be defined once at the beginning and reused, reducing the chance of mismatched versions and easing maintenance when changing CUDA versions. It further streamlines the build process for potential multi-stage builds with varying CUDA dependencies.

Refs #nvidia-update
2024-03-17 02:27:06 -04:00
Danny Liu db0712aefd Merge branch 'dev' into feat/system-wide-theme 2024-03-16 23:23:56 -07:00
Danny Liu f1716f45b9 add event listener in app.html to handle system theme changes 2024-03-16 23:14:38 -07:00
Danny Liu 6f3acb347d update theme handling and persist selection using Svelte store 2024-03-16 23:14:13 -07:00
Joseph Young f6cef312f2 Optimize Dockerfile for CUDA support
Refactored the Dockerfile to better organize and streamline environment variable settings, emphasizing support for a CUDA-based WebUI backend while retaining the ability to build a CPU-only image. Consolidated ENV commands to reduce layers, improving build efficiency, and set a default PORT environment to enhance container usability. Enabled exposure of the backend service on port 8080 and leveraged combined RUN directives to minimize the image footprint. These changes facilitate a more robust deployment process, catering to both CPU and CUDA environments.
2024-03-17 01:55:37 -04:00
Joseph Young 75a40dead6 Create Dockerfile-cuda
+Dockerfile-cuda

I created this file to help add CUDA support to open-webui for access to a GPU during embedding operations.
2024-03-16 19:26:21 -04:00
Jannik S 29e48b1c1f Exposed port 8080 2024-03-16 20:11:09 +01:00
Jannik S 62ab163316 Update Dockerfile 2024-03-16 12:43:48 +01:00
Timothy J. Baek e414b9ea6d fix: typo 2024-03-16 03:28:02 -07:00
Timothy J. Baek 1e03871748 fix: openai issue 2024-03-16 03:25:20 -07:00
Timothy J. Baek f90236f521 doc: demo.gif 2024-03-16 03:22:37 -07:00
Timothy J. Baek cf82aa9268 Update README.md 2024-03-16 03:01:43 -07:00
Timothy Jaeryang Baek ddb654f293 Merge pull request #1099 from zhecho/feat/helm-labels-and-lb-class
feat(helm): adding lb class and labels for using it with Cilium CNI l…
2024-03-16 04:50:49 -05:00
Timothy J. Baek ed964260ba fix: openai urls issue 2024-03-16 02:45:24 -07:00
Timothy J. Baek a636e784bc fix: styling 2024-03-16 02:43:51 -07:00
Timothy J. Baek ffeae78b88 feat: chat menu tooltip added 2024-03-16 02:35:40 -07:00
Timothy J. Baek 79a02b85a8 refac: chat menu styling 2024-03-16 02:34:27 -07:00
Timothy Jaeryang Baek 36a5588957 Merge pull request #926 from asedmammad/feat/add-i18n
Add i18n
2024-03-16 04:30:22 -05:00
Timothy J. Baek e664c38377 refac: settings styling 2024-03-16 02:24:32 -07:00
Timothy J. Baek 264eb28455 fix: styling 2024-03-16 02:16:24 -07:00
Timothy J. Baek 06f7cba401 Update package-lock.json 2024-03-16 02:10:19 -07:00
Timothy J. Baek df55ced0c0 Merge branch 'dev' into pr/926 2024-03-16 02:08:02 -07:00
Timothy J. Baek 71def5c4cb feat: sidebar ui update 2024-03-16 01:57:26 -07:00
Timothy J. Baek d6905d6297 feat: sidebar ui update 2024-03-16 00:27:29 -07:00
Timothy J. Baek 91efd6cb63 fix: file upload encoding issue 2024-03-15 23:52:37 -07:00
Timothy Jaeryang Baek 5ce421e7fa Merge pull request #1144 from open-webui/dev
Create and publish a Docker image / build-and-push-image (push) Failing after 1m17s
0.1.112
2024-03-15 15:49:52 -05:00
Timothy J. Baek 51ef5cfa45 doc: changelog 2024-03-15 13:46:43 -07:00
Timothy J. Baek 072b499a50 fix: backslash rag content issue 2024-03-15 13:34:52 -07:00
Ased Mammad d6e89d074d Update Ukranian translation 2024-03-15 15:14:07 +03:30
Timothy J. Baek cd92cf0da5 fix: image settings save issue 2024-03-15 02:40:44 -07:00
Ased Mammad f9bc35a11c fix: Ternary expression workaround for i18n:parse 2024-03-15 12:30:49 +03:30
Timothy Jaeryang Baek 7cef008b44 Merge pull request #1163 from joequant/main
fix typo in uploading blob to ollama
2024-03-14 15:48:49 -05:00
Ased Mammad b85385385a Update uk translation 2024-03-14 23:42:30 +03:30
Ased Mammad aeb265c789 Update persian translation + run i18n:parse 2024-03-14 23:35:09 +03:30
Jannik Streidl 1e590b79cf added uk keys 2024-03-14 20:52:52 +01:00
Jannik Streidl c0de658dac uk key dix 2024-03-14 20:32:59 +01:00
Jannik Streidl a65d042c73 title fix + new translation keys 2024-03-14 20:30:30 +01:00
Jannik Streidl e99ab95987 maybe this matches better.. im done 2024-03-14 17:29:37 +01:00
Jannik Streidl dd22f1aebc ..and the icon 2024-03-14 17:28:00 +01:00
Jannik Streidl 81fba4774b typo 2024-03-14 17:20:56 +01:00
Jannik Streidl 8a23704138 added changelog entry 2024-03-14 17:19:39 +01:00
Jannik Streidl 5d6182eb7f sorted 2024-03-14 14:43:17 +01:00
Jannik Streidl fafe42e487 more missing translation keys 2024-03-14 14:40:52 +01:00
Jannik Streidl ccc1c81256 added missing translation keys 2024-03-14 14:38:05 +01:00
Jannik Streidl dbdc602791 added simplified + traditional chinese, updates uk keys, changed standart language code format to xx-XX 2024-03-14 12:10:04 +01:00
Jannik Streidl 384b7e8462 changed from bullseye to bookworm + removed unused steps 2024-03-14 11:33:54 +01:00
Jannik Streidl 50bec32153 Dockerfile optimisation 2024-03-14 11:18:27 +01:00
Joseph C Wang 9ee0feae32 fix typo in uploading blob to ollama 2024-03-14 17:17:52 +08:00
Jannik Streidl aa3985e879 merged from main and added new translation keys 2024-03-14 09:42:37 +01:00
Jannik Streidl 2a5bc2b2ad added chinese 2024-03-14 09:29:02 +01:00
changchiyou c6e14ce327 refactor: restrict the scope of USER_PERMISSIONS_CHAT_DELETION
it can easily confuse people before becuase when people accidentally set `env.USER_PERMISSIONS_CHAT_DELETION` to `true/yes/Yes`, `USER_PERMISSIONS["chat"]["deletion"]` would become `False`, which is unexpectedly and hard to notice.
2024-03-14 00:01:46 +08:00
changchiyou 04e3b168a6 config: allow custom default user permissions - chat deletion
Allow Chat Deletion
2024-03-13 23:17:22 +08:00
Timothy Jaeryang Baek 75607541c6 Merge pull request #1138 from Silentoplayz/patch-1
Update tailwind.css
2024-03-12 15:57:51 -05:00
Timothy J. Baek 3790790a18 fix: possible fix for #1139 2024-03-12 13:47:49 -07:00
Timothy J. Baek 5a567ce4d0 fix: message after image generation 2024-03-12 13:43:49 -07:00
Timothy J. Baek 7f78e58488 refac: image generation error handling 2024-03-12 13:35:30 -07:00
Silentoplayz cc4b82a3f3 Update tailwind.css
Fix spacing
2024-03-12 06:08:03 -04:00
Silentoplayz 97842d037e Update tailwind.css
- Combined font-family declaration: Instead of repeating the font-family declaration for both `html` and `pre`, it's combined into one declaration to save space and avoid repetition.

- Removed unnecessary `pre` styling: The `pre` styling for `font-family` is removed as the font-family is already defined in the `html` rule.

The code is more concise and easier to read.
2024-03-12 05:34:00 -04:00
Timothy J. Baek 26a187f5ac refac: print removed 2024-03-12 00:26:53 -07:00
Timothy J. Baek be3ab88c88 fix: error handling 2024-03-12 00:26:14 -07:00
Ased Mammad 1091ee5a9b fix: Typo 2024-03-11 18:54:31 +03:30
Timothy Jaeryang Baek 7ae4669f35 Merge pull request #1131 from open-webui/dev
fix: env var migration issue
2024-03-10 21:29:20 -05:00
Timothy J. Baek e3fc97241d fix: env var migration issue 2024-03-10 19:26:06 -07:00
Timothy J. Baek b4c770d74b fix: disable openai model by default 2024-03-10 19:00:43 -07:00
Timothy Jaeryang Baek 11ca2703b0 Merge pull request #1130 from open-webui/dev
fix: rag
2024-03-10 20:41:58 -05:00
Timothy J. Baek 8df6b137cb fix: rag 2024-03-10 18:40:50 -07:00
Timothy Jaeryang Baek 89634046e7 Merge pull request #1107 from open-webui/dev
Create and publish a Docker image / build-and-push-image (push) Failing after 1m1s
0.1.111
2024-03-10 17:00:56 -05:00
Timothy J. Baek 88d324b52d doc: changelog 2024-03-10 14:55:17 -07:00
Ased Mammad 78f79ef670 Update persian translation with new dev features 2024-03-11 01:04:22 +03:30
Timothy J. Baek 64afde6c0e refac: config versioning 2024-03-10 14:15:32 -07:00
Timothy J. Baek 1e9d40af42 feat: update all models 2024-03-10 14:10:32 -07:00
Timothy J. Baek 98948814fd feat: toggle pdf ocr 2024-03-10 13:32:34 -07:00
Ased Mammad 7545a717ff Add more translation keys 2024-03-10 22:31:10 +03:30
Ased Mammad b8902072fd Merge branch 'dev' into feat/add-i18n 2024-03-10 22:02:16 +03:30
Timothy J. Baek 96ada23272 Update requirements.txt 2024-03-10 00:00:16 -08:00
Timothy J. Baek a02ac67b5c Update requirements.txt 2024-03-09 23:59:17 -08:00
Timothy J. Baek 350489e600 fix: requirements.txt 2024-03-09 23:49:07 -08:00
Timothy J. Baek 8a08ba0791 refac: settings save 2024-03-09 22:02:27 -08:00
Timothy J. Baek c6667510c4 refac: confusing icon 2024-03-09 21:55:13 -08:00
Timothy J. Baek bd84753c6b feat: title auto-generate for openai apis 2024-03-09 21:52:19 -08:00
Timothy J. Baek a4ca1fc5c4 feat: model filter list env var 2024-03-09 21:47:01 -08:00
Timothy Jaeryang Baek bcabd3df84 Merge pull request #1117 from open-webui/model-whitelist
feat: model filter (whitelist)
2024-03-10 00:30:43 -05:00
Timothy J. Baek 81daf4ceb9 feat: model filter frontend integration 2024-03-09 21:29:04 -08:00
Timothy J. Baek b550e23bf6 feat: model filter backend 2024-03-09 21:19:20 -08:00
Timothy J. Baek 83a900bd4a fix: dragged layover 2024-03-09 20:27:54 -08:00
Timothy J. Baek 1a93021cc4 fix: log modified messages 2024-03-09 20:12:32 -08:00
Danny Liu 27153ddb03 remove unused variable 2024-03-09 13:12:15 -08:00
Danny Liu b94dc767ff implement system wide light/dark mode option 🔦 2024-03-09 12:17:47 -08:00
Ased Mammad 6e57fda8f4 fix: Whisper French translation 2024-03-09 15:18:14 +03:30
Timothy J. Baek 6d5ff8d469 feat: frontend whitelist model selector 2024-03-09 01:50:31 -08:00
Timothy J. Baek 219466374d feat: model whitelist 2024-03-09 01:43:02 -08:00
Timothy J. Baek d40edc09e1 feat: hide litellm by default 2024-03-09 00:50:48 -08:00
Timothy Jaeryang Baek d99114518c Merge pull request #1113 from open-webui/rag
feat: rag api
2024-03-09 02:22:40 -05:00
Timothy J. Baek 784ee6f521 fix: error handling 2024-03-08 23:21:00 -08:00
Timothy J. Baek d936353da0 fix: message type edge case 2024-03-08 23:19:20 -08:00
Timothy J. Baek 9f58ed5afa fix 2024-03-08 22:52:42 -08:00
Timothy J. Baek dfcc314283 fix: only edit body with whitelisted paths 2024-03-08 22:51:42 -08:00
Timothy J. Baek 6c58bb59be feat: rag docs as payload field 2024-03-08 22:43:06 -08:00
Timothy J. Baek c49491e516 refac: rag to backend 2024-03-08 22:34:47 -08:00
Timothy J. Baek 6ba62cf25d fix: dalle3 issue 2024-03-08 19:54:47 -08:00
Timothy Jaeryang Baek 19700e9074 Merge pull request #1109 from ther0bster/fix-openai-env-var-parsing
fix: parsing of OPENAI_API_BASE_URLS env var
2024-03-08 22:31:57 -05:00
Timothy J. Baek 7e5e2c42c9 refac: rag routes 2024-03-08 19:26:39 -08:00
Roberto Gudelj 9235864f56 fix: parsing of OPENAI_API_BASE_URLS env var 2024-03-09 04:11:39 +01:00
Ased Mammad f221e39c24 Merge remote-tracking branch 'upstream/dev' into feat/add-i18n 2024-03-09 05:26:39 +03:30
Timothy Jaeryang Baek 30503b5958 Merge pull request #1108 from open-webui/dall-e
feat: dall-e integration
2024-03-08 20:41:03 -05:00
Timothy J. Baek fe7610d380 fix: disable dall-e image generation w/o key 2024-03-08 17:40:30 -08:00
Timothy J. Baek 0221acd163 feat: dall-e integration 2024-03-08 17:38:10 -08:00
Ased Mammad c7ca7d03ee Add more translations 2024-03-09 04:03:53 +03:30
Timothy J. Baek dd3a4b3889 refac: image generation 2024-03-08 16:22:19 -08:00
Ased Mammad 90513941bc feat: add i18n:parser script to package.json 2024-03-09 03:40:32 +03:30
Ased Mammad e8ffb2c023 fix: configure i18next to not return empty strings 2024-03-09 03:33:20 +03:30
Ased Mammad 48e8b45dc9 fix: issue with nbsp in i18next-parser 2024-03-09 03:11:45 +03:30
Timothy J. Baek f1c8e7f5d1 Update README.md 2024-03-08 14:47:34 -08:00
Timothy J. Baek f4bd442495 fix: consistent stroke width for icons 2024-03-08 14:22:23 -08:00
Timothy J. Baek f2c7db7637 fix: empty title issue 2024-03-08 14:04:08 -08:00
Timothy J. Baek 404aa62a8a fix: chat list issues 2024-03-08 13:58:56 -08:00
Timothy J. Baek 9881022b11 fix 2024-03-08 13:45:21 -08:00
Timothy J. Baek 9a83bde7e5 feat: max token option for litellm models 2024-03-08 13:41:38 -08:00
Timothy J. Baek 2b84af878a refac: litellm 2024-03-08 13:33:56 -08:00
Zhecho Zhechev 3c4cc60277 feat(helm): adding lb class and labels for using it with Cilium CNI l2 annoncements mode 2024-03-08 10:09:21 +02:00
Ased Mammad f605bd96be Update translations 2024-03-07 23:24:15 +03:30
Timothy Jaeryang Baek 171084ea0b Merge pull request #1088 from pandego/patch-1
Update Dockerfile
2024-03-07 14:35:59 -05:00
Timothy Jaeryang Baek 712f0e3501 Merge pull request #1084 from jannikstdl/patch-4
fix: show lates changes in releases
2024-03-07 14:35:29 -05:00
Timothy J. Baek 04ddbf4306 fix: button click issue 2024-03-07 11:07:27 -08:00
Ased Mammad f73cae2a73 format some files with prettier 2024-03-07 22:21:00 +03:30
Ased Mammad 3fa5144cf6 fix: Add missing english translations 2024-03-07 20:39:43 +03:30
Jannik Streidl 275a8256bb second merge 2024-03-07 18:04:50 +01:00
Jannik Streidl d4c8a7dab2 merge 2024-03-07 17:58:43 +01:00
Ased Mammad 1f2d704f76 fix: Add missing translations in admin setting 2024-03-07 20:27:52 +03:30
Jannik Streidl 12c74b2cd1 select fix + uk update 2024-03-07 17:56:57 +01:00
Ased Mammad fcc6189091 fix: Update uk translations 2024-03-07 20:24:44 +03:30
Jannik Streidl 93ed5851ca spelling + changed to hardcoded text 2024-03-07 16:37:37 +01:00
Jannik Streidl d40fbcd06b added margin 2024-03-07 16:21:56 +01:00
Jannik Streidl 8c596ea2fc only show the info when language = en (makes more sense to me) 2024-03-07 16:02:14 +01:00
Jannik Streidl 0d127ffef1 merged conflicts 2024-03-07 15:47:15 +01:00
Jannik Streidl f5afb0ca52 contribution info in the settings 2024-03-07 15:41:18 +01:00
pandego 203cd84922 Update Dockerfile
Tiny typo.
2024-03-07 15:13:51 +01:00
Ased Mammad f7e10e1fb6 Update translations 2024-03-07 16:35:56 +03:30
Ased Mammad 03690de773 fix: disable i18next debug 2024-03-07 16:23:17 +03:30
Ased Mammad 80e2125266 add missing types 2024-03-07 16:23:17 +03:30
Ased Mammad 7031aa14e8 Merge branch 'dev' into feat/add-i18n 2024-03-07 15:41:42 +03:30
Ased Mammad 08aa60b33e feat: auto add translation keys to json
Uses i18next-parser to automatically extract translation keys
from js and svelte files.
2024-03-07 15:21:37 +03:30
Jannik S bbf9deabf0 fix: show lates changes in releases
fix for ##1048
2024-03-07 11:41:23 +01:00
Ased Mammad f55525c680 fix: load languages in an exported function 2024-03-07 14:10:30 +03:30
Timothy J. Baek a901031896 fix: accept attribute 2024-03-07 02:17:57 -08:00
Ased Mammad c724e19e62 add new persian translations 2024-03-07 13:27:09 +03:30
Ased Mammad b76eb46d86 docs: Update contributing.md 2024-03-07 13:20:00 +03:30
Ased Mammad f4a1885298 feat: Get available languages from json file 2024-03-07 13:08:37 +03:30
Ased Mammad 41378748b8 refac: Move store to i18n index 2024-03-07 13:08:37 +03:30
Timothy Jaeryang Baek ef9a799e77 Merge pull request #1080 from officialsahyaboutorabi/patch-1
feat: additional file types for uploading models
2024-03-07 00:02:23 -05:00
Timothy Jaeryang Baek 8ed5759d0e Merge pull request #1071 from open-webui/dev
Create and publish a Docker image / build-and-push-image (push) Failing after 43s
0.1.110
2024-03-06 23:32:24 -05:00
Timothy Jaeryang Baek 6c4e368ac7 Merge pull request #1077 from fbirlik/patch-listblocks
fix: numbered lists with an additional line between items are rendered incorrectly
2024-03-06 23:28:28 -05:00
Timothy J. Baek df49e4e1cc fix: default openai api value 2024-03-06 20:25:24 -08:00
officialsahyaboutorabi 14c38d31a7 Update Models.svelte 2024-03-07 15:06:12 +11:00
Firat Birlik 3823908f37 fix: numbered lists with an additional line between items are rendered incorrectly 2024-03-06 21:15:18 -06:00
Timothy J. Baek 35918cefcc doc: changelog 2024-03-06 18:54:52 -08:00
Timothy J. Baek 34c7b6783c fix: ocr issue 2024-03-06 18:49:35 -08:00
Timothy J. Baek 0476c5f30b fix: add doc modal issue 2024-03-06 18:39:33 -08:00
Timothy J. Baek 53adc6a0ca fix: rag issue 2024-03-06 18:37:40 -08:00
Timothy J. Baek b88c64f80e fix: ocr issue 2024-03-06 17:54:42 -08:00
Timothy Jaeryang Baek dc6e91a23d Merge pull request #1074 from open-webui/main
dev
2024-03-06 20:07:37 -05:00
Timothy J. Baek bb98c10abb revert: ocr feature 2024-03-06 17:04:40 -08:00
Timothy Jaeryang Baek e17e2e7c17 Merge pull request #1070 from open-webui/multi-openai
feat: multiple openai apis
2024-03-06 19:14:03 -05:00
Timothy J. Baek c255cba198 feat: multiple openai apis 2024-03-06 16:13:25 -08:00
Timothy J. Baek 51d509bafb Update config.py 2024-03-06 13:18:17 -08:00
Timothy Jaeryang Baek df298e1001 Merge pull request #1066 from open-webui/dev
refac: semicolon as delimiter
2024-03-06 15:42:38 -05:00
Timothy J. Baek 0142c2de43 refac: semicolon as delimiter 2024-03-06 12:42:14 -08:00
Timothy Jaeryang Baek 92e21acb4c Merge pull request #1033 from open-webui/dev
Create and publish a Docker image / build-and-push-image (push) Failing after 55s
0.1.109
2024-03-06 15:40:28 -05:00
Timothy J. Baek ad237b61f3 Update CHANGELOG.md 2024-03-06 12:15:47 -08:00
Jannik Streidl 6a271a1691 fix: spelling 2024-03-06 20:55:07 +01:00
Timothy J. Baek c9173b71b6 chore: comment rename 2024-03-06 11:51:51 -08:00
Timothy J. Baek f741adc6c9 refac: OLLAMA_API_BASE_URL deprecated 2024-03-06 11:44:00 -08:00
Timothy J. Baek 5ae121b087 feat: message tooltips 2024-03-06 11:26:39 -08:00
Timothy J. Baek 434595b3e6 fix: delete model list 2024-03-06 11:14:33 -08:00
Timothy J. Baek 534ba9e4f0 fix: message edit textarea height 2024-03-06 11:09:04 -08:00
Timothy Jaeryang Baek 34b6a99601 Merge pull request #1062 from justinh-rahb/fix/gguf-modelfile-template
Remove extra 'S' in 'ASSISTANT'
2024-03-06 13:31:26 -05:00
Justin Hayes 0aa4e3aafb Restore colons 2024-03-06 13:03:39 -05:00
Justin Hayes 7258a794f1 Remove colons and another extra 'S' 2024-03-06 12:59:47 -05:00
Ased Mammad 213e08a8a5 feat: add French translation 2024-03-06 20:03:33 +03:30
Justin Hayes e4eb32709d Remove extra 'S' in 'ASSISTANT' 2024-03-06 11:08:04 -05:00
Timothy Jaeryang Baek 20284dc66d Merge pull request #1004 from dannyl1u/refac/delete-message
refac: delete message logic
2024-03-06 03:57:40 -05:00
Timothy J. Baek 2b016adc6e revert 2024-03-06 00:55:51 -08:00
Timothy J. Baek a9d74b669e refac 2024-03-06 00:33:47 -08:00
Timothy Jaeryang Baek 8fb5f54751 Merge pull request #1050 from jannikstdl/rag-pdf-ocr
feat: added ocr functionality to the pdf loader
2024-03-06 00:45:33 -05:00
Timothy Jaeryang Baek 2111398d13 Merge pull request #1048 from jannikstdl/release-notes
feat: show latest changes in releases
2024-03-06 00:44:57 -05:00
Ased Mammad 25e0f0de42 Merge remote-tracking branch 'upstream/dev' into feat/add-i18n 2024-03-06 01:25:29 +03:30
Jannik Streidl 089a63e0c6 feat: added ocr functionality to the pdf loader 2024-03-05 22:25:25 +01:00
Timothy Jaeryang Baek 3455f8993b Merge pull request #1049 from open-webui/tjbck-patch-1
Update bug_report.md
2024-03-05 11:19:11 -05:00
Timothy Jaeryang Baek 132e05ad57 Update bug_report.md 2024-03-05 11:18:46 -05:00
Jannik S 95b20f3cb8 feat: show latest changes in releases
This should show the latest Changes in the CHANGELOG.md file when creating a new release.

For now it only shows "Automatically created new release".

It is running 'awk '/^## [/{n++} n==1' CHANGELOG.md' which extracts the latest changes. Note: I only tested the command on my linux machine, worked.
2024-03-05 16:45:47 +01:00
Ased Mammad df8aeb39c6 docs: Add translations section to contributing.md 2024-03-05 18:17:52 +03:30
Jannik Streidl 2b3c8194eb fix: type 2024-03-05 15:39:57 +01:00
Jannik Streidl 71dba592bf changed some german spelling 2024-03-05 14:24:03 +01:00
Jannik Streidl 31fc9a04b6 Merge branch 'feat/add-i18n' of https://github.com/asedmammad/open-webui into feat/add-i18n 2024-03-05 14:06:47 +01:00
Jannik Streidl 53f69ace6c fixed you var + added ua translation for the new playground 2024-03-05 14:06:27 +01:00
Ased Mammad 66342140a3 fix: use translation key as fallback + more translations 2024-03-05 15:28:54 +03:30
Jannik Streidl b5b860f575 add: ukrainian translation 2024-03-05 11:52:07 +01:00
Jannik Streidl 7f9049c3a1 add: added Playground + AddFilesPlaceholder translation 2024-03-05 11:44:37 +01:00
Timothy J. Baek 1fad6e10cd feat: allow model switching mid convo 2024-03-05 02:37:05 -08:00
Timothy J. Baek 124020f824 chore: added print url for debugging 2024-03-05 02:19:25 -08:00
Timothy J. Baek fbdac832bb feat: multiple ollama model management 2024-03-05 02:12:55 -08:00
Timothy Jaeryang Baek 8181d98e99 Merge pull request #1044 from open-webui/multiple-ollama
feat: multiple ollama support
2024-03-05 04:51:08 -05:00
Timothy J. Baek 8626ae60dd chore: old_main removed 2024-03-05 01:43:33 -08:00
Timothy J. Baek 8d34324d12 feat: cancel request
Resolves #1006
2024-03-05 01:41:22 -08:00
Timothy J. Baek b2dd2f191d refac: comment 2024-03-05 01:21:50 -08:00
Timothy J. Baek 8fd7bc342d refac: error message 2024-03-05 01:07:59 -08:00
Timothy J. Baek f04d60b6d9 feat: multiple ollama support 2024-03-05 00:59:35 -08:00
Jannik Streidl b9f53abf37 fix: show translated user role in admin panel 2024-03-05 09:30:00 +01:00
Jannik Streidl fcb991db63 fix: darkmode for selects 2024-03-05 09:15:22 +01:00
Danny Liu 03907f9a8a check if deleted message response has sibling responses for multi model chats 2024-03-04 21:23:41 -08:00
Timothy J. Baek 475105473c feat: tooltip aria label 2024-03-04 13:58:39 -08:00
Timothy Jaeryang Baek 2d59847fb9 Merge pull request #1025 from Carlos-err406/fix/dom-queries
rf: less dom queries using bind:this
2024-03-04 16:22:31 -05:00
Timothy Jaeryang Baek 32495256fa Merge pull request #1029 from fbirlik/patch-ragrecreate
recreate rag collection instead of falling back to stale version
2024-03-04 16:21:54 -05:00
Ased Mammad 5f5b6ec141 feat: add persian translation for new keys 2024-03-05 00:47:43 +03:30
Danny Liu 8c01197483 refac: reassign grandchildren of deleted message as children of parent message 2024-03-04 12:34:14 -08:00
Firat Birlik 6782e95c75 recreate rag collection is now optional and only used for web requests 2024-03-04 10:00:06 -06:00
Jannik Streidl 4d67dd977d sidebar tooltop translation 2024-03-04 14:53:34 +01:00
Ased Mammad ec8f229f5a fix: make translation key naming consistent 2024-03-04 16:48:08 +03:30
Jannik Streidl d4fd6c5a57 merged new updates 2024-03-04 11:53:09 +01:00
Jannik Streidl 7a79aab5d4 (probably) last transition vars + Theme select element bg and icon fix 2024-03-04 11:15:54 +01:00
Jannik Streidl 3fe5f00114 more translations 2024-03-04 09:53:56 +01:00
Carlos Daniel Vilaseca 7a30dbc839 rf: added Element to variable names 2024-03-03 23:05:16 -05:00
Carlos Daniel Vilaseca b986c2aefd rf: dom queries in layout and pages 2024-03-03 23:02:11 -05:00
Timothy J. Baek 20263f742a refac: confusing ollama proxy route path 2024-03-03 19:55:32 -08:00
Firat Birlik 5d4ff85228 recreate rag collection instead of falling back to stale version 2024-03-03 21:25:00 -06:00
Carlos Daniel Vilaseca 50acdb09de fix: better variable names 2024-03-03 17:40:18 -05:00
Carlos Daniel Vilaseca 0def6f8724 rf: dom queries in ChatCompletion component 2024-03-03 17:36:28 -05:00
Carlos Daniel Vilaseca 15e0f9de86 rf: dom queries in AddDocModal component 2024-03-03 17:35:45 -05:00
Carlos Daniel Vilaseca fe040ce82b rf: dom queries in Models component 2024-03-03 17:35:07 -05:00
Carlos Daniel Vilaseca f4f6724d96 rf: dom queries in Chats component 2024-03-03 17:34:38 -05:00
Carlos Daniel Vilaseca 13f0052122 rf: dom queries in UserMessage component 2024-03-03 17:33:01 -05:00
Carlos Daniel Vilaseca a5c1ac9680 rf: dom queries in Account component 2024-03-03 17:32:04 -05:00
Carlos Daniel Vilaseca 0fc76d46db rf: dom queries in ResponseMessageComponent 2024-03-03 17:30:08 -05:00
Carlos Daniel Vilaseca cc471597cd rf: message input dom queries 2024-03-03 17:03:03 -05:00
Timothy Jaeryang Baek fe19f125d4 Merge pull request #1023 from fbirlik/patch-useragent
add fake_useragent to get a realistic header for rag/web requests
2024-03-03 15:22:06 -05:00
Firat Birlik 05221ea135 add fake_useragent to get a realistic header for rag/web requests 2024-03-03 13:58:51 -06:00
Jannik Streidl 304006aa8c typo 2024-03-03 12:22:54 +01:00
Jannik Streidl 893b738cbf german translations + new vars 2024-03-03 12:22:29 +01:00
Ased Mammad 670b65c066 fix: add missed imports 2024-03-03 13:34:26 +03:30
Ased Mammad 6d2f462090 fix: add missed translations 2024-03-03 13:31:34 +03:30
Danny Liu 2250387382 retain the message in history object 2024-03-02 23:31:03 -08:00
Danny Liu f9f3fe5ec0 refac delete logic 2024-03-02 23:23:49 -08:00
Timothy Jaeryang Baek eb51ad14e4 Merge pull request #997 from open-webui/dev
Create and publish a Docker image / build-and-push-image (push) Failing after 48s
0.1.108
2024-03-02 22:25:17 -05:00
Timothy J. Baek 65804e657a Update CHANGELOG.md 2024-03-02 19:24:02 -08:00
Timothy J. Baek 25c0316fc6 doc: changelog 2024-03-02 19:19:39 -08:00
Timothy J. Baek 4a1e506a35 fix: input autofocus on mobile issue 2024-03-02 19:05:16 -08:00
Timothy J. Baek 47a05a47b4 feat: add rag top k value setting 2024-03-02 18:56:57 -08:00
Timothy Jaeryang Baek 9694c6569f Merge pull request #1002 from open-webui/playground
feat: playground
2024-03-02 21:36:00 -05:00
Timothy J. Baek 9201769ba5 refac: unused style 2024-03-02 18:35:33 -08:00
Timothy J. Baek 79d7e135ec refac 2024-03-02 18:35:19 -08:00
Timothy J. Baek bf3f3c580e fix: text completion 2024-03-02 18:23:27 -08:00
Timothy J. Baek 901e7a33fa feat: chat playground backend integration 2024-03-02 18:16:02 -08:00
Timothy J. Baek 656f8dab05 feat: playground chat mode 2024-03-02 17:11:48 -08:00
Ased Mammad da0202851f feat: add farsi translation file v1 2024-03-03 01:45:18 +03:30
Ased Mammad 45f6908154 fix: Minor fixes in english translation file 2024-03-03 01:43:49 +03:30
Ased Mammad fbed07f651 fix: Merge similar string literals 2024-03-03 01:23:41 +03:30
Ased Mammad 511b52f642 feat: Add translation file for english 2024-03-03 01:12:32 +03:30
Ased Mammad 3c471ee2ca feat: Migrate hardcoded strings to i18n calls 2024-03-03 00:56:24 +03:30
Timothy J. Baek 06ce5aed4a fix: text completion replaced with chat completion 2024-03-02 13:14:14 -08:00
Ased Mammad 7a77f3c2c0 feat: Change translation keys to fallback strings 2024-03-02 14:47:41 +03:30
Ased Mammad fab89a76b1 feat: WIP: Initial setup for i18next 2024-03-02 14:47:37 +03:30
Timothy J. Baek 2379e94cbf feat: text completion playground 2024-03-02 03:01:44 -08:00
Timothy J. Baek 9b86e0bb41 Update Sidebar.svelte 2024-03-02 01:27:34 -08:00
Timothy J. Baek b9444d00b3 Update Tooltip.svelte 2024-03-02 01:27:01 -08:00
Timothy J. Baek 0bc3e0a302 feat: tooltip added to sidebar 2024-03-02 01:21:00 -08:00
Timothy J. Baek f9482275f2 fix: tooltip 2024-03-02 01:20:50 -08:00
Timothy J. Baek 63c0927022 feat: tooltip
Co-Authored-By: Jannik S. <69747628+jannikstdl@users.noreply.github.com>
2024-03-02 01:00:20 -08:00
Timothy J. Baek edb63c2280 feat: download db from admin settings 2024-03-02 00:33:20 -08:00
Timothy J. Baek 6d854125cc refac: ollama.db renamed to webui.db 2024-03-02 00:19:24 -08:00
Timothy J. Baek 74809e7330 fix: user chat delete loophole 2024-03-02 00:07:50 -08:00
Timothy J. Baek a4c6a8d5a4 fix: sonner toast styling issue 2024-03-02 00:05:25 -08:00
Timothy Jaeryang Baek 9caf6c26ff Merge pull request #998 from chamburr/patch-1
Fix enable signup env
2024-03-02 02:58:41 -05:00
Han Cen a12b5ffab3 Fix enable signup env 2024-03-02 15:38:14 +08:00
Timothy J. Baek b85c6ef667 fix: ol display issue
#963
2024-03-01 23:32:06 -08:00
Timothy Jaeryang Baek 6c70d0f770 Merge pull request #996 from open-webui/dev
Create and publish a Docker image / build-and-push-image (push) Failing after 49s
0.1.107
2024-03-02 02:05:50 -05:00
Timothy J. Baek 96e2ee48f7 Update CHANGELOG.md 2024-03-01 23:04:20 -08:00
Timothy J. Baek 63e7246c97 doc: changelog 2024-03-01 23:02:47 -08:00
Timothy J. Baek 6f4a863562 feat: dark mode auth page 2024-03-01 22:52:21 -08:00
Timothy Jaeryang Baek a7ae141301 Merge pull request #982 from jannikstdl/svelte-sonner
ui: svelte-french-toast -> svelte-sonner
2024-03-02 01:41:49 -05:00
Timothy J. Baek 2564b154fc fix: toast position 2024-03-01 22:40:55 -08:00
Timothy Jaeryang Baek 8310392c9d Merge pull request #992 from jannikstdl/bottom-scroll
show chat in browser title + scroll to bottom
2024-03-02 01:39:00 -05:00
Timothy J. Baek 78d9c469a2 feat: title for all routes 2024-03-01 22:38:04 -08:00
Timothy J. Baek e5c812f1d2 refac 2024-03-01 22:35:08 -08:00
Jannik Streidl 8461b92f08 show chat in browser title + scroll to bottom 2024-03-01 21:18:17 +01:00
Timothy Jaeryang Baek 3396723057 Merge pull request #989 from jmtatsch/patch-1
Update run-compose.sh
2024-03-01 14:51:20 -05:00
jmtatsch 4fe47f43be Update run-compose.sh
fix webui port not being effective
2024-03-01 17:45:32 +01:00
Jannik Streidl 705f5aecd7 svelte-sonner migration 2024-03-01 10:18:07 +01:00
Timothy Jaeryang Baek 19d49df76f Merge pull request #968 from Carlos-err406/fix/double-loop
fix: unnecesary double loop
2024-02-29 15:15:19 -05:00
Carlos Daniel Vilaseca 30c94ff10f fix: unnecesary double loop 2024-02-29 12:37:46 -05:00
Timothy Jaeryang Baek 941ab5d6cf Merge pull request #848 from Patrice-Gaudicheau/feat-makefile-llm-update 2024-02-28 16:38:54 -05:00
Timothy Jaeryang Baek 5a81ca7e39 Merge pull request #960 from cocktailpeanut/main 2024-02-28 16:36:09 -05:00
cocktailpeanut f4122fd0ce update 2024-02-28 14:27:12 -05:00
Timothy Jaeryang Baek 5745b9c5db Merge pull request #955 from open-webui/dev
fix: openai convo
2024-02-28 05:19:20 -05:00
Timothy J. Baek 3fd55ebc32 fix: openai convo 2024-02-28 02:18:58 -08:00
Timothy Jaeryang Baek 776b463ff3 Merge pull request #953 from open-webui/dev
fix: title edit issue
2024-02-28 01:36:32 -05:00
Timothy J. Baek 5640b38694 fix: title edit issue 2024-02-27 22:35:57 -08:00
Timothy Jaeryang Baek a181b2b63b Merge pull request #951 from open-webui/dev
Create and publish a Docker image / build-and-push-image (push) Failing after 53s
0.1.106
2024-02-27 23:11:43 -05:00
Timothy J. Baek 32361dc3da Update CHANGELOG.md 2024-02-27 20:10:29 -08:00
Timothy J. Baek 59ae5b6d34 fix: openai filtering 2024-02-27 20:08:57 -08:00
Timothy J. Baek a36627cbce doc: changelog 2024-02-27 20:07:23 -08:00
Timothy Jaeryang Baek 8a63d22000 Merge pull request #927 from sakkus-ai/fix-openai-integration
Fix OpenAI integration: allow OpenAI to make chat completion calls with a valid API key
2024-02-27 23:03:10 -05:00
Timothy J. Baek 781be2779b refac: unnecessary max_token value removed 2024-02-27 20:02:23 -08:00
Timothy Jaeryang Baek f347d664ac Merge pull request #941 from jannikstdl/autofocus-chat
fix: added focus selector
2024-02-27 22:59:10 -05:00
Timothy J. Baek 260a8b8b83 feat: chat input focus on new chat 2024-02-27 19:56:52 -08:00
Timothy J. Baek 1d4d1ddbea revert 2024-02-27 19:06:32 -08:00
Timothy Jaeryang Baek 8f2d580991 Merge pull request #940 from jannikstdl/link-fix
fix: mark text when editing chat titles
2024-02-27 22:05:32 -05:00
Timothy Jaeryang Baek 6bbc3721b4 Merge pull request #937 from jannikstdl/patch-3
Added star-history
2024-02-27 22:04:24 -05:00
Jannik Streidl 7fe412374c more readable 2024-02-27 16:00:58 +01:00
Jannik Streidl 03210c9204 keep the functionality to drag a chat 2024-02-27 15:48:12 +01:00
Jannik Streidl d24b6fa9af link fix 2024-02-27 15:48:12 +01:00
Jannik Streidl 7c7e16c382 added focus selector 2024-02-27 13:30:03 +01:00
Jannik S 70f807e8c9 Added star-history
Added https://star-history.com/#open-webui/open-webui&Date
2024-02-27 11:51:12 +01:00
Timothy Jaeryang Baek 210ae331cc Merge pull request #924 from eltociear/patch-1
chore: update Models.svelte
2024-02-26 17:29:30 -05:00
Sakkus bbeaa92904 Fix OpenAI integration:
from docker on mac get errors since num_ctx not recognized;
remove num_ctx from, and max_tokens to, body in API calls.
2024-02-26 12:25:08 +00:00
Ikko Eltociear Ashimine a7a817d12b chore: update Models.svelte
HuggingFace -> Hugging Face
2024-02-26 19:34:43 +09:00
Timothy Jaeryang Baek 6df2505bf0 Merge pull request #919 from open-webui/dev
Create and publish a Docker image / build-and-push-image (push) Failing after 1m0s
0.1.105
2024-02-26 00:53:39 -05:00
Timothy J. Baek 3a7ded3f80 Update CHANGELOG.md 2024-02-25 21:46:43 -08:00
Timothy J. Baek 6d8b1385bb doc: changelog 2024-02-25 21:45:38 -08:00
Timothy J. Baek 92c922b061 feat: batch doc tagging 2024-02-25 21:39:10 -08:00
Timothy J. Baek 63628a70a6 feat: document select 2024-02-25 21:16:11 -08:00
Timothy Jaeryang Baek 95dd618a62 Merge pull request #914 from buroa/main
fix: add semver to container builds
2024-02-25 19:23:13 -05:00
Timothy J. Baek f8cf43c0f7 refac: console logs removed 2024-02-25 16:13:34 -08:00
Timothy Jaeryang Baek 334d5246ba Merge pull request #916 from open-webui/dev
fix: default model load issue
2024-02-25 19:09:27 -05:00
Timothy J. Baek 42251c232a fix: default model load issue 2024-02-25 16:09:05 -08:00
Timothy Jaeryang Baek 6b0eae9fad Merge pull request #915 from open-webui/dev
fix: continue generation
2024-02-25 18:48:40 -05:00
Timothy J. Baek 1ff0c9a95d fix: continue generation 2024-02-25 15:46:12 -08:00
Steven Kreitzer 0a2ee691db fix: add semver to container builds
Signed-off-by: Steven Kreitzer <skre@skre.me>
2024-02-25 15:57:46 -06:00
Timothy J. Baek 6245146661 refac: messages 2024-02-25 13:55:04 -08:00
Timothy Jaeryang Baek 588daace91 Merge pull request #913 from open-webui/dev
refac: styling
2024-02-25 16:45:55 -05:00
Timothy J. Baek 8f4a12b479 refac: styling 2024-02-25 13:45:24 -08:00
Timothy Jaeryang Baek 81a50c5104 Merge pull request #912 from open-webui/dev
refac: styling
2024-02-25 16:27:46 -05:00
Timothy J. Baek d1656d5da8 refac: styling 2024-02-25 13:27:19 -08:00
Timothy Jaeryang Baek 3c10c3b928 Merge pull request #910 from open-webui/dev
Create and publish a Docker image / build-and-push-image (push) Failing after 1m9s
0.1.104
2024-02-25 16:05:21 -05:00
Timothy J. Baek 1d937ec2f2 fix: cleanup unused tags 2024-02-25 13:03:26 -08:00
Timothy J. Baek 7c1b8e396a Update CHANGELOG.md 2024-02-25 12:51:08 -08:00
Timothy J. Baek ce891dfd5a fix: styling 2024-02-25 12:45:23 -08:00
Timothy J. Baek c5009907ff Update CHANGELOG.md 2024-02-25 12:37:23 -08:00
Timothy J. Baek 6780b1b19e fix: styling 2024-02-25 12:36:33 -08:00
Timothy J. Baek 8dce6b4b49 feat: personalised greeting 2024-02-25 12:34:32 -08:00
Timothy J. Baek 0d9e38a0ce refac: styling 2024-02-25 12:31:31 -08:00
Timothy Jaeryang Baek 129bb21a0a Merge pull request #911 from open-webui/check-updates
fix: check version loading progress
2024-02-25 15:11:06 -05:00
Timothy J. Baek fb3804ac95 fix: check version loading progress 2024-02-25 12:10:14 -08:00
Timothy Jaeryang Baek 13db1d5063 Merge pull request #909 from open-webui/check-updates
Check updates
2024-02-25 14:55:56 -05:00
Timothy J. Baek 759883a4c8 feat: check for updates 2024-02-25 11:55:15 -08:00
Timothy J. Baek 6bfe2a6306 feat: latest release check api 2024-02-25 11:26:58 -08:00
Timothy Jaeryang Baek b82ac66c70 Merge pull request #908 from open-webui/main
dev
2024-02-25 14:12:48 -05:00
Patrice-Gaudicheau 0f6bdaa602 feat: implemented user confirmation for safe removal of containers and volumes in Makefile 2024-02-24 09:02:18 +01:00
Patrice-Gaudicheau a016171573 fix: update Makefile and rename script for open-webui integration 2024-02-24 07:51:27 +01:00
Patrice Gaudicheau 7d0d504390 Updated code comments to English. 2024-02-23 15:53:47 +01:00
Patrice Gaudicheau 6bc627bbfb Updated code comments to English. 2024-02-23 15:52:55 +01:00
Patrice-Gaudicheau 5adff7767f Adding Makefile and LLM update script 2024-02-22 22:00:59 +01:00
Anuraag Jain ae97a96379 WIP feat: cancel model download 2024-02-18 21:29:47 +02:00
214 changed files with 27253 additions and 7828 deletions
-1
View File
@@ -7,7 +7,6 @@ node_modules
/package
.env
.env.*
!.env.example
vite.config.js.timestamp-*
vite.config.ts.timestamp-*
__pycache__
+7 -3
View File
@@ -1,6 +1,6 @@
# Ollama URL for the backend to connect
# The path '/ollama/api' will be redirected to the specified backend URL
OLLAMA_API_BASE_URL='http://localhost:11434/api'
# The path '/ollama' will be redirected to the specified backend URL
OLLAMA_BASE_URL='http://localhost:11434'
OPENAI_API_BASE_URL=''
OPENAI_API_KEY=''
@@ -9,4 +9,8 @@ OPENAI_API_KEY=''
# DO NOT TRACK
SCARF_NO_ANALYTICS=true
DO_NOT_TRACK=true
DO_NOT_TRACK=true
# Use locally bundled version of the LiteLLM cost map json
# to avoid repetitive startup connections
LITELLM_LOCAL_MODEL_COST_MAP="True"
+4 -1
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]
@@ -32,7 +35,7 @@ assignees: ''
**Confirmation:**
- [ ] I have read and followed all the instructions provided in the README.md.
- [ ] I have reviewed the troubleshooting.md document.
- [ ] I am on the latest version of both Open WebUI and Ollama.
- [ ] I have included the browser console logs.
- [ ] I have included the Docker container logs.
+23 -2
View File
@@ -19,24 +19,34 @@ jobs:
echo "No changes to package.json"
exit 1
}
- name: Get version number from package.json
id: get_version
run: |
VERSION=$(jq -r '.version' package.json)
echo "::set-output name=version::$VERSION"
- name: Extract latest CHANGELOG entry
id: changelog
run: |
CHANGELOG_CONTENT=$(awk 'BEGIN {print_section=0;} /^## \[/ {if (print_section == 0) {print_section=1;} else {exit;}} print_section {print;}' CHANGELOG.md)
CHANGELOG_ESCAPED=$(echo "$CHANGELOG_CONTENT" | sed ':a;N;$!ba;s/\n/%0A/g')
echo "Extracted latest release notes from CHANGELOG.md:"
echo -e "$CHANGELOG_CONTENT"
echo "::set-output name=content::$CHANGELOG_ESCAPED"
- name: Create GitHub release
uses: actions/github-script@v5
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
script: |
const changelog = `${{ steps.changelog.outputs.content }}`;
const release = await github.rest.repos.createRelease({
owner: context.repo.owner,
repo: context.repo.repo,
tag_name: `v${{ steps.get_version.outputs.version }}`,
name: `v${{ steps.get_version.outputs.version }}`,
body: 'Automatically created new release',
body: changelog,
})
console.log(`Created release ${release.data.html_url}`)
@@ -47,3 +57,14 @@ jobs:
path: .
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- name: Trigger Docker build workflow
uses: actions/github-script@v7
with:
script: |
github.rest.actions.createWorkflowDispatch({
owner: context.repo.owner,
repo: context.repo.repo,
workflow_id: 'docker-build.yaml',
ref: 'v${{ steps.get_version.outputs.version }}',
})
+336 -17
View File
@@ -1,8 +1,7 @@
#
name: Create and publish a Docker image
name: Create and publish Docker images with specific build args
# Configures this workflow to run every time a change is pushed to the branch called `release`.
on:
workflow_dispatch:
push:
branches:
- main
@@ -10,30 +9,39 @@ on:
tags:
- v*
# Defines two custom environment variables for the workflow. These are used for the Container registry domain, and a name for the Docker image that this workflow builds.
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
FULL_IMAGE_NAME: ghcr.io/${{ github.repository }}
# There is a single job in this workflow. It's configured to run on the latest available version of Ubuntu.
jobs:
build-and-push-image:
build-main-image:
runs-on: ubuntu-latest
# Sets the permissions granted to the `GITHUB_TOKEN` for the actions in this job.
permissions:
contents: read
packages: write
#
strategy:
fail-fast: false
matrix:
platform:
- linux/amd64
- linux/arm64
steps:
- name: Prepare
run: |
platform=${{ matrix.platform }}
echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
- name: Checkout repository
uses: actions/checkout@v4
# Required for multi architecture build
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
# Required for multi architecture build
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
# Uses the `docker/login-action` action to log in to the Container registry registry using the account and password that will publish the packages. Once published, the packages are scoped to the account defined here.
- name: Log in to the Container registry
uses: docker/login-action@v3
with:
@@ -41,25 +49,336 @@ jobs:
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata for Docker images
- name: Extract metadata for Docker images (default latest tag)
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
# This configuration dynamically generates tags based on the branch, tag, commit, and custom suffix for lite version.
images: ${{ env.FULL_IMAGE_NAME }}
tags: |
type=ref,event=branch
type=ref,event=tag
type=sha,prefix=git-
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
flavor: |
latest=${{ github.ref == 'refs/heads/main' }}
- name: Build and push Docker image
- name: Build Docker image (latest)
uses: docker/build-push-action@v5
id: build
with:
context: .
push: true
platforms: linux/amd64,linux/arm64
tags: ${{ steps.meta.outputs.tags }}
platforms: ${{ matrix.platform }}
labels: ${{ steps.meta.outputs.labels }}
outputs: type=image,name=${{ env.FULL_IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
cache-from: type=gha
cache-to: type=gha,mode=max
- name: Export digest
run: |
mkdir -p /tmp/digests
digest="${{ steps.build.outputs.digest }}"
touch "/tmp/digests/${digest#sha256:}"
- name: Upload digest
uses: actions/upload-artifact@v4
with:
name: digests-main-${{ env.PLATFORM_PAIR }}
path: /tmp/digests/*
if-no-files-found: error
retention-days: 1
build-cuda-image:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
strategy:
fail-fast: false
matrix:
platform:
- linux/amd64
- linux/arm64
steps:
- name: Prepare
run: |
platform=${{ matrix.platform }}
echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to the Container registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata for Docker images (default latest tag)
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.FULL_IMAGE_NAME }}
tags: |
type=ref,event=branch
type=ref,event=tag
type=sha,prefix=git-
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=cuda
flavor: |
latest=${{ github.ref == 'refs/heads/main' }}
suffix=-cuda,onlatest=true
- name: Build Docker image (cuda)
uses: docker/build-push-action@v5
id: build
with:
context: .
push: true
platforms: ${{ matrix.platform }}
labels: ${{ steps.meta.outputs.labels }}
outputs: type=image,name=${{ env.FULL_IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
cache-from: type=gha
cache-to: type=gha,mode=max
build-args: USE_CUDA=true
- name: Export digest
run: |
mkdir -p /tmp/digests
digest="${{ steps.build.outputs.digest }}"
touch "/tmp/digests/${digest#sha256:}"
- name: Upload digest
uses: actions/upload-artifact@v4
with:
name: digests-cuda-${{ env.PLATFORM_PAIR }}
path: /tmp/digests/*
if-no-files-found: error
retention-days: 1
build-ollama-image:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
strategy:
fail-fast: false
matrix:
platform:
- linux/amd64
- linux/arm64
steps:
- name: Prepare
run: |
platform=${{ matrix.platform }}
echo "PLATFORM_PAIR=${platform//\//-}" >> $GITHUB_ENV
- name: Checkout repository
uses: actions/checkout@v4
- name: Set up QEMU
uses: docker/setup-qemu-action@v3
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to the Container registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata for Docker images (ollama tag)
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.FULL_IMAGE_NAME }}
tags: |
type=ref,event=branch
type=ref,event=tag
type=sha,prefix=git-
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=ollama
flavor: |
latest=${{ github.ref == 'refs/heads/main' }}
suffix=-ollama,onlatest=true
- name: Build Docker image (ollama)
uses: docker/build-push-action@v5
id: build
with:
context: .
push: true
platforms: ${{ matrix.platform }}
labels: ${{ steps.meta.outputs.labels }}
outputs: type=image,name=${{ env.FULL_IMAGE_NAME }},push-by-digest=true,name-canonical=true,push=true
cache-from: type=gha
cache-to: type=gha,mode=max
build-args: USE_OLLAMA=true
- name: Export digest
run: |
mkdir -p /tmp/digests
digest="${{ steps.build.outputs.digest }}"
touch "/tmp/digests/${digest#sha256:}"
- name: Upload digest
uses: actions/upload-artifact@v4
with:
name: digests-ollama-${{ env.PLATFORM_PAIR }}
path: /tmp/digests/*
if-no-files-found: error
retention-days: 1
merge-main-images:
runs-on: ubuntu-latest
needs: [ build-main-image ]
steps:
- name: Download digests
uses: actions/download-artifact@v4
with:
pattern: digests-main-*
path: /tmp/digests
merge-multiple: true
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to the Container registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata for Docker images (default latest tag)
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.FULL_IMAGE_NAME }}
tags: |
type=ref,event=branch
type=ref,event=tag
type=sha,prefix=git-
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
flavor: |
latest=${{ github.ref == 'refs/heads/main' }}
- name: Create manifest list and push
working-directory: /tmp/digests
run: |
docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
$(printf '${{ env.FULL_IMAGE_NAME }}@sha256:%s ' *)
- name: Inspect image
run: |
docker buildx imagetools inspect ${{ env.FULL_IMAGE_NAME }}:${{ steps.meta.outputs.version }}
merge-cuda-images:
runs-on: ubuntu-latest
needs: [ build-cuda-image ]
steps:
- name: Download digests
uses: actions/download-artifact@v4
with:
pattern: digests-cuda-*
path: /tmp/digests
merge-multiple: true
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to the Container registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata for Docker images (default latest tag)
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.FULL_IMAGE_NAME }}
tags: |
type=ref,event=branch
type=ref,event=tag
type=sha,prefix=git-
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=cuda
flavor: |
latest=${{ github.ref == 'refs/heads/main' }}
suffix=-cuda,onlatest=true
- name: Create manifest list and push
working-directory: /tmp/digests
run: |
docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
$(printf '${{ env.FULL_IMAGE_NAME }}@sha256:%s ' *)
- name: Inspect image
run: |
docker buildx imagetools inspect ${{ env.FULL_IMAGE_NAME }}:${{ steps.meta.outputs.version }}
merge-ollama-images:
runs-on: ubuntu-latest
needs: [ build-ollama-image ]
steps:
- name: Download digests
uses: actions/download-artifact@v4
with:
pattern: digests-ollama-*
path: /tmp/digests
merge-multiple: true
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Log in to the Container registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata for Docker images (default ollama tag)
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.FULL_IMAGE_NAME }}
tags: |
type=ref,event=branch
type=ref,event=tag
type=sha,prefix=git-
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
type=raw,enable=${{ github.ref == 'refs/heads/main' }},prefix=,suffix=,value=ollama
flavor: |
latest=${{ github.ref == 'refs/heads/main' }}
suffix=-ollama,onlatest=true
- name: Create manifest list and push
working-directory: /tmp/digests
run: |
docker buildx imagetools create $(jq -cr '.tags | map("-t " + .) | join(" ")' <<< "$DOCKER_METADATA_OUTPUT_JSON") \
$(printf '${{ env.FULL_IMAGE_NAME }}@sha256:%s ' *)
- name: Inspect image
run: |
docker buildx imagetools inspect ${{ env.FULL_IMAGE_NAME }}:${{ steps.meta.outputs.version }}
+23 -11
View File
@@ -1,27 +1,39 @@
name: Python CI
on:
push:
branches: ['main']
branches:
- main
- dev
pull_request:
branches:
- main
- dev
jobs:
build:
name: 'Format Backend'
env:
PUBLIC_API_BASE_URL: ''
runs-on: ubuntu-latest
strategy:
matrix:
node-version:
- latest
python-version: [3.11]
steps:
- uses: actions/checkout@v4
- name: Use Python
uses: actions/setup-python@v4
- name: Use Bun
uses: oven-sh/setup-bun@v1
- name: Set up Python
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install yapf
pip install black
- name: Format backend
run: bun run format:backend
run: npm run format:backend
- name: Check for changes after format
run: git diff --exit-code
+28 -14
View File
@@ -1,22 +1,36 @@
name: Bun CI
name: Frontend Build
on:
push:
branches: ['main']
branches:
- main
- dev
pull_request:
branches:
- main
- dev
jobs:
build:
name: 'Format & Build Frontend'
env:
PUBLIC_API_BASE_URL: ''
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Use Bun
uses: oven-sh/setup-bun@v1
- run: bun --version
- name: Install frontend dependencies
run: bun install
- name: Format frontend
run: bun run format
- name: Build frontend
run: bun run build
- name: Checkout Repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: '20' # Or specify any other version you want to use
- name: Install Dependencies
run: npm install
- name: Format Frontend
run: npm run format
- name: Check for Changes After Format
run: git diff --exit-code
- name: Build Frontend
run: npm run build
+1 -1
View File
@@ -166,7 +166,7 @@ cython_debug/
# 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/
.idea/
# Logs
logs
+287
View File
@@ -5,6 +5,293 @@ 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.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
- **🦙 Ollama and CUDA Images**: Added support for ':ollama' and ':cuda' tagged images.
- **👍 Enhanced Response Rating**: Now you can annotate your ratings for better feedback.
- **👤 User Initials Profile Photo**: User initials are now the default profile photo.
- **🔍 Update RAG Embedding Model**: Customize RAG embedding model directly in document settings.
- **🌍 Additional Language Support**: Added Turkish language support.
### Fixed
- **🔒 Share Chat Permission**: Resolved issue with chat sharing permissions.
- **🛠 Modal Close**: Modals can now be closed using the Esc key.
### Changed
- **🎨 Admin Panel Styling**: Refreshed styling for the admin panel.
- **🐳 Docker Image Build**: Updated docker image build process for improved efficiency.
## [0.1.117] - 2024-04-03
### Added
- 🗨️ **Local Chat Sharing**: Share chat links seamlessly between users.
- 🔑 **API Key Generation Support**: Generate secret keys to leverage Open WebUI with OpenAI libraries.
- 📄 **Chat Download as PDF**: Easily download chats in PDF format.
- 📝 **Improved Logging**: Enhancements to logging functionality.
- 📧 **Trusted Email Authentication**: Authenticate using a trusted email header.
### Fixed
- 🌷 **Enhanced Dutch Translation**: Improved translation for Dutch users.
-**White Theme Styling**: Resolved styling issue with the white theme.
- 📜 **LaTeX Chat Screen Overflow**: Fixed screen overflow issue with LaTeX rendering.
- 🔒 **Security Patches**: Applied necessary security patches.
## [0.1.116] - 2024-03-31
### Added
- **🔄 Enhanced UI**: Model selector now conveniently located in the navbar, enabling seamless switching between multiple models during conversations.
- **🔍 Improved Model Selector**: Directly pull a model from the selector/Models now display detailed information for better understanding.
- **💬 Webhook Support**: Now compatible with Google Chat and Microsoft Teams.
- **🌐 Localization**: Korean translation (I18n) now available.
- **🌑 Dark Theme**: OLED dark theme introduced for reduced strain during prolonged usage.
- **🏷️ Tag Autocomplete**: Dropdown feature added for effortless chat tagging.
### Fixed
- **🔽 Auto-Scrolling**: Addressed OpenAI auto-scrolling issue.
- **🏷️ Tag Validation**: Implemented tag validation to prevent empty string tags.
- **🚫 Model Whitelisting**: Resolved LiteLLM model whitelisting issue.
- **✅ Spelling**: Corrected various spelling issues for improved readability.
## [0.1.115] - 2024-03-24
### Added
- **🔍 Custom Model Selector**: Easily find and select custom models with the new search filter feature.
- **🛑 Cancel Model Download**: Added the ability to cancel model downloads.
- **🎨 Image Generation ComfyUI**: Image generation now supports ComfyUI.
- **🌟 Updated Light Theme**: Updated the light theme for a fresh look.
- **🌍 Additional Language Support**: Now supporting Bulgarian, Italian, Portuguese, Japanese, and Dutch.
### Fixed
- **🔧 Fixed Broken Experimental GGUF Upload**: Resolved issues with experimental GGUF upload functionality.
### Changed
- **🔄 Vector Storage Reset Button**: Moved the reset vector storage button to document settings.
## [0.1.114] - 2024-03-20
### Added
- **🔗 Webhook Integration**: Now you can subscribe to new user sign-up events via webhook. Simply navigate to the admin panel > admin settings > webhook URL.
- **🛡️ Enhanced Model Filtering**: Alongside Ollama, OpenAI proxy model whitelisting, we've added model filtering functionality for LiteLLM proxy.
- **🌍 Expanded Language Support**: Spanish, Catalan, and Vietnamese languages are now available, with improvements made to others.
### Fixed
- **🔧 Input Field Spelling**: Resolved issue with spelling mistakes in input fields.
- **🖊️ Light Mode Styling**: Fixed styling issue with light mode in document adding.
### Changed
- **🔄 Language Sorting**: Languages are now sorted alphabetically by their code for improved organization.
## [0.1.113] - 2024-03-18
### Added
- 🌍 **Localization**: You can now change the UI language in Settings > General. We support Ukrainian, German, Farsi (Persian), Traditional and Simplified Chinese and French translations. You can help us to translate the UI into your language! More info in our [CONTRIBUTION.md](https://github.com/open-webui/open-webui/blob/main/docs/CONTRIBUTING.md#-translations-and-internationalization).
- 🎨 **System-wide Theme**: Introducing a new system-wide theme for enhanced visual experience.
### Fixed
- 🌑 **Dark Background on Select Fields**: Improved readability by adding a dark background to select fields, addressing issues on certain browsers/devices.
- **Multiple OPENAI_API_BASE_URLS Issue**: Resolved issue where multiple base URLs caused conflicts when one wasn't functioning.
- **RAG Encoding Issue**: Fixed encoding problem in RAG.
- **npm Audit Fix**: Addressed npm audit findings.
- **Reduced Scroll Threshold**: Improved auto-scroll experience by reducing the scroll threshold from 50px to 5px.
### Changed
- 🔄 **Sidebar UI Update**: Updated sidebar UI to feature a chat menu dropdown, replacing two icons for improved navigation.
## [0.1.112] - 2024-03-15
### Fixed
- 🗨️ Resolved chat malfunction after image generation.
- 🎨 Fixed various RAG issues.
- 🧪 Rectified experimental broken GGUF upload logic.
## [0.1.111] - 2024-03-10
### Added
- 🛡️ **Model Whitelisting**: Admins now have the ability to whitelist models for users with the 'user' role.
- 🔄 **Update All Models**: Added a convenient button to update all models at once.
- 📄 **Toggle PDF OCR**: Users can now toggle PDF OCR option for improved parsing performance.
- 🎨 **DALL-E Integration**: Introduced DALL-E integration for image generation alongside automatic1111.
- 🛠️ **RAG API Refactoring**: Refactored RAG logic and exposed its API, with additional documentation to follow.
### Fixed
- 🔒 **Max Token Settings**: Added max token settings for anthropic/claude-3-sonnet-20240229 (Issue #1094).
- 🔧 **Misalignment Issue**: Corrected misalignment of Edit and Delete Icons when Chat Title is Empty (Issue #1104).
- 🔄 **Context Loss Fix**: Resolved RAG losing context on model response regeneration with Groq models via API key (Issue #1105).
- 📁 **File Handling Bug**: Addressed File Not Found Notification when Dropping a Conversation Element (Issue #1098).
- 🖱️ **Dragged File Styling**: Fixed dragged file layover styling issue.
## [0.1.110] - 2024-03-06
### Added
- **🌐 Multiple OpenAI Servers Support**: Enjoy seamless integration with multiple OpenAI-compatible APIs, now supported natively.
### Fixed
- **🔍 OCR Issue**: Resolved PDF parsing issue caused by OCR malfunction.
- **🚫 RAG Issue**: Fixed the RAG functionality, ensuring it operates smoothly.
- **📄 "Add Docs" Model Button**: Addressed the non-functional behavior of the "Add Docs" model button.
## [0.1.109] - 2024-03-06
### Added
- **🔄 Multiple Ollama Servers Support**: Enjoy enhanced scalability and performance with support for multiple Ollama servers in a single WebUI. Load balancing features are now available, providing improved efficiency (#788, #278).
- **🔧 Support for Claude 3 and Gemini**: Responding to user requests, we've expanded our toolset to include Claude 3 and Gemini, offering a wider range of functionalities within our platform (#1064).
- **🔍 OCR Functionality for PDF Loader**: We've augmented our PDF loader with Optical Character Recognition (OCR) capabilities. Now, extract text from scanned documents and images within PDFs, broadening the scope of content processing (#1050).
### Fixed
- **🛠️ RAG Collection**: Implemented a dynamic mechanism to recreate RAG collections, ensuring users have up-to-date and accurate data (#1031).
- **📝 User Agent Headers**: Fixed issue of RAG web requests being sent with empty user_agent headers, reducing rejections from certain websites. Realistic headers are now utilized for these requests (#1024).
- **⏹️ Playground Cancel Functionality**: Introducing a new "Cancel" option for stopping Ollama generation in the Playground, enhancing user control and usability (#1006).
- **🔤 Typographical Error in 'ASSISTANT' Field**: Corrected a typographical error in the 'ASSISTANT' field within the GGUF model upload template for accuracy and consistency (#1061).
### Changed
- **🔄 Refactored Message Deletion Logic**: Streamlined message deletion process for improved efficiency and user experience, simplifying interactions within the platform (#1004).
- **⚠️ Deprecation of `OLLAMA_API_BASE_URL`**: Deprecated `OLLAMA_API_BASE_URL` environment variable; recommend using `OLLAMA_BASE_URL` instead. Refer to our documentation for further details.
## [0.1.108] - 2024-03-02
### Added
- **🎮 Playground Feature (Beta)**: Explore the full potential of the raw API through an intuitive UI with our new playground feature, accessible to admins. Simply click on the bottom name area of the sidebar to access it. The playground feature offers two modes text completion (notebook) and chat completion. As it's in beta, please report any issues you encounter.
- **🛠️ Direct Database Download for Admins**: Admins can now download the database directly from the WebUI via the admin settings.
- **🎨 Additional RAG Settings**: Customize your RAG process with the ability to edit the TOP K value. Navigate to Documents > Settings > General to make changes.
- **🖥️ UI Improvements**: Tooltips now available in the input area and sidebar handle. More tooltips will be added across other parts of the UI.
### Fixed
- Resolved input autofocus issue on mobile when the sidebar is open, making it easier to use.
- Corrected numbered list display issue in Safari (#963).
- Restricted user ability to delete chats without proper permissions (#993).
### Changed
- **Simplified Ollama Settings**: Ollama settings now don't require the `/api` suffix. You can now utilize the Ollama base URL directly, e.g., `http://localhost:11434`. Also, an `OLLAMA_BASE_URL` environment variable has been added.
- **Database Renaming**: Starting from this release, `ollama.db` will be automatically renamed to `webui.db`.
## [0.1.107] - 2024-03-01
### Added
- **🚀 Makefile and LLM Update Script**: Included Makefile and a script for LLM updates in the repository.
### Fixed
- Corrected issue where links in the settings modal didn't appear clickable (#960).
- Fixed problem with web UI port not taking effect due to incorrect environment variable name in run-compose.sh (#996).
- Enhanced user experience by displaying chat in browser title and enabling automatic scrolling to the bottom (#992).
### Changed
- Upgraded toast library from `svelte-french-toast` to `svelte-sonner` for a more polished UI.
- Enhanced accessibility with the addition of dark mode on the authentication page.
## [0.1.106] - 2024-02-27
### Added
- **🎯 Auto-focus Feature**: The input area now automatically focuses when initiating or opening a chat conversation.
### Fixed
- Corrected typo from "HuggingFace" to "Hugging Face" (Issue #924).
- Resolved bug causing errors in chat completion API calls to OpenAI due to missing "num_ctx" parameter (Issue #927).
- Fixed issues preventing text editing, selection, and cursor retention in the input field (Issue #940).
- Fixed a bug where defining an OpenAI-compatible API server using 'OPENAI_API_BASE_URL' containing 'openai' string resulted in hiding models not containing 'gpt' string from the model menu. (Issue #930)
## [0.1.105] - 2024-02-25
### Added
- **📄 Document Selection**: Now you can select and delete multiple documents at once for easier management.
### Changed
- **🏷️ Document Pre-tagging**: Simply click the "+" button at the top, enter tag names in the popup window, or select from a list of existing tags. Then, upload files with the added tags for streamlined organization.
## [0.1.104] - 2024-02-25
### Added
- **🔄 Check for Updates**: Keep your system current by checking for updates conveniently located in Settings > About.
- **🗑️ Automatic Tag Deletion**: Unused tags on the sidebar will now be deleted automatically with just a click.
### Changed
- **🎨 Modernized Styling**: Enjoy a refreshed look with updated styling for a more contemporary experience.
## [0.1.103] - 2024-02-25
### Added
+86 -42
View File
@@ -1,75 +1,117 @@
# syntax=docker/dockerfile:1
# Initialize device type args
# use build args in the docker build commmand with --build-arg="BUILDARG=true"
ARG USE_CUDA=false
ARG USE_OLLAMA=false
# Tested with cu117 for CUDA 11 and cu121 for CUDA 12 (default)
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 (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
FROM node:alpine as build
######## WebUI frontend ########
FROM --platform=$BUILDPLATFORM node:21-alpine3.19 as build
WORKDIR /app
# wget embedding model weight from alpine (does not exist from slim-buster)
RUN wget "https://chroma-onnx-models.s3.amazonaws.com/all-MiniLM-L6-v2/onnx.tar.gz" -O - | \
tar -xzf - -C /app
COPY package.json package-lock.json ./
RUN npm ci
COPY . .
RUN npm run build
######## WebUI backend ########
FROM python:3.11-slim-bookworm as base
ENV ENV=prod
ENV PORT ""
# Use args
ARG USE_CUDA
ARG USE_OLLAMA
ARG USE_CUDA_VER
ARG USE_EMBEDDING_MODEL
ENV OLLAMA_API_BASE_URL "/ollama/api"
## Basis ##
ENV ENV=prod \
PORT=8080 \
# pass build args to the build
USE_OLLAMA_DOCKER=${USE_OLLAMA} \
USE_CUDA_DOCKER=${USE_CUDA} \
USE_CUDA_DOCKER_VER=${USE_CUDA_VER} \
USE_EMBEDDING_MODEL_DOCKER=${USE_EMBEDDING_MODEL}
ENV OPENAI_API_BASE_URL ""
ENV OPENAI_API_KEY ""
## Basis URL Config ##
ENV OLLAMA_BASE_URL="/ollama" \
OPENAI_API_BASE_URL=""
ENV WEBUI_SECRET_KEY ""
## API Key and Security Config ##
ENV OPENAI_API_KEY="" \
WEBUI_SECRET_KEY="" \
SCARF_NO_ANALYTICS=true \
DO_NOT_TRACK=true
ENV SCARF_NO_ANALYTICS true
ENV DO_NOT_TRACK true
# Use locally bundled version of the LiteLLM cost map json
# to avoid repetitive startup connections
ENV LITELLM_LOCAL_MODEL_COST_MAP="True"
######## Preloaded models ########
# whisper TTS Settings
ENV WHISPER_MODEL="base"
ENV WHISPER_MODEL_DIR="/app/backend/data/cache/whisper/models"
# RAG Embedding Model Settings
# 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 persormance 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.
ENV RAG_EMBEDDING_MODEL="all-MiniLM-L6-v2"
# device type for whisper tts and ebbeding models - "cpu" (default), "cuda" (nvidia gpu and CUDA required) or "mps" (apple silicon) - choosing this right can lead to better performance
ENV RAG_EMBEDDING_MODEL_DEVICE_TYPE="cpu"
ENV RAG_EMBEDDING_MODEL_DIR="/app/backend/data/cache/embedding/models"
ENV SENTENCE_TRANSFORMERS_HOME $RAG_EMBEDDING_MODEL_DIR
#### Other models #########################################################
## whisper TTS model settings ##
ENV WHISPER_MODEL="base" \
WHISPER_MODEL_DIR="/app/backend/data/cache/whisper/models"
######## Preloaded models ########
## RAG Embedding model settings ##
ENV RAG_EMBEDDING_MODEL="$USE_EMBEDDING_MODEL_DOCKER" \
RAG_EMBEDDING_MODEL_DIR="/app/backend/data/cache/embedding/models" \
SENTENCE_TRANSFORMERS_HOME="/app/backend/data/cache/embedding/models"
#### Other models ##########################################################
WORKDIR /app/backend
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/*; \
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/*; \
fi
# install python dependencies
COPY ./backend/requirements.txt ./requirements.txt
RUN pip3 install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu --no-cache-dir
RUN pip3 install -r requirements.txt --no-cache-dir
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 && \
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
# Install pandoc and netcat
# RUN python -c "import pypandoc; pypandoc.download_pandoc()"
RUN apt-get update \
&& apt-get install -y pandoc netcat-openbsd \
&& rm -rf /var/lib/apt/lists/*
# preload embedding model
RUN python -c "import os; from chromadb.utils import embedding_functions; sentence_transformer_ef = embedding_functions.SentenceTransformerEmbeddingFunction(model_name=os.environ['RAG_EMBEDDING_MODEL'], device=os.environ['RAG_EMBEDDING_MODEL_DEVICE_TYPE'])"
# preload tts model
RUN python -c "import os; from faster_whisper import WhisperModel; WhisperModel(os.environ['WHISPER_MODEL'], device='auto', compute_type='int8', download_root=os.environ['WHISPER_MODEL_DIR'])"
# copy embedding weight from build
RUN mkdir -p /root/.cache/chroma/onnx_models/all-MiniLM-L6-v2
COPY --from=build /app/onnx /root/.cache/chroma/onnx_models/all-MiniLM-L6-v2/onnx
# RUN mkdir -p /root/.cache/chroma/onnx_models/all-MiniLM-L6-v2
# 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
@@ -79,4 +121,6 @@ COPY --from=build /app/package.json /app/package.json
# copy backend files
COPY ./backend .
EXPOSE 8080
CMD [ "bash", "start.sh"]
+27
View File
@@ -0,0 +1,27 @@
install:
@docker-compose up -d
remove:
@chmod +x confirm_remove.sh
@./confirm_remove.sh
start:
@docker-compose start
startAndBuild:
docker-compose up -d --build
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
# Make sure the ollama-webui container is stopped before rebuilding
@docker stop open-webui || true
@docker-compose up --build -d
@docker-compose start
+59 -16
View File
@@ -11,7 +11,7 @@
[![Discord](https://img.shields.io/badge/Discord-Open_WebUI-blue?logo=discord&logoColor=white)](https://discord.gg/5rJgQTnV4s)
[![](https://img.shields.io/static/v1?label=Sponsor&message=%E2%9D%A4&logo=GitHub&color=%23fe8e86)](https://github.com/sponsors/tjbck)
User-friendly WebUI for LLMs, supported LLM runners include Ollama and OpenAI-compatible APIs. For more information, be sure to check out our [Open WebUI Documentation](https://docs.openwebui.com/).
Open WebUI is an extensible, feature-rich, and user-friendly self-hosted WebUI designed to operate entirely offline. It supports various LLM runners, including Ollama and OpenAI-compatible APIs. For more information, be sure to check out our [Open WebUI Documentation](https://docs.openwebui.com/).
![Open WebUI Demo](./demo.gif)
@@ -25,22 +25,28 @@ User-friendly WebUI for LLMs, supported LLM runners include Ollama and OpenAI-co
- 🚀 **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,24 +59,48 @@ User-friendly WebUI for LLMs, supported LLM runners include Ollama and OpenAI-co
- 💬 **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.
- 🤝 **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**.
- 🗨️ **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 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.
- 🌐🌍 **Multilingual Support**: Experience Open WebUI in your preferred language with our internationalization (i18n) support. Join us in expanding our supported languages! We're actively seeking contributors!
- 🌟 **Continuous Updates**: We are committed to improving Open WebUI with regular updates and new features.
## 🔗 Also Check Out Open WebUI Community!
@@ -84,24 +114,27 @@ Don't forget to explore our sibling project, [Open WebUI Community](https://open
### Quick Start with Docker 🐳
> [!IMPORTANT]
> [!WARNING]
> When using Docker to install Open WebUI, make sure to include the `-v open-webui:/app/backend/data` in your Docker command. This step is crucial as it ensures your database is properly mounted and prevents any loss of data.
- **If Ollama is on your computer**, use this command:
> [!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.
```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_API_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_API_BASE_URL=https://example.com/api -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:
- After installation, you can access Open WebUI at [http://localhost:3000](http://localhost:3000). Enjoy! 😄
```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
```
After installation, you can access Open WebUI at [http://localhost:3000](http://localhost:3000). Enjoy! 😄
#### Open WebUI: Server Connection Error
@@ -110,7 +143,7 @@ If you're experiencing connection issues, its often due to the WebUI docker c
**Example Docker Command**:
```bash
docker run -d --network=host -v open-webui:/app/backend/data -e OLLAMA_API_BASE_URL=http://127.0.0.1:11434/api --name open-webui --restart always ghcr.io/open-webui/open-webui:main
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
@@ -160,6 +193,16 @@ This project is licensed under the [MIT License](LICENSE) - see the [LICENSE](LI
If you have any questions, suggestions, or need assistance, please open an issue or join our
[Open WebUI Discord community](https://discord.gg/5rJgQTnV4s) to connect with us! 🤝
## Star History
<a href="https://star-history.com/#open-webui/open-webui&Date">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date&theme=dark" />
<source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
<img alt="Star History Chart" src="https://api.star-history.com/svg?repos=open-webui/open-webui&type=Date" />
</picture>
</a>
---
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! 💪
+4 -4
View File
@@ -4,7 +4,7 @@
The Open WebUI system is designed to streamline interactions between the client (your browser) and the Ollama API. At the heart of this design is a backend reverse proxy, enhancing security and resolving CORS issues.
- **How it Works**: The Open WebUI is designed to interact with the Ollama API through a specific route. When a request is made from the WebUI to Ollama, it is not directly sent to the Ollama API. Initially, the request is sent to the Open WebUI backend via `/ollama/api` route. From there, the backend is responsible for forwarding the request to the Ollama API. This forwarding is accomplished by using the route specified in the `OLLAMA_API_BASE_URL` environment variable. Therefore, a request made to `/ollama/api` in the WebUI is effectively the same as making a request to `OLLAMA_API_BASE_URL` in the backend. For instance, a request to `/ollama/api/tags` in the WebUI is equivalent to `OLLAMA_API_BASE_URL/tags` in the backend.
- **How it Works**: The Open WebUI is designed to interact with the Ollama API through a specific route. When a request is made from the WebUI to Ollama, it is not directly sent to the Ollama API. Initially, the request is sent to the Open WebUI backend via `/ollama` route. From there, the backend is responsible for forwarding the request to the Ollama API. This forwarding is accomplished by using the route specified in the `OLLAMA_BASE_URL` environment variable. Therefore, a request made to `/ollama` in the WebUI is effectively the same as making a request to `OLLAMA_BASE_URL` in the backend. For instance, a request to `/ollama/api/tags` in the WebUI is equivalent to `OLLAMA_BASE_URL/api/tags` in the backend.
- **Security Benefits**: This design prevents direct exposure of the Ollama API to the frontend, safeguarding against potential CORS (Cross-Origin Resource Sharing) issues and unauthorized access. Requiring authentication to access the Ollama API further enhances this security layer.
@@ -15,7 +15,7 @@ If you're experiencing connection issues, its often due to the WebUI docker c
**Example Docker Command**:
```bash
docker run -d --network=host -v open-webui:/app/backend/data -e OLLAMA_API_BASE_URL=http://127.0.0.1:11434/api --name open-webui --restart always ghcr.io/open-webui/open-webui:main
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
```
### General Connection Errors
@@ -25,8 +25,8 @@ docker run -d --network=host -v open-webui:/app/backend/data -e OLLAMA_API_BASE_
**Troubleshooting Steps**:
1. **Verify Ollama URL Format**:
- When running the Web UI container, ensure the `OLLAMA_API_BASE_URL` is correctly set, including the `/api` suffix. (e.g., `http://192.168.1.1:11434/api` for different host setups).
- When running the Web UI container, ensure the `OLLAMA_BASE_URL` is correctly set. (e.g., `http://192.168.1.1:11434` for different host setups).
- In the Open WebUI, navigate to "Settings" > "General".
- Confirm that the Ollama Server URL is correctly set to `[OLLAMA URL]/api` (e.g., `http://localhost:11434/api`), including the `/api` suffix.
- Confirm that the Ollama Server URL is correctly set to `[OLLAMA URL]` (e.g., `http://localhost:11434`).
By following these enhanced troubleshooting steps, connection issues should be effectively resolved. For further assistance or queries, feel free to reach out to us on our community Discord.
+144 -11
View File
@@ -1,4 +1,5 @@
import os
import logging
from fastapi import (
FastAPI,
Request,
@@ -9,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 (
@@ -21,7 +33,20 @@ from utils.utils import (
)
from utils.misc import calculate_sha256
from config import CACHE_DIR, UPLOAD_DIR, WHISPER_MODEL, WHISPER_MODEL_DIR
from config import (
SRC_LOG_LEVELS,
CACHE_DIR,
UPLOAD_DIR,
WHISPER_MODEL,
WHISPER_MODEL_DIR,
WHISPER_MODEL_AUTO_UPDATE,
DEVICE_TYPE,
AUDIO_OPENAI_API_BASE_URL,
AUDIO_OPENAI_API_KEY,
)
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["AUDIO"])
app = FastAPI()
app.add_middleware(
@@ -33,12 +58,108 @@ app.add_middleware(
)
@app.post("/transcribe")
app.state.OPENAI_API_BASE_URL = AUDIO_OPENAI_API_BASE_URL
app.state.OPENAI_API_KEY = AUDIO_OPENAI_API_KEY
# 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)
class OpenAIConfigUpdateForm(BaseModel):
url: str
key: str
@app.get("/config")
async def get_openai_config(user=Depends(get_admin_user)):
return {
"OPENAI_API_BASE_URL": app.state.OPENAI_API_BASE_URL,
"OPENAI_API_KEY": app.state.OPENAI_API_KEY,
}
@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.OPENAI_API_BASE_URL = form_data.url
app.state.OPENAI_API_KEY = form_data.key
return {
"status": True,
"OPENAI_API_BASE_URL": app.state.OPENAI_API_BASE_URL,
"OPENAI_API_KEY": app.state.OPENAI_API_KEY,
}
@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.OPENAI_API_KEY}"
headers["Content-Type"] = "application/json"
r = None
try:
r = requests.post(
url=f"{app.state.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),
):
print(file.content_type)
log.info(f"file.content_type: {file.content_type}")
if file.content_type not in ["audio/mpeg", "audio/wav"]:
raise HTTPException(
@@ -54,15 +175,27 @@ def transcribe(
f.write(contents)
f.close()
model = WhisperModel(
WHISPER_MODEL,
device="auto",
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)
print(
log.info(
"Detected language '%s' with probability %f"
% (info.language, info.language_probability)
)
@@ -72,7 +205,7 @@ def transcribe(
return {"text": transcript.strip()}
except Exception as e:
print(e)
log.exception(e)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
+308 -58
View File
@@ -18,10 +18,33 @@ from utils.utils import (
get_current_user,
get_admin_user,
)
from apps.images.utils.comfyui import ImageGenerationPayload, comfyui_generate_image
from utils.misc import calculate_sha256
from typing import Optional
from pydantic import BaseModel
from config import AUTOMATIC1111_BASE_URL
from pathlib import Path
import uuid
import base64
import json
import logging
from config import (
SRC_LOG_LEVELS,
CACHE_DIR,
ENABLE_IMAGE_GENERATION,
AUTOMATIC1111_BASE_URL,
COMFYUI_BASE_URL,
IMAGES_OPENAI_API_BASE_URL,
IMAGES_OPENAI_API_KEY,
)
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["IMAGES"])
IMAGE_CACHE_DIR = Path(CACHE_DIR).joinpath("./image/generations/")
IMAGE_CACHE_DIR.mkdir(parents=True, exist_ok=True)
app = FastAPI()
app.add_middleware(
@@ -32,50 +55,116 @@ app.add_middleware(
allow_headers=["*"],
)
app.state.ENGINE = ""
app.state.ENABLED = ENABLE_IMAGE_GENERATION
app.state.OPENAI_API_BASE_URL = IMAGES_OPENAI_API_BASE_URL
app.state.OPENAI_API_KEY = IMAGES_OPENAI_API_KEY
app.state.MODEL = ""
app.state.AUTOMATIC1111_BASE_URL = AUTOMATIC1111_BASE_URL
app.state.ENABLED = app.state.AUTOMATIC1111_BASE_URL != ""
app.state.COMFYUI_BASE_URL = COMFYUI_BASE_URL
app.state.IMAGE_SIZE = "512x512"
app.state.IMAGE_STEPS = 50
@app.get("/enabled", response_model=bool)
async def get_enable_status(request: Request, user=Depends(get_admin_user)):
return app.state.ENABLED
@app.get("/config")
async def get_config(request: Request, user=Depends(get_admin_user)):
return {"engine": app.state.ENGINE, "enabled": app.state.ENABLED}
@app.get("/enabled/toggle", response_model=bool)
async def toggle_enabled(request: Request, user=Depends(get_admin_user)):
try:
r = requests.head(app.state.AUTOMATIC1111_BASE_URL)
app.state.ENABLED = not app.state.ENABLED
return app.state.ENABLED
except Exception as e:
raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(e))
class ConfigUpdateForm(BaseModel):
engine: str
enabled: bool
class UrlUpdateForm(BaseModel):
url: str
@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}
class EngineUrlUpdateForm(BaseModel):
AUTOMATIC1111_BASE_URL: Optional[str] = None
COMFYUI_BASE_URL: Optional[str] = None
@app.get("/url")
async def get_openai_url(user=Depends(get_admin_user)):
return {"AUTOMATIC1111_BASE_URL": app.state.AUTOMATIC1111_BASE_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,
}
@app.post("/url/update")
async def update_openai_url(form_data: UrlUpdateForm, user=Depends(get_admin_user)):
async def update_engine_url(
form_data: EngineUrlUpdateForm, user=Depends(get_admin_user)
):
if form_data.url == "":
if form_data.AUTOMATIC1111_BASE_URL == None:
app.state.AUTOMATIC1111_BASE_URL = AUTOMATIC1111_BASE_URL
else:
app.state.AUTOMATIC1111_BASE_URL = form_data.url.strip("/")
url = form_data.AUTOMATIC1111_BASE_URL.strip("/")
try:
r = requests.head(url)
app.state.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
else:
url = form_data.COMFYUI_BASE_URL.strip("/")
try:
r = requests.head(url)
app.state.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,
"status": True,
}
class OpenAIConfigUpdateForm(BaseModel):
url: str
key: str
@app.get("/openai/config")
async def get_openai_config(user=Depends(get_admin_user)):
return {
"OPENAI_API_BASE_URL": app.state.OPENAI_API_BASE_URL,
"OPENAI_API_KEY": app.state.OPENAI_API_KEY,
}
@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_BASE_URL = form_data.url
app.state.OPENAI_API_KEY = form_data.key
return {
"status": True,
"OPENAI_API_BASE_URL": app.state.OPENAI_API_BASE_URL,
"OPENAI_API_KEY": app.state.OPENAI_API_KEY,
}
class ImageSizeUpdateForm(BaseModel):
size: str
@@ -132,9 +221,34 @@ async def update_image_size(
@app.get("/models")
def get_models(user=Depends(get_current_user)):
try:
r = requests.get(url=f"{app.state.AUTOMATIC1111_BASE_URL}/sdapi/v1/sd-models")
models = r.json()
return models
if app.state.ENGINE == "openai":
return [
{"id": "dall-e-2", "name": "DALL·E 2"},
{"id": "dall-e-3", "name": "DALL·E 3"},
]
elif app.state.ENGINE == "comfyui":
r = requests.get(url=f"{app.state.COMFYUI_BASE_URL}/object_info")
info = r.json()
return list(
map(
lambda model: {"id": model, "name": model},
info["CheckpointLoaderSimple"]["input"]["required"]["ckpt_name"][0],
)
)
else:
r = requests.get(
url=f"{app.state.AUTOMATIC1111_BASE_URL}/sdapi/v1/sd-models"
)
models = r.json()
return list(
map(
lambda model: {"id": model["title"], "name": model["model_name"]},
models,
)
)
except Exception as e:
app.state.ENABLED = False
raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(e))
@@ -143,10 +257,14 @@ def get_models(user=Depends(get_current_user)):
@app.get("/models/default")
async def get_default_model(user=Depends(get_admin_user)):
try:
r = requests.get(url=f"{app.state.AUTOMATIC1111_BASE_URL}/sdapi/v1/options")
options = r.json()
return {"model": options["sd_model_checkpoint"]}
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 ""}
else:
r = requests.get(url=f"{app.state.AUTOMATIC1111_BASE_URL}/sdapi/v1/options")
options = r.json()
return {"model": options["sd_model_checkpoint"]}
except Exception as e:
app.state.ENABLED = False
raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(e))
@@ -157,16 +275,23 @@ class UpdateModelForm(BaseModel):
def set_model_handler(model: str):
r = requests.get(url=f"{app.state.AUTOMATIC1111_BASE_URL}/sdapi/v1/options")
options = r.json()
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
else:
r = requests.get(url=f"{app.state.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
)
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
)
return options
return options
@app.post("/models/default/update")
@@ -181,45 +306,170 @@ class GenerateImageForm(BaseModel):
model: Optional[str] = None
prompt: str
n: int = 1
size: str = "512x512"
size: Optional[str] = None
negative_prompt: Optional[str] = None
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)
# Write the image data to a file
with open(file_path, "wb") as f:
f.write(img_data)
return image_id
except Exception as e:
log.error(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()
with open(file_path, "wb") as image_file:
image_file.write(r.content)
return image_id
except Exception as e:
log.exception(f"Error saving image: {e}")
return None
@app.post("/generations")
def generate_image(
form_data: GenerateImageForm,
user=Depends(get_current_user),
):
print(form_data)
width, height = tuple(map(int, app.state.IMAGE_SIZE.split("x")))
r = None
try:
if form_data.model:
set_model_handler(form_data.model)
if app.state.ENGINE == "openai":
width, height = tuple(map(int, app.state.IMAGE_SIZE.split("x")))
headers = {}
headers["Authorization"] = f"Bearer {app.state.OPENAI_API_KEY}"
headers["Content-Type"] = "application/json"
data = {
"prompt": form_data.prompt,
"batch_size": form_data.n,
"width": width,
"height": height,
}
data = {
"model": app.state.MODEL if app.state.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,
"response_format": "b64_json",
}
if app.state.IMAGE_STEPS != None:
data["steps"] = app.state.IMAGE_STEPS
r = requests.post(
url=f"{app.state.OPENAI_API_BASE_URL}/images/generations",
json=data,
headers=headers,
)
if form_data.negative_prompt != None:
data["negative_prompt"] = form_data.negative_prompt
r.raise_for_status()
res = r.json()
print(data)
images = []
r = requests.post(
url=f"{app.state.AUTOMATIC1111_BASE_URL}/sdapi/v1/txt2img",
json=data,
)
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")
with open(file_body_path, "w") as f:
json.dump(data, f)
return images
elif app.state.ENGINE == "comfyui":
data = {
"prompt": form_data.prompt,
"width": width,
"height": height,
"n": form_data.n,
}
if app.state.IMAGE_STEPS != None:
data["steps"] = app.state.IMAGE_STEPS
if form_data.negative_prompt != None:
data["negative_prompt"] = form_data.negative_prompt
data = ImageGenerationPayload(**data)
res = comfyui_generate_image(
app.state.MODEL,
data,
user.id,
app.state.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")
with open(file_body_path, "w") as f:
json.dump(data.model_dump(exclude_none=True), f)
log.debug(f"images: {images}")
return images
else:
if form_data.model:
set_model_handler(form_data.model)
data = {
"prompt": form_data.prompt,
"batch_size": form_data.n,
"width": width,
"height": height,
}
if app.state.IMAGE_STEPS != None:
data["steps"] = app.state.IMAGE_STEPS
if form_data.negative_prompt != None:
data["negative_prompt"] = form_data.negative_prompt
r = requests.post(
url=f"{app.state.AUTOMATIC1111_BASE_URL}/sdapi/v1/txt2img",
json=data,
)
res = r.json()
log.debug(f"res: {res}")
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")
with open(file_body_path, "w") as f:
json.dump({**data, "info": res["info"]}, f)
return images
return r.json()
except Exception as e:
print(e)
raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(e))
error = e
if r != None:
data = r.json()
if "error" in data:
error = data["error"]["message"]
raise HTTPException(status_code=400, detail=ERROR_MESSAGES.DEFAULT(error))
+234
View File
@@ -0,0 +1,234 @@
import websocket # NOTE: websocket-client (https://github.com/websocket-client/websocket-client)
import uuid
import json
import urllib.request
import urllib.parse
import random
import logging
from config import SRC_LOG_LEVELS
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["COMFYUI"])
from pydantic import BaseModel
from typing import Optional
COMFYUI_DEFAULT_PROMPT = """
{
"3": {
"inputs": {
"seed": 0,
"steps": 20,
"cfg": 8,
"sampler_name": "euler",
"scheduler": "normal",
"denoise": 1,
"model": [
"4",
0
],
"positive": [
"6",
0
],
"negative": [
"7",
0
],
"latent_image": [
"5",
0
]
},
"class_type": "KSampler",
"_meta": {
"title": "KSampler"
}
},
"4": {
"inputs": {
"ckpt_name": "model.safetensors"
},
"class_type": "CheckpointLoaderSimple",
"_meta": {
"title": "Load Checkpoint"
}
},
"5": {
"inputs": {
"width": 512,
"height": 512,
"batch_size": 1
},
"class_type": "EmptyLatentImage",
"_meta": {
"title": "Empty Latent Image"
}
},
"6": {
"inputs": {
"text": "Prompt",
"clip": [
"4",
1
]
},
"class_type": "CLIPTextEncode",
"_meta": {
"title": "CLIP Text Encode (Prompt)"
}
},
"7": {
"inputs": {
"text": "Negative Prompt",
"clip": [
"4",
1
]
},
"class_type": "CLIPTextEncode",
"_meta": {
"title": "CLIP Text Encode (Prompt)"
}
},
"8": {
"inputs": {
"samples": [
"3",
0
],
"vae": [
"4",
2
]
},
"class_type": "VAEDecode",
"_meta": {
"title": "VAE Decode"
}
},
"9": {
"inputs": {
"filename_prefix": "ComfyUI",
"images": [
"8",
0
]
},
"class_type": "SaveImage",
"_meta": {
"title": "Save Image"
}
}
}
"""
def queue_prompt(prompt, client_id, base_url):
log.info("queue_prompt")
p = {"prompt": prompt, "client_id": client_id}
data = json.dumps(p).encode("utf-8")
req = urllib.request.Request(f"{base_url}/prompt", data=data)
return json.loads(urllib.request.urlopen(req).read())
def get_image(filename, subfolder, folder_type, base_url):
log.info("get_image")
data = {"filename": filename, "subfolder": subfolder, "type": folder_type}
url_values = urllib.parse.urlencode(data)
with urllib.request.urlopen(f"{base_url}/view?{url_values}") as response:
return response.read()
def get_image_url(filename, subfolder, folder_type, base_url):
log.info("get_image")
data = {"filename": filename, "subfolder": subfolder, "type": folder_type}
url_values = urllib.parse.urlencode(data)
return f"{base_url}/view?{url_values}"
def get_history(prompt_id, base_url):
log.info("get_history")
with urllib.request.urlopen(f"{base_url}/history/{prompt_id}") as response:
return json.loads(response.read())
def get_images(ws, prompt, client_id, base_url):
prompt_id = queue_prompt(prompt, client_id, base_url)["prompt_id"]
output_images = []
while True:
out = ws.recv()
if isinstance(out, str):
message = json.loads(out)
if message["type"] == "executing":
data = message["data"]
if data["node"] is None and data["prompt_id"] == prompt_id:
break # Execution is done
else:
continue # previews are binary data
history = get_history(prompt_id, base_url)[prompt_id]
for o in history["outputs"]:
for node_id in history["outputs"]:
node_output = history["outputs"][node_id]
if "images" in node_output:
for image in node_output["images"]:
url = get_image_url(
image["filename"], image["subfolder"], image["type"], base_url
)
output_images.append({"url": url})
return {"data": output_images}
class ImageGenerationPayload(BaseModel):
prompt: str
negative_prompt: Optional[str] = ""
steps: Optional[int] = None
seed: Optional[int] = None
width: int
height: int
n: int = 1
def comfyui_generate_image(
model: str, payload: ImageGenerationPayload, client_id, base_url
):
ws_url = base_url.replace("http://", "ws://").replace("https://", "wss://")
comfyui_prompt = json.loads(COMFYUI_DEFAULT_PROMPT)
comfyui_prompt["4"]["inputs"]["ckpt_name"] = model
comfyui_prompt["5"]["inputs"]["batch_size"] = payload.n
comfyui_prompt["5"]["inputs"]["width"] = payload.width
comfyui_prompt["5"]["inputs"]["height"] = payload.height
# set the text prompt for our positive CLIPTextEncode
comfyui_prompt["6"]["inputs"]["text"] = payload.prompt
comfyui_prompt["7"]["inputs"]["text"] = payload.negative_prompt
if payload.steps:
comfyui_prompt["3"]["inputs"]["steps"] = payload.steps
comfyui_prompt["3"]["inputs"]["seed"] = (
payload.seed if payload.seed else random.randint(0, 18446744073709551614)
)
try:
ws = websocket.WebSocket()
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}")
return None
try:
images = get_images(ws, comfyui_prompt, client_id, base_url)
except Exception as e:
log.exception(f"Error while receiving images: {e}")
images = None
ws.close()
return images
+351
View File
@@ -0,0 +1,351 @@
import sys
from fastapi import FastAPI, Depends, HTTPException
from fastapi.routing import APIRoute
from fastapi.middleware.cors import CORSMiddleware
import logging
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 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
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["LITELLM"])
from config import (
MODEL_FILTER_ENABLED,
MODEL_FILTER_LIST,
DATA_DIR,
LITELLM_PROXY_PORT,
LITELLM_PROXY_HOST,
)
from litellm.utils import get_llm_provider
import asyncio
import subprocess
import yaml
app = FastAPI()
origins = ["*"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
LITELLM_CONFIG_DIR = f"{DATA_DIR}/litellm/config.yaml"
with open(LITELLM_CONFIG_DIR, "r") as file:
litellm_config = yaml.safe_load(file)
app.state.CONFIG = litellm_config
# Global variable to store the subprocess reference
background_process = None
async def run_background_process(command):
global background_process
log.info("run_background_process")
try:
# Log the command to be executed
log.info(f"Executing command: {command}")
# Execute the command and create a subprocess
process = await asyncio.create_subprocess_exec(
*command, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
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:
log.error(f"Failed to start subprocess: {e}")
raise # Optionally re-raise the exception if you want it to propagate
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,
]
await run_background_process(command)
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
@app.on_event("startup")
async def startup_event():
log.info("startup_event")
# TODO: Check config.yaml file and create one
asyncio.create_task(start_litellm_background())
app.state.MODEL_FILTER_ENABLED = MODEL_FILTER_ENABLED
app.state.MODEL_FILTER_LIST = MODEL_FILTER_LIST
@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)):
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.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"],
)
)
return 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']}"
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",
}
@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
)
File diff suppressed because it is too large Load Diff
-127
View File
@@ -1,127 +0,0 @@
from fastapi import FastAPI, Request, Response, HTTPException, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse
import requests
import json
from pydantic import BaseModel
from apps.web.models.users import Users
from constants import ERROR_MESSAGES
from utils.utils import decode_token, get_current_user
from config import OLLAMA_API_BASE_URL, WEBUI_AUTH
import aiohttp
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.state.OLLAMA_API_BASE_URL = OLLAMA_API_BASE_URL
# TARGET_SERVER_URL = OLLAMA_API_BASE_URL
@app.get("/url")
async def get_ollama_api_url(user=Depends(get_current_user)):
if user and user.role == "admin":
return {"OLLAMA_API_BASE_URL": app.state.OLLAMA_API_BASE_URL}
else:
raise HTTPException(status_code=401, detail=ERROR_MESSAGES.ACCESS_PROHIBITED)
class UrlUpdateForm(BaseModel):
url: str
@app.post("/url/update")
async def update_ollama_api_url(
form_data: UrlUpdateForm, user=Depends(get_current_user)
):
if user and user.role == "admin":
app.state.OLLAMA_API_BASE_URL = form_data.url
return {"OLLAMA_API_BASE_URL": app.state.OLLAMA_API_BASE_URL}
else:
raise HTTPException(status_code=401, detail=ERROR_MESSAGES.ACCESS_PROHIBITED)
# async def fetch_sse(method, target_url, body, headers):
# async with aiohttp.ClientSession() as session:
# try:
# async with session.request(
# method, target_url, data=body, headers=headers
# ) as response:
# print(response.status)
# async for line in response.content:
# yield line
# except Exception as e:
# print(e)
# error_detail = "Open WebUI: Server Connection Error"
# yield json.dumps({"error": error_detail, "message": str(e)}).encode()
@app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
async def proxy(path: str, request: Request, user=Depends(get_current_user)):
target_url = f"{app.state.OLLAMA_API_BASE_URL}/{path}"
print(target_url)
body = await request.body()
headers = dict(request.headers)
if user.role in ["user", "admin"]:
if path in ["pull", "delete", "push", "copy", "create"]:
if user.role != "admin":
raise HTTPException(
status_code=401, detail=ERROR_MESSAGES.ACCESS_PROHIBITED
)
else:
raise HTTPException(status_code=401, detail=ERROR_MESSAGES.ACCESS_PROHIBITED)
headers.pop("Host", None)
headers.pop("Authorization", None)
headers.pop("Origin", None)
headers.pop("Referer", None)
session = aiohttp.ClientSession()
response = None
try:
response = await session.request(
request.method, target_url, data=body, headers=headers
)
print(response)
if not response.ok:
data = await response.json()
print(data)
response.raise_for_status()
async def generate():
async for line in response.content:
print(line)
yield line
await session.close()
return StreamingResponse(generate(), response.status)
except Exception as e:
print(e)
error_detail = "Open WebUI: Server Connection Error"
if response is not None:
try:
res = await response.json()
if "error" in res:
error_detail = f"Ollama: {res['error']}"
except:
error_detail = f"Ollama: {e}"
await session.close()
raise HTTPException(
status_code=response.status if response else 500,
detail=error_detail,
)
+242 -95
View File
@@ -3,7 +3,11 @@ from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import StreamingResponse, JSONResponse, FileResponse
import requests
import aiohttp
import asyncio
import json
import logging
from pydantic import BaseModel
@@ -15,11 +19,23 @@ from utils.utils import (
get_verified_user,
get_admin_user,
)
from config import OPENAI_API_BASE_URL, OPENAI_API_KEY, CACHE_DIR
from config import (
SRC_LOG_LEVELS,
OPENAI_API_BASE_URLS,
OPENAI_API_KEYS,
CACHE_DIR,
MODEL_FILTER_ENABLED,
MODEL_FILTER_LIST,
)
from typing import List, Optional
import hashlib
from pathlib import Path
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["OPENAI"])
app = FastAPI()
app.add_middleware(
CORSMiddleware,
@@ -29,132 +45,275 @@ app.add_middleware(
allow_headers=["*"],
)
app.state.OPENAI_API_BASE_URL = OPENAI_API_BASE_URL
app.state.OPENAI_API_KEY = OPENAI_API_KEY
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.MODELS = {}
class UrlUpdateForm(BaseModel):
url: str
@app.middleware("http")
async def check_url(request: Request, call_next):
if len(app.state.MODELS) == 0:
await get_all_models()
else:
pass
response = await call_next(request)
return response
class KeyUpdateForm(BaseModel):
key: str
class UrlsUpdateForm(BaseModel):
urls: List[str]
@app.get("/url")
async def get_openai_url(user=Depends(get_admin_user)):
return {"OPENAI_API_BASE_URL": app.state.OPENAI_API_BASE_URL}
class KeysUpdateForm(BaseModel):
keys: List[str]
@app.post("/url/update")
async def update_openai_url(form_data: UrlUpdateForm, user=Depends(get_admin_user)):
app.state.OPENAI_API_BASE_URL = form_data.url
return {"OPENAI_API_BASE_URL": app.state.OPENAI_API_BASE_URL}
@app.get("/urls")
async def get_openai_urls(user=Depends(get_admin_user)):
return {"OPENAI_API_BASE_URLS": app.state.OPENAI_API_BASE_URLS}
@app.get("/key")
async def get_openai_key(user=Depends(get_admin_user)):
return {"OPENAI_API_KEY": app.state.OPENAI_API_KEY}
@app.post("/urls/update")
async def update_openai_urls(form_data: UrlsUpdateForm, user=Depends(get_admin_user)):
await get_all_models()
app.state.OPENAI_API_BASE_URLS = form_data.urls
return {"OPENAI_API_BASE_URLS": app.state.OPENAI_API_BASE_URLS}
@app.post("/key/update")
async def update_openai_key(form_data: KeyUpdateForm, user=Depends(get_admin_user)):
app.state.OPENAI_API_KEY = form_data.key
return {"OPENAI_API_KEY": app.state.OPENAI_API_KEY}
@app.get("/keys")
async def get_openai_keys(user=Depends(get_admin_user)):
return {"OPENAI_API_KEYS": app.state.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.post("/audio/speech")
async def speech(request: Request, user=Depends(get_verified_user)):
target_url = f"{app.state.OPENAI_API_BASE_URL}/audio/speech"
if app.state.OPENAI_API_KEY == "":
raise HTTPException(status_code=401, detail=ERROR_MESSAGES.API_KEY_NOT_FOUND)
body = await request.body()
name = hashlib.sha256(body).hexdigest()
SPEECH_CACHE_DIR = Path(CACHE_DIR).joinpath("./audio/speech/")
SPEECH_CACHE_DIR.mkdir(parents=True, exist_ok=True)
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.OPENAI_API_KEY}"
headers["Content-Type"] = "application/json"
idx = None
try:
print("openai")
r = requests.post(
url=target_url,
data=body,
headers=headers,
stream=True,
)
idx = app.state.OPENAI_API_BASE_URLS.index("https://api.openai.com/v1")
body = await request.body()
name = hashlib.sha256(body).hexdigest()
r.raise_for_status()
SPEECH_CACHE_DIR = Path(CACHE_DIR).joinpath("./audio/speech/")
SPEECH_CACHE_DIR.mkdir(parents=True, exist_ok=True)
file_path = SPEECH_CACHE_DIR.joinpath(f"{name}.mp3")
file_body_path = SPEECH_CACHE_DIR.joinpath(f"{name}.json")
# 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)
# Check if the file already exists in the cache
if file_path.is_file():
return FileResponse(file_path)
with open(file_body_path, "w") as f:
json.dump(json.loads(body.decode("utf-8")), f)
headers = {}
headers["Authorization"] = f"Bearer {app.state.OPENAI_API_KEYS[idx]}"
headers["Content-Type"] = "application/json"
# Return the saved file
return FileResponse(file_path)
r = None
try:
r = requests.post(
url=f"{app.state.OPENAI_API_BASE_URLS[idx]}/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']}"
except:
error_detail = f"External: {e}"
raise HTTPException(
status_code=r.status_code if r else 500, detail=error_detail
)
except ValueError:
raise HTTPException(status_code=401, detail=ERROR_MESSAGES.OPENAI_NOT_FOUND)
async def fetch_url(url, key):
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()
except Exception as e:
print(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}"
# Handle connection error here
log.error(f"Connection error: {e}")
return None
raise HTTPException(status_code=r.status_code, detail=error_detail)
def merge_models_lists(model_lists):
merged_list = []
for idx, models in enumerate(model_lists):
if models is not None and "error" not in models:
merged_list.extend(
[
{**model, "urlIdx": idx}
for model in models
if "api.openai.com" not in app.state.OPENAI_API_BASE_URLS[idx]
or "gpt" in model["id"]
]
)
return merged_list
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] == "":
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)
]
responses = await asyncio.gather(*tasks)
models = {
"data": merge_models_lists(
list(
map(
lambda response: (
response["data"]
if response and "data" in response
else None
),
responses,
)
)
)
}
log.info(f"models: {models}")
app.state.MODELS = {model["id"]: model for model in models["data"]}
return models
@app.get("/models")
@app.get("/models/{url_idx}")
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 user.role == "user":
models["data"] = list(
filter(
lambda model: model["id"] in app.state.MODEL_FILTER_LIST,
models["data"],
)
)
return models
return models
else:
url = app.state.OPENAI_API_BASE_URLS[url_idx]
r = None
try:
r = requests.request(method="GET", url=f"{url}/models")
r.raise_for_status()
response_data = r.json()
if "api.openai.com" in url:
response_data["data"] = list(
filter(lambda model: "gpt" in model["id"], response_data["data"])
)
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']}"
except:
error_detail = f"External: {e}"
raise HTTPException(
status_code=r.status_code if r else 500,
detail=error_detail,
)
@app.api_route("/{path:path}", methods=["GET", "POST", "PUT", "DELETE"])
async def proxy(path: str, request: Request, user=Depends(get_verified_user)):
target_url = f"{app.state.OPENAI_API_BASE_URL}/{path}"
print(target_url, app.state.OPENAI_API_KEY)
if app.state.OPENAI_API_KEY == "":
raise HTTPException(status_code=401, detail=ERROR_MESSAGES.API_KEY_NOT_FOUND)
idx = 0
body = await request.body()
# TODO: Remove below after gpt-4-vision fix from Open AI
# Try to decode the body of the request from bytes to a UTF-8 string (Require add max_token to fix gpt-4-vision)
try:
body = body.decode("utf-8")
body = json.loads(body)
idx = app.state.MODELS[body.get("model")]["urlIdx"]
# Check if the model is "gpt-4-vision-preview" and set "max_tokens" to 4000
# This is a workaround until OpenAI fixes the issue with this model
if body.get("model") == "gpt-4-vision-preview":
if "max_tokens" not in body:
body["max_tokens"] = 4000
print("Modified body_dict:", body)
log.debug("Modified body_dict:", body)
# Fix for ChatGPT calls failing because the num_ctx key is in body
if "num_ctx" in body:
# If 'num_ctx' is in the dictionary, delete it
# Leaving it there generates an error with the
# OpenAI API (Feb 2024)
del body["num_ctx"]
# Convert the modified body back to JSON
body = json.dumps(body)
except json.JSONDecodeError as e:
print("Error loading request body into a dictionary:", 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]
target_url = f"{url}/{path}"
if key == "":
raise HTTPException(status_code=401, detail=ERROR_MESSAGES.API_KEY_NOT_FOUND)
headers = {}
headers["Authorization"] = f"Bearer {app.state.OPENAI_API_KEY}"
headers["Authorization"] = f"Bearer {key}"
headers["Content-Type"] = "application/json"
r = None
try:
r = requests.request(
method=request.method,
@@ -174,31 +333,19 @@ async def proxy(path: str, request: Request, user=Depends(get_verified_user)):
headers=dict(r.headers),
)
else:
# For non-SSE, read the response and return it
# response_data = (
# r.json()
# if r.headers.get("Content-Type", "")
# == "application/json"
# else r.text
# )
response_data = r.json()
if "openai" in app.state.OPENAI_API_BASE_URL and path == "models":
response_data["data"] = list(
filter(lambda model: "gpt" in model["id"], response_data["data"])
)
return response_data
except Exception as e:
print(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']}"
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, detail=error_detail)
raise HTTPException(
status_code=r.status_code if r else 500, detail=error_detail
)
+377 -204
View File
@@ -8,19 +8,19 @@ from fastapi import (
Form,
)
from fastapi.middleware.cors import CORSMiddleware
import os, shutil
import os, shutil, logging, re
from pathlib import Path
from typing import List
from sentence_transformers import SentenceTransformer
from chromadb.utils import embedding_functions
from chromadb.utils.batch_utils import create_batches
from langchain_community.document_loaders import (
WebBaseLoader,
TextLoader,
PyPDFLoader,
CSVLoader,
BSHTMLLoader,
Docx2txtLoader,
UnstructuredEPubLoader,
UnstructuredWordDocumentLoader,
@@ -37,6 +37,9 @@ import mimetypes
import uuid
import json
import sentence_transformers
from apps.ollama.main import generate_ollama_embeddings, GenerateEmbeddingsForm
from apps.web.models.documents import (
Documents,
@@ -44,6 +47,12 @@ from apps.web.models.documents import (
DocumentResponse,
)
from apps.rag.utils import (
query_embeddings_doc,
query_embeddings_collection,
generate_openai_embeddings,
)
from utils.misc import (
calculate_sha256,
calculate_sha256_string,
@@ -52,10 +61,15 @@ from utils.misc import (
)
from utils.utils import get_current_user, get_admin_user
from config import (
SRC_LOG_LEVELS,
UPLOAD_DIR,
DOCS_DIR,
RAG_EMBEDDING_ENGINE,
RAG_EMBEDDING_MODEL,
RAG_EMBEDDING_MODEL_DEVICE_TYPE,
RAG_EMBEDDING_MODEL_TRUST_REMOTE_CODE,
RAG_OPENAI_API_BASE_URL,
RAG_OPENAI_API_KEY,
DEVICE_TYPE,
CHROMA_CLIENT,
CHUNK_SIZE,
CHUNK_OVERLAP,
@@ -64,27 +78,32 @@ from config import (
from constants import ERROR_MESSAGES
#
# if RAG_EMBEDDING_MODEL:
# sentence_transformer_ef = SentenceTransformer(
# model_name_or_path=RAG_EMBEDDING_MODEL,
# cache_folder=RAG_EMBEDDING_MODEL_DIR,
# device=RAG_EMBEDDING_MODEL_DEVICE_TYPE,
# )
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["RAG"])
app = FastAPI()
app.state.TOP_K = 4
app.state.CHUNK_SIZE = CHUNK_SIZE
app.state.CHUNK_OVERLAP = CHUNK_OVERLAP
app.state.RAG_TEMPLATE = RAG_TEMPLATE
app.state.RAG_EMBEDDING_ENGINE = RAG_EMBEDDING_ENGINE
app.state.RAG_EMBEDDING_MODEL = RAG_EMBEDDING_MODEL
app.state.sentence_transformer_ef = (
embedding_functions.SentenceTransformerEmbeddingFunction(
model_name=app.state.RAG_EMBEDDING_MODEL,
device=RAG_EMBEDDING_MODEL_DEVICE_TYPE,
app.state.RAG_TEMPLATE = RAG_TEMPLATE
app.state.OPENAI_API_BASE_URL = RAG_OPENAI_API_BASE_URL
app.state.OPENAI_API_KEY = RAG_OPENAI_API_KEY
app.state.PDF_EXTRACT_IMAGES = False
if app.state.RAG_EMBEDDING_ENGINE == "":
app.state.sentence_transformer_ef = sentence_transformers.SentenceTransformer(
app.state.RAG_EMBEDDING_MODEL,
device=DEVICE_TYPE,
trust_remote_code=RAG_EMBEDDING_MODEL_TRUST_REMOTE_CODE,
)
)
origins = ["*"]
@@ -106,33 +125,6 @@ class StoreWebForm(CollectionNameForm):
url: str
def store_data_in_vector_db(data, collection_name) -> bool:
text_splitter = RecursiveCharacterTextSplitter(
chunk_size=app.state.CHUNK_SIZE, chunk_overlap=app.state.CHUNK_OVERLAP
)
docs = text_splitter.split_documents(data)
texts = [doc.page_content for doc in docs]
metadatas = [doc.metadata for doc in docs]
try:
collection = CHROMA_CLIENT.create_collection(
name=collection_name,
embedding_function=app.state.sentence_transformer_ef,
)
collection.add(
documents=texts, metadatas=metadatas, ids=[str(uuid.uuid1()) for _ in texts]
)
return True
except Exception as e:
print(e)
if e.__class__.__name__ == "UniqueConstraintError":
return True
return False
@app.get("/")
async def get_status():
return {
@@ -140,46 +132,88 @@ async def get_status():
"chunk_size": app.state.CHUNK_SIZE,
"chunk_overlap": app.state.CHUNK_OVERLAP,
"template": app.state.RAG_TEMPLATE,
"embedding_engine": app.state.RAG_EMBEDDING_ENGINE,
"embedding_model": app.state.RAG_EMBEDDING_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_engine": app.state.RAG_EMBEDDING_ENGINE,
"embedding_model": app.state.RAG_EMBEDDING_MODEL,
"openai_config": {
"url": app.state.OPENAI_API_BASE_URL,
"key": app.state.OPENAI_API_KEY,
},
}
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)
):
app.state.RAG_EMBEDDING_MODEL = form_data.embedding_model
app.state.sentence_transformer_ef = (
embedding_functions.SentenceTransformerEmbeddingFunction(
model_name=app.state.RAG_EMBEDDING_MODEL,
device=RAG_EMBEDDING_MODEL_DEVICE_TYPE,
)
log.info(
f"Updating embedding model: {app.state.RAG_EMBEDDING_MODEL} to {form_data.embedding_model}"
)
try:
app.state.RAG_EMBEDDING_ENGINE = form_data.embedding_engine
if app.state.RAG_EMBEDDING_ENGINE in ["ollama", "openai"]:
app.state.RAG_EMBEDDING_MODEL = form_data.embedding_model
app.state.sentence_transformer_ef = None
if form_data.openai_config != None:
app.state.OPENAI_API_BASE_URL = form_data.openai_config.url
app.state.OPENAI_API_KEY = form_data.openai_config.key
else:
sentence_transformer_ef = sentence_transformers.SentenceTransformer(
app.state.RAG_EMBEDDING_MODEL,
device=DEVICE_TYPE,
trust_remote_code=RAG_EMBEDDING_MODEL_TRUST_REMOTE_CODE,
)
app.state.RAG_EMBEDDING_MODEL = form_data.embedding_model
app.state.sentence_transformer_ef = sentence_transformer_ef
return {
"status": True,
"embedding_engine": app.state.RAG_EMBEDDING_ENGINE,
"embedding_model": app.state.RAG_EMBEDDING_MODEL,
"openai_config": {
"url": app.state.OPENAI_API_BASE_URL,
"key": app.state.OPENAI_API_KEY,
},
}
except Exception as e:
log.exception(f"Problem updating embedding 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,
"embedding_model": app.state.RAG_EMBEDDING_MODEL,
}
@app.get("/chunk")
async def get_chunk_params(user=Depends(get_admin_user)):
return {
"status": True,
"chunk_size": app.state.CHUNK_SIZE,
"chunk_overlap": app.state.CHUNK_OVERLAP,
"pdf_extract_images": app.state.PDF_EXTRACT_IMAGES,
"chunk": {
"chunk_size": app.state.CHUNK_SIZE,
"chunk_overlap": app.state.CHUNK_OVERLAP,
},
}
@@ -188,17 +222,24 @@ class ChunkParamUpdateForm(BaseModel):
chunk_overlap: int
@app.post("/chunk/update")
async def update_chunk_params(
form_data: ChunkParamUpdateForm, user=Depends(get_admin_user)
):
app.state.CHUNK_SIZE = form_data.chunk_size
app.state.CHUNK_OVERLAP = form_data.chunk_overlap
class ConfigUpdateForm(BaseModel):
pdf_extract_images: bool
chunk: ChunkParamUpdateForm
@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
return {
"status": True,
"chunk_size": app.state.CHUNK_SIZE,
"chunk_overlap": app.state.CHUNK_OVERLAP,
"pdf_extract_images": app.state.PDF_EXTRACT_IMAGES,
"chunk": {
"chunk_size": app.state.CHUNK_SIZE,
"chunk_overlap": app.state.CHUNK_OVERLAP,
},
}
@@ -210,40 +251,71 @@ async def get_rag_template(user=Depends(get_current_user)):
}
class RAGTemplateForm(BaseModel):
template: str
@app.get("/query/settings")
async def get_query_settings(user=Depends(get_admin_user)):
return {
"status": True,
"template": app.state.RAG_TEMPLATE,
"k": app.state.TOP_K,
}
@app.post("/template/update")
async def update_rag_template(form_data: RAGTemplateForm, user=Depends(get_admin_user)):
# TODO: check template requirements
app.state.RAG_TEMPLATE = (
form_data.template if form_data.template != "" else RAG_TEMPLATE
)
class QuerySettingsForm(BaseModel):
k: Optional[int] = None
template: Optional[str] = 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}
class QueryDocForm(BaseModel):
collection_name: str
query: str
k: Optional[int] = 4
k: Optional[int] = None
@app.post("/query/doc")
def query_doc(
def query_doc_handler(
form_data: QueryDocForm,
user=Depends(get_current_user),
):
try:
# if you use docker use the model from the environment variable
collection = CHROMA_CLIENT.get_collection(
name=form_data.collection_name,
embedding_function=app.state.sentence_transformer_ef,
if app.state.RAG_EMBEDDING_ENGINE == "":
query_embeddings = app.state.sentence_transformer_ef.encode(
form_data.query
).tolist()
elif app.state.RAG_EMBEDDING_ENGINE == "ollama":
query_embeddings = generate_ollama_embeddings(
GenerateEmbeddingsForm(
**{
"model": app.state.RAG_EMBEDDING_MODEL,
"prompt": form_data.query,
}
)
)
elif app.state.RAG_EMBEDDING_ENGINE == "openai":
query_embeddings = generate_openai_embeddings(
model=app.state.RAG_EMBEDDING_MODEL,
text=form_data.query,
key=app.state.OPENAI_API_KEY,
url=app.state.OPENAI_API_BASE_URL,
)
return query_embeddings_doc(
collection_name=form_data.collection_name,
query=form_data.query,
query_embeddings=query_embeddings,
k=form_data.k if form_data.k else app.state.TOP_K,
)
result = collection.query(query_texts=[form_data.query], n_results=form_data.k)
return result
except Exception as e:
print(e)
log.exception(e)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=ERROR_MESSAGES.DEFAULT(e),
@@ -253,77 +325,48 @@ def query_doc(
class QueryCollectionsForm(BaseModel):
collection_names: List[str]
query: str
k: Optional[int] = 4
def merge_and_sort_query_results(query_results, k):
# Initialize lists to store combined data
combined_ids = []
combined_distances = []
combined_metadatas = []
combined_documents = []
# 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])
# Create a list of tuples (distance, id, metadata, document)
combined = list(
zip(combined_distances, combined_ids, combined_metadatas, combined_documents)
)
# Sort the list based on distances
combined.sort(key=lambda x: x[0])
# Unzip the sorted list
sorted_distances, sorted_ids, sorted_metadatas, sorted_documents = 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]
# Create the output dictionary
merged_query_results = {
"ids": [sorted_ids],
"distances": [sorted_distances],
"metadatas": [sorted_metadatas],
"documents": [sorted_documents],
"embeddings": None,
"uris": None,
"data": None,
}
return merged_query_results
k: Optional[int] = None
@app.post("/query/collection")
def query_collection(
def query_collection_handler(
form_data: QueryCollectionsForm,
user=Depends(get_current_user),
):
results = []
for collection_name in form_data.collection_names:
try:
# if you use docker use the model from the environment variable
collection = CHROMA_CLIENT.get_collection(
name=collection_name,
embedding_function=app.state.sentence_transformer_ef,
try:
if app.state.RAG_EMBEDDING_ENGINE == "":
query_embeddings = app.state.sentence_transformer_ef.encode(
form_data.query
).tolist()
elif app.state.RAG_EMBEDDING_ENGINE == "ollama":
query_embeddings = generate_ollama_embeddings(
GenerateEmbeddingsForm(
**{
"model": app.state.RAG_EMBEDDING_MODEL,
"prompt": form_data.query,
}
)
)
elif app.state.RAG_EMBEDDING_ENGINE == "openai":
query_embeddings = generate_openai_embeddings(
model=app.state.RAG_EMBEDDING_MODEL,
text=form_data.query,
key=app.state.OPENAI_API_KEY,
url=app.state.OPENAI_API_BASE_URL,
)
result = collection.query(
query_texts=[form_data.query], n_results=form_data.k
)
results.append(result)
except:
pass
return query_embeddings_collection(
collection_names=form_data.collection_names,
query_embeddings=query_embeddings,
k=form_data.k if form_data.k else app.state.TOP_K,
)
return merge_and_sort_query_results(results, form_data.k)
except Exception as e:
log.exception(e)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=ERROR_MESSAGES.DEFAULT(e),
)
@app.post("/web")
@@ -337,20 +380,106 @@ def store_web(form_data: StoreWebForm, user=Depends(get_current_user)):
if collection_name == "":
collection_name = calculate_sha256_string(form_data.url)[:63]
store_data_in_vector_db(data, collection_name)
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:
print(e)
log.exception(e)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail=ERROR_MESSAGES.DEFAULT(e),
)
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,
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)
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,
add_start_index=True,
)
docs = text_splitter.create_documents([text], metadatas=[metadata])
return store_docs_in_vector_db(docs, collection_name, overwrite)
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]
texts = list(map(lambda x: x.replace("\n", " "), texts))
metadatas = [doc.metadata for doc in docs]
try:
if overwrite:
for collection in CHROMA_CLIENT.list_collections():
if collection_name == collection.name:
log.info(f"deleting existing collection {collection_name}")
CHROMA_CLIENT.delete_collection(name=collection_name)
collection = CHROMA_CLIENT.create_collection(name=collection_name)
if app.state.RAG_EMBEDDING_ENGINE == "":
embeddings = app.state.sentence_transformer_ef.encode(texts).tolist()
elif app.state.RAG_EMBEDDING_ENGINE == "ollama":
embeddings = [
generate_ollama_embeddings(
GenerateEmbeddingsForm(
**{"model": app.state.RAG_EMBEDDING_MODEL, "prompt": text}
)
)
for text in texts
]
elif app.state.RAG_EMBEDDING_ENGINE == "openai":
embeddings = [
generate_openai_embeddings(
model=app.state.RAG_EMBEDDING_MODEL,
text=text,
key=app.state.OPENAI_API_KEY,
url=app.state.OPENAI_API_BASE_URL,
)
for text in texts
]
for batch in create_batches(
api=CHROMA_CLIENT,
ids=[str(uuid.uuid1()) for _ in texts],
metadatas=metadatas,
embeddings=embeddings,
documents=texts,
):
collection.add(*batch)
return True
except Exception as e:
log.exception(e)
if e.__class__.__name__ == "UniqueConstraintError":
return True
return False
def get_loader(filename: str, file_content_type: str, file_path: str):
file_ext = filename.split(".")[-1].lower()
known_type = True
@@ -401,13 +530,15 @@ def get_loader(filename: str, file_content_type: str, file_path: str):
]
if file_ext == "pdf":
loader = PyPDFLoader(file_path)
loader = PyPDFLoader(file_path, extract_images=app.state.PDF_EXTRACT_IMAGES)
elif file_ext == "csv":
loader = CSVLoader(file_path)
elif file_ext == "rst":
loader = UnstructuredRSTLoader(file_path, mode="elements")
elif file_ext == "xml":
loader = UnstructuredXMLLoader(file_path)
elif file_ext in ["htm", "html"]:
loader = BSHTMLLoader(file_path, open_encoding="unicode_escape")
elif file_ext == "md":
loader = UnstructuredMarkdownLoader(file_path)
elif file_content_type == "application/epub+zip":
@@ -423,10 +554,12 @@ def get_loader(filename: str, file_content_type: str, file_path: str):
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
] or file_ext in ["xls", "xlsx"]:
loader = UnstructuredExcelLoader(file_path)
elif file_ext in known_source_ext or (file_content_type and file_content_type.find("text/") >= 0):
loader = TextLoader(file_path)
elif file_ext in known_source_ext or (
file_content_type and file_content_type.find("text/") >= 0
):
loader = TextLoader(file_path, autodetect_encoding=True)
else:
loader = TextLoader(file_path)
loader = TextLoader(file_path, autodetect_encoding=True)
known_type = False
return loader, known_type
@@ -440,10 +573,13 @@ def store_doc(
):
# "https://www.gutenberg.org/files/1727/1727-h/1727-h.htm"
print(file.content_type)
log.info(f"file.content_type: {file.content_type}")
try:
filename = file.filename
unsanitized_filename = file.filename
filename = os.path.basename(unsanitized_filename)
file_path = f"{UPLOAD_DIR}/{filename}"
contents = file.file.read()
with open(file_path, "wb") as f:
f.write(contents)
@@ -454,24 +590,26 @@ def store_doc(
collection_name = calculate_sha256(f)[:63]
f.close()
loader, known_type = get_loader(file.filename, file.content_type, file_path)
loader, known_type = get_loader(filename, file.content_type, file_path)
data = loader.load()
result = store_data_in_vector_db(data, collection_name)
if result:
return {
"status": True,
"collection_name": collection_name,
"filename": filename,
"known_type": known_type,
}
else:
try:
result = store_data_in_vector_db(data, collection_name)
if result:
return {
"status": True,
"collection_name": collection_name,
"filename": filename,
"known_type": known_type,
}
except Exception as e:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=ERROR_MESSAGES.DEFAULT(),
detail=e,
)
except Exception as e:
print(e)
log.exception(e)
if "No pandoc was found" in str(e):
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
@@ -484,6 +622,37 @@ def store_doc(
)
class TextRAGForm(BaseModel):
name: str
content: str
collection_name: Optional[str] = None
@app.post("/text")
def store_text(
form_data: TextRAGForm,
user=Depends(get_current_user),
):
collection_name = form_data.collection_name
if collection_name == None:
collection_name = calculate_sha256_string(form_data.content)
result = store_text_in_vector_db(
form_data.content,
metadata={"name": form_data.name, "created_by": user.id},
collection_name=collection_name,
)
if result:
return {"status": True, "collection_name": collection_name}
else:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=ERROR_MESSAGES.DEFAULT(),
)
@app.get("/scan")
def scan_docs_dir(user=Depends(get_admin_user)):
for path in Path(DOCS_DIR).rglob("./**/*"):
@@ -502,41 +671,45 @@ def scan_docs_dir(user=Depends(get_admin_user)):
)
data = loader.load()
result = store_data_in_vector_db(data, collection_name)
try:
result = store_data_in_vector_db(data, collection_name)
if result:
sanitized_filename = sanitize_filename(filename)
doc = Documents.get_doc_by_name(sanitized_filename)
if result:
sanitized_filename = sanitize_filename(filename)
doc = Documents.get_doc_by_name(sanitized_filename)
if doc == None:
doc = Documents.insert_new_doc(
user.id,
DocumentForm(
**{
"name": sanitized_filename,
"title": filename,
"collection_name": collection_name,
"filename": filename,
"content": (
json.dumps(
{
"tags": list(
map(
lambda name: {"name": name},
tags,
if doc == None:
doc = Documents.insert_new_doc(
user.id,
DocumentForm(
**{
"name": sanitized_filename,
"title": filename,
"collection_name": collection_name,
"filename": filename,
"content": (
json.dumps(
{
"tags": list(
map(
lambda name: {"name": name},
tags,
)
)
)
}
)
if len(tags)
else "{}"
),
}
),
)
}
)
if len(tags)
else "{}"
),
}
),
)
except Exception as e:
log.exception(e)
pass
except Exception as e:
print(e)
log.exception(e)
return True
@@ -557,11 +730,11 @@ def reset(user=Depends(get_admin_user)) -> bool:
elif os.path.isdir(file_path):
shutil.rmtree(file_path)
except Exception as e:
print("Failed to delete %s. Reason: %s" % (file_path, e))
log.error("Failed to delete %s. Reason: %s" % (file_path, e))
try:
CHROMA_CLIENT.reset()
except Exception as e:
print(e)
log.exception(e)
return True
+252
View File
@@ -0,0 +1,252 @@
import logging
import requests
from typing import List
from apps.ollama.main import (
generate_ollama_embeddings,
GenerateEmbeddingsForm,
)
from config import SRC_LOG_LEVELS, CHROMA_CLIENT
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["RAG"])
def query_embeddings_doc(collection_name: str, query: str, query_embeddings, k: int):
try:
# if you use docker use the model from the environment variable
log.info(f"query_embeddings_doc {query_embeddings}")
collection = CHROMA_CLIENT.get_collection(name=collection_name)
result = collection.query(
query_embeddings=[query_embeddings],
n_results=k,
)
log.info(f"query_embeddings_doc:result {result}")
return result
except Exception as e:
raise e
def merge_and_sort_query_results(query_results, k):
# Initialize lists to store combined data
combined_ids = []
combined_distances = []
combined_metadatas = []
combined_documents = []
# 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])
# Create a list of tuples (distance, id, metadata, document)
combined = list(
zip(combined_distances, combined_ids, combined_metadatas, combined_documents)
)
# Sort the list based on distances
combined.sort(key=lambda x: x[0])
# Unzip the sorted list
sorted_distances, sorted_ids, sorted_metadatas, sorted_documents = 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]
# Create the output dictionary
merged_query_results = {
"ids": [sorted_ids],
"distances": [sorted_distances],
"metadatas": [sorted_metadatas],
"documents": [sorted_documents],
"embeddings": None,
"uris": None,
"data": None,
}
return merged_query_results
def query_embeddings_collection(
collection_names: List[str], query: str, query_embeddings, k: int
):
results = []
log.info(f"query_embeddings_collection {query_embeddings}")
for collection_name in collection_names:
try:
result = query_embeddings_doc(
collection_name=collection_name,
query=query,
query_embeddings=query_embeddings,
k=k,
)
results.append(result)
except:
pass
return merge_and_sort_query_results(results, k)
def rag_template(template: str, context: str, query: str):
template = template.replace("[context]", context)
template = template.replace("[query]", query)
return template
def rag_messages(
docs,
messages,
template,
k,
embedding_engine,
embedding_model,
embedding_function,
openai_key,
openai_url,
):
log.debug(
f"docs: {docs} {messages} {embedding_engine} {embedding_model} {embedding_function} {openai_key} {openai_url}"
)
last_user_message_idx = None
for i in range(len(messages) - 1, -1, -1):
if messages[i]["role"] == "user":
last_user_message_idx = i
break
user_message = messages[last_user_message_idx]
if isinstance(user_message["content"], list):
# Handle list content input
content_type = "list"
query = ""
for content_item in user_message["content"]:
if content_item["type"] == "text":
query = content_item["text"]
break
elif isinstance(user_message["content"], str):
# Handle text content input
content_type = "text"
query = user_message["content"]
else:
# Fallback in case the input does not match expected types
content_type = None
query = ""
relevant_contexts = []
for doc in docs:
context = None
try:
if doc["type"] == "text":
context = doc["content"]
else:
if embedding_engine == "":
query_embeddings = embedding_function.encode(query).tolist()
elif embedding_engine == "ollama":
query_embeddings = generate_ollama_embeddings(
GenerateEmbeddingsForm(
**{
"model": embedding_model,
"prompt": query,
}
)
)
elif embedding_engine == "openai":
query_embeddings = generate_openai_embeddings(
model=embedding_model,
text=query,
key=openai_key,
url=openai_url,
)
if doc["type"] == "collection":
context = query_embeddings_collection(
collection_names=doc["collection_names"],
query=query,
query_embeddings=query_embeddings,
k=k,
)
else:
context = query_embeddings_doc(
collection_name=doc["collection_name"],
query=query,
query_embeddings=query_embeddings,
k=k,
)
except Exception as e:
log.exception(e)
context = None
relevant_contexts.append(context)
log.debug(f"relevant_contexts: {relevant_contexts}")
context_string = ""
for context in relevant_contexts:
if context:
context_string += " ".join(context["documents"][0]) + "\n"
ra_content = rag_template(
template=template,
context=context_string,
query=query,
)
if content_type == "list":
new_content = []
for content_item in user_message["content"]:
if content_item["type"] == "text":
# Update the text item's content with ra_content
new_content.append({"type": "text", "text": ra_content})
else:
# Keep other types of content as they are
new_content.append(content_item)
new_user_message = {**user_message, "content": new_content}
else:
new_user_message = {
**user_message,
"content": ra_content,
}
messages[last_user_message_idx] = new_user_message
return messages
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
+19 -3
View File
@@ -1,6 +1,22 @@
from peewee import *
from config import DATA_DIR
from peewee_migrate import Router
from config import SRC_LOG_LEVELS, DATA_DIR
import os
import logging
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["DB"])
# Check if the file exists
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.")
else:
pass
DB = SqliteDatabase(f"{DATA_DIR}/ollama.db")
DB.connect()
DB = SqliteDatabase(f"{DATA_DIR}/webui.db")
router = Router(DB, migrate_dir="apps/web/internal/migrations", logger=log)
router.run()
DB.connect(reuse_if_open=True)
@@ -0,0 +1,149 @@
"""Peewee migrations -- 001_initial_schema.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.create_model
class Auth(pw.Model):
id = pw.CharField(max_length=255, unique=True)
email = pw.CharField(max_length=255)
password = pw.CharField(max_length=255)
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.CharField()
chat = pw.TextField()
timestamp = pw.DateField()
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.DateField()
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.CharField()
filename = pw.CharField()
content = pw.TextField(null=True)
user_id = pw.CharField(max_length=255)
timestamp = pw.DateField()
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.DateField()
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.CharField()
content = pw.TextField()
timestamp = pw.DateField()
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.CharField(max_length=255)
timestamp = pw.DateField()
class Meta:
table_name = "user"
def rollback(migrator: Migrator, database: pw.Database, *, fake=False):
"""Write your rollback migrations here."""
migrator.remove_model("user")
migrator.remove_model("tag")
migrator.remove_model("prompt")
migrator.remove_model("modelfile")
migrator.remove_model("document")
migrator.remove_model("chatidtag")
migrator.remove_model("chat")
migrator.remove_model("auth")
@@ -0,0 +1,48 @@
"""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", share_id=pw.CharField(max_length=255, null=True, unique=True)
)
def rollback(migrator: Migrator, database: pw.Database, *, fake=False):
"""Write your rollback migrations here."""
migrator.remove_fields("chat", "share_id")
@@ -0,0 +1,48 @@
"""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(
"user", api_key=pw.CharField(max_length=255, null=True, unique=True)
)
def rollback(migrator: Migrator, database: pw.Database, *, fake=False):
"""Write your rollback migrations here."""
migrator.remove_fields("user", "api_key")
@@ -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,77 @@
"""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 '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 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("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))
@@ -0,0 +1,21 @@
# Database Migrations
This directory contains all the database migrations for the web app.
Migrations are done using the [`peewee-migrate`](https://github.com/klen/peewee_migrate) library.
Migrations are automatically ran at app startup.
## Creating a migration
Have you made a change to the schema of an existing model?
You will need to create a migration file to ensure that existing databases are updated for backwards compatibility.
1. Have a database file (`webui.db`) that has the old schema prior to any of your changes.
2. Make your changes to the models.
3. From the `backend` directory, run the following command:
```bash
pw_migrate create --auto --auto-source apps.web.models --database sqlite:///${SQLITE_DB} --directory apps/web/internal/migrations ${MIGRATION_NAME}
```
- `$SQLITE_DB` should be the path to the database file.
- `$MIGRATION_NAME` should be a descriptive name for the migration.
4. The migration file will be created in the `apps/web/internal/migrations` directory.
+4 -1
View File
@@ -19,6 +19,8 @@ from config import (
DEFAULT_USER_ROLE,
ENABLE_SIGNUP,
USER_PERMISSIONS,
WEBHOOK_URL,
WEBUI_AUTH_TRUSTED_EMAIL_HEADER,
)
app = FastAPI()
@@ -32,7 +34,8 @@ 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.AUTH_TRUSTED_EMAIL_HEADER = WEBUI_AUTH_TRUSTED_EMAIL_HEADER
app.add_middleware(
CORSMiddleware,
+42 -4
View File
@@ -2,6 +2,7 @@ from pydantic import BaseModel
from typing import List, Union, Optional
import time
import uuid
import logging
from peewee import *
from apps.web.models.users import UserModel, Users
@@ -9,6 +10,11 @@ from utils.utils import verify_password
from apps.web.internal.db import DB
from config import SRC_LOG_LEVELS
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["MODELS"])
####################
# DB MODEL
####################
@@ -41,6 +47,10 @@ class Token(BaseModel):
token_type: str
class ApiKey(BaseModel):
api_key: Optional[str] = None
class UserResponse(BaseModel):
id: str
email: str
@@ -76,6 +86,7 @@ class SignupForm(BaseModel):
name: str
email: str
password: str
profile_image_url: Optional[str] = "/user.png"
class AuthsTable:
@@ -84,9 +95,14 @@ class AuthsTable:
self.db.create_tables([Auth])
def insert_new_auth(
self, email: str, password: str, name: str, role: str = "pending"
self,
email: str,
password: str,
name: str,
profile_image_url: str = "/user.png",
role: str = "pending",
) -> Optional[UserModel]:
print("insert_new_auth")
log.info("insert_new_auth")
id = str(uuid.uuid4())
@@ -95,7 +111,7 @@ class AuthsTable:
)
result = Auth.create(**auth.model_dump())
user = Users.insert_new_user(id, name, email, role)
user = Users.insert_new_user(id, name, email, profile_image_url, role)
if result and user:
return user
@@ -103,7 +119,7 @@ class AuthsTable:
return None
def authenticate_user(self, email: str, password: str) -> Optional[UserModel]:
print("authenticate_user", email)
log.info(f"authenticate_user: {email}")
try:
auth = Auth.get(Auth.email == email, Auth.active == True)
if auth:
@@ -117,6 +133,28 @@ class AuthsTable:
except:
return None
def authenticate_user_by_api_key(self, api_key: str) -> Optional[UserModel]:
log.info(f"authenticate_user_by_api_key: {api_key}")
# if no api_key, return None
if not api_key:
return None
try:
user = Users.get_user_by_api_key(api_key)
return user if user else None
except:
return False
def authenticate_user_by_trusted_header(self, email: str) -> Optional[UserModel]:
log.info(f"authenticate_user_by_trusted_header: {email}")
try:
auth = Auth.get(Auth.email == email, Auth.active == True)
if auth:
user = Users.get_user_by_id(auth.id)
return user
except:
return None
def update_user_password_by_id(self, id: str, new_password: str) -> bool:
try:
query = Auth.update(password=new_password).where(Auth.id == id)
+147 -14
View File
@@ -19,7 +19,12 @@ class Chat(Model):
user_id = CharField()
title = CharField()
chat = TextField() # Save Chat JSON as Text
timestamp = DateField()
created_at = DateTimeField()
updated_at = DateTimeField()
share_id = CharField(null=True, unique=True)
archived = BooleanField(default=False)
class Meta:
database = DB
@@ -30,7 +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
####################
@@ -51,12 +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:
@@ -74,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()),
}
)
@@ -86,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()
@@ -95,12 +111,64 @@ class ChatTable:
except:
return None
def update_chat_by_id(self, id: str, chat: dict) -> Optional[ChatModel]:
def insert_shared_chat_by_chat_id(self, chat_id: str) -> Optional[ChatModel]:
# Get the existing chat to share
chat = Chat.get(Chat.id == chat_id)
# Check if the chat is already shared
if chat.share_id:
return self.get_chat_by_id_and_user_id(chat.share_id, "shared")
# Create a new chat with the same data, but with a new ID
shared_chat = ChatModel(
**{
"id": str(uuid.uuid4()),
"user_id": f"shared-{chat_id}",
"title": chat.title,
"chat": chat.chat,
"created_at": chat.created_at,
"updated_at": int(time.time()),
}
)
shared_result = Chat.create(**shared_chat.model_dump())
# Update the original chat with the share_id
result = (
Chat.update(share_id=shared_chat.id).where(Chat.id == chat_id).execute()
)
return shared_chat if (shared_result and result) else None
def update_shared_chat_by_chat_id(self, chat_id: str) -> Optional[ChatModel]:
try:
print("update_shared_chat_by_id")
chat = Chat.get(Chat.id == chat_id)
print(chat)
query = Chat.update(
title=chat.title,
chat=chat.chat,
).where(Chat.id == chat.share_id)
query.execute()
chat = Chat.get(Chat.id == chat.share_id)
return ChatModel(**model_to_dict(chat))
except:
return None
def delete_shared_chat_by_chat_id(self, chat_id: str) -> bool:
try:
query = Chat.delete().where(Chat.user_id == f"shared-{chat_id}")
query.execute() # Remove the rows, return number of rows removed.
return True
except:
return False
def update_chat_share_id_by_id(
self, id: str, share_id: Optional[str]
) -> Optional[ChatModel]:
try:
query = Chat.update(
chat=json.dumps(chat),
title=chat["title"] if "title" in chat else "New Chat",
timestamp=int(time.time()),
share_id=share_id,
).where(Chat.id == id)
query.execute()
@@ -109,14 +177,42 @@ class ChatTable:
except:
return None
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_lists_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.updated_at.desc())
# .limit(limit)
# .offset(skip)
]
def get_chat_lists_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.timestamp.desc())
.order_by(Chat.updated_at.desc())
# .limit(limit)
# .offset(skip)
]
@@ -127,14 +223,15 @@ class ChatTable:
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())
.order_by(Chat.updated_at.desc())
]
def get_all_chats(self) -> List[ChatModel]:
return [
ChatModel(**model_to_dict(chat))
for chat in Chat.select().order_by(Chat.timestamp.desc())
for chat in Chat.select().order_by(Chat.updated_at.desc())
]
def get_all_chats_by_user_id(self, user_id: str) -> List[ChatModel]:
@@ -142,9 +239,28 @@ class ChatTable:
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]:
try:
chat = Chat.get(Chat.id == id)
return ChatModel(**model_to_dict(chat))
except:
return None
def get_chat_by_share_id(self, id: str) -> Optional[ChatModel]:
try:
chat = Chat.get(Chat.share_id == id)
if chat:
chat = Chat.get(Chat.id == id)
return ChatModel(**model_to_dict(chat))
else:
return None
except:
return None
def get_chat_by_id_and_user_id(self, id: str, user_id: str) -> Optional[ChatModel]:
try:
chat = Chat.get(Chat.id == id, Chat.user_id == user_id)
@@ -163,12 +279,15 @@ class ChatTable:
query = Chat.delete().where((Chat.id == id) & (Chat.user_id == user_id))
query.execute() # Remove the rows, return number of rows removed.
return True
return True and self.delete_shared_chat_by_chat_id(id)
except:
return False
def delete_chats_by_user_id(self, user_id: str) -> bool:
try:
self.delete_shared_chats_by_user_id(user_id)
query = Chat.delete().where(Chat.user_id == user_id)
query.execute() # Remove the rows, return number of rows removed.
@@ -176,5 +295,19 @@ class ChatTable:
except:
return False
def delete_shared_chats_by_user_id(self, user_id: str) -> bool:
try:
shared_chat_ids = [
f"shared-{chat.id}"
for chat in Chat.select().where(Chat.user_id == user_id)
]
query = Chat.delete().where(Chat.user_id << shared_chat_ids)
query.execute() # Remove the rows, return number of rows removed.
return True
except:
return False
Chats = ChatTable(DB)
+8 -2
View File
@@ -3,6 +3,7 @@ from peewee import *
from playhouse.shortcuts import model_to_dict
from typing import List, Union, Optional
import time
import logging
from utils.utils import decode_token
from utils.misc import get_gravatar_url
@@ -11,6 +12,11 @@ from apps.web.internal.db import DB
import json
from config import SRC_LOG_LEVELS
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["MODELS"])
####################
# Documents DB Schema
####################
@@ -118,7 +124,7 @@ class DocumentsTable:
doc = Document.get(Document.name == form_data.name)
return DocumentModel(**model_to_dict(doc))
except Exception as e:
print(e)
log.exception(e)
return None
def update_doc_content_by_name(
@@ -138,7 +144,7 @@ class DocumentsTable:
doc = Document.get(Document.name == name)
return DocumentModel(**model_to_dict(doc))
except Exception as e:
print(e)
log.exception(e)
return None
def delete_doc_by_name(self, name: str) -> bool:
+12 -12
View File
@@ -64,8 +64,8 @@ class ModelfilesTable:
self.db.create_tables([Modelfile])
def insert_new_modelfile(
self, user_id: str,
form_data: ModelfileForm) -> Optional[ModelfileModel]:
self, user_id: str, form_data: ModelfileForm
) -> Optional[ModelfileModel]:
if "tagName" in form_data.modelfile:
modelfile = ModelfileModel(
**{
@@ -73,7 +73,8 @@ class ModelfilesTable:
"tag_name": form_data.modelfile["tagName"],
"modelfile": json.dumps(form_data.modelfile),
"timestamp": int(time.time()),
})
}
)
try:
result = Modelfile.create(**modelfile.model_dump())
@@ -87,29 +88,28 @@ class ModelfilesTable:
else:
return None
def get_modelfile_by_tag_name(self,
tag_name: str) -> Optional[ModelfileModel]:
def get_modelfile_by_tag_name(self, tag_name: str) -> Optional[ModelfileModel]:
try:
modelfile = Modelfile.get(Modelfile.tag_name == tag_name)
return ModelfileModel(**model_to_dict(modelfile))
except:
return None
def get_modelfiles(self,
skip: int = 0,
limit: int = 50) -> List[ModelfileResponse]:
def get_modelfiles(self, skip: int = 0, limit: int = 50) -> List[ModelfileResponse]:
return [
ModelfileResponse(
**{
**model_to_dict(modelfile),
"modelfile":
json.loads(modelfile.modelfile),
}) for modelfile in Modelfile.select()
"modelfile": json.loads(modelfile.modelfile),
}
)
for modelfile in Modelfile.select()
# .limit(limit).offset(skip)
]
def update_modelfile_by_tag_name(
self, tag_name: str, modelfile: dict) -> Optional[ModelfileModel]:
self, tag_name: str, modelfile: dict
) -> Optional[ModelfileModel]:
try:
query = Modelfile.update(
modelfile=json.dumps(modelfile),
+9 -6
View File
@@ -52,8 +52,9 @@ class PromptsTable:
self.db = db
self.db.create_tables([Prompt])
def insert_new_prompt(self, user_id: str,
form_data: PromptForm) -> Optional[PromptModel]:
def insert_new_prompt(
self, user_id: str, form_data: PromptForm
) -> Optional[PromptModel]:
prompt = PromptModel(
**{
"user_id": user_id,
@@ -61,7 +62,8 @@ class PromptsTable:
"title": form_data.title,
"content": form_data.content,
"timestamp": int(time.time()),
})
}
)
try:
result = Prompt.create(**prompt.model_dump())
@@ -81,13 +83,14 @@ class PromptsTable:
def get_prompts(self) -> List[PromptModel]:
return [
PromptModel(**model_to_dict(prompt)) for prompt in Prompt.select()
PromptModel(**model_to_dict(prompt))
for prompt in Prompt.select()
# .limit(limit).offset(skip)
]
def update_prompt_by_command(
self, command: str,
form_data: PromptForm) -> Optional[PromptModel]:
self, command: str, form_data: PromptForm
) -> Optional[PromptModel]:
try:
query = Prompt.update(
title=form_data.title,
+41 -10
View File
@@ -6,9 +6,15 @@ from playhouse.shortcuts import model_to_dict
import json
import uuid
import time
import logging
from apps.web.internal.db import DB
from config import SRC_LOG_LEVELS
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["MODELS"])
####################
# Tag DB Schema
####################
@@ -130,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(
@@ -145,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(
@@ -167,17 +177,13 @@ class TagTable:
.count()
)
def delete_tag_by_tag_name_and_chat_id_and_user_id(
self, tag_name: str, chat_id: str, user_id: str
) -> bool:
def delete_tag_by_tag_name_and_user_id(self, tag_name: str, user_id: str) -> bool:
try:
query = ChatIdTag.delete().where(
(ChatIdTag.tag_name == tag_name)
& (ChatIdTag.chat_id == chat_id)
& (ChatIdTag.user_id == user_id)
(ChatIdTag.tag_name == tag_name) & (ChatIdTag.user_id == user_id)
)
res = query.execute() # Remove the rows, return number of rows removed.
print(res)
log.debug(f"res: {res}")
tag_count = self.count_chat_ids_by_tag_name_and_user_id(tag_name, user_id)
if tag_count == 0:
@@ -189,7 +195,32 @@ class TagTable:
return True
except Exception as e:
print("delete_tag", e)
log.error(f"delete_tag: {e}")
return False
def delete_tag_by_tag_name_and_chat_id_and_user_id(
self, tag_name: str, chat_id: str, user_id: str
) -> bool:
try:
query = ChatIdTag.delete().where(
(ChatIdTag.tag_name == tag_name)
& (ChatIdTag.chat_id == chat_id)
& (ChatIdTag.user_id == user_id)
)
res = query.execute() # Remove the rows, return number of rows removed.
log.debug(f"res: {res}")
tag_count = self.count_chat_ids_by_tag_name_and_user_id(tag_name, user_id)
if tag_count == 0:
# Remove tag item from Tag col as well
query = Tag.delete().where(
(Tag.name == tag_name) & (Tag.user_id == user_id)
)
query.execute() # Remove the rows, return number of rows removed.
return True
except Exception as e:
log.error(f"delete_tag: {e}")
return False
def delete_tags_by_chat_id_and_user_id(self, chat_id: str, user_id: str) -> bool:
+33 -3
View File
@@ -20,6 +20,7 @@ class User(Model):
role = CharField()
profile_image_url = CharField()
timestamp = DateField()
api_key = CharField(null=True, unique=True)
class Meta:
database = DB
@@ -30,8 +31,9 @@ class UserModel(BaseModel):
name: str
email: str
role: str = "pending"
profile_image_url: str = "/user.png"
profile_image_url: str
timestamp: int # timestamp in epoch
api_key: Optional[str] = None
####################
@@ -57,7 +59,12 @@ class UsersTable:
self.db.create_tables([User])
def insert_new_user(
self, id: str, name: str, email: str, role: str = "pending"
self,
id: str,
name: str,
email: str,
profile_image_url: str = "/user.png",
role: str = "pending",
) -> Optional[UserModel]:
user = UserModel(
**{
@@ -65,7 +72,7 @@ class UsersTable:
"name": name,
"email": email,
"role": role,
"profile_image_url": "/user.png",
"profile_image_url": profile_image_url,
"timestamp": int(time.time()),
}
)
@@ -82,6 +89,13 @@ class UsersTable:
except:
return None
def get_user_by_api_key(self, api_key: str) -> Optional[UserModel]:
try:
user = User.get(User.api_key == api_key)
return UserModel(**model_to_dict(user))
except:
return None
def get_user_by_email(self, email: str) -> Optional[UserModel]:
try:
user = User.get(User.email == email)
@@ -149,5 +163,21 @@ class UsersTable:
except:
return False
def update_user_api_key_by_id(self, id: str, api_key: str) -> str:
try:
query = User.update(api_key=api_key).where(User.id == id)
result = query.execute()
return True if result == 1 else False
except:
return False
def get_user_api_key_by_id(self, id: str) -> Optional[str]:
try:
user = User.get(User.id == id)
return user.api_key
except:
return None
Users = UsersTable(DB)
+80 -10
View File
@@ -1,13 +1,10 @@
from fastapi import Response, Request
from fastapi import Depends, FastAPI, HTTPException, status
from datetime import datetime, timedelta
from typing import List, Union
from fastapi import Request
from fastapi import Depends, HTTPException, status
from fastapi import APIRouter, status
from fastapi import APIRouter
from pydantic import BaseModel
import time
import uuid
import re
import uuid
from apps.web.models.auths import (
SigninForm,
@@ -17,6 +14,7 @@ from apps.web.models.auths import (
UserResponse,
SigninResponse,
Auths,
ApiKey,
)
from apps.web.models.users import Users
@@ -25,9 +23,12 @@ from utils.utils import (
get_current_user,
get_admin_user,
create_token,
create_api_key,
)
from utils.misc import parse_duration, validate_email_format
from constants import ERROR_MESSAGES
from utils.webhook import post_webhook
from constants import ERROR_MESSAGES, WEBHOOK_MESSAGES
from config import WEBUI_AUTH_TRUSTED_EMAIL_HEADER
router = APIRouter()
@@ -78,6 +79,8 @@ async def update_profile(
async def update_password(
form_data: UpdatePasswordForm, session_user=Depends(get_current_user)
):
if WEBUI_AUTH_TRUSTED_EMAIL_HEADER:
raise HTTPException(400, detail=ERROR_MESSAGES.ACTION_PROHIBITED)
if session_user:
user = Auths.authenticate_user(session_user.email, form_data.password)
@@ -97,7 +100,22 @@ async def update_password(
@router.post("/signin", response_model=SigninResponse)
async def signin(request: Request, form_data: SigninForm):
user = Auths.authenticate_user(form_data.email.lower(), form_data.password)
if WEBUI_AUTH_TRUSTED_EMAIL_HEADER:
if WEBUI_AUTH_TRUSTED_EMAIL_HEADER not in request.headers:
raise HTTPException(400, detail=ERROR_MESSAGES.INVALID_TRUSTED_HEADER)
trusted_email = request.headers[WEBUI_AUTH_TRUSTED_EMAIL_HEADER].lower()
if not Users.get_user_by_email(trusted_email.lower()):
await signup(
request,
SignupForm(
email=trusted_email, password=str(uuid.uuid4()), name=trusted_email
),
)
user = Auths.authenticate_user_by_trusted_header(trusted_email)
else:
user = Auths.authenticate_user(form_data.email.lower(), form_data.password)
if user:
token = create_token(
data={"id": user.id},
@@ -145,7 +163,11 @@ async def signup(request: Request, form_data: SignupForm):
)
hashed = get_password_hash(form_data.password)
user = Auths.insert_new_auth(
form_data.email.lower(), hashed, form_data.name, role
form_data.email.lower(),
hashed,
form_data.name,
form_data.profile_image_url,
role,
)
if user:
@@ -155,6 +177,17 @@ async def signup(request: Request, form_data: SignupForm):
)
# response.set_cookie(key='token', value=token, httponly=True)
if request.app.state.WEBHOOK_URL:
post_webhook(
request.app.state.WEBHOOK_URL,
WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
{
"action": "signup",
"message": WEBHOOK_MESSAGES.USER_SIGNUP(user.name),
"user": user.model_dump_json(exclude_none=True),
},
)
return {
"token": token,
"token_type": "Bearer",
@@ -237,3 +270,40 @@ async def update_token_expires_duration(
return request.app.state.JWT_EXPIRES_IN
else:
return request.app.state.JWT_EXPIRES_IN
############################
# API Key
############################
# create api key
@router.post("/api_key", response_model=ApiKey)
async def create_api_key_(user=Depends(get_current_user)):
api_key = create_api_key()
success = Users.update_user_api_key_by_id(user.id, api_key)
if success:
return {
"api_key": api_key,
}
else:
raise HTTPException(500, detail=ERROR_MESSAGES.CREATE_API_KEY_ERROR)
# delete api key
@router.delete("/api_key", response_model=bool)
async def delete_api_key(user=Depends(get_current_user)):
success = Users.update_user_api_key_by_id(user.id, None)
return success
# get api key
@router.get("/api_key", response_model=ApiKey)
async def get_api_key(user=Depends(get_current_user)):
api_key = Users.get_user_api_key_by_id(user.id)
if api_key:
return {
"api_key": api_key,
}
else:
raise HTTPException(404, detail=ERROR_MESSAGES.API_KEY_NOT_FOUND)
+138 -5
View File
@@ -5,6 +5,7 @@ from utils.utils import get_current_user, get_admin_user
from fastapi import APIRouter
from pydantic import BaseModel
import json
import logging
from apps.web.models.users import Users
from apps.web.models.chats import (
@@ -27,6 +28,11 @@ from apps.web.models.tags import (
from constants import ERROR_MESSAGES
from config import SRC_LOG_LEVELS, ENABLE_ADMIN_EXPORT
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["MODELS"])
router = APIRouter()
############################
@@ -41,6 +47,18 @@ async def get_user_chats(
return Chats.get_chat_lists_by_user_id(user.id, skip, limit)
############################
# GetArchivedChats
############################
@router.get("/archived", response_model=List[ChatTitleIdResponse])
async def get_archived_user_chats(
user=Depends(get_current_user), skip: int = 0, limit: int = 50
):
return Chats.get_archived_chat_lists_by_user_id(user.id, skip, limit)
############################
# GetAllChats
############################
@@ -61,6 +79,11 @@ 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()
@@ -78,7 +101,7 @@ async def create_new_chat(form_data: ChatForm, user=Depends(get_current_user)):
chat = Chats.insert_new_chat(user.id, form_data)
return ChatResponse(**{**chat.model_dump(), "chat": json.loads(chat.chat)})
except Exception as e:
print(e)
log.exception(e)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
)
@@ -95,7 +118,7 @@ async def get_all_tags(user=Depends(get_current_user)):
tags = Tags.get_tags_by_user_id(user.id)
return tags
except Exception as e:
print(e)
log.exception(e)
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST, detail=ERROR_MESSAGES.DEFAULT()
)
@@ -115,9 +138,12 @@ async def get_user_chats_by_tag_name(
for chat_id_tag in Tags.get_chat_ids_by_tag_name_and_user_id(tag_name, user.id)
]
print(chat_ids)
chats = Chats.get_chat_lists_by_chat_ids(chat_ids, skip, limit)
return 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
############################
@@ -180,6 +206,103 @@ async def delete_chat_by_id(request: Request, id: str, user=Depends(get_current_
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()
)
############################
# ShareChatById
############################
@router.post("/{id}/share", response_model=Optional[ChatResponse])
async def share_chat_by_id(id: str, user=Depends(get_current_user)):
chat = Chats.get_chat_by_id_and_user_id(id, user.id)
if chat:
if chat.share_id:
shared_chat = Chats.update_shared_chat_by_chat_id(chat.id)
return ChatResponse(
**{**shared_chat.model_dump(), "chat": json.loads(shared_chat.chat)}
)
shared_chat = Chats.insert_shared_chat_by_chat_id(chat.id)
if not shared_chat:
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail=ERROR_MESSAGES.DEFAULT(),
)
return ChatResponse(
**{**shared_chat.model_dump(), "chat": json.loads(shared_chat.chat)}
)
else:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
)
############################
# DeletedSharedChatById
############################
@router.delete("/{id}/share", response_model=Optional[bool])
async def delete_shared_chat_by_id(id: str, user=Depends(get_current_user)):
chat = Chats.get_chat_by_id_and_user_id(id, user.id)
if chat:
if not chat.share_id:
return False
result = Chats.delete_shared_chat_by_chat_id(id)
update_result = Chats.update_chat_share_id_by_id(id, None)
return result and update_result != None
else:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail=ERROR_MESSAGES.ACCESS_PROHIBITED,
)
############################
# 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
############################
@@ -268,6 +391,16 @@ async def delete_all_chat_tags_by_id(id: str, user=Depends(get_current_user)):
@router.delete("/", response_model=bool)
async def delete_all_user_chats(user=Depends(get_current_user)):
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
+6 -2
View File
@@ -10,7 +10,12 @@ import uuid
from apps.web.models.users import Users
from utils.utils import get_password_hash, get_current_user, get_admin_user, create_token
from utils.utils import (
get_password_hash,
get_current_user,
get_admin_user,
create_token,
)
from utils.misc import get_gravatar_url, validate_email_format
from constants import ERROR_MESSAGES
@@ -43,7 +48,6 @@ async def set_global_default_models(
return request.app.state.DEFAULT_MODELS
@router.post("/default/suggestions", response_model=List[PromptSuggestion])
async def set_global_default_suggestions(
request: Request,
+24 -21
View File
@@ -24,9 +24,9 @@ router = APIRouter()
@router.get("/", response_model=List[ModelfileResponse])
async def get_modelfiles(skip: int = 0,
limit: int = 50,
user=Depends(get_current_user)):
async def get_modelfiles(
skip: int = 0, limit: int = 50, user=Depends(get_current_user)
):
return Modelfiles.get_modelfiles(skip, limit)
@@ -36,17 +36,16 @@ async def get_modelfiles(skip: int = 0,
@router.post("/create", response_model=Optional[ModelfileResponse])
async def create_new_modelfile(form_data: ModelfileForm,
user=Depends(get_admin_user)):
async def create_new_modelfile(form_data: ModelfileForm, user=Depends(get_admin_user)):
modelfile = Modelfiles.insert_new_modelfile(user.id, form_data)
if modelfile:
return ModelfileResponse(
**{
**modelfile.model_dump(),
"modelfile":
json.loads(modelfile.modelfile),
})
"modelfile": json.loads(modelfile.modelfile),
}
)
else:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
@@ -60,17 +59,18 @@ async def create_new_modelfile(form_data: ModelfileForm,
@router.post("/", response_model=Optional[ModelfileResponse])
async def get_modelfile_by_tag_name(form_data: ModelfileTagNameForm,
user=Depends(get_current_user)):
async def get_modelfile_by_tag_name(
form_data: ModelfileTagNameForm, user=Depends(get_current_user)
):
modelfile = Modelfiles.get_modelfile_by_tag_name(form_data.tag_name)
if modelfile:
return ModelfileResponse(
**{
**modelfile.model_dump(),
"modelfile":
json.loads(modelfile.modelfile),
})
"modelfile": json.loads(modelfile.modelfile),
}
)
else:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
@@ -84,8 +84,9 @@ async def get_modelfile_by_tag_name(form_data: ModelfileTagNameForm,
@router.post("/update", response_model=Optional[ModelfileResponse])
async def update_modelfile_by_tag_name(form_data: ModelfileUpdateForm,
user=Depends(get_admin_user)):
async def update_modelfile_by_tag_name(
form_data: ModelfileUpdateForm, user=Depends(get_admin_user)
):
modelfile = Modelfiles.get_modelfile_by_tag_name(form_data.tag_name)
if modelfile:
updated_modelfile = {
@@ -94,14 +95,15 @@ async def update_modelfile_by_tag_name(form_data: ModelfileUpdateForm,
}
modelfile = Modelfiles.update_modelfile_by_tag_name(
form_data.tag_name, updated_modelfile)
form_data.tag_name, updated_modelfile
)
return ModelfileResponse(
**{
**modelfile.model_dump(),
"modelfile":
json.loads(modelfile.modelfile),
})
"modelfile": json.loads(modelfile.modelfile),
}
)
else:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
@@ -115,7 +117,8 @@ async def update_modelfile_by_tag_name(form_data: ModelfileUpdateForm,
@router.delete("/delete", response_model=bool)
async def delete_modelfile_by_tag_name(form_data: ModelfileTagNameForm,
user=Depends(get_admin_user)):
async def delete_modelfile_by_tag_name(
form_data: ModelfileTagNameForm, user=Depends(get_admin_user)
):
result = Modelfiles.delete_modelfile_by_tag_name(form_data.tag_name)
return result
+7 -1
View File
@@ -7,6 +7,7 @@ from fastapi import APIRouter
from pydantic import BaseModel
import time
import uuid
import logging
from apps.web.models.users import UserModel, UserUpdateForm, UserRoleUpdateForm, Users
from apps.web.models.auths import Auths
@@ -14,6 +15,11 @@ from apps.web.models.auths import Auths
from utils.utils import get_current_user, get_password_hash, get_admin_user
from constants import ERROR_MESSAGES
from config import SRC_LOG_LEVELS
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["MODELS"])
router = APIRouter()
############################
@@ -83,7 +89,7 @@ async def update_user_by_id(
if form_data.password:
hashed = get_password_hash(form_data.password)
print(hashed)
log.debug(f"hashed: {hashed}")
Auths.update_user_password_by_id(user_id, hashed)
Auths.update_email_by_id(user_id, form_data.email.lower())
+87 -158
View File
@@ -1,174 +1,103 @@
from fastapi import APIRouter, UploadFile, File, BackgroundTasks
from fastapi import APIRouter, UploadFile, File, Response
from fastapi import Depends, HTTPException, status
from starlette.responses import StreamingResponse
from starlette.responses import StreamingResponse, FileResponse
from pydantic import BaseModel
import requests
import os
import aiohttp
import json
from fpdf import FPDF
import markdown
from utils.utils import get_admin_user
from utils.misc import calculate_sha256, get_gravatar_url
from config import OLLAMA_API_BASE_URL, DATA_DIR, UPLOAD_DIR
from config import OLLAMA_BASE_URLS, DATA_DIR, UPLOAD_DIR
from constants import ERROR_MESSAGES
from typing import List
router = APIRouter()
class UploadBlobForm(BaseModel):
filename: str
from urllib.parse import urlparse
def parse_huggingface_url(hf_url):
try:
# Parse the URL
parsed_url = urlparse(hf_url)
# Get the path and split it into components
path_components = parsed_url.path.split("/")
# Extract the desired output
user_repo = "/".join(path_components[1:3])
model_file = path_components[-1]
return model_file
except ValueError:
return None
async def download_file_stream(url, file_path, file_name, chunk_size=1024 * 1024):
done = False
if os.path.exists(file_path):
current_size = os.path.getsize(file_path)
else:
current_size = 0
headers = {"Range": f"bytes={current_size}-"} if current_size > 0 else {}
timeout = aiohttp.ClientTimeout(total=600) # Set the timeout
async with aiohttp.ClientSession(timeout=timeout) as session:
async with session.get(url, headers=headers) as response:
total_size = int(response.headers.get("content-length", 0)) + current_size
with open(file_path, "ab+") as file:
async for data in response.content.iter_chunked(chunk_size):
current_size += len(data)
file.write(data)
done = current_size == total_size
progress = round((current_size / total_size) * 100, 2)
yield f'data: {{"progress": {progress}, "completed": {current_size}, "total": {total_size}}}\n\n'
if done:
file.seek(0)
hashed = calculate_sha256(file)
file.seek(0)
url = f"{OLLAMA_API_BASE_URL}/blobs/sha256:{hashed}"
response = requests.post(url, data=file)
if response.ok:
res = {
"done": done,
"blob": f"sha256:{hashed}",
"name": file_name,
}
os.remove(file_path)
yield f"data: {json.dumps(res)}\n\n"
else:
raise "Ollama: Could not create blob, Please try again."
@router.get("/download")
async def download(
url: str,
):
# url = "https://huggingface.co/TheBloke/stablelm-zephyr-3b-GGUF/resolve/main/stablelm-zephyr-3b.Q2_K.gguf"
file_name = parse_huggingface_url(url)
if file_name:
file_path = f"{UPLOAD_DIR}/{file_name}"
return StreamingResponse(
download_file_stream(url, file_path, file_name),
media_type="text/event-stream",
)
else:
return None
@router.post("/upload")
def upload(file: UploadFile = File(...)):
file_path = f"{UPLOAD_DIR}/{file.filename}"
# Save file in chunks
with open(file_path, "wb+") as f:
for chunk in file.file:
f.write(chunk)
def file_process_stream():
total_size = os.path.getsize(file_path)
chunk_size = 1024 * 1024
try:
with open(file_path, "rb") as f:
total = 0
done = False
while not done:
chunk = f.read(chunk_size)
if not chunk:
done = True
continue
total += len(chunk)
progress = round((total / total_size) * 100, 2)
res = {
"progress": progress,
"total": total_size,
"completed": total,
}
yield f"data: {json.dumps(res)}\n\n"
if done:
f.seek(0)
hashed = calculate_sha256(f)
f.seek(0)
url = f"{OLLAMA_API_BASE_URL}/blobs/sha256:{hashed}"
response = requests.post(url, data=f)
if response.ok:
res = {
"done": done,
"blob": f"sha256:{hashed}",
"name": file.filename,
}
os.remove(file_path)
yield f"data: {json.dumps(res)}\n\n"
else:
raise Exception(
"Ollama: Could not create blob, Please try again."
)
except Exception as e:
res = {"error": str(e)}
yield f"data: {json.dumps(res)}\n\n"
return StreamingResponse(file_process_stream(), media_type="text/event-stream")
@router.get("/gravatar")
async def get_gravatar(
email: str,
):
return get_gravatar_url(email)
class MarkdownForm(BaseModel):
md: str
@router.post("/markdown")
async def get_html_from_markdown(
form_data: MarkdownForm,
):
return {"html": markdown.markdown(form_data.md)}
class ChatForm(BaseModel):
title: str
messages: List[dict]
@router.post("/pdf")
async def download_chat_as_pdf(
form_data: ChatForm,
):
pdf = FPDF()
pdf.add_page()
STATIC_DIR = "./static"
FONTS_DIR = f"{STATIC_DIR}/fonts"
pdf.add_font("NotoSans", "", f"{FONTS_DIR}/NotoSans-Regular.ttf")
pdf.add_font("NotoSans", "b", f"{FONTS_DIR}/NotoSans-Bold.ttf")
pdf.add_font("NotoSans", "i", f"{FONTS_DIR}/NotoSans-Italic.ttf")
pdf.add_font("NotoSansKR", "", f"{FONTS_DIR}/NotoSansKR-Regular.ttf")
pdf.add_font("NotoSansJP", "", f"{FONTS_DIR}/NotoSansJP-Regular.ttf")
pdf.set_font("NotoSans", size=12)
pdf.set_fallback_fonts(["NotoSansKR", "NotoSansJP"])
pdf.set_auto_page_break(auto=True, margin=15)
# Adjust the effective page width for multi_cell
effective_page_width = (
pdf.w - 2 * pdf.l_margin - 10
) # Subtracted an additional 10 for extra padding
# Add chat messages
for message in form_data.messages:
role = message["role"]
content = message["content"]
pdf.set_font("NotoSans", "B", size=14) # Bold for the role
pdf.multi_cell(effective_page_width, 10, f"{role.upper()}", 0, "L")
pdf.ln(1) # Extra space between messages
pdf.set_font("NotoSans", size=10) # Regular for content
pdf.multi_cell(effective_page_width, 6, content, 0, "L")
pdf.ln(1.5) # Extra space between messages
# Save the pdf with name .pdf
pdf_bytes = pdf.output()
return Response(
content=bytes(pdf_bytes),
media_type="application/pdf",
headers={"Content-Disposition": f"attachment;filename=chat.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,
)
return FileResponse(
f"{DATA_DIR}/webui.db",
media_type="application/octet-stream",
filename="webui.db",
)
+221 -45
View File
@@ -1,4 +1,6 @@
import os
import sys
import logging
import chromadb
from chromadb import Settings
from base64 import b64encode
@@ -16,15 +18,60 @@ from secrets import token_bytes
from constants import ERROR_MESSAGES
####################################
# 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"])
####################################
# Load .env file
####################################
try:
from dotenv import load_dotenv, find_dotenv
load_dotenv(find_dotenv("../.env"))
except ImportError:
print("dotenv not installed, skipping...")
log.warning("dotenv not installed, skipping...")
WEBUI_NAME = "Open WebUI"
shutil.copyfile("../build/favicon.png", "./static/favicon.png")
WEBUI_NAME = os.environ.get("WEBUI_NAME", "Open WebUI")
WEBUI_FAVICON_URL = "https://openwebui.com/favicon.png"
####################################
# ENV (dev,test,prod)
@@ -99,36 +146,6 @@ for version in soup.find_all("h2"):
CHANGELOG = changelog_json
####################################
# CUSTOM_NAME
####################################
CUSTOM_NAME = os.environ.get("CUSTOM_NAME", "")
if CUSTOM_NAME:
try:
r = requests.get(f"https://api.openwebui.com/api/v1/custom/{CUSTOM_NAME}")
data = r.json()
if r.ok:
if "logo" in data:
url = (
f"https://api.openwebui.com{data['logo']}"
if data["logo"][0] == "/"
else data["logo"]
)
r = requests.get(url, stream=True)
if r.status_code == 200:
with open("./static/favicon.png", "wb") as f:
r.raw.decode_content = True
shutil.copyfileobj(r.raw, f)
WEBUI_NAME = data["name"]
except Exception as e:
print(e)
pass
####################################
# DATA/FRONTEND BUILD DIR
####################################
@@ -142,6 +159,47 @@ try:
except:
CONFIG_DATA = {}
####################################
# 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")
####################################
# CUSTOM_NAME
####################################
CUSTOM_NAME = os.environ.get("CUSTOM_NAME", "")
if CUSTOM_NAME:
try:
r = requests.get(f"https://api.openwebui.com/api/v1/custom/{CUSTOM_NAME}")
data = r.json()
if r.ok:
if "logo" in data:
WEBUI_FAVICON_URL = url = (
f"https://api.openwebui.com{data['logo']}"
if data["logo"][0] == "/"
else data["logo"]
)
r = requests.get(url, stream=True)
if r.status_code == 200:
with open(f"{STATIC_DIR}/favicon.png", "wb") as f:
r.raw.decode_content = True
shutil.copyfileobj(r.raw, f)
WEBUI_NAME = data["name"]
except Exception as e:
log.exception(e)
pass
else:
if WEBUI_NAME != "Open WebUI":
WEBUI_NAME += " (Open WebUI)"
####################################
# File Upload DIR
####################################
@@ -194,22 +252,47 @@ def create_config_file(file_path):
LITELLM_CONFIG_PATH = f"{DATA_DIR}/litellm/config.yaml"
if not os.path.exists(LITELLM_CONFIG_PATH):
print("Config file doesn't exist. Creating...")
log.info("Config file doesn't exist. Creating...")
create_config_file(LITELLM_CONFIG_PATH)
print("Config file created successfully.")
log.info("Config file created successfully.")
####################################
# OLLAMA_API_BASE_URL
# OLLAMA_BASE_URL
####################################
OLLAMA_API_BASE_URL = os.environ.get(
"OLLAMA_API_BASE_URL", "http://localhost:11434/api"
)
OLLAMA_BASE_URL = os.environ.get("OLLAMA_BASE_URL", "")
K8S_FLAG = os.environ.get("K8S_FLAG", "")
USE_OLLAMA_DOCKER = os.environ.get("USE_OLLAMA_DOCKER", "false")
if OLLAMA_BASE_URL == "" and OLLAMA_API_BASE_URL != "":
OLLAMA_BASE_URL = (
OLLAMA_API_BASE_URL[:-4]
if OLLAMA_API_BASE_URL.endswith("/api")
else OLLAMA_API_BASE_URL
)
if ENV == "prod":
if OLLAMA_API_BASE_URL == "/ollama/api":
OLLAMA_API_BASE_URL = "http://host.docker.internal:11434/api"
if OLLAMA_BASE_URL == "/ollama" and not K8S_FLAG:
if USE_OLLAMA_DOCKER.lower() == "true":
# if you use all-in-one docker container (Open WebUI + Ollama)
# with the docker build arg USE_OLLAMA=true (--build-arg="USE_OLLAMA=true") this only works with http://localhost:11434
OLLAMA_BASE_URL = "http://localhost:11434"
else:
OLLAMA_BASE_URL = "http://host.docker.internal:11434"
elif K8S_FLAG:
OLLAMA_BASE_URL = "http://ollama-service.open-webui.svc.cluster.local:11434"
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(";")]
####################################
# OPENAI_API
@@ -218,15 +301,43 @@ if ENV == "prod":
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "")
OPENAI_API_BASE_URL = os.environ.get("OPENAI_API_BASE_URL", "")
if OPENAI_API_BASE_URL == "":
OPENAI_API_BASE_URL = "https://api.openai.com/v1"
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_BASE_URLS = os.environ.get("OPENAI_API_BASE_URLS", "")
OPENAI_API_BASE_URLS = (
OPENAI_API_BASE_URLS if OPENAI_API_BASE_URLS != "" else OPENAI_API_BASE_URL
)
OPENAI_API_BASE_URLS = [
url.strip() if url != "" else "https://api.openai.com/v1"
for url in OPENAI_API_BASE_URLS.split(";")
]
OPENAI_API_KEY = ""
try:
OPENAI_API_KEY = OPENAI_API_KEYS[
OPENAI_API_BASE_URLS.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)
ENABLE_SIGNUP = os.environ.get("ENABLE_SIGNUP", "True").lower() == "true"
DEFAULT_MODELS = os.environ.get("DEFAULT_MODELS", None)
@@ -257,8 +368,21 @@ DEFAULT_PROMPT_SUGGESTIONS = (
DEFAULT_USER_ROLE = os.getenv("DEFAULT_USER_ROLE", "pending")
USER_PERMISSIONS = {"chat": {"deletion": True}}
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", "")
ENABLE_ADMIN_EXPORT = os.environ.get("ENABLE_ADMIN_EXPORT", "True").lower() == "true"
####################################
# WEBUI_VERSION
@@ -271,6 +395,9 @@ WEBUI_VERSION = os.environ.get("WEBUI_VERSION", "v1.0.0-alpha.100")
####################################
WEBUI_AUTH = True
WEBUI_AUTH_TRUSTED_EMAIL_HEADER = os.environ.get(
"WEBUI_AUTH_TRUSTED_EMAIL_HEADER", None
)
####################################
# WEBUI_SECRET_KEY
@@ -291,12 +418,28 @@ 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")
# device type ebbeding models - "cpu" (default), "cuda" (nvidia gpu required) or "mps" (apple silicon) - choosing this right can lead to better performance
RAG_EMBEDDING_MODEL_DEVICE_TYPE = os.environ.get(
"RAG_EMBEDDING_MODEL_DEVICE_TYPE", "cpu"
# 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_EMBEDDING_ENGINE = os.environ.get("RAG_EMBEDDING_ENGINE", "")
RAG_EMBEDDING_MODEL = os.environ.get(
"RAG_EMBEDDING_MODEL", "sentence-transformers/all-MiniLM-L6-v2"
)
log.info(f"Embedding model set: {RAG_EMBEDDING_MODEL}"),
RAG_EMBEDDING_MODEL_TRUST_REMOTE_CODE = (
os.environ.get("RAG_EMBEDDING_MODEL_TRUST_REMOTE_CODE", "").lower() == "true"
)
# 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":
DEVICE_TYPE = "cuda"
else:
DEVICE_TYPE = "cpu"
CHROMA_CLIENT = chromadb.PersistentClient(
path=CHROMA_DATA_PATH,
settings=Settings(allow_reset=True, anonymized_telemetry=False),
@@ -319,16 +462,49 @@ And answer according to the language of the user's question.
Given the context information, answer the query.
Query: [query]"""
RAG_OPENAI_API_BASE_URL = os.getenv("RAG_OPENAI_API_BASE_URL", OPENAI_API_BASE_URL)
RAG_OPENAI_API_KEY = os.getenv("RAG_OPENAI_API_KEY", OPENAI_API_KEY)
####################################
# 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
####################################
ENABLE_IMAGE_GENERATION = (
os.environ.get("ENABLE_IMAGE_GENERATION", "").lower() == "true"
)
AUTOMATIC1111_BASE_URL = os.getenv("AUTOMATIC1111_BASE_URL", "")
COMFYUI_BASE_URL = os.getenv("COMFYUI_BASE_URL", "")
IMAGES_OPENAI_API_BASE_URL = os.getenv(
"IMAGES_OPENAI_API_BASE_URL", OPENAI_API_BASE_URL
)
IMAGES_OPENAI_API_KEY = os.getenv("IMAGES_OPENAI_API_KEY", OPENAI_API_KEY)
####################################
# Audio
####################################
AUDIO_OPENAI_API_BASE_URL = os.getenv("AUDIO_OPENAI_API_BASE_URL", OPENAI_API_BASE_URL)
AUDIO_OPENAI_API_KEY = os.getenv("AUDIO_OPENAI_API_KEY", OPENAI_API_KEY)
####################################
# LiteLLM
####################################
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")
+23 -1
View File
@@ -3,6 +3,17 @@ 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):
DEFAULT = lambda msg="": f"{msg if msg else ''}"
USER_SIGNUP = lambda username="": (
f"New user signed up: {username}" if username else "New user signed up"
)
class ERROR_MESSAGES(str, Enum):
@@ -13,6 +24,7 @@ class ERROR_MESSAGES(str, Enum):
ENV_VAR_NOT_FOUND = "Required environment variable not found. Terminating now."
CREATE_USER_ERROR = "Oops! Something went wrong while creating your account. Please try again later. If the issue persists, contact support for assistance."
DELETE_USER_ERROR = "Oops! Something went wrong. We encountered an issue while trying to delete the user. Please give it another shot."
EMAIL_MISMATCH = "Uh-oh! This email does not match the email your provider is registered with. Please check your email and try again."
EMAIL_TAKEN = "Uh-oh! This email is already registered. Sign in with your existing account or choose another email to start anew."
USERNAME_TAKEN = (
"Uh-oh! This username is already registered. Please choose another username."
@@ -29,6 +41,7 @@ class ERROR_MESSAGES(str, Enum):
INVALID_PASSWORD = (
"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."
UNAUTHORIZED = "401 Unauthorized"
ACCESS_PROHIBITED = "You do not have permission to access this resource. Please contact your administrator for assistance."
ACTION_PROHIBITED = (
@@ -41,9 +54,18 @@ class ERROR_MESSAGES(str, Enum):
NOT_FOUND = "We could not find what you're looking for :/"
USER_NOT_FOUND = "We could not find what you're looking for :/"
API_KEY_NOT_FOUND = "Oops! It looks like there's a hiccup. The API key is missing. Please make sure to provide a valid API key to access this feature."
MALICIOUS = "Unusual activities detected, please try again in a few minutes."
PANDOC_NOT_INSTALLED = "Pandoc is not installed on the server. Please contact your administrator for assistance."
INCORRECT_FORMAT = (
lambda err="": f"Invalid format. Please use the correct format{err if err else ''}"
lambda err="": f"Invalid format. Please use the correct format{err}"
)
RATE_LIMIT_EXCEEDED = "API rate limit exceeded"
MODEL_NOT_FOUND = lambda name="": f"Model '{name}' was not found"
OPENAI_NOT_FOUND = lambda name="": "OpenAI API was not found"
OLLAMA_NOT_FOUND = "WebUI could not connect to Ollama"
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."
+23 -33
View File
@@ -1,34 +1,24 @@
{
"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."
},
{
"title": [
"Give me ideas",
"for what to do with my kids' art"
],
"content": "What are 5 creative things I could do with my kids' art? I don't want to throw them away, but it's also so much clutter."
},
{
"title": [
"Tell me a fun fact",
"about the Roman Empire"
],
"content": "Tell me a random fun fact about the Roman Empire"
},
{
"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."
}
]
}
}
"version": 0,
"ui": {
"default_locale": "en-US",
"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."
},
{
"title": ["Give me ideas", "for what to do with my kids' art"],
"content": "What are 5 creative things I could do with my kids' art? I don't want to throw them away, but it's also so much clutter."
},
{
"title": ["Tell me a fun fact", "about the Roman Empire"],
"content": "Tell me a random fun fact about the Roman Empire"
},
{
"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."
}
]
}
}
+233 -41
View File
@@ -4,29 +4,61 @@ import markdown
import time
import os
import sys
import logging
import aiohttp
import requests
from fastapi import FastAPI, Request, Depends
from fastapi import FastAPI, Request, Depends, status
from fastapi.staticfiles import StaticFiles
from fastapi import HTTPException
from fastapi.responses import JSONResponse
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 litellm.proxy.proxy_server import ProxyConfig, initialize
from litellm.proxy.proxy_server import app as litellm_app
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,
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
from config import WEBUI_NAME, ENV, VERSION, CHANGELOG, FRONTEND_BUILD_DIR
from utils.utils import get_http_authorization_cred, get_current_user
from utils.utils import get_admin_user
from apps.rag.utils import rag_messages
from config import (
CONFIG_DATA,
WEBUI_NAME,
ENV,
VERSION,
CHANGELOG,
FRONTEND_BUILD_DIR,
CACHE_DIR,
STATIC_DIR,
MODEL_FILTER_ENABLED,
MODEL_FILTER_LIST,
GLOBAL_LOG_LEVEL,
SRC_LOG_LEVELS,
WEBHOOK_URL,
ENABLE_ADMIN_EXPORT,
)
from constants import ERROR_MESSAGES
logging.basicConfig(stream=sys.stdout, level=GLOBAL_LOG_LEVEL)
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["MAIN"])
class SPAStaticFiles(StaticFiles):
@@ -40,25 +72,89 @@ class SPAStaticFiles(StaticFiles):
raise ex
proxy_config = ProxyConfig()
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)
async def startup():
await config()
print(
f"""
___ __ __ _ _ _ ___
/ _ \ _ __ ___ _ __ \ \ / /__| |__ | | | |_ _|
| | | | '_ \ / _ \ '_ \ \ \ /\ / / _ \ '_ \| | | || |
| |_| | |_) | __/ | | | \ V V / __/ |_) | |_| || |
\___/| .__/ \___|_| |_| \_/\_/ \___|_.__/ \___/|___|
|_|
v{VERSION} - building the best open-source AI user interface.
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
app.state.WEBHOOK_URL = WEBHOOK_URL
origins = ["*"]
class RAGMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
if request.method == "POST" and (
"/api/chat" in request.url.path or "/chat/completions" in request.url.path
):
log.debug(f"request.url.path: {request.url.path}")
# Read the original request body
body = await request.body()
# Decode body to string
body_str = body.decode("utf-8")
# Parse string to JSON
data = json.loads(body_str) if body_str else {}
# 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.RAG_EMBEDDING_ENGINE,
rag_app.state.RAG_EMBEDDING_MODEL,
rag_app.state.sentence_transformer_ef,
rag_app.state.OPENAI_API_KEY,
rag_app.state.OPENAI_API_BASE_URL,
)
del data["docs"]
log.debug(f"data['messages']: {data['messages']}")
modified_body_bytes = json.dumps(data).encode("utf-8")
# Replace the request body with the modified one
request._body = modified_body_bytes
# Set custom header to ensure content-length matches new body length
request.headers.__dict__["_list"] = [
(b"content-length", str(len(modified_body_bytes)).encode("utf-8")),
*[
(k, v)
for k, v in request.headers.raw
if k.lower() != b"content-length"
],
]
response = await call_next(request)
return response
async def _receive(self, body: bytes):
return {"type": "http.request", "body": body, "more_body": False}
app.add_middleware(RAGMiddleware)
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
@@ -68,11 +164,6 @@ app.add_middleware(
)
@app.on_event("startup")
async def on_startup():
await startup()
@app.middleware("http")
async def check_url(request: Request, call_next):
start_time = int(time.time())
@@ -83,25 +174,15 @@ async def check_url(request: Request, call_next):
return response
@litellm_app.middleware("http")
async def auth_middleware(request: Request, call_next):
auth_header = request.headers.get("Authorization", "")
if ENV != "dev":
try:
user = get_current_user(get_http_authorization_cred(auth_header))
print(user)
except Exception as e:
return JSONResponse(status_code=400, content={"detail": str(e)})
response = await call_next(request)
return response
@app.on_event("startup")
async def on_startup():
asyncio.create_task(start_litellm_background())
app.mount("/api/v1", webui_app)
app.mount("/litellm/api", litellm_app)
app.mount("/ollama/api", ollama_app)
app.mount("/ollama", ollama_app)
app.mount("/openai/api", openai_app)
app.mount("/images/api/v1", images_app)
@@ -111,27 +192,138 @@ app.mount("/rag/api/v1", rag_app)
@app.get("/api/config")
async def get_app_config():
# Checking and Handling the Absence of 'ui' in CONFIG_DATA
default_locale = "en-US"
if "ui" in CONFIG_DATA:
default_locale = CONFIG_DATA["ui"].get("default_locale", "en-US")
# The Rest of the Function Now Uses the Variables Defined Above
return {
"status": True,
"name": WEBUI_NAME,
"version": VERSION,
"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,
"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,
}
class ModelFilterConfigForm(BaseModel):
enabled: bool
models: List[str]
@app.post("/api/config/model/filter")
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
ollama_app.state.MODEL_FILTER_ENABLED = app.state.MODEL_FILTER_ENABLED
ollama_app.state.MODEL_FILTER_LIST = app.state.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
litellm_app.state.MODEL_FILTER_ENABLED = app.state.MODEL_FILTER_ENABLED
litellm_app.state.MODEL_FILTER_LIST = app.state.MODEL_FILTER_LIST
return {
"enabled": app.state.MODEL_FILTER_ENABLED,
"models": app.state.MODEL_FILTER_LIST,
}
@app.get("/api/webhook")
async def get_webhook_url(user=Depends(get_admin_user)):
return {
"url": app.state.WEBHOOK_URL,
}
class UrlForm(BaseModel):
url: str
@app.post("/api/webhook")
async def update_webhook_url(form_data: UrlForm, user=Depends(get_admin_user)):
app.state.WEBHOOK_URL = form_data.url
webui_app.state.WEBHOOK_URL = app.state.WEBHOOK_URL
return {
"url": app.state.WEBHOOK_URL,
}
@app.get("/api/version")
async def get_app_config():
return {
"version": VERSION,
}
@app.get("/api/changelog")
async def get_app_changelog():
return CHANGELOG
return {key: CHANGELOG[key] for idx, key in enumerate(CHANGELOG) if idx < 5}
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/api/version/updates")
async def get_app_latest_release_version():
try:
async with aiohttp.ClientSession() as session:
async with session.get(
"https://api.github.com/repos/open-webui/open-webui/releases/latest"
) as response:
response.raise_for_status()
data = await response.json()
latest_version = data["tag_name"]
return {"current": VERSION, "latest": latest_version[1:]}
except aiohttp.ClientError as e:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail=ERROR_MESSAGES.RATE_LIMIT_EXCEEDED,
)
@app.get("/manifest.json")
async def get_manifest_json():
return {
"name": WEBUI_NAME,
"short_name": WEBUI_NAME,
"start_url": "/",
"display": "standalone",
"background_color": "#343541",
"theme_color": "#343541",
"orientation": "portrait-primary",
"icons": [{"src": "/favicon.png", "type": "image/png", "sizes": "844x884"}],
}
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",
)
@app.on_event("shutdown")
async def shutdown_event():
await shutdown_litellm_background()
+16 -1
View File
@@ -14,14 +14,22 @@ uuid
requests
aiohttp
peewee
peewee-migrate
bcrypt
litellm
litellm==1.35.17
litellm[proxy]==1.35.17
boto3
argon2-cffi
apscheduler
google-generativeai
langchain
langchain-chroma
langchain-community
fake_useragent
chromadb
sentence_transformers
pypdf
@@ -34,9 +42,16 @@ openpyxl
pyxlsb
xlrd
opencv-python-headless
rapidocr-onnxruntime
fpdf2
rank_bm25
faster-whisper
PyJWT
pyjwt[crypto]
black
langfuse
+16 -6
View File
@@ -7,16 +7,26 @@ KEY_FILE=.webui_secret_key
PORT="${PORT:-8080}"
if test "$WEBUI_SECRET_KEY $WEBUI_JWT_SECRET_KEY" = " "; then
echo No WEBUI_SECRET_KEY provided
echo "No WEBUI_SECRET_KEY provided"
if ! [ -e "$KEY_FILE" ]; then
echo Generating WEBUI_SECRET_KEY
echo "Generating WEBUI_SECRET_KEY"
# Generate a random value to use as a WEBUI_SECRET_KEY in case the user didn't provide one.
echo $(head -c 12 /dev/random | base64) > $KEY_FILE
echo $(head -c 12 /dev/random | base64) > "$KEY_FILE"
fi
echo Loading WEBUI_SECRET_KEY from $KEY_FILE
WEBUI_SECRET_KEY=`cat $KEY_FILE`
echo "Loading WEBUI_SECRET_KEY from $KEY_FILE"
WEBUI_SECRET_KEY=$(cat "$KEY_FILE")
fi
WEBUI_SECRET_KEY="$WEBUI_SECRET_KEY" exec uvicorn main:app --host 0.0.0.0 --port "$PORT" --forwarded-allow-ips '*'
if [ "$USE_OLLAMA_DOCKER" = "true" ]; then
echo "USE_OLLAMA is set to true, starting ollama serve."
ollama serve &
fi
if [ "$USE_CUDA_DOCKER" = "true" ]; then
echo "CUDA is enabled, appending LD_LIBRARY_PATH to include torch/cudnn & cublas libraries."
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 '*'
Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.0 KiB

After

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+22
View File
@@ -1,6 +1,8 @@
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from fastapi import HTTPException, status, Depends
from apps.web.models.users import Users
from pydantic import BaseModel
from typing import Union, Optional
from constants import ERROR_MESSAGES
@@ -8,6 +10,7 @@ from passlib.context import CryptContext
from datetime import datetime, timedelta
import requests
import jwt
import uuid
import logging
import config
@@ -58,6 +61,11 @@ def extract_token_from_auth_header(auth_header: str):
return auth_header[len("Bearer ") :]
def create_api_key():
key = str(uuid.uuid4()).replace("-", "")
return f"sk-{key}"
def get_http_authorization_cred(auth_header: str):
try:
scheme, credentials = auth_header.split(" ")
@@ -69,6 +77,10 @@ def get_http_authorization_cred(auth_header: str):
def get_current_user(
auth_token: HTTPAuthorizationCredentials = Depends(bearer_security),
):
# auth by api key
if auth_token.credentials.startswith("sk-"):
return get_current_user_by_api_key(auth_token.credentials)
# auth by jwt token
data = decode_token(auth_token.credentials)
if data != None and "id" in data:
user = Users.get_user_by_id(data["id"])
@@ -85,6 +97,16 @@ 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,
)
return user
def get_verified_user(user=Depends(get_current_user)):
if user.role not in {"user", "admin"}:
raise HTTPException(
+54
View File
@@ -0,0 +1,54 @@
import json
import requests
import logging
from config import SRC_LOG_LEVELS, VERSION, WEBUI_FAVICON_URL, WEBUI_NAME
log = logging.getLogger(__name__)
log.setLevel(SRC_LOG_LEVELS["WEBHOOK"])
def post_webhook(url: str, message: str, event_data: dict) -> bool:
try:
payload = {}
# Slack and Google Chat Webhooks
if "https://hooks.slack.com" in url or "https://chat.googleapis.com" in url:
payload["text"] = message
# Discord Webhooks
elif "https://discord.com/api/webhooks" in url:
payload["content"] = message
# Microsoft Teams Webhooks
elif "webhook.office.com" in url:
action = event_data.get("action", "undefined")
facts = [
{"name": name, "value": value}
for name, value in json.loads(event_data.get("user", {})).items()
]
payload = {
"@type": "MessageCard",
"@context": "http://schema.org/extensions",
"themeColor": "0076D7",
"summary": message,
"sections": [
{
"activityTitle": message,
"activitySubtitle": f"{WEBUI_NAME} ({VERSION}) - {action}",
"activityImage": WEBUI_FAVICON_URL,
"facts": facts,
"markdown": True,
}
],
}
# Default Payload
else:
payload = {**event_data}
log.debug(f"payload: {payload}")
r = requests.post(url, json=payload)
r.raise_for_status()
log.debug(f"r.text: {r.text}")
return True
except Exception as e:
log.exception(e)
return False
+8
View File
@@ -0,0 +1,8 @@
#!/bin/bash
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
else
echo "Operation cancelled."
fi
BIN
View File
Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.1 MiB

After

Width:  |  Height:  |  Size: 5.0 MiB

+8
View File
@@ -0,0 +1,8 @@
services:
ollama:
devices:
- /dev/kfd:/dev/kfd
- /dev/dri:/dev/dri
image: ollama/ollama:${OLLAMA_DOCKER_TAG-rocm}
environment:
- 'HSA_OVERRIDE_GFX_VERSION=${HSA_OVERRIDE_GFX_VERSION-11.0.0}'
+4 -4
View File
@@ -8,15 +8,15 @@ services:
pull_policy: always
tty: true
restart: unless-stopped
image: ollama/ollama:latest
image: ollama/ollama:${OLLAMA_DOCKER_TAG-latest}
open-webui:
build:
context: .
args:
OLLAMA_API_BASE_URL: '/ollama/api'
OLLAMA_BASE_URL: '/ollama'
dockerfile: Dockerfile
image: ghcr.io/open-webui/open-webui:main
image: ghcr.io/open-webui/open-webui:${WEBUI_DOCKER_TAG-main}
container_name: open-webui
volumes:
- open-webui:/app/backend/data
@@ -25,7 +25,7 @@ services:
ports:
- ${OPEN_WEBUI_PORT-3000}:8080
environment:
- 'OLLAMA_API_BASE_URL=http://ollama:11434/api'
- 'OLLAMA_BASE_URL=http://ollama:11434'
- 'WEBUI_SECRET_KEY='
extra_hosts:
- host.docker.internal:host-gateway
+12
View File
@@ -50,6 +50,18 @@ We welcome pull requests. Before submitting one, please:
Help us make Open WebUI more accessible by improving documentation, writing tutorials, or creating guides on setting up and optimizing the web UI.
### 🌐 Translations and Internationalization
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.
To add a new language:
- Create a new directory in the `src/lib/i18n/locales` path with the appropriate language code as its name. For instance, if you're adding translations for Spanish (Spain), create a new directory named `es-ES`.
- Copy the American English translation file(s) (from `en-US` directory in `src/lib/i18n/locale`) to this new directory and update the string values in JSON format according to your language. Make sure to preserve the structure of the JSON object.
- Add the language code and its respective title to languages file at `src/lib/i18n/locales/languages.json`.
### 🤔 Questions & Feedback
Got questions or feedback? Join our [Discord community](https://discord.gg/5rJgQTnV4s) or open an issue. We're here to help!
+38
View File
@@ -0,0 +1,38 @@
// i18next-parser.config.ts
import { getLanguages } from './src/lib/i18n/index.ts';
const getLangCodes = async () => {
const languages = await getLanguages();
return languages.map((l) => l.code);
};
export default {
contextSeparator: '_',
createOldCatalogs: false,
defaultNamespace: 'translation',
defaultValue: '',
indentation: 2,
keepRemoved: false,
keySeparator: false,
lexers: {
svelte: ['JavascriptLexer'],
js: ['JavascriptLexer'],
ts: ['JavascriptLexer'],
default: ['JavascriptLexer']
},
lineEnding: 'auto',
locales: await getLangCodes(),
namespaceSeparator: false,
output: 'src/lib/i18n/locales/$LOCALE/$NAMESPACE.json',
pluralSeparator: '_',
input: 'src/**/*.{js,svelte}',
sort: true,
verbose: true,
failOnWarnings: false,
failOnUpdate: false,
customValueTemplate: null,
resetDefaultValueLocale: null,
i18nextOptions: null,
yamlOptions: null
};
+5 -1
View File
@@ -7,7 +7,11 @@ ollama
{{- end -}}
{{- define "ollama.url" -}}
{{- printf "http://%s.%s.svc.cluster.local:%d/api" (include "ollama.name" .) (.Release.Namespace) (.Values.ollama.service.port | int) }}
{{- 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" -}}
@@ -1,3 +1,4 @@
{{- if not .Values.ollama.externalHost }}
apiVersion: v1
kind: Service
metadata:
@@ -19,3 +20,4 @@ spec:
port: {{ .port }}
targetPort: http
{{- end }}
{{- end }}
@@ -1,3 +1,4 @@
{{- if not .Values.ollama.externalHost }}
apiVersion: apps/v1
kind: StatefulSet
metadata:
@@ -88,9 +89,10 @@ spec:
resources:
requests:
storage: {{ .Values.ollama.persistence.size | quote }}
storageClass: {{ .Values.ollama.persistence.storageClass }}
storageClassName: {{ .Values.ollama.persistence.storageClass }}
{{- with .Values.ollama.persistence.selector }}
selector:
{{- toYaml . | nindent 8 }}
{{- end }}
{{- end }}
{{- end }}
@@ -40,7 +40,7 @@ spec:
- name: data
mountPath: /app/backend/data
env:
- name: OLLAMA_API_BASE_URL
- name: OLLAMA_BASE_URL
value: {{ include "ollama.url" . | quote }}
tty: true
{{- with .Values.webui.nodeSelector }}
+3 -1
View File
@@ -17,7 +17,9 @@ spec:
resources:
requests:
storage: {{ .Values.webui.persistence.size }}
storageClass: {{ .Values.webui.persistence.storageClass }}
{{- if .Values.webui.persistence.storageClass }}
storageClassName: {{ .Values.webui.persistence.storageClass }}
{{- end }}
{{- with .Values.webui.persistence.selector }}
selector:
{{- toYaml . | nindent 4 }}
+11 -6
View File
@@ -4,6 +4,9 @@ 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 }}
@@ -11,14 +14,16 @@ metadata:
spec:
selector:
{{- include "open-webui.selectorLabels" . | nindent 4 }}
{{- with .Values.webui.service }}
type: {{ .type }}
type: {{ .Values.webui.service.type | default "ClusterIP" }}
ports:
- protocol: TCP
name: http
port: {{ .port }}
port: {{ .Values.webui.service.port }}
targetPort: http
{{- if .nodePort }}
nodePort: {{ .nodePort | int }}
{{- if .Values.webui.service.nodePort }}
nodePort: {{ .Values.webui.service.nodePort | int }}
{{- end }}
{{- end }}
{{- if .Values.webui.service.loadBalancerClass }}
loadBalancerClass: {{ .Values.webui.service.loadBalancerClass | quote }}
{{- end }}
+3
View File
@@ -1,6 +1,7 @@
nameOverride: ""
ollama:
externalHost: ""
annotations: {}
podAnnotations: {}
replicaCount: 1
@@ -70,3 +71,5 @@ webui:
port: 80
containerPort: 8080
nodePort: ""
labels: {}
loadBalancerClass: ""
@@ -26,8 +26,8 @@ spec:
cpu: "1000m"
memory: "1Gi"
env:
- name: OLLAMA_API_BASE_URL
value: "http://ollama-service.open-webui.svc.cluster.local:11434/api"
- name: OLLAMA_BASE_URL
value: "http://ollama-service.open-webui.svc.cluster.local:11434"
tty: true
volumeMounts:
- name: webui-volume
@@ -35,4 +35,4 @@ spec:
volumes:
- name: webui-volume
persistentVolumeClaim:
claimName: ollama-webui-pvc
claimName: open-webui-pvc
+2 -2
View File
@@ -2,8 +2,8 @@ apiVersion: v1
kind: PersistentVolumeClaim
metadata:
labels:
app: ollama-webui
name: ollama-webui-pvc
app: open-webui
name: open-webui-pvc
namespace: open-webui
spec:
accessModes: ["ReadWriteOnce"]
+3310 -2977
View File
File diff suppressed because it is too large Load Diff
+11 -4
View File
@@ -1,6 +1,6 @@
{
"name": "open-webui",
"version": "0.1.103",
"version": "0.1.121",
"private": true,
"scripts": {
"dev": "vite dev --host",
@@ -13,7 +13,8 @@
"lint:types": "npm run check",
"lint:backend": "pylint backend/",
"format": "prettier --plugin-search-dir --write '**/*.{js,ts,svelte,css,md,html,json}'",
"format:backend": "yapf --recursive backend -p -i"
"format:backend": "black . --exclude \"/venv/\"",
"i18n:parse": "i18next --config i18next-parser.config.ts && prettier --write 'src/lib/i18n/**/*.{js,json}'"
},
"devDependencies": {
"@sveltejs/adapter-auto": "^2.0.0",
@@ -27,6 +28,7 @@
"eslint": "^8.56.0",
"eslint-config-prettier": "^8.5.0",
"eslint-plugin-svelte": "^2.30.0",
"i18next-parser": "^8.13.0",
"postcss": "^8.4.31",
"prettier": "^2.8.0",
"prettier-plugin-svelte": "^2.10.1",
@@ -42,15 +44,20 @@
"dependencies": {
"@sveltejs/adapter-node": "^1.3.1",
"async": "^3.2.5",
"bits-ui": "^0.19.7",
"dayjs": "^1.11.10",
"file-saver": "^2.0.5",
"highlight.js": "^11.9.0",
"i18next": "^23.10.0",
"i18next-browser-languagedetector": "^7.2.0",
"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",
"svelte-french-toast": "^1.2.0",
"svelte-sonner": "^0.3.19",
"tippy.js": "^6.3.7",
"uuid": "^9.0.1"
}
}
}
+1 -1
View File
@@ -182,7 +182,7 @@ else
export OLLAMA_DATA_DIR=$data_dir # Set OLLAMA_DATA_DIR environment variable
fi
if [[ -n $webui_port ]]; then
export OLLAMA_WEBUI_PORT=$webui_port # Set OLLAMA_WEBUI_PORT environment variable
export OPEN_WEBUI_PORT=$webui_port # Set OPEN_WEBUI_PORT environment variable
fi
DEFAULT_COMPOSE_COMMAND+=" up -d"
DEFAULT_COMPOSE_COMMAND+=" --remove-orphans"
+23
View File
@@ -28,6 +28,25 @@ math {
@apply rounded-lg;
}
ol > li {
counter-increment: list-number;
display: block;
margin-bottom: 0;
margin-top: 0;
min-height: 28px;
}
.prose ol > li::before {
content: counters(list-number, '.') '.';
padding-right: 0.5rem;
color: var(--tw-prose-counters);
font-weight: 400;
}
li p {
display: inline;
}
::-webkit-scrollbar-thumb {
--tw-border-opacity: 1;
background-color: rgba(217, 217, 227, 0.8);
@@ -59,3 +78,7 @@ select {
/* for Chrome */
-webkit-appearance: none;
}
.katex-mathml {
display: none;
}
+33 -12
View File
@@ -3,23 +3,44 @@
<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" />
<script>
// On page load or when changing themes, best to add inline in `head` to avoid FOUC
if (
localStorage.theme === 'light' ||
(!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: light)').matches)
) {
document.documentElement.classList.add('light');
} else if (localStorage.theme) {
localStorage.theme.split(' ').forEach((e) => {
document.documentElement.classList.add(e);
(() => {
if (localStorage?.theme && localStorage?.theme.includes('oled')) {
document.documentElement.style.setProperty('--color-gray-900', '#000000');
document.documentElement.style.setProperty('--color-gray-950', '#000000');
document.documentElement.classList.add('dark');
} else if (
localStorage.theme === 'light' ||
(!('theme' in localStorage) && window.matchMedia('(prefers-color-scheme: light)').matches)
) {
document.documentElement.classList.add('light');
} else if (localStorage.theme && localStorage.theme !== 'system') {
localStorage.theme.split(' ').forEach((e) => {
document.documentElement.classList.add(e);
});
} else if (localStorage.theme && localStorage.theme === 'system') {
systemTheme = window.matchMedia('(prefers-color-scheme: dark)').matches;
document.documentElement.classList.add(systemTheme ? 'dark' : 'light');
} else {
document.documentElement.classList.add('dark');
}
window.matchMedia('(prefers-color-scheme: dark)').addListener((e) => {
if (localStorage.theme === 'system') {
if (e.matches) {
document.documentElement.classList.add('dark');
document.documentElement.classList.remove('light');
} else {
document.documentElement.classList.add('light');
document.documentElement.classList.remove('dark');
}
}
});
} else {
document.documentElement.classList.add('dark');
}
})();
</script>
%sveltekit.head%
+100 -1
View File
@@ -1,11 +1,73 @@
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;
};
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 +91,40 @@ export const transcribeAudio = async (token: string, file: File) => {
return res;
};
export const synthesizeOpenAISpeech = async (
token: string = '',
speaker: string = 'alloy',
text: string = ''
) => {
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: 'tts-1',
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;
};
+83 -2
View File
@@ -58,7 +58,12 @@ export const userSignIn = async (email: string, password: string) => {
return res;
};
export const userSignUp = async (name: string, email: string, password: string) => {
export const userSignUp = async (
name: string,
email: string,
password: string,
profile_image_url: string
) => {
let error = null;
const res = await fetch(`${WEBUI_API_BASE_URL}/auths/signup`, {
@@ -69,7 +74,8 @@ export const userSignUp = async (name: string, email: string, password: string)
body: JSON.stringify({
name: name,
email: email,
password: password
password: password,
profile_image_url: profile_image_url
})
})
.then(async (res) => {
@@ -318,3 +324,78 @@ export const updateJWTExpiresDuration = async (token: string, duration: string)
return res;
};
export const createAPIKey = async (token: string) => {
let error = null;
const res = await fetch(`${WEBUI_API_BASE_URL}/auths/api_key`, {
method: 'POST',
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.api_key;
};
export const getAPIKey = async (token: string) => {
let error = null;
const res = await fetch(`${WEBUI_API_BASE_URL}/auths/api_key`, {
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.api_key;
};
export const deleteAPIKey = async (token: string) => {
let error = null;
const res = await fetch(`${WEBUI_API_BASE_URL}/auths/api_key`, {
method: 'DELETE',
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;
};
+160 -1
View File
@@ -62,6 +62,37 @@ export const getChatList = async (token: string = '') => {
return res;
};
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;
};
export const getAllChats = async (token: string) => {
let error = null;
@@ -218,6 +249,134 @@ export const getChatById = async (token: string, id: string) => {
return res;
};
export const getChatByShareId = async (token: string, share_id: string) => {
let error = null;
const res = await fetch(`${WEBUI_API_BASE_URL}/chats/share/${share_id}`, {
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 shareChatById = async (token: string, id: string) => {
let error = null;
const res = await fetch(`${WEBUI_API_BASE_URL}/chats/${id}/share`, {
method: 'POST',
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 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;
const res = await fetch(`${WEBUI_API_BASE_URL}/chats/${id}/share`, {
method: 'DELETE',
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 updateChatById = async (token: string, id: string, chat: object) => {
let error = null;
@@ -439,7 +598,7 @@ export const deleteAllChats = async (token: string) => {
return json;
})
.catch((err) => {
error = err;
error = err.detail;
console.log(err);
return null;
+4 -2
View File
@@ -5,7 +5,8 @@ export const createNewDoc = async (
collection_name: string,
filename: string,
name: string,
title: string
title: string,
content: object | null = null
) => {
let error = null;
@@ -20,7 +21,8 @@ export const createNewDoc = async (
collection_name: collection_name,
filename: filename,
name: name,
title: title
title: title,
...(content ? { content: JSON.stringify(content) } : {})
})
})
.then(async (res) => {
+88 -12
View File
@@ -1,9 +1,9 @@
import { IMAGES_API_BASE_URL } from '$lib/constants';
export const getImageGenerationEnabledStatus = async (token: string = '') => {
export const getImageGenerationConfig = async (token: string = '') => {
let error = null;
const res = await fetch(`${IMAGES_API_BASE_URL}/enabled`, {
const res = await fetch(`${IMAGES_API_BASE_URL}/config`, {
method: 'GET',
headers: {
Accept: 'application/json',
@@ -32,10 +32,50 @@ export const getImageGenerationEnabledStatus = async (token: string = '') => {
return res;
};
export const toggleImageGenerationEnabledStatus = async (token: string = '') => {
export const updateImageGenerationConfig = async (
token: string = '',
engine: string,
enabled: boolean
) => {
let error = null;
const res = await fetch(`${IMAGES_API_BASE_URL}/enabled/toggle`, {
const res = await fetch(`${IMAGES_API_BASE_URL}/config/update`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
...(token && { authorization: `Bearer ${token}` })
},
body: JSON.stringify({
engine,
enabled
})
})
.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 getOpenAIConfig = async (token: string = '') => {
let error = null;
const res = await fetch(`${IMAGES_API_BASE_URL}/openai/config`, {
method: 'GET',
headers: {
Accept: 'application/json',
@@ -64,7 +104,43 @@ export const toggleImageGenerationEnabledStatus = async (token: string = '') =>
return res;
};
export const getAUTOMATIC1111Url = async (token: string = '') => {
export const updateOpenAIConfig = async (token: string = '', url: string, key: string) => {
let error = null;
const res = await fetch(`${IMAGES_API_BASE_URL}/openai/config/update`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
...(token && { authorization: `Bearer ${token}` })
},
body: JSON.stringify({
url: url,
key: key
})
})
.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 getImageGenerationEngineUrls = async (token: string = '') => {
let error = null;
const res = await fetch(`${IMAGES_API_BASE_URL}/url`, {
@@ -93,10 +169,10 @@ export const getAUTOMATIC1111Url = async (token: string = '') => {
throw error;
}
return res.AUTOMATIC1111_BASE_URL;
return res;
};
export const updateAUTOMATIC1111Url = async (token: string = '', url: string) => {
export const updateImageGenerationEngineUrls = async (token: string = '', urls: object = {}) => {
let error = null;
const res = await fetch(`${IMAGES_API_BASE_URL}/url/update`, {
@@ -107,7 +183,7 @@ export const updateAUTOMATIC1111Url = async (token: string = '', url: string) =>
...(token && { authorization: `Bearer ${token}` })
},
body: JSON.stringify({
url: url
...urls
})
})
.then(async (res) => {
@@ -128,7 +204,7 @@ export const updateAUTOMATIC1111Url = async (token: string = '', url: string) =>
throw error;
}
return res.AUTOMATIC1111_BASE_URL;
return res;
};
export const getImageSize = async (token: string = '') => {
@@ -263,7 +339,7 @@ export const updateImageSteps = async (token: string = '', steps: number) => {
return res.IMAGE_STEPS;
};
export const getDiffusionModels = async (token: string = '') => {
export const getImageGenerationModels = async (token: string = '') => {
let error = null;
const res = await fetch(`${IMAGES_API_BASE_URL}/models`, {
@@ -295,7 +371,7 @@ export const getDiffusionModels = async (token: string = '') => {
return res;
};
export const getDefaultDiffusionModel = async (token: string = '') => {
export const getDefaultImageGenerationModel = async (token: string = '') => {
let error = null;
const res = await fetch(`${IMAGES_API_BASE_URL}/models/default`, {
@@ -327,7 +403,7 @@ export const getDefaultDiffusionModel = async (token: string = '') => {
return res.model;
};
export const updateDefaultDiffusionModel = async (token: string = '', model: string) => {
export const updateDefaultImageGenerationModel = async (token: string = '', model: string) => {
let error = null;
const res = await fetch(`${IMAGES_API_BASE_URL}/models/default/update`, {
+153
View File
@@ -19,6 +19,10 @@ export const getBackendConfig = async () => {
return null;
});
if (error) {
throw error;
}
return res;
};
@@ -41,5 +45,154 @@ export const getChangelog = async () => {
return null;
});
if (error) {
throw error;
}
return res;
};
export const getVersionUpdates = async () => {
let error = null;
const res = await fetch(`${WEBUI_BASE_URL}/api/version/updates`, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then(async (res) => {
if (!res.ok) throw await res.json();
return res.json();
})
.catch((err) => {
console.log(err);
error = err;
return null;
});
if (error) {
throw error;
}
return res;
};
export const getModelFilterConfig = async (token: string) => {
let error = null;
const res = await fetch(`${WEBUI_BASE_URL}/api/config/model/filter`, {
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;
return null;
});
if (error) {
throw error;
}
return res;
};
export const updateModelFilterConfig = async (
token: string,
enabled: boolean,
models: string[]
) => {
let error = null;
const res = await fetch(`${WEBUI_BASE_URL}/api/config/model/filter`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify({
enabled: enabled,
models: models
})
})
.then(async (res) => {
if (!res.ok) throw await res.json();
return res.json();
})
.catch((err) => {
console.log(err);
error = err;
return null;
});
if (error) {
throw error;
}
return res;
};
export const getWebhookUrl = async (token: string) => {
let error = null;
const res = await fetch(`${WEBUI_BASE_URL}/api/webhook`, {
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;
return null;
});
if (error) {
throw error;
}
return res.url;
};
export const updateWebhookUrl = async (token: string, url: string) => {
let error = null;
const res = await fetch(`${WEBUI_BASE_URL}/api/webhook`, {
method: 'POST',
headers: {
'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) => {
console.log(err);
error = err;
return null;
});
if (error) {
throw error;
}
return res.url;
};
+4 -2
View File
@@ -33,7 +33,7 @@ export const getLiteLLMModels = async (token: string = '') => {
id: model.id,
name: model.name ?? model.id,
external: true,
source: 'litellm'
source: 'LiteLLM'
}))
.sort((a, b) => {
return a.name.localeCompare(b.name);
@@ -77,6 +77,7 @@ type AddLiteLLMModelForm = {
api_base: string;
api_key: string;
rpm: string;
max_tokens: string;
};
export const addLiteLLMModel = async (token: string = '', payload: AddLiteLLMModelForm) => {
@@ -95,7 +96,8 @@ export const addLiteLLMModel = async (token: string = '', payload: AddLiteLLMMod
model: payload.model,
...(payload.api_base === '' ? {} : { api_base: payload.api_base }),
...(payload.api_key === '' ? {} : { api_key: payload.api_key }),
...(isNaN(parseInt(payload.rpm)) ? {} : { rpm: parseInt(payload.rpm) })
...(isNaN(parseInt(payload.rpm)) ? {} : { rpm: parseInt(payload.rpm) }),
...(payload.max_tokens === '' ? {} : { max_tokens: payload.max_tokens })
}
})
})
+169 -34
View File
@@ -1,9 +1,10 @@
import { OLLAMA_API_BASE_URL } from '$lib/constants';
import { promptTemplate } from '$lib/utils';
export const getOllamaAPIUrl = async (token: string = '') => {
export const getOllamaUrls = async (token: string = '') => {
let error = null;
const res = await fetch(`${OLLAMA_API_BASE_URL}/url`, {
const res = await fetch(`${OLLAMA_API_BASE_URL}/urls`, {
method: 'GET',
headers: {
Accept: 'application/json',
@@ -29,13 +30,13 @@ export const getOllamaAPIUrl = async (token: string = '') => {
throw error;
}
return res.OLLAMA_API_BASE_URL;
return res.OLLAMA_BASE_URLS;
};
export const updateOllamaAPIUrl = async (token: string = '', url: string) => {
export const updateOllamaUrls = async (token: string = '', urls: string[]) => {
let error = null;
const res = await fetch(`${OLLAMA_API_BASE_URL}/url/update`, {
const res = await fetch(`${OLLAMA_API_BASE_URL}/urls/update`, {
method: 'POST',
headers: {
Accept: 'application/json',
@@ -43,7 +44,7 @@ export const updateOllamaAPIUrl = async (token: string = '', url: string) => {
...(token && { authorization: `Bearer ${token}` })
},
body: JSON.stringify({
url: url
urls: urls
})
})
.then(async (res) => {
@@ -64,13 +65,13 @@ export const updateOllamaAPIUrl = async (token: string = '', url: string) => {
throw error;
}
return res.OLLAMA_API_BASE_URL;
return res.OLLAMA_BASE_URLS;
};
export const getOllamaVersion = async (token: string = '') => {
let error = null;
const res = await fetch(`${OLLAMA_API_BASE_URL}/version`, {
const res = await fetch(`${OLLAMA_API_BASE_URL}/api/version`, {
method: 'GET',
headers: {
Accept: 'application/json',
@@ -102,7 +103,7 @@ export const getOllamaVersion = async (token: string = '') => {
export const getOllamaModels = async (token: string = '') => {
let error = null;
const res = await fetch(`${OLLAMA_API_BASE_URL}/tags`, {
const res = await fetch(`${OLLAMA_API_BASE_URL}/api/tags`, {
method: 'GET',
headers: {
Accept: 'application/json',
@@ -144,14 +145,15 @@ export const generateTitle = async (
) => {
let error = null;
template = template.replace(/{{prompt}}/g, prompt);
template = promptTemplate(template, prompt);
console.log(template);
const res = await fetch(`${OLLAMA_API_BASE_URL}/generate`, {
const res = await fetch(`${OLLAMA_API_BASE_URL}/api/generate`, {
method: 'POST',
headers: {
'Content-Type': 'text/event-stream',
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify({
@@ -186,10 +188,11 @@ export const generatePrompt = async (token: string = '', model: string, conversa
conversation = '[no existing conversation]';
}
const res = await fetch(`${OLLAMA_API_BASE_URL}/generate`, {
const res = await fetch(`${OLLAMA_API_BASE_URL}/api/generate`, {
method: 'POST',
headers: {
'Content-Type': 'text/event-stream',
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify({
@@ -217,15 +220,69 @@ 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;
const res = await fetch(`${OLLAMA_API_BASE_URL}/api/generate`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify({
model: model,
prompt: text,
stream: true
})
}).catch((err) => {
error = err;
return null;
});
if (error) {
throw error;
}
return res;
};
export const generateChatCompletion = async (token: string = '', body: object) => {
let controller = new AbortController();
let error = null;
const res = await fetch(`${OLLAMA_API_BASE_URL}/chat`, {
const res = await fetch(`${OLLAMA_API_BASE_URL}/api/chat`, {
signal: controller.signal,
method: 'POST',
headers: {
'Content-Type': 'text/event-stream',
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify(body)
@@ -241,7 +298,7 @@ export const generateChatCompletion = async (token: string = '', body: object) =
return [res, controller];
};
export const cancelChatCompletion = async (token: string = '', requestId: string) => {
export const cancelOllamaRequest = async (token: string = '', requestId: string) => {
let error = null;
const res = await fetch(`${OLLAMA_API_BASE_URL}/cancel/${requestId}`, {
@@ -265,10 +322,11 @@ export const cancelChatCompletion = async (token: string = '', requestId: string
export const createModel = async (token: string, tagName: string, content: string) => {
let error = null;
const res = await fetch(`${OLLAMA_API_BASE_URL}/create`, {
const res = await fetch(`${OLLAMA_API_BASE_URL}/api/create`, {
method: 'POST',
headers: {
'Content-Type': 'text/event-stream',
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify({
@@ -287,19 +345,23 @@ export const createModel = async (token: string, tagName: string, content: strin
return res;
};
export const deleteModel = async (token: string, tagName: string) => {
export const deleteModel = async (token: string, tagName: string, urlIdx: string | null = null) => {
let error = null;
const res = await fetch(`${OLLAMA_API_BASE_URL}/delete`, {
method: 'DELETE',
headers: {
'Content-Type': 'text/event-stream',
Authorization: `Bearer ${token}`
},
body: JSON.stringify({
name: tagName
})
})
const res = await fetch(
`${OLLAMA_API_BASE_URL}/api/delete${urlIdx !== null ? `/${urlIdx}` : ''}`,
{
method: 'DELETE',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify({
name: tagName
})
}
)
.then(async (res) => {
if (!res.ok) throw await res.json();
return res.json();
@@ -310,7 +372,12 @@ export const deleteModel = async (token: string, tagName: string) => {
})
.catch((err) => {
console.log(err);
error = err.error;
error = err;
if ('detail' in err) {
error = err.detail;
}
return null;
});
@@ -321,13 +388,14 @@ export const deleteModel = async (token: string, tagName: string) => {
return res;
};
export const pullModel = async (token: string, tagName: string) => {
export const pullModel = async (token: string, tagName: string, urlIdx: string | null = null) => {
let error = null;
const res = await fetch(`${OLLAMA_API_BASE_URL}/pull`, {
const res = await fetch(`${OLLAMA_API_BASE_URL}/api/pull${urlIdx !== null ? `/${urlIdx}` : ''}`, {
method: 'POST',
headers: {
'Content-Type': 'text/event-stream',
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify({
@@ -349,6 +417,73 @@ export const pullModel = async (token: string, tagName: string) => {
return res;
};
export const downloadModel = async (
token: string,
download_url: string,
urlIdx: string | null = null
) => {
let error = null;
const res = await fetch(
`${OLLAMA_API_BASE_URL}/models/download${urlIdx !== null ? `/${urlIdx}` : ''}`,
{
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify({
url: download_url
})
}
).catch((err) => {
console.log(err);
error = err;
if ('detail' in err) {
error = err.detail;
}
return null;
});
if (error) {
throw error;
}
return res;
};
export const uploadModel = async (token: string, file: File, urlIdx: string | null = null) => {
let error = null;
const formData = new FormData();
formData.append('file', file);
const res = await fetch(
`${OLLAMA_API_BASE_URL}/models/upload${urlIdx !== null ? `/${urlIdx}` : ''}`,
{
method: 'POST',
headers: {
Authorization: `Bearer ${token}`
},
body: formData
}
).catch((err) => {
console.log(err);
error = err;
if ('detail' in err) {
error = err.detail;
}
return null;
});
if (error) {
throw error;
}
return res;
};
// export const pullModel = async (token: string, tagName: string) => {
// return await fetch(`${OLLAMA_API_BASE_URL}/pull`, {
// method: 'POST',
+65 -15
View File
@@ -1,9 +1,10 @@
import { OPENAI_API_BASE_URL } from '$lib/constants';
import { promptTemplate } from '$lib/utils';
export const getOpenAIUrl = async (token: string = '') => {
export const getOpenAIUrls = async (token: string = '') => {
let error = null;
const res = await fetch(`${OPENAI_API_BASE_URL}/url`, {
const res = await fetch(`${OPENAI_API_BASE_URL}/urls`, {
method: 'GET',
headers: {
Accept: 'application/json',
@@ -29,13 +30,13 @@ export const getOpenAIUrl = async (token: string = '') => {
throw error;
}
return res.OPENAI_API_BASE_URL;
return res.OPENAI_API_BASE_URLS;
};
export const updateOpenAIUrl = async (token: string = '', url: string) => {
export const updateOpenAIUrls = async (token: string = '', urls: string[]) => {
let error = null;
const res = await fetch(`${OPENAI_API_BASE_URL}/url/update`, {
const res = await fetch(`${OPENAI_API_BASE_URL}/urls/update`, {
method: 'POST',
headers: {
Accept: 'application/json',
@@ -43,7 +44,7 @@ export const updateOpenAIUrl = async (token: string = '', url: string) => {
...(token && { authorization: `Bearer ${token}` })
},
body: JSON.stringify({
url: url
urls: urls
})
})
.then(async (res) => {
@@ -64,13 +65,13 @@ export const updateOpenAIUrl = async (token: string = '', url: string) => {
throw error;
}
return res.OPENAI_API_BASE_URL;
return res.OPENAI_API_BASE_URLS;
};
export const getOpenAIKey = async (token: string = '') => {
export const getOpenAIKeys = async (token: string = '') => {
let error = null;
const res = await fetch(`${OPENAI_API_BASE_URL}/key`, {
const res = await fetch(`${OPENAI_API_BASE_URL}/keys`, {
method: 'GET',
headers: {
Accept: 'application/json',
@@ -96,13 +97,13 @@ export const getOpenAIKey = async (token: string = '') => {
throw error;
}
return res.OPENAI_API_KEY;
return res.OPENAI_API_KEYS;
};
export const updateOpenAIKey = async (token: string = '', key: string) => {
export const updateOpenAIKeys = async (token: string = '', keys: string[]) => {
let error = null;
const res = await fetch(`${OPENAI_API_BASE_URL}/key/update`, {
const res = await fetch(`${OPENAI_API_BASE_URL}/keys/update`, {
method: 'POST',
headers: {
Accept: 'application/json',
@@ -110,7 +111,7 @@ export const updateOpenAIKey = async (token: string = '', key: string) => {
...(token && { authorization: `Bearer ${token}` })
},
body: JSON.stringify({
key: key
keys: keys
})
})
.then(async (res) => {
@@ -131,7 +132,7 @@ export const updateOpenAIKey = async (token: string = '', key: string) => {
throw error;
}
return res.OPENAI_API_KEY;
return res.OPENAI_API_KEYS;
};
export const getOpenAIModels = async (token: string = '') => {
@@ -150,7 +151,6 @@ export const getOpenAIModels = async (token: string = '') => {
return res.json();
})
.catch((err) => {
console.log(err);
error = `OpenAI: ${err?.error?.message ?? 'Network Problem'}`;
return [];
});
@@ -264,3 +264,53 @@ export const synthesizeOpenAISpeech = async (
return res;
};
export const generateTitle = async (
token: string = '',
template: string,
model: string,
prompt: string,
url: string = OPENAI_API_BASE_URL
) => {
let error = null;
template = promptTemplate(template, prompt);
console.log(template);
const res = await fetch(`${url}/chat/completions`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify({
model: model,
messages: [
{
role: 'user',
content: template
}
],
stream: false
})
})
.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;
}
return null;
});
if (error) {
throw error;
}
return res?.choices[0]?.message?.content ?? 'New Chat';
};
+120 -11
View File
@@ -1,9 +1,9 @@
import { RAG_API_BASE_URL } from '$lib/constants';
export const getChunkParams = async (token: string) => {
export const getRAGConfig = async (token: string) => {
let error = null;
const res = await fetch(`${RAG_API_BASE_URL}/chunk`, {
const res = await fetch(`${RAG_API_BASE_URL}/config`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
@@ -27,18 +27,27 @@ export const getChunkParams = async (token: string) => {
return res;
};
export const updateChunkParams = async (token: string, size: number, overlap: number) => {
type ChunkConfigForm = {
chunk_size: number;
chunk_overlap: number;
};
type RAGConfigForm = {
pdf_extract_images: boolean;
chunk: ChunkConfigForm;
};
export const updateRAGConfig = async (token: string, payload: RAGConfigForm) => {
let error = null;
const res = await fetch(`${RAG_API_BASE_URL}/chunk/update`, {
const res = await fetch(`${RAG_API_BASE_URL}/config/update`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify({
chunk_size: size,
chunk_overlap: overlap
...payload
})
})
.then(async (res) => {
@@ -85,17 +94,49 @@ export const getRAGTemplate = async (token: string) => {
return res?.template ?? '';
};
export const updateRAGTemplate = async (token: string, template: string) => {
export const getQuerySettings = async (token: string) => {
let error = null;
const res = await fetch(`${RAG_API_BASE_URL}/template/update`, {
const res = await fetch(`${RAG_API_BASE_URL}/query/settings`, {
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 QuerySettings = {
k: number | null;
template: string | null;
};
export const updateQuerySettings = async (token: string, settings: QuerySettings) => {
let error = null;
const res = await fetch(`${RAG_API_BASE_URL}/query/settings/update`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
},
body: JSON.stringify({
template: template
...settings
})
})
.then(async (res) => {
@@ -183,7 +224,7 @@ export const queryDoc = async (
token: string,
collection_name: string,
query: string,
k: number
k: number | null = null
) => {
let error = null;
@@ -220,7 +261,7 @@ export const queryCollection = async (
token: string,
collection_names: string,
query: string,
k: number
k: number | null = null
) => {
let error = null;
@@ -304,3 +345,71 @@ export const resetVectorDB = async (token: string) => {
return res;
};
export const getEmbeddingConfig = async (token: string) => {
let error = null;
const res = await fetch(`${RAG_API_BASE_URL}/embedding`, {
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 = {
key: string;
url: string;
};
type EmbeddingModelUpdateForm = {
openai_config?: OpenAIConfigForm;
embedding_engine: string;
embedding_model: string;
};
export const updateEmbeddingConfig = async (token: string, payload: EmbeddingModelUpdateForm) => {
let error = null;
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;
};
+70
View File
@@ -0,0 +1,70 @@
type TextStreamUpdate = {
done: boolean;
value: string;
};
// createOpenAITextStream takes a ReadableStreamDefaultReader from an SSE response,
// and returns an async generator that emits delta updates with large deltas chunked into random sized chunks
export async function createOpenAITextStream(
messageStream: ReadableStreamDefaultReader,
splitLargeDeltas: boolean
): Promise<AsyncGenerator<TextStreamUpdate>> {
let iterator = openAIStreamToIterator(messageStream);
if (splitLargeDeltas) {
iterator = streamLargeDeltasAsRandomChunks(iterator);
}
return iterator;
}
async function* openAIStreamToIterator(
reader: ReadableStreamDefaultReader
): AsyncGenerator<TextStreamUpdate> {
while (true) {
const { value, done } = await reader.read();
if (done) {
yield { done: true, value: '' };
break;
}
const lines = value.split('\n');
for (const line of lines) {
if (line !== '') {
console.log(line);
if (line === 'data: [DONE]') {
yield { done: true, value: '' };
} else {
const data = JSON.parse(line.replace(/^data: /, ''));
console.log(data);
yield { done: false, value: data.choices[0].delta.content ?? '' };
}
}
}
}
}
// 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;
}
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 };
await sleep(5);
content = content.slice(chunkSize);
}
}
}
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+83
View File
@@ -21,3 +21,86 @@ export const getGravatarUrl = async (email: string) => {
return res;
};
export const downloadChatAsPDF = async (chat: object) => {
let error = null;
const blob = await fetch(`${WEBUI_API_BASE_URL}/utils/pdf`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: chat.title,
messages: chat.messages
})
})
.then(async (res) => {
if (!res.ok) throw await res.json();
return res.blob();
})
.catch((err) => {
console.log(err);
error = err;
return null;
});
return blob;
};
export const getHTMLFromMarkdown = async (md: string) => {
let error = null;
const res = await fetch(`${WEBUI_API_BASE_URL}/utils/markdown`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
md: md
})
})
.then(async (res) => {
if (!res.ok) throw await res.json();
return res.json();
})
.catch((err) => {
console.log(err);
error = err;
return null;
});
return res.html;
};
export const downloadDatabase = async (token: string) => {
let error = null;
const res = await fetch(`${WEBUI_API_BASE_URL}/utils/db/download`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${token}`
}
})
.then((response) => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.blob();
})
.then((blob) => {
const url = window.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'webui.db';
document.body.appendChild(a);
a.click();
window.URL.revokeObjectURL(url);
})
.catch((err) => {
console.log(err);
error = err;
return null;
});
};
@@ -1,8 +1,13 @@
<script>
import { getContext } from 'svelte';
const i18n = getContext('i18n');
</script>
<div class=" text-center text-6xl mb-3">📄</div>
<div class="text-center dark:text-white text-2xl font-semibold z-50">Add Files</div>
<div class="text-center dark:text-white text-2xl font-semibold z-50">{$i18n.t('Add Files')}</div>
<slot
><div class=" mt-2 text-center text-sm dark:text-gray-200 w-full">
Drop any files here to add to the conversation
{$i18n.t('Drop any files here to add to the conversation')}
</div>
</slot>
+8 -4
View File
@@ -1,5 +1,5 @@
<script lang="ts">
import { onMount } from 'svelte';
import { onMount, getContext } from 'svelte';
import { Confetti } from 'svelte-confetti';
import { WEBUI_NAME, config } from '$lib/stores';
@@ -9,6 +9,8 @@
import Modal from './common/Modal.svelte';
const i18n = getContext('i18n');
export let show = false;
let changelog = null;
@@ -23,12 +25,14 @@
<div class="px-5 py-4 dark:text-gray-300">
<div class="flex justify-between items-start">
<div class="text-xl font-bold">
Whats New in {$WEBUI_NAME}
{$i18n.t('Whats New in')}
{$WEBUI_NAME}
<Confetti x={[-1, -0.25]} y={[0, 0.5]} />
</div>
<button
class="self-center"
on:click={() => {
localStorage.version = $config.version;
show = false;
}}
>
@@ -45,7 +49,7 @@
</button>
</div>
<div class="flex items-center mt-1">
<div class="text-sm dark:text-gray-200">Release Notes</div>
<div class="text-sm dark:text-gray-200">{$i18n.t('Release Notes')}</div>
<div class="flex self-center w-[1px] h-6 mx-2.5 bg-gray-200 dark:bg-gray-700" />
<div class="text-sm dark:text-gray-200">
v{WEBUI_VERSION}
@@ -108,7 +112,7 @@
}}
class=" px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-gray-100 transition rounded"
>
<span class="relative">Okay, Let's Go!</span>
<span class="relative">{$i18n.t("Okay, Let's Go!")}</span>
</button>
</div>
</div>
+10 -8
View File
@@ -1,12 +1,13 @@
<script lang="ts">
import toast from 'svelte-french-toast';
import { toast } from 'svelte-sonner';
import dayjs from 'dayjs';
import { createEventDispatcher } from 'svelte';
import { onMount } from 'svelte';
import { onMount, getContext } from 'svelte';
import { updateUserById } from '$lib/apis/users';
import Modal from '../common/Modal.svelte';
const i18n = getContext('i18n');
const dispatch = createEventDispatcher();
export let show = false;
@@ -42,7 +43,7 @@
<Modal size="sm" bind:show>
<div>
<div class=" flex justify-between dark:text-gray-300 px-5 py-4">
<div class=" text-lg font-medium self-center">Edit User</div>
<div class=" text-lg font-medium self-center">{$i18n.t('Edit User')}</div>
<button
class="self-center"
on:click={() => {
@@ -84,7 +85,8 @@
<div class=" self-center capitalize font-semibold">{selectedUser.name}</div>
<div class="text-xs text-gray-500">
Created at {dayjs(selectedUser.timestamp * 1000).format('MMMM DD, YYYY')}
{$i18n.t('Created at')}
{dayjs(selectedUser.timestamp * 1000).format($i18n.t('MMMM DD, YYYY'))}
</div>
</div>
</div>
@@ -93,7 +95,7 @@
<div class=" flex flex-col space-y-1.5">
<div class="flex flex-col w-full">
<div class=" mb-1 text-xs text-gray-500">Email</div>
<div class=" mb-1 text-xs text-gray-500">{$i18n.t('Email')}</div>
<div class="flex-1">
<input
@@ -108,7 +110,7 @@
</div>
<div class="flex flex-col w-full">
<div class=" mb-1 text-xs text-gray-500">Name</div>
<div class=" mb-1 text-xs text-gray-500">{$i18n.t('Name')}</div>
<div class="flex-1">
<input
@@ -122,7 +124,7 @@
</div>
<div class="flex flex-col w-full">
<div class=" mb-1 text-xs text-gray-500">New Password</div>
<div class=" mb-1 text-xs text-gray-500">{$i18n.t('New Password')}</div>
<div class="flex-1">
<input
@@ -140,7 +142,7 @@
class=" px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-gray-100 transition rounded"
type="submit"
>
Save
{$i18n.t('Save')}
</button>
</div>
</form>
@@ -0,0 +1,68 @@
<script lang="ts">
import { downloadDatabase } from '$lib/apis/utils';
import { onMount, getContext } from 'svelte';
import { config } from '$lib/stores';
const i18n = getContext('i18n');
export let saveHandler: Function;
onMount(async () => {
// permissions = await getUserPermissions(localStorage.token);
});
</script>
<form
class="flex flex-col h-full justify-between space-y-3 text-sm"
on:submit|preventDefault={async () => {
saveHandler();
}}
>
<div class=" space-y-3 pr-1.5 overflow-y-scroll max-h-80">
<div>
<div class=" mb-2 text-sm font-medium">{$i18n.t('Database')}</div>
<div class=" flex w-full justify-between">
<!-- <div class=" self-center text-xs font-medium">{$i18n.t('Allow Chat Deletion')}</div> -->
{#if $config?.admin_export_enabled ?? true}
<button
class=" flex rounded-md py-1.5 px-3 w-full hover:bg-gray-200 dark:hover:bg-gray-800 transition"
type="button"
on:click={() => {
// exportAllUserChats();
downloadDatabase(localStorage.token);
}}
>
<div class=" self-center mr-3">
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 16 16"
fill="currentColor"
class="w-4 h-4"
>
<path d="M2 3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v1a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V3Z" />
<path
fill-rule="evenodd"
d="M13 6H3v6a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2V6ZM8.75 7.75a.75.75 0 0 0-1.5 0v2.69L6.03 9.22a.75.75 0 0 0-1.06 1.06l2.5 2.5a.75.75 0 0 0 1.06 0l2.5-2.5a.75.75 0 1 0-1.06-1.06l-1.22 1.22V7.75Z"
clip-rule="evenodd"
/>
</svg>
</div>
<div class=" self-center text-sm font-medium">{$i18n.t('Download Database')}</div>
</button>
{/if}
</div>
</div>
</div>
<!-- <div class="flex justify-end pt-3 text-sm font-medium">
<button
class=" px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-gray-100 transition rounded"
type="submit"
>
Save
</button>
</div> -->
</form>
@@ -1,4 +1,5 @@
<script lang="ts">
import { getWebhookUrl, updateWebhookUrl } from '$lib/apis';
import {
getDefaultUserRole,
getJWTExpiresDuration,
@@ -7,13 +8,17 @@
updateDefaultUserRole,
updateJWTExpiresDuration
} from '$lib/apis/auths';
import { onMount } from 'svelte';
import { onMount, getContext } from 'svelte';
const i18n = getContext('i18n');
export let saveHandler: Function;
let signUpEnabled = true;
let defaultUserRole = 'pending';
let JWTExpiresIn = '';
let webhookUrl = '';
const toggleSignUpEnabled = async () => {
signUpEnabled = await toggleSignUpEnabledStatus(localStorage.token);
};
@@ -26,27 +31,32 @@
JWTExpiresIn = await updateJWTExpiresDuration(localStorage.token, duration);
};
const updateWebhookUrlHandler = async () => {
webhookUrl = await updateWebhookUrl(localStorage.token, webhookUrl);
};
onMount(async () => {
signUpEnabled = await getSignUpEnabledStatus(localStorage.token);
defaultUserRole = await getDefaultUserRole(localStorage.token);
JWTExpiresIn = await getJWTExpiresDuration(localStorage.token);
webhookUrl = await getWebhookUrl(localStorage.token);
});
</script>
<form
class="flex flex-col h-full justify-between space-y-3 text-sm"
on:submit|preventDefault={() => {
// console.log('submit');
updateJWTExpiresDurationHandler(JWTExpiresIn);
updateWebhookUrlHandler();
saveHandler();
}}
>
<div class=" space-y-3 pr-1.5 overflow-y-scroll max-h-80">
<div>
<div class=" mb-2 text-sm font-medium">General Settings</div>
<div class=" mb-2 text-sm font-medium">{$i18n.t('General Settings')}</div>
<div class=" flex w-full justify-between">
<div class=" self-center text-xs font-medium">Enable New Sign Ups</div>
<div class=" self-center text-xs font-medium">{$i18n.t('Enable New Sign Ups')}</div>
<button
class="p-1 px-3 text-xs flex rounded transition"
@@ -66,7 +76,7 @@
d="M11.5 1A3.5 3.5 0 0 0 8 4.5V7H2.5A1.5 1.5 0 0 0 1 8.5v5A1.5 1.5 0 0 0 2.5 15h7a1.5 1.5 0 0 0 1.5-1.5v-5A1.5 1.5 0 0 0 9.5 7V4.5a2 2 0 1 1 4 0v1.75a.75.75 0 0 0 1.5 0V4.5A3.5 3.5 0 0 0 11.5 1Z"
/>
</svg>
<span class="ml-2 self-center">Enabled</span>
<span class="ml-2 self-center">{$i18n.t('Enabled')}</span>
{:else}
<svg
xmlns="http://www.w3.org/2000/svg"
@@ -81,25 +91,25 @@
/>
</svg>
<span class="ml-2 self-center">Disabled</span>
<span class="ml-2 self-center">{$i18n.t('Disabled')}</span>
{/if}
</button>
</div>
<div class=" flex w-full justify-between">
<div class=" self-center text-xs font-medium">Default User Role</div>
<div class=" self-center text-xs font-medium">{$i18n.t('Default User Role')}</div>
<div class="flex items-center relative">
<select
class="w-fit pr-8 rounded py-2 px-2 text-xs bg-transparent outline-none text-right"
class="dark:bg-gray-900 w-fit pr-8 rounded py-2 px-2 text-xs bg-transparent outline-none text-right"
bind:value={defaultUserRole}
placeholder="Select a theme"
on:change={(e) => {
updateDefaultUserRoleHandler(e.target.value);
}}
>
<option value="pending">Pending</option>
<option value="user">User</option>
<option value="admin">Admin</option>
<option value="pending">{$i18n.t('pending')}</option>
<option value="user">{$i18n.t('user')}</option>
<option value="admin">{$i18n.t('admin')}</option>
</select>
</div>
</div>
@@ -108,7 +118,24 @@
<div class=" w-full justify-between">
<div class="flex w-full justify-between">
<div class=" self-center text-xs font-medium">JWT Expiration</div>
<div class=" self-center text-xs font-medium">{$i18n.t('Webhook URL')}</div>
</div>
<div class="flex mt-2 space-x-2">
<input
class="w-full rounded py-1.5 px-4 text-sm dark:text-gray-300 dark:bg-gray-800 outline-none border border-gray-100 dark:border-gray-600"
type="text"
placeholder={`https://example.com/webhook`}
bind:value={webhookUrl}
/>
</div>
</div>
<hr class=" dark:border-gray-700 my-3" />
<div class=" w-full justify-between">
<div class="flex w-full justify-between">
<div class=" self-center text-xs font-medium">{$i18n.t('JWT Expiration')}</div>
</div>
<div class="flex mt-2 space-x-2">
@@ -121,8 +148,9 @@
</div>
<div class="mt-2 text-xs text-gray-400 dark:text-gray-500">
Valid time units: <span class=" text-gray-300 font-medium"
>'s', 'm', 'h', 'd', 'w' or '-1' for no expiration.</span
{$i18n.t('Valid time units:')}
<span class=" text-gray-300 font-medium"
>{$i18n.t("'s', 'm', 'h', 'd', 'w' or '-1' for no expiration.")}</span
>
</div>
</div>
@@ -134,7 +162,7 @@
class=" px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-gray-100 transition rounded"
type="submit"
>
Save
{$i18n.t('Save')}
</button>
</div>
</form>
+123 -6
View File
@@ -1,10 +1,17 @@
<script lang="ts">
import { getModelFilterConfig, updateModelFilterConfig } from '$lib/apis';
import { getSignUpEnabledStatus, toggleSignUpEnabledStatus } from '$lib/apis/auths';
import { getUserPermissions, updateUserPermissions } from '$lib/apis/users';
import { onMount } from 'svelte';
import { onMount, getContext } from 'svelte';
import { models } from '$lib/stores';
const i18n = getContext('i18n');
export let saveHandler: Function;
let whitelistEnabled = false;
let whitelistModels = [''];
let permissions = {
chat: {
deletion: true
@@ -13,6 +20,13 @@
onMount(async () => {
permissions = await getUserPermissions(localStorage.token);
const res = await getModelFilterConfig(localStorage.token);
if (res) {
whitelistEnabled = res.enabled;
whitelistModels = res.models.length > 0 ? res.models : [''];
}
});
</script>
@@ -21,15 +35,17 @@
on:submit|preventDefault={async () => {
// console.log('submit');
await updateUserPermissions(localStorage.token, permissions);
await updateModelFilterConfig(localStorage.token, whitelistEnabled, whitelistModels);
saveHandler();
}}
>
<div class=" space-y-3 pr-1.5 overflow-y-scroll max-h-80">
<div>
<div class=" mb-2 text-sm font-medium">User Permissions</div>
<div class=" mb-2 text-sm font-medium">{$i18n.t('User Permissions')}</div>
<div class=" flex w-full justify-between">
<div class=" self-center text-xs font-medium">Allow Chat Deletion</div>
<div class=" self-center text-xs font-medium">{$i18n.t('Allow Chat Deletion')}</div>
<button
class="p-1 px-3 text-xs flex rounded transition"
@@ -49,7 +65,7 @@
d="M11.5 1A3.5 3.5 0 0 0 8 4.5V7H2.5A1.5 1.5 0 0 0 1 8.5v5A1.5 1.5 0 0 0 2.5 15h7a1.5 1.5 0 0 0 1.5-1.5v-5A1.5 1.5 0 0 0 9.5 7V4.5a2 2 0 1 1 4 0v1.75a.75.75 0 0 0 1.5 0V4.5A3.5 3.5 0 0 0 11.5 1Z"
/>
</svg>
<span class="ml-2 self-center">Allow</span>
<span class="ml-2 self-center">{$i18n.t('Allow')}</span>
{:else}
<svg
xmlns="http://www.w3.org/2000/svg"
@@ -64,11 +80,112 @@
/>
</svg>
<span class="ml-2 self-center">Don't Allow</span>
<span class="ml-2 self-center">{$i18n.t("Don't Allow")}</span>
{/if}
</button>
</div>
</div>
<hr class=" dark:border-gray-700 my-2" />
<div class="mt-2 space-y-3 pr-1.5">
<div>
<div class="mb-2">
<div class="flex justify-between items-center text-xs">
<div class=" text-sm font-medium">{$i18n.t('Manage Models')}</div>
</div>
</div>
<div class=" space-y-3">
<div>
<div class="flex justify-between items-center text-xs">
<div class=" text-xs font-medium">{$i18n.t('Model Whitelisting')}</div>
<button
class=" text-xs font-medium text-gray-500"
type="button"
on:click={() => {
whitelistEnabled = !whitelistEnabled;
}}>{whitelistEnabled ? $i18n.t('On') : $i18n.t('Off')}</button
>
</div>
</div>
{#if whitelistEnabled}
<div>
<div class=" space-y-1.5">
{#each whitelistModels as modelId, modelIdx}
<div class="flex w-full">
<div class="flex-1 mr-2">
<select
class="w-full rounded-lg py-2 px-4 text-sm dark:text-gray-300 dark:bg-gray-850 outline-none"
bind:value={modelId}
placeholder="Select a model"
>
<option value="" disabled selected>{$i18n.t('Select a model')}</option>
{#each $models.filter((model) => model.id) as model}
<option value={model.id} class="bg-gray-100 dark:bg-gray-700"
>{model.name}</option
>
{/each}
</select>
</div>
{#if modelIdx === 0}
<button
class="px-2.5 bg-gray-100 hover:bg-gray-200 text-gray-800 dark:bg-gray-900 dark:text-white rounded-lg transition"
type="button"
on:click={() => {
if (whitelistModels.at(-1) !== '') {
whitelistModels = [...whitelistModels, ''];
}
}}
>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 16 16"
fill="currentColor"
class="w-4 h-4"
>
<path
d="M8.75 3.75a.75.75 0 0 0-1.5 0v3.5h-3.5a.75.75 0 0 0 0 1.5h3.5v3.5a.75.75 0 0 0 1.5 0v-3.5h3.5a.75.75 0 0 0 0-1.5h-3.5v-3.5Z"
/>
</svg>
</button>
{:else}
<button
class="px-2.5 bg-gray-100 hover:bg-gray-200 text-gray-800 dark:bg-gray-900 dark:text-white rounded-lg transition"
type="button"
on:click={() => {
whitelistModels.splice(modelIdx, 1);
whitelistModels = whitelistModels;
}}
>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 16 16"
fill="currentColor"
class="w-4 h-4"
>
<path d="M3.75 7.25a.75.75 0 0 0 0 1.5h8.5a.75.75 0 0 0 0-1.5h-8.5Z" />
</svg>
</button>
{/if}
</div>
{/each}
</div>
<div class="flex justify-end items-center text-xs mt-1.5 text-right">
<div class=" text-xs font-medium">
{whitelistModels.length}
{$i18n.t('Model(s) Whitelisted')}
</div>
</div>
</div>
{/if}
</div>
</div>
</div>
</div>
<div class="flex justify-end pt-3 text-sm font-medium">
@@ -76,7 +193,7 @@
class=" px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-gray-100 transition rounded"
type="submit"
>
Save
{$i18n.t('Save')}
</button>
</div>
</form>
+41 -3
View File
@@ -1,9 +1,13 @@
<script>
import { getContext } from 'svelte';
import Modal from '../common/Modal.svelte';
import Database from './Settings/Database.svelte';
import General from './Settings/General.svelte';
import Users from './Settings/Users.svelte';
const i18n = getContext('i18n');
export let show = false;
let selectedTab = 'general';
@@ -12,7 +16,7 @@
<Modal bind:show>
<div>
<div class=" flex justify-between dark:text-gray-300 px-5 py-4">
<div class=" text-lg font-medium self-center">Admin Settings</div>
<div class=" text-lg font-medium self-center">{$i18n.t('Admin Settings')}</div>
<button
class="self-center"
on:click={() => {
@@ -60,7 +64,7 @@
/>
</svg>
</div>
<div class=" self-center">General</div>
<div class=" self-center">{$i18n.t('General')}</div>
</button>
<button
@@ -84,7 +88,35 @@
/>
</svg>
</div>
<div class=" self-center">Users</div>
<div class=" self-center">{$i18n.t('Users')}</div>
</button>
<button
class="px-2.5 py-2.5 min-w-fit rounded-lg flex-1 md:flex-none flex text-right transition {selectedTab ===
'db'
? 'bg-gray-200 dark:bg-gray-700'
: ' hover:bg-gray-300 dark:hover:bg-gray-800'}"
on:click={() => {
selectedTab = 'db';
}}
>
<div class=" self-center mr-2">
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 16 16"
fill="currentColor"
class="w-4 h-4"
>
<path d="M8 7c3.314 0 6-1.343 6-3s-2.686-3-6-3-6 1.343-6 3 2.686 3 6 3Z" />
<path
d="M8 8.5c1.84 0 3.579-.37 4.914-1.037A6.33 6.33 0 0 0 14 6.78V8c0 1.657-2.686 3-6 3S2 9.657 2 8V6.78c.346.273.72.5 1.087.683C4.42 8.131 6.16 8.5 8 8.5Z"
/>
<path
d="M8 12.5c1.84 0 3.579-.37 4.914-1.037.366-.183.74-.41 1.086-.684V12c0 1.657-2.686 3-6 3s-6-1.343-6-3v-1.22c.346.273.72.5 1.087.683C4.42 12.131 6.16 12.5 8 12.5Z"
/>
</svg>
</div>
<div class=" self-center">{$i18n.t('Database')}</div>
</button>
</div>
<div class="flex-1 md:min-h-[380px]">
@@ -100,6 +132,12 @@
show = false;
}}
/>
{:else if selectedTab === 'db'}
<Database
saveHandler={() => {
show = false;
}}
/>
{/if}
</div>
</div>
+212 -183
View File
@@ -1,6 +1,6 @@
<script lang="ts">
import toast from 'svelte-french-toast';
import { onMount, tick } from 'svelte';
import { toast } from 'svelte-sonner';
import { onMount, tick, getContext } from 'svelte';
import { settings } from '$lib/stores';
import { blobToFile, calculateSHA256, findWordIndices } from '$lib/utils';
@@ -12,13 +12,16 @@
import Documents from './MessageInput/Documents.svelte';
import Models from './MessageInput/Models.svelte';
import { transcribeAudio } from '$lib/apis/audio';
import Tooltip from '../common/Tooltip.svelte';
const i18n = getContext('i18n');
export let submitPrompt: Function;
export let stopResponse: Function;
export let suggestionPrompts = [];
export let autoScroll = true;
let chatTextAreaElement: HTMLTextAreaElement;
let filesInputElement;
let promptsElement;
@@ -42,11 +45,9 @@
let speechRecognition;
$: if (prompt) {
const chatInput = document.getElementById('chat-textarea');
if (chatInput) {
chatInput.style.height = '';
chatInput.style.height = Math.min(chatInput.scrollHeight, 200) + 'px';
if (chatTextAreaElement) {
chatTextAreaElement.style.height = '';
chatTextAreaElement.style.height = Math.min(chatTextAreaElement.scrollHeight, 200) + 'px';
}
}
@@ -85,9 +86,7 @@
if (res) {
prompt = res.text;
await tick();
const inputElement = document.getElementById('chat-textarea');
inputElement?.focus();
chatTextAreaElement?.focus();
if (prompt !== '' && $settings?.speechAutoSend === true) {
submitPrompt(prompt, user);
@@ -190,8 +189,7 @@
prompt = `${prompt}${transcript}`;
await tick();
const inputElement = document.getElementById('chat-textarea');
inputElement?.focus();
chatTextAreaElement?.focus();
// Restart the inactivity timeout
timeoutId = setTimeout(() => {
@@ -213,11 +211,11 @@
// Event triggered when an error occurs
speechRecognition.onerror = function (event) {
console.log(event);
toast.error(`Speech recognition error: ${event.error}`);
toast.error($i18n.t(`Speech recognition error: {{error}}`, { error: event.error }));
isRecording = false;
};
} else {
toast.error('SpeechRecognition API is not supported in this browser.');
toast.error($i18n.t('SpeechRecognition API is not supported in this browser.'));
}
}
}
@@ -293,8 +291,17 @@
};
onMount(() => {
window.setTimeout(() => chatTextAreaElement?.focus(), 0);
const dropZone = document.querySelector('body');
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key === 'Escape') {
console.log('Escape');
dragged = false;
}
};
const onDragOver = (e) => {
e.preventDefault();
dragged = true;
@@ -309,49 +316,55 @@
console.log(e);
if (e.dataTransfer?.files) {
let reader = new FileReader();
reader.onload = (event) => {
files = [
...files,
{
type: 'image',
url: `${event.target.result}`
}
];
};
const inputFiles = e.dataTransfer?.files;
const inputFiles = Array.from(e.dataTransfer?.files);
if (inputFiles && inputFiles.length > 0) {
const file = inputFiles[0];
console.log(file, file.name.split('.').at(-1));
if (['image/gif', 'image/jpeg', 'image/png'].includes(file['type'])) {
reader.readAsDataURL(file);
} else if (
SUPPORTED_FILE_TYPE.includes(file['type']) ||
SUPPORTED_FILE_EXTENSIONS.includes(file.name.split('.').at(-1))
) {
uploadDoc(file);
} else {
toast.error(
`Unknown File Type '${file['type']}', but accepting and treating as plain text`
);
uploadDoc(file);
}
inputFiles.forEach((file) => {
console.log(file, file.name.split('.').at(-1));
if (['image/gif', 'image/jpeg', 'image/png'].includes(file['type'])) {
let reader = new FileReader();
reader.onload = (event) => {
files = [
...files,
{
type: 'image',
url: `${event.target.result}`
}
];
};
reader.readAsDataURL(file);
} else if (
SUPPORTED_FILE_TYPE.includes(file['type']) ||
SUPPORTED_FILE_EXTENSIONS.includes(file.name.split('.').at(-1))
) {
uploadDoc(file);
} else {
toast.error(
$i18n.t(
`Unknown File Type '{{file_type}}', but accepting and treating as plain text`,
{ file_type: file['type'] }
)
);
uploadDoc(file);
}
});
} else {
toast.error(`File not found.`);
toast.error($i18n.t(`File not found.`));
}
}
dragged = false;
};
window.addEventListener('keydown', handleKeyDown);
dropZone?.addEventListener('dragover', onDragOver);
dropZone?.addEventListener('drop', onDrop);
dropZone?.addEventListener('dragleave', onDragLeave);
return () => {
window.removeEventListener('keydown', handleKeyDown);
dropZone?.removeEventListener('dragover', onDragOver);
dropZone?.removeEventListener('drop', onDrop);
dropZone?.removeEventListener('dragleave', onDragLeave);
@@ -361,12 +374,12 @@
{#if dragged}
<div
class="fixed w-full h-full flex z-50 touch-none pointer-events-none"
class="fixed lg:w-[calc(100%-260px)] w-full h-full flex z-50 touch-none pointer-events-none"
id="dropzone"
role="region"
aria-label="Drag and Drop Container"
>
<div class="absolute rounded-xl w-full h-full backdrop-blur bg-gray-800/40 flex justify-center">
<div class="absolute w-full h-full backdrop-blur bg-gray-800/40 flex justify-center">
<div class="m-auto pt-64 flex flex-col justify-center">
<div class="max-w-md">
<AddFilesPlaceholder />
@@ -453,44 +466,49 @@
bind:files={inputFiles}
type="file"
hidden
multiple
on:change={async () => {
let reader = new FileReader();
reader.onload = (event) => {
files = [
...files,
{
type: 'image',
url: `${event.target.result}`
}
];
inputFiles = null;
filesInputElement.value = '';
};
if (inputFiles && inputFiles.length > 0) {
const file = inputFiles[0];
if (['image/gif', 'image/jpeg', 'image/png'].includes(file['type'])) {
reader.readAsDataURL(file);
} else if (
SUPPORTED_FILE_TYPE.includes(file['type']) ||
SUPPORTED_FILE_EXTENSIONS.includes(file.name.split('.').at(-1))
) {
uploadDoc(file);
filesInputElement.value = '';
} else {
toast.error(
`Unknown File Type '${file['type']}', but accepting and treating as plain text`
);
uploadDoc(file);
filesInputElement.value = '';
}
const _inputFiles = Array.from(inputFiles);
_inputFiles.forEach((file) => {
if (['image/gif', 'image/jpeg', 'image/png'].includes(file['type'])) {
let reader = new FileReader();
reader.onload = (event) => {
files = [
...files,
{
type: 'image',
url: `${event.target.result}`
}
];
inputFiles = null;
filesInputElement.value = '';
};
reader.readAsDataURL(file);
} else if (
SUPPORTED_FILE_TYPE.includes(file['type']) ||
SUPPORTED_FILE_EXTENSIONS.includes(file.name.split('.').at(-1))
) {
uploadDoc(file);
filesInputElement.value = '';
} else {
toast.error(
$i18n.t(
`Unknown File Type '{{file_type}}', but accepting and treating as plain text`,
{ file_type: file['type'] }
)
);
uploadDoc(file);
filesInputElement.value = '';
}
});
} else {
toast.error(`File not found.`);
toast.error($i18n.t(`File not found.`));
}
}}
/>
<form
class=" flex flex-col relative w-full rounded-xl border dark:border-gray-700 bg-white dark:bg-gray-900 dark:text-gray-100"
class=" flex flex-col relative w-full rounded-3xl px-1.5 border border-gray-100 dark:border-gray-850 bg-white dark:bg-gray-900 dark:text-gray-100"
on:submit|preventDefault={() => {
submitPrompt(prompt, user);
}}
@@ -572,7 +590,7 @@
{file.name}
</div>
<div class=" text-gray-500 text-sm">Document</div>
<div class=" text-gray-500 text-sm">{$i18n.t('Document')}</div>
</div>
</div>
{:else if file.type === 'collection'}
@@ -600,7 +618,7 @@
{file?.title ?? `#${file.name}`}
</div>
<div class=" text-gray-500 text-sm">Collection</div>
<div class=" text-gray-500 text-sm">{$i18n.t('Collection')}</div>
</div>
</div>
{/if}
@@ -633,40 +651,41 @@
<div class=" flex">
{#if fileUploadEnabled}
<div class=" self-end mb-2 ml-1.5">
<button
class=" text-gray-600 dark:text-gray-200 transition rounded-lg p-1 ml-1"
type="button"
on:click={() => {
filesInputElement.click();
}}
>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
class="w-5 h-5"
<div class=" self-end mb-2 ml-1">
<Tooltip content={$i18n.t('Upload files')}>
<button
class="bg-gray-50 hover:bg-gray-100 text-gray-800 dark:bg-gray-850 dark:text-white dark:hover:bg-gray-800 transition rounded-full p-1.5"
type="button"
on:click={() => {
filesInputElement.click();
}}
>
<path
fill-rule="evenodd"
d="M15.621 4.379a3 3 0 00-4.242 0l-7 7a3 3 0 004.241 4.243h.001l.497-.5a.75.75 0 011.064 1.057l-.498.501-.002.002a4.5 4.5 0 01-6.364-6.364l7-7a4.5 4.5 0 016.368 6.36l-3.455 3.553A2.625 2.625 0 119.52 9.52l3.45-3.451a.75.75 0 111.061 1.06l-3.45 3.451a1.125 1.125 0 001.587 1.595l3.454-3.553a3 3 0 000-4.242z"
clip-rule="evenodd"
/>
</svg>
</button>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 16 16"
fill="currentColor"
class="w-[1.2rem] h-[1.2rem]"
>
<path
d="M8.75 3.75a.75.75 0 0 0-1.5 0v3.5h-3.5a.75.75 0 0 0 0 1.5h3.5v3.5a.75.75 0 0 0 1.5 0v-3.5h3.5a.75.75 0 0 0 0-1.5h-3.5v-3.5Z"
/>
</svg>
</button>
</Tooltip>
</div>
{/if}
<textarea
id="chat-textarea"
class=" dark:bg-gray-900 dark:text-gray-100 outline-none w-full py-3 px-2 {fileUploadEnabled
bind:this={chatTextAreaElement}
class=" dark:bg-gray-900 dark:text-gray-100 outline-none w-full py-3 px-3 {fileUploadEnabled
? ''
: ' pl-4'} rounded-xl resize-none h-[48px]"
placeholder={chatInputPlaceholder !== ''
? chatInputPlaceholder
: isRecording
? 'Listening...'
: 'Send a message'}
? $i18n.t('Listening...')
: $i18n.t('Send a Message')}
bind:value={prompt}
on:keypress={(e) => {
if (e.keyCode == 13 && !e.shiftKey) {
@@ -803,92 +822,102 @@
}}
/>
<div class="self-end mb-2 flex space-x-0.5 mr-2">
<div class="self-end mb-2 flex space-x-1 mr-1">
{#if messages.length == 0 || messages.at(-1).done == true}
{#if speechRecognitionEnabled}
<Tooltip content={$i18n.t('Record voice')}>
{#if speechRecognitionEnabled}
<button
id="voice-input-button"
class=" text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-850 transition rounded-full p-1.5 mr-0.5 self-center"
type="button"
on:click={() => {
speechRecognitionHandler();
}}
>
{#if isRecording}
<svg
class=" w-5 h-5 translate-y-[0.5px]"
fill="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
><style>
.spinner_qM83 {
animation: spinner_8HQG 1.05s infinite;
}
.spinner_oXPr {
animation-delay: 0.1s;
}
.spinner_ZTLf {
animation-delay: 0.2s;
}
@keyframes spinner_8HQG {
0%,
57.14% {
animation-timing-function: cubic-bezier(0.33, 0.66, 0.66, 1);
transform: translate(0);
}
28.57% {
animation-timing-function: cubic-bezier(0.33, 0, 0.66, 0.33);
transform: translateY(-6px);
}
100% {
transform: translate(0);
}
}
</style><circle class="spinner_qM83" cx="4" cy="12" r="2.5" /><circle
class="spinner_qM83 spinner_oXPr"
cx="12"
cy="12"
r="2.5"
/><circle
class="spinner_qM83 spinner_ZTLf"
cx="20"
cy="12"
r="2.5"
/></svg
>
{:else}
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
class="w-5 h-5 translate-y-[0.5px]"
>
<path d="M7 4a3 3 0 016 0v6a3 3 0 11-6 0V4z" />
<path
d="M5.5 9.643a.75.75 0 00-1.5 0V10c0 3.06 2.29 5.585 5.25 5.954V17.5h-1.5a.75.75 0 000 1.5h4.5a.75.75 0 000-1.5h-1.5v-1.546A6.001 6.001 0 0016 10v-.357a.75.75 0 00-1.5 0V10a4.5 4.5 0 01-9 0v-.357z"
/>
</svg>
{/if}
</button>
{/if}
</Tooltip>
<Tooltip content={$i18n.t('Send message')}>
<button
id="voice-input-button"
class=" text-gray-600 dark:text-gray-300 transition rounded-lg p-1.5 mr-0.5 self-center"
type="button"
on:click={() => {
speechRecognitionHandler();
}}
class="{prompt !== ''
? 'bg-black text-white hover:bg-gray-900 dark:bg-white dark:text-black dark:hover:bg-gray-100 '
: 'text-white bg-gray-100 dark:text-gray-900 dark:bg-gray-800 disabled'} transition rounded-full p-1.5 self-center"
type="submit"
disabled={prompt === ''}
>
{#if isRecording}
<svg
class=" w-5 h-5 translate-y-[0.5px]"
fill="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
><style>
.spinner_qM83 {
animation: spinner_8HQG 1.05s infinite;
}
.spinner_oXPr {
animation-delay: 0.1s;
}
.spinner_ZTLf {
animation-delay: 0.2s;
}
@keyframes spinner_8HQG {
0%,
57.14% {
animation-timing-function: cubic-bezier(0.33, 0.66, 0.66, 1);
transform: translate(0);
}
28.57% {
animation-timing-function: cubic-bezier(0.33, 0, 0.66, 0.33);
transform: translateY(-6px);
}
100% {
transform: translate(0);
}
}
</style><circle class="spinner_qM83" cx="4" cy="12" r="2.5" /><circle
class="spinner_qM83 spinner_oXPr"
cx="12"
cy="12"
r="2.5"
/><circle class="spinner_qM83 spinner_ZTLf" cx="20" cy="12" r="2.5" /></svg
>
{:else}
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
fill="currentColor"
class="w-5 h-5 translate-y-[0.5px]"
>
<path d="M7 4a3 3 0 016 0v6a3 3 0 11-6 0V4z" />
<path
d="M5.5 9.643a.75.75 0 00-1.5 0V10c0 3.06 2.29 5.585 5.25 5.954V17.5h-1.5a.75.75 0 000 1.5h4.5a.75.75 0 000-1.5h-1.5v-1.546A6.001 6.001 0 0016 10v-.357a.75.75 0 00-1.5 0V10a4.5 4.5 0 01-9 0v-.357z"
/>
</svg>
{/if}
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 16 16"
fill="currentColor"
class="w-5 h-5"
>
<path
fill-rule="evenodd"
d="M8 14a.75.75 0 0 1-.75-.75V4.56L4.03 7.78a.75.75 0 0 1-1.06-1.06l4.5-4.5a.75.75 0 0 1 1.06 0l4.5 4.5a.75.75 0 0 1-1.06 1.06L8.75 4.56v8.69A.75.75 0 0 1 8 14Z"
clip-rule="evenodd"
/>
</svg>
</button>
{/if}
<button
class="{prompt !== ''
? 'bg-black text-white hover:bg-gray-900 dark:bg-white dark:text-black dark:hover:bg-gray-100 '
: 'text-white bg-gray-100 dark:text-gray-900 dark:bg-gray-800 disabled'} transition rounded-lg p-1 mr-0.5 w-7 h-7 self-center"
type="submit"
disabled={prompt === ''}
>
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 16 16"
fill="currentColor"
class="w-4.5 h-4.5 mx-auto"
>
<path
fill-rule="evenodd"
d="M8 14a.75.75 0 0 1-.75-.75V4.56L4.03 7.78a.75.75 0 0 1-1.06-1.06l4.5-4.5a.75.75 0 0 1 1.06 0l4.5 4.5a.75.75 0 0 1-1.06 1.06L8.75 4.56v8.69A.75.75 0 0 1 8 14Z"
clip-rule="evenodd"
/>
</svg>
</button>
</Tooltip>
{:else}
<button
class="bg-white hover:bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-white dark:hover:bg-gray-800 transition rounded-lg p-1.5"
class="bg-white hover:bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-white dark:hover:bg-gray-800 transition rounded-full p-1.5"
on:click={stopResponse}
>
<svg
@@ -910,7 +939,7 @@
</form>
<div class="mt-1.5 text-xs text-gray-500 text-center">
LLMs can make mistakes. Verify important information.
{$i18n.t('LLMs can make mistakes. Verify important information.')}
</div>
</div>
</div>
@@ -3,8 +3,10 @@
import { documents } from '$lib/stores';
import { removeFirstHashWord, isValidHttpUrl } from '$lib/utils';
import { tick } from 'svelte';
import toast from 'svelte-french-toast';
import { tick, getContext } from 'svelte';
import { toast } from 'svelte-sonner';
const i18n = getContext('i18n');
export let prompt = '';
@@ -89,16 +91,16 @@
{#if filteredItems.length > 0 || prompt.split(' ')?.at(0)?.substring(1).startsWith('http')}
<div class="md:px-2 mb-3 text-left w-full absolute bottom-0 left-0 right-0">
<div class="flex w-full rounded-lg border border-gray-100 dark:border-gray-700">
<div class=" bg-gray-100 dark:bg-gray-700 w-10 rounded-l-lg text-center">
<div class="flex w-full px-2">
<div class=" bg-gray-100 dark:bg-gray-700 w-10 rounded-l-xl text-center">
<div class=" text-lg font-semibold mt-2">#</div>
</div>
<div class="max-h-60 flex flex-col w-full rounded-r-lg">
<div class=" overflow-y-auto bg-white p-2 rounded-tr-lg space-y-0.5">
<div class="max-h-60 flex flex-col w-full rounded-r-xl bg-white">
<div class="m-1 overflow-y-auto p-1 rounded-r-xl space-y-0.5">
{#each filteredItems as doc, docIdx}
<button
class=" px-3 py-1.5 rounded-lg w-full text-left {docIdx === selectedIdx
class=" px-3 py-1.5 rounded-xl w-full text-left {docIdx === selectedIdx
? ' bg-gray-100 selected-command-option-button'
: ''}"
type="button"
@@ -117,7 +119,7 @@
{doc?.title ?? `#${doc.name}`}
</div>
<div class=" text-xs text-gray-600 line-clamp-1">Collection</div>
<div class=" text-xs text-gray-600 line-clamp-1">{$i18n.t('Collection')}</div>
{:else}
<div class=" font-medium text-black line-clamp-1">
#{doc.name} ({doc.filename})
@@ -132,7 +134,7 @@
{#if prompt.split(' ')?.at(0)?.substring(1).startsWith('http')}
<button
class="px-3 py-1.5 rounded-lg w-full text-left bg-gray-100 selected-command-option-button"
class="px-3 py-1.5 rounded-xl w-full text-left bg-gray-100 selected-command-option-button"
type="button"
on:click={() => {
const url = prompt.split(' ')?.at(0)?.substring(1);
@@ -140,7 +142,9 @@
confirmSelectWeb(url);
} else {
toast.error(
'Oops! Looks like the URL is invalid. Please double-check and try again.'
$i18n.t(
'Oops! Looks like the URL is invalid. Please double-check and try again.'
)
);
}
}}
@@ -149,7 +153,7 @@
{prompt.split(' ')?.at(0)?.substring(1)}
</div>
<div class=" text-xs text-gray-600 line-clamp-1">Web</div>
<div class=" text-xs text-gray-600 line-clamp-1">{$i18n.t('Web')}</div>
</button>
{/if}
</div>
@@ -2,8 +2,10 @@
import { generatePrompt } from '$lib/apis/ollama';
import { models } from '$lib/stores';
import { splitStream } from '$lib/utils';
import { tick } from 'svelte';
import toast from 'svelte-french-toast';
import { tick, getContext } from 'svelte';
import { toast } from 'svelte-sonner';
const i18n = getContext('i18n');
export let prompt = '';
export let user = null;
@@ -41,7 +43,7 @@
user = JSON.parse(JSON.stringify(model.name));
await tick();
chatInputPlaceholder = `'${model.name}' is thinking...`;
chatInputPlaceholder = $i18n.t('{{modelName}} is thinking...', { modelName: model.name });
const chatInputElement = document.getElementById('chat-textarea');
@@ -79,14 +81,18 @@
throw data;
}
if (data.done == false) {
if (prompt == '' && data.response == '\n') {
continue;
} else {
prompt += data.response;
console.log(data.response);
chatInputElement.scrollTop = chatInputElement.scrollHeight;
await tick();
if ('id' in data) {
console.log(data);
} else {
if (data.done == false) {
if (prompt == '' && data.response == '\n') {
continue;
} else {
prompt += data.response;
console.log(data.response);
chatInputElement.scrollTop = chatInputElement.scrollHeight;
await tick();
}
}
}
}
@@ -109,7 +115,9 @@
toast.error(error.error);
}
} else {
toast.error(`Uh-oh! There was an issue connecting to Ollama.`);
toast.error(
$i18n.t('Uh-oh! There was an issue connecting to {{provider}}.', { provider: 'llama' })
);
}
}
@@ -121,16 +129,16 @@
{#if filteredModels.length > 0}
<div class="md:px-2 mb-3 text-left w-full absolute bottom-0 left-0 right-0">
<div class="flex w-full rounded-lg border border-gray-100 dark:border-gray-700">
<div class=" bg-gray-100 dark:bg-gray-700 w-10 rounded-l-lg text-center">
<div class="flex w-full px-2">
<div class=" bg-gray-100 dark:bg-gray-700 w-10 rounded-l-xl text-center">
<div class=" text-lg font-semibold mt-2">@</div>
</div>
<div class="max-h-60 flex flex-col w-full rounded-r-lg">
<div class=" overflow-y-auto bg-white p-2 rounded-tr-lg space-y-0.5">
<div class="max-h-60 flex flex-col w-full rounded-r-xl bg-white">
<div class="m-1 overflow-y-auto p-1 rounded-r-xl space-y-0.5">
{#each filteredModels as model, modelIdx}
<button
class=" px-3 py-1.5 rounded-lg w-full text-left {modelIdx === selectedIdx
class=" px-3 py-1.5 rounded-xl w-full text-left {modelIdx === selectedIdx
? ' bg-gray-100 selected-command-option-button'
: ''}"
type="button"
@@ -1,8 +1,10 @@
<script lang="ts">
import { prompts } from '$lib/stores';
import { findWordIndices } from '$lib/utils';
import { tick } from 'svelte';
import toast from 'svelte-french-toast';
import { tick, getContext } from 'svelte';
import { toast } from 'svelte-sonner';
const i18n = getContext('i18n');
export let prompt = '';
let selectedCommandIdx = 0;
@@ -29,7 +31,7 @@
if (command.content.includes('{{CLIPBOARD}}')) {
const clipboardText = await navigator.clipboard.readText().catch((err) => {
toast.error('Failed to read clipboard contents');
toast.error($i18n.t('Failed to read clipboard contents'));
return '{{CLIPBOARD}}';
});
@@ -60,16 +62,16 @@
{#if filteredPromptCommands.length > 0}
<div class="md:px-2 mb-3 text-left w-full absolute bottom-0 left-0 right-0">
<div class="flex w-full rounded-lg border border-gray-100 dark:border-gray-700">
<div class=" bg-gray-100 dark:bg-gray-700 w-10 rounded-l-lg text-center">
<div class="flex w-full px-2">
<div class=" bg-gray-100 dark:bg-gray-700 w-10 rounded-l-xl text-center">
<div class=" text-lg font-semibold mt-2">/</div>
</div>
<div class="max-h-60 flex flex-col w-full rounded-r-lg">
<div class=" overflow-y-auto bg-white p-2 rounded-tr-lg space-y-0.5">
<div class="max-h-60 flex flex-col w-full rounded-r-xl bg-white">
<div class="m-1 overflow-y-auto p-1 rounded-r-xl space-y-0.5">
{#each filteredPromptCommands as command, commandIdx}
<button
class=" px-3 py-1.5 rounded-lg w-full text-left {commandIdx === selectedCommandIdx
class=" px-3 py-1.5 rounded-xl w-full text-left {commandIdx === selectedCommandIdx
? ' bg-gray-100 selected-command-option-button'
: ''}"
type="button"
@@ -93,7 +95,7 @@
</div>
<div
class=" px-2 pb-1 text-xs text-gray-600 bg-white rounded-br-lg flex items-center space-x-1"
class=" px-2 pb-1 text-xs text-gray-600 bg-white rounded-br-xl flex items-center space-x-1"
>
<div>
<svg
@@ -113,8 +115,9 @@
</div>
<div class="line-clamp-1">
Tip: Update multiple variable slots consecutively by pressing the tab key in the chat
input after each replacement.
{$i18n.t(
'Tip: Update multiple variable slots consecutively by pressing the tab key in the chat input after each replacement.'
)}
</div>
</div>
</div>

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