ResponseMessage.svelte 33 KB

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