Chat.svelte 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379
  1. <script lang="ts">
  2. export let show = false;
  3. export let selectedModelId = '';
  4. import { marked } from 'marked';
  5. import { toast } from 'svelte-sonner';
  6. import { goto } from '$app/navigation';
  7. import { onMount, tick, getContext } from 'svelte';
  8. import {
  9. OLLAMA_API_BASE_URL,
  10. OPENAI_API_BASE_URL,
  11. WEBUI_API_BASE_URL,
  12. WEBUI_BASE_URL
  13. } from '$lib/constants';
  14. import { WEBUI_NAME, config, user, models, settings } from '$lib/stores';
  15. import { chatCompletion, generateOpenAIChatCompletion } from '$lib/apis/openai';
  16. import { splitStream } from '$lib/utils';
  17. import Messages from '$lib/components/notes/NoteEditor/Chat/Messages.svelte';
  18. import MessageInput from '$lib/components/channel/MessageInput.svelte';
  19. import XMark from '$lib/components/icons/XMark.svelte';
  20. import Tooltip from '$lib/components/common/Tooltip.svelte';
  21. import Pencil from '$lib/components/icons/Pencil.svelte';
  22. import PencilSquare from '$lib/components/icons/PencilSquare.svelte';
  23. const i18n = getContext('i18n');
  24. export let enhancing = false;
  25. export let streaming = false;
  26. export let stopResponseFlag = false;
  27. export let note = null;
  28. export let files = [];
  29. export let messages = [];
  30. export let onInsert = (content) => {};
  31. export let onStop = () => {};
  32. export let scrollToBottomHandler = () => {};
  33. let loaded = false;
  34. let loading = false;
  35. let messagesContainerElement: HTMLDivElement;
  36. let system = '';
  37. let editorEnabled = false;
  38. let chatInputElement = null;
  39. const DEFAULT_DOCUMENT_EDITOR_PROMPT = `You are an expert document editor.
  40. ## Task
  41. Based on the user's instruction, update and enhance the existing notes by incorporating relevant and accurate information from the provided context. Ensure all edits strictly follow the user’s intent.
  42. ## Input Structure
  43. - Existing notes: Enclosed within <notes></notes> XML tags.
  44. - Additional context: Enclosed within <context></context> XML tags.
  45. - Editing instruction: Provided in the user message.
  46. ## Output Instructions
  47. - Deliver a single, rewritten version of the notes in markdown format.
  48. - Integrate information from the context only if it directly supports the user's instruction.
  49. - Use clear, organized markdown elements: headings, bullet points, numbered lists, bold and italic text as appropriate.
  50. - Focus on improving clarity, completeness, and usefulness of the notes.
  51. - Return only the final, fully-edited markdown notes—do not include explanations, reasoning, or XML tags.
  52. `;
  53. let scrolledToBottom = true;
  54. const scrollToBottom = () => {
  55. if (messagesContainerElement) {
  56. if (scrolledToBottom) {
  57. messagesContainerElement.scrollTop = messagesContainerElement.scrollHeight;
  58. }
  59. }
  60. };
  61. const onScroll = () => {
  62. if (messagesContainerElement) {
  63. scrolledToBottom =
  64. messagesContainerElement.scrollHeight - messagesContainerElement.scrollTop <=
  65. messagesContainerElement.clientHeight + 10;
  66. }
  67. };
  68. const chatCompletionHandler = async () => {
  69. if (selectedModelId === '') {
  70. toast.error($i18n.t('Please select a model.'));
  71. return;
  72. }
  73. const model = $models.find((model) => model.id === selectedModelId);
  74. if (!model) {
  75. selectedModelId = '';
  76. return;
  77. }
  78. let responseMessage;
  79. if (messages.at(-1)?.role === 'assistant') {
  80. responseMessage = messages.at(-1);
  81. } else {
  82. responseMessage = {
  83. role: 'assistant',
  84. content: '',
  85. done: false
  86. };
  87. messages.push(responseMessage);
  88. messages = messages;
  89. }
  90. await tick();
  91. scrollToBottom();
  92. let enhancedContent = {
  93. json: null,
  94. html: '',
  95. md: ''
  96. };
  97. system = '';
  98. if (editorEnabled) {
  99. system = `${DEFAULT_DOCUMENT_EDITOR_PROMPT}\n\n`;
  100. } else {
  101. system = `You are a helpful assistant. Please answer the user's questions based on the context provided.\n\n`;
  102. }
  103. system +=
  104. `<notes>${note?.data?.content?.md ?? ''}</notes>` +
  105. (files && files.length > 0
  106. ? `\n<context>${files.map((file) => `${file.name}: ${file?.file?.data?.content ?? 'Could not extract content'}\n`).join('')}</context>`
  107. : '');
  108. const chatMessages = JSON.parse(
  109. JSON.stringify([
  110. {
  111. role: 'system',
  112. content: `${system}`
  113. },
  114. ...messages
  115. ])
  116. );
  117. const [res, controller] = await chatCompletion(
  118. localStorage.token,
  119. {
  120. model: model.id,
  121. stream: true,
  122. messages: chatMessages
  123. // ...(files && files.length > 0 ? { files } : {}) // TODO: Decide whether to use native file handling or not
  124. },
  125. `${WEBUI_BASE_URL}/api`
  126. );
  127. await tick();
  128. scrollToBottom();
  129. let messageContent = '';
  130. if (res && res.ok) {
  131. const reader = res.body
  132. .pipeThrough(new TextDecoderStream())
  133. .pipeThrough(splitStream('\n'))
  134. .getReader();
  135. while (true) {
  136. const { value, done } = await reader.read();
  137. if (done || stopResponseFlag) {
  138. if (stopResponseFlag) {
  139. controller.abort('User: Stop Response');
  140. }
  141. if (editorEnabled) {
  142. enhancing = false;
  143. streaming = false;
  144. }
  145. break;
  146. }
  147. try {
  148. let lines = value.split('\n');
  149. for (const line of lines) {
  150. if (line !== '') {
  151. console.log(line);
  152. if (line === 'data: [DONE]') {
  153. if (editorEnabled) {
  154. responseMessage.content = '<status title="Edited" done="true" />';
  155. }
  156. responseMessage.done = true;
  157. messages = messages;
  158. } else {
  159. let data = JSON.parse(line.replace(/^data: /, ''));
  160. console.log(data);
  161. let deltaContent = data.choices[0]?.delta?.content ?? '';
  162. if (responseMessage.content == '' && deltaContent == '\n') {
  163. continue;
  164. } else {
  165. if (editorEnabled) {
  166. enhancing = true;
  167. streaming = true;
  168. enhancedContent.md += deltaContent;
  169. enhancedContent.html = marked.parse(enhancedContent.md);
  170. note.data.content.md = enhancedContent.md;
  171. note.data.content.html = enhancedContent.html;
  172. note.data.content.json = null;
  173. responseMessage.content = '<status title="Editing" done="false" />';
  174. scrollToBottomHandler();
  175. messages = messages;
  176. } else {
  177. messageContent += deltaContent;
  178. responseMessage.content = messageContent;
  179. messages = messages;
  180. }
  181. await tick();
  182. }
  183. }
  184. }
  185. }
  186. } catch (error) {
  187. console.log(error);
  188. }
  189. scrollToBottom();
  190. }
  191. }
  192. };
  193. const submitHandler = async (e) => {
  194. const { content, data } = e;
  195. if (selectedModelId && content) {
  196. messages.push({
  197. role: 'user',
  198. content: content
  199. });
  200. messages = messages;
  201. await tick();
  202. scrollToBottom();
  203. loading = true;
  204. await chatCompletionHandler();
  205. messages = messages.map((message) => {
  206. message.done = true;
  207. return message;
  208. });
  209. loading = false;
  210. stopResponseFlag = false;
  211. }
  212. };
  213. onMount(async () => {
  214. if ($user?.role !== 'admin') {
  215. await goto('/');
  216. }
  217. if ($settings?.models) {
  218. selectedModelId = $settings?.models[0];
  219. } else if ($config?.default_models) {
  220. selectedModelId = $config?.default_models.split(',')[0];
  221. } else {
  222. selectedModelId = '';
  223. }
  224. loaded = true;
  225. scrollToBottom();
  226. });
  227. </script>
  228. <div class="flex items-center mb-2 pt-1">
  229. <div class=" -translate-x-1.5 flex items-center">
  230. <button
  231. class="p-0.5 bg-transparent transition rounded-lg"
  232. on:click={() => {
  233. show = !show;
  234. }}
  235. >
  236. <XMark className="size-5" strokeWidth="2.5" />
  237. </button>
  238. </div>
  239. <div class=" font-medium text-base flex items-center gap-1">
  240. <div>
  241. {$i18n.t('Chat')}
  242. </div>
  243. <div>
  244. <Tooltip
  245. content={$i18n.t(
  246. 'This feature is experimental and may be modified or discontinued without notice.'
  247. )}
  248. position="top"
  249. className="inline-block"
  250. >
  251. <span class="text-gray-500 text-sm">({$i18n.t('Experimental')})</span>
  252. </Tooltip>
  253. </div>
  254. </div>
  255. </div>
  256. <div class="flex flex-col items-center mb-2 flex-1 @container">
  257. <div class=" flex flex-col justify-between w-full overflow-y-auto h-full">
  258. <div class="mx-auto w-full md:px-0 h-full relative">
  259. <div class=" flex flex-col h-full">
  260. <div
  261. class=" pb-2.5 flex flex-col justify-between w-full flex-auto overflow-auto h-0"
  262. id="messages-container"
  263. bind:this={messagesContainerElement}
  264. on:scroll={onScroll}
  265. >
  266. <div class=" h-full w-full flex flex-col">
  267. <div class="flex-1 p-1">
  268. <Messages bind:messages {onInsert} />
  269. </div>
  270. </div>
  271. </div>
  272. <div class=" pb-2">
  273. <MessageInput
  274. bind:chatInputElement
  275. acceptFiles={false}
  276. inputLoading={loading}
  277. onSubmit={submitHandler}
  278. {onStop}
  279. >
  280. <div slot="menu" class="flex items-center justify-between gap-2 w-full pr-2">
  281. <div>
  282. <Tooltip content={$i18n.t('Edit')} placement="top">
  283. <button
  284. on:click|preventDefault={() => (editorEnabled = !editorEnabled)}
  285. type="button"
  286. class="px-2 @xl:px-2.5 py-2 flex gap-1.5 items-center text-sm rounded-full transition-colors duration-300 focus:outline-hidden max-w-full overflow-hidden hover:bg-gray-50 dark:hover:bg-gray-800 {editorEnabled
  287. ? ' text-sky-500 dark:text-sky-300 bg-sky-50 dark:bg-sky-200/5'
  288. : 'bg-transparent text-gray-600 dark:text-gray-300 '}"
  289. >
  290. <PencilSquare className="size-4" strokeWidth="1.75" />
  291. <span
  292. class="block whitespace-nowrap overflow-hidden text-ellipsis leading-none pr-0.5"
  293. >{$i18n.t('Edit')}</span
  294. >
  295. </button>
  296. </Tooltip>
  297. </div>
  298. <Tooltip content={selectedModelId}>
  299. <select
  300. class=" bg-transparent rounded-lg py-1 px-2 -mx-0.5 text-sm outline-hidden w-20"
  301. bind:value={selectedModelId}
  302. >
  303. {#each $models as model}
  304. <option value={model.id} class="bg-gray-50 dark:bg-gray-700"
  305. >{model.name}</option
  306. >
  307. {/each}
  308. </select>
  309. </Tooltip>
  310. </div>
  311. </MessageInput>
  312. </div>
  313. </div>
  314. </div>
  315. </div>
  316. </div>