Selector.svelte 12 KB

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