MessageInput.svelte 35 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094
  1. <script lang="ts">
  2. import { toast } from 'svelte-sonner';
  3. import { v4 as uuidv4 } from 'uuid';
  4. import { onMount, tick, getContext, createEventDispatcher, onDestroy } from 'svelte';
  5. const dispatch = createEventDispatcher();
  6. import {
  7. type Model,
  8. mobile,
  9. settings,
  10. showSidebar,
  11. models,
  12. config,
  13. showCallOverlay,
  14. tools,
  15. user as _user,
  16. showControls
  17. } from '$lib/stores';
  18. import { blobToFile, findWordIndices } from '$lib/utils';
  19. import { transcribeAudio } from '$lib/apis/audio';
  20. import { uploadFile } from '$lib/apis/files';
  21. import { WEBUI_BASE_URL, WEBUI_API_BASE_URL } from '$lib/constants';
  22. import Tooltip from '../common/Tooltip.svelte';
  23. import InputMenu from './MessageInput/InputMenu.svelte';
  24. import Headphone from '../icons/Headphone.svelte';
  25. import VoiceRecording from './MessageInput/VoiceRecording.svelte';
  26. import FileItem from '../common/FileItem.svelte';
  27. import FilesOverlay from './MessageInput/FilesOverlay.svelte';
  28. import Commands from './MessageInput/Commands.svelte';
  29. import XMark from '../icons/XMark.svelte';
  30. import RichTextInput from '../common/RichTextInput.svelte';
  31. const i18n = getContext('i18n');
  32. export let transparentBackground = false;
  33. export let createMessagePair: Function;
  34. export let stopResponse: Function;
  35. export let autoScroll = false;
  36. export let atSelectedModel: Model | undefined;
  37. export let selectedModels: [''];
  38. export let history;
  39. export let prompt = '';
  40. export let files = [];
  41. export let availableToolIds = [];
  42. export let selectedToolIds = [];
  43. export let webSearchEnabled = false;
  44. let recording = false;
  45. let chatInputContainerElement;
  46. let chatInputElement;
  47. let filesInputElement;
  48. let commandsElement;
  49. let inputFiles;
  50. let dragged = false;
  51. let user = null;
  52. export let placeholder = '';
  53. let visionCapableModels = [];
  54. $: visionCapableModels = [...(atSelectedModel ? [atSelectedModel] : selectedModels)].filter(
  55. (model) => $models.find((m) => m.id === model)?.info?.meta?.capabilities?.vision ?? true
  56. );
  57. $: if (prompt) {
  58. if (chatInputContainerElement) {
  59. chatInputContainerElement.style.height = '';
  60. chatInputContainerElement.style.height =
  61. Math.min(chatInputContainerElement.scrollHeight, 200) + 'px';
  62. }
  63. }
  64. const scrollToBottom = () => {
  65. const element = document.getElementById('messages-container');
  66. element.scrollTo({
  67. top: element.scrollHeight,
  68. behavior: 'smooth'
  69. });
  70. };
  71. const uploadFileHandler = async (file) => {
  72. console.log(file);
  73. const tempItemId = uuidv4();
  74. const fileItem = {
  75. type: 'file',
  76. file: '',
  77. id: null,
  78. url: '',
  79. name: file.name,
  80. collection_name: '',
  81. status: 'uploading',
  82. size: file.size,
  83. error: '',
  84. itemId: tempItemId
  85. };
  86. if (fileItem.size == 0) {
  87. toast.error($i18n.t('You cannot upload an empty file.'));
  88. return null;
  89. }
  90. files = [...files, fileItem];
  91. // Check if the file is an audio file and transcribe/convert it to text file
  92. if (['audio/mpeg', 'audio/wav', 'audio/ogg', 'audio/x-m4a'].includes(file['type'])) {
  93. const res = await transcribeAudio(localStorage.token, file).catch((error) => {
  94. toast.error(error);
  95. return null;
  96. });
  97. if (res) {
  98. console.log(res);
  99. const blob = new Blob([res.text], { type: 'text/plain' });
  100. file = blobToFile(blob, `${file.name}.txt`);
  101. fileItem.name = file.name;
  102. fileItem.size = file.size;
  103. }
  104. }
  105. try {
  106. // During the file upload, file content is automatically extracted.
  107. const uploadedFile = await uploadFile(localStorage.token, file);
  108. if (uploadedFile) {
  109. if (uploadedFile.error) {
  110. toast.warning(uploadedFile.error);
  111. }
  112. fileItem.status = 'uploaded';
  113. fileItem.file = uploadedFile;
  114. fileItem.id = uploadedFile.id;
  115. fileItem.collection_name = uploadedFile?.meta?.collection_name;
  116. fileItem.url = `${WEBUI_API_BASE_URL}/files/${uploadedFile.id}`;
  117. files = files;
  118. } else {
  119. files = files.filter((item) => item?.itemId !== tempItemId);
  120. }
  121. } catch (e) {
  122. toast.error(e);
  123. files = files.filter((item) => item?.itemId !== tempItemId);
  124. }
  125. };
  126. const inputFilesHandler = async (inputFiles) => {
  127. inputFiles.forEach((file) => {
  128. console.log(file, file.name.split('.').at(-1));
  129. if (
  130. ($config?.file?.max_size ?? null) !== null &&
  131. file.size > ($config?.file?.max_size ?? 0) * 1024 * 1024
  132. ) {
  133. toast.error(
  134. $i18n.t(`File size should not exceed {{maxSize}} MB.`, {
  135. maxSize: $config?.file?.max_size
  136. })
  137. );
  138. return;
  139. }
  140. if (['image/gif', 'image/webp', 'image/jpeg', 'image/png'].includes(file['type'])) {
  141. if (visionCapableModels.length === 0) {
  142. toast.error($i18n.t('Selected model(s) do not support image inputs'));
  143. return;
  144. }
  145. let reader = new FileReader();
  146. reader.onload = (event) => {
  147. files = [
  148. ...files,
  149. {
  150. type: 'image',
  151. url: `${event.target.result}`
  152. }
  153. ];
  154. };
  155. reader.readAsDataURL(file);
  156. } else {
  157. uploadFileHandler(file);
  158. }
  159. });
  160. };
  161. const handleKeyDown = (event: KeyboardEvent) => {
  162. if (event.key === 'Escape') {
  163. console.log('Escape');
  164. dragged = false;
  165. }
  166. };
  167. const onDragOver = (e) => {
  168. e.preventDefault();
  169. // Check if a file is being dragged.
  170. if (e.dataTransfer?.types?.includes('Files')) {
  171. dragged = true;
  172. } else {
  173. dragged = false;
  174. }
  175. };
  176. const onDragLeave = () => {
  177. dragged = false;
  178. };
  179. const onDrop = async (e) => {
  180. e.preventDefault();
  181. console.log(e);
  182. if (e.dataTransfer?.files) {
  183. const inputFiles = Array.from(e.dataTransfer?.files);
  184. if (inputFiles && inputFiles.length > 0) {
  185. console.log(inputFiles);
  186. inputFilesHandler(inputFiles);
  187. }
  188. }
  189. dragged = false;
  190. };
  191. onMount(() => {
  192. window.setTimeout(() => {
  193. const chatInput = document.getElementById('chat-input');
  194. chatInput?.focus();
  195. }, 0);
  196. window.addEventListener('keydown', handleKeyDown);
  197. const dropZone = document.getElementById('chat-container');
  198. dropZone?.addEventListener('dragover', onDragOver);
  199. dropZone?.addEventListener('drop', onDrop);
  200. dropZone?.addEventListener('dragleave', onDragLeave);
  201. });
  202. onDestroy(() => {
  203. window.removeEventListener('keydown', handleKeyDown);
  204. const dropZone = document.getElementById('chat-container');
  205. dropZone?.removeEventListener('dragover', onDragOver);
  206. dropZone?.removeEventListener('drop', onDrop);
  207. dropZone?.removeEventListener('dragleave', onDragLeave);
  208. });
  209. </script>
  210. <FilesOverlay show={dragged} />
  211. <div class="w-full font-primary">
  212. <div class=" -mb-0.5 mx-auto inset-x-0 bg-transparent flex justify-center">
  213. <div class="flex flex-col px-2.5 max-w-6xl w-full">
  214. <div class="relative">
  215. {#if autoScroll === false && history?.currentId}
  216. <div
  217. class=" absolute -top-12 left-0 right-0 flex justify-center z-30 pointer-events-none"
  218. >
  219. <button
  220. class=" bg-white border border-gray-100 dark:border-none dark:bg-white/20 p-1.5 rounded-full pointer-events-auto"
  221. on:click={() => {
  222. autoScroll = true;
  223. scrollToBottom();
  224. }}
  225. >
  226. <svg
  227. xmlns="http://www.w3.org/2000/svg"
  228. viewBox="0 0 20 20"
  229. fill="currentColor"
  230. class="w-5 h-5"
  231. >
  232. <path
  233. fill-rule="evenodd"
  234. 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"
  235. clip-rule="evenodd"
  236. />
  237. </svg>
  238. </button>
  239. </div>
  240. {/if}
  241. </div>
  242. <div class="w-full relative">
  243. {#if atSelectedModel !== undefined || selectedToolIds.length > 0 || webSearchEnabled}
  244. <div
  245. class="px-3 pb-0.5 pt-1.5 text-left w-full flex flex-col absolute bottom-0 left-0 right-0 bg-gradient-to-t from-white dark:from-gray-900 z-10"
  246. >
  247. {#if atSelectedModel !== undefined}
  248. <div class="flex items-center justify-between w-full">
  249. <div class="flex items-center gap-2 text-sm dark:text-gray-500">
  250. <img
  251. crossorigin="anonymous"
  252. alt="model profile"
  253. class="size-3.5 max-w-[28px] object-cover rounded-full"
  254. src={$models.find((model) => model.id === atSelectedModel.id)?.info?.meta
  255. ?.profile_image_url ??
  256. ($i18n.language === 'dg-DG'
  257. ? `/doge.png`
  258. : `${WEBUI_BASE_URL}/static/favicon.png`)}
  259. />
  260. <div class="translate-y-[0.5px]">
  261. Talking to <span class=" font-medium">{atSelectedModel.name}</span>
  262. </div>
  263. </div>
  264. <div>
  265. <button
  266. class="flex items-center dark:text-gray-500"
  267. on:click={() => {
  268. atSelectedModel = undefined;
  269. }}
  270. >
  271. <XMark />
  272. </button>
  273. </div>
  274. </div>
  275. {/if}
  276. {#if selectedToolIds.length > 0}
  277. <div class="flex items-center justify-between w-full">
  278. <div class="flex items-center gap-2 text-sm dark:text-gray-500">
  279. <div>
  280. <svg
  281. xmlns="http://www.w3.org/2000/svg"
  282. viewBox="0 0 16 16"
  283. fill="currentColor"
  284. class="size-3.5"
  285. >
  286. <path
  287. fill-rule="evenodd"
  288. d="M11.5 8a3.5 3.5 0 0 0 3.362-4.476c-.094-.325-.497-.39-.736-.15L12.099 5.4a.48.48 0 0 1-.653.033 8.554 8.554 0 0 1-.879-.879.48.48 0 0 1 .033-.653l2.027-2.028c.24-.239.175-.642-.15-.736a3.502 3.502 0 0 0-4.476 3.427c.018.99-.133 2.093-.914 2.7l-5.31 4.13a2.015 2.015 0 1 0 2.828 2.827l4.13-5.309c.607-.78 1.71-.932 2.7-.914L11.5 8ZM3 13.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5Z"
  289. clip-rule="evenodd"
  290. />
  291. </svg>
  292. </div>
  293. <div class=" translate-y-[0.5px]">
  294. {selectedToolIds
  295. .map((id) => {
  296. return $tools.find((tool) => tool.id === id)?.name;
  297. })
  298. .join(', ')}
  299. </div>
  300. </div>
  301. <div>
  302. <button
  303. class="flex items-center dark:text-gray-500"
  304. on:click={() => {
  305. webSearchEnabled = false;
  306. }}
  307. >
  308. <XMark />
  309. </button>
  310. </div>
  311. </div>
  312. {/if}
  313. {#if webSearchEnabled}
  314. <div class="flex items-center justify-between w-full">
  315. <div class="flex items-center gap-2 text-sm dark:text-gray-500">
  316. <div>
  317. <svg
  318. xmlns="http://www.w3.org/2000/svg"
  319. viewBox="0 0 16 16"
  320. fill="currentColor"
  321. class="size-3.5"
  322. >
  323. <path
  324. fill-rule="evenodd"
  325. d="M3.757 4.5c.18.217.376.42.586.608.153-.61.354-1.175.596-1.678A5.53 5.53 0 0 0 3.757 4.5ZM8 1a6.994 6.994 0 0 0-7 7 7 7 0 1 0 7-7Zm0 1.5c-.476 0-1.091.386-1.633 1.427-.293.564-.531 1.267-.683 2.063A5.48 5.48 0 0 0 8 6.5a5.48 5.48 0 0 0 2.316-.51c-.152-.796-.39-1.499-.683-2.063C9.09 2.886 8.476 2.5 8 2.5Zm3.657 2.608a8.823 8.823 0 0 0-.596-1.678c.444.298.842.659 1.182 1.07-.18.217-.376.42-.586.608Zm-1.166 2.436A6.983 6.983 0 0 1 8 8a6.983 6.983 0 0 1-2.49-.456 10.703 10.703 0 0 0 .202 2.6c.72.231 1.49.356 2.288.356.798 0 1.568-.125 2.29-.356a10.705 10.705 0 0 0 .2-2.6Zm1.433 1.85a12.652 12.652 0 0 0 .018-2.609c.405-.276.78-.594 1.117-.947a5.48 5.48 0 0 1 .44 2.262 7.536 7.536 0 0 1-1.575 1.293Zm-2.172 2.435a9.046 9.046 0 0 1-3.504 0c.039.084.078.166.12.244C6.907 13.114 7.523 13.5 8 13.5s1.091-.386 1.633-1.427c.04-.078.08-.16.12-.244Zm1.31.74a8.5 8.5 0 0 0 .492-1.298c.457-.197.893-.43 1.307-.696a5.526 5.526 0 0 1-1.8 1.995Zm-6.123 0a8.507 8.507 0 0 1-.493-1.298 8.985 8.985 0 0 1-1.307-.696 5.526 5.526 0 0 0 1.8 1.995ZM2.5 8.1c.463.5.993.935 1.575 1.293a12.652 12.652 0 0 1-.018-2.608 7.037 7.037 0 0 1-1.117-.947 5.48 5.48 0 0 0-.44 2.262Z"
  326. clip-rule="evenodd"
  327. />
  328. </svg>
  329. </div>
  330. <div class=" translate-y-[0.5px]">{$i18n.t('Search the web')}</div>
  331. </div>
  332. <div>
  333. <button
  334. class="flex items-center dark:text-gray-500"
  335. on:click={() => {
  336. webSearchEnabled = false;
  337. }}
  338. >
  339. <XMark />
  340. </button>
  341. </div>
  342. </div>
  343. {/if}
  344. </div>
  345. {/if}
  346. <Commands
  347. bind:this={commandsElement}
  348. bind:prompt
  349. bind:files
  350. on:upload={(e) => {
  351. dispatch('upload', e.detail);
  352. }}
  353. on:select={(e) => {
  354. const data = e.detail;
  355. if (data?.type === 'model') {
  356. atSelectedModel = data.data;
  357. }
  358. const chatInputElement = document.getElementById('chat-input');
  359. chatInputElement?.focus();
  360. }}
  361. />
  362. </div>
  363. </div>
  364. </div>
  365. <div class="{transparentBackground ? 'bg-transparent' : 'bg-white dark:bg-gray-900'} ">
  366. <div class="max-w-6xl px-4 mx-auto inset-x-0">
  367. <div class="">
  368. <input
  369. bind:this={filesInputElement}
  370. bind:files={inputFiles}
  371. type="file"
  372. hidden
  373. multiple
  374. on:change={async () => {
  375. if (inputFiles && inputFiles.length > 0) {
  376. const _inputFiles = Array.from(inputFiles);
  377. inputFilesHandler(_inputFiles);
  378. } else {
  379. toast.error($i18n.t(`File not found.`));
  380. }
  381. filesInputElement.value = '';
  382. }}
  383. />
  384. {#if recording}
  385. <VoiceRecording
  386. bind:recording
  387. on:cancel={async () => {
  388. recording = false;
  389. await tick();
  390. document.getElementById('chat-input')?.focus();
  391. }}
  392. on:confirm={async (e) => {
  393. const { text, filename } = e.detail;
  394. prompt = `${prompt}${text} `;
  395. recording = false;
  396. await tick();
  397. document.getElementById('chat-input')?.focus();
  398. if ($settings?.speechAutoSend ?? false) {
  399. dispatch('submit', prompt);
  400. }
  401. }}
  402. />
  403. {:else}
  404. <form
  405. class="w-full flex gap-1.5"
  406. on:submit|preventDefault={() => {
  407. // check if selectedModels support image input
  408. dispatch('submit', prompt);
  409. }}
  410. >
  411. <div
  412. 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"
  413. dir={$settings?.chatDirection ?? 'LTR'}
  414. >
  415. {#if files.length > 0}
  416. <div class="mx-1 mt-2.5 mb-1 flex flex-wrap gap-2">
  417. {#each files as file, fileIdx}
  418. {#if file.type === 'image'}
  419. <div class=" relative group">
  420. <div class="relative">
  421. <img
  422. src={file.url}
  423. alt="input"
  424. class=" h-16 w-16 rounded-xl object-cover"
  425. />
  426. {#if atSelectedModel ? visionCapableModels.length === 0 : selectedModels.length !== visionCapableModels.length}
  427. <Tooltip
  428. className=" absolute top-1 left-1"
  429. content={$i18n.t('{{ models }}', {
  430. models: [...(atSelectedModel ? [atSelectedModel] : selectedModels)]
  431. .filter((id) => !visionCapableModels.includes(id))
  432. .join(', ')
  433. })}
  434. >
  435. <svg
  436. xmlns="http://www.w3.org/2000/svg"
  437. viewBox="0 0 24 24"
  438. fill="currentColor"
  439. class="size-4 fill-yellow-300"
  440. >
  441. <path
  442. fill-rule="evenodd"
  443. 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"
  444. clip-rule="evenodd"
  445. />
  446. </svg>
  447. </Tooltip>
  448. {/if}
  449. </div>
  450. <div class=" absolute -top-1 -right-1">
  451. <button
  452. class=" bg-gray-400 text-white border border-white rounded-full group-hover:visible invisible transition"
  453. type="button"
  454. on:click={() => {
  455. files.splice(fileIdx, 1);
  456. files = files;
  457. }}
  458. >
  459. <svg
  460. xmlns="http://www.w3.org/2000/svg"
  461. viewBox="0 0 20 20"
  462. fill="currentColor"
  463. class="w-4 h-4"
  464. >
  465. <path
  466. 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"
  467. />
  468. </svg>
  469. </button>
  470. </div>
  471. </div>
  472. {:else}
  473. <FileItem
  474. item={file}
  475. name={file.name}
  476. type={file.type}
  477. size={file?.size}
  478. loading={file.status === 'uploading'}
  479. dismissible={true}
  480. edit={true}
  481. on:dismiss={() => {
  482. files.splice(fileIdx, 1);
  483. files = files;
  484. }}
  485. on:click={() => {
  486. console.log(file);
  487. }}
  488. />
  489. {/if}
  490. {/each}
  491. </div>
  492. {/if}
  493. <div class=" flex">
  494. <div class=" ml-0.5 self-end mb-1.5 flex space-x-1">
  495. <InputMenu
  496. bind:webSearchEnabled
  497. bind:selectedToolIds
  498. {availableToolIds}
  499. uploadFilesHandler={() => {
  500. filesInputElement.click();
  501. }}
  502. onClose={async () => {
  503. await tick();
  504. const chatInput = document.getElementById('chat-input');
  505. chatInput?.focus();
  506. }}
  507. >
  508. <button
  509. 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"
  510. type="button"
  511. aria-label="More"
  512. >
  513. <svg
  514. xmlns="http://www.w3.org/2000/svg"
  515. viewBox="0 0 16 16"
  516. fill="currentColor"
  517. class="size-5"
  518. >
  519. <path
  520. 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"
  521. />
  522. </svg>
  523. </button>
  524. </InputMenu>
  525. </div>
  526. {#if $settings?.richTextInput ?? true}
  527. <div
  528. bind:this={chatInputContainerElement}
  529. id="chat-input-container"
  530. class="scrollbar-hidden text-left bg-gray-50 dark:bg-gray-850 dark:text-gray-100 outline-none w-full py-2.5 px-1 rounded-xl resize-none h-[48px] overflow-auto"
  531. >
  532. <RichTextInput
  533. bind:this={chatInputElement}
  534. id="chat-input"
  535. trim={true}
  536. placeholder={placeholder ? placeholder : $i18n.t('Send a Message')}
  537. bind:value={prompt}
  538. shiftEnter={!$mobile ||
  539. !(
  540. 'ontouchstart' in window ||
  541. navigator.maxTouchPoints > 0 ||
  542. navigator.msMaxTouchPoints > 0
  543. )}
  544. on:enter={async (e) => {
  545. if (prompt !== '') {
  546. dispatch('submit', prompt);
  547. }
  548. }}
  549. on:input={async (e) => {
  550. if (chatInputContainerElement) {
  551. chatInputContainerElement.style.height = '';
  552. chatInputContainerElement.style.height =
  553. Math.min(chatInputContainerElement.scrollHeight, 200) + 'px';
  554. }
  555. }}
  556. on:focus={async (e) => {
  557. if (chatInputContainerElement) {
  558. chatInputContainerElement.style.height = '';
  559. chatInputContainerElement.style.height =
  560. Math.min(chatInputContainerElement.scrollHeight, 200) + 'px';
  561. }
  562. }}
  563. on:keypress={(e) => {
  564. e = e.detail.event;
  565. }}
  566. on:keydown={async (e) => {
  567. e = e.detail.event;
  568. if (chatInputContainerElement) {
  569. chatInputContainerElement.style.height = '';
  570. chatInputContainerElement.style.height =
  571. Math.min(chatInputContainerElement.scrollHeight, 200) + 'px';
  572. }
  573. const isCtrlPressed = e.ctrlKey || e.metaKey; // metaKey is for Cmd key on Mac
  574. const commandsContainerElement =
  575. document.getElementById('commands-container');
  576. // Command/Ctrl + Shift + Enter to submit a message pair
  577. if (isCtrlPressed && e.key === 'Enter' && e.shiftKey) {
  578. e.preventDefault();
  579. createMessagePair(prompt);
  580. }
  581. // Check if Ctrl + R is pressed
  582. if (prompt === '' && isCtrlPressed && e.key.toLowerCase() === 'r') {
  583. e.preventDefault();
  584. console.log('regenerate');
  585. const regenerateButton = [
  586. ...document.getElementsByClassName('regenerate-response-button')
  587. ]?.at(-1);
  588. regenerateButton?.click();
  589. }
  590. if (prompt === '' && e.key == 'ArrowUp') {
  591. e.preventDefault();
  592. const userMessageElement = [
  593. ...document.getElementsByClassName('user-message')
  594. ]?.at(-1);
  595. const editButton = [
  596. ...document.getElementsByClassName('edit-user-message-button')
  597. ]?.at(-1);
  598. console.log(userMessageElement);
  599. userMessageElement.scrollIntoView({ block: 'center' });
  600. editButton?.click();
  601. }
  602. if (commandsContainerElement && e.key === 'ArrowUp') {
  603. e.preventDefault();
  604. commandsElement.selectUp();
  605. const commandOptionButton = [
  606. ...document.getElementsByClassName('selected-command-option-button')
  607. ]?.at(-1);
  608. commandOptionButton.scrollIntoView({ block: 'center' });
  609. }
  610. if (commandsContainerElement && e.key === 'ArrowDown') {
  611. e.preventDefault();
  612. commandsElement.selectDown();
  613. const commandOptionButton = [
  614. ...document.getElementsByClassName('selected-command-option-button')
  615. ]?.at(-1);
  616. commandOptionButton.scrollIntoView({ block: 'center' });
  617. }
  618. if (commandsContainerElement && e.key === 'Enter') {
  619. e.preventDefault();
  620. const commandOptionButton = [
  621. ...document.getElementsByClassName('selected-command-option-button')
  622. ]?.at(-1);
  623. if (e.shiftKey) {
  624. prompt = `${prompt}\n`;
  625. } else if (commandOptionButton) {
  626. commandOptionButton?.click();
  627. } else {
  628. document.getElementById('send-message-button')?.click();
  629. }
  630. }
  631. if (commandsContainerElement && e.key === 'Tab') {
  632. e.preventDefault();
  633. const commandOptionButton = [
  634. ...document.getElementsByClassName('selected-command-option-button')
  635. ]?.at(-1);
  636. commandOptionButton?.click();
  637. }
  638. if (e.key === 'Escape') {
  639. console.log('Escape');
  640. atSelectedModel = undefined;
  641. selectedToolIds = [];
  642. webSearchEnabled = false;
  643. }
  644. }}
  645. on:paste={async (e) => {
  646. e = e.detail.event;
  647. console.log(e);
  648. const clipboardData = e.clipboardData || window.clipboardData;
  649. if (clipboardData && clipboardData.items) {
  650. for (const item of clipboardData.items) {
  651. if (item.type.indexOf('image') !== -1) {
  652. const blob = item.getAsFile();
  653. const reader = new FileReader();
  654. reader.onload = function (e) {
  655. files = [
  656. ...files,
  657. {
  658. type: 'image',
  659. url: `${e.target.result}`
  660. }
  661. ];
  662. };
  663. reader.readAsDataURL(blob);
  664. }
  665. }
  666. }
  667. }}
  668. />
  669. </div>
  670. {:else}
  671. <textarea
  672. id="chat-input"
  673. bind:this={chatInputElement}
  674. 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]"
  675. placeholder={placeholder ? placeholder : $i18n.t('Send a Message')}
  676. bind:value={prompt}
  677. on:keypress={(e) => {
  678. if (
  679. !$mobile ||
  680. !(
  681. 'ontouchstart' in window ||
  682. navigator.maxTouchPoints > 0 ||
  683. navigator.msMaxTouchPoints > 0
  684. )
  685. ) {
  686. // Prevent Enter key from creating a new line
  687. if (e.key === 'Enter' && !e.shiftKey) {
  688. e.preventDefault();
  689. }
  690. // Submit the prompt when Enter key is pressed
  691. if (prompt !== '' && e.key === 'Enter' && !e.shiftKey) {
  692. dispatch('submit', prompt);
  693. }
  694. }
  695. }}
  696. on:keydown={async (e) => {
  697. const isCtrlPressed = e.ctrlKey || e.metaKey; // metaKey is for Cmd key on Mac
  698. const commandsContainerElement =
  699. document.getElementById('commands-container');
  700. // Command/Ctrl + Shift + Enter to submit a message pair
  701. if (isCtrlPressed && e.key === 'Enter' && e.shiftKey) {
  702. e.preventDefault();
  703. createMessagePair(prompt);
  704. }
  705. // Check if Ctrl + R is pressed
  706. if (prompt === '' && isCtrlPressed && e.key.toLowerCase() === 'r') {
  707. e.preventDefault();
  708. console.log('regenerate');
  709. const regenerateButton = [
  710. ...document.getElementsByClassName('regenerate-response-button')
  711. ]?.at(-1);
  712. regenerateButton?.click();
  713. }
  714. if (prompt === '' && e.key == 'ArrowUp') {
  715. e.preventDefault();
  716. const userMessageElement = [
  717. ...document.getElementsByClassName('user-message')
  718. ]?.at(-1);
  719. const editButton = [
  720. ...document.getElementsByClassName('edit-user-message-button')
  721. ]?.at(-1);
  722. console.log(userMessageElement);
  723. userMessageElement.scrollIntoView({ block: 'center' });
  724. editButton?.click();
  725. }
  726. if (commandsContainerElement && e.key === 'ArrowUp') {
  727. e.preventDefault();
  728. commandsElement.selectUp();
  729. const commandOptionButton = [
  730. ...document.getElementsByClassName('selected-command-option-button')
  731. ]?.at(-1);
  732. commandOptionButton.scrollIntoView({ block: 'center' });
  733. }
  734. if (commandsContainerElement && e.key === 'ArrowDown') {
  735. e.preventDefault();
  736. commandsElement.selectDown();
  737. const commandOptionButton = [
  738. ...document.getElementsByClassName('selected-command-option-button')
  739. ]?.at(-1);
  740. commandOptionButton.scrollIntoView({ block: 'center' });
  741. }
  742. if (commandsContainerElement && e.key === 'Enter') {
  743. e.preventDefault();
  744. const commandOptionButton = [
  745. ...document.getElementsByClassName('selected-command-option-button')
  746. ]?.at(-1);
  747. if (e.shiftKey) {
  748. prompt = `${prompt}\n`;
  749. } else if (commandOptionButton) {
  750. commandOptionButton?.click();
  751. } else {
  752. document.getElementById('send-message-button')?.click();
  753. }
  754. }
  755. if (commandsContainerElement && e.key === 'Tab') {
  756. e.preventDefault();
  757. const commandOptionButton = [
  758. ...document.getElementsByClassName('selected-command-option-button')
  759. ]?.at(-1);
  760. commandOptionButton?.click();
  761. } else if (e.key === 'Tab') {
  762. const words = findWordIndices(prompt);
  763. if (words.length > 0) {
  764. const word = words.at(0);
  765. const fullPrompt = prompt;
  766. prompt = prompt.substring(0, word?.endIndex + 1);
  767. await tick();
  768. e.target.scrollTop = e.target.scrollHeight;
  769. prompt = fullPrompt;
  770. await tick();
  771. e.preventDefault();
  772. e.target.setSelectionRange(word?.startIndex, word.endIndex + 1);
  773. }
  774. e.target.style.height = '';
  775. e.target.style.height = Math.min(e.target.scrollHeight, 200) + 'px';
  776. }
  777. if (e.key === 'Escape') {
  778. console.log('Escape');
  779. atSelectedModel = undefined;
  780. selectedToolIds = [];
  781. webSearchEnabled = false;
  782. }
  783. }}
  784. rows="1"
  785. on:input={async (e) => {
  786. e.target.style.height = '';
  787. e.target.style.height = Math.min(e.target.scrollHeight, 200) + 'px';
  788. user = null;
  789. }}
  790. on:focus={async (e) => {
  791. e.target.style.height = '';
  792. e.target.style.height = Math.min(e.target.scrollHeight, 200) + 'px';
  793. }}
  794. on:paste={async (e) => {
  795. const clipboardData = e.clipboardData || window.clipboardData;
  796. if (clipboardData && clipboardData.items) {
  797. for (const item of clipboardData.items) {
  798. if (item.type.indexOf('image') !== -1) {
  799. const blob = item.getAsFile();
  800. const reader = new FileReader();
  801. reader.onload = function (e) {
  802. files = [
  803. ...files,
  804. {
  805. type: 'image',
  806. url: `${e.target.result}`
  807. }
  808. ];
  809. };
  810. reader.readAsDataURL(blob);
  811. }
  812. }
  813. }
  814. }}
  815. />
  816. {/if}
  817. <div class="self-end mb-2 flex space-x-1 mr-1">
  818. {#if !history?.currentId || history.messages[history.currentId]?.done == true}
  819. <Tooltip content={$i18n.t('Record voice')}>
  820. <button
  821. id="voice-input-button"
  822. 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"
  823. type="button"
  824. on:click={async () => {
  825. try {
  826. let stream = await navigator.mediaDevices
  827. .getUserMedia({ audio: true })
  828. .catch(function (err) {
  829. toast.error(
  830. $i18n.t(
  831. `Permission denied when accessing microphone: {{error}}`,
  832. {
  833. error: err
  834. }
  835. )
  836. );
  837. return null;
  838. });
  839. if (stream) {
  840. recording = true;
  841. const tracks = stream.getTracks();
  842. tracks.forEach((track) => track.stop());
  843. }
  844. stream = null;
  845. } catch {
  846. toast.error($i18n.t('Permission denied when accessing microphone'));
  847. }
  848. }}
  849. aria-label="Voice Input"
  850. >
  851. <svg
  852. xmlns="http://www.w3.org/2000/svg"
  853. viewBox="0 0 20 20"
  854. fill="currentColor"
  855. class="w-5 h-5 translate-y-[0.5px]"
  856. >
  857. <path d="M7 4a3 3 0 016 0v6a3 3 0 11-6 0V4z" />
  858. <path
  859. 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"
  860. />
  861. </svg>
  862. </button>
  863. </Tooltip>
  864. {/if}
  865. </div>
  866. </div>
  867. </div>
  868. <div class="flex items-end w-10">
  869. {#if !history.currentId || history.messages[history.currentId]?.done == true}
  870. {#if prompt === ''}
  871. <div class=" flex items-center mb-1">
  872. <Tooltip content={$i18n.t('Call')}>
  873. <button
  874. class=" text-gray-600 dark:text-gray-300 hover:bg-gray-50 dark:hover:bg-gray-850 transition rounded-full p-2 self-center"
  875. type="button"
  876. on:click={async () => {
  877. if (selectedModels.length > 1) {
  878. toast.error($i18n.t('Select only one model to call'));
  879. return;
  880. }
  881. if ($config.audio.stt.engine === 'web') {
  882. toast.error(
  883. $i18n.t('Call feature is not supported when using Web STT engine')
  884. );
  885. return;
  886. }
  887. // check if user has access to getUserMedia
  888. try {
  889. let stream = await navigator.mediaDevices.getUserMedia({ audio: true });
  890. // If the user grants the permission, proceed to show the call overlay
  891. if (stream) {
  892. const tracks = stream.getTracks();
  893. tracks.forEach((track) => track.stop());
  894. }
  895. stream = null;
  896. showCallOverlay.set(true);
  897. showControls.set(true);
  898. } catch (err) {
  899. // If the user denies the permission or an error occurs, show an error message
  900. toast.error($i18n.t('Permission denied when accessing media devices'));
  901. }
  902. }}
  903. aria-label="Call"
  904. >
  905. <Headphone className="size-6" />
  906. </button>
  907. </Tooltip>
  908. </div>
  909. {:else}
  910. <div class=" flex items-center mb-1">
  911. <Tooltip content={$i18n.t('Send message')}>
  912. <button
  913. id="send-message-button"
  914. class="{prompt !== ''
  915. ? 'bg-black text-white hover:bg-gray-900 dark:bg-white dark:text-black dark:hover:bg-gray-100 '
  916. : '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"
  917. type="submit"
  918. disabled={prompt === ''}
  919. >
  920. <svg
  921. xmlns="http://www.w3.org/2000/svg"
  922. viewBox="0 0 16 16"
  923. fill="currentColor"
  924. class="size-6"
  925. >
  926. <path
  927. fill-rule="evenodd"
  928. 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"
  929. clip-rule="evenodd"
  930. />
  931. </svg>
  932. </button>
  933. </Tooltip>
  934. </div>
  935. {/if}
  936. {:else}
  937. <div class=" flex items-center mb-1.5">
  938. <Tooltip content={$i18n.t('Stop')}>
  939. <button
  940. 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"
  941. on:click={() => {
  942. stopResponse();
  943. }}
  944. >
  945. <svg
  946. xmlns="http://www.w3.org/2000/svg"
  947. viewBox="0 0 24 24"
  948. fill="currentColor"
  949. class="size-6"
  950. >
  951. <path
  952. fill-rule="evenodd"
  953. 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"
  954. clip-rule="evenodd"
  955. />
  956. </svg>
  957. </button>
  958. </Tooltip>
  959. </div>
  960. {/if}
  961. </div>
  962. </form>
  963. {/if}
  964. </div>
  965. </div>
  966. </div>
  967. </div>