Chat.svelte 12 KB

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