2023-10-08 22:38:42 +00:00
< script lang = "ts" >
2023-10-16 08:27:26 +00:00
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
2023-12-26 20:50:52 +00:00
import { onMount , tick } 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,
2024-03-01 20:18:17 +00:00
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
2024-01-18 03:19:44 +00:00
import { generateChatCompletion , cancelChatCompletion , generateTitle } 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';
2024-01-07 08:57:10 +00:00
import { generateOpenAIChatCompletion } 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';
2024-02-22 12:12:26 +00:00
import { LITELLM_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';
2023-11-20 01:47:07 +00:00
let stopResponseFlag = false;
let autoScroll = true;
2024-01-07 11:19:34 +00:00
let processing = '';
2023-10-08 22:38:42 +00:00
2024-01-18 03:19:44 +00:00
let currentRequestId = null;
2023-11-12 18:30:34 +00:00
let selectedModels = [''];
2023-12-26 20:50:52 +00:00
2023-12-03 19:54:11 +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 = [];
2023-10-13 00:45:11 +00:00
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
2023-10-16 08:27:26 +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 () => {
2024-01-18 03:42:40 +00:00
if (currentRequestId !== null) {
await cancelChatCompletion(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 = () => {
const element = document.getElementById('messages-container');
element.scrollTop = element.scrollHeight;
};
2023-10-13 00:45:11 +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('')) {
toast.error('Model not selected');
} 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(
`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 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: 'New Chat',
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
2024-01-07 10:14:17 +00:00
const docs = messages
.filter((message) => message?.files ?? null)
2024-02-03 23:57:06 +00:00
.map((message) =>
message.files.filter((item) => item.type === 'doc' || item.type === 'collection')
)
2024-01-07 10:14:17 +00:00
.flat(1);
2024-01-07 09:40:36 +00:00
console.log(docs);
2024-01-07 08:57:10 +00:00
if (docs.length > 0) {
2024-01-07 11:19:34 +00:00
processing = 'Reading';
2024-01-07 08:57:10 +00:00
const query = history.messages[parentId].content;
2024-02-03 06:57:18 +00:00
let relevantContexts = await Promise.all(
docs.map(async (doc) => {
2024-02-03 23:57:06 +00:00
if (doc.type === 'collection') {
return await queryCollection(localStorage.token, doc.collection_names, query, 4).catch(
(error) => {
console.log(error);
return null;
}
);
} else {
return await queryDoc(localStorage.token, doc.collection_name, query, 4).catch(
(error) => {
console.log(error);
return null;
}
);
}
2024-02-03 06:57:18 +00:00
})
);
relevantContexts = relevantContexts.filter((context) => context);
2024-02-01 21:35:41 +00:00
2024-02-03 06:57:18 +00:00
const contextString = relevantContexts.reduce((a, context, i, arr) => {
return `${ a } ${ context . documents . join ( ' ' )} \n`;
}, '');
2024-02-01 21:35:41 +00:00
2024-02-03 06:57:18 +00:00
console.log(contextString);
2024-02-01 21:35:41 +00:00
2024-02-18 06:41:03 +00:00
history.messages[parentId].raContent = await RAGTemplate(
localStorage.token,
contextString,
query
);
2024-02-03 06:57:18 +00:00
history.messages[parentId].contexts = relevantContexts;
2024-01-07 08:57:10 +00:00
await tick();
2024-01-07 11:19:34 +00:00
processing = '';
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-02-24 09:49:19 +00:00
toast.error(`Model ${ modelId } not found`);
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();
2023-11-02 02:29:50 +00:00
2024-02-04 08:29:40 +00:00
const messagesBody = [
$settings.system
? {
role: 'system',
content: $settings.system
}
: undefined,
2024-02-24 01:12:19 +00:00
...messages.filter((message) => !message.deleted)
2024-02-04 08:29:40 +00:00
]
.filter((message) => message)
.map((message, idx, arr) => ({
role: message.role,
content: arr.length - 2 !== idx ? message.content : message?.raContent ?? message.content,
...(message.files && {
images: message.files
.filter((file) => file.type === 'image')
.map((file) => file.url.slice(file.url.indexOf(',') + 1))
})
}));
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-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,
keep_alive: $settings.keepAlive ?? undefined
2024-01-04 21:06:31 +00:00
});
2023-12-11 06:47:16 +00:00
2023-12-13 21:05:31 +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');
await cancelChatCompletion(localStorage.token, currentRequestId);
}
currentRequestId = null;
2023-12-11 10:28:49 +00:00
break;
}
2023-11-02 02:29:50 +00:00
2023-12-11 10:28:49 +00:00
try {
let lines = value.split('\n');
2023-11-02 02:29:50 +00:00
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-11-02 02:29:50 +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-11-02 02:29:50 +00:00
}
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-11-02 02:29:50 +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));
}
2023-11-02 02:29:50 +00:00
}
2023-12-13 21:05:31 +00:00
} else {
if (res !== null) {
const error = await res.json();
2023-11-02 02:29:50 +00:00
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;
2023-12-13 21:05:31 +00:00
} 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
}
2023-12-13 21:05:31 +00:00
} else {
toast.error(`Uh-oh! There was an issue connecting to Ollama.`);
2023-12-13 23:31:07 +00:00
responseMessage.content = `Uh-oh! There was an issue connecting to Ollama.`;
2023-11-02 02:29:50 +00:00
}
2023-12-13 23:31:07 +00:00
responseMessage.error = true;
responseMessage.content = `Uh-oh! There was an issue connecting to Ollama.`;
responseMessage.done = true;
messages = messages;
2023-11-02 02:29:50 +00:00
}
stopResponseFlag = false;
await tick();
2023-12-26 20:50:52 +00:00
2023-11-02 02:29:50 +00:00
if (autoScroll) {
2024-02-16 00:20:46 +00:00
scrollToBottom();
2023-11-02 02:29:50 +00:00
}
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 } `);
await generateChatTitle(_chatId, userPrompt);
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];
2024-02-16 00:20:46 +00:00
scrollToBottom();
2023-11-04 00:16:02 +00:00
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-02-24 06:27:28 +00:00
...messages.filter((message) => !message.deleted)
2024-02-22 12:12:26 +00:00
]
.filter((message) => message)
.map((message, idx, arr) => ({
role: message.role,
...(message.files?.filter((file) => file.type === 'image').length > 0 ?? false
? {
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,
max_tokens: $settings?.options?.num_predict ?? undefined
},
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;
2023-12-23 04:09:50 +00:00
} 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;
}
2023-12-23 04:09:50 +00:00
}
}
}
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 {
toast.error(`Uh-oh! There was an issue connecting to ${ model } .`);
responseMessage.content = `Uh-oh! There was an issue connecting to ${ model } .`;
2023-11-04 00:16:02 +00:00
}
2024-01-05 03:20:49 +00:00
responseMessage.error = true;
responseMessage.content = `Uh-oh! There was an issue connecting to ${ model } .`;
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 } `);
await setChatTitle(_chatId, userPrompt);
2023-11-04 00:16:02 +00:00
}
2023-11-02 02:29:50 +00:00
};
2023-11-20 01:47:07 +00:00
const stopResponse = () => {
stopResponseFlag = true;
console.log('stopResponse');
};
2023-10-13 00:45:11 +00:00
const regenerateResponse = async () => {
2023-12-26 20:50:52 +00:00
console.log('regenerateResponse');
2023-10-13 00:45:11 +00:00
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
2023-11-02 02:29:50 +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
}
2023-11-02 02:29:50 +00:00
};
2023-10-13 00:45:11 +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 {
toast.error(`Model ${ modelId } not found`);
2024-02-15 09:23:02 +00:00
}
};
2023-11-04 00:16:02 +00:00
const generateChatTitle = async (_chatId, userPrompt) => {
2023-11-22 21:20:41 +00:00
if ($settings.titleAutoGenerate ?? true) {
2023-12-26 20:50:52 +00:00
const title = await generateTitle(
localStorage.token,
2024-02-21 20:51:52 +00:00
$settings?.titleGenerationPrompt ??
"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 }} ",
2024-01-03 01:08:35 +00:00
$settings?.titleAutoGenerateModel ?? selectedModels[0],
2023-12-26 20:50:52 +00:00
userPrompt
);
if (title) {
await setChatTitle(_chatId, title);
2023-11-22 21:20:41 +00:00
}
} else {
await setChatTitle(_chatId, `${ userPrompt } `);
2023-11-04 00:16:02 +00:00
}
};
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-11-04 00:16:02 +00:00
const setChatTitle = async (_chatId, _title) => {
2023-11-21 17:39:11 +00:00
if (_chatId === $chatId) {
2023-11-04 00:16:02 +00:00
title = _title;
2023-10-16 08:27:26 +00:00
}
2023-12-26 20:50:52 +00:00
2024-01-06 10:33:00 +00:00
if ($settings.saveChatHistory ?? true) {
chat = await updateChatById(localStorage.token, _chatId, { title : _title } );
await chats.set(await getChatList(localStorage.token));
}
2023-10-16 08:27:26 +00:00
};
2023-10-08 22:38:42 +00:00
< / script >
2024-03-01 20:18:17 +00:00
< svelte:head >
< title >
2024-03-02 06:35:08 +00:00
{ title
? `${ title . length > 30 ? `$ { title . slice ( 0 , 30 )}... ` : title } | ${ $WEBUI_NAME } `
: `${ $WEBUI_NAME } `}
2024-03-01 20:18:17 +00:00
< / title >
< / svelte:head >
2024-02-16 21:23:11 +00:00
< div class = "h-screen max-h-[100dvh] w-full flex flex-col" >
2024-02-15 22:43:10 +00:00
< Navbar { title } 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"
on:scroll={( e ) => {
autoScroll = e.target.scrollHeight - e.target.scrollTop < = e.target.clientHeight + 50;
}}
>
2024-02-15 22:43:10 +00:00
< div
class="{ $settings ? . fullScreenMode ?? null
? 'max-w-full'
: 'max-w-2xl md:px-0'} mx-auto w-full px-4"
>
2024-02-16 04:18:05 +00:00
< ModelSelector
bind:selectedModels
disabled={ messages . length > 0 && ! selectedModels . includes ( '' )}
/>
2024-02-15 22:43:10 +00:00
< / div >
2024-02-16 00:20:46 +00:00
< div class = " h-full w-full flex flex-col py-8" >
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 >
2023-10-12 04:43:42 +00:00
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 >