Selector.svelte 15 KB

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