ResponseMessage.svelte 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641
  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?.audio?.TTSEngine === 'openai') {
  123. loadingSpeech = true;
  124. const sentences = extractSentences(message.content).reduce((mergedTexts, currentText) => {
  125. const lastIndex = mergedTexts.length - 1;
  126. if (lastIndex >= 0) {
  127. const previousText = mergedTexts[lastIndex];
  128. const wordCount = previousText.split(/\s+/).length;
  129. if (wordCount < 2) {
  130. mergedTexts[lastIndex] = previousText + ' ' + currentText;
  131. } else {
  132. mergedTexts.push(currentText);
  133. }
  134. } else {
  135. mergedTexts.push(currentText);
  136. }
  137. return mergedTexts;
  138. }, []);
  139. console.log(sentences);
  140. sentencesAudio = sentences.reduce((a, e, i, arr) => {
  141. a[i] = null;
  142. return a;
  143. }, {});
  144. let lastPlayedAudioPromise = Promise.resolve(); // Initialize a promise that resolves immediately
  145. for (const [idx, sentence] of sentences.entries()) {
  146. const res = await synthesizeOpenAISpeech(
  147. localStorage.token,
  148. $settings?.audio?.speaker,
  149. sentence
  150. ).catch((error) => {
  151. toast.error(error);
  152. return null;
  153. });
  154. if (res) {
  155. const blob = await res.blob();
  156. const blobUrl = URL.createObjectURL(blob);
  157. const audio = new Audio(blobUrl);
  158. sentencesAudio[idx] = audio;
  159. loadingSpeech = false;
  160. lastPlayedAudioPromise = lastPlayedAudioPromise.then(() => playAudio(idx));
  161. }
  162. }
  163. } else {
  164. let voices = [];
  165. const getVoicesLoop = setInterval(async () => {
  166. voices = await speechSynthesis.getVoices();
  167. if (voices.length > 0) {
  168. clearInterval(getVoicesLoop);
  169. const voice =
  170. voices?.filter((v) => v.name === $settings?.audio?.speaker)?.at(0) ?? undefined;
  171. const speak = new SpeechSynthesisUtterance(message.content);
  172. speak.onend = () => {
  173. speaking = null;
  174. if ($settings.conversationMode) {
  175. document.getElementById('voice-input-button')?.click();
  176. }
  177. };
  178. speak.voice = voice;
  179. speechSynthesis.speak(speak);
  180. }
  181. }, 100);
  182. }
  183. }
  184. };
  185. const editMessageHandler = async () => {
  186. edit = true;
  187. editedContent = message.content;
  188. await tick();
  189. const editElement = document.getElementById(`message-edit-${message.id}`);
  190. editElement.style.height = '';
  191. editElement.style.height = `${editElement.scrollHeight}px`;
  192. };
  193. const editMessageConfirmHandler = async () => {
  194. confirmEditResponseMessage(message.id, editedContent);
  195. edit = false;
  196. editedContent = '';
  197. await tick();
  198. renderStyling();
  199. };
  200. const cancelEditMessage = async () => {
  201. edit = false;
  202. editedContent = '';
  203. await tick();
  204. renderStyling();
  205. };
  206. onMount(async () => {
  207. await tick();
  208. renderStyling();
  209. });
  210. </script>
  211. {#key message.id}
  212. <div class=" flex w-full message-{message.id}">
  213. <ProfileImage src={modelfiles[message.model]?.imageUrl ?? '/favicon.png'} />
  214. <div class="w-full overflow-hidden">
  215. <Name>
  216. {#if message.model in modelfiles}
  217. {modelfiles[message.model]?.title}
  218. {:else}
  219. Ollama <span class=" text-gray-500 text-sm font-medium"
  220. >{message.model ? ` ${message.model}` : ''}</span
  221. >
  222. {/if}
  223. {#if message.timestamp}
  224. <span class=" invisible group-hover:visible text-gray-400 text-xs font-medium">
  225. {dayjs(message.timestamp * 1000).format('DD/MM/YYYY HH:mm')}
  226. </span>
  227. {/if}
  228. </Name>
  229. {#if message.content === ''}
  230. <Skeleton />
  231. {:else}
  232. <div
  233. 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"
  234. >
  235. <div>
  236. {#if edit === true}
  237. <div class=" w-full">
  238. <textarea
  239. id="message-edit-{message.id}"
  240. class=" bg-transparent outline-none w-full resize-none"
  241. bind:value={editedContent}
  242. on:input={(e) => {
  243. e.target.style.height = `${e.target.scrollHeight}px`;
  244. }}
  245. />
  246. <div class=" mt-2 mb-1 flex justify-center space-x-2 text-sm font-medium">
  247. <button
  248. class="px-4 py-2 bg-emerald-600 hover:bg-emerald-700 text-gray-100 transition rounded-lg"
  249. on:click={() => {
  250. editMessageConfirmHandler();
  251. }}
  252. >
  253. Save
  254. </button>
  255. <button
  256. 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"
  257. on:click={() => {
  258. cancelEditMessage();
  259. }}
  260. >
  261. Cancel
  262. </button>
  263. </div>
  264. </div>
  265. {:else}
  266. <div class="w-full">
  267. {#if message?.error === true}
  268. <div
  269. 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"
  270. >
  271. <svg
  272. xmlns="http://www.w3.org/2000/svg"
  273. fill="none"
  274. viewBox="0 0 24 24"
  275. stroke-width="1.5"
  276. stroke="currentColor"
  277. class="w-5 h-5 self-center"
  278. >
  279. <path
  280. stroke-linecap="round"
  281. stroke-linejoin="round"
  282. d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z"
  283. />
  284. </svg>
  285. <div class=" self-center">
  286. {message.content}
  287. </div>
  288. </div>
  289. {:else}
  290. {#each tokens as token}
  291. {#if token.type === 'code'}
  292. <!-- {token.text} -->
  293. <CodeBlock lang={token.lang} code={token.text} />
  294. {:else}
  295. {@html marked.parse(token.raw, {
  296. ...defaults,
  297. gfm: true,
  298. breaks: true,
  299. renderer
  300. })}
  301. {/if}
  302. {/each}
  303. <!-- {@html marked(message.content.replaceAll('\\', '\\\\'))} -->
  304. {/if}
  305. {#if message.done}
  306. <div class=" flex justify-start space-x-1 -mt-2">
  307. {#if siblings.length > 1}
  308. <div class="flex self-center">
  309. <button
  310. class="self-center"
  311. on:click={() => {
  312. showPreviousMessage(message);
  313. }}
  314. >
  315. <svg
  316. xmlns="http://www.w3.org/2000/svg"
  317. viewBox="0 0 20 20"
  318. fill="currentColor"
  319. class="w-4 h-4"
  320. >
  321. <path
  322. fill-rule="evenodd"
  323. 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"
  324. clip-rule="evenodd"
  325. />
  326. </svg>
  327. </button>
  328. <div class="text-xs font-bold self-center">
  329. {siblings.indexOf(message.id) + 1} / {siblings.length}
  330. </div>
  331. <button
  332. class="self-center"
  333. on:click={() => {
  334. showNextMessage(message);
  335. }}
  336. >
  337. <svg
  338. xmlns="http://www.w3.org/2000/svg"
  339. viewBox="0 0 20 20"
  340. fill="currentColor"
  341. class="w-4 h-4"
  342. >
  343. <path
  344. fill-rule="evenodd"
  345. 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"
  346. clip-rule="evenodd"
  347. />
  348. </svg>
  349. </button>
  350. </div>
  351. {/if}
  352. <button
  353. class="{isLastMessage
  354. ? 'visible'
  355. : 'invisible group-hover:visible'} p-1 rounded dark:hover:text-white transition"
  356. on:click={() => {
  357. editMessageHandler();
  358. }}
  359. >
  360. <svg
  361. xmlns="http://www.w3.org/2000/svg"
  362. fill="none"
  363. viewBox="0 0 24 24"
  364. stroke-width="1.5"
  365. stroke="currentColor"
  366. class="w-4 h-4"
  367. >
  368. <path
  369. stroke-linecap="round"
  370. stroke-linejoin="round"
  371. 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"
  372. />
  373. </svg>
  374. </button>
  375. <button
  376. class="{isLastMessage
  377. ? 'visible'
  378. : 'invisible group-hover:visible'} p-1 rounded dark:hover:text-white transition copy-response-button"
  379. on:click={() => {
  380. copyToClipboard(message.content);
  381. }}
  382. >
  383. <svg
  384. xmlns="http://www.w3.org/2000/svg"
  385. fill="none"
  386. viewBox="0 0 24 24"
  387. stroke-width="1.5"
  388. stroke="currentColor"
  389. class="w-4 h-4"
  390. >
  391. <path
  392. stroke-linecap="round"
  393. stroke-linejoin="round"
  394. 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"
  395. />
  396. </svg>
  397. </button>
  398. <button
  399. class="{isLastMessage
  400. ? 'visible'
  401. : 'invisible group-hover:visible'} p-1 rounded {message.rating === 1
  402. ? 'bg-gray-100 dark:bg-gray-800'
  403. : ''} transition"
  404. on:click={() => {
  405. rateMessage(message.id, 1);
  406. }}
  407. >
  408. <svg
  409. stroke="currentColor"
  410. fill="none"
  411. stroke-width="2"
  412. viewBox="0 0 24 24"
  413. stroke-linecap="round"
  414. stroke-linejoin="round"
  415. class="w-4 h-4"
  416. xmlns="http://www.w3.org/2000/svg"
  417. ><path
  418. 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"
  419. /></svg
  420. >
  421. </button>
  422. <button
  423. class="{isLastMessage
  424. ? 'visible'
  425. : 'invisible group-hover:visible'} p-1 rounded {message.rating === -1
  426. ? 'bg-gray-100 dark:bg-gray-800'
  427. : ''} transition"
  428. on:click={() => {
  429. rateMessage(message.id, -1);
  430. }}
  431. >
  432. <svg
  433. stroke="currentColor"
  434. fill="none"
  435. stroke-width="2"
  436. viewBox="0 0 24 24"
  437. stroke-linecap="round"
  438. stroke-linejoin="round"
  439. class="w-4 h-4"
  440. xmlns="http://www.w3.org/2000/svg"
  441. ><path
  442. 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"
  443. /></svg
  444. >
  445. </button>
  446. <button
  447. id="speak-button-{message.id}"
  448. class="{isLastMessage
  449. ? 'visible'
  450. : 'invisible group-hover:visible'} p-1 rounded dark:hover:text-white transition"
  451. on:click={() => {
  452. if (!loadingSpeech) {
  453. toggleSpeakMessage(message);
  454. }
  455. }}
  456. >
  457. {#if loadingSpeech}
  458. <svg
  459. class=" w-4 h-4"
  460. fill="currentColor"
  461. viewBox="0 0 24 24"
  462. xmlns="http://www.w3.org/2000/svg"
  463. ><style>
  464. .spinner_S1WN {
  465. animation: spinner_MGfb 0.8s linear infinite;
  466. animation-delay: -0.8s;
  467. }
  468. .spinner_Km9P {
  469. animation-delay: -0.65s;
  470. }
  471. .spinner_JApP {
  472. animation-delay: -0.5s;
  473. }
  474. @keyframes spinner_MGfb {
  475. 93.75%,
  476. 100% {
  477. opacity: 0.2;
  478. }
  479. }
  480. </style><circle class="spinner_S1WN" cx="4" cy="12" r="3" /><circle
  481. class="spinner_S1WN spinner_Km9P"
  482. cx="12"
  483. cy="12"
  484. r="3"
  485. /><circle class="spinner_S1WN spinner_JApP" cx="20" cy="12" r="3" /></svg
  486. >
  487. {:else if speaking}
  488. <svg
  489. xmlns="http://www.w3.org/2000/svg"
  490. fill="none"
  491. viewBox="0 0 24 24"
  492. stroke-width="1.5"
  493. stroke="currentColor"
  494. class="w-4 h-4"
  495. >
  496. <path
  497. stroke-linecap="round"
  498. stroke-linejoin="round"
  499. 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"
  500. />
  501. </svg>
  502. {:else}
  503. <svg
  504. xmlns="http://www.w3.org/2000/svg"
  505. fill="none"
  506. viewBox="0 0 24 24"
  507. stroke-width="1.5"
  508. stroke="currentColor"
  509. class="w-4 h-4"
  510. >
  511. <path
  512. stroke-linecap="round"
  513. stroke-linejoin="round"
  514. 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"
  515. />
  516. </svg>
  517. {/if}
  518. </button>
  519. {#if message.info}
  520. <button
  521. class=" {isLastMessage
  522. ? 'visible'
  523. : 'invisible group-hover:visible'} p-1 rounded dark:hover:text-white transition whitespace-pre-wrap"
  524. on:click={() => {
  525. console.log(message);
  526. }}
  527. id="info-{message.id}"
  528. >
  529. <svg
  530. xmlns="http://www.w3.org/2000/svg"
  531. fill="none"
  532. viewBox="0 0 24 24"
  533. stroke-width="1.5"
  534. stroke="currentColor"
  535. class="w-4 h-4"
  536. >
  537. <path
  538. stroke-linecap="round"
  539. stroke-linejoin="round"
  540. 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"
  541. />
  542. </svg>
  543. </button>
  544. {/if}
  545. {#if isLastMessage}
  546. <button
  547. type="button"
  548. class="{isLastMessage
  549. ? 'visible'
  550. : 'invisible group-hover:visible'} p-1 rounded dark:hover:text-white transition regenerate-response-button"
  551. on:click={regenerateResponse}
  552. >
  553. <svg
  554. xmlns="http://www.w3.org/2000/svg"
  555. fill="none"
  556. viewBox="0 0 24 24"
  557. stroke-width="1.5"
  558. stroke="currentColor"
  559. class="w-4 h-4"
  560. >
  561. <path
  562. stroke-linecap="round"
  563. stroke-linejoin="round"
  564. 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"
  565. />
  566. </svg>
  567. </button>
  568. {/if}
  569. </div>
  570. {/if}
  571. </div>
  572. {/if}
  573. </div>
  574. </div>
  575. {/if}
  576. </div>
  577. </div>
  578. {/key}