Selector.svelte 14 KB

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