1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441 |
- import { WEBUI_API_BASE_URL, WEBUI_BASE_URL } from '$lib/constants';
- import { convertOpenApiToToolPayload } from '$lib/utils';
- import { getOpenAIModelsDirect } from './openai';
- export const getModels = async (
- token: string = '',
- connections: object | null = null,
- base: boolean = false
- ) => {
- let error = null;
- const res = await fetch(`${WEBUI_BASE_URL}/api/models${base ? '/base' : ''}`, {
- method: 'GET',
- headers: {
- Accept: 'application/json',
- 'Content-Type': 'application/json',
- ...(token && { authorization: `Bearer ${token}` })
- }
- })
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- error = err;
- console.log(err);
- return null;
- });
- if (error) {
- throw error;
- }
- let models = res?.data ?? [];
- if (connections && !base) {
- let localModels = [];
- if (connections) {
- const OPENAI_API_BASE_URLS = connections.OPENAI_API_BASE_URLS;
- const OPENAI_API_KEYS = connections.OPENAI_API_KEYS;
- const OPENAI_API_CONFIGS = connections.OPENAI_API_CONFIGS;
- const requests = [];
- for (const idx in OPENAI_API_BASE_URLS) {
- const url = OPENAI_API_BASE_URLS[idx];
- if (idx.toString() in OPENAI_API_CONFIGS) {
- const apiConfig = OPENAI_API_CONFIGS[idx.toString()] ?? {};
- const enable = apiConfig?.enable ?? true;
- const modelIds = apiConfig?.model_ids ?? [];
- if (enable) {
- if (modelIds.length > 0) {
- const modelList = {
- object: 'list',
- data: modelIds.map((modelId) => ({
- id: modelId,
- name: modelId,
- owned_by: 'openai',
- openai: { id: modelId },
- urlIdx: idx
- }))
- };
- requests.push(
- (async () => {
- return modelList;
- })()
- );
- } else {
- requests.push(
- (async () => {
- return await getOpenAIModelsDirect(url, OPENAI_API_KEYS[idx])
- .then((res) => {
- return res;
- })
- .catch((err) => {
- return {
- object: 'list',
- data: [],
- urlIdx: idx
- };
- });
- })()
- );
- }
- } else {
- requests.push(
- (async () => {
- return {
- object: 'list',
- data: [],
- urlIdx: idx
- };
- })()
- );
- }
- }
- }
- const responses = await Promise.all(requests);
- for (const idx in responses) {
- const response = responses[idx];
- const apiConfig = OPENAI_API_CONFIGS[idx.toString()] ?? {};
- let models = Array.isArray(response) ? response : (response?.data ?? []);
- models = models.map((model) => ({ ...model, openai: { id: model.id }, urlIdx: idx }));
- const prefixId = apiConfig.prefix_id;
- if (prefixId) {
- for (const model of models) {
- model.id = `${prefixId}.${model.id}`;
- }
- }
- const tags = apiConfig.tags;
- if (tags) {
- for (const model of models) {
- model.tags = tags;
- }
- }
- localModels = localModels.concat(models);
- }
- }
- models = models.concat(
- localModels.map((model) => ({
- ...model,
- name: model?.name ?? model?.id,
- direct: true
- }))
- );
- // Remove duplicates
- const modelsMap = {};
- for (const model of models) {
- modelsMap[model.id] = model;
- }
- models = Object.values(modelsMap);
- }
- return models;
- };
- type ChatCompletedForm = {
- model: string;
- messages: string[];
- chat_id: string;
- session_id: string;
- };
- export const chatCompleted = async (token: string, body: ChatCompletedForm) => {
- let error = null;
- const res = await fetch(`${WEBUI_BASE_URL}/api/chat/completed`, {
- method: 'POST',
- headers: {
- Accept: 'application/json',
- 'Content-Type': 'application/json',
- ...(token && { authorization: `Bearer ${token}` })
- },
- body: JSON.stringify(body)
- })
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- if ('detail' in err) {
- error = err.detail;
- } else {
- error = err;
- }
- return null;
- });
- if (error) {
- throw error;
- }
- return res;
- };
- type ChatActionForm = {
- model: string;
- messages: string[];
- chat_id: string;
- };
- export const chatAction = async (token: string, action_id: string, body: ChatActionForm) => {
- let error = null;
- const res = await fetch(`${WEBUI_BASE_URL}/api/chat/actions/${action_id}`, {
- method: 'POST',
- headers: {
- Accept: 'application/json',
- 'Content-Type': 'application/json',
- ...(token && { authorization: `Bearer ${token}` })
- },
- body: JSON.stringify(body)
- })
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- if ('detail' in err) {
- error = err.detail;
- } else {
- error = err;
- }
- return null;
- });
- if (error) {
- throw error;
- }
- return res;
- };
- export const stopTask = async (token: string, id: string) => {
- let error = null;
- const res = await fetch(`${WEBUI_BASE_URL}/api/tasks/stop/${id}`, {
- method: 'POST',
- headers: {
- Accept: 'application/json',
- 'Content-Type': 'application/json',
- ...(token && { authorization: `Bearer ${token}` })
- }
- })
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- if ('detail' in err) {
- error = err.detail;
- } else {
- error = err;
- }
- return null;
- });
- if (error) {
- throw error;
- }
- return res;
- };
- export const getToolServerData = async (token: string, url: string) => {
- let error = null;
- const res = await fetch(`${url}/openapi.json`, {
- method: 'GET',
- headers: {
- Accept: 'application/json',
- 'Content-Type': 'application/json',
- ...(token && { authorization: `Bearer ${token}` })
- }
- })
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- if ('detail' in err) {
- error = err.detail;
- } else {
- error = err;
- }
- return null;
- });
- if (error) {
- throw error;
- }
- const data = {
- openapi: res,
- info: res.info,
- specs: convertOpenApiToToolPayload(res)
- };
- console.log(data);
- return data;
- };
- export const getToolServersData = async (servers: object[]) => {
- return await Promise.all(
- servers
- .filter((server) => server?.config?.enable)
- .map(async (server) => {
- const data = await getToolServerData(server?.key, server?.url).catch((err) => {
- console.error(err);
- return null;
- });
- if (data) {
- const { openapi, info, specs } = data;
- return {
- url: server?.url,
- openapi: openapi,
- info: info,
- specs: specs
- };
- }
- })
- );
- };
- export const executeToolServer = async (
- token: string,
- url: string,
- name: string,
- params: Record<string, any>,
- serverData: { openapi: any; info: any; specs: any }
- ) => {
- let error = null;
- try {
- // Find the matching operationId in the OpenAPI spec
- const matchingRoute = Object.entries(serverData.openapi.paths).find(([_, methods]) =>
- Object.entries(methods as any).some(([__, operation]: any) => operation.operationId === name)
- );
- if (!matchingRoute) {
- throw new Error(`No matching route found for operationId: ${name}`);
- }
- const [routePath, methods] = matchingRoute;
- const methodEntry = Object.entries(methods as any).find(
- ([_, operation]: any) => operation.operationId === name
- );
- if (!methodEntry) {
- throw new Error(`No matching method found for operationId: ${name}`);
- }
- const [httpMethod, operation]: [string, any] = methodEntry;
- // Split parameters by type
- const pathParams: Record<string, any> = {};
- const queryParams: Record<string, any> = {};
- let bodyParams: any = {};
- if (operation.parameters) {
- operation.parameters.forEach((param: any) => {
- const paramName = param.name;
- const paramIn = param.in;
- if (params.hasOwnProperty(paramName)) {
- if (paramIn === 'path') {
- pathParams[paramName] = params[paramName];
- } else if (paramIn === 'query') {
- queryParams[paramName] = params[paramName];
- }
- }
- });
- }
- let finalUrl = `${url}${routePath}`;
- // Replace path parameters (`{param}`)
- Object.entries(pathParams).forEach(([key, value]) => {
- finalUrl = finalUrl.replace(new RegExp(`{${key}}`, 'g'), encodeURIComponent(value));
- });
- // Append query parameters to URL if any
- if (Object.keys(queryParams).length > 0) {
- const queryString = new URLSearchParams(
- Object.entries(queryParams).map(([k, v]) => [k, String(v)])
- ).toString();
- finalUrl += `?${queryString}`;
- }
- // Handle requestBody composite
- if (operation.requestBody && operation.requestBody.content) {
- const contentType = Object.keys(operation.requestBody.content)[0]; // typically "application/json"
- if (params.body !== undefined) {
- bodyParams = params.body; // Assume the provided params has a "body" property containing the payload
- } else {
- // Optional: Fallback or explicit error if body is expected but not provided
- throw new Error(`Request body expected for operation '${name}' but none found.`);
- }
- }
- // Prepare headers and request options
- const headers: Record<string, string> = {
- 'Content-Type': 'application/json',
- ...(token && { authorization: `Bearer ${token}` })
- };
- let requestOptions: RequestInit = {
- method: httpMethod.toUpperCase(),
- headers
- };
- if (['post', 'put', 'patch'].includes(httpMethod.toLowerCase()) && operation.requestBody) {
- requestOptions.body = JSON.stringify(bodyParams);
- }
- const res = await fetch(finalUrl, requestOptions);
- if (!res.ok) {
- const resText = await res.text();
- throw new Error(`HTTP error! Status: ${res.status}. Message: ${resText}`);
- }
- return await res.json();
- } catch (err: any) {
- error = err.message;
- console.error('API Request Error:', error);
- return { error };
- }
- };
- export const getTaskConfig = async (token: string = '') => {
- let error = null;
- const res = await fetch(`${WEBUI_BASE_URL}/api/v1/tasks/config`, {
- method: 'GET',
- headers: {
- Accept: 'application/json',
- 'Content-Type': 'application/json',
- ...(token && { authorization: `Bearer ${token}` })
- }
- })
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- error = err;
- return null;
- });
- if (error) {
- throw error;
- }
- return res;
- };
- export const updateTaskConfig = async (token: string, config: object) => {
- let error = null;
- const res = await fetch(`${WEBUI_BASE_URL}/api/v1/tasks/config/update`, {
- method: 'POST',
- headers: {
- Accept: 'application/json',
- 'Content-Type': 'application/json',
- ...(token && { authorization: `Bearer ${token}` })
- },
- body: JSON.stringify(config)
- })
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- if ('detail' in err) {
- error = err.detail;
- } else {
- error = err;
- }
- return null;
- });
- if (error) {
- throw error;
- }
- return res;
- };
- export const generateTitle = async (
- token: string = '',
- model: string,
- messages: string[],
- chat_id?: string
- ) => {
- let error = null;
- const res = await fetch(`${WEBUI_BASE_URL}/api/v1/tasks/title/completions`, {
- method: 'POST',
- headers: {
- Accept: 'application/json',
- 'Content-Type': 'application/json',
- Authorization: `Bearer ${token}`
- },
- body: JSON.stringify({
- model: model,
- messages: messages,
- ...(chat_id && { chat_id: chat_id })
- })
- })
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- if ('detail' in err) {
- error = err.detail;
- }
- return null;
- });
- if (error) {
- throw error;
- }
- return res?.choices[0]?.message?.content.replace(/["']/g, '') ?? 'New Chat';
- };
- export const generateTags = async (
- token: string = '',
- model: string,
- messages: string,
- chat_id?: string
- ) => {
- let error = null;
- const res = await fetch(`${WEBUI_BASE_URL}/api/v1/tasks/tags/completions`, {
- method: 'POST',
- headers: {
- Accept: 'application/json',
- 'Content-Type': 'application/json',
- Authorization: `Bearer ${token}`
- },
- body: JSON.stringify({
- model: model,
- messages: messages,
- ...(chat_id && { chat_id: chat_id })
- })
- })
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- if ('detail' in err) {
- error = err.detail;
- }
- return null;
- });
- if (error) {
- throw error;
- }
- try {
- // Step 1: Safely extract the response string
- const response = res?.choices[0]?.message?.content ?? '';
- // Step 2: Attempt to fix common JSON format issues like single quotes
- const sanitizedResponse = response.replace(/['‘’`]/g, '"'); // Convert single quotes to double quotes for valid JSON
- // Step 3: Find the relevant JSON block within the response
- const jsonStartIndex = sanitizedResponse.indexOf('{');
- const jsonEndIndex = sanitizedResponse.lastIndexOf('}');
- // Step 4: Check if we found a valid JSON block (with both `{` and `}`)
- if (jsonStartIndex !== -1 && jsonEndIndex !== -1) {
- const jsonResponse = sanitizedResponse.substring(jsonStartIndex, jsonEndIndex + 1);
- // Step 5: Parse the JSON block
- const parsed = JSON.parse(jsonResponse);
- // Step 6: If there's a "tags" key, return the tags array; otherwise, return an empty array
- if (parsed && parsed.tags) {
- return Array.isArray(parsed.tags) ? parsed.tags : [];
- } else {
- return [];
- }
- }
- // If no valid JSON block found, return an empty array
- return [];
- } catch (e) {
- // Catch and safely return empty array on any parsing errors
- console.error('Failed to parse response: ', e);
- return [];
- }
- };
- export const generateEmoji = async (
- token: string = '',
- model: string,
- prompt: string,
- chat_id?: string
- ) => {
- let error = null;
- const res = await fetch(`${WEBUI_BASE_URL}/api/v1/tasks/emoji/completions`, {
- method: 'POST',
- headers: {
- Accept: 'application/json',
- 'Content-Type': 'application/json',
- Authorization: `Bearer ${token}`
- },
- body: JSON.stringify({
- model: model,
- prompt: prompt,
- ...(chat_id && { chat_id: chat_id })
- })
- })
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- if ('detail' in err) {
- error = err.detail;
- }
- return null;
- });
- if (error) {
- throw error;
- }
- const response = res?.choices[0]?.message?.content.replace(/["']/g, '') ?? null;
- if (response) {
- if (/\p{Extended_Pictographic}/u.test(response)) {
- return response.match(/\p{Extended_Pictographic}/gu)[0];
- }
- }
- return null;
- };
- export const generateQueries = async (
- token: string = '',
- model: string,
- messages: object[],
- prompt: string,
- type?: string = 'web_search'
- ) => {
- let error = null;
- const res = await fetch(`${WEBUI_BASE_URL}/api/v1/tasks/queries/completions`, {
- method: 'POST',
- headers: {
- Accept: 'application/json',
- 'Content-Type': 'application/json',
- Authorization: `Bearer ${token}`
- },
- body: JSON.stringify({
- model: model,
- messages: messages,
- prompt: prompt,
- type: type
- })
- })
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- if ('detail' in err) {
- error = err.detail;
- }
- return null;
- });
- if (error) {
- throw error;
- }
- // Step 1: Safely extract the response string
- const response = res?.choices[0]?.message?.content ?? '';
- try {
- const jsonStartIndex = response.indexOf('{');
- const jsonEndIndex = response.lastIndexOf('}');
- if (jsonStartIndex !== -1 && jsonEndIndex !== -1) {
- const jsonResponse = response.substring(jsonStartIndex, jsonEndIndex + 1);
- // Step 5: Parse the JSON block
- const parsed = JSON.parse(jsonResponse);
- // Step 6: If there's a "queries" key, return the queries array; otherwise, return an empty array
- if (parsed && parsed.queries) {
- return Array.isArray(parsed.queries) ? parsed.queries : [];
- } else {
- return [];
- }
- }
- // If no valid JSON block found, return response as is
- return [response];
- } catch (e) {
- // Catch and safely return empty array on any parsing errors
- console.error('Failed to parse response: ', e);
- return [response];
- }
- };
- export const generateAutoCompletion = async (
- token: string = '',
- model: string,
- prompt: string,
- messages?: object[],
- type: string = 'search query'
- ) => {
- const controller = new AbortController();
- let error = null;
- const res = await fetch(`${WEBUI_BASE_URL}/api/v1/tasks/auto/completions`, {
- signal: controller.signal,
- method: 'POST',
- headers: {
- Accept: 'application/json',
- 'Content-Type': 'application/json',
- Authorization: `Bearer ${token}`
- },
- body: JSON.stringify({
- model: model,
- prompt: prompt,
- ...(messages && { messages: messages }),
- type: type,
- stream: false
- })
- })
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- if ('detail' in err) {
- error = err.detail;
- }
- return null;
- });
- if (error) {
- throw error;
- }
- const response = res?.choices[0]?.message?.content ?? '';
- try {
- const jsonStartIndex = response.indexOf('{');
- const jsonEndIndex = response.lastIndexOf('}');
- if (jsonStartIndex !== -1 && jsonEndIndex !== -1) {
- const jsonResponse = response.substring(jsonStartIndex, jsonEndIndex + 1);
- // Step 5: Parse the JSON block
- const parsed = JSON.parse(jsonResponse);
- // Step 6: If there's a "queries" key, return the queries array; otherwise, return an empty array
- if (parsed && parsed.text) {
- return parsed.text;
- } else {
- return '';
- }
- }
- // If no valid JSON block found, return response as is
- return response;
- } catch (e) {
- // Catch and safely return empty array on any parsing errors
- console.error('Failed to parse response: ', e);
- return response;
- }
- };
- export const generateMoACompletion = async (
- token: string = '',
- model: string,
- prompt: string,
- responses: string[]
- ) => {
- const controller = new AbortController();
- let error = null;
- const res = await fetch(`${WEBUI_BASE_URL}/api/v1/tasks/moa/completions`, {
- signal: controller.signal,
- method: 'POST',
- headers: {
- Accept: 'application/json',
- 'Content-Type': 'application/json',
- Authorization: `Bearer ${token}`
- },
- body: JSON.stringify({
- model: model,
- prompt: prompt,
- responses: responses,
- stream: true
- })
- }).catch((err) => {
- console.log(err);
- error = err;
- return null;
- });
- if (error) {
- throw error;
- }
- return [res, controller];
- };
- export const getPipelinesList = async (token: string = '') => {
- let error = null;
- const res = await fetch(`${WEBUI_BASE_URL}/api/v1/pipelines/list`, {
- method: 'GET',
- headers: {
- Accept: 'application/json',
- 'Content-Type': 'application/json',
- ...(token && { authorization: `Bearer ${token}` })
- }
- })
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- error = err;
- return null;
- });
- if (error) {
- throw error;
- }
- let pipelines = res?.data ?? [];
- return pipelines;
- };
- export const uploadPipeline = async (token: string, file: File, urlIdx: string) => {
- let error = null;
- // Create a new FormData object to handle the file upload
- const formData = new FormData();
- formData.append('file', file);
- formData.append('urlIdx', urlIdx);
- const res = await fetch(`${WEBUI_BASE_URL}/api/v1/pipelines/upload`, {
- method: 'POST',
- headers: {
- ...(token && { authorization: `Bearer ${token}` })
- // 'Content-Type': 'multipart/form-data' is not needed as Fetch API will set it automatically
- },
- body: formData
- })
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- if ('detail' in err) {
- error = err.detail;
- } else {
- error = err;
- }
- return null;
- });
- if (error) {
- throw error;
- }
- return res;
- };
- export const downloadPipeline = async (token: string, url: string, urlIdx: string) => {
- let error = null;
- const res = await fetch(`${WEBUI_BASE_URL}/api/v1/pipelines/add`, {
- method: 'POST',
- headers: {
- Accept: 'application/json',
- 'Content-Type': 'application/json',
- ...(token && { authorization: `Bearer ${token}` })
- },
- body: JSON.stringify({
- url: url,
- urlIdx: urlIdx
- })
- })
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- if ('detail' in err) {
- error = err.detail;
- } else {
- error = err;
- }
- return null;
- });
- if (error) {
- throw error;
- }
- return res;
- };
- export const deletePipeline = async (token: string, id: string, urlIdx: string) => {
- let error = null;
- const res = await fetch(`${WEBUI_BASE_URL}/api/v1/pipelines/delete`, {
- method: 'DELETE',
- headers: {
- Accept: 'application/json',
- 'Content-Type': 'application/json',
- ...(token && { authorization: `Bearer ${token}` })
- },
- body: JSON.stringify({
- id: id,
- urlIdx: urlIdx
- })
- })
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- if ('detail' in err) {
- error = err.detail;
- } else {
- error = err;
- }
- return null;
- });
- if (error) {
- throw error;
- }
- return res;
- };
- export const getPipelines = async (token: string, urlIdx?: string) => {
- let error = null;
- const searchParams = new URLSearchParams();
- if (urlIdx !== undefined) {
- searchParams.append('urlIdx', urlIdx);
- }
- const res = await fetch(`${WEBUI_BASE_URL}/api/v1/pipelines/?${searchParams.toString()}`, {
- method: 'GET',
- headers: {
- Accept: 'application/json',
- 'Content-Type': 'application/json',
- ...(token && { authorization: `Bearer ${token}` })
- }
- })
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- error = err;
- return null;
- });
- if (error) {
- throw error;
- }
- let pipelines = res?.data ?? [];
- return pipelines;
- };
- export const getPipelineValves = async (token: string, pipeline_id: string, urlIdx: string) => {
- let error = null;
- const searchParams = new URLSearchParams();
- if (urlIdx !== undefined) {
- searchParams.append('urlIdx', urlIdx);
- }
- const res = await fetch(
- `${WEBUI_BASE_URL}/api/v1/pipelines/${pipeline_id}/valves?${searchParams.toString()}`,
- {
- method: 'GET',
- headers: {
- Accept: 'application/json',
- 'Content-Type': 'application/json',
- ...(token && { authorization: `Bearer ${token}` })
- }
- }
- )
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- error = err;
- return null;
- });
- if (error) {
- throw error;
- }
- return res;
- };
- export const getPipelineValvesSpec = async (token: string, pipeline_id: string, urlIdx: string) => {
- let error = null;
- const searchParams = new URLSearchParams();
- if (urlIdx !== undefined) {
- searchParams.append('urlIdx', urlIdx);
- }
- const res = await fetch(
- `${WEBUI_BASE_URL}/api/v1/pipelines/${pipeline_id}/valves/spec?${searchParams.toString()}`,
- {
- method: 'GET',
- headers: {
- Accept: 'application/json',
- 'Content-Type': 'application/json',
- ...(token && { authorization: `Bearer ${token}` })
- }
- }
- )
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- error = err;
- return null;
- });
- if (error) {
- throw error;
- }
- return res;
- };
- export const updatePipelineValves = async (
- token: string = '',
- pipeline_id: string,
- valves: object,
- urlIdx: string
- ) => {
- let error = null;
- const searchParams = new URLSearchParams();
- if (urlIdx !== undefined) {
- searchParams.append('urlIdx', urlIdx);
- }
- const res = await fetch(
- `${WEBUI_BASE_URL}/api/v1/pipelines/${pipeline_id}/valves/update?${searchParams.toString()}`,
- {
- method: 'POST',
- headers: {
- Accept: 'application/json',
- 'Content-Type': 'application/json',
- ...(token && { authorization: `Bearer ${token}` })
- },
- body: JSON.stringify(valves)
- }
- )
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- if ('detail' in err) {
- error = err.detail;
- } else {
- error = err;
- }
- return null;
- });
- if (error) {
- throw error;
- }
- return res;
- };
- export const getBackendConfig = async () => {
- let error = null;
- const res = await fetch(`${WEBUI_BASE_URL}/api/config`, {
- method: 'GET',
- credentials: 'include',
- headers: {
- 'Content-Type': 'application/json'
- }
- })
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- error = err;
- return null;
- });
- if (error) {
- throw error;
- }
- return res;
- };
- export const getChangelog = async () => {
- let error = null;
- const res = await fetch(`${WEBUI_BASE_URL}/api/changelog`, {
- method: 'GET',
- headers: {
- 'Content-Type': 'application/json'
- }
- })
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- error = err;
- return null;
- });
- if (error) {
- throw error;
- }
- return res;
- };
- export const getVersionUpdates = async (token: string) => {
- let error = null;
- const res = await fetch(`${WEBUI_BASE_URL}/api/version/updates`, {
- method: 'GET',
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Bearer ${token}`
- }
- })
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- error = err;
- return null;
- });
- if (error) {
- throw error;
- }
- return res;
- };
- export const getModelFilterConfig = async (token: string) => {
- let error = null;
- const res = await fetch(`${WEBUI_BASE_URL}/api/config/model/filter`, {
- method: 'GET',
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Bearer ${token}`
- }
- })
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- error = err;
- return null;
- });
- if (error) {
- throw error;
- }
- return res;
- };
- export const updateModelFilterConfig = async (
- token: string,
- enabled: boolean,
- models: string[]
- ) => {
- let error = null;
- const res = await fetch(`${WEBUI_BASE_URL}/api/config/model/filter`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Bearer ${token}`
- },
- body: JSON.stringify({
- enabled: enabled,
- models: models
- })
- })
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- error = err;
- return null;
- });
- if (error) {
- throw error;
- }
- return res;
- };
- export const getWebhookUrl = async (token: string) => {
- let error = null;
- const res = await fetch(`${WEBUI_BASE_URL}/api/webhook`, {
- method: 'GET',
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Bearer ${token}`
- }
- })
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- error = err;
- return null;
- });
- if (error) {
- throw error;
- }
- return res.url;
- };
- export const updateWebhookUrl = async (token: string, url: string) => {
- let error = null;
- const res = await fetch(`${WEBUI_BASE_URL}/api/webhook`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Bearer ${token}`
- },
- body: JSON.stringify({
- url: url
- })
- })
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- error = err;
- return null;
- });
- if (error) {
- throw error;
- }
- return res.url;
- };
- export const getCommunitySharingEnabledStatus = async (token: string) => {
- let error = null;
- const res = await fetch(`${WEBUI_BASE_URL}/api/community_sharing`, {
- method: 'GET',
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Bearer ${token}`
- }
- })
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- error = err;
- return null;
- });
- if (error) {
- throw error;
- }
- return res;
- };
- export const toggleCommunitySharingEnabledStatus = async (token: string) => {
- let error = null;
- const res = await fetch(`${WEBUI_BASE_URL}/api/community_sharing/toggle`, {
- method: 'GET',
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Bearer ${token}`
- }
- })
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- error = err.detail;
- return null;
- });
- if (error) {
- throw error;
- }
- return res;
- };
- export const getModelConfig = async (token: string): Promise<GlobalModelConfig> => {
- let error = null;
- const res = await fetch(`${WEBUI_BASE_URL}/api/config/models`, {
- method: 'GET',
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Bearer ${token}`
- }
- })
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- error = err;
- return null;
- });
- if (error) {
- throw error;
- }
- return res.models;
- };
- export interface ModelConfig {
- id: string;
- name: string;
- meta: ModelMeta;
- base_model_id?: string;
- params: ModelParams;
- }
- export interface ModelMeta {
- description?: string;
- capabilities?: object;
- profile_image_url?: string;
- }
- export interface ModelParams {}
- export type GlobalModelConfig = ModelConfig[];
- export const updateModelConfig = async (token: string, config: GlobalModelConfig) => {
- let error = null;
- const res = await fetch(`${WEBUI_BASE_URL}/api/config/models`, {
- method: 'POST',
- headers: {
- 'Content-Type': 'application/json',
- Authorization: `Bearer ${token}`
- },
- body: JSON.stringify({
- models: config
- })
- })
- .then(async (res) => {
- if (!res.ok) throw await res.json();
- return res.json();
- })
- .catch((err) => {
- console.log(err);
- error = err;
- return null;
- });
- if (error) {
- throw error;
- }
- return res;
- };
|