Матенков Андрей commited on
Commit
39a2f10
·
1 Parent(s): e347f27

Chat moved from github

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .env.local.template +14 -0
  2. Dockerfile +3 -3
  3. chat-ui/.dockerignore +8 -0
  4. chat-ui/.eslintignore +13 -0
  5. chat-ui/.eslintrc.cjs +43 -0
  6. chat-ui/.gitignore +10 -0
  7. chat-ui/.npmrc +1 -0
  8. chat-ui/.prettierignore +13 -0
  9. chat-ui/.prettierrc +8 -0
  10. chat-ui/.vscode/settings.json +8 -0
  11. chat-ui/LICENSE +203 -0
  12. chat-ui/PRIVACY.md +38 -0
  13. chat-ui/README.md +317 -0
  14. chat-ui/package-lock.json +0 -0
  15. chat-ui/package.json +68 -0
  16. chat-ui/postcss.config.js +6 -0
  17. chat-ui/src/app.d.ts +20 -0
  18. chat-ui/src/app.html +23 -0
  19. chat-ui/src/hooks.server.ts +113 -0
  20. chat-ui/src/lib/actions/snapScrollToBottom.ts +54 -0
  21. chat-ui/src/lib/buildPrompt.ts +49 -0
  22. chat-ui/src/lib/buildSearchPrompt.ts +25 -0
  23. chat-ui/src/lib/components/AnnouncementBanner.svelte +15 -0
  24. chat-ui/src/lib/components/CodeBlock.svelte +28 -0
  25. chat-ui/src/lib/components/CopyToClipBoardBtn.svelte +50 -0
  26. chat-ui/src/lib/components/LoginModal.svelte +76 -0
  27. chat-ui/src/lib/components/MobileNav.svelte +62 -0
  28. chat-ui/src/lib/components/Modal.svelte +62 -0
  29. chat-ui/src/lib/components/ModelCardMetadata.svelte +48 -0
  30. chat-ui/src/lib/components/ModelsModal.svelte +153 -0
  31. chat-ui/src/lib/components/NavConversationItem.svelte +87 -0
  32. chat-ui/src/lib/components/NavMenu.svelte +107 -0
  33. chat-ui/src/lib/components/OpenWebSearchResults.svelte +114 -0
  34. chat-ui/src/lib/components/Portal.svelte +19 -0
  35. chat-ui/src/lib/components/ScrollToBottomBtn.svelte +46 -0
  36. chat-ui/src/lib/components/SettingsModal.svelte +124 -0
  37. chat-ui/src/lib/components/StopGeneratingBtn.svelte +13 -0
  38. chat-ui/src/lib/components/Switch.svelte +13 -0
  39. chat-ui/src/lib/components/Toast.svelte +19 -0
  40. chat-ui/src/lib/components/Tooltip.svelte +22 -0
  41. chat-ui/src/lib/components/WebSearchToggle.svelte +26 -0
  42. chat-ui/src/lib/components/chat/ChatInput.svelte +65 -0
  43. chat-ui/src/lib/components/chat/ChatIntroduction.svelte +48 -0
  44. chat-ui/src/lib/components/chat/ChatMessage.svelte +196 -0
  45. chat-ui/src/lib/components/chat/ChatMessages.svelte +71 -0
  46. chat-ui/src/lib/components/chat/ChatWindow.svelte +124 -0
  47. chat-ui/src/lib/components/icons/IconChevron.svelte +20 -0
  48. chat-ui/src/lib/components/icons/IconCopy.svelte +26 -0
  49. chat-ui/src/lib/components/icons/IconDazzled.svelte +36 -0
  50. chat-ui/src/lib/components/icons/IconLoading.svelte +18 -0
.env.local.template CHANGED
@@ -9,9 +9,23 @@ MONGODB_DIRECT_CONNECTION=false
9
  COOKIE_NAME=chat-ui
10
  HF_ACCESS_TOKEN=#hf_<token> from from https://huggingface.co/settings/token
11
 
 
 
 
 
 
 
 
 
12
  # used to activate search with web functionality. disabled if not defined
13
  SERPAPI_KEY=#your serpapi key here
14
  SERPER_API_KEY=${SERPER_API_KEY}
 
 
 
 
 
 
15
 
16
  # Parameters to enable "Sign in with HF"
17
  OPENID_CLIENT_ID=
 
9
  COOKIE_NAME=chat-ui
10
  HF_ACCESS_TOKEN=#hf_<token> from from https://huggingface.co/settings/token
11
 
12
+ # custom parameters
13
+ SIMILARITY_API_URL=${SIMILARITY_API_URL}
14
+ SIMILARITY_THRESHOLD=${SIMILARITY_THRESHOLD}
15
+
16
+ SAIGA_PROMPT_WEB_SEARCH_GENERATE_QUERY=`Представим, что ты специалист по налогам. Перефразируй запрос пользователя({{query}}) так, чтобы это можно было найти в поисковой системе.`
17
+ SAIGA_PROMPT_WEB_SEARCH_ANALYZE=Ответь на запрос "{{query}}". Не повторяй текст запроса. Отвечай подробно. Предположим, что следующий текст содержит правдивую информацию: {{context}}
18
+ SAIGA_TRUNCATE_WEB_CONTEXT=4000
19
+
20
  # used to activate search with web functionality. disabled if not defined
21
  SERPAPI_KEY=#your serpapi key here
22
  SERPER_API_KEY=${SERPER_API_KEY}
23
+ USE_YANDEX_SEARCH=${USE_YANDEX_SEARCH}
24
+ YANDEX_API_KEY=${YANDEX_API_KEY}
25
+ YANDEX_FOLDER_ID=${YANDEX_FOLDER_ID}
26
+ WEB_SEARCH_TEMPLATE=${WEB_SEARCH_TEMPLATE}
27
+ USE_CUSTOM_PARSER=true
28
+ MAX_N_PAGES_SCRAPE=10
29
 
30
  # Parameters to enable "Sign in with HF"
31
  OPENID_CLIENT_ID=
Dockerfile CHANGED
@@ -12,12 +12,12 @@ ARG APP_NAME
12
  WORKDIR /app
13
 
14
  RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
15
- git gettext && \
16
  rm -rf /var/lib/apt/lists/*
17
 
18
 
19
- RUN git clone https://github.com/amatenkov/chat-ui.git
20
-
21
  WORKDIR /app/chat-ui
22
 
23
 
 
12
  WORKDIR /app
13
 
14
  RUN apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y --no-install-recommends \
15
+ gettext && \
16
  rm -rf /var/lib/apt/lists/*
17
 
18
 
19
+ #RUN git clone https://github.com/amatenkov/chat-ui.git
20
+ COPY ./chat-ui ./
21
  WORKDIR /app/chat-ui
22
 
23
 
chat-ui/.dockerignore ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ Dockerfile
2
+ .vscode/
3
+ .idea
4
+ .gitignore
5
+ LICENSE
6
+ README.md
7
+ node_modules/
8
+ .svelte-kit/
chat-ui/.eslintignore ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .DS_Store
2
+ node_modules
3
+ /build
4
+ /.svelte-kit
5
+ /package
6
+ .env
7
+ .env.*
8
+ !.env.example
9
+
10
+ # Ignore files for PNPM, NPM and YARN
11
+ pnpm-lock.yaml
12
+ package-lock.json
13
+ yarn.lock
chat-ui/.eslintrc.cjs ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ module.exports = {
2
+ root: true,
3
+ parser: "@typescript-eslint/parser",
4
+ extends: [
5
+ "eslint:recommended",
6
+ "plugin:@typescript-eslint/recommended",
7
+ "plugin:svelte/recommended",
8
+ "prettier",
9
+ ],
10
+ plugins: ["@typescript-eslint"],
11
+ ignorePatterns: ["*.cjs"],
12
+ overrides: [
13
+ {
14
+ files: ["*.svelte"],
15
+ parser: "svelte-eslint-parser",
16
+ parserOptions: {
17
+ parser: "@typescript-eslint/parser",
18
+ },
19
+ },
20
+ ],
21
+ parserOptions: {
22
+ sourceType: "module",
23
+ ecmaVersion: 2020,
24
+ extraFileExtensions: [".svelte"],
25
+ },
26
+ rules: {
27
+ "no-shadow": ["error"],
28
+ "@typescript-eslint/no-explicit-any": "error",
29
+ "@typescript-eslint/no-non-null-assertion": "error",
30
+ "@typescript-eslint/no-unused-vars": [
31
+ // prevent variables with a _ prefix from being marked as unused
32
+ "error",
33
+ {
34
+ argsIgnorePattern: "^_",
35
+ },
36
+ ],
37
+ },
38
+ env: {
39
+ browser: true,
40
+ es2017: true,
41
+ node: true,
42
+ },
43
+ };
chat-ui/.gitignore ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ .DS_Store
2
+ node_modules
3
+ /build
4
+ /.svelte-kit
5
+ /package
6
+ .env
7
+ .env.*
8
+ !.env.example
9
+ vite.config.js.timestamp-*
10
+ vite.config.ts.timestamp-*
chat-ui/.npmrc ADDED
@@ -0,0 +1 @@
 
 
1
+ engine-strict=true
chat-ui/.prettierignore ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ .DS_Store
2
+ node_modules
3
+ /build
4
+ /.svelte-kit
5
+ /package
6
+ .env
7
+ .env.*
8
+ !.env.example
9
+
10
+ # Ignore files for PNPM, NPM and YARN
11
+ pnpm-lock.yaml
12
+ package-lock.json
13
+ yarn.lock
chat-ui/.prettierrc ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "useTabs": true,
3
+ "trailingComma": "es5",
4
+ "printWidth": 100,
5
+ "plugins": ["prettier-plugin-svelte", "prettier-plugin-tailwindcss"],
6
+ "pluginSearchDirs": ["."],
7
+ "overrides": [{ "files": "*.svelte", "options": { "parser": "svelte" } }]
8
+ }
chat-ui/.vscode/settings.json ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "editor.formatOnSave": true,
3
+ "editor.defaultFormatter": "esbenp.prettier-vscode",
4
+ "editor.codeActionsOnSave": {
5
+ "source.fixAll": true
6
+ },
7
+ "eslint.validate": ["javascript", "svelte"]
8
+ }
chat-ui/LICENSE ADDED
@@ -0,0 +1,203 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright 2018- The Hugging Face team. All rights reserved.
2
+
3
+ Apache License
4
+ Version 2.0, January 2004
5
+ http://www.apache.org/licenses/
6
+
7
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
8
+
9
+ 1. Definitions.
10
+
11
+ "License" shall mean the terms and conditions for use, reproduction,
12
+ and distribution as defined by Sections 1 through 9 of this document.
13
+
14
+ "Licensor" shall mean the copyright owner or entity authorized by
15
+ the copyright owner that is granting the License.
16
+
17
+ "Legal Entity" shall mean the union of the acting entity and all
18
+ other entities that control, are controlled by, or are under common
19
+ control with that entity. For the purposes of this definition,
20
+ "control" means (i) the power, direct or indirect, to cause the
21
+ direction or management of such entity, whether by contract or
22
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
23
+ outstanding shares, or (iii) beneficial ownership of such entity.
24
+
25
+ "You" (or "Your") shall mean an individual or Legal Entity
26
+ exercising permissions granted by this License.
27
+
28
+ "Source" form shall mean the preferred form for making modifications,
29
+ including but not limited to software source code, documentation
30
+ source, and configuration files.
31
+
32
+ "Object" form shall mean any form resulting from mechanical
33
+ transformation or translation of a Source form, including but
34
+ not limited to compiled object code, generated documentation,
35
+ and conversions to other media types.
36
+
37
+ "Work" shall mean the work of authorship, whether in Source or
38
+ Object form, made available under the License, as indicated by a
39
+ copyright notice that is included in or attached to the work
40
+ (an example is provided in the Appendix below).
41
+
42
+ "Derivative Works" shall mean any work, whether in Source or Object
43
+ form, that is based on (or derived from) the Work and for which the
44
+ editorial revisions, annotations, elaborations, or other modifications
45
+ represent, as a whole, an original work of authorship. For the purposes
46
+ of this License, Derivative Works shall not include works that remain
47
+ separable from, or merely link (or bind by name) to the interfaces of,
48
+ the Work and Derivative Works thereof.
49
+
50
+ "Contribution" shall mean any work of authorship, including
51
+ the original version of the Work and any modifications or additions
52
+ to that Work or Derivative Works thereof, that is intentionally
53
+ submitted to Licensor for inclusion in the Work by the copyright owner
54
+ or by an individual or Legal Entity authorized to submit on behalf of
55
+ the copyright owner. For the purposes of this definition, "submitted"
56
+ means any form of electronic, verbal, or written communication sent
57
+ to the Licensor or its representatives, including but not limited to
58
+ communication on electronic mailing lists, source code control systems,
59
+ and issue tracking systems that are managed by, or on behalf of, the
60
+ Licensor for the purpose of discussing and improving the Work, but
61
+ excluding communication that is conspicuously marked or otherwise
62
+ designated in writing by the copyright owner as "Not a Contribution."
63
+
64
+ "Contributor" shall mean Licensor and any individual or Legal Entity
65
+ on behalf of whom a Contribution has been received by Licensor and
66
+ subsequently incorporated within the Work.
67
+
68
+ 2. Grant of Copyright License. Subject to the terms and conditions of
69
+ this License, each Contributor hereby grants to You a perpetual,
70
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
71
+ copyright license to reproduce, prepare Derivative Works of,
72
+ publicly display, publicly perform, sublicense, and distribute the
73
+ Work and such Derivative Works in Source or Object form.
74
+
75
+ 3. Grant of Patent License. Subject to the terms and conditions of
76
+ this License, each Contributor hereby grants to You a perpetual,
77
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
78
+ (except as stated in this section) patent license to make, have made,
79
+ use, offer to sell, sell, import, and otherwise transfer the Work,
80
+ where such license applies only to those patent claims licensable
81
+ by such Contributor that are necessarily infringed by their
82
+ Contribution(s) alone or by combination of their Contribution(s)
83
+ with the Work to which such Contribution(s) was submitted. If You
84
+ institute patent litigation against any entity (including a
85
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
86
+ or a Contribution incorporated within the Work constitutes direct
87
+ or contributory patent infringement, then any patent licenses
88
+ granted to You under this License for that Work shall terminate
89
+ as of the date such litigation is filed.
90
+
91
+ 4. Redistribution. You may reproduce and distribute copies of the
92
+ Work or Derivative Works thereof in any medium, with or without
93
+ modifications, and in Source or Object form, provided that You
94
+ meet the following conditions:
95
+
96
+ (a) You must give any other recipients of the Work or
97
+ Derivative Works a copy of this License; and
98
+
99
+ (b) You must cause any modified files to carry prominent notices
100
+ stating that You changed the files; and
101
+
102
+ (c) You must retain, in the Source form of any Derivative Works
103
+ that You distribute, all copyright, patent, trademark, and
104
+ attribution notices from the Source form of the Work,
105
+ excluding those notices that do not pertain to any part of
106
+ the Derivative Works; and
107
+
108
+ (d) If the Work includes a "NOTICE" text file as part of its
109
+ distribution, then any Derivative Works that You distribute must
110
+ include a readable copy of the attribution notices contained
111
+ within such NOTICE file, excluding those notices that do not
112
+ pertain to any part of the Derivative Works, in at least one
113
+ of the following places: within a NOTICE text file distributed
114
+ as part of the Derivative Works; within the Source form or
115
+ documentation, if provided along with the Derivative Works; or,
116
+ within a display generated by the Derivative Works, if and
117
+ wherever such third-party notices normally appear. The contents
118
+ of the NOTICE file are for informational purposes only and
119
+ do not modify the License. You may add Your own attribution
120
+ notices within Derivative Works that You distribute, alongside
121
+ or as an addendum to the NOTICE text from the Work, provided
122
+ that such additional attribution notices cannot be construed
123
+ as modifying the License.
124
+
125
+ You may add Your own copyright statement to Your modifications and
126
+ may provide additional or different license terms and conditions
127
+ for use, reproduction, or distribution of Your modifications, or
128
+ for any such Derivative Works as a whole, provided Your use,
129
+ reproduction, and distribution of the Work otherwise complies with
130
+ the conditions stated in this License.
131
+
132
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
133
+ any Contribution intentionally submitted for inclusion in the Work
134
+ by You to the Licensor shall be under the terms and conditions of
135
+ this License, without any additional terms or conditions.
136
+ Notwithstanding the above, nothing herein shall supersede or modify
137
+ the terms of any separate license agreement you may have executed
138
+ with Licensor regarding such Contributions.
139
+
140
+ 6. Trademarks. This License does not grant permission to use the trade
141
+ names, trademarks, service marks, or product names of the Licensor,
142
+ except as required for reasonable and customary use in describing the
143
+ origin of the Work and reproducing the content of the NOTICE file.
144
+
145
+ 7. Disclaimer of Warranty. Unless required by applicable law or
146
+ agreed to in writing, Licensor provides the Work (and each
147
+ Contributor provides its Contributions) on an "AS IS" BASIS,
148
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
149
+ implied, including, without limitation, any warranties or conditions
150
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
151
+ PARTICULAR PURPOSE. You are solely responsible for determining the
152
+ appropriateness of using or redistributing the Work and assume any
153
+ risks associated with Your exercise of permissions under this License.
154
+
155
+ 8. Limitation of Liability. In no event and under no legal theory,
156
+ whether in tort (including negligence), contract, or otherwise,
157
+ unless required by applicable law (such as deliberate and grossly
158
+ negligent acts) or agreed to in writing, shall any Contributor be
159
+ liable to You for damages, including any direct, indirect, special,
160
+ incidental, or consequential damages of any character arising as a
161
+ result of this License or out of the use or inability to use the
162
+ Work (including but not limited to damages for loss of goodwill,
163
+ work stoppage, computer failure or malfunction, or any and all
164
+ other commercial damages or losses), even if such Contributor
165
+ has been advised of the possibility of such damages.
166
+
167
+ 9. Accepting Warranty or Additional Liability. While redistributing
168
+ the Work or Derivative Works thereof, You may choose to offer,
169
+ and charge a fee for, acceptance of support, warranty, indemnity,
170
+ or other liability obligations and/or rights consistent with this
171
+ License. However, in accepting such obligations, You may act only
172
+ on Your own behalf and on Your sole responsibility, not on behalf
173
+ of any other Contributor, and only if You agree to indemnify,
174
+ defend, and hold each Contributor harmless for any liability
175
+ incurred by, or claims asserted against, such Contributor by reason
176
+ of your accepting any such warranty or additional liability.
177
+
178
+ END OF TERMS AND CONDITIONS
179
+
180
+ APPENDIX: How to apply the Apache License to your work.
181
+
182
+ To apply the Apache License to your work, attach the following
183
+ boilerplate notice, with the fields enclosed by brackets "[]"
184
+ replaced with your own identifying information. (Don't include
185
+ the brackets!) The text should be enclosed in the appropriate
186
+ comment syntax for the file format. We also recommend that a
187
+ file or class name and description of purpose be included on the
188
+ same "printed page" as the copyright notice for easier
189
+ identification within third-party archives.
190
+
191
+ Copyright [yyyy] [name of copyright owner]
192
+
193
+ Licensed under the Apache License, Version 2.0 (the "License");
194
+ you may not use this file except in compliance with the License.
195
+ You may obtain a copy of the License at
196
+
197
+ http://www.apache.org/licenses/LICENSE-2.0
198
+
199
+ Unless required by applicable law or agreed to in writing, software
200
+ distributed under the License is distributed on an "AS IS" BASIS,
201
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
202
+ See the License for the specific language governing permissions and
203
+ limitations under the License.
chat-ui/PRIVACY.md ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Privacy
2
+
3
+ > Last updated: July 23, 2023
4
+
5
+ Users of HuggingChat are authenticated through their HF user account.
6
+
7
+ By default, your conversations may be shared with the respective models' authors (e.g. if you're chatting with the Open Assistant model, to <a target="_blank" href="https://open-assistant.io/dashboard">Open Assistant</a>) to improve their training data and model over time. Model authors are the custodians of the data collected by their model, even if it's hosted on our platform.
8
+
9
+ If you disable data sharing in your settings, your conversations will not be used for any downstream usage (including for research or model training purposes), and they will only be stored to let you access past conversations. You can click on the Delete icon to delete any past conversation at any moment.
10
+
11
+ 🗓 Please also consult huggingface.co's main privacy policy at https://huggingface.co/privacy. To exercise any of your legal privacy rights, please send an email to privacy@huggingface.co.
12
+
13
+ ## About available LLMs
14
+
15
+ The goal of this app is to showcase that it is now (May 2023) possible to build an open source alternative to ChatGPT. 💪
16
+
17
+ For now, it's running both OpenAssistant's [latest LLaMA based model](https://huggingface.co/OpenAssistant/oasst-sft-6-llama-30b-xor) (which is one of the current best open source chat models) as well as [Meta's newer Llama 2](https://huggingface.co/meta-llama/Llama-2-70b-chat-hf), but the plan in the longer-term is to expose all good-quality chat models from the Hub.
18
+
19
+ We are not affiliated with Open Assistant nor Meta AI, but if you want to contribute to the training data for the next generation of open models, please consider contributing to https://open-assistant.io/ or https://ai.meta.com/llama/ ❤️
20
+
21
+ ## Technical details
22
+
23
+ This app is running in a [Space](https://huggingface.co/docs/hub/spaces-overview), which entails that the code for this UI is publicly visible [inside the Space repo](https://huggingface.co/spaces/huggingchat/chat-ui/tree/main).
24
+
25
+ **Further development takes place on the [huggingface/chat-ui GitHub repo](https://github.com/huggingface/chat-ui).**
26
+
27
+ The inference backend is running the optimized [text-generation-inference](https://github.com/huggingface/text-generation-inference) on HuggingFace's Inference API infrastructure.
28
+
29
+ It is therefore possible to deploy a copy of this app to a Space and customize it (swap model, add some UI elements, or store user messages according to your own Terms and conditions). You can also 1-click deploy your own instance using the [Chat UI Spaces Docker template](https://huggingface.co/new-space?template=huggingchat/chat-ui-template).
30
+
31
+ We welcome any feedback on this app: please participate to the public discussion at https://huggingface.co/spaces/huggingchat/chat-ui/discussions
32
+
33
+ <a target="_blank" href="https://huggingface.co/spaces/huggingchat/chat-ui/discussions"><img src="https://huggingface.co/datasets/huggingface/badges/raw/main/open-a-discussion-xl.svg" title="open a discussion"></a>
34
+
35
+ ## Coming soon
36
+
37
+ - User setting to share conversations with model authors (done ✅)
38
+ - LLM watermarking
chat-ui/README.md ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: chat-ui
3
+ emoji: 🔥
4
+ colorFrom: purple
5
+ colorTo: purple
6
+ sdk: docker
7
+ pinned: false
8
+ license: apache-2.0
9
+ base_path: /chat
10
+ app_port: 3000
11
+ ---
12
+
13
+ # Chat UI
14
+
15
+ ![Chat UI repository thumbnail](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/chatui-websearch.png)
16
+
17
+ A chat interface using open source models, eg OpenAssistant or Llama. It is a SvelteKit app and it powers the [HuggingChat app on hf.co/chat](https://huggingface.co/chat).
18
+
19
+ 0. [No Setup Deploy](#no-setup-deploy)
20
+ 1. [Setup](#setup)
21
+ 2. [Launch](#launch)
22
+ 3. [Web Search](#web-search)
23
+ 4. [Extra parameters](#extra-parameters)
24
+ 5. [Deploying to a HF Space](#deploying-to-a-hf-space)
25
+ 6. [Building](#building)
26
+
27
+ ##  No Setup Deploy
28
+
29
+ If you don't want to configure, setup, and launch your own Chat UI yourself, you can use this option as a fast deploy alternative.
30
+
31
+ You can deploy your own customized Chat UI instance with any supported LLM of your choice with only a few clicks to Hugging Face Spaces thanks to the Chat UI Spaces Docker template. Get started [here](https://huggingface.co/new-space?template=huggingchat/chat-ui-template).
32
+ If you'd like to deploy a model with gated access or a model in a private repository, you can simply provide `HUGGING_FACE_HUB_TOKEN` in [Space secrets](https://huggingface.co/docs/hub/spaces-overview#managing-secrets-and-environment-variables). You need to set its value to an access token you can get from [here](https://huggingface.co/settings/tokens).
33
+
34
+ Read the full tutorial [here](https://huggingface.co/docs/hub/spaces-sdks-docker-chatui#chatui-on-spaces).
35
+
36
+ ## Setup
37
+
38
+ The default config for Chat UI is stored in the `.env` file. You will need to override some values to get Chat UI to run locally. This is done in `.env.local`.
39
+
40
+ Start by creating a `.env.local` file in the root of the repository. The bare minimum config you need to get Chat UI to run locally is the following:
41
+
42
+ ```bash
43
+ MONGODB_URL=<the URL to your mongoDB instance>
44
+ HF_ACCESS_TOKEN=<your access token>
45
+ ```
46
+
47
+ ### Database
48
+
49
+ The chat history is stored in a MongoDB instance, and having a DB instance available is needed for Chat UI to work.
50
+
51
+ You can use a local MongoDB instance. The easiest way is to spin one up using docker:
52
+
53
+ ```bash
54
+ docker run -d -p 27017:27017 --name mongo-chatui mongo:latest
55
+ ```
56
+
57
+ In which case the url of your DB will be `MONGODB_URL=mongodb://localhost:27017`.
58
+
59
+ Alternatively, you can use a [free MongoDB Atlas](https://www.mongodb.com/pricing) instance for this, Chat UI should fit comfortably within their free tier. After which you can set the `MONGODB_URL` variable in `.env.local` to match your instance.
60
+
61
+ ### Hugging Face Access Token
62
+
63
+ You will need a Hugging Face access token to run Chat UI locally, if you use a remote inference endpoint. You can get one from [your Hugging Face profile](https://huggingface.co/settings/tokens).
64
+
65
+ ## Launch
66
+
67
+ After you're done with the `.env.local` file you can run Chat UI locally with:
68
+
69
+ ```bash
70
+ npm install
71
+ npm run dev
72
+ ```
73
+
74
+ ## Web Search
75
+
76
+ Chat UI features a powerful Web Search feature. It works by:
77
+
78
+ 1. Generating an appropriate Google query from the user prompt.
79
+ 2. Performing Google search and extracting content from webpages.
80
+ 3. Creating embeddings from texts using [transformers.js](https://huggingface.co/docs/transformers.js). Specifically, using [Xenova/gte-small](https://huggingface.co/Xenova/gte-small) model.
81
+ 4. From these embeddings, find the ones that are closest to the user query using vector similarity search. Specifically, we use `inner product` distance.
82
+ 5. Get the corresponding texts to those closest embeddings and perform [Retrieval-Augmented Generation](https://huggingface.co/papers/2005.11401) (i.e. expand user prompt by adding those texts so that a LLM can use this information).
83
+
84
+ ## Extra parameters
85
+
86
+ ### OpenID connect
87
+
88
+ The login feature is disabled by default and users are attributed a unique ID based on their browser. But if you want to use OpenID to authenticate your users, you can add the following to your `.env.local` file:
89
+
90
+ ```bash
91
+ OPENID_PROVIDER_URL=<your OIDC issuer>
92
+ OPENID_CLIENT_ID=<your OIDC client ID>
93
+ OPENID_CLIENT_SECRET=<your OIDC client secret>
94
+ ```
95
+
96
+ These variables will enable the openID sign-in modal for users.
97
+
98
+ ### Theming
99
+
100
+ You can use a few environment variables to customize the look and feel of chat-ui. These are by default:
101
+
102
+ ```
103
+ PUBLIC_APP_NAME=ChatUI
104
+ PUBLIC_APP_ASSETS=chatui
105
+ PUBLIC_APP_COLOR=blue
106
+ PUBLIC_APP_DATA_SHARING=
107
+ PUBLIC_APP_DISCLAIMER=
108
+ ```
109
+
110
+ - `PUBLIC_APP_NAME` The name used as a title throughout the app.
111
+ - `PUBLIC_APP_ASSETS` Is used to find logos & favicons in `static/$PUBLIC_APP_ASSETS`, current options are `chatui` and `huggingchat`.
112
+ - `PUBLIC_APP_COLOR` Can be any of the [tailwind colors](https://tailwindcss.com/docs/customizing-colors#default-color-palette).
113
+ - `PUBLIC_APP_DATA_SHARING` Can be set to 1 to add a toggle in the user settings that lets your users opt-in to data sharing with models creator.
114
+ - `PUBLIC_APP_DISCLAIMER` If set to 1, we show a disclaimer about generated outputs on login.
115
+
116
+ ### Web Search
117
+
118
+ You can enable the web search by adding either `SERPER_API_KEY` ([serper.dev](https://serper.dev/)) or `SERPAPI_KEY` ([serpapi.com](https://serpapi.com/)) to your `.env.local`.
119
+
120
+ ### Custom models
121
+
122
+ You can customize the parameters passed to the model or even use a new model by updating the `MODELS` variable in your `.env.local`. The default one can be found in `.env` and looks like this :
123
+
124
+ ```
125
+
126
+ MODELS=`[
127
+ {
128
+ "name": "OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5",
129
+ "datasetName": "OpenAssistant/oasst1",
130
+ "description": "A good alternative to ChatGPT",
131
+ "websiteUrl": "https://open-assistant.io",
132
+ "userMessageToken": "<|prompter|>", # This does not need to be a token, can be any string
133
+ "assistantMessageToken": "<|assistant|>", # This does not need to be a token, can be any string
134
+ "userMessageEndToken": "<|endoftext|>", # Applies only to user messages. Can be any string.
135
+ "assistantMessageEndToken": "<|endoftext|>", # Applies only to assistant messages. Can be any string.
136
+ "preprompt": "Below are a series of dialogues between various people and an AI assistant. The AI tries to be helpful, polite, honest, sophisticated, emotionally aware, and humble-but-knowledgeable. The assistant is happy to help with almost anything, and will do its best to understand exactly what is needed. It also tries to avoid giving false or misleading information, and it caveats when it isn't entirely sure about the right answer. That said, the assistant is practical and really does its best, and doesn't let caution get too much in the way of being useful.\n-----\n",
137
+ "promptExamples": [
138
+ {
139
+ "title": "Write an email from bullet list",
140
+ "prompt": "As a restaurant owner, write a professional email to the supplier to get these products every week: \n\n- Wine (x10)\n- Eggs (x24)\n- Bread (x12)"
141
+ }, {
142
+ "title": "Code a snake game",
143
+ "prompt": "Code a basic snake game in python, give explanations for each step."
144
+ }, {
145
+ "title": "Assist in a task",
146
+ "prompt": "How do I make a delicious lemon cheesecake?"
147
+ }
148
+ ],
149
+ "parameters": {
150
+ "temperature": 0.9,
151
+ "top_p": 0.95,
152
+ "repetition_penalty": 1.2,
153
+ "top_k": 50,
154
+ "truncate": 1000,
155
+ "max_new_tokens": 1024,
156
+ "stop": ["<|endoftext|>"] # This does not need to be tokens, can be any list of strings
157
+ }
158
+ }
159
+ ]`
160
+
161
+ ```
162
+
163
+ You can change things like the parameters, or customize the preprompt to better suit your needs. You can also add more models by adding more objects to the array, with different preprompts for example.
164
+
165
+ #### Custom prompt templates:
166
+
167
+ By default the prompt is constructed using `userMessageToken`, `assistantMessageToken`, `userMessageEndToken`, `assistantMessageEndToken`, `preprompt` parameters and a series of default templates.
168
+
169
+ However, these templates can be modified by setting the `chatPromptTemplate` and `webSearchQueryPromptTemplate` parameters. Note that if WebSearch is not enabled, only `chatPromptTemplate` needs to be set. The template language is https://handlebarsjs.com. The templates have access to the model's prompt parameters (`preprompt`, etc.). However, if the templates are specified it is recommended to inline the prompt parameters, as using the references (`{{preprompt}}`) is deprecated.
170
+
171
+ For example:
172
+
173
+ ```
174
+ <System>You are an AI, called ChatAI.</System>
175
+ {{#each messages}}
176
+ {{#ifUser}}<User>{{content}}</User>{{/ifUser}}
177
+ {{#ifAssistant}}<Assistant>{{content}}</Assistant>{{/ifAssistant}}
178
+ {{/each}}
179
+ <Assistant>
180
+ ```
181
+
182
+ **chatPromptTemplate**
183
+
184
+ When quering the model for a chat response, the `chatPromptTemplate` template is used. `messages` is an array of chat messages, it has the format `[{ content: string }, ...]`. To idenify if a message is a user message or an assistant message the `ifUser` and `ifAssistant` block helpers can be used.
185
+
186
+ The following is the default `chatPromptTemplate`, although newlines and indentiation have been added for readability.
187
+
188
+ ```
189
+ {{preprompt}}
190
+ {{#each messages}}
191
+ {{#ifUser}}{{@root.userMessageToken}}{{content}}{{@root.userMessageEndToken}}{{/ifUser}}
192
+ {{#ifAssistant}}{{@root.assistantMessageToken}}{{content}}{{@root.assistantMessageEndToken}}{{/ifAssistant}}
193
+ {{/each}}
194
+ {{assistantMessageToken}}
195
+ ```
196
+
197
+ **webSearchQueryPromptTemplate**
198
+
199
+ When performing a websearch, the search query is constructed using the `webSearchQueryPromptTemplate` template. It is recommended that that the prompt instructs the chat model to only return a few keywords.
200
+
201
+ The following is the default `webSearchQueryPromptTemplate`.
202
+
203
+ ```
204
+ {{userMessageToken}}
205
+ My question is: {{message.content}}.
206
+ Based on the conversation history (my previous questions are: {{previousMessages}}), give me an appropriate query to answer my question for google search. You should not say more than query. You should not say any words except the query. For the context, today is {{currentDate}}
207
+ {{userMessageEndToken}}
208
+ {{assistantMessageToken}}
209
+ ```
210
+
211
+ #### Running your own models using a custom endpoint
212
+
213
+ If you want to, instead of hitting models on the Hugging Face Inference API, you can run your own models locally.
214
+
215
+ A good option is to hit a [text-generation-inference](https://github.com/huggingface/text-generation-inference) endpoint. This is what is done in the official [Chat UI Spaces Docker template](https://huggingface.co/new-space?template=huggingchat/chat-ui-template) for instance: both this app and a text-generation-inference server run inside the same container.
216
+
217
+ To do this, you can add your own endpoints to the `MODELS` variable in `.env.local`, by adding an `"endpoints"` key for each model in `MODELS`.
218
+
219
+ ```
220
+
221
+ {
222
+ // rest of the model config here
223
+ "endpoints": [{"url": "https://HOST:PORT"}]
224
+ }
225
+
226
+ ```
227
+
228
+ If `endpoints` is left unspecified, ChatUI will look for the model on the hosted Hugging Face inference API using the model name.
229
+
230
+ ### Custom endpoint authorization
231
+
232
+ #### Basic and Bearer
233
+
234
+ Custom endpoints may require authorization, depending on how you configure them. Authentication will usually be set either with `Basic` or `Bearer`.
235
+
236
+ For `Basic` we will need to generate a base64 encoding of the username and password.
237
+
238
+ `echo -n "USER:PASS" | base64`
239
+
240
+ > VVNFUjpQQVNT
241
+
242
+ For `Bearer` you can use a token, which can be grabbed from [here](https://huggingface.co/settings/tokens).
243
+
244
+ You can then add the generated information and the `authorization` parameter to your `.env.local`.
245
+
246
+ ```
247
+
248
+ "endpoints": [
249
+ {
250
+ "url": "https://HOST:PORT",
251
+ "authorization": "Basic VVNFUjpQQVNT",
252
+ }
253
+ ]
254
+
255
+ ```
256
+
257
+ ### Amazon SageMaker
258
+
259
+ You can also specify your Amazon SageMaker instance as an endpoint for chat-ui. The config goes like this:
260
+
261
+ ```
262
+ "endpoints": [
263
+ {
264
+ "host" : "sagemaker",
265
+ "url": "", // your aws sagemaker url here
266
+ "accessKey": "",
267
+ "secretKey" : "",
268
+ "sessionToken": "", // optional
269
+ "weight": 1
270
+ }
271
+ ```
272
+
273
+ You can get the `accessKey` and `secretKey` from your AWS user, under programmatic access.
274
+
275
+ #### Client Certificate Authentication (mTLS)
276
+
277
+ Custom endpoints may require client certificate authentication, depending on how you configure them. To enable mTLS between Chat UI and your custom endpoint, you will need to set the `USE_CLIENT_CERTIFICATE` to `true`, and add the `CERT_PATH` and `KEY_PATH` parameters to your `.env.local`. These parameters should point to the location of the certificate and key files on your local machine. The certificate and key files should be in PEM format. The key file can be encrypted with a passphrase, in which case you will also need to add the `CLIENT_KEY_PASSWORD` parameter to your `.env.local`.
278
+
279
+ If you're using a certificate signed by a private CA, you will also need to add the `CA_PATH` parameter to your `.env.local`. This parameter should point to the location of the CA certificate file on your local machine.
280
+
281
+ If you're using a self-signed certificate, e.g. for testing or development purposes, you can set the `REJECT_UNAUTHORIZED` parameter to `false` in your `.env.local`. This will disable certificate validation, and allow Chat UI to connect to your custom endpoint.
282
+
283
+ #### Models hosted on multiple custom endpoints
284
+
285
+ If the model being hosted will be available on multiple servers/instances add the `weight` parameter to your `.env.local`. The `weight` will be used to determine the probability of requesting a particular endpoint.
286
+
287
+ ```
288
+
289
+ "endpoints": [
290
+ {
291
+ "url": "https://HOST:PORT",
292
+ "weight": 1
293
+ }
294
+ {
295
+ "url": "https://HOST:PORT",
296
+ "weight": 2
297
+ }
298
+ ...
299
+ ]
300
+
301
+ ```
302
+
303
+ ## Deploying to a HF Space
304
+
305
+ Create a `DOTENV_LOCAL` secret to your HF space with the content of your .env.local, and they will be picked up automatically when you run.
306
+
307
+ ## Building
308
+
309
+ To create a production version of your app:
310
+
311
+ ```bash
312
+ npm run build
313
+ ```
314
+
315
+ You can preview the production build with `npm run preview`.
316
+
317
+ > To deploy your app, you may need to install an [adapter](https://kit.svelte.dev/docs/adapters) for your target environment.
chat-ui/package-lock.json ADDED
The diff for this file is too large to render. See raw diff
 
chat-ui/package.json ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "chat-ui",
3
+ "version": "0.6.0",
4
+ "private": true,
5
+ "packageManager": "npm@9.5.0",
6
+ "scripts": {
7
+ "dev": "vite dev",
8
+ "build": "vite build",
9
+ "preview": "vite preview",
10
+ "check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
11
+ "check:watch": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json --watch",
12
+ "lint": "prettier --plugin-search-dir . --check . && eslint .",
13
+ "format": "prettier --plugin-search-dir . --write .",
14
+ "test": "MONGODB_URL=mongodb://127.0.0.1:27017/ vitest"
15
+ },
16
+ "devDependencies": {
17
+ "@iconify-json/carbon": "^1.1.16",
18
+ "@iconify-json/eos-icons": "^1.1.6",
19
+ "@sveltejs/adapter-node": "^1.2.4",
20
+ "@sveltejs/kit": "^1.15.10",
21
+ "@tailwindcss/typography": "^0.5.9",
22
+ "@types/jsdom": "^21.1.1",
23
+ "@types/marked": "^4.0.8",
24
+ "@types/parquetjs": "^0.10.3",
25
+ "@types/xml2js": "^0.4.12",
26
+ "@typescript-eslint/eslint-plugin": "^5.45.0",
27
+ "@typescript-eslint/parser": "^5.45.0",
28
+ "eslint": "^8.28.0",
29
+ "eslint-config-prettier": "^8.5.0",
30
+ "eslint-plugin-svelte": "^2.27.3",
31
+ "marked-katex-extension": "^3.0.6",
32
+ "prettier": "^2.8.0",
33
+ "prettier-plugin-svelte": "^2.8.1",
34
+ "prettier-plugin-tailwindcss": "^0.2.7",
35
+ "svelte": "^3.58.0",
36
+ "svelte-check": "^3.2.0",
37
+ "tslib": "^2.4.1",
38
+ "typescript": "^4.9.3",
39
+ "unplugin-icons": "^0.16.1",
40
+ "vite": "^4.3.9",
41
+ "vitest": "^0.31.0"
42
+ },
43
+ "type": "module",
44
+ "dependencies": {
45
+ "@huggingface/hub": "^0.5.1",
46
+ "@huggingface/inference": "^2.2.0",
47
+ "@xenova/transformers": "^2.6.0",
48
+ "autoprefixer": "^10.4.14",
49
+ "aws4fetch": "^1.0.17",
50
+ "date-fns": "^2.29.3",
51
+ "dotenv": "^16.0.3",
52
+ "handlebars": "^4.7.8",
53
+ "highlight.js": "^11.7.0",
54
+ "jsdom": "^22.0.0",
55
+ "marked": "^4.3.0",
56
+ "mongodb": "^5.8.0",
57
+ "nanoid": "^4.0.2",
58
+ "openid-client": "^5.4.2",
59
+ "parquetjs": "^0.11.2",
60
+ "postcss": "^8.4.21",
61
+ "serpapi": "^1.1.1",
62
+ "tailwind-scrollbar": "^3.0.0",
63
+ "tailwindcss": "^3.3.1",
64
+ "transformers": "^3.1.0",
65
+ "xml2js": "^0.6.2",
66
+ "zod": "^3.21.4"
67
+ }
68
+ }
chat-ui/postcss.config.js ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ export default {
2
+ plugins: {
3
+ tailwindcss: {},
4
+ autoprefixer: {},
5
+ },
6
+ };
chat-ui/src/app.d.ts ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /// <reference types="@sveltejs/kit" />
2
+ /// <reference types="unplugin-icons/types/svelte" />
3
+
4
+ import type { User } from "$lib/types/User";
5
+
6
+ // See https://kit.svelte.dev/docs/types#app
7
+ // for information about these interfaces
8
+ declare global {
9
+ namespace App {
10
+ // interface Error {}
11
+ interface Locals {
12
+ sessionId: string;
13
+ user?: User;
14
+ }
15
+ // interface PageData {}
16
+ // interface Platform {}
17
+ }
18
+ }
19
+
20
+ export {};
chat-ui/src/app.html ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en" class="h-full">
3
+ <head>
4
+ <meta charset="utf-8" />
5
+ <meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
6
+ <script>
7
+ if (
8
+ localStorage.theme === "dark" ||
9
+ (!("theme" in localStorage) && window.matchMedia("(prefers-color-scheme: dark)").matches)
10
+ ) {
11
+ document.documentElement.classList.add("dark");
12
+ }
13
+
14
+ // For some reason, Sveltekit doesn't let us load env variables from .env here, so we load it from hooks.server.ts
15
+ window.gaId = "%gaId%";
16
+ window.gaIdDeprecated = "%gaIdDeprecated%";
17
+ </script>
18
+ %sveltekit.head%
19
+ </head>
20
+ <body data-sveltekit-preload-data="hover" class="h-full dark:bg-gray-900">
21
+ <div id="app" class="contents h-full">%sveltekit.body%</div>
22
+ </body>
23
+ </html>
chat-ui/src/hooks.server.ts ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { COOKIE_NAME, MESSAGES_BEFORE_LOGIN } from "$env/static/private";
2
+ import type { Handle } from "@sveltejs/kit";
3
+ import {
4
+ PUBLIC_GOOGLE_ANALYTICS_ID,
5
+ PUBLIC_DEPRECATED_GOOGLE_ANALYTICS_ID,
6
+ PUBLIC_ORIGIN,
7
+ PUBLIC_APP_DISCLAIMER,
8
+ } from "$env/static/public";
9
+ import { collections } from "$lib/server/database";
10
+ import { base } from "$app/paths";
11
+ import { refreshSessionCookie, requiresUser } from "$lib/server/auth";
12
+ import { ERROR_MESSAGES } from "$lib/stores/errors";
13
+
14
+ export const handle: Handle = async ({ event, resolve }) => {
15
+ const token = event.cookies.get(COOKIE_NAME);
16
+
17
+ event.locals.sessionId = token || crypto.randomUUID();
18
+
19
+ const user = await collections.users.findOne({ sessionId: event.locals.sessionId });
20
+
21
+ if (user) {
22
+ event.locals.user = user;
23
+ }
24
+
25
+ function errorResponse(status: number, message: string) {
26
+ const sendJson =
27
+ event.request.headers.get("accept")?.includes("application/json") ||
28
+ event.request.headers.get("content-type")?.includes("application/json");
29
+ return new Response(sendJson ? JSON.stringify({ error: message }) : message, {
30
+ status,
31
+ headers: {
32
+ "content-type": sendJson ? "application/json" : "text/plain",
33
+ },
34
+ });
35
+ }
36
+
37
+ // CSRF protection
38
+ const requestContentType = event.request.headers.get("content-type")?.split(";")[0] ?? "";
39
+ /** https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form#attr-enctype */
40
+ const nativeFormContentTypes = [
41
+ "multipart/form-data",
42
+ "application/x-www-form-urlencoded",
43
+ "text/plain",
44
+ ];
45
+ if (event.request.method === "POST" && nativeFormContentTypes.includes(requestContentType)) {
46
+ const referer = event.request.headers.get("referer");
47
+
48
+ if (!referer) {
49
+ return errorResponse(403, "Non-JSON form requests need to have a referer");
50
+ }
51
+
52
+ const validOrigins = [
53
+ new URL(event.request.url).origin,
54
+ ...(PUBLIC_ORIGIN ? [new URL(PUBLIC_ORIGIN).origin] : []),
55
+ ];
56
+
57
+ if (!validOrigins.includes(new URL(referer).origin)) {
58
+ return errorResponse(403, "Invalid referer for POST request");
59
+ }
60
+ }
61
+
62
+ if (
63
+ !event.url.pathname.startsWith(`${base}/login`) &&
64
+ !event.url.pathname.startsWith(`${base}/admin`) &&
65
+ !["GET", "OPTIONS", "HEAD"].includes(event.request.method)
66
+ ) {
67
+ if (
68
+ !user &&
69
+ requiresUser &&
70
+ !((MESSAGES_BEFORE_LOGIN ? parseInt(MESSAGES_BEFORE_LOGIN) : 0) > 0)
71
+ ) {
72
+ return errorResponse(401, ERROR_MESSAGES.authOnly);
73
+ }
74
+
75
+ // if login is not required and the call is not from /settings and we display the ethics modal with PUBLIC_APP_DISCLAIMER
76
+ // we check if the user has accepted the ethics modal first.
77
+ // If login is required, `ethicsModalAcceptedAt` is already true at this point, so do not pass this condition. This saves a DB call.
78
+ if (
79
+ !requiresUser &&
80
+ !event.url.pathname.startsWith(`${base}/settings`) &&
81
+ !!PUBLIC_APP_DISCLAIMER
82
+ ) {
83
+ const hasAcceptedEthicsModal = await collections.settings.countDocuments({
84
+ sessionId: event.locals.sessionId,
85
+ ethicsModalAcceptedAt: { $exists: true },
86
+ });
87
+
88
+ if (!hasAcceptedEthicsModal) {
89
+ return errorResponse(405, "You need to accept the welcome modal first");
90
+ }
91
+ }
92
+ }
93
+
94
+ refreshSessionCookie(event.cookies, event.locals.sessionId);
95
+
96
+ let replaced = false;
97
+
98
+ const response = await resolve(event, {
99
+ transformPageChunk: (chunk) => {
100
+ // For some reason, Sveltekit doesn't let us load env variables from .env in the app.html template
101
+ if (replaced || !chunk.html.includes("%gaId%") || !chunk.html.includes("%gaIdDeprecated%")) {
102
+ return chunk.html;
103
+ }
104
+ replaced = true;
105
+
106
+ return chunk.html
107
+ .replace("%gaId%", PUBLIC_GOOGLE_ANALYTICS_ID)
108
+ .replace("%gaIdDeprecated%", PUBLIC_DEPRECATED_GOOGLE_ANALYTICS_ID);
109
+ },
110
+ });
111
+
112
+ return response;
113
+ };
chat-ui/src/lib/actions/snapScrollToBottom.ts ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { navigating } from "$app/stores";
2
+ import { tick } from "svelte";
3
+ import { get } from "svelte/store";
4
+
5
+ const detachedOffset = 10;
6
+
7
+ /**
8
+ * @param node element to snap scroll to bottom
9
+ * @param dependency pass in a dependency to update scroll on changes.
10
+ */
11
+ export const snapScrollToBottom = (node: HTMLElement, dependency: unknown) => {
12
+ let prevScrollValue = node.scrollTop;
13
+ let isDetached = false;
14
+
15
+ const handleScroll = () => {
16
+ // if user scrolled up, we detach
17
+ if (node.scrollTop < prevScrollValue) {
18
+ isDetached = true;
19
+ }
20
+
21
+ // if user scrolled back to within 10px of bottom, we reattach
22
+ if (node.scrollTop - (node.scrollHeight - node.clientHeight) >= -detachedOffset) {
23
+ isDetached = false;
24
+ }
25
+
26
+ prevScrollValue = node.scrollTop;
27
+ };
28
+
29
+ const updateScroll = async (_options: { force?: boolean } = {}) => {
30
+ const defaultOptions = { force: false };
31
+ const options = { ...defaultOptions, ..._options };
32
+ const { force } = options;
33
+
34
+ if (!force && isDetached && !get(navigating)) return;
35
+
36
+ // wait for next tick to ensure that the DOM is updated
37
+ await tick();
38
+
39
+ node.scrollTo({ top: node.scrollHeight });
40
+ };
41
+
42
+ node.addEventListener("scroll", handleScroll);
43
+
44
+ if (dependency) {
45
+ updateScroll({ force: true });
46
+ }
47
+
48
+ return {
49
+ update: updateScroll,
50
+ destroy: () => {
51
+ node.removeEventListener("scroll", handleScroll);
52
+ },
53
+ };
54
+ };
chat-ui/src/lib/buildPrompt.ts ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { SAIGA_PROMPT_WEB_SEARCH_ANALYZE } from "$env/static/private";
2
+ import type { BackendModel } from "./server/models";
3
+ import type { Message } from "./types/Message";
4
+ import { format } from "date-fns";
5
+ import type { WebSearch } from "./types/WebSearch";
6
+ /**
7
+ * Convert [{user: "assistant", content: "hi"}, {user: "user", content: "hello"}] to:
8
+ *
9
+ * <|assistant|>hi<|endoftext|><|prompter|>hello<|endoftext|><|assistant|>
10
+ */
11
+
12
+ interface buildPromptOptions {
13
+ messages: Pick<Message, "from" | "content">[];
14
+ model: BackendModel;
15
+ locals?: App.Locals;
16
+ webSearch?: WebSearch;
17
+ preprompt?: string;
18
+ }
19
+
20
+ export async function buildPrompt({
21
+ messages,
22
+ model,
23
+ webSearch,
24
+ preprompt,
25
+ }: buildPromptOptions): Promise<Pick<Message, "from" | "content">[]> {
26
+ if (webSearch && webSearch.context) {
27
+ const messagesWithoutLastUsrMsg = messages.slice(0, -1);
28
+ const lastUserMsg = messages.slice(-1)[0];
29
+ const currentDate = format(new Date(), "yyyy.MM.dd");
30
+ messages = [
31
+ //...messagesWithoutLastUsrMsg,
32
+ {
33
+ from: "user",
34
+ content: SAIGA_PROMPT_WEB_SEARCH_ANALYZE.replace('{{query}}', lastUserMsg.content).replace('{{context}}', webSearch.context),
35
+ },
36
+ ];
37
+ }
38
+
39
+ return messages;
40
+ // console.log('messages', messages)
41
+ return (
42
+ model
43
+ .chatPromptRender({ messages, preprompt })
44
+ // Not super precise, but it's truncated in the model's backend anyway
45
+ .split(" ")
46
+ .slice(-(model.parameters?.truncate ?? 0))
47
+ .join(" ")
48
+ );
49
+ }
chat-ui/src/lib/buildSearchPrompt.ts ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { SAIGA_PROMPT_WEB_SEARCH_ANALYZE } from "$env/static/private";
2
+ import type { BackendModel } from "./server/models";
3
+ import type { Message } from "./types/Message";
4
+ import type { WebSearch } from "./types/WebSearch";
5
+
6
+ interface buildSearchPromptOptions {
7
+ messages: Message[];
8
+ webSearch?: WebSearch;
9
+ }
10
+
11
+ export async function buildSearchPrompt({
12
+ messages,
13
+ webSearch
14
+ }: buildSearchPromptOptions): Promise<Message[]> {
15
+ const lastUserMsg = messages.filter(m => m.from == 'user').slice(-1)[0];
16
+ let content = lastUserMsg.content;
17
+ if (webSearch && webSearch.context){
18
+ content = SAIGA_PROMPT_WEB_SEARCH_ANALYZE.replace('{{query}}', lastUserMsg.content).replace('{{context}}', webSearch.context)
19
+ }
20
+
21
+ return [{
22
+ ...lastUserMsg,
23
+ content: content,
24
+ }];
25
+ }
chat-ui/src/lib/components/AnnouncementBanner.svelte ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ export let title = "";
3
+ export let classNames = "";
4
+ </script>
5
+
6
+ <div class="flex items-center rounded-xl bg-gray-100 p-1 text-sm dark:bg-gray-800 {classNames}">
7
+ <span
8
+ class="mr-2 inline-flex items-center rounded-lg bg-gradient-to-br from-primary-300 px-2 py-1 text-xxs font-medium uppercase leading-3 text-primary-700 dark:from-primary-900 dark:text-primary-400"
9
+ >New</span
10
+ >
11
+ {title}
12
+ <div class="ml-auto shrink-0">
13
+ <slot />
14
+ </div>
15
+ </div>
chat-ui/src/lib/components/CodeBlock.svelte ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { afterUpdate } from "svelte";
3
+ import CopyToClipBoardBtn from "./CopyToClipBoardBtn.svelte";
4
+
5
+ export let code = "";
6
+ export let lang = "";
7
+
8
+ $: highlightedCode = "";
9
+
10
+ afterUpdate(async () => {
11
+ const { default: hljs } = await import("highlight.js");
12
+ const language = hljs.getLanguage(lang);
13
+
14
+ highlightedCode = hljs.highlightAuto(code, language?.aliases).value;
15
+ });
16
+ </script>
17
+
18
+ <div class="group relative my-4 rounded-lg">
19
+ <!-- eslint-disable svelte/no-at-html-tags -->
20
+ <pre
21
+ class="scrollbar-custom overflow-auto px-5 scrollbar-thumb-gray-500 hover:scrollbar-thumb-gray-400 dark:scrollbar-thumb-white/10 dark:hover:scrollbar-thumb-white/20"><code
22
+ class="language-{lang}">{@html highlightedCode || code.replaceAll("<", "&lt;")}</code
23
+ ></pre>
24
+ <CopyToClipBoardBtn
25
+ classNames="absolute top-2 right-2 invisible opacity-0 group-hover:visible group-hover:opacity-100"
26
+ value={code}
27
+ />
28
+ </div>
chat-ui/src/lib/components/CopyToClipBoardBtn.svelte ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { onDestroy } from "svelte";
3
+
4
+ import IconCopy from "./icons/IconCopy.svelte";
5
+ import Tooltip from "./Tooltip.svelte";
6
+
7
+ export let classNames = "";
8
+ export let value: string;
9
+
10
+ let isSuccess = false;
11
+ let timeout: ReturnType<typeof setTimeout>;
12
+
13
+ const handleClick = async () => {
14
+ // writeText() can be unavailable or fail in some cases (iframe, etc) so we try/catch
15
+ try {
16
+ await navigator.clipboard.writeText(value);
17
+
18
+ isSuccess = true;
19
+ if (timeout) {
20
+ clearTimeout(timeout);
21
+ }
22
+ timeout = setTimeout(() => {
23
+ isSuccess = false;
24
+ }, 1000);
25
+ } catch (err) {
26
+ console.error(err);
27
+ }
28
+ };
29
+
30
+ onDestroy(() => {
31
+ if (timeout) {
32
+ clearTimeout(timeout);
33
+ }
34
+ });
35
+ </script>
36
+
37
+ <button
38
+ class="btn rounded-lg border border-gray-200 px-2 py-2 text-sm shadow-sm transition-all hover:border-gray-300 active:shadow-inner dark:border-gray-600 dark:hover:border-gray-400 {classNames}
39
+ {!isSuccess && 'text-gray-200 dark:text-gray-200'}
40
+ {isSuccess && 'text-green-500'}
41
+ "
42
+ title={"Copy to clipboard"}
43
+ type="button"
44
+ on:click={handleClick}
45
+ >
46
+ <span class="relative">
47
+ <IconCopy />
48
+ <Tooltip classNames={isSuccess ? "opacity-100" : "opacity-0"} />
49
+ </span>
50
+ </button>
chat-ui/src/lib/components/LoginModal.svelte ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { browser } from "$app/environment";
3
+ import { base } from "$app/paths";
4
+ import { page } from "$app/stores";
5
+ import { PUBLIC_APP_DATA_SHARING, PUBLIC_APP_NAME, PUBLIC_VERSION } from "$env/static/public";
6
+ import LogoHuggingFaceBorderless from "$lib/components/icons/LogoHuggingFaceBorderless.svelte";
7
+ import Modal from "$lib/components/Modal.svelte";
8
+ import type { LayoutData } from "../../routes/$types";
9
+ import Logo from "./icons/Logo.svelte";
10
+ export let settings: LayoutData["settings"];
11
+
12
+ const isIframe = browser && window.self !== window.parent;
13
+ </script>
14
+
15
+ <Modal>
16
+ <div
17
+ class="flex w-full flex-col items-center gap-6 bg-gradient-to-t from-primary-500/40 via-primary-500/10 to-primary-500/0 px-4 pb-10 pt-9 text-center "
18
+ >
19
+ <h2 class="flex items-center text-2xl font-semibold text-gray-800">
20
+ <Logo classNames="mr-1" />
21
+ {PUBLIC_APP_NAME}
22
+ <div
23
+ class="ml-3 flex h-6 items-center rounded-lg border border-gray-100 bg-gray-50 px-2 text-base text-gray-400"
24
+ >
25
+ v{PUBLIC_VERSION}
26
+ </div>
27
+ </h2>
28
+ {#if $page.data.requiresLogin}
29
+ <p
30
+ class="px-4 text-lg font-semibold leading-snug text-gray-800 sm:px-12"
31
+ style="text-wrap: balance;"
32
+ >
33
+ Please Sign in with Hugging Face to continue
34
+ </p>
35
+ {/if}
36
+ <p class="text-base text-gray-800">
37
+ Disclaimer: AI is an area of active research with known problems such as biased generation and
38
+ misinformation. Do not use this application for high-stakes decisions or advice.
39
+ </p>
40
+ {#if PUBLIC_APP_DATA_SHARING}
41
+ <p class="px-2 text-sm text-gray-500">
42
+ Your conversations will be shared with model authors unless you disable it from your
43
+ settings.
44
+ </p>
45
+ {/if}
46
+ <form
47
+ action="{base}/{$page.data.requiresLogin ? 'login' : 'settings'}"
48
+ target={isIframe ? "_blank" : ""}
49
+ method="POST"
50
+ class="flex w-full flex-col items-center gap-2"
51
+ >
52
+ {#if $page.data.requiresLogin}
53
+ <button
54
+ type="submit"
55
+ class="mt-2 flex items-center whitespace-nowrap rounded-full bg-black px-5 py-2 text-lg font-semibold text-gray-100 transition-colors hover:bg-primary-500"
56
+ >
57
+ Sign in
58
+ {#if PUBLIC_APP_NAME === "HuggingChat"}
59
+ with <LogoHuggingFaceBorderless classNames="text-xl mr-1 ml-1.5" /> Hugging Face
60
+ {/if}
61
+ </button>
62
+ {:else}
63
+ <input type="hidden" name="ethicsModalAccepted" value={true} />
64
+ {#each Object.entries(settings) as [key, val]}
65
+ <input type="hidden" name={key} value={val} />
66
+ {/each}
67
+ <button
68
+ type="submit"
69
+ class="mt-2 rounded-full bg-black px-5 py-2 text-lg font-semibold text-gray-100 transition-colors hover:bg-primary-500"
70
+ >
71
+ Start chatting
72
+ </button>
73
+ {/if}
74
+ </form>
75
+ </div>
76
+ </Modal>
chat-ui/src/lib/components/MobileNav.svelte ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { navigating } from "$app/stores";
3
+ import { createEventDispatcher } from "svelte";
4
+ import { browser } from "$app/environment";
5
+ import { base } from "$app/paths";
6
+
7
+ import CarbonClose from "~icons/carbon/close";
8
+ import CarbonAdd from "~icons/carbon/add";
9
+ import CarbonTextAlignJustify from "~icons/carbon/text-align-justify";
10
+
11
+ export let isOpen = false;
12
+ export let title: string | undefined;
13
+
14
+ $: title = title || "New Chat";
15
+
16
+ let closeEl: HTMLButtonElement;
17
+ let openEl: HTMLButtonElement;
18
+
19
+ const dispatch = createEventDispatcher();
20
+
21
+ $: if ($navigating) {
22
+ dispatch("toggle", false);
23
+ }
24
+
25
+ $: if (isOpen && closeEl) {
26
+ closeEl.focus();
27
+ } else if (!isOpen && browser && document.activeElement === closeEl) {
28
+ openEl.focus();
29
+ }
30
+ </script>
31
+
32
+ <nav
33
+ class="flex h-12 items-center justify-between border-b bg-gray-50 px-4 dark:border-gray-800 dark:bg-gray-800/70 md:hidden"
34
+ >
35
+ <button
36
+ type="button"
37
+ class="-ml-3 flex h-9 w-9 shrink-0 items-center justify-center"
38
+ on:click={() => dispatch("toggle", true)}
39
+ aria-label="Open menu"
40
+ bind:this={openEl}><CarbonTextAlignJustify /></button
41
+ >
42
+ <span class="truncate px-4">{title}</span>
43
+ <a href={`${base}/`} class="-mr-3 flex h-9 w-9 shrink-0 items-center justify-center"
44
+ ><CarbonAdd /></a
45
+ >
46
+ </nav>
47
+ <nav
48
+ class="fixed inset-0 z-30 grid max-h-screen grid-cols-1 grid-rows-[auto,auto,1fr,auto] bg-white bg-gradient-to-l from-gray-50 dark:bg-gray-900 dark:from-gray-800/30 {isOpen
49
+ ? 'block'
50
+ : 'hidden'}"
51
+ >
52
+ <div class="flex h-12 items-center px-4">
53
+ <button
54
+ type="button"
55
+ class="-mr-3 ml-auto flex h-9 w-9 items-center justify-center"
56
+ on:click={() => dispatch("toggle", false)}
57
+ aria-label="Close menu"
58
+ bind:this={closeEl}><CarbonClose /></button
59
+ >
60
+ </div>
61
+ <slot />
62
+ </nav>
chat-ui/src/lib/components/Modal.svelte ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { createEventDispatcher, onDestroy, onMount } from "svelte";
3
+ import { cubicOut } from "svelte/easing";
4
+ import { fade } from "svelte/transition";
5
+ import Portal from "./Portal.svelte";
6
+ import { browser } from "$app/environment";
7
+
8
+ export let width = "max-w-sm";
9
+
10
+ let backdropEl: HTMLDivElement;
11
+ let modalEl: HTMLDivElement;
12
+
13
+ const dispatch = createEventDispatcher<{ close: void }>();
14
+
15
+ function handleKeydown(event: KeyboardEvent) {
16
+ // close on ESC
17
+ if (event.key === "Escape") {
18
+ event.preventDefault();
19
+ dispatch("close");
20
+ }
21
+ }
22
+
23
+ function handleBackdropClick(event: MouseEvent) {
24
+ if (event.target === backdropEl) {
25
+ dispatch("close");
26
+ }
27
+ }
28
+
29
+ onMount(() => {
30
+ document.getElementById("app")?.setAttribute("inert", "true");
31
+ modalEl.focus();
32
+ });
33
+
34
+ onDestroy(() => {
35
+ if (!browser) return;
36
+ // remove inert attribute if this is the last modal
37
+ if (document.querySelectorAll('[role="dialog"]:not(#app *)').length === 1) {
38
+ document.getElementById("app")?.removeAttribute("inert");
39
+ }
40
+ });
41
+ </script>
42
+
43
+ <Portal>
44
+ <div
45
+ role="presentation"
46
+ tabindex="-1"
47
+ bind:this={backdropEl}
48
+ on:click={handleBackdropClick}
49
+ transition:fade={{ easing: cubicOut, duration: 300 }}
50
+ class="fixed inset-0 z-40 flex items-center justify-center bg-black/80 p-8 backdrop-blur-sm dark:bg-black/50"
51
+ >
52
+ <div
53
+ role="dialog"
54
+ tabindex="-1"
55
+ bind:this={modalEl}
56
+ on:keydown={handleKeydown}
57
+ class="max-h-[90dvh] overflow-y-auto overflow-x-hidden rounded-2xl bg-white shadow-2xl outline-none sm:-mt-10 sm:max-h-screen {width}"
58
+ >
59
+ <slot />
60
+ </div>
61
+ </div>
62
+ </Portal>
chat-ui/src/lib/components/ModelCardMetadata.svelte ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import CarbonEarth from "~icons/carbon/earth";
3
+ import CarbonArrowUpRight from "~icons/carbon/arrow-up-right";
4
+ import type { Model } from "$lib/types/Model";
5
+
6
+ export let model: Pick<Model, "name" | "datasetName" | "websiteUrl" | "modelUrl" | "datasetUrl">;
7
+
8
+ export let variant: "light" | "dark" = "light";
9
+ </script>
10
+
11
+ <div
12
+ class="flex items-center gap-5 rounded-xl bg-gray-100 px-3 py-2 text-xs sm:text-sm
13
+ {variant === 'dark'
14
+ ? 'text-gray-600 dark:bg-gray-800 dark:text-gray-300'
15
+ : 'text-gray-800 dark:bg-gray-100 dark:text-gray-600'}"
16
+ >
17
+ <a
18
+ href={model.modelUrl || "https://huggingface.co/" + model.name}
19
+ target="_blank"
20
+ rel="noreferrer"
21
+ class="flex items-center hover:underline"
22
+ ><CarbonArrowUpRight class="mr-1.5 shrink-0 text-xs text-gray-400" />
23
+ Model
24
+ <div class="max-sm:hidden">&nbsp;page</div></a
25
+ >
26
+ {#if model.datasetName || model.datasetUrl}
27
+ <a
28
+ href={model.datasetUrl || "https://huggingface.co/datasets/" + model.datasetName}
29
+ target="_blank"
30
+ rel="noreferrer"
31
+ class="flex items-center hover:underline"
32
+ ><CarbonArrowUpRight class="mr-1.5 shrink-0 text-xs text-gray-400" />
33
+ Dataset
34
+ <div class="max-sm:hidden">&nbsp;page</div></a
35
+ >
36
+ {/if}
37
+ {#if model.websiteUrl}
38
+ <a
39
+ href={model.websiteUrl}
40
+ target="_blank"
41
+ class="ml-auto flex items-center hover:underline"
42
+ rel="noreferrer"
43
+ >
44
+ <CarbonEarth class="mr-1.5 shrink-0 text-xs text-gray-400" />
45
+ Website
46
+ </a>
47
+ {/if}
48
+ </div>
chat-ui/src/lib/components/ModelsModal.svelte ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { createEventDispatcher } from "svelte";
3
+
4
+ import Modal from "$lib/components/Modal.svelte";
5
+ import CarbonClose from "~icons/carbon/close";
6
+ import CarbonCheckmark from "~icons/carbon/checkmark-filled";
7
+ import ModelCardMetadata from "./ModelCardMetadata.svelte";
8
+ import type { Model } from "$lib/types/Model";
9
+ import type { LayoutData } from "../../routes/$types";
10
+ import { enhance } from "$app/forms";
11
+ import { base } from "$app/paths";
12
+
13
+ import CarbonEdit from "~icons/carbon/edit";
14
+ import CarbonSave from "~icons/carbon/save";
15
+ import CarbonRestart from "~icons/carbon/restart";
16
+
17
+ export let settings: LayoutData["settings"];
18
+ export let models: Array<Model>;
19
+
20
+ let selectedModelId = settings.activeModel;
21
+
22
+ const dispatch = createEventDispatcher<{ close: void }>();
23
+
24
+ let expanded = false;
25
+
26
+ function onToggle() {
27
+ if (expanded) {
28
+ settings.customPrompts[selectedModelId] = value;
29
+ }
30
+ expanded = !expanded;
31
+ }
32
+
33
+ let value = "";
34
+
35
+ function onModelChange() {
36
+ value =
37
+ settings.customPrompts[selectedModelId] ??
38
+ models.filter((el) => el.id === selectedModelId)[0].preprompt ??
39
+ "";
40
+ }
41
+
42
+ $: selectedModelId, onModelChange();
43
+ </script>
44
+
45
+ <Modal width="max-w-lg" on:close>
46
+ <form
47
+ action="{base}/settings"
48
+ method="post"
49
+ on:submit={() => {
50
+ if (expanded) {
51
+ onToggle();
52
+ }
53
+ }}
54
+ use:enhance={() => {
55
+ dispatch("close");
56
+ }}
57
+ class="flex w-full flex-col gap-5 p-6"
58
+ >
59
+ {#each Object.entries(settings).filter(([k]) => !(k == "activeModel" || k === "customPrompts")) as [key, val]}
60
+ <input type="hidden" name={key} value={val} />
61
+ {/each}
62
+ <input type="hidden" name="customPrompts" value={JSON.stringify(settings.customPrompts)} />
63
+ <div class="flex items-start justify-between text-xl font-semibold text-gray-800">
64
+ <h2>Models</h2>
65
+ <button type="button" class="group" on:click={() => dispatch("close")}>
66
+ <CarbonClose class="text-gray-900 group-hover:text-gray-500" />
67
+ </button>
68
+ </div>
69
+
70
+ <div class="space-y-4">
71
+ {#each models as model}
72
+ {@const active = model.id === selectedModelId}
73
+ <div
74
+ class="relative rounded-xl border border-gray-100 {active
75
+ ? 'bg-gradient-to-r from-primary-200/40 via-primary-500/10'
76
+ : ''}"
77
+ >
78
+ <label
79
+ class="group flex cursor-pointer flex-col p-3"
80
+ on:change
81
+ aria-label={model.displayName}
82
+ >
83
+ <input
84
+ type="radio"
85
+ class="sr-only"
86
+ name="activeModel"
87
+ value={model.id}
88
+ bind:group={selectedModelId}
89
+ />
90
+ <div
91
+ class="mb-1.5 block pr-8 text-sm font-semibold leading-tight text-gray-800 sm:text-base"
92
+ >
93
+ {model.displayName}
94
+ </div>
95
+ {#if model.description}
96
+ <div class="text-xs text-gray-500 sm:text-sm">{model.description}</div>
97
+ {/if}
98
+ <CarbonCheckmark
99
+ class="absolute right-2 top-2 text-xl {active
100
+ ? 'text-primary-400'
101
+ : 'text-transparent group-hover:text-gray-200'}"
102
+ />
103
+ </label>
104
+ {#if active}
105
+ <div class=" overflow-hidden rounded-xl px-3 pb-2">
106
+ <div class="flex flex-row flex-nowrap gap-2 pb-1">
107
+ <div class="text-xs font-semibold text-gray-500">System Prompt</div>
108
+ {#if expanded}
109
+ <button
110
+ class="text-gray-500 hover:text-gray-900"
111
+ on:click|preventDefault={onToggle}
112
+ >
113
+ <CarbonSave class="text-sm" />
114
+ </button>
115
+ <button
116
+ class="text-gray-500 hover:text-gray-900"
117
+ on:click|preventDefault={() => {
118
+ value = model.preprompt ?? "";
119
+ }}
120
+ >
121
+ <CarbonRestart class="text-sm" />
122
+ </button>
123
+ {:else}
124
+ <button
125
+ class=" text-gray-500 hover:text-gray-900"
126
+ on:click|preventDefault={onToggle}
127
+ >
128
+ <CarbonEdit class="text-sm" />
129
+ </button>
130
+ {/if}
131
+ </div>
132
+ <textarea
133
+ enterkeyhint="send"
134
+ tabindex="0"
135
+ rows="1"
136
+ class="h-20 w-full resize-none scroll-p-3 overflow-x-hidden overflow-y-scroll rounded-md border border-gray-300 bg-transparent p-1 text-xs outline-none focus:ring-0 focus-visible:ring-0"
137
+ bind:value
138
+ hidden={!expanded}
139
+ />
140
+ </div>
141
+ {/if}
142
+ <ModelCardMetadata {model} />
143
+ </div>
144
+ {/each}
145
+ </div>
146
+ <button
147
+ type="submit"
148
+ class="sticky bottom-6 mt-2 rounded-full bg-black px-5 py-2 text-lg font-semibold text-gray-100 ring-gray-400 ring-offset-1 transition-colors hover:ring"
149
+ >
150
+ Apply
151
+ </button>
152
+ </form>
153
+ </Modal>
chat-ui/src/lib/components/NavConversationItem.svelte ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { base } from "$app/paths";
3
+ import { page } from "$app/stores";
4
+ import { createEventDispatcher } from "svelte";
5
+
6
+ import CarbonCheckmark from "~icons/carbon/checkmark";
7
+ import CarbonTrashCan from "~icons/carbon/trash-can";
8
+ import CarbonClose from "~icons/carbon/close";
9
+ import CarbonEdit from "~icons/carbon/edit";
10
+
11
+ export let conv: { id: string; title: string };
12
+
13
+ let confirmDelete = false;
14
+
15
+ const dispatch = createEventDispatcher<{
16
+ deleteConversation: string;
17
+ editConversationTitle: { id: string; title: string };
18
+ }>();
19
+ </script>
20
+
21
+ <a
22
+ data-sveltekit-noscroll
23
+ on:mouseleave={() => {
24
+ confirmDelete = false;
25
+ }}
26
+ href="{base}/conversation/{conv.id}"
27
+ class="group flex h-11 flex-none items-center gap-1.5 rounded-lg pl-3 pr-2 text-gray-500 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-700 {conv.id ===
28
+ $page.params.id
29
+ ? 'bg-gray-100 dark:bg-gray-700'
30
+ : ''}"
31
+ >
32
+ <div class="flex-1 truncate">
33
+ {#if confirmDelete}
34
+ <span class="font-semibold"> Удалить </span>
35
+ {/if}
36
+ {conv.title}
37
+ </div>
38
+
39
+ {#if confirmDelete}
40
+ <button
41
+ type="button"
42
+ class="flex h-5 w-5 items-center justify-center rounded md:hidden md:group-hover:flex"
43
+ title="Удалить"
44
+ on:click|preventDefault={() => dispatch("deleteConversation", conv.id)}
45
+ >
46
+ <CarbonCheckmark class="text-xs text-gray-400 hover:text-gray-500 dark:hover:text-gray-300" />
47
+ </button>
48
+ <button
49
+ type="button"
50
+ class="flex h-5 w-5 items-center justify-center rounded md:hidden md:group-hover:flex"
51
+ title="Отмена"
52
+ on:click|preventDefault={() => {
53
+ confirmDelete = false;
54
+ }}
55
+ >
56
+ <CarbonClose class="text-xs text-gray-400 hover:text-gray-500 dark:hover:text-gray-300" />
57
+ </button>
58
+ {:else}
59
+ <button
60
+ type="button"
61
+ class="flex h-5 w-5 items-center justify-center rounded md:hidden md:group-hover:flex"
62
+ title="Редактировать заголовок"
63
+ on:click|preventDefault={() => {
64
+ const newTitle = prompt("Введите заголовок для диалога:", conv.title);
65
+ if (!newTitle) return;
66
+ dispatch("editConversationTitle", { id: conv.id, title: newTitle });
67
+ }}
68
+ >
69
+ <CarbonEdit class="text-xs text-gray-400 hover:text-gray-500 dark:hover:text-gray-300" />
70
+ </button>
71
+
72
+ <button
73
+ type="button"
74
+ class="flex h-5 w-5 items-center justify-center rounded md:hidden md:group-hover:flex"
75
+ title="Удалить заголовок"
76
+ on:click|preventDefault={(event) => {
77
+ if (event.shiftKey) {
78
+ dispatch("deleteConversation", conv.id);
79
+ } else {
80
+ confirmDelete = true;
81
+ }
82
+ }}
83
+ >
84
+ <CarbonTrashCan class="text-xs text-gray-400 hover:text-gray-500 dark:hover:text-gray-300" />
85
+ </button>
86
+ {/if}
87
+ </a>
chat-ui/src/lib/components/NavMenu.svelte ADDED
@@ -0,0 +1,107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { base } from "$app/paths";
3
+ import { createEventDispatcher } from "svelte";
4
+
5
+ import Logo from "$lib/components/icons/Logo.svelte";
6
+ import { switchTheme } from "$lib/switchTheme";
7
+ import { PUBLIC_APP_NAME, PUBLIC_ORIGIN } from "$env/static/public";
8
+ import NavConversationItem from "./NavConversationItem.svelte";
9
+ import type { LayoutData } from "../../routes/$types";
10
+
11
+ const dispatch = createEventDispatcher<{
12
+ shareConversation: { id: string; title: string };
13
+ clickSettings: void;
14
+ clickLogout: void;
15
+ }>();
16
+
17
+ export let conversations: Array<{
18
+ id: string;
19
+ title: string;
20
+ }> = [];
21
+
22
+ export let canLogin: boolean;
23
+ export let user: LayoutData["user"];
24
+
25
+ export let loginModalVisible;
26
+ </script>
27
+
28
+ <div class="sticky top-0 flex flex-none items-center justify-between px-3 py-3.5 max-sm:pt-0">
29
+ <a class="flex items-center rounded-xl text-lg font-semibold" href="{PUBLIC_ORIGIN}{base}/">
30
+ <Logo classNames="mr-1" />
31
+ {PUBLIC_APP_NAME}
32
+ </a>
33
+ <a
34
+ href={`${base}/`}
35
+ class="flex rounded-lg border bg-white px-2 py-0.5 text-center shadow-sm hover:shadow-none dark:border-gray-600 dark:bg-gray-700"
36
+ >
37
+ Новый диалог
38
+ </a>
39
+ </div>
40
+ <div
41
+ class="scrollbar-custom flex flex-col gap-1 overflow-y-auto rounded-r-xl bg-gradient-to-l from-gray-50 px-3 pb-3 pt-2 dark:from-gray-800/30"
42
+ >
43
+ {#each conversations as conv (conv.id)}
44
+ <NavConversationItem on:editConversationTitle on:deleteConversation {conv} />
45
+ {/each}
46
+ </div>
47
+ <div
48
+ class="mt-0.5 flex flex-col gap-1 rounded-r-xl bg-gradient-to-l from-gray-50 p-3 text-sm dark:from-gray-800/30"
49
+ >
50
+ {#if user?.username || user?.email}
51
+ <form
52
+ action="{base}/logout"
53
+ method="post"
54
+ class="group flex items-center gap-1.5 rounded-lg pl-3 pr-2 hover:bg-gray-100 dark:hover:bg-gray-700"
55
+ >
56
+ <span
57
+ class="flex h-9 flex-none shrink items-center gap-1.5 truncate pr-2 text-gray-500 dark:text-gray-400"
58
+ >{user?.username || user?.email}</span
59
+ >
60
+ <button
61
+ type="submit"
62
+ class="ml-auto h-6 flex-none items-center gap-1.5 rounded-md border bg-white px-2 text-gray-700 shadow-sm group-hover:flex hover:shadow-none dark:border-gray-600 dark:bg-gray-600 dark:text-gray-400 dark:hover:text-gray-300 md:hidden"
63
+ >
64
+ Sign Out
65
+ </button>
66
+ </form>
67
+ {/if}
68
+ {#if canLogin}
69
+ <button
70
+ on:click={() => (loginModalVisible = true)}
71
+ type="button"
72
+ class="flex h-9 flex-none items-center gap-1.5 rounded-lg pl-3 pr-2 text-gray-500 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-700"
73
+ >
74
+ Login
75
+ </button>
76
+ {/if}
77
+ <button
78
+ on:click={switchTheme}
79
+ type="button"
80
+ class="flex h-9 flex-none items-center gap-1.5 rounded-lg pl-3 pr-2 text-gray-500 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-700"
81
+ >
82
+ Переключить тему
83
+ </button>
84
+ <button
85
+ on:click={() => dispatch("clickSettings")}
86
+ type="button"
87
+ class="flex h-9 flex-none items-center gap-1.5 rounded-lg pl-3 pr-2 text-gray-500 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-700"
88
+ >
89
+ Настройки
90
+ </button>
91
+ {#if PUBLIC_APP_NAME === "HuggingChat"}
92
+ <a
93
+ href="https://huggingface.co/spaces/huggingchat/chat-ui/discussions"
94
+ target="_blank"
95
+ rel="noreferrer"
96
+ class="flex h-9 flex-none items-center gap-1.5 rounded-lg pl-3 pr-2 text-gray-500 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-700"
97
+ >
98
+ Feedback
99
+ </a>
100
+ <a
101
+ href="{base}/privacy"
102
+ class="flex h-9 flex-none items-center gap-1.5 rounded-lg pl-3 pr-2 text-gray-500 hover:bg-gray-100 dark:text-gray-400 dark:hover:bg-gray-700"
103
+ >
104
+ About & Privacy
105
+ </a>
106
+ {/if}
107
+ </div>
chat-ui/src/lib/components/OpenWebSearchResults.svelte ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import type { WebSearchUpdate } from "$lib/types/MessageUpdate";
3
+ import CarbonCaretRight from "~icons/carbon/caret-right";
4
+
5
+ import CarbonCheckmark from "~icons/carbon/checkmark-filled";
6
+ import CarbonError from "~icons/carbon/error-filled";
7
+
8
+ import EosIconsLoading from "~icons/eos-icons/loading";
9
+
10
+ export let loading = false;
11
+ export let classNames = "";
12
+ export let webSearchMessages: WebSearchUpdate[] = [];
13
+
14
+ let detailsOpen: boolean;
15
+ let error: boolean;
16
+ $: error = webSearchMessages[webSearchMessages.length - 1]?.messageType === "error";
17
+ </script>
18
+
19
+ <details
20
+ class="flex w-fit rounded-xl border border-gray-200 bg-white shadow-sm dark:border-gray-800 dark:bg-gray-900 {classNames} max-w-full"
21
+ bind:open={detailsOpen}
22
+ >
23
+ <summary
24
+ class="align-center flex cursor-pointer select-none list-none py-1 pl-2.5 pr-2 align-text-top transition-all"
25
+ >
26
+ {#if error}
27
+ <CarbonError class="my-auto text-red-700 dark:text-red-500" />
28
+ {:else if loading}
29
+ <EosIconsLoading class="my-auto text-gray-500" />
30
+ {:else}
31
+ <CarbonCheckmark class="my-auto text-gray-500" />
32
+ {/if}
33
+ <span class="px-2 font-medium" class:text-red-700={error} class:dark:text-red-500={error}
34
+ >Поиск в интернете
35
+ </span>
36
+ <div class="my-auto transition-all" class:rotate-90={detailsOpen}>
37
+ <CarbonCaretRight />
38
+ </div>
39
+ </summary>
40
+
41
+ <div class="content px-5 pb-5 pt-4">
42
+ {#if webSearchMessages.length === 0}
43
+ <div class="mx-auto w-fit">
44
+ <EosIconsLoading class="mb-3 h-4 w-4" />
45
+ </div>
46
+ {:else}
47
+ <ol>
48
+ {#each webSearchMessages as message}
49
+ {#if message.messageType === "update"}
50
+ <li class="group border-l pb-6 last:!border-transparent last:pb-0 dark:border-gray-800">
51
+ <div class="flex items-start">
52
+ <div
53
+ class="-ml-1.5 h-3 w-3 flex-none rounded-full bg-gray-200 dark:bg-gray-600 {loading
54
+ ? 'group-last:animate-pulse group-last:bg-gray-300 group-last:dark:bg-gray-500'
55
+ : ''}"
56
+ />
57
+ <h3 class="text-md -mt-1.5 pl-2.5 text-gray-800 dark:text-gray-100">
58
+ {message.message}
59
+ </h3>
60
+ </div>
61
+ {#if message.args}
62
+ <p class="mt-1.5 pl-4 text-gray-500 dark:text-gray-400">
63
+ {message.args}
64
+ </p>
65
+ {/if}
66
+ </li>
67
+ {:else if message.messageType === "error"}
68
+ <li class="group border-l pb-6 last:!border-transparent last:pb-0 dark:border-gray-800">
69
+ <div class="flex items-start">
70
+ <CarbonError
71
+ class="-ml-1.5 h-3 w-3 flex-none scale-110 text-red-700 dark:text-red-500"
72
+ />
73
+ <h3 class="text-md -mt-1.5 pl-2.5 text-red-700 dark:text-red-500">
74
+ {message.message}
75
+ </h3>
76
+ </div>
77
+ {#if message.args}
78
+ <p class="mt-1.5 pl-4 text-gray-500 dark:text-gray-400">
79
+ {message.args}
80
+ </p>
81
+ {/if}
82
+ </li>
83
+ {/if}
84
+ {/each}
85
+ </ol>
86
+ {/if}
87
+ </div>
88
+ </details>
89
+
90
+ <style>
91
+ @keyframes grow {
92
+ 0% {
93
+ font-size: 0;
94
+ opacity: 0;
95
+ }
96
+ 30% {
97
+ font-size: 1em;
98
+ opacity: 0;
99
+ }
100
+ 100% {
101
+ opacity: 1;
102
+ }
103
+ }
104
+
105
+ details[open] .content {
106
+ animation-name: grow;
107
+ animation-duration: 300ms;
108
+ animation-delay: 0ms;
109
+ }
110
+
111
+ details summary::-webkit-details-marker {
112
+ display: none;
113
+ }
114
+ </style>
chat-ui/src/lib/components/Portal.svelte ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { onMount, onDestroy } from "svelte";
3
+
4
+ let el: HTMLElement;
5
+
6
+ onMount(() => {
7
+ el.ownerDocument.body.appendChild(el);
8
+ });
9
+
10
+ onDestroy(() => {
11
+ if (el?.parentNode) {
12
+ el.parentNode.removeChild(el);
13
+ }
14
+ });
15
+ </script>
16
+
17
+ <div bind:this={el} class="contents" hidden>
18
+ <slot />
19
+ </div>
chat-ui/src/lib/components/ScrollToBottomBtn.svelte ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { fade } from "svelte/transition";
3
+ import { onDestroy } from "svelte";
4
+ import IconChevron from "./icons/IconChevron.svelte";
5
+
6
+ export let scrollNode: HTMLElement;
7
+ export { className as class };
8
+
9
+ let visible = false;
10
+ let className = "";
11
+ let observer: ResizeObserver | null = null;
12
+
13
+ $: if (scrollNode) {
14
+ destroy();
15
+
16
+ if (window.ResizeObserver) {
17
+ observer = new ResizeObserver(() => {
18
+ updateVisibility();
19
+ });
20
+ observer.observe(scrollNode);
21
+ }
22
+ scrollNode.addEventListener("scroll", updateVisibility);
23
+ }
24
+
25
+ function updateVisibility() {
26
+ if (!scrollNode) return;
27
+ visible =
28
+ Math.ceil(scrollNode.scrollTop) + 200 < scrollNode.scrollHeight - scrollNode.clientHeight;
29
+ }
30
+
31
+ function destroy() {
32
+ observer?.disconnect();
33
+ scrollNode?.removeEventListener("scroll", updateVisibility);
34
+ }
35
+
36
+ onDestroy(destroy);
37
+ </script>
38
+
39
+ {#if visible}
40
+ <button
41
+ transition:fade|local={{ duration: 150 }}
42
+ on:click={() => scrollNode.scrollTo({ top: scrollNode.scrollHeight, behavior: "smooth" })}
43
+ class="btn absolute flex h-[41px] w-[41px] rounded-full border bg-white shadow-md transition-all hover:bg-gray-100 dark:border-gray-600 dark:bg-gray-700 dark:shadow-gray-950 dark:hover:bg-gray-600 {className}"
44
+ ><IconChevron classNames="mt-[2px]" /></button
45
+ >
46
+ {/if}
chat-ui/src/lib/components/SettingsModal.svelte ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { createEventDispatcher } from "svelte";
3
+
4
+ import Modal from "$lib/components/Modal.svelte";
5
+ import CarbonClose from "~icons/carbon/close";
6
+ import Switch from "$lib/components/Switch.svelte";
7
+ import { enhance } from "$app/forms";
8
+ import { base } from "$app/paths";
9
+ import { PUBLIC_APP_DATA_SHARING } from "$env/static/public";
10
+ import type { Model } from "$lib/types/Model";
11
+ import type { LayoutData } from "../../routes/$types";
12
+
13
+ export let settings: LayoutData["settings"];
14
+ export let models: Array<Model>;
15
+
16
+ let shareConversationsWithModelAuthors = settings.shareConversationsWithModelAuthors;
17
+ let isConfirmingDeletion = false;
18
+
19
+ const dispatch = createEventDispatcher<{ close: void }>();
20
+ </script>
21
+
22
+ <Modal on:close>
23
+ <div class="flex w-full flex-col gap-5 p-6">
24
+ <div class="flex items-start justify-between text-xl font-semibold text-gray-800">
25
+ <h2>Настройки</h2>
26
+ <button type="button" class="group" on:click={() => dispatch("close")}>
27
+ <CarbonClose class="text-gray-900 group-hover:text-gray-500" />
28
+ </button>
29
+ </div>
30
+ <form
31
+ class="flex flex-col gap-5"
32
+ use:enhance={() => {
33
+ dispatch("close");
34
+ }}
35
+ method="post"
36
+ action="{base}/settings"
37
+ >
38
+ {#if PUBLIC_APP_DATA_SHARING}
39
+ <label class="flex cursor-pointer select-none items-center gap-2 text-gray-500">
40
+ {#each Object.entries(settings).filter(([k]) => !(k === "shareConversationsWithModelAuthors" || k === "customPrompts")) as [key, val]}
41
+ <input type="hidden" name={key} value={val} />
42
+ {/each}
43
+ <input
44
+ type="hidden"
45
+ name="customPrompts"
46
+ value={JSON.stringify(settings.customPrompts)}
47
+ />
48
+ <Switch
49
+ name="shareConversationsWithModelAuthors"
50
+ bind:checked={shareConversationsWithModelAuthors}
51
+ />
52
+ Share conversations with model authors
53
+ </label>
54
+
55
+ <p class="text-gray-800">
56
+ Sharing your data will help improve the training data and make open models better over
57
+ time.
58
+ </p>
59
+ <p class="text-gray-800">
60
+ You can change this setting at any time, it applies to all your conversations.
61
+ </p>
62
+ <div>
63
+ <p class="text-gray-800 ">Read more about model authors:</p>
64
+ <ul class="list-inside list-disc">
65
+ {#each models as model}
66
+ <li class="list-item">
67
+ <a
68
+ href={model["websiteUrl"]}
69
+ target="_blank"
70
+ rel="noreferrer"
71
+ class="underline decoration-gray-300 hover:decoration-gray-700">{model["name"]}</a
72
+ >
73
+ </li>
74
+ {/each}
75
+ </ul>
76
+ </div>
77
+ {/if}
78
+ <form
79
+ method="post"
80
+ action="{base}/conversations?/delete"
81
+ on:submit|preventDefault={() => (isConfirmingDeletion = true)}
82
+ >
83
+ <button type="submit" class="underline decoration-gray-300 hover:decoration-gray-700">
84
+ Удалить все диалоги
85
+ </button>
86
+ </form>
87
+ <button
88
+ type="submit"
89
+ class="mt-2 rounded-full bg-black px-5 py-2 text-lg font-semibold text-gray-100 ring-gray-400 ring-offset-1 transition-all focus-visible:outline-none focus-visible:ring hover:ring"
90
+ >
91
+ Применить
92
+ </button>
93
+ </form>
94
+
95
+ {#if isConfirmingDeletion}
96
+ <Modal on:close={() => (isConfirmingDeletion = false)}>
97
+ <form
98
+ use:enhance={() => {
99
+ dispatch("close");
100
+ }}
101
+ method="post"
102
+ action="{base}/conversations?/delete"
103
+ class="flex w-full flex-col gap-5 p-6"
104
+ >
105
+ <div class="flex items-start justify-between text-xl font-semibold text-gray-800">
106
+ <h2>Вы уверены?</h2>
107
+ <button type="button" class="group" on:click={() => (isConfirmingDeletion = false)}>
108
+ <CarbonClose class="text-gray-900 group-hover:text-gray-500" />
109
+ </button>
110
+ </div>
111
+ <p class="text-gray-800">
112
+ Вы собираетесь удалить все диалоги без возможности восстановления.
113
+ </p>
114
+ <button
115
+ type="submit"
116
+ class="mt-2 rounded-full bg-red-700 px-5 py-2 text-lg font-semibold text-gray-100 ring-gray-400 ring-offset-1 transition-all focus-visible:outline-none focus-visible:ring hover:ring"
117
+ >
118
+ Подтвердить
119
+ </button>
120
+ </form>
121
+ </Modal>
122
+ {/if}
123
+ </div>
124
+ </Modal>
chat-ui/src/lib/components/StopGeneratingBtn.svelte ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import CarbonStopFilledAlt from "~icons/carbon/stop-filled-alt";
3
+
4
+ export let classNames = "";
5
+ </script>
6
+
7
+ <!-- <button
8
+ type="button"
9
+ on:click
10
+ class="btn flex h-9 rounded-lg border bg-white px-3 py-1 shadow-sm transition-all hover:bg-gray-100 dark:border-gray-600 dark:bg-gray-700 dark:hover:bg-gray-600 {classNames}"
11
+ >
12
+ <CarbonStopFilledAlt class="-ml-1 mr-1 h-[1.25rem] w-[1.1875rem] text-gray-400" /> Остановить
13
+ </button> -->
chat-ui/src/lib/components/Switch.svelte ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ export let checked: boolean;
3
+ export let name: string;
4
+ </script>
5
+
6
+ <input bind:checked type="checkbox" {name} class="peer pointer-events-none absolute opacity-0" />
7
+ <div
8
+ on:click
9
+ on:keypress
10
+ class="relative inline-flex h-5 w-9 shrink-0 items-center rounded-full bg-gray-300 p-1 shadow-inner ring-gray-400 transition-all peer-checked:bg-blue-600 peer-focus-visible:ring peer-focus-visible:ring-offset-1 hover:bg-gray-400 dark:bg-gray-600 peer-checked:[&>div]:translate-x-3.5"
11
+ >
12
+ <div class="h-3.5 w-3.5 rounded-full bg-white shadow-sm transition-all" />
13
+ </div>
chat-ui/src/lib/components/Toast.svelte ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { fade } from "svelte/transition";
3
+
4
+ import IconDazzled from "$lib/components/icons/IconDazzled.svelte";
5
+
6
+ export let message = "";
7
+ </script>
8
+
9
+ <div
10
+ transition:fade={{ duration: 300 }}
11
+ class="pointer-events-none fixed right-0 top-12 z-20 bg-gradient-to-bl from-red-500/20 via-red-500/0 to-red-500/0 pb-36 pl-36 pr-2 pt-2 md:top-0 md:pr-8 md:pt-5"
12
+ >
13
+ <div
14
+ class="pointer-events-auto flex items-center rounded-full bg-white/90 px-3 py-1 shadow-sm dark:bg-gray-900/80"
15
+ >
16
+ <IconDazzled classNames="text-2xl mr-2" />
17
+ <h2 class="font-semibold">{message}</h2>
18
+ </div>
19
+ </div>
chat-ui/src/lib/components/Tooltip.svelte ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ export let classNames = "";
3
+ export let label = "Copied";
4
+ export let position = "left-1/2 top-full transform -translate-x-1/2 translate-y-2";
5
+ </script>
6
+
7
+ <div
8
+ class="
9
+ pointer-events-none absolute rounded bg-black px-2 py-1 font-normal leading-tight text-white shadow transition-opacity
10
+ {position}
11
+ {classNames}
12
+ "
13
+ >
14
+ <div
15
+ class="absolute bottom-full left-1/2 h-0 w-0 -translate-x-1/2 transform border-4 border-t-0 border-black"
16
+ style="
17
+ border-left-color: transparent;
18
+ border-right-color: transparent;
19
+ "
20
+ />
21
+ {label}
22
+ </div>
chat-ui/src/lib/components/WebSearchToggle.svelte ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { webSearchParameters } from "$lib/stores/webSearchParameters";
3
+ import CarbonInformation from "~icons/carbon/information";
4
+ import Switch from "./Switch.svelte";
5
+
6
+ const toggle = () => ($webSearchParameters.useSearch = !$webSearchParameters.useSearch);
7
+ </script>
8
+
9
+ <div
10
+ class="flex h-9 cursor-pointer select-none items-center gap-2 rounded-xl border bg-white p-1.5 shadow-sm hover:shadow-none dark:border-gray-800 dark:bg-gray-900"
11
+ on:click={toggle}
12
+ on:keypress={toggle}
13
+ >
14
+ <Switch name="useSearch" bind:checked={$webSearchParameters.useSearch} on:click on:keypress />
15
+ <div class="whitespace-nowrap text-sm text-gray-800 dark:text-gray-200">Искать в интернете</div>
16
+ <div class="group relative w-max">
17
+ <CarbonInformation class="text-xs text-gray-500" />
18
+ <div
19
+ class="pointer-events-none absolute -top-20 left-1/2 w-max -translate-x-1/2 rounded-md bg-gray-100 p-2 opacity-0 transition-opacity group-hover:opacity-100 dark:bg-gray-800"
20
+ >
21
+ <p class="max-w-sm text-sm text-gray-800 dark:text-gray-200">
22
+ Если включено, то нейросеть дополнит свой ответ информацией, полученной из интернета.
23
+ </p>
24
+ </div>
25
+ </div>
26
+ </div>
chat-ui/src/lib/components/chat/ChatInput.svelte ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { createEventDispatcher, onMount } from "svelte";
3
+
4
+ export let value = "";
5
+ export let minRows = 1;
6
+ export let maxRows: null | number = null;
7
+ export let placeholder = "";
8
+ export let disabled = false;
9
+
10
+ // Approximate width from which we disable autofocus
11
+ const TABLET_VIEWPORT_WIDTH = 768;
12
+
13
+ let innerWidth = 0;
14
+ let textareaElement: HTMLTextAreaElement;
15
+
16
+ const dispatch = createEventDispatcher<{ submit: void }>();
17
+
18
+ $: minHeight = `${1 + minRows * 1.5}em`;
19
+ $: maxHeight = maxRows ? `${1 + maxRows * 1.5}em` : `auto`;
20
+
21
+ function handleKeydown(event: KeyboardEvent) {
22
+ // submit on enter
23
+ if (event.key === "Enter" && !event.shiftKey) {
24
+ event.preventDefault();
25
+ dispatch("submit"); // use a custom event instead of `event.target.form.requestSubmit()` as it does not work on Safari 14
26
+ }
27
+ }
28
+
29
+ onMount(() => {
30
+ if (innerWidth > TABLET_VIEWPORT_WIDTH) {
31
+ textareaElement.focus();
32
+ }
33
+ });
34
+ </script>
35
+
36
+ <svelte:window bind:innerWidth />
37
+
38
+ <div class="relative min-w-0 flex-1">
39
+ <pre
40
+ class="scrollbar-custom invisible overflow-x-hidden overflow-y-scroll whitespace-pre-wrap break-words p-3"
41
+ aria-hidden="true"
42
+ style="min-height: {minHeight}; max-height: {maxHeight}">{(value || " ") + "\n"}</pre>
43
+
44
+ <textarea
45
+ enterkeyhint="send"
46
+ tabindex="0"
47
+ rows="1"
48
+ class="scrollbar-custom absolute top-0 m-0 h-full w-full resize-none scroll-p-3 overflow-x-hidden overflow-y-scroll border-0 bg-transparent p-3 outline-none focus:ring-0 focus-visible:ring-0"
49
+ bind:value
50
+ bind:this={textareaElement}
51
+ {disabled}
52
+ on:keydown={handleKeydown}
53
+ on:keypress
54
+ {placeholder}
55
+ />
56
+ </div>
57
+
58
+ <style>
59
+ pre,
60
+ textarea {
61
+ font-family: inherit;
62
+ box-sizing: border-box;
63
+ line-height: 1.5;
64
+ }
65
+ </style>
chat-ui/src/lib/components/chat/ChatIntroduction.svelte ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { PUBLIC_APP_NAME, PUBLIC_VERSION } from "$env/static/public";
3
+ import { PUBLIC_ANNOUNCEMENT_BANNERS } from "$env/static/public";
4
+ import Logo from "$lib/components/icons/Logo.svelte";
5
+ import { createEventDispatcher } from "svelte";
6
+ import IconChevron from "$lib/components/icons/IconChevron.svelte";
7
+ import CarbonArrowUpRight from "~icons/carbon/arrow-up-right";
8
+ import AnnouncementBanner from "../AnnouncementBanner.svelte";
9
+ import ModelsModal from "../ModelsModal.svelte";
10
+ import type { Model } from "$lib/types/Model";
11
+ import ModelCardMetadata from "../ModelCardMetadata.svelte";
12
+ import type { LayoutData } from "../../../routes/$types";
13
+ import { findCurrentModel } from "$lib/utils/models";
14
+
15
+ export let currentModel: Model;
16
+ export let settings: LayoutData["settings"];
17
+ export let models: Model[];
18
+
19
+ let isModelsModalOpen = false;
20
+
21
+ $: currentModelMetadata = findCurrentModel(models, settings.activeModel);
22
+
23
+ const announcementBanners = PUBLIC_ANNOUNCEMENT_BANNERS
24
+ ? JSON.parse(PUBLIC_ANNOUNCEMENT_BANNERS)
25
+ : [];
26
+
27
+ const dispatch = createEventDispatcher<{ message: string }>();
28
+ </script>
29
+
30
+ <div class="my-auto grid gap-8 lg:grid-cols-3">
31
+
32
+
33
+ {#if currentModelMetadata.promptExamples && currentModelMetadata.promptExamples.length > 0}
34
+ <div class="lg:col-span-3 lg:mt-6">
35
+ <p class="mb-3 text-gray-600 dark:text-gray-300">Примеры запросов</p>
36
+ <div class="grid gap-3 lg:grid-cols-3 lg:gap-5">
37
+ {#each currentModelMetadata.promptExamples as example}
38
+ <button
39
+ type="button"
40
+ class="rounded-xl border bg-gray-50 p-2.5 text-gray-600 hover:bg-gray-100 dark:border-gray-800 dark:bg-gray-800 dark:text-gray-300 dark:hover:bg-gray-700 sm:p-4"
41
+ on:click={() => dispatch("message", example.prompt)}
42
+ >
43
+ {example.title}
44
+ </button>
45
+ {/each}
46
+ </div>
47
+ </div>{/if}
48
+ </div>
chat-ui/src/lib/components/chat/ChatMessage.svelte ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import { marked } from "marked";
3
+ import markedKatex from "marked-katex-extension";
4
+ import type { Message } from "$lib/types/Message";
5
+ import { afterUpdate, createEventDispatcher } from "svelte";
6
+ import { deepestChild } from "$lib/utils/deepestChild";
7
+ import { page } from "$app/stores";
8
+
9
+ import CodeBlock from "../CodeBlock.svelte";
10
+ import IconLoading from "../icons/IconLoading.svelte";
11
+ import CarbonRotate360 from "~icons/carbon/rotate-360";
12
+ import CarbonDownload from "~icons/carbon/download";
13
+ import CarbonThumbsUp from "~icons/carbon/thumbs-up";
14
+ import CarbonThumbsDown from "~icons/carbon/thumbs-down";
15
+ import { PUBLIC_SEP_TOKEN } from "$lib/constants/publicSepToken";
16
+ import type { Model } from "$lib/types/Model";
17
+
18
+ import OpenWebSearchResults from "../OpenWebSearchResults.svelte";
19
+ import type { WebSearchUpdate } from "$lib/types/MessageUpdate";
20
+
21
+ function sanitizeMd(md: string) {
22
+ let ret = md
23
+ .replace(/<\|[a-z]*$/, "")
24
+ .replace(/<\|[a-z]+\|$/, "")
25
+ .replace(/<$/, "")
26
+ .replaceAll(PUBLIC_SEP_TOKEN, " ")
27
+ .replaceAll(/<\|[a-z]+\|>/g, " ")
28
+ .replaceAll(/<br\s?\/?>/gi, "\n")
29
+ .replaceAll("<", "&lt;")
30
+ .trim();
31
+
32
+ for (const stop of [...(model.parameters?.stop ?? []), "<|endoftext|>"]) {
33
+ if (ret.endsWith(stop)) {
34
+ ret = ret.slice(0, -stop.length).trim();
35
+ }
36
+ }
37
+
38
+ return ret;
39
+ }
40
+ function unsanitizeMd(md: string) {
41
+ return md.replaceAll("&lt;", "<");
42
+ }
43
+
44
+ export let model: Model;
45
+ export let message: Message;
46
+ export let loading = false;
47
+ export let isAuthor = true;
48
+ export let readOnly = false;
49
+ export let isTapped = false;
50
+
51
+ export let webSearchMessages: WebSearchUpdate[];
52
+
53
+ const dispatch = createEventDispatcher<{
54
+ retry: { content: string; id: Message["id"] };
55
+ vote: { score: Message["score"]; id: Message["id"] };
56
+ }>();
57
+
58
+ let contentEl: HTMLElement;
59
+ let loadingEl: IconLoading;
60
+ let pendingTimeout: ReturnType<typeof setTimeout>;
61
+
62
+ const renderer = new marked.Renderer();
63
+ // For code blocks with simple backticks
64
+ renderer.codespan = (code) => {
65
+ // Unsanitize double-sanitized code
66
+ return `<code>${code.replaceAll("&amp;", "&")}</code>`;
67
+ };
68
+
69
+ // eslint-disable-next-line @typescript-eslint/no-unused-vars
70
+ const { extensions, ...defaults } = marked.getDefaults() as marked.MarkedOptions & {
71
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
72
+ extensions: any;
73
+ };
74
+ const options: marked.MarkedOptions = {
75
+ ...defaults,
76
+ gfm: true,
77
+ breaks: true,
78
+ renderer,
79
+ };
80
+
81
+ marked.use(
82
+ markedKatex({
83
+ throwOnError: false,
84
+ // output: "html",
85
+ })
86
+ );
87
+
88
+ $: tokens = marked.lexer(sanitizeMd(message.content));
89
+
90
+ afterUpdate(() => {
91
+ loadingEl?.$destroy();
92
+ clearTimeout(pendingTimeout);
93
+
94
+ // Add loading animation to the last message if update takes more than 600ms
95
+ if (loading) {
96
+ pendingTimeout = setTimeout(() => {
97
+ if (contentEl) {
98
+ loadingEl = new IconLoading({
99
+ target: deepestChild(contentEl),
100
+ props: { classNames: "loading inline ml-2" },
101
+ });
102
+ }
103
+ }, 600);
104
+ }
105
+ });
106
+
107
+ let searchUpdates: WebSearchUpdate[] = [];
108
+
109
+ $: searchUpdates = ((webSearchMessages.length > 0
110
+ ? webSearchMessages
111
+ : message.updates?.filter(({ type }) => type === "webSearch")) ?? []) as WebSearchUpdate[];
112
+
113
+ $: downloadLink =
114
+ message.from === "user" ? `${$page.url.pathname}/message/${message.id}/prompt` : undefined;
115
+
116
+ let webSearchIsDone = true;
117
+
118
+ $: webSearchIsDone =
119
+ searchUpdates.length > 0 && searchUpdates[searchUpdates.length - 1].messageType === "sources";
120
+
121
+ $: webSearchSources =
122
+ searchUpdates &&
123
+ searchUpdates?.filter(({ messageType }) => messageType === "sources")?.[0]?.sources;
124
+ </script>
125
+
126
+ {#if message.from === "assistant"}
127
+ <div
128
+ class="group relative -mb-8 flex items-start justify-start gap-4 pb-8 leading-relaxed"
129
+ on:click={() => (isTapped = !isTapped)}
130
+ on:keypress={() => (isTapped = !isTapped)}
131
+ >
132
+ <img
133
+ alt=""
134
+ src="https://huggingface.co/avatars/2edb18bd0206c16b433841a47f53fa8e.svg"
135
+ class="mt-5 h-3 w-3 flex-none select-none rounded-full shadow-lg"
136
+ />
137
+ <div
138
+ class="relative min-h-[calc(2rem+theme(spacing[3.5])*2)] min-w-[60px] break-words rounded-2xl border border-gray-100 bg-gradient-to-br from-gray-50 px-5 py-3.5 text-gray-600 prose-pre:my-2 dark:border-gray-800 dark:from-gray-800/40 dark:text-gray-300"
139
+ >
140
+ {#if searchUpdates && searchUpdates.length > 0}
141
+ <OpenWebSearchResults
142
+ classNames={tokens.length ? "mb-3.5" : ""}
143
+ webSearchMessages={searchUpdates}
144
+ loading={!(searchUpdates[searchUpdates.length - 1]?.messageType === "sources")}
145
+ />
146
+ {/if}
147
+ {#if !message.content && (webSearchIsDone || (webSearchMessages && webSearchMessages.length === 0))}
148
+ <IconLoading />
149
+ {/if}
150
+
151
+ <div
152
+ class="prose max-w-none dark:prose-invert max-sm:prose-sm prose-headings:font-semibold prose-h1:text-lg prose-h2:text-base prose-h3:text-base prose-pre:bg-gray-800 dark:prose-pre:bg-gray-900"
153
+ bind:this={contentEl}
154
+ >
155
+ {#each tokens as token}
156
+ {#if token.type === "code"}
157
+ <CodeBlock lang={token.lang} code={unsanitizeMd(token.text)} />
158
+ {:else}
159
+ <!-- eslint-disable-next-line svelte/no-at-html-tags -->
160
+ {@html marked.parse(token.raw, options)}
161
+ {/if}
162
+ {/each}
163
+ </div>
164
+ <!-- Web Search sources -->
165
+ {#if webSearchSources?.length}
166
+ <div class="mt-4 flex flex-wrap items-center gap-x-2 gap-y-1.5 text-sm">
167
+ <div class="text-gray-400">Источники:</div>
168
+ {#each webSearchSources as { link, title, hostname }}
169
+ <a
170
+ class="flex items-center gap-2 whitespace-nowrap rounded-lg border bg-white px-2 py-1.5 leading-none hover:border-gray-300 dark:border-gray-800 dark:bg-gray-900 dark:hover:border-gray-700"
171
+ href={link}
172
+ target="_blank"
173
+ >
174
+ <img
175
+ class="h-3.5 w-3.5 rounded"
176
+ src="https://www.google.com/s2/favicons?sz=64&domain_url={hostname}"
177
+ alt="{title} favicon"
178
+ />
179
+ <div>{hostname.replace(/^www\./, "")}</div>
180
+ </a>
181
+ {/each}
182
+ </div>
183
+ {/if}
184
+ </div>
185
+ </div>
186
+ {/if}
187
+ {#if message.from === "user"}
188
+ <div class="group relative flex items-start justify-start gap-4 max-sm:text-sm">
189
+ <div class="mt-5 h-3 w-3 flex-none rounded-full" />
190
+ <div
191
+ class="max-w-full whitespace-break-spaces break-words rounded-2xl px-5 py-3.5 text-gray-500 dark:text-gray-400"
192
+ >
193
+ {message.content.trim()}
194
+ </div>
195
+ </div>
196
+ {/if}
chat-ui/src/lib/components/chat/ChatMessages.svelte ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import type { Message } from "$lib/types/Message";
3
+ import { snapScrollToBottom } from "$lib/actions/snapScrollToBottom";
4
+ import ScrollToBottomBtn from "$lib/components/ScrollToBottomBtn.svelte";
5
+ import { tick } from "svelte";
6
+ import { randomUUID } from "$lib/utils/randomUuid";
7
+ import type { Model } from "$lib/types/Model";
8
+ import type { LayoutData } from "../../../routes/$types";
9
+ import ChatIntroduction from "./ChatIntroduction.svelte";
10
+ import ChatMessage from "./ChatMessage.svelte";
11
+ import type { WebSearchUpdate } from "$lib/types/MessageUpdate";
12
+ import { browser } from "$app/environment";
13
+
14
+ export let messages: Message[];
15
+ export let loading: boolean;
16
+ export let pending: boolean;
17
+ export let isAuthor: boolean;
18
+ export let currentModel: Model;
19
+ export let settings: LayoutData["settings"];
20
+ export let models: Model[];
21
+ export let readOnly: boolean;
22
+
23
+ let chatContainer: HTMLElement;
24
+
25
+ export let webSearchMessages: WebSearchUpdate[] = [];
26
+
27
+ async function scrollToBottom() {
28
+ await tick();
29
+ chatContainer.scrollTop = chatContainer.scrollHeight;
30
+ }
31
+
32
+ // If last message is from user, scroll to bottom
33
+ $: if (browser && messages[messages.length - 1]?.from === "user") {
34
+ scrollToBottom();
35
+ }
36
+ </script>
37
+
38
+ <div
39
+ class="scrollbar-custom mr-1 h-full overflow-y-auto"
40
+ use:snapScrollToBottom={messages.length ? [...messages, ...webSearchMessages] : false}
41
+ bind:this={chatContainer}
42
+ >
43
+ <div class="mx-auto flex h-full max-w-3xl flex-col gap-6 px-5 pt-6 sm:gap-8 xl:max-w-4xl">
44
+ {#each messages as message, i}
45
+ <ChatMessage
46
+ loading={loading && i === messages.length - 1}
47
+ {message}
48
+ {isAuthor}
49
+ {readOnly}
50
+ model={currentModel}
51
+ webSearchMessages={i === messages.length - 1 ? webSearchMessages : []}
52
+ on:retry
53
+ on:vote
54
+ />
55
+ {:else}
56
+ <ChatIntroduction {settings} {models} {currentModel} on:message />
57
+ {/each}
58
+ {#if pending}
59
+ <ChatMessage
60
+ message={{ from: "assistant", content: "", id: randomUUID() }}
61
+ model={currentModel}
62
+ {webSearchMessages}
63
+ />
64
+ {/if}
65
+ <div class="h-44 flex-none" />
66
+ </div>
67
+ <ScrollToBottomBtn
68
+ class="bottom-36 right-4 max-md:hidden lg:right-10"
69
+ scrollNode={chatContainer}
70
+ />
71
+ </div>
chat-ui/src/lib/components/chat/ChatWindow.svelte ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ import type { Message } from "$lib/types/Message";
3
+ import { createEventDispatcher } from "svelte";
4
+
5
+ import CarbonSendAltFilled from "~icons/carbon/send-alt-filled";
6
+ import CarbonExport from "~icons/carbon/export";
7
+ import CarbonStopFilledAlt from "~icons/carbon/stop-filled-alt";
8
+ import EosIconsLoading from "~icons/eos-icons/loading";
9
+
10
+ import ChatMessages from "./ChatMessages.svelte";
11
+ import ChatInput from "./ChatInput.svelte";
12
+ import StopGeneratingBtn from "../StopGeneratingBtn.svelte";
13
+ import type { Model } from "$lib/types/Model";
14
+ import type { LayoutData } from "../../../routes/$types";
15
+ import WebSearchToggle from "../WebSearchToggle.svelte";
16
+ import LoginModal from "../LoginModal.svelte";
17
+ import type { WebSearchUpdate } from "$lib/types/MessageUpdate";
18
+
19
+ export let messages: Message[] = [];
20
+ export let loading = false;
21
+ export let pending = false;
22
+ export let shared = false;
23
+ export let currentModel: Model;
24
+ export let models: Model[];
25
+ export let settings: LayoutData["settings"];
26
+ export let webSearchMessages: WebSearchUpdate[] = [];
27
+
28
+ export let loginRequired = false;
29
+ $: isReadOnly = !models.some((model) => model.id === currentModel.id);
30
+
31
+ let loginModalOpen = false;
32
+ let message: string;
33
+
34
+ const dispatch = createEventDispatcher<{
35
+ message: string;
36
+ share: void;
37
+ stop: void;
38
+ retry: { id: Message["id"]; content: string };
39
+ }>();
40
+
41
+ const handleSubmit = () => {
42
+ if (loading) return;
43
+ dispatch("message", message);
44
+ message = "";
45
+ };
46
+ </script>
47
+
48
+ <div class="relative min-h-0 min-w-0">
49
+ {#if loginModalOpen}
50
+ <LoginModal {settings} on:close={() => (loginModalOpen = false)} />
51
+ {/if}
52
+ <ChatMessages
53
+ {loading}
54
+ {pending}
55
+ {settings}
56
+ {currentModel}
57
+ {models}
58
+ {messages}
59
+ readOnly={isReadOnly}
60
+ isAuthor={!shared}
61
+ {webSearchMessages}
62
+ on:message
63
+ on:vote
64
+ on:retry={(ev) => {
65
+ if (!loading) dispatch("retry", ev.detail);
66
+ }}
67
+ />
68
+ <div
69
+ class="dark:via-gray-80 pointer-events-none absolute inset-x-0 bottom-0 z-0 mx-auto flex w-full max-w-3xl flex-col items-center justify-center bg-gradient-to-t from-white via-white/80 to-white/0 px-3.5 py-4 dark:border-gray-800 dark:from-gray-900 dark:to-gray-900/0 max-md:border-t max-md:bg-white max-md:dark:bg-gray-900 sm:px-5 md:py-8 xl:max-w-4xl [&>*]:pointer-events-auto"
70
+ >
71
+ <div class="flex w-full pb-3 max-md:justify-between">
72
+ {#if settings?.searchEnabled}
73
+ <WebSearchToggle />
74
+ {/if}
75
+ {#if loading}
76
+ <StopGeneratingBtn
77
+ classNames={settings?.searchEnabled ? "md:-translate-x-1/2 md:mx-auto" : "mx-auto"}
78
+ on:click={() => dispatch("stop")}
79
+ />
80
+ {/if}
81
+ </div>
82
+ <form
83
+ on:submit|preventDefault={handleSubmit}
84
+ class="relative flex w-full max-w-4xl flex-1 items-center rounded-xl border bg-gray-100 focus-within:border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:focus-within:border-gray-500
85
+ {isReadOnly ? 'opacity-30' : ''}"
86
+ >
87
+ <div class="flex w-full flex-1 border-none bg-transparent">
88
+ <ChatInput
89
+ placeholder="Введите запрос"
90
+ bind:value={message}
91
+ on:submit={handleSubmit}
92
+ on:keypress={() => {
93
+ if (loginRequired) loginModalOpen = true;
94
+ }}
95
+ maxRows={4}
96
+ disabled={isReadOnly}
97
+ />
98
+
99
+ {#if loading}
100
+ <button
101
+ class="btn mx-1 my-1 inline-block h-[2.4rem] self-end rounded-lg bg-transparent p-1 px-[0.7rem] text-gray-400 disabled:opacity-60 enabled:hover:text-gray-700 dark:disabled:opacity-40 enabled:dark:hover:text-gray-100 md:hidden"
102
+ on:click={() => dispatch("stop")}
103
+ >
104
+ <CarbonStopFilledAlt />
105
+ </button>
106
+ <div
107
+ class="mx-1 my-1 hidden h-[2.4rem] items-center p-1 px-[0.7rem] text-gray-400 disabled:opacity-60 enabled:hover:text-gray-700 dark:disabled:opacity-40 enabled:dark:hover:text-gray-100 md:flex"
108
+ >
109
+ <EosIconsLoading />
110
+ </div>
111
+ {:else}
112
+ <button
113
+ class="btn mx-1 my-1 h-[2.4rem] self-end rounded-lg bg-transparent p-1 px-[0.7rem] text-gray-400 disabled:opacity-60 enabled:hover:text-gray-700 dark:disabled:opacity-40 enabled:dark:hover:text-gray-100"
114
+ disabled={!message || isReadOnly}
115
+ type="submit"
116
+ >
117
+ <CarbonSendAltFilled />
118
+ </button>
119
+ {/if}
120
+ </div>
121
+ </form>
122
+
123
+ </div>
124
+ </div>
chat-ui/src/lib/components/icons/IconChevron.svelte ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ export let classNames = "";
3
+ </script>
4
+
5
+ <svg
6
+ width="1em"
7
+ height="1em"
8
+ viewBox="0 0 15 6"
9
+ class={classNames}
10
+ fill="none"
11
+ xmlns="http://www.w3.org/2000/svg"
12
+ >
13
+ <path
14
+ d="M1.67236 1L7.67236 7L13.6724 1"
15
+ stroke="currentColor"
16
+ stroke-width="2"
17
+ stroke-linecap="round"
18
+ stroke-linejoin="round"
19
+ />
20
+ </svg>
chat-ui/src/lib/components/icons/IconCopy.svelte ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ export let classNames = "";
3
+ </script>
4
+
5
+ <svg
6
+ class={classNames}
7
+ xmlns="http://www.w3.org/2000/svg"
8
+ aria-hidden="true"
9
+ fill="currentColor"
10
+ focusable="false"
11
+ role="img"
12
+ width="1em"
13
+ height="1em"
14
+ preserveAspectRatio="xMidYMid meet"
15
+ viewBox="0 0 32 32"
16
+ >
17
+ <path
18
+ d="M28,10V28H10V10H28m0-2H10a2,2,0,0,0-2,2V28a2,2,0,0,0,2,2H28a2,2,0,0,0,2-2V10a2,2,0,0,0-2-2Z"
19
+ transform="translate(0)"
20
+ />
21
+ <path d="M4,18H2V4A2,2,0,0,1,4,2H18V4H4Z" transform="translate(0)" /><rect
22
+ fill="none"
23
+ width="32"
24
+ height="32"
25
+ />
26
+ </svg>
chat-ui/src/lib/components/icons/IconDazzled.svelte ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ export let classNames = "";
3
+ </script>
4
+
5
+ <svg
6
+ xmlns="http://www.w3.org/2000/svg"
7
+ width="1em"
8
+ height="1em"
9
+ class={classNames}
10
+ fill="none"
11
+ viewBox="0 0 26 23"
12
+ >
13
+ <path
14
+ fill="url(#a)"
15
+ d="M.93 10.65A10.17 10.17 0 0 1 11.11.48h4.67a9.45 9.45 0 0 1 0 18.89H4.53L1.62 22.2a.38.38 0 0 1-.69-.28V10.65Z"
16
+ />
17
+ <path
18
+ fill="#000"
19
+ fill-rule="evenodd"
20
+ d="M11.52 7.4a1.86 1.86 0 1 1-3.72 0 1.86 1.86 0 0 1 3.72 0Zm7.57 0a1.86 1.86 0 1 1-3.73 0 1.86 1.86 0 0 1 3.73 0ZM8.9 12.9a.55.55 0 0 0-.11.35.76.76 0 0 1-1.51 0c0-.95.67-1.94 1.76-1.94 1.09 0 1.76 1 1.76 1.94H9.3a.55.55 0 0 0-.12-.35c-.06-.07-.1-.08-.13-.08s-.08 0-.14.08Zm4.04 0a.55.55 0 0 0-.12.35h-1.51c0-.95.68-1.94 1.76-1.94 1.1 0 1.77 1 1.77 1.94h-1.51a.55.55 0 0 0-.12-.35c-.06-.07-.11-.08-.14-.08-.02 0-.07 0-.13.08Zm-1.89.79c-.02 0-.07-.01-.13-.08a.55.55 0 0 1-.12-.36h-1.5c0 .95.67 1.95 1.75 1.95 1.1 0 1.77-1 1.77-1.95h-1.51c0 .16-.06.28-.12.36-.06.07-.11.08-.14.08Zm4.04 0c-.03 0-.08-.01-.14-.08a.55.55 0 0 1-.12-.36h-1.5c0 .95.67 1.95 1.76 1.95 1.08 0 1.76-1 1.76-1.95h-1.51c0 .16-.06.28-.12.36-.06.07-.11.08-.13.08Zm1.76-.44c0-.16.05-.28.12-.35.06-.07.1-.08.13-.08s.08 0 .14.08c.06.07.11.2.11.35a.76.76 0 0 0 1.51 0c0-.95-.67-1.94-1.76-1.94-1.09 0-1.76 1-1.76 1.94h1.5Z"
21
+ clip-rule="evenodd"
22
+ />
23
+ <defs>
24
+ <radialGradient
25
+ id="a"
26
+ cx="0"
27
+ cy="0"
28
+ r="1"
29
+ gradientTransform="matrix(0 31.37 -34.85 0 13.08 -9.02)"
30
+ gradientUnits="userSpaceOnUse"
31
+ >
32
+ <stop stop-color="#FFD21E" />
33
+ <stop offset="1" stop-color="red" />
34
+ </radialGradient>
35
+ </defs>
36
+ </svg>
chat-ui/src/lib/components/icons/IconLoading.svelte ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <script lang="ts">
2
+ export let classNames = "";
3
+ </script>
4
+
5
+ <div class={"inline-flex h-8 flex-none items-center gap-1 " + classNames}>
6
+ <div
7
+ class="h-1 w-1 flex-none animate-bounce rounded-full bg-gray-500 dark:bg-gray-400"
8
+ style="animation-delay: 0.25s;"
9
+ />
10
+ <div
11
+ class="h-1 w-1 flex-none animate-bounce rounded-full bg-gray-500 dark:bg-gray-400"
12
+ style="animation-delay: 0.5s;"
13
+ />
14
+ <div
15
+ class="h-1 w-1 flex-none animate-bounce rounded-full bg-gray-500 dark:bg-gray-400"
16
+ style="animation-delay: 0.75s;"
17
+ />
18
+ </div>