Selector.svelte 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. <script lang="ts">
  2. import { Select } from 'bits-ui';
  3. import { flyAndScale } from '$lib/utils/transitions';
  4. import { createEventDispatcher, onMount, getContext } 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 = '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();
  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={() => {
  152. searchValue = '';
  153. }}
  154. selected={items.find((item) => item.value === value)}
  155. onSelectedChange={(selectedItem) => {
  156. value = selectedItem.value;
  157. }}
  158. >
  159. <Select.Trigger class="relative w-full" aria-label={placeholder}>
  160. <Select.Value
  161. class="inline-flex h-input px-0.5 w-full outline-none bg-transparent truncate text-lg font-semibold placeholder-gray-400 focus:outline-none"
  162. {placeholder}
  163. />
  164. <ChevronDown className="absolute end-2 top-1/2 -translate-y-[45%] size-3.5" strokeWidth="2.5" />
  165. </Select.Trigger>
  166. <Select.Content
  167. class="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"
  168. transition={flyAndScale}
  169. sideOffset={4}
  170. >
  171. <slot>
  172. {#if searchEnabled}
  173. <div class="flex items-center gap-2.5 px-5 mt-3.5 mb-3">
  174. <Search className="size-4" strokeWidth="2.5" />
  175. <input
  176. bind:value={searchValue}
  177. class="w-full text-sm bg-transparent outline-none"
  178. placeholder={searchPlaceholder}
  179. />
  180. </div>
  181. <hr class="border-gray-100 dark:border-gray-800" />
  182. {/if}
  183. <div class="px-3 my-2 max-h-80 overflow-y-auto">
  184. {#each filteredItems as item}
  185. <Select.Item
  186. 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"
  187. value={item.value}
  188. label={item.label}
  189. >
  190. <div class="flex items-center gap-2">
  191. <div class="line-clamp-1">
  192. {item.label}
  193. </div>
  194. {#if item.info.external}
  195. <Tooltip content={item.info?.source ?? 'External'}>
  196. <div class=" mr-2">
  197. <svg
  198. xmlns="http://www.w3.org/2000/svg"
  199. viewBox="0 0 16 16"
  200. fill="currentColor"
  201. class="w-4 h-4"
  202. >
  203. <path
  204. fill-rule="evenodd"
  205. 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"
  206. clip-rule="evenodd"
  207. />
  208. <path
  209. fill-rule="evenodd"
  210. 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"
  211. clip-rule="evenodd"
  212. />
  213. </svg>
  214. </div>
  215. </Tooltip>
  216. {/if}
  217. </div>
  218. {#if value === item.value}
  219. <div class="ml-auto">
  220. <Check />
  221. </div>
  222. {/if}
  223. </Select.Item>
  224. {:else}
  225. <div>
  226. <div class="block px-3 py-2 text-sm text-gray-700 dark:text-gray-100">
  227. No results found
  228. </div>
  229. </div>
  230. {/each}
  231. {#if !(searchValue.trim() in $MODEL_DOWNLOAD_POOL) && searchValue && ollamaVersion && $user.role === 'admin'}
  232. <button
  233. 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"
  234. on:click={() => {
  235. pullModelHandler();
  236. }}
  237. >
  238. Pull "{searchValue}" from Ollama.com
  239. </button>
  240. {/if}
  241. {#each Object.keys($MODEL_DOWNLOAD_POOL) as model}
  242. <div
  243. 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"
  244. >
  245. <div class="flex">
  246. <div class="-ml-2 mr-2.5 translate-y-0.5">
  247. <svg
  248. class="size-4"
  249. viewBox="0 0 24 24"
  250. fill="currentColor"
  251. xmlns="http://www.w3.org/2000/svg"
  252. ><style>
  253. .spinner_ajPY {
  254. transform-origin: center;
  255. animation: spinner_AtaB 0.75s infinite linear;
  256. }
  257. @keyframes spinner_AtaB {
  258. 100% {
  259. transform: rotate(360deg);
  260. }
  261. }
  262. </style><path
  263. 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"
  264. opacity=".25"
  265. /><path
  266. 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"
  267. class="spinner_ajPY"
  268. /></svg
  269. >
  270. </div>
  271. <div class="flex flex-col self-start">
  272. <div class="line-clamp-1">
  273. Downloading "{model}" {'pullProgress' in $MODEL_DOWNLOAD_POOL[model]
  274. ? `(${$MODEL_DOWNLOAD_POOL[model].pullProgress}%)`
  275. : ''}
  276. </div>
  277. {#if 'digest' in $MODEL_DOWNLOAD_POOL[model] && $MODEL_DOWNLOAD_POOL[model].digest}
  278. <div class="-mt-1 h-fit text-[0.7rem] dark:text-gray-500 line-clamp-1">
  279. {$MODEL_DOWNLOAD_POOL[model].digest}
  280. </div>
  281. {/if}
  282. </div>
  283. </div>
  284. <div class="mr-2 translate-y-0.5">
  285. <Tooltip content="Cancel">
  286. <button
  287. class="text-gray-800 dark:text-gray-100"
  288. on:click={() => {
  289. cancelModelPullHandler(model);
  290. }}
  291. >
  292. <svg
  293. class="w-4 h-4 text-gray-800 dark:text-white"
  294. aria-hidden="true"
  295. xmlns="http://www.w3.org/2000/svg"
  296. width="24"
  297. height="24"
  298. fill="currentColor"
  299. viewBox="0 0 24 24"
  300. >
  301. <path
  302. stroke="currentColor"
  303. stroke-linecap="round"
  304. stroke-linejoin="round"
  305. stroke-width="2"
  306. d="M6 18 17.94 6M18 18 6.06 6"
  307. />
  308. </svg>
  309. </button>
  310. </Tooltip>
  311. </div>
  312. </div>
  313. {/each}
  314. </div>
  315. </slot>
  316. </Select.Content>
  317. </Select.Root>