Selector.svelte 12 KB

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