MessageInput.svelte 36 KB

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