ModelEditor.svelte 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687
  1. <script lang="ts">
  2. import { v4 as uuidv4 } from 'uuid';
  3. import { toast } from 'svelte-sonner';
  4. import { goto } from '$app/navigation';
  5. import { onMount, getContext, tick } from 'svelte';
  6. import { models, tools, functions, knowledge as knowledgeCollections } from '$lib/stores';
  7. import AdvancedParams from '$lib/components/chat/Settings/Advanced/AdvancedParams.svelte';
  8. import Tags from '$lib/components/common/Tags.svelte';
  9. import Knowledge from '$lib/components/workspace/Models/Knowledge.svelte';
  10. import ToolsSelector from '$lib/components/workspace/Models/ToolsSelector.svelte';
  11. import FiltersSelector from '$lib/components/workspace/Models/FiltersSelector.svelte';
  12. import ActionsSelector from '$lib/components/workspace/Models/ActionsSelector.svelte';
  13. import Capabilities from '$lib/components/workspace/Models/Capabilities.svelte';
  14. import Textarea from '$lib/components/common/Textarea.svelte';
  15. const i18n = getContext('i18n');
  16. export let onSubmit: Function;
  17. export let model = null;
  18. export let edit = false;
  19. let loading = false;
  20. let success = false;
  21. let filesInputElement;
  22. let inputFiles;
  23. let showAdvanced = false;
  24. let showPreview = false;
  25. // ///////////
  26. // model
  27. // ///////////
  28. let id = '';
  29. let name = '';
  30. $: if (!edit) {
  31. if (name) {
  32. id = name
  33. .replace(/\s+/g, '-')
  34. .replace(/[^a-zA-Z0-9-]/g, '')
  35. .toLowerCase();
  36. }
  37. }
  38. let info = {
  39. id: '',
  40. base_model_id: null,
  41. name: '',
  42. meta: {
  43. profile_image_url: '/static/favicon.png',
  44. description: '',
  45. suggestion_prompts: null,
  46. tags: []
  47. },
  48. params: {
  49. system: ''
  50. }
  51. };
  52. let params = {};
  53. let capabilities = {
  54. vision: true,
  55. usage: undefined
  56. };
  57. let knowledge = [];
  58. let toolIds = [];
  59. let filterIds = [];
  60. let actionIds = [];
  61. const addUsage = (base_model_id) => {
  62. const baseModel = $models.find((m) => m.id === base_model_id);
  63. if (baseModel) {
  64. if (baseModel.owned_by === 'openai') {
  65. capabilities.usage = baseModel.info?.meta?.capabilities?.usage ?? false;
  66. } else {
  67. delete capabilities.usage;
  68. }
  69. capabilities = capabilities;
  70. }
  71. };
  72. const submitHandler = async () => {
  73. loading = true;
  74. info.id = id;
  75. info.name = name;
  76. info.meta.capabilities = capabilities;
  77. if (knowledge.length > 0) {
  78. info.meta.knowledge = knowledge;
  79. } else {
  80. if (info.meta.knowledge) {
  81. delete info.meta.knowledge;
  82. }
  83. }
  84. if (toolIds.length > 0) {
  85. info.meta.toolIds = toolIds;
  86. } else {
  87. if (info.meta.toolIds) {
  88. delete info.meta.toolIds;
  89. }
  90. }
  91. if (filterIds.length > 0) {
  92. info.meta.filterIds = filterIds;
  93. } else {
  94. if (info.meta.filterIds) {
  95. delete info.meta.filterIds;
  96. }
  97. }
  98. if (actionIds.length > 0) {
  99. info.meta.actionIds = actionIds;
  100. } else {
  101. if (info.meta.actionIds) {
  102. delete info.meta.actionIds;
  103. }
  104. }
  105. info.params.stop = params.stop ? params.stop.split(',').filter((s) => s.trim()) : null;
  106. Object.keys(info.params).forEach((key) => {
  107. if (info.params[key] === '' || info.params[key] === null) {
  108. delete info.params[key];
  109. }
  110. });
  111. await onSubmit(info);
  112. loading = false;
  113. success = false;
  114. };
  115. onMount(async () => {
  116. // Scroll to top 'workspace-container' element
  117. const workspaceContainer = document.getElementById('workspace-container');
  118. if (workspaceContainer) {
  119. workspaceContainer.scrollTop = 0;
  120. }
  121. if (model) {
  122. name = model.name;
  123. await tick();
  124. id = model.id;
  125. if (model.info.base_model_id) {
  126. const base_model = $models
  127. .filter((m) => !m?.preset && m?.owned_by !== 'arena')
  128. .find((m) =>
  129. [model.info.base_model_id, `${model.info.base_model_id}:latest`].includes(m.id)
  130. );
  131. console.log('base_model', base_model);
  132. if (base_model) {
  133. model.info.base_model_id = base_model.id;
  134. } else {
  135. model.info.base_model_id = null;
  136. }
  137. }
  138. params = { ...params, ...model?.info?.params };
  139. params.stop = params?.stop
  140. ? (typeof params.stop === 'string' ? params.stop.split(',') : (params?.stop ?? [])).join(
  141. ','
  142. )
  143. : null;
  144. toolIds = model?.info?.meta?.toolIds ?? [];
  145. filterIds = model?.info?.meta?.filterIds ?? [];
  146. actionIds = model?.info?.meta?.actionIds ?? [];
  147. knowledge = (model?.info?.meta?.knowledge ?? []).map((item) => {
  148. if (item?.collection_name) {
  149. return {
  150. id: item.collection_name,
  151. name: item.name,
  152. legacy: true
  153. };
  154. } else if (item?.collection_names) {
  155. return {
  156. name: item.name,
  157. type: 'collection',
  158. collection_names: item.collection_names,
  159. legacy: true
  160. };
  161. } else {
  162. return item;
  163. }
  164. });
  165. capabilities = { ...capabilities, ...(model?.info?.meta?.capabilities ?? {}) };
  166. if (model?.owned_by === 'openai') {
  167. capabilities.usage = false;
  168. }
  169. info = {
  170. ...info,
  171. ...JSON.parse(
  172. JSON.stringify(
  173. model?.info
  174. ? model?.info
  175. : {
  176. id: model.id,
  177. name: model.name
  178. }
  179. )
  180. )
  181. };
  182. console.log(model);
  183. }
  184. });
  185. </script>
  186. <div class="w-full max-h-full">
  187. <input
  188. bind:this={filesInputElement}
  189. bind:files={inputFiles}
  190. type="file"
  191. hidden
  192. accept="image/*"
  193. on:change={() => {
  194. let reader = new FileReader();
  195. reader.onload = (event) => {
  196. let originalImageUrl = `${event.target.result}`;
  197. const img = new Image();
  198. img.src = originalImageUrl;
  199. img.onload = function () {
  200. const canvas = document.createElement('canvas');
  201. const ctx = canvas.getContext('2d');
  202. // Calculate the aspect ratio of the image
  203. const aspectRatio = img.width / img.height;
  204. // Calculate the new width and height to fit within 100x100
  205. let newWidth, newHeight;
  206. if (aspectRatio > 1) {
  207. newWidth = 250 * aspectRatio;
  208. newHeight = 250;
  209. } else {
  210. newWidth = 250;
  211. newHeight = 250 / aspectRatio;
  212. }
  213. // Set the canvas size
  214. canvas.width = 250;
  215. canvas.height = 250;
  216. // Calculate the position to center the image
  217. const offsetX = (250 - newWidth) / 2;
  218. const offsetY = (250 - newHeight) / 2;
  219. // Draw the image on the canvas
  220. ctx.drawImage(img, offsetX, offsetY, newWidth, newHeight);
  221. // Get the base64 representation of the compressed image
  222. const compressedSrc = canvas.toDataURL();
  223. // Display the compressed image
  224. info.meta.profile_image_url = compressedSrc;
  225. inputFiles = null;
  226. };
  227. };
  228. if (
  229. inputFiles &&
  230. inputFiles.length > 0 &&
  231. ['image/gif', 'image/webp', 'image/jpeg', 'image/png', 'image/svg+xml'].includes(
  232. inputFiles[0]['type']
  233. )
  234. ) {
  235. reader.readAsDataURL(inputFiles[0]);
  236. } else {
  237. console.log(`Unsupported File Type '${inputFiles[0]['type']}'.`);
  238. inputFiles = null;
  239. }
  240. }}
  241. />
  242. {#if !edit || model}
  243. <form
  244. class="flex flex-col md:flex-row mx-auto gap-3 md:gap-6"
  245. on:submit|preventDefault={() => {
  246. submitHandler();
  247. }}
  248. >
  249. <div class="self-center md:self-start flex justify-center my-2 flex-shrink-0">
  250. <div class="self-center">
  251. <button
  252. class="rounded-2xl flex flex-shrink-0 items-center bg-white"
  253. type="button"
  254. on:click={() => {
  255. filesInputElement.click();
  256. }}
  257. >
  258. {#if info.meta.profile_image_url}
  259. <img
  260. src={info.meta.profile_image_url}
  261. alt="model profile"
  262. class="rounded-lg size-72 object-cover shrink-0"
  263. />
  264. {:else}
  265. <img
  266. src="/static/favicon.png"
  267. alt="model profile"
  268. class=" rounded-lg size-72 object-cover shrink-0"
  269. />
  270. {/if}
  271. </button>
  272. </div>
  273. </div>
  274. <div>
  275. <div class="mt-2 my-2 flex flex-col">
  276. <div class="flex-1">
  277. <div>
  278. <input
  279. class="text-3xl font-semibold w-full bg-transparent outline-none"
  280. placeholder={$i18n.t('Model Name')}
  281. bind:value={name}
  282. required
  283. />
  284. </div>
  285. </div>
  286. <div class="flex-1">
  287. <!-- <div class=" text-sm font-semibold">{$i18n.t('Model ID')}*</div> -->
  288. <div>
  289. <input
  290. class="text-xs w-full bg-transparent text-gray-500 outline-none rounded-lg"
  291. placeholder={$i18n.t('Model ID')}
  292. value={id}
  293. disabled={edit}
  294. required
  295. />
  296. </div>
  297. </div>
  298. </div>
  299. {#if !edit || model.preset}
  300. <div class="my-1">
  301. <div class=" text-sm font-semibold mb-1">{$i18n.t('Base Model (From)')}</div>
  302. <div>
  303. <select
  304. class="text-sm w-full bg-transparent outline-none rounded-lg"
  305. placeholder="Select a base model (e.g. llama3, gpt-4o)"
  306. bind:value={info.base_model_id}
  307. on:change={(e) => {
  308. addUsage(e.target.value);
  309. }}
  310. required
  311. >
  312. <option value={null} class=" text-gray-900">{$i18n.t('Select a base model')}</option
  313. >
  314. {#each $models.filter((m) => (model ? m.id !== model.id : true) && !m?.preset && m?.owned_by !== 'arena') as model}
  315. <option value={model.id} class=" text-gray-900">{model.name}</option>
  316. {/each}
  317. </select>
  318. </div>
  319. </div>
  320. {/if}
  321. <div class="my-1">
  322. <div class="mb-1 flex w-full justify-between items-center">
  323. <div class=" self-center text-sm font-semibold">{$i18n.t('Description')}</div>
  324. <button
  325. class="p-1 text-xs flex rounded transition"
  326. type="button"
  327. on:click={() => {
  328. if (info.meta.description === null) {
  329. info.meta.description = '';
  330. } else {
  331. info.meta.description = null;
  332. }
  333. }}
  334. >
  335. {#if info.meta.description === null}
  336. <span class="ml-2 self-center">{$i18n.t('Default')}</span>
  337. {:else}
  338. <span class="ml-2 self-center">{$i18n.t('Custom')}</span>
  339. {/if}
  340. </button>
  341. </div>
  342. {#if info.meta.description !== null}
  343. <Textarea
  344. className=" text-sm w-full bg-transparent outline-none resize-none overflow-y-hidden "
  345. placeholder={$i18n.t('Add a short description about what this model does')}
  346. rows={3}
  347. bind:value={info.meta.description}
  348. />
  349. {/if}
  350. </div>
  351. <hr class=" dark:border-gray-850 my-1.5" />
  352. <div class="my-2">
  353. <div class="flex w-full justify-between">
  354. <div class=" self-center text-sm font-semibold">{$i18n.t('Model Params')}</div>
  355. </div>
  356. <div class="mt-2">
  357. <div class="my-1">
  358. <div class=" text-xs font-semibold mb-2">{$i18n.t('System Prompt')}</div>
  359. <div>
  360. <Textarea
  361. className=" text-sm w-full bg-transparent outline-none resize-none overflow-y-hidden "
  362. placeholder={`Write your model system prompt content here\ne.g.) You are Mario from Super Mario Bros, acting as an assistant.`}
  363. rows={4}
  364. bind:value={info.params.system}
  365. />
  366. </div>
  367. </div>
  368. <div class="flex w-full justify-between">
  369. <div class=" self-center text-xs font-semibold">
  370. {$i18n.t('Advanced Params')}
  371. </div>
  372. <button
  373. class="p-1 px-3 text-xs flex rounded transition"
  374. type="button"
  375. on:click={() => {
  376. showAdvanced = !showAdvanced;
  377. }}
  378. >
  379. {#if showAdvanced}
  380. <span class="ml-2 self-center">{$i18n.t('Hide')}</span>
  381. {:else}
  382. <span class="ml-2 self-center">{$i18n.t('Show')}</span>
  383. {/if}
  384. </button>
  385. </div>
  386. {#if showAdvanced}
  387. <div class="my-2">
  388. <AdvancedParams
  389. admin={true}
  390. bind:params
  391. on:change={(e) => {
  392. info.params = { ...info.params, ...params };
  393. }}
  394. />
  395. </div>
  396. {/if}
  397. </div>
  398. </div>
  399. <hr class=" dark:border-gray-850 my-1" />
  400. <div class="my-2">
  401. <div class="flex w-full justify-between items-center">
  402. <div class="flex w-full justify-between items-center">
  403. <div class=" self-center text-sm font-semibold">{$i18n.t('Prompt suggestions')}</div>
  404. <button
  405. class="p-1 text-xs flex rounded transition"
  406. type="button"
  407. on:click={() => {
  408. if ((info?.meta?.suggestion_prompts ?? null) === null) {
  409. info.meta.suggestion_prompts = [{ content: '' }];
  410. } else {
  411. info.meta.suggestion_prompts = null;
  412. }
  413. }}
  414. >
  415. {#if (info?.meta?.suggestion_prompts ?? null) === null}
  416. <span class="ml-2 self-center">{$i18n.t('Default')}</span>
  417. {:else}
  418. <span class="ml-2 self-center">{$i18n.t('Custom')}</span>
  419. {/if}
  420. </button>
  421. </div>
  422. {#if (info?.meta?.suggestion_prompts ?? null) !== null}
  423. <button
  424. class="p-1 px-2 text-xs flex rounded transition"
  425. type="button"
  426. on:click={() => {
  427. if (
  428. info.meta.suggestion_prompts.length === 0 ||
  429. info.meta.suggestion_prompts.at(-1).content !== ''
  430. ) {
  431. info.meta.suggestion_prompts = [
  432. ...info.meta.suggestion_prompts,
  433. { content: '' }
  434. ];
  435. }
  436. }}
  437. >
  438. <svg
  439. xmlns="http://www.w3.org/2000/svg"
  440. viewBox="0 0 20 20"
  441. fill="currentColor"
  442. class="w-4 h-4"
  443. >
  444. <path
  445. d="M10.75 4.75a.75.75 0 00-1.5 0v4.5h-4.5a.75.75 0 000 1.5h4.5v4.5a.75.75 0 001.5 0v-4.5h4.5a.75.75 0 000-1.5h-4.5v-4.5z"
  446. />
  447. </svg>
  448. </button>
  449. {/if}
  450. </div>
  451. {#if info?.meta?.suggestion_prompts}
  452. <div class="flex flex-col space-y-1 mt-1 mb-3">
  453. {#if info.meta.suggestion_prompts.length > 0}
  454. {#each info.meta.suggestion_prompts as prompt, promptIdx}
  455. <div class=" flex rounded-lg">
  456. <input
  457. class=" text-sm w-full bg-transparent outline-none border-r border-gray-50 dark:border-gray-850"
  458. placeholder={$i18n.t('Write a prompt suggestion (e.g. Who are you?)')}
  459. bind:value={prompt.content}
  460. />
  461. <button
  462. class="px-2"
  463. type="button"
  464. on:click={() => {
  465. info.meta.suggestion_prompts.splice(promptIdx, 1);
  466. info.meta.suggestion_prompts = info.meta.suggestion_prompts;
  467. }}
  468. >
  469. <svg
  470. xmlns="http://www.w3.org/2000/svg"
  471. viewBox="0 0 20 20"
  472. fill="currentColor"
  473. class="w-4 h-4"
  474. >
  475. <path
  476. d="M6.28 5.22a.75.75 0 00-1.06 1.06L8.94 10l-3.72 3.72a.75.75 0 101.06 1.06L10 11.06l3.72 3.72a.75.75 0 101.06-1.06L11.06 10l3.72-3.72a.75.75 0 00-1.06-1.06L10 8.94 6.28 5.22z"
  477. />
  478. </svg>
  479. </button>
  480. </div>
  481. {/each}
  482. {:else}
  483. <div class="text-xs text-center">No suggestion prompts</div>
  484. {/if}
  485. </div>
  486. {/if}
  487. </div>
  488. <hr class=" dark:border-gray-850 my-1.5" />
  489. <div class="my-2">
  490. <Knowledge bind:selectedKnowledge={knowledge} collections={$knowledgeCollections} />
  491. </div>
  492. <div class="my-2">
  493. <ToolsSelector bind:selectedToolIds={toolIds} tools={$tools} />
  494. </div>
  495. <div class="my-2">
  496. <FiltersSelector
  497. bind:selectedFilterIds={filterIds}
  498. filters={$functions.filter((func) => func.type === 'filter')}
  499. />
  500. </div>
  501. <div class="my-2">
  502. <ActionsSelector
  503. bind:selectedActionIds={actionIds}
  504. actions={$functions.filter((func) => func.type === 'action')}
  505. />
  506. </div>
  507. <div class="my-2">
  508. <Capabilities bind:capabilities />
  509. </div>
  510. <div class="my-1">
  511. <div class="flex w-full justify-between items-center">
  512. <div class=" self-center text-sm font-semibold">{$i18n.t('Tags')}</div>
  513. </div>
  514. <div class="mt-2">
  515. <Tags
  516. tags={info?.meta?.tags ?? []}
  517. on:delete={(e) => {
  518. const tagName = e.detail;
  519. info.meta.tags = info.meta.tags.filter((tag) => tag.name !== tagName);
  520. }}
  521. on:add={(e) => {
  522. const tagName = e.detail;
  523. if (!(info?.meta?.tags ?? null)) {
  524. info.meta.tags = [{ name: tagName }];
  525. } else {
  526. info.meta.tags = [...info.meta.tags, { name: tagName }];
  527. }
  528. }}
  529. />
  530. </div>
  531. </div>
  532. <div class="my-2 text-gray-300 dark:text-gray-700">
  533. <div class="flex w-full justify-between mb-2">
  534. <div class=" self-center text-sm font-semibold">{$i18n.t('JSON Preview')}</div>
  535. <button
  536. class="p-1 px-3 text-xs flex rounded transition"
  537. type="button"
  538. on:click={() => {
  539. showPreview = !showPreview;
  540. }}
  541. >
  542. {#if showPreview}
  543. <span class="ml-2 self-center">{$i18n.t('Hide')}</span>
  544. {:else}
  545. <span class="ml-2 self-center">{$i18n.t('Show')}</span>
  546. {/if}
  547. </button>
  548. </div>
  549. {#if showPreview}
  550. <div>
  551. <textarea
  552. class="text-sm w-full bg-transparent outline-none resize-none"
  553. rows="10"
  554. value={JSON.stringify(info, null, 2)}
  555. disabled
  556. readonly
  557. />
  558. </div>
  559. {/if}
  560. </div>
  561. <div class="my-2 flex justify-end mb-20">
  562. <button
  563. class=" text-sm px-3 py-2 transition rounded-lg {loading
  564. ? ' cursor-not-allowed bg-gray-100 dark:bg-gray-800'
  565. : ' bg-gray-50 hover:bg-gray-100 dark:bg-white dark:hover:bg-gray-100 dark:text-black'} flex w-full justify-center"
  566. type="submit"
  567. disabled={loading}
  568. >
  569. <div class=" self-center font-medium">
  570. {#if edit}
  571. {$i18n.t('Save & Update')}
  572. {:else}
  573. {$i18n.t('Save & Create')}
  574. {/if}
  575. </div>
  576. {#if loading}
  577. <div class="ml-1.5 self-center">
  578. <svg
  579. class=" w-4 h-4"
  580. viewBox="0 0 24 24"
  581. fill="currentColor"
  582. xmlns="http://www.w3.org/2000/svg"
  583. ><style>
  584. .spinner_ajPY {
  585. transform-origin: center;
  586. animation: spinner_AtaB 0.75s infinite linear;
  587. }
  588. @keyframes spinner_AtaB {
  589. 100% {
  590. transform: rotate(360deg);
  591. }
  592. }
  593. </style><path
  594. 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"
  595. opacity=".25"
  596. /><path
  597. 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"
  598. class="spinner_ajPY"
  599. /></svg
  600. >
  601. </div>
  602. {/if}
  603. </button>
  604. </div>
  605. </div>
  606. </form>
  607. {/if}
  608. </div>