MessageInput.svelte 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022
  1. <script lang="ts">
  2. import { toast } from 'svelte-sonner';
  3. import { onMount, tick, getContext } from 'svelte';
  4. import {
  5. type Model,
  6. mobile,
  7. settings,
  8. showSidebar,
  9. models,
  10. config,
  11. showCallOverlay,
  12. tools,
  13. user as _user
  14. } from '$lib/stores';
  15. import { blobToFile, calculateSHA256, findWordIndices } from '$lib/utils';
  16. import {
  17. uploadDocToVectorDB,
  18. uploadWebToVectorDB,
  19. uploadYoutubeTranscriptionToVectorDB
  20. } from '$lib/apis/rag';
  21. import { SUPPORTED_FILE_TYPE, SUPPORTED_FILE_EXTENSIONS, WEBUI_BASE_URL } from '$lib/constants';
  22. import Prompts from './MessageInput/PromptCommands.svelte';
  23. import Suggestions from './MessageInput/Suggestions.svelte';
  24. import AddFilesPlaceholder from '../AddFilesPlaceholder.svelte';
  25. import Documents from './MessageInput/Documents.svelte';
  26. import Models from './MessageInput/Models.svelte';
  27. import Tooltip from '../common/Tooltip.svelte';
  28. import XMark from '$lib/components/icons/XMark.svelte';
  29. import InputMenu from './MessageInput/InputMenu.svelte';
  30. import Headphone from '../icons/Headphone.svelte';
  31. import VoiceRecording from './MessageInput/VoiceRecording.svelte';
  32. import { transcribeAudio } from '$lib/apis/audio';
  33. const i18n = getContext('i18n');
  34. export let submitPrompt: Function;
  35. export let stopResponse: Function;
  36. export let autoScroll = true;
  37. export let atSelectedModel: Model | undefined;
  38. export let selectedModels: [''];
  39. let recording = false;
  40. let chatTextAreaElement: HTMLTextAreaElement;
  41. let filesInputElement;
  42. let promptsElement;
  43. let documentsElement;
  44. let modelsElement;
  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.scrollTop = element.scrollHeight;
  68. };
  69. const uploadDoc = async (file) => {
  70. console.log(file);
  71. const doc = {
  72. type: 'doc',
  73. name: file.name,
  74. collection_name: '',
  75. upload_status: false,
  76. error: ''
  77. };
  78. try {
  79. files = [...files, doc];
  80. if (['audio/mpeg', 'audio/wav'].includes(file['type'])) {
  81. const res = await transcribeAudio(localStorage.token, file).catch((error) => {
  82. toast.error(error);
  83. return null;
  84. });
  85. if (res) {
  86. console.log(res);
  87. const blob = new Blob([res.text], { type: 'text/plain' });
  88. file = blobToFile(blob, `${file.name}.txt`);
  89. }
  90. }
  91. const res = await uploadDocToVectorDB(localStorage.token, '', file);
  92. if (res) {
  93. doc.upload_status = true;
  94. doc.collection_name = res.collection_name;
  95. files = files;
  96. }
  97. } catch (e) {
  98. // Remove the failed doc from the files array
  99. files = files.filter((f) => f.name !== file.name);
  100. toast.error(e);
  101. }
  102. };
  103. const uploadWeb = async (url) => {
  104. console.log(url);
  105. const doc = {
  106. type: 'doc',
  107. name: url,
  108. collection_name: '',
  109. upload_status: false,
  110. url: url,
  111. error: ''
  112. };
  113. try {
  114. files = [...files, doc];
  115. const res = await uploadWebToVectorDB(localStorage.token, '', url);
  116. if (res) {
  117. doc.upload_status = true;
  118. doc.collection_name = res.collection_name;
  119. files = files;
  120. }
  121. } catch (e) {
  122. // Remove the failed doc from the files array
  123. files = files.filter((f) => f.name !== url);
  124. toast.error(e);
  125. }
  126. };
  127. const uploadYoutubeTranscription = async (url) => {
  128. console.log(url);
  129. const doc = {
  130. type: 'doc',
  131. name: url,
  132. collection_name: '',
  133. upload_status: false,
  134. url: url,
  135. error: ''
  136. };
  137. try {
  138. files = [...files, doc];
  139. const res = await uploadYoutubeTranscriptionToVectorDB(localStorage.token, url);
  140. if (res) {
  141. doc.upload_status = true;
  142. doc.collection_name = res.collection_name;
  143. files = files;
  144. }
  145. } catch (e) {
  146. // Remove the failed doc from the files array
  147. files = files.filter((f) => f.name !== url);
  148. toast.error(e);
  149. }
  150. };
  151. onMount(() => {
  152. window.setTimeout(() => chatTextAreaElement?.focus(), 0);
  153. const dropZone = document.querySelector('body');
  154. const handleKeyDown = (event: KeyboardEvent) => {
  155. if (event.key === 'Escape') {
  156. console.log('Escape');
  157. dragged = false;
  158. }
  159. };
  160. const onDragOver = (e) => {
  161. e.preventDefault();
  162. dragged = true;
  163. };
  164. const onDragLeave = () => {
  165. dragged = false;
  166. };
  167. const onDrop = async (e) => {
  168. e.preventDefault();
  169. console.log(e);
  170. if (e.dataTransfer?.files) {
  171. const inputFiles = Array.from(e.dataTransfer?.files);
  172. if (inputFiles && inputFiles.length > 0) {
  173. inputFiles.forEach((file) => {
  174. console.log(file, file.name.split('.').at(-1));
  175. if (['image/gif', 'image/webp', 'image/jpeg', 'image/png'].includes(file['type'])) {
  176. if (visionCapableModels.length === 0) {
  177. toast.error($i18n.t('Selected model(s) do not support image inputs'));
  178. return;
  179. }
  180. let reader = new FileReader();
  181. reader.onload = (event) => {
  182. files = [
  183. ...files,
  184. {
  185. type: 'image',
  186. url: `${event.target.result}`
  187. }
  188. ];
  189. };
  190. reader.readAsDataURL(file);
  191. } else if (
  192. SUPPORTED_FILE_TYPE.includes(file['type']) ||
  193. SUPPORTED_FILE_EXTENSIONS.includes(file.name.split('.').at(-1))
  194. ) {
  195. uploadDoc(file);
  196. } else {
  197. toast.error(
  198. $i18n.t(
  199. `Unknown File Type '{{file_type}}', but accepting and treating as plain text`,
  200. { file_type: file['type'] }
  201. )
  202. );
  203. uploadDoc(file);
  204. }
  205. });
  206. } else {
  207. toast.error($i18n.t(`File not found.`));
  208. }
  209. }
  210. dragged = false;
  211. };
  212. window.addEventListener('keydown', handleKeyDown);
  213. dropZone?.addEventListener('dragover', onDragOver);
  214. dropZone?.addEventListener('drop', onDrop);
  215. dropZone?.addEventListener('dragleave', onDragLeave);
  216. return () => {
  217. window.removeEventListener('keydown', handleKeyDown);
  218. dropZone?.removeEventListener('dragover', onDragOver);
  219. dropZone?.removeEventListener('drop', onDrop);
  220. dropZone?.removeEventListener('dragleave', onDragLeave);
  221. };
  222. });
  223. </script>
  224. {#if dragged}
  225. <div
  226. class="fixed {$showSidebar
  227. ? 'left-0 md:left-[260px] md:w-[calc(100%-260px)]'
  228. : 'left-0'} w-full h-full flex z-50 touch-none pointer-events-none"
  229. id="dropzone"
  230. role="region"
  231. aria-label="Drag and Drop Container"
  232. >
  233. <div class="absolute w-full h-full backdrop-blur bg-gray-800/40 flex justify-center">
  234. <div class="m-auto pt-64 flex flex-col justify-center">
  235. <div class="max-w-md">
  236. <AddFilesPlaceholder />
  237. </div>
  238. </div>
  239. </div>
  240. </div>
  241. {/if}
  242. <div class="w-full">
  243. <div class=" -mb-0.5 mx-auto inset-x-0 bg-transparent flex justify-center">
  244. <div class="flex flex-col max-w-6xl px-2.5 md:px-6 w-full">
  245. <div class="relative">
  246. {#if autoScroll === false && messages.length > 0}
  247. <div class=" absolute -top-12 left-0 right-0 flex justify-center z-30">
  248. <button
  249. class=" bg-white border border-gray-100 dark:border-none dark:bg-white/20 p-1.5 rounded-full"
  250. on:click={() => {
  251. autoScroll = true;
  252. scrollToBottom();
  253. }}
  254. >
  255. <svg
  256. xmlns="http://www.w3.org/2000/svg"
  257. viewBox="0 0 20 20"
  258. fill="currentColor"
  259. class="w-5 h-5"
  260. >
  261. <path
  262. fill-rule="evenodd"
  263. 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"
  264. clip-rule="evenodd"
  265. />
  266. </svg>
  267. </button>
  268. </div>
  269. {/if}
  270. </div>
  271. <div class="w-full relative">
  272. {#if prompt.charAt(0) === '/'}
  273. <Prompts bind:this={promptsElement} bind:prompt bind:files />
  274. {:else if prompt.charAt(0) === '#'}
  275. <Documents
  276. bind:this={documentsElement}
  277. bind:prompt
  278. on:youtube={(e) => {
  279. console.log(e);
  280. uploadYoutubeTranscription(e.detail);
  281. }}
  282. on:url={(e) => {
  283. console.log(e);
  284. uploadWeb(e.detail);
  285. }}
  286. on:select={(e) => {
  287. console.log(e);
  288. files = [
  289. ...files,
  290. {
  291. type: e?.detail?.type ?? 'doc',
  292. ...e.detail,
  293. upload_status: true
  294. }
  295. ];
  296. }}
  297. />
  298. {/if}
  299. <Models
  300. bind:this={modelsElement}
  301. bind:prompt
  302. bind:chatInputPlaceholder
  303. {messages}
  304. on:select={(e) => {
  305. atSelectedModel = e.detail;
  306. chatTextAreaElement?.focus();
  307. }}
  308. />
  309. {#if atSelectedModel !== undefined}
  310. <div
  311. class="px-3 py-2.5 text-left w-full flex justify-between items-center absolute bottom-0 left-0 right-0 bg-gradient-to-t from-50% from-white dark:from-gray-900"
  312. >
  313. <div class="flex items-center gap-2 text-sm dark:text-gray-500">
  314. <img
  315. crossorigin="anonymous"
  316. alt="model profile"
  317. class="size-5 max-w-[28px] object-cover rounded-full"
  318. src={$models.find((model) => model.id === atSelectedModel.id)?.info?.meta
  319. ?.profile_image_url ??
  320. ($i18n.language === 'dg-DG'
  321. ? `/doge.png`
  322. : `${WEBUI_BASE_URL}/static/favicon.png`)}
  323. />
  324. <div>
  325. Talking to <span class=" font-medium">{atSelectedModel.name}</span>
  326. </div>
  327. </div>
  328. <div>
  329. <button
  330. class="flex items-center"
  331. on:click={() => {
  332. atSelectedModel = undefined;
  333. }}
  334. >
  335. <XMark />
  336. </button>
  337. </div>
  338. </div>
  339. {/if}
  340. </div>
  341. </div>
  342. </div>
  343. <div class="bg-white dark:bg-gray-900">
  344. <div class="max-w-6xl px-2.5 md:px-6 mx-auto inset-x-0">
  345. <div class=" pb-2">
  346. <input
  347. bind:this={filesInputElement}
  348. bind:files={inputFiles}
  349. type="file"
  350. hidden
  351. multiple
  352. on:change={async () => {
  353. if (inputFiles && inputFiles.length > 0) {
  354. const _inputFiles = Array.from(inputFiles);
  355. _inputFiles.forEach((file) => {
  356. if (['image/gif', 'image/webp', 'image/jpeg', 'image/png'].includes(file['type'])) {
  357. if (visionCapableModels.length === 0) {
  358. toast.error($i18n.t('Selected model(s) do not support image inputs'));
  359. inputFiles = null;
  360. filesInputElement.value = '';
  361. return;
  362. }
  363. let reader = new FileReader();
  364. reader.onload = (event) => {
  365. files = [
  366. ...files,
  367. {
  368. type: 'image',
  369. url: `${event.target.result}`
  370. }
  371. ];
  372. inputFiles = null;
  373. filesInputElement.value = '';
  374. };
  375. reader.readAsDataURL(file);
  376. } else if (
  377. SUPPORTED_FILE_TYPE.includes(file['type']) ||
  378. SUPPORTED_FILE_EXTENSIONS.includes(file.name.split('.').at(-1))
  379. ) {
  380. uploadDoc(file);
  381. filesInputElement.value = '';
  382. } else {
  383. toast.error(
  384. $i18n.t(
  385. `Unknown File Type '{{file_type}}', but accepting and treating as plain text`,
  386. { file_type: file['type'] }
  387. )
  388. );
  389. uploadDoc(file);
  390. filesInputElement.value = '';
  391. }
  392. });
  393. } else {
  394. toast.error($i18n.t(`File not found.`));
  395. }
  396. }}
  397. />
  398. {#if recording}
  399. <VoiceRecording
  400. bind:recording
  401. on:cancel={async () => {
  402. recording = false;
  403. await tick();
  404. document.getElementById('chat-textarea')?.focus();
  405. }}
  406. on:confirm={async (e) => {
  407. const response = e.detail;
  408. prompt = `${prompt}${response} `;
  409. recording = false;
  410. await tick();
  411. document.getElementById('chat-textarea')?.focus();
  412. if ($settings?.speechAutoSend ?? false) {
  413. submitPrompt(prompt);
  414. }
  415. }}
  416. />
  417. {:else}
  418. <form
  419. class="w-full flex gap-1.5"
  420. on:submit|preventDefault={() => {
  421. // check if selectedModels support image input
  422. submitPrompt(prompt);
  423. }}
  424. >
  425. <div
  426. 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"
  427. dir={$settings?.chatDirection ?? 'LTR'}
  428. >
  429. {#if files.length > 0}
  430. <div class="mx-2 mt-2 mb-1 flex flex-wrap gap-2">
  431. {#each files as file, fileIdx}
  432. <div class=" relative group">
  433. {#if file.type === 'image'}
  434. <div class="relative">
  435. <img
  436. src={file.url}
  437. alt="input"
  438. class=" h-16 w-16 rounded-xl object-cover"
  439. />
  440. {#if atSelectedModel ? visionCapableModels.length === 0 : selectedModels.length !== visionCapableModels.length}
  441. <Tooltip
  442. className=" absolute top-1 left-1"
  443. content={$i18n.t('{{ models }}', {
  444. models: [...(atSelectedModel ? [atSelectedModel] : selectedModels)]
  445. .filter((id) => !visionCapableModels.includes(id))
  446. .join(', ')
  447. })}
  448. >
  449. <svg
  450. xmlns="http://www.w3.org/2000/svg"
  451. viewBox="0 0 24 24"
  452. fill="currentColor"
  453. class="size-4 fill-yellow-300"
  454. >
  455. <path
  456. fill-rule="evenodd"
  457. 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"
  458. clip-rule="evenodd"
  459. />
  460. </svg>
  461. </Tooltip>
  462. {/if}
  463. </div>
  464. {:else if file.type === 'doc'}
  465. <div
  466. class="h-16 w-[15rem] flex items-center space-x-3 px-2.5 dark:bg-gray-600 rounded-xl border border-gray-200 dark:border-none"
  467. >
  468. <div class="p-2.5 bg-red-400 text-white rounded-lg">
  469. {#if file.upload_status}
  470. <svg
  471. xmlns="http://www.w3.org/2000/svg"
  472. viewBox="0 0 24 24"
  473. fill="currentColor"
  474. class="w-6 h-6"
  475. >
  476. <path
  477. fill-rule="evenodd"
  478. d="M5.625 1.5c-1.036 0-1.875.84-1.875 1.875v17.25c0 1.035.84 1.875 1.875 1.875h12.75c1.035 0 1.875-.84 1.875-1.875V12.75A3.75 3.75 0 0 0 16.5 9h-1.875a1.875 1.875 0 0 1-1.875-1.875V5.25A3.75 3.75 0 0 0 9 1.5H5.625ZM7.5 15a.75.75 0 0 1 .75-.75h7.5a.75.75 0 0 1 0 1.5h-7.5A.75.75 0 0 1 7.5 15Zm.75 2.25a.75.75 0 0 0 0 1.5H12a.75.75 0 0 0 0-1.5H8.25Z"
  479. clip-rule="evenodd"
  480. />
  481. <path
  482. d="M12.971 1.816A5.23 5.23 0 0 1 14.25 5.25v1.875c0 .207.168.375.375.375H16.5a5.23 5.23 0 0 1 3.434 1.279 9.768 9.768 0 0 0-6.963-6.963Z"
  483. />
  484. </svg>
  485. {:else}
  486. <svg
  487. class=" w-6 h-6 translate-y-[0.5px]"
  488. fill="currentColor"
  489. viewBox="0 0 24 24"
  490. xmlns="http://www.w3.org/2000/svg"
  491. ><style>
  492. .spinner_qM83 {
  493. animation: spinner_8HQG 1.05s infinite;
  494. }
  495. .spinner_oXPr {
  496. animation-delay: 0.1s;
  497. }
  498. .spinner_ZTLf {
  499. animation-delay: 0.2s;
  500. }
  501. @keyframes spinner_8HQG {
  502. 0%,
  503. 57.14% {
  504. animation-timing-function: cubic-bezier(0.33, 0.66, 0.66, 1);
  505. transform: translate(0);
  506. }
  507. 28.57% {
  508. animation-timing-function: cubic-bezier(0.33, 0, 0.66, 0.33);
  509. transform: translateY(-6px);
  510. }
  511. 100% {
  512. transform: translate(0);
  513. }
  514. }
  515. </style><circle
  516. class="spinner_qM83"
  517. cx="4"
  518. cy="12"
  519. r="2.5"
  520. /><circle
  521. class="spinner_qM83 spinner_oXPr"
  522. cx="12"
  523. cy="12"
  524. r="2.5"
  525. /><circle
  526. class="spinner_qM83 spinner_ZTLf"
  527. cx="20"
  528. cy="12"
  529. r="2.5"
  530. /></svg
  531. >
  532. {/if}
  533. </div>
  534. <div class="flex flex-col justify-center -space-y-0.5">
  535. <div class=" dark:text-gray-100 text-sm font-medium line-clamp-1">
  536. {file.name}
  537. </div>
  538. <div class=" text-gray-500 text-sm">{$i18n.t('Document')}</div>
  539. </div>
  540. </div>
  541. {:else if file.type === 'collection'}
  542. <div
  543. class="h-16 w-[15rem] flex items-center space-x-3 px-2.5 dark:bg-gray-600 rounded-xl border border-gray-200 dark:border-none"
  544. >
  545. <div class="p-2.5 bg-red-400 text-white rounded-lg">
  546. <svg
  547. xmlns="http://www.w3.org/2000/svg"
  548. viewBox="0 0 24 24"
  549. fill="currentColor"
  550. class="w-6 h-6"
  551. >
  552. <path
  553. d="M7.5 3.375c0-1.036.84-1.875 1.875-1.875h.375a3.75 3.75 0 0 1 3.75 3.75v1.875C13.5 8.161 14.34 9 15.375 9h1.875A3.75 3.75 0 0 1 21 12.75v3.375C21 17.16 20.16 18 19.125 18h-9.75A1.875 1.875 0 0 1 7.5 16.125V3.375Z"
  554. />
  555. <path
  556. d="M15 5.25a5.23 5.23 0 0 0-1.279-3.434 9.768 9.768 0 0 1 6.963 6.963A5.23 5.23 0 0 0 17.25 7.5h-1.875A.375.375 0 0 1 15 7.125V5.25ZM4.875 6H6v10.125A3.375 3.375 0 0 0 9.375 19.5H16.5v1.125c0 1.035-.84 1.875-1.875 1.875h-9.75A1.875 1.875 0 0 1 3 20.625V7.875C3 6.839 3.84 6 4.875 6Z"
  557. />
  558. </svg>
  559. </div>
  560. <div class="flex flex-col justify-center -space-y-0.5">
  561. <div class=" dark:text-gray-100 text-sm font-medium line-clamp-1">
  562. {file?.title ?? `#${file.name}`}
  563. </div>
  564. <div class=" text-gray-500 text-sm">{$i18n.t('Collection')}</div>
  565. </div>
  566. </div>
  567. {/if}
  568. <div class=" absolute -top-1 -right-1">
  569. <button
  570. class=" bg-gray-400 text-white border border-white rounded-full group-hover:visible invisible transition"
  571. type="button"
  572. on:click={() => {
  573. files.splice(fileIdx, 1);
  574. files = files;
  575. }}
  576. >
  577. <svg
  578. xmlns="http://www.w3.org/2000/svg"
  579. viewBox="0 0 20 20"
  580. fill="currentColor"
  581. class="w-4 h-4"
  582. >
  583. <path
  584. 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"
  585. />
  586. </svg>
  587. </button>
  588. </div>
  589. </div>
  590. {/each}
  591. </div>
  592. {/if}
  593. <div class=" flex">
  594. <div class=" ml-0.5 self-end mb-1.5 flex space-x-1">
  595. <InputMenu
  596. bind:webSearchEnabled
  597. bind:selectedToolIds
  598. tools={$tools.reduce((a, e, i, arr) => {
  599. if (availableToolIds.includes(e.id) || ($_user?.role ?? 'user') === 'admin') {
  600. a[e.id] = {
  601. name: e.name,
  602. description: e.meta.description,
  603. enabled: false
  604. };
  605. }
  606. return a;
  607. }, {})}
  608. uploadFilesHandler={() => {
  609. filesInputElement.click();
  610. }}
  611. onClose={async () => {
  612. await tick();
  613. chatTextAreaElement?.focus();
  614. }}
  615. >
  616. <button
  617. 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"
  618. type="button"
  619. >
  620. <svg
  621. xmlns="http://www.w3.org/2000/svg"
  622. viewBox="0 0 16 16"
  623. fill="currentColor"
  624. class="size-5"
  625. >
  626. <path
  627. 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"
  628. />
  629. </svg>
  630. </button>
  631. </InputMenu>
  632. </div>
  633. <textarea
  634. id="chat-textarea"
  635. bind:this={chatTextAreaElement}
  636. 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]"
  637. placeholder={chatInputPlaceholder !== ''
  638. ? chatInputPlaceholder
  639. : $i18n.t('Send a Message')}
  640. bind:value={prompt}
  641. on:keypress={(e) => {
  642. if (
  643. !$mobile ||
  644. !(
  645. 'ontouchstart' in window ||
  646. navigator.maxTouchPoints > 0 ||
  647. navigator.msMaxTouchPoints > 0
  648. )
  649. ) {
  650. // Prevent Enter key from creating a new line
  651. if (e.key === 'Enter' && !e.shiftKey) {
  652. e.preventDefault();
  653. }
  654. // Submit the prompt when Enter key is pressed
  655. if (prompt !== '' && e.key === 'Enter' && !e.shiftKey) {
  656. submitPrompt(prompt);
  657. }
  658. }
  659. }}
  660. on:keydown={async (e) => {
  661. const isCtrlPressed = e.ctrlKey || e.metaKey; // metaKey is for Cmd key on Mac
  662. // Check if Ctrl + R is pressed
  663. if (prompt === '' && isCtrlPressed && e.key.toLowerCase() === 'r') {
  664. e.preventDefault();
  665. console.log('regenerate');
  666. const regenerateButton = [
  667. ...document.getElementsByClassName('regenerate-response-button')
  668. ]?.at(-1);
  669. regenerateButton?.click();
  670. }
  671. if (prompt === '' && e.key == 'ArrowUp') {
  672. e.preventDefault();
  673. const userMessageElement = [
  674. ...document.getElementsByClassName('user-message')
  675. ]?.at(-1);
  676. const editButton = [
  677. ...document.getElementsByClassName('edit-user-message-button')
  678. ]?.at(-1);
  679. console.log(userMessageElement);
  680. userMessageElement.scrollIntoView({ block: 'center' });
  681. editButton?.click();
  682. }
  683. if (['/', '#', '@'].includes(prompt.charAt(0)) && e.key === 'ArrowUp') {
  684. e.preventDefault();
  685. (promptsElement || documentsElement || modelsElement).selectUp();
  686. const commandOptionButton = [
  687. ...document.getElementsByClassName('selected-command-option-button')
  688. ]?.at(-1);
  689. commandOptionButton.scrollIntoView({ block: 'center' });
  690. }
  691. if (['/', '#', '@'].includes(prompt.charAt(0)) && e.key === 'ArrowDown') {
  692. e.preventDefault();
  693. (promptsElement || documentsElement || modelsElement).selectDown();
  694. const commandOptionButton = [
  695. ...document.getElementsByClassName('selected-command-option-button')
  696. ]?.at(-1);
  697. commandOptionButton.scrollIntoView({ block: 'center' });
  698. }
  699. if (['/', '#', '@'].includes(prompt.charAt(0)) && e.key === 'Enter') {
  700. e.preventDefault();
  701. const commandOptionButton = [
  702. ...document.getElementsByClassName('selected-command-option-button')
  703. ]?.at(-1);
  704. if (e.shiftKey) {
  705. prompt = `${prompt}\n`;
  706. } else if (commandOptionButton) {
  707. commandOptionButton?.click();
  708. } else {
  709. document.getElementById('send-message-button')?.click();
  710. }
  711. }
  712. if (['/', '#', '@'].includes(prompt.charAt(0)) && e.key === 'Tab') {
  713. e.preventDefault();
  714. const commandOptionButton = [
  715. ...document.getElementsByClassName('selected-command-option-button')
  716. ]?.at(-1);
  717. commandOptionButton?.click();
  718. } else if (e.key === 'Tab') {
  719. const words = findWordIndices(prompt);
  720. if (words.length > 0) {
  721. const word = words.at(0);
  722. const fullPrompt = prompt;
  723. prompt = prompt.substring(0, word?.endIndex + 1);
  724. await tick();
  725. e.target.scrollTop = e.target.scrollHeight;
  726. prompt = fullPrompt;
  727. await tick();
  728. e.preventDefault();
  729. e.target.setSelectionRange(word?.startIndex, word.endIndex + 1);
  730. }
  731. e.target.style.height = '';
  732. e.target.style.height = Math.min(e.target.scrollHeight, 200) + 'px';
  733. }
  734. if (e.key === 'Escape') {
  735. console.log('Escape');
  736. atSelectedModel = undefined;
  737. }
  738. }}
  739. rows="1"
  740. on:input={(e) => {
  741. e.target.style.height = '';
  742. e.target.style.height = Math.min(e.target.scrollHeight, 200) + 'px';
  743. user = null;
  744. }}
  745. on:focus={(e) => {
  746. e.target.style.height = '';
  747. e.target.style.height = Math.min(e.target.scrollHeight, 200) + 'px';
  748. }}
  749. on:paste={(e) => {
  750. const clipboardData = e.clipboardData || window.clipboardData;
  751. if (clipboardData && clipboardData.items) {
  752. for (const item of clipboardData.items) {
  753. if (item.type.indexOf('image') !== -1) {
  754. const blob = item.getAsFile();
  755. const reader = new FileReader();
  756. reader.onload = function (e) {
  757. files = [
  758. ...files,
  759. {
  760. type: 'image',
  761. url: `${e.target.result}`
  762. }
  763. ];
  764. };
  765. reader.readAsDataURL(blob);
  766. }
  767. }
  768. }
  769. }}
  770. />
  771. <div class="self-end mb-2 flex space-x-1 mr-1">
  772. {#if messages.length == 0 || messages.at(-1).done == true}
  773. <Tooltip content={$i18n.t('Record voice')}>
  774. <button
  775. id="voice-input-button"
  776. 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"
  777. type="button"
  778. on:click={async () => {
  779. try {
  780. const res = await navigator.mediaDevices
  781. .getUserMedia({ audio: true })
  782. .catch(function (err) {
  783. toast.error(
  784. $i18n.t(
  785. `Permission denied when accessing microphone: {{error}}`,
  786. {
  787. error: err
  788. }
  789. )
  790. );
  791. return null;
  792. });
  793. if (res) {
  794. recording = true;
  795. }
  796. } catch {
  797. toast.error($i18n.t('Permission denied when accessing microphone'));
  798. }
  799. }}
  800. >
  801. <svg
  802. xmlns="http://www.w3.org/2000/svg"
  803. viewBox="0 0 20 20"
  804. fill="currentColor"
  805. class="w-5 h-5 translate-y-[0.5px]"
  806. >
  807. <path d="M7 4a3 3 0 016 0v6a3 3 0 11-6 0V4z" />
  808. <path
  809. 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"
  810. />
  811. </svg>
  812. </button>
  813. </Tooltip>
  814. {/if}
  815. </div>
  816. </div>
  817. </div>
  818. <div class="flex items-end w-10">
  819. {#if messages.length == 0 || messages.at(-1).done == true}
  820. {#if prompt === ''}
  821. <div class=" flex items-center mb-1">
  822. <Tooltip content={$i18n.t('Call')}>
  823. <button
  824. class=" text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-850 transition rounded-full p-2 self-center"
  825. type="button"
  826. on:click={async () => {
  827. if (selectedModels.length > 1) {
  828. toast.error($i18n.t('Select only one model to call'));
  829. return;
  830. }
  831. if ($config.audio.stt.engine === 'web') {
  832. toast.error(
  833. $i18n.t('Call feature is not supported when using Web STT engine')
  834. );
  835. return;
  836. }
  837. // check if user has access to getUserMedia
  838. try {
  839. await navigator.mediaDevices.getUserMedia({ audio: true });
  840. // If the user grants the permission, proceed to show the call overlay
  841. showCallOverlay.set(true);
  842. } catch (err) {
  843. // If the user denies the permission or an error occurs, show an error message
  844. toast.error($i18n.t('Permission denied when accessing media devices'));
  845. }
  846. }}
  847. >
  848. <Headphone className="size-6" />
  849. </button>
  850. </Tooltip>
  851. </div>
  852. {:else}
  853. <div class=" flex items-center mb-1">
  854. <Tooltip content={$i18n.t('Send message')}>
  855. <button
  856. id="send-message-button"
  857. class="{prompt !== ''
  858. ? 'bg-black text-white hover:bg-gray-900 dark:bg-white dark:text-black dark:hover:bg-gray-100 '
  859. : '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"
  860. type="submit"
  861. disabled={prompt === ''}
  862. >
  863. <svg
  864. xmlns="http://www.w3.org/2000/svg"
  865. viewBox="0 0 16 16"
  866. fill="currentColor"
  867. class="size-6"
  868. >
  869. <path
  870. fill-rule="evenodd"
  871. 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"
  872. clip-rule="evenodd"
  873. />
  874. </svg>
  875. </button>
  876. </Tooltip>
  877. </div>
  878. {/if}
  879. {:else}
  880. <div class=" flex items-center mb-1.5">
  881. <button
  882. 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"
  883. on:click={() => {
  884. stopResponse();
  885. }}
  886. >
  887. <svg
  888. xmlns="http://www.w3.org/2000/svg"
  889. viewBox="0 0 24 24"
  890. fill="currentColor"
  891. class="size-6"
  892. >
  893. <path
  894. fill-rule="evenodd"
  895. 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"
  896. clip-rule="evenodd"
  897. />
  898. </svg>
  899. </button>
  900. </div>
  901. {/if}
  902. </div>
  903. </form>
  904. {/if}
  905. <div class="mt-1.5 text-xs text-gray-500 text-center line-clamp-1">
  906. {$i18n.t('LLMs can make mistakes. Verify important information.')}
  907. </div>
  908. </div>
  909. </div>
  910. </div>
  911. </div>
  912. <style>
  913. .scrollbar-hidden:active::-webkit-scrollbar-thumb,
  914. .scrollbar-hidden:focus::-webkit-scrollbar-thumb,
  915. .scrollbar-hidden:hover::-webkit-scrollbar-thumb {
  916. visibility: visible;
  917. }
  918. .scrollbar-hidden::-webkit-scrollbar-thumb {
  919. visibility: hidden;
  920. }
  921. </style>