Selector.svelte 17 KB

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