ResponseMessage.svelte 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626
  1. <script lang="ts">
  2. import toast from 'svelte-french-toast';
  3. import dayjs from 'dayjs';
  4. import { marked } from 'marked';
  5. import { settings } from '$lib/stores';
  6. import tippy from 'tippy.js';
  7. import auto_render from 'katex/dist/contrib/auto-render.mjs';
  8. import 'katex/dist/katex.min.css';
  9. import { onMount, tick } from 'svelte';
  10. import Name from './Name.svelte';
  11. import ProfileImage from './ProfileImage.svelte';
  12. import Skeleton from './Skeleton.svelte';
  13. import CodeBlock from './CodeBlock.svelte';
  14. import { synthesizeOpenAISpeech } from '$lib/apis/openai';
  15. import { extractSentences } from '$lib/utils';
  16. export let modelfiles = [];
  17. export let message;
  18. export let siblings;
  19. export let isLastMessage = true;
  20. export let confirmEditResponseMessage: Function;
  21. export let showPreviousMessage: Function;
  22. export let showNextMessage: Function;
  23. export let rateMessage: Function;
  24. export let copyToClipboard: Function;
  25. export let regenerateResponse: Function;
  26. let edit = false;
  27. let editedContent = '';
  28. let tooltipInstance = null;
  29. let sentencesAudio = {};
  30. let speaking = null;
  31. let speakingIdx = null;
  32. let loadingSpeech = false;
  33. $: tokens = marked.lexer(message.content);
  34. const renderer = new marked.Renderer();
  35. // For code blocks with simple backticks
  36. renderer.codespan = (code) => {
  37. return `<code>${code.replaceAll('&amp;', '&')}</code>`;
  38. };
  39. const { extensions, ...defaults } = marked.getDefaults() as marked.MarkedOptions & {
  40. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  41. extensions: any;
  42. };
  43. $: if (message) {
  44. renderStyling();
  45. }
  46. const renderStyling = async () => {
  47. await tick();
  48. if (tooltipInstance) {
  49. tooltipInstance[0].destroy();
  50. }
  51. renderLatex();
  52. if (message.info) {
  53. tooltipInstance = tippy(`#info-${message.id}`, {
  54. content: `<span class="text-xs" id="tooltip-${message.id}">token/s: ${
  55. `${
  56. Math.round(
  57. ((message.info.eval_count ?? 0) / (message.info.eval_duration / 1000000000)) * 100
  58. ) / 100
  59. } tokens` ?? 'N/A'
  60. }<br/>
  61. total_duration: ${
  62. Math.round(((message.info.total_duration ?? 0) / 1000000) * 100) / 100 ??
  63. 'N/A'
  64. }ms<br/>
  65. load_duration: ${
  66. Math.round(((message.info.load_duration ?? 0) / 1000000) * 100) / 100 ?? 'N/A'
  67. }ms<br/>
  68. prompt_eval_count: ${message.info.prompt_eval_count ?? 'N/A'}<br/>
  69. prompt_eval_duration: ${
  70. Math.round(((message.info.prompt_eval_duration ?? 0) / 1000000) * 100) /
  71. 100 ?? 'N/A'
  72. }ms<br/>
  73. eval_count: ${message.info.eval_count ?? 'N/A'}<br/>
  74. eval_duration: ${
  75. Math.round(((message.info.eval_duration ?? 0) / 1000000) * 100) / 100 ?? 'N/A'
  76. }ms</span>`,
  77. allowHTML: true
  78. });
  79. }
  80. };
  81. const renderLatex = () => {
  82. let chatMessageElements = document.getElementsByClassName('chat-assistant');
  83. // let lastChatMessageElement = chatMessageElements[chatMessageElements.length - 1];
  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: true },
  90. // { left: '$', right: '$', display: false },
  91. { left: '\\(', right: '\\)', display: true },
  92. { left: '\\[', right: '\\]', display: true }
  93. ],
  94. // • rendering keys, e.g.:
  95. throwOnError: false
  96. });
  97. }
  98. };
  99. const playAudio = (idx) => {
  100. return new Promise((res) => {
  101. speakingIdx = idx;
  102. const audio = sentencesAudio[idx];
  103. audio.play();
  104. audio.onended = async (e) => {
  105. await new Promise((r) => setTimeout(r, 300));
  106. if (Object.keys(sentencesAudio).length - 1 === idx) {
  107. speaking = null;
  108. }
  109. res(e);
  110. };
  111. });
  112. };
  113. const toggleSpeakMessage = async () => {
  114. if (speaking) {
  115. speechSynthesis.cancel();
  116. sentencesAudio[speakingIdx].pause();
  117. sentencesAudio[speakingIdx].currentTime = 0;
  118. speaking = null;
  119. speakingIdx = null;
  120. } else {
  121. speaking = true;
  122. if ($settings?.speech?.engine === 'openai') {
  123. loadingSpeech = true;
  124. const sentences = extractSentences(message.content);
  125. console.log(sentences);
  126. sentencesAudio = sentences.reduce((a, e, i, arr) => {
  127. a[i] = null;
  128. return a;
  129. }, {});
  130. let lastPlayedAudioPromise = Promise.resolve(); // Initialize a promise that resolves immediately
  131. for (const [idx, sentence] of sentences.entries()) {
  132. const res = await synthesizeOpenAISpeech(
  133. localStorage.token,
  134. $settings?.speech?.speaker,
  135. sentence
  136. ).catch((error) => {
  137. toast.error(error);
  138. return null;
  139. });
  140. if (res) {
  141. const blob = await res.blob();
  142. const blobUrl = URL.createObjectURL(blob);
  143. const audio = new Audio(blobUrl);
  144. sentencesAudio[idx] = audio;
  145. loadingSpeech = false;
  146. lastPlayedAudioPromise = lastPlayedAudioPromise.then(() => playAudio(idx));
  147. }
  148. }
  149. } else {
  150. let voices = [];
  151. const getVoicesLoop = setInterval(async () => {
  152. voices = await speechSynthesis.getVoices();
  153. if (voices.length > 0) {
  154. clearInterval(getVoicesLoop);
  155. const voice =
  156. voices?.filter((v) => v.name === $settings?.speech?.speaker)?.at(0) ?? undefined;
  157. const speak = new SpeechSynthesisUtterance(message.content);
  158. speak.onend = () => {
  159. speaking = null;
  160. if ($settings.conversationMode) {
  161. document.getElementById('voice-input-button')?.click();
  162. }
  163. };
  164. speak.voice = voice;
  165. speechSynthesis.speak(speak);
  166. }
  167. }, 100);
  168. }
  169. }
  170. };
  171. const editMessageHandler = async () => {
  172. edit = true;
  173. editedContent = message.content;
  174. await tick();
  175. const editElement = document.getElementById(`message-edit-${message.id}`);
  176. editElement.style.height = '';
  177. editElement.style.height = `${editElement.scrollHeight}px`;
  178. };
  179. const editMessageConfirmHandler = async () => {
  180. confirmEditResponseMessage(message.id, editedContent);
  181. edit = false;
  182. editedContent = '';
  183. await tick();
  184. renderStyling();
  185. };
  186. const cancelEditMessage = async () => {
  187. edit = false;
  188. editedContent = '';
  189. await tick();
  190. renderStyling();
  191. };
  192. onMount(async () => {
  193. await tick();
  194. renderStyling();
  195. });
  196. </script>
  197. {#key message.id}
  198. <div class=" flex w-full message-{message.id}">
  199. <ProfileImage src={modelfiles[message.model]?.imageUrl ?? '/favicon.png'} />
  200. <div class="w-full overflow-hidden">
  201. <Name>
  202. {#if message.model in modelfiles}
  203. {modelfiles[message.model]?.title}
  204. {:else}
  205. Ollama <span class=" text-gray-500 text-sm font-medium"
  206. >{message.model ? ` ${message.model}` : ''}</span
  207. >
  208. {/if}
  209. {#if message.timestamp}
  210. <span class=" invisible group-hover:visible text-gray-400 text-xs font-medium">
  211. {dayjs(message.timestamp * 1000).format('DD/MM/YYYY HH:mm')}
  212. </span>
  213. {/if}
  214. </Name>
  215. {#if message.content === ''}
  216. <Skeleton />
  217. {:else}
  218. <div
  219. class="prose chat-{message.role} w-full max-w-full dark:prose-invert prose-headings:my-0 prose-p:my-0 prose-p:-mb-4 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-6 prose-li:-mb-4 whitespace-pre-line"
  220. >
  221. <div>
  222. {#if edit === true}
  223. <div class=" w-full">
  224. <textarea
  225. id="message-edit-{message.id}"
  226. class=" bg-transparent outline-none w-full resize-none"
  227. bind:value={editedContent}
  228. on:input={(e) => {
  229. e.target.style.height = `${e.target.scrollHeight}px`;
  230. }}
  231. />
  232. <div class=" mt-2 mb-1 flex justify-center space-x-2 text-sm font-medium">
  233. <button
  234. class="px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-gray-100 transition rounded-lg"
  235. on:click={() => {
  236. editMessageConfirmHandler();
  237. }}
  238. >
  239. Save
  240. </button>
  241. <button
  242. class=" px-4 py-2 hover:bg-gray-100 dark:bg-gray-800 dark:hover:bg-gray-700 text-gray-700 dark:text-gray-100 transition outline outline-1 outline-gray-200 dark:outline-gray-600 rounded-lg"
  243. on:click={() => {
  244. cancelEditMessage();
  245. }}
  246. >
  247. Cancel
  248. </button>
  249. </div>
  250. </div>
  251. {:else}
  252. <div class="w-full">
  253. {#if message?.error === true}
  254. <div
  255. 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"
  256. >
  257. <svg
  258. xmlns="http://www.w3.org/2000/svg"
  259. fill="none"
  260. viewBox="0 0 24 24"
  261. stroke-width="1.5"
  262. stroke="currentColor"
  263. class="w-5 h-5 self-center"
  264. >
  265. <path
  266. stroke-linecap="round"
  267. stroke-linejoin="round"
  268. d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z"
  269. />
  270. </svg>
  271. <div class=" self-center">
  272. {message.content}
  273. </div>
  274. </div>
  275. {:else}
  276. {#each tokens as token}
  277. {#if token.type === 'code'}
  278. <!-- {token.text} -->
  279. <CodeBlock lang={token.lang} code={token.text} />
  280. {:else}
  281. {@html marked.parse(token.raw, {
  282. ...defaults,
  283. gfm: true,
  284. breaks: true,
  285. renderer
  286. })}
  287. {/if}
  288. {/each}
  289. <!-- {@html marked(message.content.replaceAll('\\', '\\\\'))} -->
  290. {/if}
  291. {#if message.done}
  292. <div class=" flex justify-start space-x-1 -mt-2">
  293. {#if siblings.length > 1}
  294. <div class="flex self-center">
  295. <button
  296. class="self-center"
  297. on:click={() => {
  298. showPreviousMessage(message);
  299. }}
  300. >
  301. <svg
  302. xmlns="http://www.w3.org/2000/svg"
  303. viewBox="0 0 20 20"
  304. fill="currentColor"
  305. class="w-4 h-4"
  306. >
  307. <path
  308. fill-rule="evenodd"
  309. d="M12.79 5.23a.75.75 0 01-.02 1.06L8.832 10l3.938 3.71a.75.75 0 11-1.04 1.08l-4.5-4.25a.75.75 0 010-1.08l4.5-4.25a.75.75 0 011.06.02z"
  310. clip-rule="evenodd"
  311. />
  312. </svg>
  313. </button>
  314. <div class="text-xs font-bold self-center">
  315. {siblings.indexOf(message.id) + 1} / {siblings.length}
  316. </div>
  317. <button
  318. class="self-center"
  319. on:click={() => {
  320. showNextMessage(message);
  321. }}
  322. >
  323. <svg
  324. xmlns="http://www.w3.org/2000/svg"
  325. viewBox="0 0 20 20"
  326. fill="currentColor"
  327. class="w-4 h-4"
  328. >
  329. <path
  330. fill-rule="evenodd"
  331. d="M7.21 14.77a.75.75 0 01.02-1.06L11.168 10 7.23 6.29a.75.75 0 111.04-1.08l4.5 4.25a.75.75 0 010 1.08l-4.5 4.25a.75.75 0 01-1.06-.02z"
  332. clip-rule="evenodd"
  333. />
  334. </svg>
  335. </button>
  336. </div>
  337. {/if}
  338. <button
  339. class="{isLastMessage
  340. ? 'visible'
  341. : 'invisible group-hover:visible'} p-1 rounded dark:hover:text-white transition"
  342. on:click={() => {
  343. editMessageHandler();
  344. }}
  345. >
  346. <svg
  347. xmlns="http://www.w3.org/2000/svg"
  348. fill="none"
  349. viewBox="0 0 24 24"
  350. stroke-width="1.5"
  351. stroke="currentColor"
  352. class="w-4 h-4"
  353. >
  354. <path
  355. stroke-linecap="round"
  356. stroke-linejoin="round"
  357. 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"
  358. />
  359. </svg>
  360. </button>
  361. <button
  362. class="{isLastMessage
  363. ? 'visible'
  364. : 'invisible group-hover:visible'} p-1 rounded dark:hover:text-white transition copy-response-button"
  365. on:click={() => {
  366. copyToClipboard(message.content);
  367. }}
  368. >
  369. <svg
  370. xmlns="http://www.w3.org/2000/svg"
  371. fill="none"
  372. viewBox="0 0 24 24"
  373. stroke-width="1.5"
  374. stroke="currentColor"
  375. class="w-4 h-4"
  376. >
  377. <path
  378. stroke-linecap="round"
  379. stroke-linejoin="round"
  380. 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"
  381. />
  382. </svg>
  383. </button>
  384. <button
  385. class="{isLastMessage
  386. ? 'visible'
  387. : 'invisible group-hover:visible'} p-1 rounded {message.rating === 1
  388. ? 'bg-gray-100 dark:bg-gray-800'
  389. : ''} transition"
  390. on:click={() => {
  391. rateMessage(message.id, 1);
  392. }}
  393. >
  394. <svg
  395. stroke="currentColor"
  396. fill="none"
  397. stroke-width="2"
  398. viewBox="0 0 24 24"
  399. stroke-linecap="round"
  400. stroke-linejoin="round"
  401. class="w-4 h-4"
  402. xmlns="http://www.w3.org/2000/svg"
  403. ><path
  404. 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"
  405. /></svg
  406. >
  407. </button>
  408. <button
  409. class="{isLastMessage
  410. ? 'visible'
  411. : 'invisible group-hover:visible'} p-1 rounded {message.rating === -1
  412. ? 'bg-gray-100 dark:bg-gray-800'
  413. : ''} transition"
  414. on:click={() => {
  415. rateMessage(message.id, -1);
  416. }}
  417. >
  418. <svg
  419. stroke="currentColor"
  420. fill="none"
  421. stroke-width="2"
  422. viewBox="0 0 24 24"
  423. stroke-linecap="round"
  424. stroke-linejoin="round"
  425. class="w-4 h-4"
  426. xmlns="http://www.w3.org/2000/svg"
  427. ><path
  428. 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"
  429. /></svg
  430. >
  431. </button>
  432. <button
  433. id="speak-button-{message.id}"
  434. class="{isLastMessage
  435. ? 'visible'
  436. : 'invisible group-hover:visible'} p-1 rounded dark:hover:text-white transition"
  437. on:click={() => {
  438. if (!loadingSpeech) {
  439. toggleSpeakMessage(message);
  440. }
  441. }}
  442. >
  443. {#if loadingSpeech}
  444. <svg
  445. class=" w-4 h-4"
  446. fill="currentColor"
  447. viewBox="0 0 24 24"
  448. xmlns="http://www.w3.org/2000/svg"
  449. ><style>
  450. .spinner_S1WN {
  451. animation: spinner_MGfb 0.8s linear infinite;
  452. animation-delay: -0.8s;
  453. }
  454. .spinner_Km9P {
  455. animation-delay: -0.65s;
  456. }
  457. .spinner_JApP {
  458. animation-delay: -0.5s;
  459. }
  460. @keyframes spinner_MGfb {
  461. 93.75%,
  462. 100% {
  463. opacity: 0.2;
  464. }
  465. }
  466. </style><circle class="spinner_S1WN" cx="4" cy="12" r="3" /><circle
  467. class="spinner_S1WN spinner_Km9P"
  468. cx="12"
  469. cy="12"
  470. r="3"
  471. /><circle class="spinner_S1WN spinner_JApP" cx="20" cy="12" r="3" /></svg
  472. >
  473. {:else if speaking}
  474. <svg
  475. xmlns="http://www.w3.org/2000/svg"
  476. fill="none"
  477. viewBox="0 0 24 24"
  478. stroke-width="1.5"
  479. stroke="currentColor"
  480. class="w-4 h-4"
  481. >
  482. <path
  483. stroke-linecap="round"
  484. stroke-linejoin="round"
  485. 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"
  486. />
  487. </svg>
  488. {:else}
  489. <svg
  490. xmlns="http://www.w3.org/2000/svg"
  491. fill="none"
  492. viewBox="0 0 24 24"
  493. stroke-width="1.5"
  494. stroke="currentColor"
  495. class="w-4 h-4"
  496. >
  497. <path
  498. stroke-linecap="round"
  499. stroke-linejoin="round"
  500. 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"
  501. />
  502. </svg>
  503. {/if}
  504. </button>
  505. {#if message.info}
  506. <button
  507. class=" {isLastMessage
  508. ? 'visible'
  509. : 'invisible group-hover:visible'} p-1 rounded dark:hover:text-white transition whitespace-pre-wrap"
  510. on:click={() => {
  511. console.log(message);
  512. }}
  513. id="info-{message.id}"
  514. >
  515. <svg
  516. xmlns="http://www.w3.org/2000/svg"
  517. fill="none"
  518. viewBox="0 0 24 24"
  519. stroke-width="1.5"
  520. stroke="currentColor"
  521. class="w-4 h-4"
  522. >
  523. <path
  524. stroke-linecap="round"
  525. stroke-linejoin="round"
  526. 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"
  527. />
  528. </svg>
  529. </button>
  530. {/if}
  531. {#if isLastMessage}
  532. <button
  533. type="button"
  534. class="{isLastMessage
  535. ? 'visible'
  536. : 'invisible group-hover:visible'} p-1 rounded dark:hover:text-white transition regenerate-response-button"
  537. on:click={regenerateResponse}
  538. >
  539. <svg
  540. xmlns="http://www.w3.org/2000/svg"
  541. fill="none"
  542. viewBox="0 0 24 24"
  543. stroke-width="1.5"
  544. stroke="currentColor"
  545. class="w-4 h-4"
  546. >
  547. <path
  548. stroke-linecap="round"
  549. stroke-linejoin="round"
  550. 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"
  551. />
  552. </svg>
  553. </button>
  554. {/if}
  555. </div>
  556. {/if}
  557. </div>
  558. {/if}
  559. </div>
  560. </div>
  561. {/if}
  562. </div>
  563. </div>
  564. {/key}