2024-05-21 17:30:31 +00:00
< script lang = "ts" >
import { v4 as uuidv4 } from 'uuid';
import { toast } from 'svelte-sonner';
2024-06-03 01:03:30 +00:00
import mermaid from 'mermaid';
2024-09-21 01:33:06 +00:00
import { PaneGroup , Pane , PaneResizer } from 'paneforge';
2024-05-21 17:30:31 +00:00
2024-08-26 00:00:49 +00:00
import { getContext , onDestroy , onMount , tick } from 'svelte';
2024-05-21 17:30:31 +00:00
import { goto } from '$app/navigation';
import { page } from '$app/stores';
2024-08-26 00:00:49 +00:00
import type { Unsubscriber , Writable } from 'svelte/store';
2024-06-09 21:25:31 +00:00
import type { i18n as i18nType } from 'i18next';
2024-08-26 00:00:49 +00:00
import { WEBUI_BASE_URL } from '$lib/constants';
2024-06-09 21:25:31 +00:00
2024-05-21 17:30:31 +00:00
import {
chatId,
chats,
config,
2024-05-21 18:17:23 +00:00
type Model,
2024-05-21 17:30:31 +00:00
models,
settings,
showSidebar,
2024-05-26 19:18:43 +00:00
WEBUI_NAME,
2024-05-31 18:11:28 +00:00
banners,
2024-06-04 18:13:43 +00:00
user,
2024-06-07 06:29:08 +00:00
socket,
2024-09-17 20:05:19 +00:00
showControls,
2024-06-11 07:37:31 +00:00
showCallOverlay,
2024-08-15 14:54:16 +00:00
currentChatPage,
2024-09-21 01:33:06 +00:00
temporaryChatEnabled,
2024-09-21 02:10:24 +00:00
mobile,
showOverview
2024-05-21 17:30:31 +00:00
} from '$lib/stores';
2024-05-31 18:11:28 +00:00
import {
convertMessagesToHistory,
copyToClipboard,
2024-08-26 13:01:29 +00:00
getMessageContentParts,
2024-06-14 03:15:23 +00:00
extractSentencesForAudio,
2024-05-31 18:11:28 +00:00
promptTemplate,
splitStream
} from '$lib/utils';
2024-05-21 17:30:31 +00:00
2024-06-02 17:06:12 +00:00
import { generateChatCompletion } from '$lib/apis/ollama';
2024-05-21 17:30:31 +00:00
import {
createNewChat,
getChatById,
getChatList,
getTagsById,
updateChatById
} from '$lib/apis/chats';
2024-06-09 21:53:10 +00:00
import { generateOpenAIChatCompletion } from '$lib/apis/openai';
2024-06-09 21:25:31 +00:00
import { runWebSearch } from '$lib/apis/rag';
import { createOpenAITextStream } from '$lib/apis/streaming';
import { queryMemory } from '$lib/apis/memories';
2024-06-16 22:32:26 +00:00
import { getAndUpdateUserLocation , getUserSettings } from '$lib/apis/users';
2024-08-18 18:59:59 +00:00
import {
chatCompleted,
generateTitle,
generateSearchQuery,
chatAction,
generateMoACompletion
} from '$lib/apis';
2024-05-21 17:30:31 +00:00
2024-06-09 21:25:31 +00:00
import Banner from '../common/Banner.svelte';
2024-05-21 17:30:31 +00:00
import MessageInput from '$lib/components/chat/MessageInput.svelte';
import Messages from '$lib/components/chat/Messages.svelte';
import Navbar from '$lib/components/layout/Navbar.svelte';
2024-07-08 23:55:12 +00:00
import ChatControls from './ChatControls.svelte';
2024-07-09 04:39:06 +00:00
import EventConfirmDialog from '../common/ConfirmDialog.svelte';
2024-09-21 01:33:06 +00:00
import EllipsisVertical from '../icons/EllipsisVertical.svelte';
2024-05-27 19:48:08 +00:00
2024-05-21 17:30:31 +00:00
const i18n: Writable< i18nType > = getContext('i18n');
export let chatIdProp = '';
let loaded = false;
2024-06-13 04:18:53 +00:00
const eventTarget = new EventTarget();
2024-09-21 01:33:06 +00:00
let controlPane;
2024-06-13 04:18:53 +00:00
2024-05-21 17:30:31 +00:00
let stopResponseFlag = false;
let autoScroll = true;
let processing = '';
let messagesContainerElement: HTMLDivElement;
2024-07-09 04:39:06 +00:00
let showEventConfirmation = false;
let eventConfirmationTitle = '';
let eventConfirmationMessage = '';
2024-07-12 00:30:24 +00:00
let eventConfirmationInput = false;
let eventConfirmationInputPlaceholder = '';
2024-07-22 19:43:31 +00:00
let eventConfirmationInputValue = '';
2024-07-09 04:39:06 +00:00
let eventCallback = null;
2024-05-21 17:30:31 +00:00
let showModelSelector = true;
let selectedModels = [''];
2024-05-21 18:17:23 +00:00
let atSelectedModel: Model | undefined;
2024-05-21 17:30:31 +00:00
2024-06-11 22:29:46 +00:00
let selectedModelIds = [];
$: selectedModelIds = atSelectedModel !== undefined ? [atSelectedModel.id] : selectedModels;
2024-06-11 07:18:45 +00:00
let selectedToolIds = [];
2024-05-27 20:22:24 +00:00
let webSearchEnabled = false;
2024-05-22 21:28:45 +00:00
2024-05-21 17:30:31 +00:00
let chat = null;
let tags = [];
let title = '';
let prompt = '';
2024-07-17 09:39:37 +00:00
let chatFiles = [];
2024-05-21 17:30:31 +00:00
let files = [];
let messages = [];
let history = {
messages: {} ,
currentId: null
};
2024-07-09 02:26:31 +00:00
let params = {} ;
2024-08-26 00:00:49 +00:00
let chatIdUnsubscriber: Unsubscriber | undefined;
2024-05-21 17:30:31 +00:00
$: if (history.currentId !== null) {
let _messages = [];
let currentMessage = history.messages[history.currentId];
2024-09-19 03:15:06 +00:00
while (currentMessage) {
2024-05-21 17:30:31 +00:00
_messages.unshift({ ... currentMessage } );
currentMessage =
currentMessage.parentId !== null ? history.messages[currentMessage.parentId] : null;
}
2024-09-19 13:35:01 +00:00
// This is most likely causing the performance issue
2024-05-21 17:30:31 +00:00
messages = _messages;
} else {
messages = [];
}
$: if (chatIdProp) {
(async () => {
2024-06-14 20:02:07 +00:00
console.log(chatIdProp);
if (chatIdProp && (await loadChat())) {
2024-05-21 17:30:31 +00:00
await tick();
loaded = true;
window.setTimeout(() => scrollToBottom(), 0);
const chatInput = document.getElementById('chat-textarea');
chatInput?.focus();
} else {
await goto('/');
}
})();
}
2024-09-18 01:13:37 +00:00
const showMessage = async (message) => {
let _messageId = JSON.parse(JSON.stringify(message.id));
let messageChildrenIds = history.messages[_messageId].childrenIds;
while (messageChildrenIds.length !== 0) {
_messageId = messageChildrenIds.at(-1);
messageChildrenIds = history.messages[_messageId].childrenIds;
}
history.currentId = _messageId;
await tick();
await tick();
await tick();
const messageElement = document.getElementById(`message-${ message . id } `);
if (messageElement) {
2024-09-18 01:19:32 +00:00
messageElement.scrollIntoView({ behavior : 'smooth' } );
2024-09-18 01:13:37 +00:00
}
};
2024-07-09 04:39:06 +00:00
const chatEventHandler = async (event, cb) => {
2024-07-06 04:20:27 +00:00
if (event.chat_id === $chatId) {
2024-07-02 03:53:24 +00:00
await tick();
2024-07-06 04:20:27 +00:00
console.log(event);
let message = history.messages[event.message_id];
const type = event?.data?.type ?? null;
const data = event?.data?.data ?? null;
if (type === 'status') {
2024-07-09 04:39:06 +00:00
if (message?.statusHistory) {
2024-07-06 04:20:27 +00:00
message.statusHistory.push(data);
2024-07-03 17:18:33 +00:00
} else {
2024-07-06 04:20:27 +00:00
message.statusHistory = [data];
2024-07-03 17:18:33 +00:00
}
2024-07-06 04:20:27 +00:00
} else if (type === 'citation') {
2024-07-09 04:39:06 +00:00
if (message?.citations) {
2024-07-06 04:20:27 +00:00
message.citations.push(data);
2024-07-03 17:18:33 +00:00
} else {
2024-07-06 04:20:27 +00:00
message.citations = [data];
2024-07-03 17:18:33 +00:00
}
2024-07-11 18:00:42 +00:00
} else if (type === 'message') {
message.content += data.content;
2024-07-15 08:58:40 +00:00
} else if (type === 'replace') {
message.content = data.content;
2024-08-15 21:55:31 +00:00
} else if (type === 'action') {
if (data.action === 'continue') {
const continueButton = document.getElementById('continue-response-button');
if (continueButton) {
continueButton.click();
}
}
2024-07-09 04:39:06 +00:00
} else if (type === 'confirmation') {
eventCallback = cb;
2024-07-12 00:30:24 +00:00
eventConfirmationInput = false;
showEventConfirmation = true;
eventConfirmationTitle = data.title;
eventConfirmationMessage = data.message;
} else if (type === 'input') {
eventCallback = cb;
eventConfirmationInput = true;
2024-07-09 04:39:06 +00:00
showEventConfirmation = true;
eventConfirmationTitle = data.title;
eventConfirmationMessage = data.message;
2024-07-12 00:30:24 +00:00
eventConfirmationInputPlaceholder = data.placeholder;
2024-07-22 19:43:31 +00:00
eventConfirmationInputValue = data?.value ?? '';
2024-07-02 03:53:24 +00:00
} else {
2024-07-06 04:20:27 +00:00
console.log('Unknown message type', data);
2024-07-02 03:53:24 +00:00
}
messages = messages;
}
};
2024-08-26 00:00:49 +00:00
const onMessageHandler = async (event: {
origin: string;
data: { type : string ; text : string } ;
}) => {
if (event.origin !== window.origin) {
return;
}
2024-06-24 06:10:26 +00:00
2024-08-26 00:00:49 +00:00
// Replace with your iframe's origin
if (event.data.type === 'input:prompt') {
console.debug(event.data.text);
2024-06-24 06:10:26 +00:00
2024-08-26 00:00:49 +00:00
const inputElement = document.getElementById('chat-textarea');
2024-06-24 06:10:26 +00:00
2024-08-26 00:00:49 +00:00
if (inputElement) {
prompt = event.data.text;
inputElement.focus();
}
}
2024-06-24 06:10:26 +00:00
2024-08-26 00:00:49 +00:00
if (event.data.type === 'action:submit') {
console.debug(event.data.text);
if (prompt !== '') {
await tick();
submitPrompt(prompt);
2024-06-24 06:10:26 +00:00
}
2024-08-26 00:00:49 +00:00
}
if (event.data.type === 'input:prompt:submit') {
console.debug(event.data.text);
if (prompt !== '') {
await tick();
submitPrompt(event.data.text);
}
}
};
2024-06-24 06:10:26 +00:00
2024-08-26 00:00:49 +00:00
onMount(async () => {
window.addEventListener('message', onMessageHandler);
$socket?.on('chat-events', chatEventHandler);
2024-07-02 03:05:02 +00:00
2024-05-22 00:42:39 +00:00
if (!$chatId) {
2024-08-26 00:00:49 +00:00
chatIdUnsubscriber = chatId.subscribe(async (value) => {
2024-06-14 20:02:07 +00:00
if (!value) {
await initNewChat();
}
});
2024-05-21 17:30:31 +00:00
} else {
2024-08-15 14:54:16 +00:00
if ($temporaryChatEnabled) {
2024-05-21 17:30:31 +00:00
await goto('/');
}
}
2024-09-21 01:44:44 +00:00
showControls.subscribe(async (value) => {
2024-09-21 02:04:34 +00:00
if (controlPane && !$mobile) {
2024-09-21 01:44:44 +00:00
if (value) {
controlPane.resize(parseInt(localStorage.getItem('chat-controls-size') || '35'));
} else {
controlPane.resize(0);
}
}
2024-09-21 02:10:24 +00:00
if (!value) {
showCallOverlay.set(false);
showOverview.set(false);
}
2024-09-21 01:44:44 +00:00
});
2024-08-26 00:00:49 +00:00
});
2024-06-24 06:15:24 +00:00
2024-08-26 00:00:49 +00:00
onDestroy(() => {
chatIdUnsubscriber?.();
window.removeEventListener('message', onMessageHandler);
$socket?.off('chat-events');
2024-05-21 17:30:31 +00:00
});
//////////////////////////
// Web functions
//////////////////////////
const initNewChat = async () => {
2024-08-21 16:55:12 +00:00
if ($page.url.pathname.includes('/c/')) {
window.history.replaceState(history.state, '', `/`);
}
2024-05-21 17:30:31 +00:00
2024-08-21 16:55:12 +00:00
await chatId.set('');
2024-05-21 17:30:31 +00:00
autoScroll = true;
title = '';
messages = [];
history = {
messages: {} ,
currentId: null
};
2024-07-17 15:00:43 +00:00
chatFiles = [];
2024-07-09 02:26:31 +00:00
params = {} ;
2024-05-21 17:30:31 +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) {
2024-05-27 06:04:54 +00:00
console.log($config?.default_models.split(',') ?? '');
2024-05-21 17:30:31 +00:00
selectedModels = $config?.default_models.split(',');
} else {
selectedModels = [''];
}
2024-09-03 13:15:46 +00:00
if ($page.url.searchParams.get('web-search') === 'true') {
webSearchEnabled = true;
}
2024-05-21 17:30:31 +00:00
if ($page.url.searchParams.get('q')) {
prompt = $page.url.searchParams.get('q') ?? '';
2024-08-02 16:32:51 +00:00
selectedToolIds = ($page.url.searchParams.get('tool_ids') ?? '')
.split(',')
.map((id) => id.trim())
.filter((id) => id);
2024-05-23 06:34:29 +00:00
2024-05-21 17:30:31 +00:00
if (prompt) {
await tick();
submitPrompt(prompt);
}
}
2024-08-22 15:17:32 +00:00
if ($page.url.searchParams.get('call') === 'true') {
showCallOverlay.set(true);
}
2024-05-21 17:30:31 +00:00
selectedModels = selectedModels.map((modelId) =>
$models.map((m) => m.id).includes(modelId) ? modelId : ''
);
2024-05-27 05:47:42 +00:00
const userSettings = await getUserSettings(localStorage.token);
if (userSettings) {
settings.set(userSettings.ui);
} else {
settings.set(JSON.parse(localStorage.getItem('settings') ?? '{} '));
}
2024-05-21 17:30:31 +00:00
const chatInput = document.getElementById('chat-textarea');
setTimeout(() => chatInput?.focus(), 0);
};
const loadChat = async () => {
chatId.set(chatIdProp);
chat = await getChatById(localStorage.token, $chatId).catch(async (error) => {
await goto('/');
return null;
});
if (chat) {
tags = await getTags();
const chatContent = chat.chat;
if (chatContent) {
console.log(chatContent);
selectedModels =
(chatContent?.models ?? undefined) !== undefined
? chatContent.models
: [chatContent.models ?? ''];
history =
(chatContent?.history ?? undefined) !== undefined
? chatContent.history
: convertMessagesToHistory(chatContent.messages);
title = chatContent.title;
2024-05-27 05:47:42 +00:00
const userSettings = await getUserSettings(localStorage.token);
if (userSettings) {
await settings.set(userSettings.ui);
} else {
await settings.set(JSON.parse(localStorage.getItem('settings') ?? '{} '));
}
2024-07-09 02:26:31 +00:00
params = chatContent?.params ?? {} ;
2024-07-17 11:15:57 +00:00
chatFiles = chatContent?.files ?? [];
2024-05-27 06:04:54 +00:00
2024-05-21 17:30:31 +00:00
autoScroll = true;
await tick();
if (messages.length > 0) {
history.messages[messages.at(-1).id].done = true;
}
await tick();
return true;
} else {
return null;
}
}
};
const scrollToBottom = async () => {
await tick();
if (messagesContainerElement) {
messagesContainerElement.scrollTop = messagesContainerElement.scrollHeight;
}
};
2024-05-30 09:37:43 +00:00
const createMessagesList = (responseMessageId) => {
const message = history.messages[responseMessageId];
if (message.parentId) {
return [...createMessagesList(message.parentId), message];
} else {
return [message];
}
};
2024-07-12 02:05:59 +00:00
const chatCompletedHandler = async (chatId, modelId, responseMessageId, messages) => {
2024-06-03 01:03:30 +00:00
await mermaid.run({
querySelector: '.mermaid'
});
const res = await chatCompleted(localStorage.token, {
2024-06-03 02:02:46 +00:00
model: modelId,
2024-06-03 01:03:30 +00:00
messages: messages.map((m) => ({
id: m.id,
role: m.role,
content: m.content,
2024-06-17 08:31:22 +00:00
info: m.info ? m.info : undefined,
2024-06-03 01:03:30 +00:00
timestamp: m.timestamp
})),
2024-07-12 02:05:59 +00:00
chat_id: chatId,
2024-07-02 04:41:44 +00:00
session_id: $socket?.id,
id: responseMessageId
2024-06-03 01:03:30 +00:00
}).catch((error) => {
2024-06-20 10:23:50 +00:00
toast.error(error);
messages.at(-1).error = { content : error } ;
2024-06-03 01:03:30 +00:00
return null;
});
if (res !== null) {
// Update chat history with the new messages
for (const message of res.messages) {
history.messages[message.id] = {
...history.messages[message.id],
...(history.messages[message.id].content !== message.content
? { originalContent : history.messages [ message . id ]. content }
: {} ),
...message
};
}
}
2024-07-12 02:05:59 +00:00
if ($chatId == chatId) {
2024-08-15 14:54:16 +00:00
if (!$temporaryChatEnabled) {
2024-07-12 02:05:59 +00:00
chat = await updateChatById(localStorage.token, chatId, {
models: selectedModels,
messages: messages,
history: history,
2024-07-17 09:39:37 +00:00
params: params,
files: chatFiles
2024-07-12 02:05:59 +00:00
});
2024-08-04 14:58:08 +00:00
2024-08-04 15:04:15 +00:00
currentChatPage.set(1);
2024-08-04 14:58:08 +00:00
await chats.set(await getChatList(localStorage.token, $currentChatPage));
2024-07-12 02:05:59 +00:00
}
}
2024-06-03 01:03:30 +00:00
};
2024-08-15 15:28:43 +00:00
const chatActionHandler = async (chatId, actionId, modelId, responseMessageId, event = null) => {
2024-07-12 01:47:38 +00:00
const res = await chatAction(localStorage.token, actionId, {
model: modelId,
messages: messages.map((m) => ({
id: m.id,
role: m.role,
content: m.content,
info: m.info ? m.info : undefined,
timestamp: m.timestamp
})),
2024-08-15 15:28:43 +00:00
...(event ? { event : event } : {} ),
2024-07-12 02:05:59 +00:00
chat_id: chatId,
2024-07-12 01:47:38 +00:00
session_id: $socket?.id,
id: responseMessageId
}).catch((error) => {
toast.error(error);
messages.at(-1).error = { content : error } ;
return null;
});
if (res !== null) {
// Update chat history with the new messages
for (const message of res.messages) {
history.messages[message.id] = {
...history.messages[message.id],
...(history.messages[message.id].content !== message.content
? { originalContent : history.messages [ message . id ]. content }
: {} ),
...message
};
}
}
2024-07-12 02:05:59 +00:00
if ($chatId == chatId) {
2024-08-15 14:54:16 +00:00
if (!$temporaryChatEnabled) {
2024-07-12 02:05:59 +00:00
chat = await updateChatById(localStorage.token, chatId, {
models: selectedModels,
messages: messages,
history: history,
2024-07-17 09:39:37 +00:00
params: params,
files: chatFiles
2024-07-12 02:05:59 +00:00
});
2024-08-04 14:58:08 +00:00
2024-08-04 15:04:15 +00:00
currentChatPage.set(1);
2024-08-04 14:58:08 +00:00
await chats.set(await getChatList(localStorage.token, $currentChatPage));
2024-07-12 02:05:59 +00:00
}
}
2024-07-12 01:47:38 +00:00
};
2024-06-04 18:13:43 +00:00
const getChatEventEmitter = async (modelId: string, chatId: string = '') => {
return setInterval(() => {
$socket?.emit('usage', {
action: 'chat',
model: modelId,
chat_id: chatId
});
}, 1000);
};
2024-05-21 17:30:31 +00:00
//////////////////////////
2024-06-09 08:22:21 +00:00
// Chat functions
2024-05-21 17:30:31 +00:00
//////////////////////////
2024-06-13 04:18:53 +00:00
const submitPrompt = async (userPrompt, { _raw = false } = {} ) => {
2024-06-07 07:04:47 +00:00
let _responses = [];
2024-05-21 17:30:31 +00:00
console.log('submitPrompt', $chatId);
selectedModels = selectedModels.map((modelId) =>
$models.map((m) => m.id).includes(modelId) ? modelId : ''
);
if (selectedModels.includes('')) {
toast.error($i18n.t('Model not selected'));
} else if (messages.length != 0 && messages.at(-1).done != true) {
// Response not done
console.log('wait');
2024-06-20 09:47:27 +00:00
} else if (messages.length != 0 && messages.at(-1).error) {
// Error in response
toast.error(
$i18n.t(
`Oops! There was an error in the previous response. Please try again or contact admin.`
)
);
2024-06-19 20:31:01 +00:00
} else if (
files.length > 0 & &
files.filter((file) => file.type !== 'image' & & file.status !== 'processed').length > 0
) {
2024-05-21 17:30:31 +00:00
// Upload not done
toast.error(
$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-08-27 15:05:24 +00:00
} else if (
($config?.file?.max_count ?? null) !== null & &
files.length + chatFiles.length > $config?.file?.max_count
) {
console.log(chatFiles.length, files.length);
toast.error(
$i18n.t(`You can only chat with a maximum of {{ maxCount }} file(s) at a time.`, {
maxCount: $config?.file?.max_count
})
);
2024-05-21 17:30:31 +00:00
} else {
2024-06-10 00:20:23 +00:00
// Reset chat input textarea
const chatTextAreaElement = document.getElementById('chat-textarea');
if (chatTextAreaElement) {
chatTextAreaElement.value = '';
chatTextAreaElement.style.height = '';
}
2024-06-10 07:07:47 +00:00
const _files = JSON.parse(JSON.stringify(files));
2024-07-17 09:39:37 +00:00
chatFiles.push(..._files.filter((item) => ['doc', 'file', 'collection'].includes(item.type)));
chatFiles = chatFiles.filter(
// Remove duplicates
(item, index, array) =>
array.findIndex((i) => JSON.stringify(i) === JSON.stringify(item)) === index
);
2024-06-10 07:07:47 +00:00
files = [];
2024-06-10 00:20:23 +00:00
prompt = '';
2024-05-21 17:30:31 +00:00
// Create user message
let userMessageId = uuidv4();
let userMessage = {
id: userMessageId,
parentId: messages.length !== 0 ? messages.at(-1).id : null,
childrenIds: [],
role: 'user',
content: userPrompt,
2024-06-10 07:07:47 +00:00
files: _files.length > 0 ? _files : undefined,
2024-05-21 17:30:31 +00:00
timestamp: Math.floor(Date.now() / 1000), // Unix epoch
2024-08-16 16:54:30 +00:00
models: selectedModels
2024-05-21 17:30:31 +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();
2024-06-13 04:18:53 +00:00
_responses = await sendPrompt(userPrompt, userMessageId, { newChat : true } );
2024-05-21 17:30:31 +00:00
}
2024-06-07 07:04:47 +00:00
return _responses;
2024-05-21 17:30:31 +00:00
};
2024-08-16 16:54:30 +00:00
const sendPrompt = async (
2024-08-26 00:00:49 +00:00
prompt: string,
parentId: string,
2024-08-16 16:54:30 +00:00
{ modelId = null , modelIdx = null , newChat = false } = {}
) => {
2024-08-26 00:00:49 +00:00
let _responses: string[] = [];
2024-06-10 07:56:13 +00:00
// If modelId is provided, use it, else use selected model
let selectedModelIds = modelId
? [modelId]
: atSelectedModel !== undefined
2024-08-22 14:31:33 +00:00
? [atSelectedModel.id]
: selectedModels;
2024-06-10 07:56:13 +00:00
// Create response messages for each selected model
2024-08-26 00:00:49 +00:00
const responseMessageIds: Record< PropertyKey , string > = {} ;
2024-08-16 16:54:30 +00:00
for (const [_modelIdx, modelId] of selectedModelIds.entries()) {
2024-06-10 07:56:13 +00:00
const model = $models.filter((m) => m.id === modelId).at(0);
if (model) {
let responseMessageId = uuidv4();
let responseMessage = {
parentId: parentId,
id: responseMessageId,
childrenIds: [],
role: 'assistant',
content: '',
model: model.id,
modelName: model.name ?? model.id,
2024-08-16 16:54:30 +00:00
modelIdx: modelIdx ? modelIdx : _modelIdx,
2024-06-10 07:56:13 +00:00
userContext: null,
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-08-16 16:54:30 +00:00
responseMessageIds[`${ modelId } -${ modelIdx ? modelIdx : _modelIdx } `] = responseMessageId;
2024-06-10 07:56:13 +00:00
}
}
await tick();
// Create new chat if only one message in messages
2024-06-11 00:58:07 +00:00
if (newChat && messages.length == 2) {
2024-08-15 14:54:16 +00:00
if (!$temporaryChatEnabled) {
2024-06-10 07:56:13 +00:00
chat = await createNewChat(localStorage.token, {
id: $chatId,
title: $i18n.t('New Chat'),
models: selectedModels,
system: $settings.system ?? undefined,
2024-07-09 02:26:31 +00:00
params: params,
2024-06-10 07:56:13 +00:00
messages: messages,
history: history,
tags: [],
timestamp: Date.now()
});
2024-08-04 14:58:08 +00:00
2024-08-04 15:04:15 +00:00
currentChatPage.set(1);
2024-08-04 14:58:08 +00:00
await chats.set(await getChatList(localStorage.token, $currentChatPage));
2024-06-10 07:56:13 +00:00
await chatId.set(chat.id);
} else {
await chatId.set('local');
}
await tick();
}
2024-05-21 17:30:31 +00:00
const _chatId = JSON.parse(JSON.stringify($chatId));
await Promise.all(
2024-08-16 16:54:30 +00:00
selectedModelIds.map(async (modelId, _modelIdx) => {
2024-05-21 18:17:23 +00:00
console.log('modelId', modelId);
const model = $models.filter((m) => m.id === modelId).at(0);
if (model) {
// If there are image files, check if model is vision capable
const hasImages = messages.some((message) =>
message.files?.some((file) => file.type === 'image')
);
2024-05-21 17:30:31 +00:00
2024-05-25 07:44:21 +00:00
if (hasImages && !(model.info?.meta?.capabilities?.vision ?? true)) {
2024-05-21 18:17:23 +00:00
toast.error(
$i18n.t('Model {{ modelName }} is not vision capable', {
2024-05-25 07:44:21 +00:00
modelName: model.name ?? model.id
2024-05-21 18:17:23 +00:00
})
);
}
2024-05-21 17:30:31 +00:00
2024-08-16 16:54:30 +00:00
let responseMessageId =
responseMessageIds[`${ modelId } -${ modelIdx ? modelIdx : _modelIdx } `];
2024-06-10 07:56:13 +00:00
let responseMessage = history.messages[responseMessageId];
2024-05-21 18:17:23 +00:00
let userContext = null;
if ($settings?.memory ?? false) {
if (userContext === null) {
const res = await queryMemory(localStorage.token, prompt).catch((error) => {
toast.error(error);
return null;
});
if (res) {
if (res.documents[0].length > 0) {
2024-06-24 21:00:08 +00:00
userContext = res.documents[0].reduce((acc, doc, index) => {
const createdAtTimestamp = res.metadatas[0][index].created_at;
2024-05-21 18:17:23 +00:00
const createdAtDate = new Date(createdAtTimestamp * 1000)
.toISOString()
.split('T')[0];
2024-06-24 22:21:42 +00:00
return `${ acc } ${ index + 1 } . [${ createdAtDate } ]. ${ doc } \n`;
}, '');
2024-05-21 17:30:31 +00:00
}
2024-05-21 18:17:23 +00:00
console.log(userContext);
2024-05-21 17:30:31 +00:00
}
}
2024-05-21 18:17:23 +00:00
}
responseMessage.userContext = userContext;
2024-05-21 17:30:31 +00:00
2024-06-04 18:13:43 +00:00
const chatEventEmitter = await getChatEventEmitter(model.id, _chatId);
2024-09-07 03:50:29 +00:00
scrollToBottom();
2024-05-27 20:22:24 +00:00
if (webSearchEnabled) {
2024-05-27 21:25:36 +00:00
await getWebSearchResults(model.id, parentId, responseMessageId);
2024-05-25 13:49:49 +00:00
}
2024-05-22 21:28:45 +00:00
2024-06-07 07:04:47 +00:00
let _response = null;
2024-05-24 10:02:56 +00:00
if (model?.owned_by === 'openai') {
2024-06-07 07:04:47 +00:00
_response = await sendPromptOpenAI(model, prompt, responseMessageId, _chatId);
2024-05-21 18:17:23 +00:00
} else if (model) {
2024-06-07 07:04:47 +00:00
_response = await sendPromptOllama(model, prompt, responseMessageId, _chatId);
2024-05-21 17:30:31 +00:00
}
2024-06-07 07:04:47 +00:00
_responses.push(_response);
2024-06-04 18:13:43 +00:00
if (chatEventEmitter) clearInterval(chatEventEmitter);
2024-05-21 18:17:23 +00:00
} else {
toast.error($i18n.t(`Model {{ modelId }} not found`, { modelId } ));
2024-05-21 17:30:31 +00:00
}
2024-05-21 18:17:23 +00:00
})
2024-05-21 17:30:31 +00:00
);
2024-08-04 15:04:15 +00:00
currentChatPage.set(1);
2024-08-26 00:00:49 +00:00
chats.set(await getChatList(localStorage.token, $currentChatPage));
2024-08-01 19:20:36 +00:00
2024-06-07 07:04:47 +00:00
return _responses;
2024-05-21 17:30:31 +00:00
};
const sendPromptOllama = async (model, userPrompt, responseMessageId, _chatId) => {
2024-08-26 00:00:49 +00:00
let _response: string | null = null;
2024-06-07 07:04:47 +00:00
2024-05-21 17:30:31 +00:00
const responseMessage = history.messages[responseMessageId];
2024-07-17 20:01:39 +00:00
const userMessage = history.messages[responseMessage.parentId];
2024-05-21 17:30:31 +00:00
// Wait until history/message have been updated
await tick();
// Scroll down
scrollToBottom();
const messagesBody = [
2024-07-09 02:26:31 +00:00
params?.system || $settings.system || (responseMessage?.userContext ?? null)
2024-05-21 17:30:31 +00:00
? {
role: 'system',
2024-06-16 22:32:26 +00:00
content: `${ promptTemplate (
2024-07-09 02:26:31 +00:00
params?.system ?? $settings?.system ?? '',
2024-06-16 22:32:26 +00:00
$user.name,
$settings?.userLocation
? await getAndUpdateUserLocation(localStorage.token)
: undefined
)}${
2024-08-22 14:31:33 +00:00
(responseMessage?.userContext ?? null)
2024-06-24 22:32:49 +00:00
? `\n\nUser Context:\n${ responseMessage ? . userContext ?? '' } `
2024-05-21 17:30:31 +00:00
: ''
}`
2024-08-22 14:31:33 +00:00
}
2024-05-21 17:30:31 +00:00
: undefined,
...messages
]
2024-05-22 01:35:59 +00:00
.filter((message) => message?.content?.trim())
2024-08-26 00:00:49 +00:00
.map((message) => {
2024-05-21 17:30:31 +00:00
// Prepare the base message object
const baseMessage = {
role: message.role,
2024-05-25 05:21:57 +00:00
content: message.content
2024-05-21 17:30:31 +00:00
};
// 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
if (imageUrls && imageUrls.length > 0 && message.role === 'user') {
baseMessage.images = imageUrls;
}
return baseMessage;
});
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-07-17 09:39:37 +00:00
let files = JSON.parse(JSON.stringify(chatFiles));
2024-06-10 01:59:45 +00:00
if (model?.info?.meta?.knowledge ?? false) {
2024-08-22 12:12:18 +00:00
// Only initialize and add status if knowledge exists
responseMessage.statusHistory = [
{
2024-08-22 14:31:33 +00:00
action: 'knowledge_search',
description: $i18n.t(`Searching Knowledge for "{{ searchQuery }} "`, {
2024-08-22 12:12:18 +00:00
searchQuery: userMessage.content
2024-08-22 14:31:33 +00:00
}),
done: false
2024-08-22 12:12:18 +00:00
}
];
2024-07-17 09:39:37 +00:00
files.push(...model.info.meta.knowledge);
2024-08-22 12:12:18 +00:00
messages = messages; // Trigger Svelte update
2024-06-10 00:34:42 +00:00
}
2024-07-17 20:01:39 +00:00
files.push(
...(userMessage?.files ?? []).filter((item) =>
['doc', 'file', 'collection'].includes(item.type)
),
...(responseMessage?.files ?? []).filter((item) => ['web_search_results'].includes(item.type))
);
2024-05-21 17:30:31 +00:00
2024-08-22 12:12:18 +00:00
scrollToBottom();
2024-06-14 03:15:23 +00:00
eventTarget.dispatchEvent(
new CustomEvent('chat:start', {
detail: {
id: responseMessageId
}
})
);
await tick();
2024-06-13 04:18:53 +00:00
2024-09-19 14:25:59 +00:00
const stream = $settings?.streamResponse ?? true;
2024-05-21 17:30:31 +00:00
const [res, controller] = await generateChatCompletion(localStorage.token, {
2024-09-19 14:25:59 +00:00
stream: stream,
2024-06-10 00:34:42 +00:00
model: model.id,
2024-05-21 17:30:31 +00:00
messages: messagesBody,
options: {
2024-09-03 13:43:26 +00:00
...{ ...( $settings ? . params ?? {}), ... params } ,
2024-05-21 17:30:31 +00:00
stop:
2024-08-22 14:31:33 +00:00
(params?.stop ?? $settings?.params?.stop ?? undefined)
2024-08-04 12:27:18 +00:00
? (params?.stop.split(',').map((token) => token.trim()) ?? $settings.params.stop).map(
(str) => decodeURIComponent(JSON.parse('"' + str.replace(/\"/g, '\\"') + '"'))
2024-08-22 14:31:33 +00:00
)
2024-05-25 07:58:20 +00:00
: undefined,
2024-07-09 02:26:31 +00:00
num_predict: params?.max_tokens ?? $settings?.params?.max_tokens ?? undefined,
repeat_penalty:
params?.frequency_penalty ?? $settings?.params?.frequency_penalty ?? undefined
2024-05-21 17:30:31 +00:00
},
format: $settings.requestFormat ?? undefined,
keep_alive: $settings.keepAlive ?? undefined,
2024-06-11 07:18:45 +00:00
tool_ids: selectedToolIds.length > 0 ? selectedToolIds : undefined,
2024-06-18 21:37:12 +00:00
files: files.length > 0 ? files : undefined,
2024-07-02 03:05:02 +00:00
session_id: $socket?.id,
2024-07-02 02:33:58 +00:00
chat_id: $chatId,
id: responseMessageId
2024-05-21 17:30:31 +00:00
});
if (res && res.ok) {
2024-09-19 14:25:59 +00:00
if (!stream) {
const response = await res.json();
console.log(response);
responseMessage.content = response.message.content;
responseMessage.info = {
eval_count: response.eval_count,
eval_duration: response.eval_duration,
load_duration: response.load_duration,
prompt_eval_count: response.prompt_eval_count,
prompt_eval_duration: response.prompt_eval_duration,
total_duration: response.total_duration
};
responseMessage.done = true;
} else {
console.log('controller', controller);
2024-05-21 17:30:31 +00:00
2024-09-19 14:25:59 +00:00
const reader = res.body
.pipeThrough(new TextDecoderStream())
.pipeThrough(splitStream('\n'))
.getReader();
2024-05-21 17:30:31 +00:00
2024-09-19 14:25:59 +00:00
while (true) {
const { value , done } = await reader.read();
if (done || stopResponseFlag || _chatId !== $chatId) {
responseMessage.done = true;
messages = messages;
if (stopResponseFlag) {
controller.abort('User: Stop Response');
}
2024-05-21 17:30:31 +00:00
2024-09-19 14:25:59 +00:00
_response = responseMessage.content;
break;
2024-05-21 17:30:31 +00:00
}
2024-09-19 14:25:59 +00:00
try {
let lines = value.split('\n');
for (const line of lines) {
if (line !== '') {
console.log(line);
let data = JSON.parse(line);
2024-05-21 17:30:31 +00:00
2024-09-19 14:25:59 +00:00
if ('citations' in data) {
responseMessage.citations = data.citations;
// Only remove status if it was initially set
if (model?.info?.meta?.knowledge ?? false) {
responseMessage.statusHistory = responseMessage.statusHistory.filter(
(status) => status.action !== 'knowledge_search'
);
}
continue;
2024-08-22 12:12:18 +00:00
}
2024-05-21 17:30:31 +00:00
2024-09-19 14:25:59 +00:00
if ('detail' in data) {
throw data;
}
2024-05-21 17:30:31 +00:00
2024-09-19 14:25:59 +00:00
if (data.done == false) {
if (responseMessage.content == '' && data.message.content == '\n') {
continue;
} else {
responseMessage.content += data.message.content;
2024-06-14 03:15:23 +00:00
2024-09-19 14:25:59 +00:00
if (navigator.vibrate && ($settings?.hapticFeedback ?? false)) {
navigator.vibrate(5);
}
2024-08-14 15:05:43 +00:00
2024-09-19 14:25:59 +00:00
const messageContentParts = getMessageContentParts(
responseMessage.content,
$config?.audio?.tts?.split_on ?? 'punctuation'
2024-06-14 03:15:23 +00:00
);
2024-09-19 14:25:59 +00:00
messageContentParts.pop();
// dispatch only last sentence and make sure it hasn't been dispatched before
if (
messageContentParts.length > 0 & &
messageContentParts[messageContentParts.length - 1] !==
responseMessage.lastSentence
) {
responseMessage.lastSentence =
messageContentParts[messageContentParts.length - 1];
eventTarget.dispatchEvent(
new CustomEvent('chat', {
detail: {
id: responseMessageId,
content: messageContentParts[messageContentParts.length - 1]
}
})
);
}
messages = messages;
2024-06-14 03:15:23 +00:00
}
2024-09-19 14:25:59 +00:00
} else {
responseMessage.done = true;
2024-06-14 03:15:23 +00:00
2024-09-19 14:25:59 +00:00
if (responseMessage.content == '') {
responseMessage.error = {
code: 400,
content: `Oops! No text generated from Ollama, Please try again.`
};
}
2024-06-02 17:06:12 +00:00
2024-09-19 14:25:59 +00:00
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
2024-06-02 17:06:12 +00:00
};
2024-09-19 14:25:59 +00:00
messages = messages;
2024-06-02 17:06:12 +00:00
2024-09-19 14:25:59 +00:00
if ($settings.notificationEnabled && !document.hasFocus()) {
const notification = new Notification(`${ model . id } `, {
body: responseMessage.content,
icon: `${ WEBUI_BASE_URL } /static/favicon.png`
});
}
2024-06-02 17:06:12 +00:00
2024-09-19 14:25:59 +00:00
if ($settings?.responseAutoCopy ?? false) {
copyToClipboard(responseMessage.content);
}
2024-05-21 17:30:31 +00:00
2024-09-19 14:25:59 +00:00
if ($settings.responseAutoPlayback && !$showCallOverlay) {
await tick();
document.getElementById(`speak-button-${ responseMessage . id } `)?.click();
}
2024-05-21 17:30:31 +00:00
}
}
}
2024-09-19 14:25:59 +00:00
} catch (error) {
console.log(error);
if ('detail' in error) {
toast.error(error.detail);
}
break;
2024-05-21 17:30:31 +00:00
}
2024-09-19 14:25:59 +00:00
if (autoScroll) {
scrollToBottom();
}
2024-05-21 17:30:31 +00:00
}
}
2024-09-19 14:25:59 +00:00
await chatCompletedHandler(
_chatId,
model.id,
responseMessageId,
createMessagesList(responseMessageId)
);
2024-05-21 17:30:31 +00:00
} else {
if (res !== null) {
const error = await res.json();
console.log(error);
if ('detail' in error) {
toast.error(error.detail);
2024-06-01 17:19:27 +00:00
responseMessage.error = { content : error.detail } ;
2024-05-21 17:30:31 +00:00
} else {
toast.error(error.error);
2024-06-01 17:19:27 +00:00
responseMessage.error = { content : error.error } ;
2024-05-21 17:30:31 +00:00
}
} else {
toast.error(
$i18n.t(`Uh-oh! There was an issue connecting to {{ provider }} .`, { provider : 'Ollama' } )
);
2024-06-01 17:19:27 +00:00
responseMessage.error = {
content: $i18n.t(`Uh-oh! There was an issue connecting to {{ provider }} .`, {
provider: 'Ollama'
})
};
2024-05-21 17:30:31 +00:00
}
responseMessage.done = true;
2024-08-27 09:24:05 +00:00
if (responseMessage.statusHistory) {
responseMessage.statusHistory = responseMessage.statusHistory.filter(
(status) => status.action !== 'knowledge_search'
);
}
2024-05-21 17:30:31 +00:00
messages = messages;
}
2024-09-03 13:24:58 +00:00
await saveChatHandler(_chatId);
2024-05-21 17:30:31 +00:00
stopResponseFlag = false;
await tick();
2024-06-14 03:15:23 +00:00
2024-08-26 13:01:29 +00:00
let lastMessageContentPart =
getMessageContentParts(
responseMessage.content,
$config?.audio?.tts?.split_on ?? 'punctuation'
)?.at(-1) ?? '';
if (lastMessageContentPart) {
2024-06-14 03:15:23 +00:00
eventTarget.dispatchEvent(
new CustomEvent('chat', {
2024-08-26 13:01:29 +00:00
detail: { id : responseMessageId , content : lastMessageContentPart }
2024-06-14 03:15:23 +00:00
})
);
}
2024-08-26 13:01:29 +00:00
2024-06-14 03:15:23 +00:00
eventTarget.dispatchEvent(
new CustomEvent('chat:finish', {
detail: {
id: responseMessageId,
content: responseMessage.content
}
})
);
2024-05-21 17:30:31 +00:00
if (autoScroll) {
scrollToBottom();
}
2024-07-16 12:00:09 +00:00
if (messages.length == 2 && messages.at(1).content !== '' && selectedModels[0] === model.id) {
2024-05-21 17:30:31 +00:00
window.history.replaceState(history.state, '', `/c/${ _chatId } `);
const _title = await generateChatTitle(userPrompt);
await setChatTitle(_chatId, _title);
}
2024-06-07 07:04:47 +00:00
return _response;
2024-05-21 17:30:31 +00:00
};
const sendPromptOpenAI = async (model, userPrompt, responseMessageId, _chatId) => {
2024-06-07 07:04:47 +00:00
let _response = null;
2024-07-17 20:01:39 +00:00
2024-05-21 17:30:31 +00:00
const responseMessage = history.messages[responseMessageId];
2024-07-17 20:01:39 +00:00
const userMessage = history.messages[responseMessage.parentId];
2024-05-21 17:30:31 +00:00
2024-07-17 09:39:37 +00:00
let files = JSON.parse(JSON.stringify(chatFiles));
2024-06-10 01:59:45 +00:00
if (model?.info?.meta?.knowledge ?? false) {
2024-08-22 12:12:18 +00:00
// Only initialize and add status if knowledge exists
responseMessage.statusHistory = [
{
2024-08-22 14:31:33 +00:00
action: 'knowledge_search',
description: $i18n.t(`Searching Knowledge for "{{ searchQuery }} "`, {
2024-08-22 12:12:18 +00:00
searchQuery: userMessage.content
2024-08-22 14:31:33 +00:00
}),
done: false
2024-08-22 12:12:18 +00:00
}
];
2024-07-17 09:39:37 +00:00
files.push(...model.info.meta.knowledge);
2024-08-22 12:12:18 +00:00
messages = messages; // Trigger Svelte update
2024-06-10 00:34:42 +00:00
}
2024-07-17 20:01:39 +00:00
files.push(
...(userMessage?.files ?? []).filter((item) =>
['doc', 'file', 'collection'].includes(item.type)
),
...(responseMessage?.files ?? []).filter((item) => ['web_search_results'].includes(item.type))
);
2024-05-21 17:30:31 +00:00
scrollToBottom();
2024-06-14 03:15:23 +00:00
eventTarget.dispatchEvent(
new CustomEvent('chat:start', {
detail: {
id: responseMessageId
}
})
);
await tick();
2024-06-13 04:18:53 +00:00
2024-05-21 17:30:31 +00:00
try {
2024-09-19 14:25:59 +00:00
const stream = $settings?.streamResponse ?? true;
2024-05-21 17:30:31 +00:00
const [res, controller] = await generateOpenAIChatCompletion(
localStorage.token,
{
2024-09-19 14:25:59 +00:00
stream: stream,
2024-07-02 02:33:58 +00:00
model: model.id,
2024-09-19 14:25:59 +00:00
...(stream & & (model.info?.meta?.capabilities?.usage ?? false)
? {
stream_options: {
2024-05-27 09:11:53 +00:00
include_usage: true
2024-08-22 14:31:33 +00:00
}
2024-09-19 14:25:59 +00:00
}
: {} ),
2024-05-21 17:30:31 +00:00
messages: [
2024-07-09 02:26:31 +00:00
params?.system || $settings.system || (responseMessage?.userContext ?? null)
2024-05-21 17:30:31 +00:00
? {
role: 'system',
2024-06-16 22:32:26 +00:00
content: `${ promptTemplate (
2024-07-09 02:26:31 +00:00
params?.system ?? $settings?.system ?? '',
2024-06-16 22:32:26 +00:00
$user.name,
$settings?.userLocation
? await getAndUpdateUserLocation(localStorage.token)
: undefined
)}${
2024-08-22 14:31:33 +00:00
(responseMessage?.userContext ?? null)
2024-06-24 22:32:49 +00:00
? `\n\nUser Context:\n${ responseMessage ? . userContext ?? '' } `
2024-05-21 17:30:31 +00:00
: ''
}`
2024-08-22 14:31:33 +00:00
}
2024-05-21 17:30:31 +00:00
: undefined,
...messages
]
2024-05-22 01:35:59 +00:00
.filter((message) => message?.content?.trim())
2024-05-21 17:30:31 +00:00
.map((message, idx, arr) => ({
role: message.role,
...((message.files?.filter((file) => file.type === 'image').length > 0 ?? false) & &
message.role === 'user'
? {
content: [
{
type: 'text',
text:
arr.length - 1 !== idx
? message.content
2024-08-22 14:31:33 +00:00
: (message?.raContent ?? message.content)
2024-05-21 17:30:31 +00:00
},
...message.files
.filter((file) => file.type === 'image')
.map((file) => ({
type: 'image_url',
image_url: {
url: file.url
}
}))
]
2024-08-22 14:31:33 +00:00
}
2024-05-21 17:30:31 +00:00
: {
content:
arr.length - 1 !== idx
? message.content
2024-08-22 14:31:33 +00:00
: (message?.raContent ?? message.content)
})
2024-05-21 17:30:31 +00:00
})),
2024-07-09 02:26:31 +00:00
seed: params?.seed ?? $settings?.params?.seed ?? undefined,
2024-05-21 17:30:31 +00:00
stop:
2024-08-22 14:31:33 +00:00
(params?.stop ?? $settings?.params?.stop ?? undefined)
2024-08-04 12:27:18 +00:00
? (params?.stop.split(',').map((token) => token.trim()) ?? $settings.params.stop).map(
(str) => decodeURIComponent(JSON.parse('"' + str.replace(/\"/g, '\\"') + '"'))
2024-08-22 14:31:33 +00:00
)
2024-05-21 17:30:31 +00:00
: undefined,
2024-07-09 02:26:31 +00:00
temperature: params?.temperature ?? $settings?.params?.temperature ?? undefined,
top_p: params?.top_p ?? $settings?.params?.top_p ?? undefined,
frequency_penalty:
params?.frequency_penalty ?? $settings?.params?.frequency_penalty ?? undefined,
max_tokens: params?.max_tokens ?? $settings?.params?.max_tokens ?? undefined,
2024-06-11 07:18:45 +00:00
tool_ids: selectedToolIds.length > 0 ? selectedToolIds : undefined,
2024-06-18 21:37:12 +00:00
files: files.length > 0 ? files : undefined,
2024-07-02 03:05:02 +00:00
session_id: $socket?.id,
2024-07-02 02:33:58 +00:00
chat_id: $chatId,
id: responseMessageId
2024-05-21 17:30:31 +00:00
},
2024-06-20 10:57:36 +00:00
`${ WEBUI_BASE_URL } /api`
2024-05-21 17:30:31 +00:00
);
// Wait until history/message have been updated
await tick();
scrollToBottom();
if (res && res.ok && res.body) {
2024-09-19 14:25:59 +00:00
if (!stream) {
const response = await res.json();
console.log(response);
2024-05-21 17:30:31 +00:00
2024-09-19 14:25:59 +00:00
responseMessage.content = response.choices[0].message.content;
responseMessage.info = { ... response . usage , openai : true } ;
responseMessage.done = true;
} else {
const textStream = await createOpenAITextStream(res.body, $settings.splitLargeChunks);
2024-05-30 09:37:43 +00:00
2024-09-19 14:25:59 +00:00
for await (const update of textStream) {
const { value , done , citations , error , usage } = update;
if (error) {
await handleOpenAIError(error, null, model, responseMessage);
break;
2024-05-21 17:30:31 +00:00
}
2024-09-19 14:25:59 +00:00
if (done || stopResponseFlag || _chatId !== $chatId) {
responseMessage.done = true;
messages = messages;
2024-05-21 17:30:31 +00:00
2024-09-19 14:25:59 +00:00
if (stopResponseFlag) {
controller.abort('User: Stop Response');
}
_response = responseMessage.content;
break;
}
2024-05-21 17:30:31 +00:00
2024-09-19 14:25:59 +00:00
if (usage) {
responseMessage.info = { ... usage , openai : true } ;
}
2024-05-27 09:11:53 +00:00
2024-09-19 14:25:59 +00:00
if (citations) {
responseMessage.citations = citations;
// Only remove status if it was initially set
if (model?.info?.meta?.knowledge ?? false) {
responseMessage.statusHistory = responseMessage.statusHistory.filter(
(status) => status.action !== 'knowledge_search'
);
}
continue;
2024-08-22 12:12:18 +00:00
}
2024-05-21 17:30:31 +00:00
2024-09-19 14:25:59 +00:00
if (responseMessage.content == '' && value == '\n') {
continue;
} else {
responseMessage.content += value;
2024-06-14 03:15:23 +00:00
2024-09-19 14:25:59 +00:00
if (navigator.vibrate && ($settings?.hapticFeedback ?? false)) {
navigator.vibrate(5);
}
2024-08-14 15:05:43 +00:00
2024-09-19 14:25:59 +00:00
const messageContentParts = getMessageContentParts(
responseMessage.content,
$config?.audio?.tts?.split_on ?? 'punctuation'
2024-06-14 03:15:23 +00:00
);
2024-09-19 14:25:59 +00:00
messageContentParts.pop();
// dispatch only last sentence and make sure it hasn't been dispatched before
if (
messageContentParts.length > 0 & &
messageContentParts[messageContentParts.length - 1] !== responseMessage.lastSentence
) {
responseMessage.lastSentence = messageContentParts[messageContentParts.length - 1];
eventTarget.dispatchEvent(
new CustomEvent('chat', {
detail: {
id: responseMessageId,
content: messageContentParts[messageContentParts.length - 1]
}
})
);
}
2024-06-14 03:15:23 +00:00
2024-09-19 14:25:59 +00:00
messages = messages;
}
2024-05-21 17:30:31 +00:00
2024-09-19 14:25:59 +00:00
if (autoScroll) {
scrollToBottom();
}
2024-05-21 17:30:31 +00:00
}
2024-05-31 21:21:26 +00:00
}
2024-05-21 17:30:31 +00:00
2024-09-19 14:25:59 +00:00
await chatCompletedHandler(
_chatId,
model.id,
responseMessageId,
createMessagesList(responseMessageId)
);
2024-05-31 21:21:26 +00:00
if ($settings.notificationEnabled && !document.hasFocus()) {
2024-06-10 00:34:42 +00:00
const notification = new Notification(`${ model . id } `, {
2024-05-31 21:21:26 +00:00
body: responseMessage.content,
icon: `${ WEBUI_BASE_URL } /static/favicon.png`
});
}
2024-05-21 17:30:31 +00:00
2024-05-31 21:21:26 +00:00
if ($settings.responseAutoCopy) {
copyToClipboard(responseMessage.content);
}
2024-05-21 17:30:31 +00:00
2024-06-08 04:10:00 +00:00
if ($settings.responseAutoPlayback && !$showCallOverlay) {
2024-05-31 21:21:26 +00:00
await tick();
2024-06-08 04:10:00 +00:00
2024-05-31 21:21:26 +00:00
document.getElementById(`speak-button-${ responseMessage . id } `)?.click();
2024-05-21 17:30:31 +00:00
}
} else {
await handleOpenAIError(null, res, model, responseMessage);
}
} catch (error) {
await handleOpenAIError(error, null, model, responseMessage);
}
2024-09-03 13:23:38 +00:00
2024-09-03 13:24:58 +00:00
await saveChatHandler(_chatId);
2024-09-03 13:23:38 +00:00
2024-05-21 17:30:31 +00:00
messages = messages;
stopResponseFlag = false;
await tick();
2024-08-26 13:01:29 +00:00
let lastMessageContentPart =
getMessageContentParts(
responseMessage.content,
$config?.audio?.tts?.split_on ?? 'punctuation'
)?.at(-1) ?? '';
if (lastMessageContentPart) {
2024-06-14 03:15:23 +00:00
eventTarget.dispatchEvent(
new CustomEvent('chat', {
2024-08-26 13:01:29 +00:00
detail: { id : responseMessageId , content : lastMessageContentPart }
2024-06-14 03:15:23 +00:00
})
);
}
eventTarget.dispatchEvent(
new CustomEvent('chat:finish', {
detail: {
id: responseMessageId,
content: responseMessage.content
}
})
);
2024-06-13 04:18:53 +00:00
2024-05-21 17:30:31 +00:00
if (autoScroll) {
scrollToBottom();
}
2024-07-16 12:00:09 +00:00
if (messages.length == 2 && selectedModels[0] === model.id) {
2024-05-21 17:30:31 +00:00
window.history.replaceState(history.state, '', `/c/${ _chatId } `);
const _title = await generateChatTitle(userPrompt);
await setChatTitle(_chatId, _title);
}
2024-06-07 07:04:47 +00:00
return _response;
2024-05-21 17:30:31 +00:00
};
const handleOpenAIError = async (error, res: Response | null, model, responseMessage) => {
let errorMessage = '';
let innerError;
if (error) {
innerError = error;
} else if (res !== null) {
innerError = await res.json();
}
console.error(innerError);
if ('detail' in innerError) {
toast.error(innerError.detail);
errorMessage = innerError.detail;
} else if ('error' in innerError) {
if ('message' in innerError.error) {
toast.error(innerError.error.message);
errorMessage = innerError.error.message;
} else {
toast.error(innerError.error);
errorMessage = innerError.error;
}
} else if ('message' in innerError) {
toast.error(innerError.message);
errorMessage = innerError.message;
}
2024-06-01 17:19:27 +00:00
responseMessage.error = {
2024-06-01 17:33:49 +00:00
content:
$i18n.t(`Uh-oh! There was an issue connecting to {{ provider }} .`, {
provider: model.name ?? model.id
}) +
'\n' +
errorMessage
2024-06-01 17:19:27 +00:00
};
2024-05-21 17:30:31 +00:00
responseMessage.done = true;
2024-08-27 09:24:05 +00:00
if (responseMessage.statusHistory) {
responseMessage.statusHistory = responseMessage.statusHistory.filter(
(status) => status.action !== 'knowledge_search'
);
}
2024-05-21 17:30:31 +00:00
messages = messages;
};
const stopResponse = () => {
stopResponseFlag = true;
console.log('stopResponse');
};
const regenerateResponse = async (message) => {
console.log('regenerateResponse');
if (messages.length != 0) {
let userMessage = history.messages[message.parentId];
let userPrompt = userMessage.content;
if ((userMessage?.models ?? [...selectedModels]).length == 1) {
2024-06-13 04:18:53 +00:00
// If user message has only one model selected, sendPrompt automatically selects it for regeneration
await sendPrompt(userPrompt, userMessage.id);
2024-05-21 17:30:31 +00:00
} else {
2024-06-13 04:18:53 +00:00
// If there are multiple models selected, use the model of the response message for regeneration
// e.g. many model chat
2024-08-16 16:54:30 +00:00
await sendPrompt(userPrompt, userMessage.id, {
modelId: message.model,
modelIdx: message.modelIdx
});
2024-05-21 17:30:31 +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];
responseMessage.done = false;
await tick();
const model = $models.filter((m) => m.id === responseMessage.model).at(0);
if (model) {
2024-05-27 21:25:36 +00:00
if (model?.owned_by === 'openai') {
2024-05-21 17:30:31 +00:00
await sendPromptOpenAI(
model,
history.messages[responseMessage.parentId].content,
responseMessage.id,
_chatId
);
} else
await sendPromptOllama(
model,
history.messages[responseMessage.parentId].content,
responseMessage.id,
_chatId
);
}
} else {
toast.error($i18n.t(`Model {{ modelId }} not found`, { modelId } ));
}
};
const generateChatTitle = async (userPrompt) => {
if ($settings?.title?.auto ?? true) {
const title = await generateTitle(
localStorage.token,
2024-06-09 21:25:31 +00:00
selectedModels[0],
2024-05-21 17:30:31 +00:00
userPrompt,
2024-06-09 21:25:31 +00:00
$chatId
).catch((error) => {
console.error(error);
return 'New Chat';
});
2024-05-21 17:30:31 +00:00
return title;
} else {
return `${ userPrompt } `;
}
};
const setChatTitle = async (_chatId, _title) => {
if (_chatId === $chatId) {
title = _title;
}
2024-08-15 14:54:16 +00:00
if (!$temporaryChatEnabled) {
2024-05-21 17:30:31 +00:00
chat = await updateChatById(localStorage.token, _chatId, { title : _title } );
2024-08-04 14:58:08 +00:00
2024-08-04 15:04:15 +00:00
currentChatPage.set(1);
2024-08-04 14:58:08 +00:00
await chats.set(await getChatList(localStorage.token, $currentChatPage));
2024-05-21 17:30:31 +00:00
}
};
2024-06-13 04:18:53 +00:00
const getWebSearchResults = async (model: string, parentId: string, responseId: string) => {
const responseMessage = history.messages[responseId];
2024-06-22 20:13:46 +00:00
const userMessage = history.messages[parentId];
2024-06-13 04:18:53 +00:00
responseMessage.statusHistory = [
{
done: false,
action: 'web_search',
description: $i18n.t('Generating search query')
}
];
messages = messages;
2024-06-22 20:13:46 +00:00
const prompt = userMessage.content;
2024-09-07 03:50:29 +00:00
let searchQuery = await generateSearchQuery(
localStorage.token,
model,
messages.filter((message) => message?.content?.trim()),
prompt
).catch((error) => {
console.log(error);
return prompt;
});
2024-06-13 04:18:53 +00:00
2024-09-07 03:50:29 +00:00
if (!searchQuery || searchQuery == '') {
2024-06-13 04:18:53 +00:00
responseMessage.statusHistory.push({
done: true,
error: true,
action: 'web_search',
2024-09-07 04:03:26 +00:00
description: $i18n.t('No search query generated')
2024-06-13 04:18:53 +00:00
});
messages = messages;
2024-09-07 03:50:29 +00:00
return;
2024-06-13 04:18:53 +00:00
}
responseMessage.statusHistory.push({
done: false,
action: 'web_search',
description: $i18n.t(`Searching "{{ searchQuery }} "`, { searchQuery } )
});
messages = messages;
const results = await runWebSearch(localStorage.token, searchQuery).catch((error) => {
console.log(error);
toast.error(error);
return null;
});
if (results) {
responseMessage.statusHistory.push({
done: true,
action: 'web_search',
description: $i18n.t('Searched {{ count }} sites', { count : results.filenames.length } ),
query: searchQuery,
urls: results.filenames
});
if (responseMessage?.files ?? undefined === undefined) {
responseMessage.files = [];
}
responseMessage.files.push({
collection_name: results.collection_name,
name: searchQuery,
type: 'web_search_results',
urls: results.filenames
});
messages = messages;
} else {
responseMessage.statusHistory.push({
done: true,
error: true,
action: 'web_search',
description: 'No search results found'
});
messages = messages;
}
};
2024-05-21 17:30:31 +00:00
const getTags = async () => {
return await getTagsById(localStorage.token, $chatId).catch(async (error) => {
return [];
});
};
2024-08-18 18:59:59 +00:00
2024-08-18 19:11:59 +00:00
const saveChatHandler = async (_chatId) => {
if ($chatId == _chatId) {
if (!$temporaryChatEnabled) {
chat = await updateChatById(localStorage.token, _chatId, {
messages: messages,
history: history,
models: selectedModels,
params: params,
files: chatFiles
});
currentChatPage.set(1);
await chats.set(await getChatList(localStorage.token, $currentChatPage));
}
}
};
const mergeResponses = async (messageId, responses, _chatId) => {
2024-08-18 18:59:59 +00:00
console.log('mergeResponses', messageId, responses);
const message = history.messages[messageId];
const mergedResponse = {
status: true,
content: ''
};
message.merged = mergedResponse;
2024-08-18 19:14:22 +00:00
messages = messages;
2024-08-18 18:59:59 +00:00
try {
const [res, controller] = await generateMoACompletion(
localStorage.token,
message.model,
history.messages[message.parentId].content,
responses
);
if (res && res.ok && res.body) {
const textStream = await createOpenAITextStream(res.body, $settings.splitLargeChunks);
for await (const update of textStream) {
const { value , done , citations , error , usage } = update;
if (error || done) {
break;
}
if (mergedResponse.content == '' && value == '\n') {
continue;
} else {
mergedResponse.content += value;
messages = messages;
}
if (autoScroll) {
scrollToBottom();
}
}
2024-08-18 19:11:59 +00:00
await saveChatHandler(_chatId);
2024-08-18 18:59:59 +00:00
} else {
console.error(res);
}
} catch (e) {
console.error(e);
}
};
2024-05-21 17:30:31 +00:00
< / script >
< svelte:head >
< title >
{ title
? `${ title . length > 30 ? `$ { title . slice ( 0 , 30 )}... ` : title } | ${ $WEBUI_NAME } `
: `${ $WEBUI_NAME } `}
< / title >
< / svelte:head >
2024-06-14 03:15:23 +00:00
< audio id = "audioElement" src = "" style = "display: none;" / >
2024-07-09 04:39:06 +00:00
< EventConfirmDialog
bind:show={ showEventConfirmation }
title={ eventConfirmationTitle }
message={ eventConfirmationMessage }
2024-07-12 00:30:24 +00:00
input={ eventConfirmationInput }
inputPlaceholder={ eventConfirmationInputPlaceholder }
2024-07-22 19:43:31 +00:00
inputValue={ eventConfirmationInputValue }
2024-07-09 04:39:06 +00:00
on:confirm={( e ) => {
2024-07-12 00:30:24 +00:00
if (e.detail) {
eventCallback(e.detail);
} else {
eventCallback(true);
}
2024-07-09 04:39:06 +00:00
}}
on:cancel={() => {
eventCallback(false);
}}
/>
2024-05-21 17:30:31 +00:00
{ #if ! chatIdProp || ( loaded && chatIdProp )}
< div
2024-06-05 15:43:23 +00:00
class="h-screen max-h-[100dvh] { $showSidebar
2024-05-21 17:30:31 +00:00
? 'md:max-w-[calc(100%-260px)]'
2024-06-18 22:39:50 +00:00
: ''} w-full max-w-full flex flex-col"
2024-05-21 17:30:31 +00:00
>
2024-06-17 08:31:22 +00:00
{ #if $settings ? . backgroundImageUrl ?? null }
< div
class="absolute { $showSidebar
? 'md:max-w-[calc(100%-260px)] md:translate-x-[260px]'
: ''} top-0 left-0 w-full h-full bg-cover bg-center bg-no-repeat"
style="background-image: url({ $settings . backgroundImageUrl } ) "
/>
< div
2024-06-17 18:46:23 +00:00
class="absolute top-0 left-0 w-full h-full bg-gradient-to-t from-white to-white/85 dark:from-gray-900 dark:to-[#171717]/90 z-0"
2024-06-17 08:31:22 +00:00
/>
{ /if }
2024-05-21 17:30:31 +00:00
< Navbar
{ title }
bind:selectedModels
bind:showModelSelector
shareEnabled={ messages . length > 0 }
{ chat }
{ initNewChat }
/>
2024-05-26 19:18:43 +00:00
2024-09-21 01:33:06 +00:00
< PaneGroup direction = "horizontal" class = "w-full h-full" >
< Pane defaultSize = { 50 } class="h-full flex w-full relative " >
{ #if $banners . length > 0 && messages . length === 0 && ! $chatId && selectedModels . length <= 1 }
< div class = "absolute top-3 left-0 right-0 w-full z-20" >
< div class = " flex flex-col gap-1 w-full" >
{ #each $banners . filter ( ( b ) => ( b . dismissible ? ! JSON . parse ( localStorage . getItem ( 'dismissedBannerIds' ) ?? '[]' ). includes ( b . id ) : true ) ) as banner }
< Banner
{ banner }
on:dismiss={( e ) => {
const bannerId = e.detail;
localStorage.setItem(
'dismissedBannerIds',
JSON.stringify(
[
bannerId,
...JSON.parse(localStorage.getItem('dismissedBannerIds') ?? '[]')
].filter((id) => $banners.find((b) => b.id === id))
)
);
}}
/>
{ /each }
< / div >
< / div >
{ /if }
< div class = "flex flex-col flex-auto z-10 w-full" >
< div
class=" pb-2.5 flex flex-col justify-between w-full flex-auto overflow-auto h-0 max-w-full z-10 scrollbar-hidden"
id="messages-container"
bind:this={ messagesContainerElement }
on:scroll={( e ) => {
autoScroll =
messagesContainerElement.scrollHeight - messagesContainerElement.scrollTop < =
messagesContainerElement.clientHeight + 5;
}}
>
< div class = " h-full w-full flex flex-col { chatIdProp ? 'py-4' : 'pt-2 pb-4' } " >
< Messages
chatId={ $chatId }
{ selectedModels }
{ processing }
bind:history
bind:messages
bind:autoScroll
bind:prompt
bottomPadding={ files . length > 0 }
{ sendPrompt }
{ continueGeneration }
{ regenerateResponse }
{ mergeResponses }
{ chatActionHandler }
{ showMessage }
/>
< / div >
< / div >
< div class = "" >
< MessageInput
bind:files
bind:prompt
bind:autoScroll
bind:selectedToolIds
bind:webSearchEnabled
bind:atSelectedModel
availableToolIds={ selectedModelIds . reduce (( a , e , i , arr ) => {
const model = $models.find((m) => m.id === e);
if (model?.info?.meta?.toolIds ?? false) {
return [...new Set([...a, ...model.info.meta.toolIds])];
}
return a;
}, [])}
transparentBackground={ $settings ? . backgroundImageUrl ?? false }
{ selectedModels }
{ messages }
{ submitPrompt }
{ stopResponse }
2024-09-21 01:44:44 +00:00
on:call={ async () => {
await showControls.set(true);
2024-05-26 19:32:57 +00:00
}}
/>
2024-09-21 01:33:06 +00:00
< / div >
2024-05-26 19:32:57 +00:00
< / div >
2024-09-21 01:33:06 +00:00
< / Pane >
2024-05-26 19:18:43 +00:00
2024-09-21 01:33:06 +00:00
< ChatControls
models={ selectedModelIds . reduce (( a , e , i , arr ) => {
const model = $models.find((m) => m.id === e);
if (model) {
return [...a, model];
}
return a;
}, [])}
bind:history
bind:chatFiles
bind:params
bind:files
bind:pane={ controlPane }
{ submitPrompt }
{ stopResponse }
{ showMessage }
modelId={ selectedModelIds ? . at ( 0 ) ?? null }
chatId={ $chatId }
{ eventTarget }
/>
< / PaneGroup >
2024-05-21 17:30:31 +00:00
< / div >
{ /if }