ResponseMessage.svelte 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053
  1. <script lang="ts">
  2. import { toast } from 'svelte-sonner';
  3. import dayjs from 'dayjs';
  4. import { marked } from 'marked';
  5. import tippy from 'tippy.js';
  6. import auto_render from 'katex/dist/contrib/auto-render.mjs';
  7. import 'katex/dist/katex.min.css';
  8. import mermaid from 'mermaid';
  9. import { fade } from 'svelte/transition';
  10. import { createEventDispatcher } from 'svelte';
  11. import { onMount, tick, getContext } from 'svelte';
  12. const i18n = getContext('i18n');
  13. const dispatch = createEventDispatcher();
  14. import { config, models, settings, user } from '$lib/stores';
  15. import { synthesizeOpenAISpeech } from '$lib/apis/audio';
  16. import { imageGenerations } from '$lib/apis/images';
  17. import {
  18. approximateToHumanReadable,
  19. extractSentences,
  20. replaceTokens,
  21. revertSanitizedResponseContent,
  22. sanitizeResponseContent
  23. } from '$lib/utils';
  24. import { WEBUI_BASE_URL } from '$lib/constants';
  25. import Name from './Name.svelte';
  26. import ProfileImage from './ProfileImage.svelte';
  27. import Skeleton from './Skeleton.svelte';
  28. import CodeBlock from './CodeBlock.svelte';
  29. import Image from '$lib/components/common/Image.svelte';
  30. import Tooltip from '$lib/components/common/Tooltip.svelte';
  31. import RateComment from './RateComment.svelte';
  32. import CitationsModal from '$lib/components/chat/Messages/CitationsModal.svelte';
  33. import Spinner from '$lib/components/common/Spinner.svelte';
  34. import WebSearchResults from './ResponseMessage/WebSearchResults.svelte';
  35. export let message;
  36. export let siblings;
  37. export let isLastMessage = true;
  38. export let readOnly = false;
  39. export let updateChatMessages: Function;
  40. export let confirmEditResponseMessage: Function;
  41. export let showPreviousMessage: Function;
  42. export let showNextMessage: Function;
  43. export let rateMessage: Function;
  44. export let copyToClipboard: Function;
  45. export let continueGeneration: Function;
  46. export let regenerateResponse: Function;
  47. let model = null;
  48. $: model = $models.find((m) => m.id === message.model);
  49. let edit = false;
  50. let editedContent = '';
  51. let editTextAreaElement: HTMLTextAreaElement;
  52. let tooltipInstance = null;
  53. let sentencesAudio = {};
  54. let speaking = null;
  55. let speakingIdx = null;
  56. let loadingSpeech = false;
  57. let generatingImage = false;
  58. let showRateComment = false;
  59. let showCitationModal = false;
  60. let selectedCitation = null;
  61. $: tokens = marked.lexer(
  62. replaceTokens(sanitizeResponseContent(message?.content), model?.name, $user?.name)
  63. );
  64. const renderer = new marked.Renderer();
  65. // For code blocks with simple backticks
  66. renderer.codespan = (code) => {
  67. return `<code>${code.replaceAll('&amp;', '&')}</code>`;
  68. };
  69. // Open all links in a new tab/window (from https://github.com/markedjs/marked/issues/655#issuecomment-383226346)
  70. const origLinkRenderer = renderer.link;
  71. renderer.link = (href, title, text) => {
  72. const html = origLinkRenderer.call(renderer, href, title, text);
  73. return html.replace(/^<a /, '<a target="_blank" rel="nofollow" ');
  74. };
  75. const { extensions, ...defaults } = marked.getDefaults() as marked.MarkedOptions & {
  76. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  77. extensions: any;
  78. };
  79. $: if (message) {
  80. renderStyling();
  81. }
  82. const renderStyling = async () => {
  83. await tick();
  84. if (tooltipInstance) {
  85. tooltipInstance[0]?.destroy();
  86. }
  87. renderLatex();
  88. if (message.info) {
  89. let tooltipContent = '';
  90. if (message.info.openai) {
  91. tooltipContent = `prompt_tokens: ${message.info.prompt_tokens ?? 'N/A'}<br/>
  92. completion_tokens: ${message.info.completion_tokens ?? 'N/A'}<br/>
  93. total_tokens: ${message.info.total_tokens ?? 'N/A'}`;
  94. } else {
  95. tooltipContent = `response_token/s: ${
  96. `${
  97. Math.round(
  98. ((message.info.eval_count ?? 0) / (message.info.eval_duration / 1000000000)) * 100
  99. ) / 100
  100. } tokens` ?? 'N/A'
  101. }<br/>
  102. prompt_token/s: ${
  103. Math.round(
  104. ((message.info.prompt_eval_count ?? 0) /
  105. (message.info.prompt_eval_duration / 1000000000)) *
  106. 100
  107. ) / 100 ?? 'N/A'
  108. } tokens<br/>
  109. total_duration: ${
  110. Math.round(((message.info.total_duration ?? 0) / 1000000) * 100) / 100 ??
  111. 'N/A'
  112. }ms<br/>
  113. load_duration: ${
  114. Math.round(((message.info.load_duration ?? 0) / 1000000) * 100) / 100 ?? 'N/A'
  115. }ms<br/>
  116. prompt_eval_count: ${message.info.prompt_eval_count ?? 'N/A'}<br/>
  117. prompt_eval_duration: ${
  118. Math.round(((message.info.prompt_eval_duration ?? 0) / 1000000) * 100) /
  119. 100 ?? 'N/A'
  120. }ms<br/>
  121. eval_count: ${message.info.eval_count ?? 'N/A'}<br/>
  122. eval_duration: ${
  123. Math.round(((message.info.eval_duration ?? 0) / 1000000) * 100) / 100 ?? 'N/A'
  124. }ms<br/>
  125. approximate_total: ${approximateToHumanReadable(message.info.total_duration)}`;
  126. }
  127. tooltipInstance = tippy(`#info-${message.id}`, {
  128. content: `<span class="text-xs" id="tooltip-${message.id}">${tooltipContent}</span>`,
  129. allowHTML: true
  130. });
  131. }
  132. };
  133. const renderLatex = () => {
  134. let chatMessageElements = document
  135. .getElementById(`message-${message.id}`)
  136. ?.getElementsByClassName('chat-assistant');
  137. if (chatMessageElements) {
  138. for (const element of chatMessageElements) {
  139. auto_render(element, {
  140. // customised options
  141. // • auto-render specific keys, e.g.:
  142. delimiters: [
  143. { left: '$$', right: '$$', display: false },
  144. { left: '$ ', right: ' $', display: false },
  145. { left: '\\(', right: '\\)', display: false },
  146. { left: '\\[', right: '\\]', display: false },
  147. { left: '[ ', right: ' ]', display: false }
  148. ],
  149. // • rendering keys, e.g.:
  150. throwOnError: false
  151. });
  152. }
  153. }
  154. };
  155. const playAudio = (idx) => {
  156. return new Promise((res) => {
  157. speakingIdx = idx;
  158. const audio = sentencesAudio[idx];
  159. audio.play();
  160. audio.onended = async (e) => {
  161. await new Promise((r) => setTimeout(r, 300));
  162. if (Object.keys(sentencesAudio).length - 1 === idx) {
  163. speaking = null;
  164. }
  165. res(e);
  166. };
  167. });
  168. };
  169. const toggleSpeakMessage = async () => {
  170. if (speaking) {
  171. try {
  172. speechSynthesis.cancel();
  173. sentencesAudio[speakingIdx].pause();
  174. sentencesAudio[speakingIdx].currentTime = 0;
  175. } catch {}
  176. speaking = null;
  177. speakingIdx = null;
  178. } else {
  179. if ((message?.content ?? '').trim() !== '') {
  180. speaking = true;
  181. if ($config.audio.tts.engine === 'openai') {
  182. loadingSpeech = true;
  183. const sentences = extractSentences(message.content).reduce((mergedTexts, currentText) => {
  184. const lastIndex = mergedTexts.length - 1;
  185. if (lastIndex >= 0) {
  186. const previousText = mergedTexts[lastIndex];
  187. const wordCount = previousText.split(/\s+/).length;
  188. if (wordCount < 2) {
  189. mergedTexts[lastIndex] = previousText + ' ' + currentText;
  190. } else {
  191. mergedTexts.push(currentText);
  192. }
  193. } else {
  194. mergedTexts.push(currentText);
  195. }
  196. return mergedTexts;
  197. }, []);
  198. console.log(sentences);
  199. if (sentences.length > 0) {
  200. sentencesAudio = sentences.reduce((a, e, i, arr) => {
  201. a[i] = null;
  202. return a;
  203. }, {});
  204. let lastPlayedAudioPromise = Promise.resolve(); // Initialize a promise that resolves immediately
  205. for (const [idx, sentence] of sentences.entries()) {
  206. const res = await synthesizeOpenAISpeech(
  207. localStorage.token,
  208. $settings?.audio?.tts?.voice ?? $config?.audio?.tts?.voice,
  209. sentence
  210. ).catch((error) => {
  211. toast.error(error);
  212. speaking = null;
  213. loadingSpeech = false;
  214. return null;
  215. });
  216. if (res) {
  217. const blob = await res.blob();
  218. const blobUrl = URL.createObjectURL(blob);
  219. const audio = new Audio(blobUrl);
  220. sentencesAudio[idx] = audio;
  221. loadingSpeech = false;
  222. lastPlayedAudioPromise = lastPlayedAudioPromise.then(() => playAudio(idx));
  223. }
  224. }
  225. } else {
  226. speaking = null;
  227. loadingSpeech = false;
  228. }
  229. } else {
  230. let voices = [];
  231. const getVoicesLoop = setInterval(async () => {
  232. voices = await speechSynthesis.getVoices();
  233. if (voices.length > 0) {
  234. clearInterval(getVoicesLoop);
  235. const voice =
  236. voices
  237. ?.filter(
  238. (v) =>
  239. v.voiceURI === ($settings?.audio?.tts?.voice ?? $config?.audio?.tts?.voice)
  240. )
  241. ?.at(0) ?? undefined;
  242. console.log(voice);
  243. const speak = new SpeechSynthesisUtterance(message.content);
  244. console.log(speak);
  245. speak.onend = () => {
  246. speaking = null;
  247. if ($settings.conversationMode) {
  248. document.getElementById('voice-input-button')?.click();
  249. }
  250. };
  251. if (voice) {
  252. speak.voice = voice;
  253. }
  254. speechSynthesis.speak(speak);
  255. }
  256. }, 100);
  257. }
  258. } else {
  259. toast.error($i18n.t('No content to speak'));
  260. }
  261. }
  262. };
  263. const editMessageHandler = async () => {
  264. edit = true;
  265. editedContent = message.content;
  266. await tick();
  267. editTextAreaElement.style.height = '';
  268. editTextAreaElement.style.height = `${editTextAreaElement.scrollHeight}px`;
  269. };
  270. const editMessageConfirmHandler = async () => {
  271. if (editedContent === '') {
  272. editedContent = ' ';
  273. }
  274. confirmEditResponseMessage(message.id, editedContent);
  275. edit = false;
  276. editedContent = '';
  277. await tick();
  278. renderStyling();
  279. };
  280. const cancelEditMessage = async () => {
  281. edit = false;
  282. editedContent = '';
  283. await tick();
  284. renderStyling();
  285. };
  286. const generateImage = async (message) => {
  287. generatingImage = true;
  288. const res = await imageGenerations(localStorage.token, message.content).catch((error) => {
  289. toast.error(error);
  290. });
  291. console.log(res);
  292. if (res) {
  293. message.files = res.map((image) => ({
  294. type: 'image',
  295. url: `${image.url}`
  296. }));
  297. dispatch('save', message);
  298. }
  299. generatingImage = false;
  300. };
  301. $: if (!edit) {
  302. (async () => {
  303. await tick();
  304. renderStyling();
  305. await mermaid.run({
  306. querySelector: '.mermaid'
  307. });
  308. })();
  309. }
  310. onMount(async () => {
  311. await tick();
  312. renderStyling();
  313. await mermaid.run({
  314. querySelector: '.mermaid'
  315. });
  316. });
  317. </script>
  318. <CitationsModal bind:show={showCitationModal} citation={selectedCitation} />
  319. {#key message.id}
  320. <div
  321. class=" flex w-full message-{message.id}"
  322. id="message-{message.id}"
  323. dir={$settings.chatDirection}
  324. >
  325. <ProfileImage
  326. src={model?.info?.meta?.profile_image_url ??
  327. ($i18n.language === 'dg-DG' ? `/doge.png` : `${WEBUI_BASE_URL}/static/favicon.png`)}
  328. />
  329. <div class="w-full overflow-hidden pl-1">
  330. <Name>
  331. {model?.name ?? message.model}
  332. {#if message.timestamp}
  333. <span
  334. class=" self-center invisible group-hover:visible text-gray-400 text-xs font-medium uppercase"
  335. >
  336. {dayjs(message.timestamp * 1000).format($i18n.t('h:mm a'))}
  337. </span>
  338. {/if}
  339. </Name>
  340. {#if (message?.files ?? []).filter((f) => f.type === 'image').length > 0}
  341. <div class="my-2.5 w-full flex overflow-x-auto gap-2 flex-wrap">
  342. {#each message.files as file}
  343. <div>
  344. {#if file.type === 'image'}
  345. <Image src={file.url} />
  346. {/if}
  347. </div>
  348. {/each}
  349. </div>
  350. {/if}
  351. <div
  352. class="prose chat-{message.role} w-full max-w-full dark:prose-invert prose-headings:my-0 prose-headings:-mb-4 prose-p:m-0 prose-p:-mb-6 prose-pre:my-0 prose-table:my-0 prose-blockquote:my-0 prose-img:my-0 prose-ul:-my-4 prose-ol:-my-4 prose-li:-my-3 prose-ul:-mb-6 prose-ol:-mb-8 prose-ol:p-0 prose-li:-mb-4 whitespace-pre-line"
  353. >
  354. <div>
  355. {#if (message?.statusHistory ?? [...(message?.status ? [message?.status] : [])]).length > 0}
  356. {@const status = (
  357. message?.statusHistory ?? [...(message?.status ? [message?.status] : [])]
  358. ).at(-1)}
  359. <div class="flex items-center gap-2 pt-1 pb-1">
  360. {#if status.done === false}
  361. <div class="">
  362. <Spinner className="size-4" />
  363. </div>
  364. {/if}
  365. {#if status?.action === 'web_search' && status?.urls}
  366. <WebSearchResults {status}>
  367. <div class="flex flex-col justify-center -space-y-0.5">
  368. <div class="text-base line-clamp-1 text-wrap">
  369. {status?.description}
  370. </div>
  371. </div>
  372. </WebSearchResults>
  373. {:else}
  374. <div class="flex flex-col justify-center -space-y-0.5">
  375. <div class=" text-gray-500 dark:text-gray-500 text-base line-clamp-1 text-wrap">
  376. {status?.description}
  377. </div>
  378. </div>
  379. {/if}
  380. </div>
  381. {/if}
  382. {#if edit === true}
  383. <div class="w-full bg-gray-50 dark:bg-gray-800 rounded-3xl px-5 py-3 my-2">
  384. <textarea
  385. id="message-edit-{message.id}"
  386. bind:this={editTextAreaElement}
  387. class=" bg-transparent outline-none w-full resize-none"
  388. bind:value={editedContent}
  389. on:input={(e) => {
  390. e.target.style.height = '';
  391. e.target.style.height = `${e.target.scrollHeight}px`;
  392. }}
  393. on:keydown={(e) => {
  394. if (e.key === 'Escape') {
  395. document.getElementById('close-edit-message-button')?.click();
  396. }
  397. const isCmdOrCtrlPressed = e.metaKey || e.ctrlKey;
  398. const isEnterPressed = e.key === 'Enter';
  399. if (isCmdOrCtrlPressed && isEnterPressed) {
  400. document.getElementById('save-edit-message-button')?.click();
  401. }
  402. }}
  403. />
  404. <div class=" mt-2 mb-1 flex justify-end space-x-1.5 text-sm font-medium">
  405. <button
  406. id="close-edit-message-button"
  407. class="px-4 py-2 bg-white hover:bg-gray-100 text-gray-800 transition rounded-3xl"
  408. on:click={() => {
  409. cancelEditMessage();
  410. }}
  411. >
  412. {$i18n.t('Cancel')}
  413. </button>
  414. <button
  415. id="save-edit-message-button"
  416. class=" px-4 py-2 bg-gray-900 hover:bg-gray-850 text-gray-100 transition rounded-3xl"
  417. on:click={() => {
  418. editMessageConfirmHandler();
  419. }}
  420. >
  421. {$i18n.t('Save')}
  422. </button>
  423. </div>
  424. </div>
  425. {:else}
  426. <div class="w-full">
  427. {#if message.content === '' && !message.error}
  428. <Skeleton />
  429. {:else if message.content && message.error !== true}
  430. <!-- always show message contents even if there's an error -->
  431. <!-- unless message.error === true which is legacy error handling, where the error message is stored in message.content -->
  432. {#each tokens as token, tokenIdx}
  433. {#if token.type === 'code'}
  434. {#if token.lang === 'mermaid'}
  435. <pre class="mermaid">{revertSanitizedResponseContent(token.text)}</pre>
  436. {:else}
  437. <CodeBlock
  438. id={`${message.id}-${tokenIdx}`}
  439. lang={token?.lang ?? ''}
  440. code={revertSanitizedResponseContent(token?.text ?? '')}
  441. />
  442. {/if}
  443. {:else}
  444. {@html marked.parse(token.raw, {
  445. ...defaults,
  446. gfm: true,
  447. breaks: true,
  448. renderer
  449. })}
  450. {/if}
  451. {/each}
  452. {/if}
  453. {#if message.error}
  454. <div
  455. class="flex mt-2 mb-4 space-x-2 border px-4 py-3 border-red-800 bg-red-800/30 font-medium rounded-lg"
  456. >
  457. <svg
  458. xmlns="http://www.w3.org/2000/svg"
  459. fill="none"
  460. viewBox="0 0 24 24"
  461. stroke-width="1.5"
  462. stroke="currentColor"
  463. class="w-5 h-5 self-center"
  464. >
  465. <path
  466. stroke-linecap="round"
  467. stroke-linejoin="round"
  468. d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z"
  469. />
  470. </svg>
  471. <div class=" self-center">
  472. {message?.error?.content ?? message.content}
  473. </div>
  474. </div>
  475. {/if}
  476. {#if message.citations}
  477. <div class="mt-1 mb-2 w-full flex gap-1 items-center flex-wrap">
  478. {#each message.citations.reduce((acc, citation) => {
  479. citation.document.forEach((document, index) => {
  480. const metadata = citation.metadata?.[index];
  481. const id = metadata?.source ?? 'N/A';
  482. let source = citation?.source;
  483. // Check if ID looks like a URL
  484. if (id.startsWith('http://') || id.startsWith('https://')) {
  485. source = { name: id };
  486. }
  487. const existingSource = acc.find((item) => item.id === id);
  488. if (existingSource) {
  489. existingSource.document.push(document);
  490. existingSource.metadata.push(metadata);
  491. } else {
  492. acc.push( { id: id, source: source, document: [document], metadata: metadata ? [metadata] : [] } );
  493. }
  494. });
  495. return acc;
  496. }, []) as citation, idx}
  497. <div class="flex gap-1 text-xs font-semibold">
  498. <button
  499. class="flex dark:text-gray-300 py-1 px-1 bg-gray-50 hover:bg-gray-100 dark:bg-gray-850 dark:hover:bg-gray-800 transition rounded-xl"
  500. on:click={() => {
  501. showCitationModal = true;
  502. selectedCitation = citation;
  503. }}
  504. >
  505. <div class="bg-white dark:bg-gray-700 rounded-full size-4">
  506. {idx + 1}
  507. </div>
  508. <div class="flex-1 mx-2 line-clamp-1">
  509. {citation.source.name}
  510. </div>
  511. </button>
  512. </div>
  513. {/each}
  514. </div>
  515. {/if}
  516. {#if message.done || siblings.length > 1}
  517. <div
  518. class=" flex justify-start overflow-x-auto buttons text-gray-600 dark:text-gray-500"
  519. >
  520. {#if siblings.length > 1}
  521. <div class="flex self-center min-w-fit" dir="ltr">
  522. <button
  523. class="self-center p-1 hover:bg-black/5 dark:hover:bg-white/5 dark:hover:text-white hover:text-black rounded-md transition"
  524. on:click={() => {
  525. showPreviousMessage(message);
  526. }}
  527. >
  528. <svg
  529. xmlns="http://www.w3.org/2000/svg"
  530. fill="none"
  531. viewBox="0 0 24 24"
  532. stroke="currentColor"
  533. stroke-width="2.5"
  534. class="size-3.5"
  535. >
  536. <path
  537. stroke-linecap="round"
  538. stroke-linejoin="round"
  539. d="M15.75 19.5 8.25 12l7.5-7.5"
  540. />
  541. </svg>
  542. </button>
  543. <div
  544. class="text-sm tracking-widest font-semibold self-center dark:text-gray-100 min-w-fit"
  545. >
  546. {siblings.indexOf(message.id) + 1}/{siblings.length}
  547. </div>
  548. <button
  549. class="self-center p-1 hover:bg-black/5 dark:hover:bg-white/5 dark:hover:text-white hover:text-black rounded-md transition"
  550. on:click={() => {
  551. showNextMessage(message);
  552. }}
  553. >
  554. <svg
  555. xmlns="http://www.w3.org/2000/svg"
  556. fill="none"
  557. viewBox="0 0 24 24"
  558. stroke="currentColor"
  559. stroke-width="2.5"
  560. class="size-3.5"
  561. >
  562. <path
  563. stroke-linecap="round"
  564. stroke-linejoin="round"
  565. d="m8.25 4.5 7.5 7.5-7.5 7.5"
  566. />
  567. </svg>
  568. </button>
  569. </div>
  570. {/if}
  571. {#if message.done}
  572. {#if !readOnly}
  573. <Tooltip content={$i18n.t('Edit')} placement="bottom">
  574. <button
  575. class="{isLastMessage
  576. ? 'visible'
  577. : 'invisible group-hover:visible'} p-1.5 hover:bg-black/5 dark:hover:bg-white/5 rounded-lg dark:hover:text-white hover:text-black transition"
  578. on:click={() => {
  579. editMessageHandler();
  580. }}
  581. >
  582. <svg
  583. xmlns="http://www.w3.org/2000/svg"
  584. fill="none"
  585. viewBox="0 0 24 24"
  586. stroke-width="2.3"
  587. stroke="currentColor"
  588. class="w-4 h-4"
  589. >
  590. <path
  591. stroke-linecap="round"
  592. stroke-linejoin="round"
  593. d="M16.862 4.487l1.687-1.688a1.875 1.875 0 112.652 2.652L6.832 19.82a4.5 4.5 0 01-1.897 1.13l-2.685.8.8-2.685a4.5 4.5 0 011.13-1.897L16.863 4.487zm0 0L19.5 7.125"
  594. />
  595. </svg>
  596. </button>
  597. </Tooltip>
  598. {/if}
  599. <Tooltip content={$i18n.t('Copy')} placement="bottom">
  600. <button
  601. class="{isLastMessage
  602. ? 'visible'
  603. : 'invisible group-hover:visible'} p-1.5 hover:bg-black/5 dark:hover:bg-white/5 rounded-lg dark:hover:text-white hover:text-black transition copy-response-button"
  604. on:click={() => {
  605. copyToClipboard(message.content);
  606. }}
  607. >
  608. <svg
  609. xmlns="http://www.w3.org/2000/svg"
  610. fill="none"
  611. viewBox="0 0 24 24"
  612. stroke-width="2.3"
  613. stroke="currentColor"
  614. class="w-4 h-4"
  615. >
  616. <path
  617. stroke-linecap="round"
  618. stroke-linejoin="round"
  619. d="M15.666 3.888A2.25 2.25 0 0013.5 2.25h-3c-1.03 0-1.9.693-2.166 1.638m7.332 0c.055.194.084.4.084.612v0a.75.75 0 01-.75.75H9a.75.75 0 01-.75-.75v0c0-.212.03-.418.084-.612m7.332 0c.646.049 1.288.11 1.927.184 1.1.128 1.907 1.077 1.907 2.185V19.5a2.25 2.25 0 01-2.25 2.25H6.75A2.25 2.25 0 014.5 19.5V6.257c0-1.108.806-2.057 1.907-2.185a48.208 48.208 0 011.927-.184"
  620. />
  621. </svg>
  622. </button>
  623. </Tooltip>
  624. <Tooltip content={$i18n.t('Read Aloud')} placement="bottom">
  625. <button
  626. id="speak-button-{message.id}"
  627. class="{isLastMessage
  628. ? 'visible'
  629. : 'invisible group-hover:visible'} p-1.5 hover:bg-black/5 dark:hover:bg-white/5 rounded-lg dark:hover:text-white hover:text-black transition"
  630. on:click={() => {
  631. if (!loadingSpeech) {
  632. toggleSpeakMessage(message);
  633. }
  634. }}
  635. >
  636. {#if loadingSpeech}
  637. <svg
  638. class=" w-4 h-4"
  639. fill="currentColor"
  640. viewBox="0 0 24 24"
  641. xmlns="http://www.w3.org/2000/svg"
  642. ><style>
  643. .spinner_S1WN {
  644. animation: spinner_MGfb 0.8s linear infinite;
  645. animation-delay: -0.8s;
  646. }
  647. .spinner_Km9P {
  648. animation-delay: -0.65s;
  649. }
  650. .spinner_JApP {
  651. animation-delay: -0.5s;
  652. }
  653. @keyframes spinner_MGfb {
  654. 93.75%,
  655. 100% {
  656. opacity: 0.2;
  657. }
  658. }
  659. </style><circle class="spinner_S1WN" cx="4" cy="12" r="3" /><circle
  660. class="spinner_S1WN spinner_Km9P"
  661. cx="12"
  662. cy="12"
  663. r="3"
  664. /><circle
  665. class="spinner_S1WN spinner_JApP"
  666. cx="20"
  667. cy="12"
  668. r="3"
  669. /></svg
  670. >
  671. {:else if speaking}
  672. <svg
  673. xmlns="http://www.w3.org/2000/svg"
  674. fill="none"
  675. viewBox="0 0 24 24"
  676. stroke-width="2.3"
  677. stroke="currentColor"
  678. class="w-4 h-4"
  679. >
  680. <path
  681. stroke-linecap="round"
  682. stroke-linejoin="round"
  683. d="M17.25 9.75 19.5 12m0 0 2.25 2.25M19.5 12l2.25-2.25M19.5 12l-2.25 2.25m-10.5-6 4.72-4.72a.75.75 0 0 1 1.28.53v15.88a.75.75 0 0 1-1.28.53l-4.72-4.72H4.51c-.88 0-1.704-.507-1.938-1.354A9.009 9.009 0 0 1 2.25 12c0-.83.112-1.633.322-2.396C2.806 8.756 3.63 8.25 4.51 8.25H6.75Z"
  684. />
  685. </svg>
  686. {:else}
  687. <svg
  688. xmlns="http://www.w3.org/2000/svg"
  689. fill="none"
  690. viewBox="0 0 24 24"
  691. stroke-width="2.3"
  692. stroke="currentColor"
  693. class="w-4 h-4"
  694. >
  695. <path
  696. stroke-linecap="round"
  697. stroke-linejoin="round"
  698. d="M19.114 5.636a9 9 0 010 12.728M16.463 8.288a5.25 5.25 0 010 7.424M6.75 8.25l4.72-4.72a.75.75 0 011.28.53v15.88a.75.75 0 01-1.28.53l-4.72-4.72H4.51c-.88 0-1.704-.507-1.938-1.354A9.01 9.01 0 012.25 12c0-.83.112-1.633.322-2.396C2.806 8.756 3.63 8.25 4.51 8.25H6.75z"
  699. />
  700. </svg>
  701. {/if}
  702. </button>
  703. </Tooltip>
  704. {#if $config?.features.enable_image_generation && !readOnly}
  705. <Tooltip content={$i18n.t('Generate Image')} placement="bottom">
  706. <button
  707. class="{isLastMessage
  708. ? 'visible'
  709. : 'invisible group-hover:visible'} p-1.5 hover:bg-black/5 dark:hover:bg-white/5 rounded-lg dark:hover:text-white hover:text-black transition"
  710. on:click={() => {
  711. if (!generatingImage) {
  712. generateImage(message);
  713. }
  714. }}
  715. >
  716. {#if generatingImage}
  717. <svg
  718. class=" w-4 h-4"
  719. fill="currentColor"
  720. viewBox="0 0 24 24"
  721. xmlns="http://www.w3.org/2000/svg"
  722. ><style>
  723. .spinner_S1WN {
  724. animation: spinner_MGfb 0.8s linear infinite;
  725. animation-delay: -0.8s;
  726. }
  727. .spinner_Km9P {
  728. animation-delay: -0.65s;
  729. }
  730. .spinner_JApP {
  731. animation-delay: -0.5s;
  732. }
  733. @keyframes spinner_MGfb {
  734. 93.75%,
  735. 100% {
  736. opacity: 0.2;
  737. }
  738. }
  739. </style><circle class="spinner_S1WN" cx="4" cy="12" r="3" /><circle
  740. class="spinner_S1WN spinner_Km9P"
  741. cx="12"
  742. cy="12"
  743. r="3"
  744. /><circle
  745. class="spinner_S1WN spinner_JApP"
  746. cx="20"
  747. cy="12"
  748. r="3"
  749. /></svg
  750. >
  751. {:else}
  752. <svg
  753. xmlns="http://www.w3.org/2000/svg"
  754. fill="none"
  755. viewBox="0 0 24 24"
  756. stroke-width="2.3"
  757. stroke="currentColor"
  758. class="w-4 h-4"
  759. >
  760. <path
  761. stroke-linecap="round"
  762. stroke-linejoin="round"
  763. d="m2.25 15.75 5.159-5.159a2.25 2.25 0 0 1 3.182 0l5.159 5.159m-1.5-1.5 1.409-1.409a2.25 2.25 0 0 1 3.182 0l2.909 2.909m-18 3.75h16.5a1.5 1.5 0 0 0 1.5-1.5V6a1.5 1.5 0 0 0-1.5-1.5H3.75A1.5 1.5 0 0 0 2.25 6v12a1.5 1.5 0 0 0 1.5 1.5Zm10.5-11.25h.008v.008h-.008V8.25Zm.375 0a.375.375 0 1 1-.75 0 .375.375 0 0 1 .75 0Z"
  764. />
  765. </svg>
  766. {/if}
  767. </button>
  768. </Tooltip>
  769. {/if}
  770. {#if message.info}
  771. <Tooltip content={$i18n.t('Generation Info')} placement="bottom">
  772. <button
  773. class=" {isLastMessage
  774. ? 'visible'
  775. : 'invisible group-hover:visible'} p-1.5 hover:bg-black/5 dark:hover:bg-white/5 rounded-lg dark:hover:text-white hover:text-black transition whitespace-pre-wrap"
  776. on:click={() => {
  777. console.log(message);
  778. }}
  779. id="info-{message.id}"
  780. >
  781. <svg
  782. xmlns="http://www.w3.org/2000/svg"
  783. fill="none"
  784. viewBox="0 0 24 24"
  785. stroke-width="2.3"
  786. stroke="currentColor"
  787. class="w-4 h-4"
  788. >
  789. <path
  790. stroke-linecap="round"
  791. stroke-linejoin="round"
  792. d="M11.25 11.25l.041-.02a.75.75 0 011.063.852l-.708 2.836a.75.75 0 001.063.853l.041-.021M21 12a9 9 0 11-18 0 9 9 0 0118 0zm-9-3.75h.008v.008H12V8.25z"
  793. />
  794. </svg>
  795. </button>
  796. </Tooltip>
  797. {/if}
  798. {#if !readOnly}
  799. <Tooltip content={$i18n.t('Good Response')} placement="bottom">
  800. <button
  801. class="{isLastMessage
  802. ? 'visible'
  803. : 'invisible group-hover:visible'} p-1.5 hover:bg-black/5 dark:hover:bg-white/5 rounded-lg {(message
  804. ?.annotation?.rating ?? null) === 1
  805. ? 'bg-gray-100 dark:bg-gray-800'
  806. : ''} dark:hover:text-white hover:text-black transition"
  807. on:click={() => {
  808. rateMessage(message.id, 1);
  809. showRateComment = true;
  810. window.setTimeout(() => {
  811. document
  812. .getElementById(`message-feedback-${message.id}`)
  813. ?.scrollIntoView();
  814. }, 0);
  815. }}
  816. >
  817. <svg
  818. stroke="currentColor"
  819. fill="none"
  820. stroke-width="2.3"
  821. viewBox="0 0 24 24"
  822. stroke-linecap="round"
  823. stroke-linejoin="round"
  824. class="w-4 h-4"
  825. xmlns="http://www.w3.org/2000/svg"
  826. ><path
  827. d="M14 9V5a3 3 0 0 0-3-3l-4 9v11h11.28a2 2 0 0 0 2-1.7l1.38-9a2 2 0 0 0-2-2.3zM7 22H4a2 2 0 0 1-2-2v-7a2 2 0 0 1 2-2h3"
  828. /></svg
  829. >
  830. </button>
  831. </Tooltip>
  832. <Tooltip content={$i18n.t('Bad Response')} placement="bottom">
  833. <button
  834. class="{isLastMessage
  835. ? 'visible'
  836. : 'invisible group-hover:visible'} p-1.5 hover:bg-black/5 dark:hover:bg-white/5 rounded-lg {(message
  837. ?.annotation?.rating ?? null) === -1
  838. ? 'bg-gray-100 dark:bg-gray-800'
  839. : ''} dark:hover:text-white hover:text-black transition"
  840. on:click={() => {
  841. rateMessage(message.id, -1);
  842. showRateComment = true;
  843. window.setTimeout(() => {
  844. document
  845. .getElementById(`message-feedback-${message.id}`)
  846. ?.scrollIntoView();
  847. }, 0);
  848. }}
  849. >
  850. <svg
  851. stroke="currentColor"
  852. fill="none"
  853. stroke-width="2.3"
  854. viewBox="0 0 24 24"
  855. stroke-linecap="round"
  856. stroke-linejoin="round"
  857. class="w-4 h-4"
  858. xmlns="http://www.w3.org/2000/svg"
  859. ><path
  860. d="M10 15v4a3 3 0 0 0 3 3l4-9V2H5.72a2 2 0 0 0-2 1.7l-1.38 9a2 2 0 0 0 2 2.3zm7-13h2.67A2.31 2.31 0 0 1 22 4v7a2.31 2.31 0 0 1-2.33 2H17"
  861. /></svg
  862. >
  863. </button>
  864. </Tooltip>
  865. {#if isLastMessage}
  866. <Tooltip content={$i18n.t('Continue Response')} placement="bottom">
  867. <button
  868. type="button"
  869. class="{isLastMessage
  870. ? 'visible'
  871. : 'invisible group-hover:visible'} p-1.5 hover:bg-black/5 dark:hover:bg-white/5 rounded-lg dark:hover:text-white hover:text-black transition regenerate-response-button"
  872. on:click={() => {
  873. continueGeneration();
  874. }}
  875. >
  876. <svg
  877. xmlns="http://www.w3.org/2000/svg"
  878. fill="none"
  879. viewBox="0 0 24 24"
  880. stroke-width="2.3"
  881. stroke="currentColor"
  882. class="w-4 h-4"
  883. >
  884. <path
  885. stroke-linecap="round"
  886. stroke-linejoin="round"
  887. d="M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Z"
  888. />
  889. <path
  890. stroke-linecap="round"
  891. stroke-linejoin="round"
  892. d="M15.91 11.672a.375.375 0 0 1 0 .656l-5.603 3.113a.375.375 0 0 1-.557-.328V8.887c0-.286.307-.466.557-.327l5.603 3.112Z"
  893. />
  894. </svg>
  895. </button>
  896. </Tooltip>
  897. <Tooltip content={$i18n.t('Regenerate')} placement="bottom">
  898. <button
  899. type="button"
  900. class="{isLastMessage
  901. ? 'visible'
  902. : 'invisible group-hover:visible'} p-1.5 hover:bg-black/5 dark:hover:bg-white/5 rounded-lg dark:hover:text-white hover:text-black transition regenerate-response-button"
  903. on:click={() => {
  904. showRateComment = false;
  905. regenerateResponse(message);
  906. }}
  907. >
  908. <svg
  909. xmlns="http://www.w3.org/2000/svg"
  910. fill="none"
  911. viewBox="0 0 24 24"
  912. stroke-width="2.3"
  913. stroke="currentColor"
  914. class="w-4 h-4"
  915. >
  916. <path
  917. stroke-linecap="round"
  918. stroke-linejoin="round"
  919. d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0l3.181 3.183a8.25 8.25 0 0013.803-3.7M4.031 9.865a8.25 8.25 0 0113.803-3.7l3.181 3.182m0-4.991v4.99"
  920. />
  921. </svg>
  922. </button>
  923. </Tooltip>
  924. {/if}
  925. {/if}
  926. {/if}
  927. </div>
  928. {/if}
  929. {#if message.done && showRateComment}
  930. <RateComment
  931. messageId={message.id}
  932. bind:show={showRateComment}
  933. bind:message
  934. on:submit={() => {
  935. updateChatMessages();
  936. }}
  937. />
  938. {/if}
  939. </div>
  940. {/if}
  941. </div>
  942. </div>
  943. </div>
  944. </div>
  945. {/key}
  946. <style>
  947. .buttons::-webkit-scrollbar {
  948. display: none; /* for Chrome, Safari and Opera */
  949. }
  950. .buttons {
  951. -ms-overflow-style: none; /* IE and Edge */
  952. scrollbar-width: none; /* Firefox */
  953. }
  954. </style>