open-webui/src/routes/(app)/+page.svelte

890 lines
23 KiB
Svelte
Raw Normal View History

2023-10-08 22:38:42 +00:00
<script lang="ts">
import { v4 as uuidv4 } from 'uuid';
2024-03-01 09:18:07 +00:00
import { toast } from 'svelte-sonner';
2023-10-28 22:16:04 +00:00
2024-03-03 10:04:26 +00:00
import { onMount, tick, getContext } from 'svelte';
2023-11-20 01:47:07 +00:00
import { goto } from '$app/navigation';
2023-12-26 11:28:30 +00:00
import { page } from '$app/stores';
2023-10-29 02:58:16 +00:00
2024-01-18 10:55:25 +00:00
import {
models,
modelfiles,
user,
settings,
chats,
chatId,
config,
WEBUI_NAME,
2024-01-18 10:55:25 +00:00
tags as _tags
} from '$lib/stores';
2024-01-07 08:57:10 +00:00
import { copyToClipboard, splitStream } from '$lib/utils';
2023-12-26 20:50:52 +00:00
import { generateChatCompletion, cancelOllamaRequest } from '$lib/apis/ollama';
2024-01-18 10:10:07 +00:00
import {
addTagById,
createNewChat,
deleteTagById,
2024-01-18 10:55:25 +00:00
getAllChatTags,
2024-01-18 10:10:07 +00:00
getChatList,
getTagsById,
updateChatById
} from '$lib/apis/chats';
2024-02-03 23:57:06 +00:00
import { queryCollection, queryDoc } from '$lib/apis/rag';
import { generateOpenAIChatCompletion, generateTitle } from '$lib/apis/openai';
2023-11-20 01:47:07 +00:00
import MessageInput from '$lib/components/chat/MessageInput.svelte';
import Messages from '$lib/components/chat/Messages.svelte';
import ModelSelector from '$lib/components/chat/ModelSelector.svelte';
2023-10-20 20:21:40 +00:00
import Navbar from '$lib/components/layout/Navbar.svelte';
2024-01-07 08:57:10 +00:00
import { RAGTemplate } from '$lib/utils/rag';
import { LITELLM_API_BASE_URL, OLLAMA_API_BASE_URL, OPENAI_API_BASE_URL } from '$lib/constants';
2024-02-24 01:12:19 +00:00
import { WEBUI_BASE_URL } from '$lib/constants';
2024-03-03 10:04:26 +00:00
const i18n = getContext('i18n');
2023-11-20 01:47:07 +00:00
let stopResponseFlag = false;
let autoScroll = true;
2024-01-07 11:19:34 +00:00
let processing = '';
2024-03-03 22:42:01 +00:00
let messagesContainerElement: HTMLDivElement;
2024-01-18 03:19:44 +00:00
let currentRequestId = null;
2024-03-30 00:20:07 +00:00
let showModelSelector = false;
2023-11-12 18:30:34 +00:00
let selectedModels = [''];
2023-12-26 20:50:52 +00:00
let selectedModelfile = null;
$: selectedModelfile =
selectedModels.length === 1 &&
$modelfiles.filter((modelfile) => modelfile.tagName === selectedModels[0]).length > 0
? $modelfiles.filter((modelfile) => modelfile.tagName === selectedModels[0])[0]
: null;
2023-11-11 21:03:54 +00:00
2023-12-30 07:03:48 +00:00
let selectedModelfiles = {};
$: selectedModelfiles = selectedModels.reduce((a, tagName, i, arr) => {
const modelfile =
$modelfiles.filter((modelfile) => modelfile.tagName === tagName)?.at(0) ?? undefined;
return {
...a,
...(modelfile && { [tagName]: modelfile })
};
}, {});
2023-12-26 11:28:30 +00:00
let chat = null;
2024-01-18 10:10:07 +00:00
let tags = [];
2023-12-26 11:28:30 +00:00
2023-10-25 00:49:54 +00:00
let title = '';
2023-10-08 22:38:42 +00:00
let prompt = '';
2023-11-25 08:21:07 +00:00
let files = [];
let messages = [];
2023-11-12 04:18:03 +00:00
let history = {
messages: {},
currentId: null
};
$: if (history.currentId !== null) {
let _messages = [];
let currentMessage = history.messages[history.currentId];
while (currentMessage !== null) {
_messages.unshift({ ...currentMessage });
currentMessage =
currentMessage.parentId !== null ? history.messages[currentMessage.parentId] : null;
}
messages = _messages;
2023-12-06 16:14:20 +00:00
} else {
messages = [];
2023-11-12 04:18:03 +00:00
}
2023-10-08 22:38:42 +00:00
onMount(async () => {
2023-12-26 11:28:30 +00:00
await initNewChat();
2023-10-13 01:18:07 +00:00
});
//////////////////////////
// Web functions
//////////////////////////
2023-11-20 01:47:07 +00:00
const initNewChat = async () => {
if (currentRequestId !== null) {
2024-03-23 20:12:23 +00:00
await cancelOllamaRequest(localStorage.token, currentRequestId);
currentRequestId = null;
}
2023-12-26 22:41:41 +00:00
window.history.replaceState(history.state, '', `/`);
2023-12-26 11:28:30 +00:00
await chatId.set('');
2023-10-28 06:26:01 +00:00
2023-11-20 01:47:07 +00:00
autoScroll = true;
2023-10-28 06:26:01 +00:00
2023-11-20 01:47:07 +00:00
title = '';
messages = [];
history = {
messages: {},
currentId: null
2023-11-12 04:18:03 +00:00
};
2024-01-03 00:48:10 +00:00
if ($page.url.searchParams.get('models')) {
selectedModels = $page.url.searchParams.get('models')?.split(',');
} else if ($settings?.models) {
selectedModels = $settings?.models;
} else if ($config?.default_models) {
selectedModels = $config?.default_models.split(',');
} else {
selectedModels = [''];
}
2023-12-11 06:59:51 +00:00
2024-02-24 09:49:19 +00:00
selectedModels = selectedModels.map((modelId) =>
$models.map((m) => m.id).includes(modelId) ? modelId : ''
);
2023-12-11 06:59:51 +00:00
let _settings = JSON.parse(localStorage.getItem('settings') ?? '{}');
settings.set({
..._settings
});
2024-02-28 03:56:52 +00:00
const chatInput = document.getElementById('chat-textarea');
setTimeout(() => chatInput?.focus(), 0);
2023-11-12 04:18:03 +00:00
};
2024-02-16 00:20:46 +00:00
const scrollToBottom = () => {
2024-03-12 20:47:49 +00:00
if (messagesContainerElement) {
messagesContainerElement.scrollTop = messagesContainerElement.scrollHeight;
}
2024-02-16 00:20:46 +00:00
};
//////////////////////////
// Ollama functions
//////////////////////////
2024-01-10 06:47:31 +00:00
const submitPrompt = async (userPrompt, _user = null) => {
2024-01-07 08:57:10 +00:00
console.log('submitPrompt', $chatId);
2024-02-24 09:49:19 +00:00
selectedModels = selectedModels.map((modelId) =>
$models.map((m) => m.id).includes(modelId) ? modelId : ''
);
2024-01-07 08:57:10 +00:00
if (selectedModels.includes('')) {
2024-03-03 10:01:34 +00:00
toast.error($i18n.t('Model not selected'));
2024-01-07 08:57:10 +00:00
} else if (messages.length != 0 && messages.at(-1).done != true) {
// Response not done
console.log('wait');
2024-01-07 17:33:34 +00:00
} else if (
files.length > 0 &&
files.filter((file) => file.upload_status === false).length > 0
) {
// Upload not done
toast.error(
2024-03-03 10:04:26 +00:00
$i18n.t(
`Oops! Hold tight! Your files are still in the processing oven. We're cooking them up to perfection. Please be patient and we'll let you know once they're ready.`
)
2024-01-07 17:33:34 +00:00
);
2024-01-07 08:57:10 +00:00
} else {
// Reset chat message textarea height
document.getElementById('chat-textarea').style.height = '';
// Create user message
let userMessageId = uuidv4();
let userMessage = {
id: userMessageId,
parentId: messages.length !== 0 ? messages.at(-1).id : null,
childrenIds: [],
role: 'user',
2024-01-10 06:47:31 +00:00
user: _user ?? undefined,
2024-01-07 08:57:10 +00:00
content: userPrompt,
2024-01-17 23:09:38 +00:00
files: files.length > 0 ? files : undefined,
2024-01-18 01:43:45 +00:00
timestamp: Math.floor(Date.now() / 1000) // Unix epoch
2024-01-07 08:57:10 +00:00
};
// Add message to history and Set currentId to messageId
history.messages[userMessageId] = userMessage;
history.currentId = userMessageId;
// Append messageId to childrenIds of parent message
if (messages.length !== 0) {
history.messages[messages.at(-1).id].childrenIds.push(userMessageId);
}
// Wait until history/message have been updated
await tick();
// Create new chat if only one message in messages
if (messages.length == 1) {
if ($settings.saveChatHistory ?? true) {
chat = await createNewChat(localStorage.token, {
id: $chatId,
title: $i18n.t('New Chat'),
2024-01-07 08:57:10 +00:00
models: selectedModels,
system: $settings.system ?? undefined,
options: {
...($settings.options ?? {})
},
messages: messages,
history: history,
2024-01-18 10:17:31 +00:00
tags: [],
2024-01-07 08:57:10 +00:00
timestamp: Date.now()
});
await chats.set(await getChatList(localStorage.token));
await chatId.set(chat.id);
} else {
await chatId.set('local');
}
await tick();
}
// Reset chat input textarea
prompt = '';
files = [];
// Send prompt
await sendPrompt(userPrompt, userMessageId);
}
};
2023-12-26 11:28:30 +00:00
const sendPrompt = async (prompt, parentId) => {
const _chatId = JSON.parse(JSON.stringify($chatId));
2024-01-07 08:57:10 +00:00
2023-11-12 18:30:34 +00:00
await Promise.all(
2024-02-22 12:12:26 +00:00
selectedModels.map(async (modelId) => {
const model = $models.filter((m) => m.id === modelId).at(0);
2024-01-03 00:06:11 +00:00
2024-02-24 09:49:19 +00:00
if (model) {
// Create response message
let responseMessageId = uuidv4();
let responseMessage = {
parentId: parentId,
id: responseMessageId,
childrenIds: [],
role: 'assistant',
content: '',
model: model.id,
timestamp: Math.floor(Date.now() / 1000) // Unix epoch
};
// Add message to history and Set currentId to messageId
history.messages[responseMessageId] = responseMessage;
history.currentId = responseMessageId;
// Append messageId to childrenIds of parent message
if (parentId !== null) {
history.messages[parentId].childrenIds = [
...history.messages[parentId].childrenIds,
responseMessageId
];
}
2024-02-15 09:23:02 +00:00
2024-02-24 09:49:19 +00:00
if (model?.external) {
await sendPromptOpenAI(model, prompt, responseMessageId, _chatId);
} else if (model) {
await sendPromptOllama(model, prompt, responseMessageId, _chatId);
}
2024-01-03 00:06:11 +00:00
} else {
2024-03-03 10:01:34 +00:00
toast.error($i18n.t(`Model {{modelId}} not found`, { modelId }));
2023-11-12 18:30:34 +00:00
}
})
);
2023-11-20 01:47:07 +00:00
2023-12-26 20:50:52 +00:00
await chats.set(await getChatList(localStorage.token));
2023-11-04 00:16:02 +00:00
};
2024-02-15 09:23:02 +00:00
const sendPromptOllama = async (model, userPrompt, responseMessageId, _chatId) => {
2024-02-22 12:12:26 +00:00
model = model.id;
2024-02-15 09:23:02 +00:00
const responseMessage = history.messages[responseMessageId];
2023-11-12 04:18:03 +00:00
2023-12-26 20:50:52 +00:00
// Wait until history/message have been updated
2023-12-11 06:47:16 +00:00
await tick();
2023-12-26 20:50:52 +00:00
// Scroll down
2024-02-16 00:20:46 +00:00
scrollToBottom();
2024-02-04 08:29:40 +00:00
const messagesBody = [
$settings.system
? {
role: 'system',
content: $settings.system
}
: undefined,
2024-03-03 07:23:49 +00:00
...messages
2024-02-04 08:29:40 +00:00
]
.filter((message) => message)
2024-03-09 07:19:20 +00:00
.map((message, idx, arr) => {
// Prepare the base message object
const baseMessage = {
role: message.role,
content: arr.length - 2 !== idx ? message.content : message?.raContent ?? message.content
};
// Extract and format image URLs if any exist
const imageUrls = message.files
?.filter((file) => file.type === 'image')
.map((file) => file.url.slice(file.url.indexOf(',') + 1));
// Add images array only if it contains elements
2024-03-12 20:43:49 +00:00
if (imageUrls && imageUrls.length > 0 && message.role === 'user') {
2024-03-09 07:19:20 +00:00
baseMessage.images = imageUrls;
}
return baseMessage;
});
2024-02-04 08:29:40 +00:00
let lastImageIndex = -1;
// Find the index of the last object with images
messagesBody.forEach((item, index) => {
if (item.images) {
lastImageIndex = index;
}
});
// Remove images from all but the last one
messagesBody.forEach((item, index) => {
if (index !== lastImageIndex) {
delete item.images;
}
});
2024-03-09 06:34:47 +00:00
const docs = messages
.filter((message) => message?.files ?? null)
.map((message) =>
message.files.filter((item) => item.type === 'doc' || item.type === 'collection')
)
.flat(1);
2024-01-18 03:19:44 +00:00
const [res, controller] = await generateChatCompletion(localStorage.token, {
2024-01-04 21:06:31 +00:00
model: model,
2024-02-04 08:29:40 +00:00
messages: messagesBody,
2024-01-04 21:06:31 +00:00
options: {
...($settings.options ?? {})
},
2024-02-13 07:35:31 +00:00
format: $settings.requestFormat ?? undefined,
2024-03-09 06:34:47 +00:00
keep_alive: $settings.keepAlive ?? undefined,
2024-03-09 06:43:06 +00:00
docs: docs.length > 0 ? docs : undefined
2024-01-04 21:06:31 +00:00
});
2023-12-11 06:47:16 +00:00
if (res && res.ok) {
2024-01-18 03:19:44 +00:00
console.log('controller', controller);
2023-12-11 10:28:49 +00:00
const reader = res.body
.pipeThrough(new TextDecoderStream())
.pipeThrough(splitStream('\n'))
.getReader();
while (true) {
const { value, done } = await reader.read();
if (done || stopResponseFlag || _chatId !== $chatId) {
responseMessage.done = true;
messages = messages;
2024-01-18 03:19:44 +00:00
if (stopResponseFlag) {
controller.abort('User: Stop Response');
2024-03-23 20:12:23 +00:00
await cancelOllamaRequest(localStorage.token, currentRequestId);
2024-01-18 03:19:44 +00:00
}
currentRequestId = null;
2023-12-11 10:28:49 +00:00
break;
}
2023-12-11 10:28:49 +00:00
try {
let lines = value.split('\n');
2023-12-11 10:28:49 +00:00
for (const line of lines) {
if (line !== '') {
console.log(line);
let data = JSON.parse(line);
2023-12-11 06:47:16 +00:00
2023-12-11 10:28:49 +00:00
if ('detail' in data) {
throw data;
}
2023-12-11 06:47:16 +00:00
2024-01-18 03:19:44 +00:00
if ('id' in data) {
console.log(data);
currentRequestId = data.id;
} else {
if (data.done == false) {
if (responseMessage.content == '' && data.message.content == '\n') {
continue;
} else {
responseMessage.content += data.message.content;
messages = messages;
}
2023-12-11 10:28:49 +00:00
} else {
2024-01-18 03:19:44 +00:00
responseMessage.done = true;
if (responseMessage.content == '') {
responseMessage.error = true;
responseMessage.content =
'Oops! No text generated from Ollama, Please try again.';
}
responseMessage.context = data.context ?? null;
responseMessage.info = {
total_duration: data.total_duration,
load_duration: data.load_duration,
sample_count: data.sample_count,
sample_duration: data.sample_duration,
prompt_eval_count: data.prompt_eval_count,
prompt_eval_duration: data.prompt_eval_duration,
eval_count: data.eval_count,
eval_duration: data.eval_duration
};
2023-12-11 10:28:49 +00:00
messages = messages;
2023-12-19 02:48:51 +00:00
2024-01-18 03:19:44 +00:00
if ($settings.notificationEnabled && !document.hasFocus()) {
const notification = new Notification(
selectedModelfile
? `${
selectedModelfile.title.charAt(0).toUpperCase() +
selectedModelfile.title.slice(1)
}`
2024-02-15 22:43:10 +00:00
: `${model}`,
2024-01-18 03:19:44 +00:00
{
body: responseMessage.content,
2024-02-24 01:12:19 +00:00
icon: selectedModelfile?.imageUrl ?? `${WEBUI_BASE_URL}/static/favicon.png`
2024-01-18 03:19:44 +00:00
}
);
}
if ($settings.responseAutoCopy) {
copyToClipboard(responseMessage.content);
}
2024-02-10 00:00:39 +00:00
if ($settings.responseAutoPlayback) {
2024-02-10 00:37:21 +00:00
await tick();
2024-02-10 00:00:39 +00:00
document.getElementById(`speak-button-${responseMessage.id}`)?.click();
}
2023-12-19 02:48:51 +00:00
}
}
}
}
2023-12-11 10:28:49 +00:00
} catch (error) {
console.log(error);
if ('detail' in error) {
toast.error(error.detail);
}
break;
}
2023-12-11 10:28:49 +00:00
if (autoScroll) {
2024-02-16 00:20:46 +00:00
scrollToBottom();
2023-11-19 00:47:12 +00:00
}
2023-12-26 11:28:30 +00:00
}
2023-12-26 11:28:30 +00:00
if ($chatId == _chatId) {
2024-01-06 10:33:00 +00:00
if ($settings.saveChatHistory ?? true) {
chat = await updateChatById(localStorage.token, _chatId, {
messages: messages,
history: history
});
await chats.set(await getChatList(localStorage.token));
}
}
} else {
if (res !== null) {
const error = await res.json();
console.log(error);
2023-11-19 00:47:12 +00:00
if ('detail' in error) {
toast.error(error.detail);
2023-12-13 23:31:07 +00:00
responseMessage.content = error.detail;
} else {
toast.error(error.error);
2023-12-13 23:31:07 +00:00
responseMessage.content = error.error;
2023-11-19 00:47:12 +00:00
}
} else {
2024-03-03 10:04:26 +00:00
toast.error(
$i18n.t(`Uh-oh! There was an issue connecting to {{provider}}.`, { provider: 'Ollama' })
);
responseMessage.content = $i18n.t(`Uh-oh! There was an issue connecting to {{provider}}.`, {
provider: 'Ollama'
});
}
2023-12-13 23:31:07 +00:00
responseMessage.error = true;
2024-03-03 10:04:26 +00:00
responseMessage.content = $i18n.t(`Uh-oh! There was an issue connecting to {{provider}}.`, {
provider: 'Ollama'
});
2023-12-13 23:31:07 +00:00
responseMessage.done = true;
messages = messages;
}
stopResponseFlag = false;
await tick();
2023-12-26 20:50:52 +00:00
if (autoScroll) {
2024-02-16 00:20:46 +00:00
scrollToBottom();
}
2023-11-04 00:16:02 +00:00
2023-11-19 00:47:12 +00:00
if (messages.length == 2 && messages.at(1).content !== '') {
2023-12-06 16:14:20 +00:00
window.history.replaceState(history.state, '', `/c/${_chatId}`);
const _title = await generateChatTitle(userPrompt);
await setChatTitle(_chatId, _title);
2023-11-04 00:16:02 +00:00
}
};
2024-02-15 09:23:02 +00:00
const sendPromptOpenAI = async (model, userPrompt, responseMessageId, _chatId) => {
const responseMessage = history.messages[responseMessageId];
// Wait until history/message have been updated
await tick();
2024-02-16 00:20:46 +00:00
scrollToBottom();
2023-11-04 00:16:02 +00:00
2024-03-09 06:34:47 +00:00
const docs = messages
.filter((message) => message?.files ?? null)
.map((message) =>
message.files.filter((item) => item.type === 'doc' || item.type === 'collection')
)
.flat(1);
2024-03-09 06:43:06 +00:00
console.log(docs);
2024-02-22 12:12:26 +00:00
const res = await generateOpenAIChatCompletion(
localStorage.token,
{
model: model.id,
stream: true,
messages: [
$settings.system
2024-01-05 03:20:49 +00:00
? {
2024-02-22 12:12:26 +00:00
role: 'system',
content: $settings.system
2024-01-05 03:20:49 +00:00
}
2024-02-22 12:12:26 +00:00
: undefined,
2024-03-03 07:23:49 +00:00
...messages
2024-02-22 12:12:26 +00:00
]
.filter((message) => message)
.map((message, idx, arr) => ({
role: message.role,
2024-03-12 20:43:49 +00:00
...((message.files?.filter((file) => file.type === 'image').length > 0 ?? false) &&
message.role === 'user'
2024-02-22 12:12:26 +00:00
? {
content: [
{
type: 'text',
text:
arr.length - 1 !== idx
? message.content
: message?.raContent ?? message.content
},
...message.files
.filter((file) => file.type === 'image')
.map((file) => ({
type: 'image_url',
image_url: {
url: file.url
}
}))
]
}
: {
content:
arr.length - 1 !== idx ? message.content : message?.raContent ?? message.content
})
})),
seed: $settings?.options?.seed ?? undefined,
stop: $settings?.options?.stop ?? undefined,
temperature: $settings?.options?.temperature ?? undefined,
top_p: $settings?.options?.top_p ?? undefined,
num_ctx: $settings?.options?.num_ctx ?? undefined,
frequency_penalty: $settings?.options?.repeat_penalty ?? undefined,
2024-03-09 06:34:47 +00:00
max_tokens: $settings?.options?.num_predict ?? undefined,
2024-03-09 06:43:06 +00:00
docs: docs.length > 0 ? docs : undefined
2024-02-22 12:12:26 +00:00
},
model.source === 'litellm' ? `${LITELLM_API_BASE_URL}/v1` : `${OPENAI_API_BASE_URL}`
);
2023-11-04 00:16:02 +00:00
2024-01-05 03:20:49 +00:00
if (res && res.ok) {
const reader = res.body
.pipeThrough(new TextDecoderStream())
.pipeThrough(splitStream('\n'))
.getReader();
2023-11-04 00:16:02 +00:00
2024-01-05 03:20:49 +00:00
while (true) {
const { value, done } = await reader.read();
if (done || stopResponseFlag || _chatId !== $chatId) {
responseMessage.done = true;
messages = messages;
break;
}
2023-11-04 00:16:02 +00:00
2024-01-05 03:20:49 +00:00
try {
let lines = value.split('\n');
for (const line of lines) {
if (line !== '') {
console.log(line);
if (line === 'data: [DONE]') {
responseMessage.done = true;
messages = messages;
} else {
2024-01-05 03:20:49 +00:00
let data = JSON.parse(line.replace(/^data: /, ''));
console.log(data);
if (responseMessage.content == '' && data.choices[0].delta.content == '\n') {
continue;
} else {
responseMessage.content += data.choices[0].delta.content ?? '';
messages = messages;
}
}
}
}
2024-01-05 03:20:49 +00:00
} catch (error) {
console.log(error);
}
2023-12-19 02:48:51 +00:00
2024-01-05 03:20:49 +00:00
if ($settings.notificationEnabled && !document.hasFocus()) {
const notification = new Notification(`OpenAI ${model}`, {
body: responseMessage.content,
2024-02-24 01:12:19 +00:00
icon: `${WEBUI_BASE_URL}/static/favicon.png`
2024-01-05 03:20:49 +00:00
});
2023-12-19 02:48:51 +00:00
}
2024-01-05 03:20:49 +00:00
if ($settings.responseAutoCopy) {
copyToClipboard(responseMessage.content);
}
2023-12-19 02:48:51 +00:00
2024-02-10 00:00:39 +00:00
if ($settings.responseAutoPlayback) {
2024-02-10 00:37:21 +00:00
await tick();
2024-02-10 00:00:39 +00:00
document.getElementById(`speak-button-${responseMessage.id}`)?.click();
}
2023-11-04 00:16:02 +00:00
if (autoScroll) {
2024-02-16 00:20:46 +00:00
scrollToBottom();
2023-11-04 00:16:02 +00:00
}
2024-01-05 03:20:49 +00:00
}
2023-11-04 00:16:02 +00:00
2024-01-05 03:20:49 +00:00
if ($chatId == _chatId) {
2024-01-06 10:33:00 +00:00
if ($settings.saveChatHistory ?? true) {
chat = await updateChatById(localStorage.token, _chatId, {
messages: messages,
history: history
});
await chats.set(await getChatList(localStorage.token));
}
2024-01-05 03:20:49 +00:00
}
} else {
if (res !== null) {
const error = await res.json();
console.log(error);
if ('detail' in error) {
toast.error(error.detail);
responseMessage.content = error.detail;
} else {
if ('message' in error.error) {
toast.error(error.error.message);
responseMessage.content = error.error.message;
} else {
toast.error(error.error);
responseMessage.content = error.error;
}
2023-11-04 00:16:02 +00:00
}
2024-01-05 03:20:49 +00:00
} else {
2024-03-03 10:04:26 +00:00
toast.error(
$i18n.t(`Uh-oh! There was an issue connecting to {{provider}}.`, { provider: model })
);
responseMessage.content = $i18n.t(`Uh-oh! There was an issue connecting to {{provider}}.`, {
provider: model
});
2023-11-04 00:16:02 +00:00
}
2024-01-05 03:20:49 +00:00
responseMessage.error = true;
2024-03-03 10:04:26 +00:00
responseMessage.content = $i18n.t(`Uh-oh! There was an issue connecting to {{provider}}.`, {
provider: model
});
2024-01-05 03:20:49 +00:00
responseMessage.done = true;
messages = messages;
}
stopResponseFlag = false;
await tick();
if (autoScroll) {
2024-02-16 00:20:46 +00:00
scrollToBottom();
2024-01-05 03:20:49 +00:00
}
if (messages.length == 2) {
window.history.replaceState(history.state, '', `/c/${_chatId}`);
const _title = await generateChatTitle(userPrompt);
await setChatTitle(_chatId, _title);
2023-11-04 00:16:02 +00:00
}
};
2023-11-20 01:47:07 +00:00
const stopResponse = () => {
stopResponseFlag = true;
console.log('stopResponse');
};
const regenerateResponse = async () => {
2023-12-26 20:50:52 +00:00
console.log('regenerateResponse');
if (messages.length != 0 && messages.at(-1).done == true) {
messages.splice(messages.length - 1, 1);
messages = messages;
2023-10-08 22:38:42 +00:00
let userMessage = messages.at(-1);
let userPrompt = userMessage.content;
2023-11-04 00:16:02 +00:00
2023-12-26 20:50:52 +00:00
await sendPrompt(userPrompt, userMessage.id);
2023-10-08 22:38:42 +00:00
}
};
2024-02-15 09:23:02 +00:00
const continueGeneration = async () => {
console.log('continueGeneration');
const _chatId = JSON.parse(JSON.stringify($chatId));
if (messages.length != 0 && messages.at(-1).done == true) {
const responseMessage = history.messages[history.currentId];
2024-02-16 21:56:50 +00:00
responseMessage.done = false;
await tick();
2024-02-25 23:46:12 +00:00
const model = $models.filter((m) => m.id === responseMessage.model).at(0);
if (model) {
if (model?.external) {
await sendPromptOpenAI(
model,
history.messages[responseMessage.parentId].content,
responseMessage.id,
_chatId
);
} else
await sendPromptOllama(
model,
history.messages[responseMessage.parentId].content,
responseMessage.id,
_chatId
);
2024-02-15 09:23:02 +00:00
}
2024-02-25 23:46:12 +00:00
} else {
2024-03-03 10:01:34 +00:00
toast.error($i18n.t(`Model {{modelId}} not found`, { modelId }));
2024-02-15 09:23:02 +00:00
}
};
const generateChatTitle = async (userPrompt) => {
if ($settings?.title?.auto ?? true) {
const model = $models.find((model) => model.id === selectedModels[0]);
const titleModelId =
model?.external ?? false
? $settings?.title?.modelExternal ?? selectedModels[0]
: $settings?.title?.model ?? selectedModels[0];
const titleModel = $models.find((model) => model.id === titleModelId);
console.log(titleModel);
2023-12-26 20:50:52 +00:00
const title = await generateTitle(
localStorage.token,
$settings?.title?.prompt ??
2024-03-07 18:51:00 +00:00
$i18n.t(
"Create a concise, 3-5 word phrase as a header for the following query, strictly adhering to the 3-5 word limit and avoiding the use of the word 'title':"
) + ' {{prompt}}',
titleModelId,
userPrompt,
titleModel?.external ?? false
? titleModel.source === 'litellm'
? `${LITELLM_API_BASE_URL}/v1`
: `${OPENAI_API_BASE_URL}`
: `${OLLAMA_API_BASE_URL}/v1`
2023-12-26 20:50:52 +00:00
);
return title;
} else {
return `${userPrompt}`;
2023-11-04 00:16:02 +00:00
}
};
2024-03-26 08:45:25 +00:00
const setChatTitle = async (_chatId, _title) => {
if (_chatId === $chatId) {
title = _title;
}
if ($settings.saveChatHistory ?? true) {
chat = await updateChatById(localStorage.token, _chatId, { title: _title });
await chats.set(await getChatList(localStorage.token));
}
};
2024-01-18 10:10:07 +00:00
const getTags = async () => {
return await getTagsById(localStorage.token, $chatId).catch(async (error) => {
return [];
});
};
const addTag = async (tagName) => {
const res = await addTagById(localStorage.token, $chatId, tagName);
tags = await getTags();
2024-01-18 10:17:31 +00:00
chat = await updateChatById(localStorage.token, $chatId, {
tags: tags
});
2024-01-18 10:55:25 +00:00
_tags.set(await getAllChatTags(localStorage.token));
2024-01-18 10:10:07 +00:00
};
const deleteTag = async (tagName) => {
const res = await deleteTagById(localStorage.token, $chatId, tagName);
tags = await getTags();
2024-01-18 10:17:31 +00:00
chat = await updateChatById(localStorage.token, $chatId, {
tags: tags
});
2024-01-18 10:55:25 +00:00
_tags.set(await getAllChatTags(localStorage.token));
2024-01-18 10:10:07 +00:00
};
2023-10-08 22:38:42 +00:00
</script>
<svelte:head>
<title>
2024-03-02 06:35:08 +00:00
{title
? `${title.length > 30 ? `${title.slice(0, 30)}...` : title} | ${$WEBUI_NAME}`
: `${$WEBUI_NAME}`}
</title>
</svelte:head>
2024-02-16 21:23:11 +00:00
<div class="h-screen max-h-[100dvh] w-full flex flex-col">
2024-03-30 00:20:07 +00:00
<Navbar
{title}
bind:selectedModels
bind:showModelSelector
shareEnabled={messages.length > 0}
{initNewChat}
{tags}
{addTag}
{deleteTag}
/>
2024-02-16 00:20:46 +00:00
<div class="flex flex-col flex-auto">
<div
2024-02-16 04:18:05 +00:00
class=" pb-2.5 flex flex-col justify-between w-full flex-auto overflow-auto h-0"
2024-02-16 00:20:46 +00:00
id="messages-container"
2024-03-03 22:42:01 +00:00
bind:this={messagesContainerElement}
2024-02-16 00:20:46 +00:00
on:scroll={(e) => {
2024-03-03 22:42:01 +00:00
autoScroll =
messagesContainerElement.scrollHeight - messagesContainerElement.scrollTop <=
messagesContainerElement.clientHeight + 5;
2024-02-16 00:20:46 +00:00
}}
>
2024-03-30 00:20:07 +00:00
<div class=" h-full w-full flex flex-col pt-2 pb-4">
2024-02-15 22:43:10 +00:00
<Messages
chatId={$chatId}
{selectedModels}
{selectedModelfiles}
{processing}
bind:history
bind:messages
bind:autoScroll
bottomPadding={files.length > 0}
{sendPrompt}
{continueGeneration}
{regenerateResponse}
/>
</div>
2023-10-08 22:38:42 +00:00
</div>
2024-02-15 22:43:10 +00:00
<MessageInput
bind:files
bind:prompt
bind:autoScroll
suggestionPrompts={selectedModelfile?.suggestionPrompts ?? $config.default_prompt_suggestions}
{messages}
{submitPrompt}
{stopResponse}
/>
2023-11-20 01:47:07 +00:00
</div>
</div>