Selector.svelte 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586
  1. <script lang="ts">
  2. import { DropdownMenu } from 'bits-ui';
  3. import { marked } from 'marked';
  4. import Fuse from 'fuse.js';
  5. import { flyAndScale } from '$lib/utils/transitions';
  6. import { createEventDispatcher, onMount, getContext, tick } from 'svelte';
  7. import ChevronDown from '$lib/components/icons/ChevronDown.svelte';
  8. import Check from '$lib/components/icons/Check.svelte';
  9. import Search from '$lib/components/icons/Search.svelte';
  10. import { deleteModel, getOllamaVersion, pullModel } from '$lib/apis/ollama';
  11. import { user, MODEL_DOWNLOAD_POOL, models, mobile, temporaryChatEnabled } from '$lib/stores';
  12. import { toast } from 'svelte-sonner';
  13. import { capitalizeFirstLetter, sanitizeResponseContent, splitStream } from '$lib/utils';
  14. import { getModels } from '$lib/apis';
  15. import Tooltip from '$lib/components/common/Tooltip.svelte';
  16. import Switch from '$lib/components/common/Switch.svelte';
  17. import ChatBubbleOval from '$lib/components/icons/ChatBubbleOval.svelte';
  18. import { goto } from '$app/navigation';
  19. const i18n = getContext('i18n');
  20. const dispatch = createEventDispatcher();
  21. export let id = '';
  22. export let value = '';
  23. export let placeholder = 'Select a model';
  24. export let searchEnabled = true;
  25. export let searchPlaceholder = $i18n.t('Search a model');
  26. export let showTemporaryChatControl = false;
  27. export let items: {
  28. label: string;
  29. value: string;
  30. model: Model;
  31. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  32. [key: string]: any;
  33. }[] = [];
  34. export let className = 'w-[32rem]';
  35. let show = false;
  36. let selectedModel = '';
  37. $: selectedModel = items.find((item) => item.value === value) ?? '';
  38. let searchValue = '';
  39. let ollamaVersion = null;
  40. let selectedModelIdx = 0;
  41. const fuse = new Fuse(
  42. items
  43. .filter((item) => !item.model?.info?.meta?.hidden)
  44. .map((item) => {
  45. const _item = {
  46. ...item,
  47. modelName: item.model?.name,
  48. tags: item.model?.info?.meta?.tags?.map((tag) => tag.name).join(' '),
  49. desc: item.model?.info?.meta?.description
  50. };
  51. return _item;
  52. }),
  53. {
  54. keys: ['value', 'tags', 'modelName'],
  55. threshold: 0.3
  56. }
  57. );
  58. $: filteredItems = searchValue
  59. ? fuse.search(searchValue).map((e) => {
  60. return e.item;
  61. })
  62. : items.filter((item) => !item.model?.info?.meta?.hidden);
  63. const pullModelHandler = async () => {
  64. const sanitizedModelTag = searchValue.trim().replace(/^ollama\s+(run|pull)\s+/, '');
  65. console.log($MODEL_DOWNLOAD_POOL);
  66. if ($MODEL_DOWNLOAD_POOL[sanitizedModelTag]) {
  67. toast.error(
  68. $i18n.t(`Model '{{modelTag}}' is already in queue for downloading.`, {
  69. modelTag: sanitizedModelTag
  70. })
  71. );
  72. return;
  73. }
  74. if (Object.keys($MODEL_DOWNLOAD_POOL).length === 3) {
  75. toast.error(
  76. $i18n.t('Maximum of 3 models can be downloaded simultaneously. Please try again later.')
  77. );
  78. return;
  79. }
  80. const [res, controller] = await pullModel(localStorage.token, sanitizedModelTag, '0').catch(
  81. (error) => {
  82. toast.error(error);
  83. return null;
  84. }
  85. );
  86. if (res) {
  87. const reader = res.body
  88. .pipeThrough(new TextDecoderStream())
  89. .pipeThrough(splitStream('\n'))
  90. .getReader();
  91. MODEL_DOWNLOAD_POOL.set({
  92. ...$MODEL_DOWNLOAD_POOL,
  93. [sanitizedModelTag]: {
  94. ...$MODEL_DOWNLOAD_POOL[sanitizedModelTag],
  95. abortController: controller,
  96. reader,
  97. done: false
  98. }
  99. });
  100. while (true) {
  101. try {
  102. const { value, done } = await reader.read();
  103. if (done) break;
  104. let lines = value.split('\n');
  105. for (const line of lines) {
  106. if (line !== '') {
  107. let data = JSON.parse(line);
  108. console.log(data);
  109. if (data.error) {
  110. throw data.error;
  111. }
  112. if (data.detail) {
  113. throw data.detail;
  114. }
  115. if (data.status) {
  116. if (data.digest) {
  117. let downloadProgress = 0;
  118. if (data.completed) {
  119. downloadProgress = Math.round((data.completed / data.total) * 1000) / 10;
  120. } else {
  121. downloadProgress = 100;
  122. }
  123. MODEL_DOWNLOAD_POOL.set({
  124. ...$MODEL_DOWNLOAD_POOL,
  125. [sanitizedModelTag]: {
  126. ...$MODEL_DOWNLOAD_POOL[sanitizedModelTag],
  127. pullProgress: downloadProgress,
  128. digest: data.digest
  129. }
  130. });
  131. } else {
  132. toast.success(data.status);
  133. MODEL_DOWNLOAD_POOL.set({
  134. ...$MODEL_DOWNLOAD_POOL,
  135. [sanitizedModelTag]: {
  136. ...$MODEL_DOWNLOAD_POOL[sanitizedModelTag],
  137. done: data.status === 'success'
  138. }
  139. });
  140. }
  141. }
  142. }
  143. }
  144. } catch (error) {
  145. console.log(error);
  146. if (typeof error !== 'string') {
  147. error = error.message;
  148. }
  149. toast.error(error);
  150. // opts.callback({ success: false, error, modelName: opts.modelName });
  151. break;
  152. }
  153. }
  154. if ($MODEL_DOWNLOAD_POOL[sanitizedModelTag].done) {
  155. toast.success(
  156. $i18n.t(`Model '{{modelName}}' has been successfully downloaded.`, {
  157. modelName: sanitizedModelTag
  158. })
  159. );
  160. models.set(await getModels(localStorage.token));
  161. } else {
  162. toast.error($i18n.t('Download canceled'));
  163. }
  164. delete $MODEL_DOWNLOAD_POOL[sanitizedModelTag];
  165. MODEL_DOWNLOAD_POOL.set({
  166. ...$MODEL_DOWNLOAD_POOL
  167. });
  168. }
  169. };
  170. onMount(async () => {
  171. ollamaVersion = await getOllamaVersion(localStorage.token).catch((error) => false);
  172. });
  173. const cancelModelPullHandler = async (model: string) => {
  174. const { reader, abortController } = $MODEL_DOWNLOAD_POOL[model];
  175. if (abortController) {
  176. abortController.abort();
  177. }
  178. if (reader) {
  179. await reader.cancel();
  180. delete $MODEL_DOWNLOAD_POOL[model];
  181. MODEL_DOWNLOAD_POOL.set({
  182. ...$MODEL_DOWNLOAD_POOL
  183. });
  184. await deleteModel(localStorage.token, model);
  185. toast.success(`${model} download has been canceled`);
  186. }
  187. };
  188. </script>
  189. <DropdownMenu.Root
  190. bind:open={show}
  191. onOpenChange={async () => {
  192. searchValue = '';
  193. selectedModelIdx = 0;
  194. window.setTimeout(() => document.getElementById('model-search-input')?.focus(), 0);
  195. }}
  196. closeFocus={false}
  197. >
  198. <DropdownMenu.Trigger
  199. class="relative w-full font-primary"
  200. aria-label={placeholder}
  201. id="model-selector-{id}-button"
  202. >
  203. <div
  204. class="flex w-full text-left px-0.5 outline-none bg-transparent truncate text-lg font-medium placeholder-gray-400 focus:outline-none"
  205. >
  206. {#if selectedModel}
  207. {selectedModel.label}
  208. {:else}
  209. {placeholder}
  210. {/if}
  211. <ChevronDown className=" self-center ml-2 size-3" strokeWidth="2.5" />
  212. </div>
  213. </DropdownMenu.Trigger>
  214. <DropdownMenu.Content
  215. class=" z-40 {$mobile
  216. ? `w-full`
  217. : `${className}`} max-w-[calc(100vw-1rem)] justify-start rounded-xl bg-white dark:bg-gray-850 dark:text-white shadow-lg outline-none"
  218. transition={flyAndScale}
  219. side={$mobile ? 'bottom' : 'bottom-start'}
  220. sideOffset={3}
  221. >
  222. <slot>
  223. {#if searchEnabled}
  224. <div class="flex items-center gap-2.5 px-5 mt-3.5 mb-3">
  225. <Search className="size-4" strokeWidth="2.5" />
  226. <input
  227. id="model-search-input"
  228. bind:value={searchValue}
  229. class="w-full text-sm bg-transparent outline-none"
  230. placeholder={searchPlaceholder}
  231. autocomplete="off"
  232. on:keydown={(e) => {
  233. if (e.code === 'Enter' && filteredItems.length > 0) {
  234. value = filteredItems[selectedModelIdx].value;
  235. show = false;
  236. return; // dont need to scroll on selection
  237. } else if (e.code === 'ArrowDown') {
  238. selectedModelIdx = Math.min(selectedModelIdx + 1, filteredItems.length - 1);
  239. } else if (e.code === 'ArrowUp') {
  240. selectedModelIdx = Math.max(selectedModelIdx - 1, 0);
  241. } else {
  242. // if the user types something, reset to the top selection.
  243. selectedModelIdx = 0;
  244. }
  245. const item = document.querySelector(`[data-arrow-selected="true"]`);
  246. item?.scrollIntoView({ block: 'center', inline: 'nearest', behavior: 'instant' });
  247. }}
  248. />
  249. </div>
  250. <hr class="border-gray-50 dark:border-gray-850" />
  251. {/if}
  252. <div class="px-3 my-2 max-h-64 overflow-y-auto scrollbar-hidden group">
  253. {#each filteredItems as item, index}
  254. <button
  255. aria-label="model-item"
  256. class="flex w-full text-left font-medium line-clamp-1 select-none items-center rounded-button py-2 pl-3 pr-1.5 text-sm text-gray-700 dark:text-gray-100 outline-none transition-all duration-75 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg cursor-pointer data-[highlighted]:bg-muted {index ===
  257. selectedModelIdx
  258. ? 'bg-gray-100 dark:bg-gray-800 group-hover:bg-transparent'
  259. : ''}"
  260. data-arrow-selected={index === selectedModelIdx}
  261. on:click={() => {
  262. value = item.value;
  263. selectedModelIdx = index;
  264. show = false;
  265. }}
  266. >
  267. <div class="flex flex-col">
  268. {#if $mobile && (item?.model?.info?.meta?.tags ?? []).length > 0}
  269. <div class="flex gap-0.5 self-start h-full mb-1.5 -translate-x-1">
  270. {#each item.model?.info?.meta.tags as tag}
  271. <div
  272. class=" text-xs font-bold px-1 rounded uppercase line-clamp-1 bg-gray-500/20 text-gray-700 dark:text-gray-200"
  273. >
  274. {tag.name}
  275. </div>
  276. {/each}
  277. </div>
  278. {/if}
  279. <div class="flex items-center gap-2">
  280. <div class="flex items-center min-w-fit">
  281. <div class="line-clamp-1">
  282. <div class="flex items-center min-w-fit">
  283. <img
  284. src={item.model?.info?.meta?.profile_image_url ?? '/static/favicon.png'}
  285. alt="Model"
  286. class="rounded-full size-5 flex items-center mr-2"
  287. />
  288. {item.label}
  289. </div>
  290. </div>
  291. {#if item.model.owned_by === 'ollama' && (item.model.ollama?.details?.parameter_size ?? '') !== ''}
  292. <div class="flex ml-1 items-center translate-y-[0.5px]">
  293. <Tooltip
  294. content={`${
  295. item.model.ollama?.details?.quantization_level
  296. ? item.model.ollama?.details?.quantization_level + ' '
  297. : ''
  298. }${
  299. item.model.ollama?.size
  300. ? `(${(item.model.ollama?.size / 1024 ** 3).toFixed(1)}GB)`
  301. : ''
  302. }`}
  303. className="self-end"
  304. >
  305. <span
  306. class=" text-xs font-medium text-gray-600 dark:text-gray-400 line-clamp-1"
  307. >{item.model.ollama?.details?.parameter_size ?? ''}</span
  308. >
  309. </Tooltip>
  310. </div>
  311. {/if}
  312. </div>
  313. <!-- {JSON.stringify(item.info)} -->
  314. {#if item.model.owned_by === 'openai'}
  315. <Tooltip content={`${'External'}`}>
  316. <div class="translate-y-[1px]">
  317. <svg
  318. xmlns="http://www.w3.org/2000/svg"
  319. viewBox="0 0 16 16"
  320. fill="currentColor"
  321. class="size-3"
  322. >
  323. <path
  324. fill-rule="evenodd"
  325. d="M8.914 6.025a.75.75 0 0 1 1.06 0 3.5 3.5 0 0 1 0 4.95l-2 2a3.5 3.5 0 0 1-5.396-4.402.75.75 0 0 1 1.251.827 2 2 0 0 0 3.085 2.514l2-2a2 2 0 0 0 0-2.828.75.75 0 0 1 0-1.06Z"
  326. clip-rule="evenodd"
  327. />
  328. <path
  329. fill-rule="evenodd"
  330. d="M7.086 9.975a.75.75 0 0 1-1.06 0 3.5 3.5 0 0 1 0-4.95l2-2a3.5 3.5 0 0 1 5.396 4.402.75.75 0 0 1-1.251-.827 2 2 0 0 0-3.085-2.514l-2 2a2 2 0 0 0 0 2.828.75.75 0 0 1 0 1.06Z"
  331. clip-rule="evenodd"
  332. />
  333. </svg>
  334. </div>
  335. </Tooltip>
  336. {/if}
  337. {#if item.model?.info?.meta?.description}
  338. <Tooltip
  339. content={`${marked.parse(
  340. sanitizeResponseContent(item.model?.info?.meta?.description).replaceAll(
  341. '\n',
  342. '<br>'
  343. )
  344. )}`}
  345. >
  346. <div class=" translate-y-[1px]">
  347. <svg
  348. xmlns="http://www.w3.org/2000/svg"
  349. fill="none"
  350. viewBox="0 0 24 24"
  351. stroke-width="1.5"
  352. stroke="currentColor"
  353. class="w-4 h-4"
  354. >
  355. <path
  356. stroke-linecap="round"
  357. stroke-linejoin="round"
  358. d="m11.25 11.25.041-.02a.75.75 0 0 1 1.063.852l-.708 2.836a.75.75 0 0 0 1.063.853l.041-.021M21 12a9 9 0 1 1-18 0 9 9 0 0 1 18 0Zm-9-3.75h.008v.008H12V8.25Z"
  359. />
  360. </svg>
  361. </div>
  362. </Tooltip>
  363. {/if}
  364. {#if !$mobile && (item?.model?.info?.meta?.tags ?? []).length > 0}
  365. <div class="flex gap-0.5 self-center items-center h-full translate-y-[0.5px]">
  366. {#each item.model?.info?.meta.tags as tag}
  367. <Tooltip content={tag.name}>
  368. <div
  369. class=" text-xs font-bold px-1 rounded uppercase line-clamp-1 bg-gray-500/20 text-gray-700 dark:text-gray-200"
  370. >
  371. {tag.name}
  372. </div>
  373. </Tooltip>
  374. {/each}
  375. </div>
  376. {/if}
  377. </div>
  378. </div>
  379. {#if value === item.value}
  380. <div class="ml-auto pl-2 pr-2 md:pr-0">
  381. <Check />
  382. </div>
  383. {/if}
  384. </button>
  385. {:else}
  386. <div>
  387. <div class="block px-3 py-2 text-sm text-gray-700 dark:text-gray-100">
  388. {$i18n.t('No results found')}
  389. </div>
  390. </div>
  391. {/each}
  392. {#if !(searchValue.trim() in $MODEL_DOWNLOAD_POOL) && searchValue && ollamaVersion && $user.role === 'admin'}
  393. <button
  394. class="flex w-full font-medium line-clamp-1 select-none items-center rounded-button py-2 pl-3 pr-1.5 text-sm text-gray-700 dark:text-gray-100 outline-none transition-all duration-75 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg cursor-pointer data-[highlighted]:bg-muted"
  395. on:click={() => {
  396. pullModelHandler();
  397. }}
  398. >
  399. {$i18n.t(`Pull "{{searchValue}}" from Ollama.com`, { searchValue: searchValue })}
  400. </button>
  401. {/if}
  402. {#each Object.keys($MODEL_DOWNLOAD_POOL) as model}
  403. <div
  404. class="flex w-full justify-between font-medium select-none rounded-button py-2 pl-3 pr-1.5 text-sm text-gray-700 dark:text-gray-100 outline-none transition-all duration-75 rounded-lg cursor-pointer data-[highlighted]:bg-muted"
  405. >
  406. <div class="flex">
  407. <div class="-ml-2 mr-2.5 translate-y-0.5">
  408. <svg
  409. class="size-4"
  410. viewBox="0 0 24 24"
  411. fill="currentColor"
  412. xmlns="http://www.w3.org/2000/svg"
  413. ><style>
  414. .spinner_ajPY {
  415. transform-origin: center;
  416. animation: spinner_AtaB 0.75s infinite linear;
  417. }
  418. @keyframes spinner_AtaB {
  419. 100% {
  420. transform: rotate(360deg);
  421. }
  422. }
  423. </style><path
  424. d="M12,1A11,11,0,1,0,23,12,11,11,0,0,0,12,1Zm0,19a8,8,0,1,1,8-8A8,8,0,0,1,12,20Z"
  425. opacity=".25"
  426. /><path
  427. d="M10.14,1.16a11,11,0,0,0-9,8.92A1.59,1.59,0,0,0,2.46,12,1.52,1.52,0,0,0,4.11,10.7a8,8,0,0,1,6.66-6.61A1.42,1.42,0,0,0,12,2.69h0A1.57,1.57,0,0,0,10.14,1.16Z"
  428. class="spinner_ajPY"
  429. /></svg
  430. >
  431. </div>
  432. <div class="flex flex-col self-start">
  433. <div class="flex gap-1">
  434. <div class="line-clamp-1">
  435. Downloading "{model}"
  436. </div>
  437. <div class="flex-shrink-0">
  438. {'pullProgress' in $MODEL_DOWNLOAD_POOL[model]
  439. ? `(${$MODEL_DOWNLOAD_POOL[model].pullProgress}%)`
  440. : ''}
  441. </div>
  442. </div>
  443. {#if 'digest' in $MODEL_DOWNLOAD_POOL[model] && $MODEL_DOWNLOAD_POOL[model].digest}
  444. <div class="-mt-1 h-fit text-[0.7rem] dark:text-gray-500 line-clamp-1">
  445. {$MODEL_DOWNLOAD_POOL[model].digest}
  446. </div>
  447. {/if}
  448. </div>
  449. </div>
  450. <div class="mr-2 ml-1 translate-y-0.5">
  451. <Tooltip content={$i18n.t('Cancel')}>
  452. <button
  453. class="text-gray-800 dark:text-gray-100"
  454. on:click={() => {
  455. cancelModelPullHandler(model);
  456. }}
  457. >
  458. <svg
  459. class="w-4 h-4 text-gray-800 dark:text-white"
  460. aria-hidden="true"
  461. xmlns="http://www.w3.org/2000/svg"
  462. width="24"
  463. height="24"
  464. fill="currentColor"
  465. viewBox="0 0 24 24"
  466. >
  467. <path
  468. stroke="currentColor"
  469. stroke-linecap="round"
  470. stroke-linejoin="round"
  471. stroke-width="2"
  472. d="M6 18 17.94 6M18 18 6.06 6"
  473. />
  474. </svg>
  475. </button>
  476. </Tooltip>
  477. </div>
  478. </div>
  479. {/each}
  480. </div>
  481. {#if showTemporaryChatControl}
  482. <hr class="border-gray-50 dark:border-gray-850" />
  483. <div class="flex items-center mx-2 my-2">
  484. <button
  485. class="flex justify-between w-full font-medium line-clamp-1 select-none items-center rounded-button py-2 px-3 text-sm text-gray-700 dark:text-gray-100 outline-none transition-all duration-75 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg cursor-pointer data-[highlighted]:bg-muted"
  486. on:click={async () => {
  487. temporaryChatEnabled.set(!$temporaryChatEnabled);
  488. await goto('/');
  489. const newChatButton = document.getElementById('new-chat-button');
  490. setTimeout(() => {
  491. newChatButton?.click();
  492. }, 0);
  493. // add 'temporary-chat=true' to the URL
  494. if ($temporaryChatEnabled) {
  495. history.replaceState(null, '', '?temporary-chat=true');
  496. } else {
  497. history.replaceState(null, '', location.pathname);
  498. }
  499. show = false;
  500. }}
  501. >
  502. <div class="flex gap-2.5 items-center">
  503. <ChatBubbleOval className="size-4" strokeWidth="2.5" />
  504. {$i18n.t(`Temporary Chat`)}
  505. </div>
  506. <div>
  507. <Switch state={$temporaryChatEnabled} />
  508. </div>
  509. </button>
  510. </div>
  511. {/if}
  512. <div class="hidden w-[42rem]" />
  513. <div class="hidden w-[32rem]" />
  514. </slot>
  515. </DropdownMenu.Content>
  516. </DropdownMenu.Root>
  517. <style>
  518. .scrollbar-hidden:active::-webkit-scrollbar-thumb,
  519. .scrollbar-hidden:focus::-webkit-scrollbar-thumb,
  520. .scrollbar-hidden:hover::-webkit-scrollbar-thumb {
  521. visibility: visible;
  522. }
  523. .scrollbar-hidden::-webkit-scrollbar-thumb {
  524. visibility: hidden;
  525. }
  526. </style>