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

485 lines
12 KiB
Svelte
Raw Normal View History

2023-10-09 00:38:42 +02:00
<script lang="ts">
import { v4 as uuidv4 } from 'uuid';
2023-10-29 00:16:04 +02:00
import toast from 'svelte-french-toast';
2023-11-20 02:47:07 +01:00
import { OLLAMA_API_BASE_URL } from '$lib/constants';
2023-10-13 03:18:07 +02:00
import { onMount, tick } from 'svelte';
2023-11-20 02:47:07 +01:00
import { splitStream } from '$lib/utils';
import { goto } from '$app/navigation';
2023-10-29 03:58:16 +01:00
2023-11-20 02:47:07 +01:00
import { config, user, settings, db, chats, chatId } from '$lib/stores';
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 22:21:40 +02:00
import Navbar from '$lib/components/layout/Navbar.svelte';
2023-11-20 02:47:07 +01:00
let stopResponseFlag = false;
let autoScroll = true;
2023-10-09 00:38:42 +02:00
2023-11-12 19:30:34 +01:00
let selectedModels = [''];
2023-11-11 22:03:54 +01:00
2023-10-25 02:49:54 +02:00
let title = '';
2023-10-09 00:38:42 +02:00
let prompt = '';
2023-11-25 09:21:07 +01:00
let files = [];
2023-11-20 02:47:07 +01:00
let messages = [];
2023-11-12 05:18:03 +01: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-10-09 00:38:42 +02:00
onMount(async () => {
2023-11-20 05:39:13 +01:00
await chatId.set(uuidv4());
chatId.subscribe(async () => {
await initNewChat();
});
2023-10-13 03:18:07 +02:00
});
//////////////////////////
// Web functions
//////////////////////////
2023-11-20 02:47:07 +01:00
const initNewChat = async () => {
console.log($chatId);
2023-10-28 08:26:01 +02:00
2023-11-20 02:47:07 +01:00
autoScroll = true;
2023-10-28 08:26:01 +02:00
2023-11-20 02:47:07 +01:00
title = '';
messages = [];
history = {
messages: {},
currentId: null
2023-11-12 05:18:03 +01:00
};
2023-11-20 02:47:07 +01:00
selectedModels = $settings.models ?? [''];
2023-11-12 05:18:03 +01:00
};
//////////////////////////
// Ollama functions
//////////////////////////
2023-11-12 05:18:03 +01:00
const sendPrompt = async (userPrompt, parentId) => {
2023-11-12 19:30:34 +01:00
await Promise.all(
selectedModels.map(async (model) => {
if (model.includes('gpt-')) {
await sendPromptOpenAI(model, userPrompt, parentId);
} else {
await sendPromptOllama(model, userPrompt, parentId);
}
})
);
2023-11-20 02:47:07 +01:00
await chats.set(await $db.getChats());
2023-11-04 01:16:02 +01:00
};
2023-11-12 19:30:34 +01:00
const sendPromptOllama = async (model, userPrompt, parentId) => {
2023-11-22 22:11:26 +01:00
console.log('sendPromptOllama');
2023-11-12 05:18:03 +01:00
let responseMessageId = uuidv4();
let responseMessage = {
2023-11-12 05:18:03 +01:00
parentId: parentId,
id: responseMessageId,
childrenIds: [],
role: 'assistant',
2023-11-12 19:30:34 +01:00
content: '',
model: model
};
2023-11-12 05:18:03 +01:00
history.messages[responseMessageId] = responseMessage;
history.currentId = responseMessageId;
if (parentId !== null) {
history.messages[parentId].childrenIds = [
...history.messages[parentId].childrenIds,
responseMessageId
];
}
window.scrollTo({ top: document.body.scrollHeight });
2023-11-20 02:47:07 +01:00
const res = await fetch(`${$settings?.API_BASE_URL ?? OLLAMA_API_BASE_URL}/generate`, {
method: 'POST',
headers: {
2023-11-14 23:27:42 +01:00
'Content-Type': 'text/event-stream',
2023-11-20 02:47:07 +01:00
...($settings.authHeader && { Authorization: $settings.authHeader }),
2023-11-19 01:47:12 +01:00
...($user && { Authorization: `Bearer ${localStorage.token}` })
},
body: JSON.stringify({
2023-11-12 19:30:34 +01:00
model: model,
prompt: userPrompt,
2023-11-20 02:47:07 +01:00
system: $settings.system ?? undefined,
2023-11-05 04:00:17 +01:00
options: {
2023-11-20 02:47:07 +01:00
seed: $settings.seed ?? undefined,
temperature: $settings.temperature ?? undefined,
repeat_penalty: $settings.repeat_penalty ?? undefined,
top_k: $settings.top_k ?? undefined,
top_p: $settings.top_p ?? undefined
2023-11-05 04:00:17 +01:00
},
2023-11-20 02:47:07 +01:00
format: $settings.requestFormat ?? undefined,
context:
2023-11-12 05:18:03 +01:00
history.messages[parentId] !== null &&
history.messages[parentId].parentId in history.messages
? history.messages[history.messages[parentId].parentId]?.context ?? undefined
: undefined
})
});
const reader = res.body
.pipeThrough(new TextDecoderStream())
.pipeThrough(splitStream('\n'))
.getReader();
while (true) {
const { value, done } = await reader.read();
if (done || stopResponseFlag) {
if (stopResponseFlag) {
responseMessage.done = true;
messages = messages;
}
break;
}
try {
let lines = value.split('\n');
for (const line of lines) {
if (line !== '') {
console.log(line);
let data = JSON.parse(line);
if (data.done == false) {
if (responseMessage.content == '' && data.response == '\n') {
continue;
} else {
responseMessage.content += data.response;
messages = messages;
}
2023-11-19 01:47:12 +01:00
} else if ('detail' in data) {
throw data;
} else {
responseMessage.done = true;
responseMessage.context = data.context;
messages = messages;
}
}
}
} catch (error) {
console.log(error);
2023-11-19 01:47:12 +01:00
if ('detail' in error) {
toast.error(error.detail);
}
break;
}
if (autoScroll) {
window.scrollTo({ top: document.body.scrollHeight });
}
await $db.updateChatById($chatId, {
title: title === '' ? 'New Chat' : title,
2023-11-12 19:30:34 +01:00
models: selectedModels,
2023-11-20 02:47:07 +01:00
system: $settings.system ?? undefined,
options: {
2023-11-20 02:47:07 +01:00
seed: $settings.seed ?? undefined,
temperature: $settings.temperature ?? undefined,
repeat_penalty: $settings.repeat_penalty ?? undefined,
top_k: $settings.top_k ?? undefined,
top_p: $settings.top_p ?? undefined
},
2023-11-12 05:18:03 +01:00
messages: messages,
history: history
});
}
stopResponseFlag = false;
await tick();
if (autoScroll) {
window.scrollTo({ top: document.body.scrollHeight });
}
2023-11-04 01:16:02 +01:00
2023-11-19 01:47:12 +01:00
if (messages.length == 2 && messages.at(1).content !== '') {
2023-11-20 02:47:07 +01:00
window.history.replaceState(history.state, '', `/c/${$chatId}`);
await generateChatTitle($chatId, userPrompt);
2023-11-04 01:16:02 +01:00
}
};
2023-11-12 19:30:34 +01:00
const sendPromptOpenAI = async (model, userPrompt, parentId) => {
2023-11-22 22:11:26 +01:00
if ($settings.OPENAI_API_KEY) {
2023-11-04 01:16:02 +01:00
if (models) {
let responseMessageId = uuidv4();
2023-11-04 01:16:02 +01:00
let responseMessage = {
parentId: parentId,
id: responseMessageId,
childrenIds: [],
2023-11-04 01:16:02 +01:00
role: 'assistant',
2023-11-12 19:30:34 +01:00
content: '',
model: model
2023-11-04 01:16:02 +01:00
};
history.messages[responseMessageId] = responseMessage;
history.currentId = responseMessageId;
if (parentId !== null) {
history.messages[parentId].childrenIds = [
...history.messages[parentId].childrenIds,
responseMessageId
];
}
2023-11-04 01:16:02 +01:00
window.scrollTo({ top: document.body.scrollHeight });
const res = await fetch(`https://api.openai.com/v1/chat/completions`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
2023-11-22 22:11:26 +01:00
Authorization: `Bearer ${$settings.OPENAI_API_KEY}`
2023-11-04 01:16:02 +01:00
},
body: JSON.stringify({
2023-11-12 19:30:34 +01:00
model: model,
2023-11-04 01:16:02 +01:00
stream: true,
2023-11-05 04:00:17 +01:00
messages: [
2023-11-20 02:47:07 +01:00
$settings.system
2023-11-05 04:00:17 +01:00
? {
role: 'system',
2023-11-22 22:11:26 +01:00
content: $settings.system
2023-11-05 04:00:17 +01:00
}
: undefined,
...messages
]
.filter((message) => message)
.map((message) => ({ role: message.role, content: message.content })),
2023-11-20 02:47:07 +01:00
temperature: $settings.temperature ?? undefined,
top_p: $settings.top_p ?? undefined,
frequency_penalty: $settings.repeat_penalty ?? undefined
2023-11-04 01:16:02 +01:00
})
});
const reader = res.body
.pipeThrough(new TextDecoderStream())
.pipeThrough(splitStream('\n'))
.getReader();
while (true) {
const { value, done } = await reader.read();
if (done || stopResponseFlag) {
if (stopResponseFlag) {
responseMessage.done = true;
messages = messages;
}
break;
}
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 {
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;
}
}
}
}
} catch (error) {
console.log(error);
}
if (autoScroll) {
window.scrollTo({ top: document.body.scrollHeight });
}
await $db.updateChatById($chatId, {
2023-11-04 01:16:02 +01:00
title: title === '' ? 'New Chat' : title,
2023-11-12 19:30:34 +01:00
models: selectedModels,
2023-11-20 02:47:07 +01:00
system: $settings.system ?? undefined,
2023-11-04 01:16:02 +01:00
options: {
2023-11-20 02:47:07 +01:00
seed: $settings.seed ?? undefined,
temperature: $settings.temperature ?? undefined,
repeat_penalty: $settings.repeat_penalty ?? undefined,
top_k: $settings.top_k ?? undefined,
top_p: $settings.top_p ?? undefined
2023-11-04 01:16:02 +01:00
},
2023-11-12 05:18:03 +01:00
messages: messages,
history: history
2023-11-04 01:16:02 +01:00
});
}
stopResponseFlag = false;
await tick();
if (autoScroll) {
window.scrollTo({ top: document.body.scrollHeight });
}
if (messages.length == 2) {
2023-11-20 02:47:07 +01:00
window.history.replaceState(history.state, '', `/c/${$chatId}`);
await setChatTitle($chatId, userPrompt);
2023-11-04 01:16:02 +01:00
}
}
}
};
const submitPrompt = async (userPrompt) => {
2023-10-09 00:38:42 +02:00
console.log('submitPrompt');
2023-10-09 04:42:54 +02:00
2023-11-12 19:30:34 +01:00
if (selectedModels.includes('')) {
toast.error('Model not selected');
} else if (messages.length != 0 && messages.at(-1).done != true) {
console.log('wait');
} else {
2023-11-08 10:25:18 +01:00
document.getElementById('chat-textarea').style.height = '';
2023-11-12 05:18:03 +01:00
let userMessageId = uuidv4();
let userMessage = {
id: userMessageId,
parentId: messages.length !== 0 ? messages.at(-1).id : null,
childrenIds: [],
role: 'user',
2023-11-25 09:21:07 +01:00
content: userPrompt,
files: files.length > 0 ? files : undefined
2023-11-12 05:18:03 +01:00
};
if (messages.length !== 0) {
history.messages[messages.at(-1).id].childrenIds.push(userMessageId);
}
history.messages[userMessageId] = userMessage;
history.currentId = userMessageId;
2023-11-08 10:25:18 +01:00
prompt = '';
2023-11-25 09:21:07 +01:00
files = [];
2023-11-08 10:25:18 +01:00
if (messages.length == 0) {
await $db.createNewChat({
2023-11-20 02:47:07 +01:00
id: $chatId,
title: 'New Chat',
2023-11-12 19:30:34 +01:00
models: selectedModels,
2023-11-20 02:47:07 +01:00
system: $settings.system ?? undefined,
2023-10-19 07:57:55 +02:00
options: {
2023-11-20 02:47:07 +01:00
seed: $settings.seed ?? undefined,
temperature: $settings.temperature ?? undefined,
repeat_penalty: $settings.repeat_penalty ?? undefined,
top_k: $settings.top_k ?? undefined,
top_p: $settings.top_p ?? undefined
2023-10-19 07:57:55 +02:00
},
2023-11-12 05:18:03 +01:00
messages: messages,
history: history
});
}
2023-10-09 04:42:54 +02:00
setTimeout(() => {
window.scrollTo({ top: document.body.scrollHeight, behavior: 'smooth' });
}, 50);
2023-11-12 05:18:03 +01:00
await sendPrompt(userPrompt, userMessageId);
2023-10-09 00:38:42 +02:00
}
};
2023-11-20 02:47:07 +01:00
const stopResponse = () => {
stopResponseFlag = true;
console.log('stopResponse');
};
const regenerateResponse = async () => {
console.log('regenerateResponse');
if (messages.length != 0 && messages.at(-1).done == true) {
messages.splice(messages.length - 1, 1);
messages = messages;
2023-10-09 00:38:42 +02:00
let userMessage = messages.at(-1);
let userPrompt = userMessage.content;
2023-11-04 01:16:02 +01:00
2023-11-12 05:18:03 +01:00
await sendPrompt(userPrompt, userMessage.id);
2023-10-09 00:38:42 +02:00
}
};
2023-11-04 01:16:02 +01:00
const generateChatTitle = async (_chatId, userPrompt) => {
if ($settings.titleAutoGenerate ?? true) {
console.log('generateChatTitle');
const res = await fetch(`${$settings?.API_BASE_URL ?? OLLAMA_API_BASE_URL}/generate`, {
method: 'POST',
headers: {
'Content-Type': 'text/event-stream',
...($settings.authHeader && { Authorization: $settings.authHeader }),
...($user && { Authorization: `Bearer ${localStorage.token}` })
},
body: JSON.stringify({
model: selectedModels[0],
prompt: `Generate a brief 3-5 word title for this question, excluding the term 'title.' Then, please reply with only the title: ${userPrompt}`,
stream: false
})
})
.then(async (res) => {
if (!res.ok) throw await res.json();
return res.json();
})
.catch((error) => {
if ('detail' in error) {
toast.error(error.detail);
}
console.log(error);
return null;
});
if (res) {
await setChatTitle(_chatId, res.response === '' ? 'New Chat' : res.response);
}
} else {
await setChatTitle(_chatId, `${userPrompt}`);
2023-11-04 01:16:02 +01:00
}
};
const setChatTitle = async (_chatId, _title) => {
await $db.updateChatById(_chatId, { title: _title });
if (_chatId === $chatId) {
2023-11-04 01:16:02 +01:00
title = _title;
}
};
2023-10-09 00:38:42 +02:00
</script>
<svelte:window
on:scroll={(e) => {
2023-11-09 01:40:58 +01:00
autoScroll = window.innerHeight + window.scrollY >= document.body.offsetHeight - 40;
}}
/>
2023-11-20 02:47:07 +01:00
<Navbar {title} />
<div class="min-h-screen w-full flex justify-center">
<div class=" py-2.5 flex flex-col justify-between w-full">
<div class="max-w-2xl mx-auto w-full px-3 md:px-0 mt-10">
<ModelSelector bind:selectedModels disabled={messages.length > 0} />
2023-10-09 00:38:42 +02:00
</div>
2023-11-20 02:47:07 +01:00
<div class=" h-full mt-10 mb-32 w-full flex flex-col">
<Messages bind:history bind:messages bind:autoScroll {sendPrompt} {regenerateResponse} />
</div>
</div>
2023-10-25 02:49:54 +02:00
2023-11-25 09:21:07 +01:00
<MessageInput bind:prompt bind:files bind:autoScroll {messages} {submitPrompt} {stopResponse} />
2023-11-20 02:47:07 +01:00
</div>