MessageInput.svelte 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. <script lang="ts">
  2. import { toast } from 'svelte-sonner';
  3. import { onMount, tick, getContext, createEventDispatcher } from 'svelte';
  4. const dispatch = createEventDispatcher();
  5. import {
  6. type Model,
  7. mobile,
  8. settings,
  9. showSidebar,
  10. models,
  11. config,
  12. showCallOverlay,
  13. tools,
  14. user as _user
  15. } from '$lib/stores';
  16. import { blobToFile, findWordIndices } from '$lib/utils';
  17. import { processDocToVectorDB } from '$lib/apis/rag';
  18. import { transcribeAudio } from '$lib/apis/audio';
  19. import { uploadFile } from '$lib/apis/files';
  20. import {
  21. SUPPORTED_FILE_TYPE,
  22. SUPPORTED_FILE_EXTENSIONS,
  23. WEBUI_BASE_URL,
  24. WEBUI_API_BASE_URL
  25. } from '$lib/constants';
  26. import Tooltip from '../common/Tooltip.svelte';
  27. import InputMenu from './MessageInput/InputMenu.svelte';
  28. import Headphone from '../icons/Headphone.svelte';
  29. import VoiceRecording from './MessageInput/VoiceRecording.svelte';
  30. import FileItem from '../common/FileItem.svelte';
  31. import FilesOverlay from './MessageInput/FilesOverlay.svelte';
  32. import Commands from './MessageInput/Commands.svelte';
  33. import XMark from '../icons/XMark.svelte';
  34. const i18n = getContext('i18n');
  35. export let transparentBackground = false;
  36. export let submitPrompt: Function;
  37. export let stopResponse: Function;
  38. export let autoScroll = false;
  39. export let atSelectedModel: Model | undefined;
  40. export let selectedModels: [''];
  41. let recording = false;
  42. let chatTextAreaElement: HTMLTextAreaElement;
  43. let filesInputElement;
  44. let commandsElement;
  45. let inputFiles;
  46. let dragged = false;
  47. let user = null;
  48. let chatInputPlaceholder = '';
  49. export let files = [];
  50. export let availableToolIds = [];
  51. export let selectedToolIds = [];
  52. export let webSearchEnabled = false;
  53. export let prompt = '';
  54. export let messages = [];
  55. let visionCapableModels = [];
  56. $: visionCapableModels = [...(atSelectedModel ? [atSelectedModel] : selectedModels)].filter(
  57. (model) => $models.find((m) => m.id === model)?.info?.meta?.capabilities?.vision ?? true
  58. );
  59. $: if (prompt) {
  60. if (chatTextAreaElement) {
  61. chatTextAreaElement.style.height = '';
  62. chatTextAreaElement.style.height = Math.min(chatTextAreaElement.scrollHeight, 200) + 'px';
  63. }
  64. }
  65. const scrollToBottom = () => {
  66. const element = document.getElementById('messages-container');
  67. element.scrollTo({
  68. top: element.scrollHeight,
  69. behavior: 'smooth'
  70. });
  71. };
  72. const uploadFileHandler = async (file) => {
  73. console.log(file);
  74. // Check if the file is an audio file and transcribe/convert it to text file
  75. if (['audio/mpeg', 'audio/wav'].includes(file['type'])) {
  76. const res = await transcribeAudio(localStorage.token, file).catch((error) => {
  77. toast.error(error);
  78. return null;
  79. });
  80. if (res) {
  81. console.log(res);
  82. const blob = new Blob([res.text], { type: 'text/plain' });
  83. file = blobToFile(blob, `${file.name}.txt`);
  84. }
  85. }
  86. const fileItem = {
  87. type: 'file',
  88. file: '',
  89. id: null,
  90. url: '',
  91. name: file.name,
  92. collection_name: '',
  93. status: '',
  94. size: file.size,
  95. error: ''
  96. };
  97. files = [...files, fileItem];
  98. try {
  99. const uploadedFile = await uploadFile(localStorage.token, file);
  100. if (uploadedFile) {
  101. fileItem.status = 'uploaded';
  102. fileItem.file = uploadedFile;
  103. fileItem.id = uploadedFile.id;
  104. fileItem.url = `${WEBUI_API_BASE_URL}/files/${uploadedFile.id}`;
  105. // TODO: Check if tools & functions have files support to skip this step to delegate file processing
  106. // Default Upload to VectorDB
  107. if (
  108. SUPPORTED_FILE_TYPE.includes(file['type']) ||
  109. SUPPORTED_FILE_EXTENSIONS.includes(file.name.split('.').at(-1))
  110. ) {
  111. processFileItem(fileItem);
  112. } else {
  113. toast.error(
  114. $i18n.t(`Unknown file type '{{file_type}}'. Proceeding with the file upload anyway.`, {
  115. file_type: file['type']
  116. })
  117. );
  118. processFileItem(fileItem);
  119. }
  120. } else {
  121. files = files.filter((item) => item.status !== null);
  122. }
  123. } catch (e) {
  124. toast.error(e);
  125. files = files.filter((item) => item.status !== null);
  126. }
  127. };
  128. const processFileItem = async (fileItem) => {
  129. try {
  130. const res = await processDocToVectorDB(localStorage.token, fileItem.id);
  131. if (res) {
  132. fileItem.status = 'processed';
  133. fileItem.collection_name = res.collection_name;
  134. files = files;
  135. }
  136. } catch (e) {
  137. // Remove the failed doc from the files array
  138. // files = files.filter((f) => f.id !== fileItem.id);
  139. toast.error(e);
  140. fileItem.status = 'processed';
  141. files = files;
  142. }
  143. };
  144. onMount(() => {
  145. window.setTimeout(() => chatTextAreaElement?.focus(), 0);
  146. const dropZone = document.querySelector('body');
  147. const handleKeyDown = (event: KeyboardEvent) => {
  148. if (event.key === 'Escape') {
  149. console.log('Escape');
  150. dragged = false;
  151. }
  152. };
  153. const onDragOver = (e) => {
  154. e.preventDefault();
  155. dragged = true;
  156. };
  157. const onDragLeave = () => {
  158. dragged = false;
  159. };
  160. const onDrop = async (e) => {
  161. e.preventDefault();
  162. console.log(e);
  163. if (e.dataTransfer?.files) {
  164. const inputFiles = Array.from(e.dataTransfer?.files);
  165. if (inputFiles && inputFiles.length > 0) {
  166. inputFiles.forEach((file) => {
  167. console.log(file, file.name.split('.').at(-1));
  168. if (['image/gif', 'image/webp', 'image/jpeg', 'image/png'].includes(file['type'])) {
  169. if (visionCapableModels.length === 0) {
  170. toast.error($i18n.t('Selected model(s) do not support image inputs'));
  171. return;
  172. }
  173. let reader = new FileReader();
  174. reader.onload = (event) => {
  175. files = [
  176. ...files,
  177. {
  178. type: 'image',
  179. url: `${event.target.result}`
  180. }
  181. ];
  182. };
  183. reader.readAsDataURL(file);
  184. } else {
  185. uploadFileHandler(file);
  186. }
  187. });
  188. } else {
  189. toast.error($i18n.t(`File not found.`));
  190. }
  191. }
  192. dragged = false;
  193. };
  194. window.addEventListener('keydown', handleKeyDown);
  195. dropZone?.addEventListener('dragover', onDragOver);
  196. dropZone?.addEventListener('drop', onDrop);
  197. dropZone?.addEventListener('dragleave', onDragLeave);
  198. return () => {
  199. window.removeEventListener('keydown', handleKeyDown);
  200. dropZone?.removeEventListener('dragover', onDragOver);
  201. dropZone?.removeEventListener('drop', onDrop);
  202. dropZone?.removeEventListener('dragleave', onDragLeave);
  203. };
  204. });
  205. </script>
  206. <FilesOverlay show={dragged} />
  207. <div class="w-full font-primary">
  208. <div class=" -mb-0.5 mx-auto inset-x-0 bg-transparent flex justify-center">
  209. <div class="flex flex-col max-w-6xl px-2.5 md:px-6 w-full">
  210. <div class="relative">
  211. {#if autoScroll === false && messages.length > 0}
  212. <div
  213. class=" absolute -top-12 left-0 right-0 flex justify-center z-30 pointer-events-none"
  214. >
  215. <button
  216. class=" bg-white border border-gray-100 dark:border-none dark:bg-white/20 p-1.5 rounded-full pointer-events-auto"
  217. on:click={() => {
  218. autoScroll = true;
  219. scrollToBottom();
  220. }}
  221. >
  222. <svg
  223. xmlns="http://www.w3.org/2000/svg"
  224. viewBox="0 0 20 20"
  225. fill="currentColor"
  226. class="w-5 h-5"
  227. >
  228. <path
  229. fill-rule="evenodd"
  230. d="M10 3a.75.75 0 01.75.75v10.638l3.96-4.158a.75.75 0 111.08 1.04l-5.25 5.5a.75.75 0 01-1.08 0l-5.25-5.5a.75.75 0 111.08-1.04l3.96 4.158V3.75A.75.75 0 0110 3z"
  231. clip-rule="evenodd"
  232. />
  233. </svg>
  234. </button>
  235. </div>
  236. {/if}
  237. </div>
  238. <div class="w-full relative">
  239. {#if atSelectedModel !== undefined}
  240. <div
  241. class="px-3 py-2.5 text-left w-full flex justify-between items-center absolute bottom-0.5 left-0 right-0 bg-gradient-to-t from-50% from-white dark:from-gray-900 z-10"
  242. >
  243. <div class="flex items-center gap-2 text-sm dark:text-gray-500">
  244. <img
  245. crossorigin="anonymous"
  246. alt="model profile"
  247. class="size-5 max-w-[28px] object-cover rounded-full"
  248. src={$models.find((model) => model.id === atSelectedModel.id)?.info?.meta
  249. ?.profile_image_url ??
  250. ($i18n.language === 'dg-DG'
  251. ? `/doge.png`
  252. : `${WEBUI_BASE_URL}/static/favicon.png`)}
  253. />
  254. <div>
  255. Talking to <span class=" font-medium">{atSelectedModel.name}</span>
  256. </div>
  257. </div>
  258. <div>
  259. <button
  260. class="flex items-center"
  261. on:click={() => {
  262. atSelectedModel = undefined;
  263. }}
  264. >
  265. <XMark />
  266. </button>
  267. </div>
  268. </div>
  269. {/if}
  270. <Commands
  271. bind:this={commandsElement}
  272. bind:prompt
  273. bind:files
  274. on:select={(e) => {
  275. const data = e.detail;
  276. if (data?.type === 'model') {
  277. atSelectedModel = data.data;
  278. }
  279. chatTextAreaElement?.focus();
  280. }}
  281. />
  282. </div>
  283. </div>
  284. </div>
  285. <div class="{transparentBackground ? 'bg-transparent' : 'bg-white dark:bg-gray-900'} ">
  286. <div class="max-w-6xl px-2.5 md:px-6 mx-auto inset-x-0">
  287. <div class=" pb-2">
  288. <input
  289. bind:this={filesInputElement}
  290. bind:files={inputFiles}
  291. type="file"
  292. hidden
  293. multiple
  294. on:change={async () => {
  295. if (inputFiles && inputFiles.length > 0) {
  296. const _inputFiles = Array.from(inputFiles);
  297. _inputFiles.forEach((file) => {
  298. if (['image/gif', 'image/webp', 'image/jpeg', 'image/png'].includes(file['type'])) {
  299. if (visionCapableModels.length === 0) {
  300. toast.error($i18n.t('Selected model(s) do not support image inputs'));
  301. return;
  302. }
  303. let reader = new FileReader();
  304. reader.onload = (event) => {
  305. files = [
  306. ...files,
  307. {
  308. type: 'image',
  309. url: `${event.target.result}`
  310. }
  311. ];
  312. };
  313. reader.readAsDataURL(file);
  314. } else {
  315. uploadFileHandler(file);
  316. }
  317. });
  318. } else {
  319. toast.error($i18n.t(`File not found.`));
  320. }
  321. filesInputElement.value = '';
  322. }}
  323. />
  324. {#if recording}
  325. <VoiceRecording
  326. bind:recording
  327. on:cancel={async () => {
  328. recording = false;
  329. await tick();
  330. document.getElementById('chat-textarea')?.focus();
  331. }}
  332. on:confirm={async (e) => {
  333. const response = e.detail;
  334. prompt = `${prompt}${response} `;
  335. recording = false;
  336. await tick();
  337. document.getElementById('chat-textarea')?.focus();
  338. if ($settings?.speechAutoSend ?? false) {
  339. submitPrompt(prompt);
  340. }
  341. }}
  342. />
  343. {:else}
  344. <form
  345. class="w-full flex gap-1.5"
  346. on:submit|preventDefault={() => {
  347. // check if selectedModels support image input
  348. submitPrompt(prompt);
  349. }}
  350. >
  351. <div
  352. class="flex-1 flex flex-col relative w-full rounded-3xl px-1.5 bg-gray-50 dark:bg-gray-850 dark:text-gray-100"
  353. dir={$settings?.chatDirection ?? 'LTR'}
  354. >
  355. {#if files.length > 0}
  356. <div class="mx-1 mt-2.5 mb-1 flex flex-wrap gap-2">
  357. {#each files as file, fileIdx}
  358. {#if file.type === 'image'}
  359. <div class=" relative group">
  360. <div class="relative">
  361. <img
  362. src={file.url}
  363. alt="input"
  364. class=" h-16 w-16 rounded-xl object-cover"
  365. />
  366. {#if atSelectedModel ? visionCapableModels.length === 0 : selectedModels.length !== visionCapableModels.length}
  367. <Tooltip
  368. className=" absolute top-1 left-1"
  369. content={$i18n.t('{{ models }}', {
  370. models: [...(atSelectedModel ? [atSelectedModel] : selectedModels)]
  371. .filter((id) => !visionCapableModels.includes(id))
  372. .join(', ')
  373. })}
  374. >
  375. <svg
  376. xmlns="http://www.w3.org/2000/svg"
  377. viewBox="0 0 24 24"
  378. fill="currentColor"
  379. class="size-4 fill-yellow-300"
  380. >
  381. <path
  382. fill-rule="evenodd"
  383. d="M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003ZM12 8.25a.75.75 0 0 1 .75.75v3.75a.75.75 0 0 1-1.5 0V9a.75.75 0 0 1 .75-.75Zm0 8.25a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Z"
  384. clip-rule="evenodd"
  385. />
  386. </svg>
  387. </Tooltip>
  388. {/if}
  389. </div>
  390. <div class=" absolute -top-1 -right-1">
  391. <button
  392. class=" bg-gray-400 text-white border border-white rounded-full group-hover:visible invisible transition"
  393. type="button"
  394. on:click={() => {
  395. files.splice(fileIdx, 1);
  396. files = files;
  397. }}
  398. >
  399. <svg
  400. xmlns="http://www.w3.org/2000/svg"
  401. viewBox="0 0 20 20"
  402. fill="currentColor"
  403. class="w-4 h-4"
  404. >
  405. <path
  406. d="M6.28 5.22a.75.75 0 00-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 101.06 1.06L10 11.06l3.72 3.72a.75.75 0 101.06-1.06L11.06 10l3.72-3.72a.75.75 0 00-1.06-1.06L10 8.94 6.28 5.22z"
  407. />
  408. </svg>
  409. </button>
  410. </div>
  411. </div>
  412. {:else}
  413. <FileItem
  414. name={file.name}
  415. type={file.type}
  416. size={file?.size}
  417. status={file.status}
  418. dismissible={true}
  419. on:dismiss={() => {
  420. files.splice(fileIdx, 1);
  421. files = files;
  422. }}
  423. />
  424. {/if}
  425. {/each}
  426. </div>
  427. {/if}
  428. <div class=" flex">
  429. <div class=" ml-0.5 self-end mb-1.5 flex space-x-1">
  430. <InputMenu
  431. bind:webSearchEnabled
  432. bind:selectedToolIds
  433. tools={$tools.reduce((a, e, i, arr) => {
  434. if (availableToolIds.includes(e.id) || ($_user?.role ?? 'user') === 'admin') {
  435. a[e.id] = {
  436. name: e.name,
  437. description: e.meta.description,
  438. enabled: false
  439. };
  440. }
  441. return a;
  442. }, {})}
  443. uploadFilesHandler={() => {
  444. filesInputElement.click();
  445. }}
  446. onClose={async () => {
  447. await tick();
  448. chatTextAreaElement?.focus();
  449. }}
  450. >
  451. <button
  452. class="bg-gray-50 hover:bg-gray-100 text-gray-800 dark:bg-gray-850 dark:text-white dark:hover:bg-gray-800 transition rounded-full p-2 outline-none focus:outline-none"
  453. type="button"
  454. >
  455. <svg
  456. xmlns="http://www.w3.org/2000/svg"
  457. viewBox="0 0 16 16"
  458. fill="currentColor"
  459. class="size-5"
  460. >
  461. <path
  462. d="M8.75 3.75a.75.75 0 0 0-1.5 0v3.5h-3.5a.75.75 0 0 0 0 1.5h3.5v3.5a.75.75 0 0 0 1.5 0v-3.5h3.5a.75.75 0 0 0 0-1.5h-3.5v-3.5Z"
  463. />
  464. </svg>
  465. </button>
  466. </InputMenu>
  467. </div>
  468. <textarea
  469. id="chat-textarea"
  470. bind:this={chatTextAreaElement}
  471. class="scrollbar-hidden bg-gray-50 dark:bg-gray-850 dark:text-gray-100 outline-none w-full py-3 px-1 rounded-xl resize-none h-[48px]"
  472. placeholder={chatInputPlaceholder !== ''
  473. ? chatInputPlaceholder
  474. : $i18n.t('Send a Message')}
  475. bind:value={prompt}
  476. on:keypress={(e) => {
  477. if (
  478. !$mobile ||
  479. !(
  480. 'ontouchstart' in window ||
  481. navigator.maxTouchPoints > 0 ||
  482. navigator.msMaxTouchPoints > 0
  483. )
  484. ) {
  485. // Prevent Enter key from creating a new line
  486. if (e.key === 'Enter' && !e.shiftKey) {
  487. e.preventDefault();
  488. }
  489. // Submit the prompt when Enter key is pressed
  490. if (prompt !== '' && e.key === 'Enter' && !e.shiftKey) {
  491. submitPrompt(prompt);
  492. }
  493. }
  494. }}
  495. on:keydown={async (e) => {
  496. const isCtrlPressed = e.ctrlKey || e.metaKey; // metaKey is for Cmd key on Mac
  497. const commandsContainerElement = document.getElementById('commands-container');
  498. // Check if Ctrl + R is pressed
  499. if (prompt === '' && isCtrlPressed && e.key.toLowerCase() === 'r') {
  500. e.preventDefault();
  501. console.log('regenerate');
  502. const regenerateButton = [
  503. ...document.getElementsByClassName('regenerate-response-button')
  504. ]?.at(-1);
  505. regenerateButton?.click();
  506. }
  507. if (prompt === '' && e.key == 'ArrowUp') {
  508. e.preventDefault();
  509. const userMessageElement = [
  510. ...document.getElementsByClassName('user-message')
  511. ]?.at(-1);
  512. const editButton = [
  513. ...document.getElementsByClassName('edit-user-message-button')
  514. ]?.at(-1);
  515. console.log(userMessageElement);
  516. userMessageElement.scrollIntoView({ block: 'center' });
  517. editButton?.click();
  518. }
  519. if (commandsContainerElement && e.key === 'ArrowUp') {
  520. e.preventDefault();
  521. commandsElement.selectUp();
  522. const commandOptionButton = [
  523. ...document.getElementsByClassName('selected-command-option-button')
  524. ]?.at(-1);
  525. commandOptionButton.scrollIntoView({ block: 'center' });
  526. }
  527. if (commandsContainerElement && e.key === 'ArrowDown') {
  528. e.preventDefault();
  529. commandsElement.selectDown();
  530. const commandOptionButton = [
  531. ...document.getElementsByClassName('selected-command-option-button')
  532. ]?.at(-1);
  533. commandOptionButton.scrollIntoView({ block: 'center' });
  534. }
  535. if (commandsContainerElement && e.key === 'Enter') {
  536. e.preventDefault();
  537. const commandOptionButton = [
  538. ...document.getElementsByClassName('selected-command-option-button')
  539. ]?.at(-1);
  540. if (e.shiftKey) {
  541. prompt = `${prompt}\n`;
  542. } else if (commandOptionButton) {
  543. commandOptionButton?.click();
  544. } else {
  545. document.getElementById('send-message-button')?.click();
  546. }
  547. }
  548. if (commandsContainerElement && e.key === 'Tab') {
  549. e.preventDefault();
  550. const commandOptionButton = [
  551. ...document.getElementsByClassName('selected-command-option-button')
  552. ]?.at(-1);
  553. commandOptionButton?.click();
  554. } else if (e.key === 'Tab') {
  555. const words = findWordIndices(prompt);
  556. if (words.length > 0) {
  557. const word = words.at(0);
  558. const fullPrompt = prompt;
  559. prompt = prompt.substring(0, word?.endIndex + 1);
  560. await tick();
  561. e.target.scrollTop = e.target.scrollHeight;
  562. prompt = fullPrompt;
  563. await tick();
  564. e.preventDefault();
  565. e.target.setSelectionRange(word?.startIndex, word.endIndex + 1);
  566. }
  567. e.target.style.height = '';
  568. e.target.style.height = Math.min(e.target.scrollHeight, 200) + 'px';
  569. }
  570. if (e.key === 'Escape') {
  571. console.log('Escape');
  572. atSelectedModel = undefined;
  573. }
  574. }}
  575. rows="1"
  576. on:input={(e) => {
  577. e.target.style.height = '';
  578. e.target.style.height = Math.min(e.target.scrollHeight, 200) + 'px';
  579. user = null;
  580. }}
  581. on:focus={(e) => {
  582. e.target.style.height = '';
  583. e.target.style.height = Math.min(e.target.scrollHeight, 200) + 'px';
  584. }}
  585. on:paste={(e) => {
  586. const clipboardData = e.clipboardData || window.clipboardData;
  587. if (clipboardData && clipboardData.items) {
  588. for (const item of clipboardData.items) {
  589. if (item.type.indexOf('image') !== -1) {
  590. const blob = item.getAsFile();
  591. const reader = new FileReader();
  592. reader.onload = function (e) {
  593. files = [
  594. ...files,
  595. {
  596. type: 'image',
  597. url: `${e.target.result}`
  598. }
  599. ];
  600. };
  601. reader.readAsDataURL(blob);
  602. }
  603. }
  604. }
  605. }}
  606. />
  607. <div class="self-end mb-2 flex space-x-1 mr-1">
  608. {#if messages.length == 0 || messages.at(-1).done == true}
  609. <Tooltip content={$i18n.t('Record voice')}>
  610. <button
  611. id="voice-input-button"
  612. class=" text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-850 transition rounded-full p-1.5 mr-0.5 self-center"
  613. type="button"
  614. on:click={async () => {
  615. try {
  616. let stream = await navigator.mediaDevices
  617. .getUserMedia({ audio: true })
  618. .catch(function (err) {
  619. toast.error(
  620. $i18n.t(
  621. `Permission denied when accessing microphone: {{error}}`,
  622. {
  623. error: err
  624. }
  625. )
  626. );
  627. return null;
  628. });
  629. if (stream) {
  630. recording = true;
  631. const tracks = stream.getTracks();
  632. tracks.forEach((track) => track.stop());
  633. }
  634. stream = null;
  635. } catch {
  636. toast.error($i18n.t('Permission denied when accessing microphone'));
  637. }
  638. }}
  639. >
  640. <svg
  641. xmlns="http://www.w3.org/2000/svg"
  642. viewBox="0 0 20 20"
  643. fill="currentColor"
  644. class="w-5 h-5 translate-y-[0.5px]"
  645. >
  646. <path d="M7 4a3 3 0 016 0v6a3 3 0 11-6 0V4z" />
  647. <path
  648. d="M5.5 9.643a.75.75 0 00-1.5 0V10c0 3.06 2.29 5.585 5.25 5.954V17.5h-1.5a.75.75 0 000 1.5h4.5a.75.75 0 000-1.5h-1.5v-1.546A6.001 6.001 0 0016 10v-.357a.75.75 0 00-1.5 0V10a4.5 4.5 0 01-9 0v-.357z"
  649. />
  650. </svg>
  651. </button>
  652. </Tooltip>
  653. {/if}
  654. </div>
  655. </div>
  656. </div>
  657. <div class="flex items-end w-10">
  658. {#if messages.length == 0 || messages.at(-1).done == true}
  659. {#if prompt === ''}
  660. <div class=" flex items-center mb-1">
  661. <Tooltip content={$i18n.t('Call')}>
  662. <button
  663. class=" text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-850 transition rounded-full p-2 self-center"
  664. type="button"
  665. on:click={async () => {
  666. if (selectedModels.length > 1) {
  667. toast.error($i18n.t('Select only one model to call'));
  668. return;
  669. }
  670. if ($config.audio.stt.engine === 'web') {
  671. toast.error(
  672. $i18n.t('Call feature is not supported when using Web STT engine')
  673. );
  674. return;
  675. }
  676. // check if user has access to getUserMedia
  677. try {
  678. let stream = await navigator.mediaDevices.getUserMedia({ audio: true });
  679. // If the user grants the permission, proceed to show the call overlay
  680. stream.getTracks().forEach((track) => track.stop());
  681. stream = null;
  682. showCallOverlay.set(true);
  683. dispatch('call');
  684. } catch (err) {
  685. // If the user denies the permission or an error occurs, show an error message
  686. toast.error($i18n.t('Permission denied when accessing media devices'));
  687. }
  688. }}
  689. >
  690. <Headphone className="size-6" />
  691. </button>
  692. </Tooltip>
  693. </div>
  694. {:else}
  695. <div class=" flex items-center mb-1">
  696. <Tooltip content={$i18n.t('Send message')}>
  697. <button
  698. id="send-message-button"
  699. class="{prompt !== ''
  700. ? 'bg-black text-white hover:bg-gray-900 dark:bg-white dark:text-black dark:hover:bg-gray-100 '
  701. : 'text-white bg-gray-200 dark:text-gray-900 dark:bg-gray-700 disabled'} transition rounded-full p-1.5 m-0.5 self-center"
  702. type="submit"
  703. disabled={prompt === ''}
  704. >
  705. <svg
  706. xmlns="http://www.w3.org/2000/svg"
  707. viewBox="0 0 16 16"
  708. fill="currentColor"
  709. class="size-6"
  710. >
  711. <path
  712. fill-rule="evenodd"
  713. d="M8 14a.75.75 0 0 1-.75-.75V4.56L4.03 7.78a.75.75 0 0 1-1.06-1.06l4.5-4.5a.75.75 0 0 1 1.06 0l4.5 4.5a.75.75 0 0 1-1.06 1.06L8.75 4.56v8.69A.75.75 0 0 1 8 14Z"
  714. clip-rule="evenodd"
  715. />
  716. </svg>
  717. </button>
  718. </Tooltip>
  719. </div>
  720. {/if}
  721. {:else}
  722. <div class=" flex items-center mb-1.5">
  723. <button
  724. class="bg-white hover:bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-white dark:hover:bg-gray-800 transition rounded-full p-1.5"
  725. on:click={() => {
  726. stopResponse();
  727. }}
  728. >
  729. <svg
  730. xmlns="http://www.w3.org/2000/svg"
  731. viewBox="0 0 24 24"
  732. fill="currentColor"
  733. class="size-6"
  734. >
  735. <path
  736. fill-rule="evenodd"
  737. d="M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12zm6-2.438c0-.724.588-1.312 1.313-1.312h4.874c.725 0 1.313.588 1.313 1.313v4.874c0 .725-.588 1.313-1.313 1.313H9.564a1.312 1.312 0 01-1.313-1.313V9.564z"
  738. clip-rule="evenodd"
  739. />
  740. </svg>
  741. </button>
  742. </div>
  743. {/if}
  744. </div>
  745. </form>
  746. {/if}
  747. <div class="mt-1.5 text-xs text-gray-500 text-center line-clamp-1">
  748. {$i18n.t('LLMs can make mistakes. Verify important information.')}
  749. </div>
  750. </div>
  751. </div>
  752. </div>
  753. </div>
  754. <style>
  755. .scrollbar-hidden:active::-webkit-scrollbar-thumb,
  756. .scrollbar-hidden:focus::-webkit-scrollbar-thumb,
  757. .scrollbar-hidden:hover::-webkit-scrollbar-thumb {
  758. visibility: visible;
  759. }
  760. .scrollbar-hidden::-webkit-scrollbar-thumb {
  761. visibility: hidden;
  762. }
  763. </style>