Selector.svelte 16 KB

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