Chat.svelte 33.6 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
<script lang="ts">
	import { v4 as uuidv4 } from 'uuid';
	import { toast } from 'svelte-sonner';

	import { getContext, onMount, tick } from 'svelte';
	import { goto } from '$app/navigation';
	import { page } from '$app/stores';

	import {
		chatId,
		chats,
		config,
13
		type Model,
14
15
16
17
		models,
		settings,
		showSidebar,
		tags as _tags,
Timothy J. Baek's avatar
Timothy J. Baek committed
18
		WEBUI_NAME,
19
20
		banners,
		user
21
	} from '$lib/stores';
22
23
24
25
26
27
	import {
		convertMessagesToHistory,
		copyToClipboard,
		promptTemplate,
		splitStream
	} from '$lib/utils';
28
29
30
31
32
33
34
35
36
37
38
39

	import { cancelOllamaRequest, generateChatCompletion } from '$lib/apis/ollama';
	import {
		addTagById,
		createNewChat,
		deleteTagById,
		getAllChatTags,
		getChatById,
		getChatList,
		getTagsById,
		updateChatById
	} from '$lib/apis/chats';
40
41
42
43
44
	import {
		generateOpenAIChatCompletion,
		generateSearchQuery,
		generateTitle
	} from '$lib/apis/openai';
45
46
47
48

	import MessageInput from '$lib/components/chat/MessageInput.svelte';
	import Messages from '$lib/components/chat/Messages.svelte';
	import Navbar from '$lib/components/layout/Navbar.svelte';
Timothy J. Baek's avatar
Timothy J. Baek committed
49
	import { OLLAMA_API_BASE_URL, OPENAI_API_BASE_URL, WEBUI_BASE_URL } from '$lib/constants';
50
51
52
53
	import { createOpenAITextStream } from '$lib/apis/streaming';
	import { queryMemory } from '$lib/apis/memories';
	import type { Writable } from 'svelte/store';
	import type { i18n as i18nType } from 'i18next';
54
	import { runWebSearch } from '$lib/apis/rag';
Timothy J. Baek's avatar
Timothy J. Baek committed
55
	import Banner from '../common/Banner.svelte';
56
	import { getUserSettings } from '$lib/apis/users';
57
	import { chatCompleted } from '$lib/apis';
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
58

59
60
61
62
63
64
65
66
67
68
69
70
71
72
	const i18n: Writable<i18nType> = getContext('i18n');

	export let chatIdProp = '';
	let loaded = false;

	let stopResponseFlag = false;
	let autoScroll = true;
	let processing = '';
	let messagesContainerElement: HTMLDivElement;
	let currentRequestId = null;

	let showModelSelector = true;

	let selectedModels = [''];
73
	let atSelectedModel: Model | undefined;
74

Timothy J. Baek's avatar
Timothy J. Baek committed
75
	let webSearchEnabled = false;
76

77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
	let chat = null;
	let tags = [];

	let title = '';
	let prompt = '';
	let files = [];
	let messages = [];
	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;
	} else {
		messages = [];
	}

	$: if (chatIdProp) {
		(async () => {
			if (await loadChat()) {
				await tick();
				loaded = true;

				window.setTimeout(() => scrollToBottom(), 0);
				const chatInput = document.getElementById('chat-textarea');
				chatInput?.focus();
			} else {
				await goto('/');
			}
		})();
	}

	onMount(async () => {
Timothy J. Baek's avatar
Timothy J. Baek committed
119
		if (!$chatId) {
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
			await initNewChat();
		} else {
			if (!($settings.saveChatHistory ?? true)) {
				await goto('/');
			}
		}
	});

	//////////////////////////
	// Web functions
	//////////////////////////

	const initNewChat = async () => {
		if (currentRequestId !== null) {
			await cancelOllamaRequest(localStorage.token, currentRequestId);
			currentRequestId = null;
		}
		window.history.replaceState(history.state, '', `/`);
		await chatId.set('');

		autoScroll = true;

		title = '';
		messages = [];
		history = {
			messages: {},
			currentId: null
		};

		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) {
154
			console.log($config?.default_models.split(',') ?? '');
155
156
157
158
159
160
161
			selectedModels = $config?.default_models.split(',');
		} else {
			selectedModels = [''];
		}

		if ($page.url.searchParams.get('q')) {
			prompt = $page.url.searchParams.get('q') ?? '';
Timothy J. Baek's avatar
Timothy J. Baek committed
162

163
164
165
166
167
168
169
170
171
172
			if (prompt) {
				await tick();
				submitPrompt(prompt);
			}
		}

		selectedModels = selectedModels.map((modelId) =>
			$models.map((m) => m.id).includes(modelId) ? modelId : ''
		);

173
174
175
176
177
178
179
		const userSettings = await getUserSettings(localStorage.token);

		if (userSettings) {
			settings.set(userSettings.ui);
		} else {
			settings.set(JSON.parse(localStorage.getItem('settings') ?? '{}'));
		}
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208

		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;

209
210
211
212
213
214
215
216
				const userSettings = await getUserSettings(localStorage.token);

				if (userSettings) {
					await settings.set(userSettings.ui);
				} else {
					await settings.set(JSON.parse(localStorage.getItem('settings') ?? '{}'));
				}

217
				await settings.set({
218
219
220
					...$settings,
					system: chatContent.system ?? $settings.system,
					params: chatContent.options ?? $settings.params
221
				});
222

223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
				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;
		}
	};

245
246
247
248
249
250
251
252
253
	const createMessagesList = (responseMessageId) => {
		const message = history.messages[responseMessageId];
		if (message.parentId) {
			return [...createMessagesList(message.parentId), message];
		} else {
			return [message];
		}
	};

254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
	//////////////////////////
	// Ollama functions
	//////////////////////////

	const submitPrompt = async (userPrompt, _user = null) => {
		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');
		} else if (
			files.length > 0 &&
			files.filter((file) => file.upload_status === false).length > 0
		) {
			// 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.`
				)
			);
		} 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',
				user: _user ?? undefined,
				content: userPrompt,
				files: files.length > 0 ? files : undefined,
				timestamp: Math.floor(Date.now() / 1000), // Unix epoch
				models: selectedModels.filter((m, mIdx) => selectedModels.indexOf(m) === mIdx)
			};

			// Add message to history and Set currentId to messageId
			history.messages[userMessageId] = userMessage;
			history.currentId = userMessageId;

			// Append messageId to childrenIds of parent message
			if (messages.length !== 0) {
				history.messages[messages.at(-1).id].childrenIds.push(userMessageId);
			}

			// Wait until history/message have been updated
			await tick();

			// Create new chat if only one message in messages
			if (messages.length == 1) {
				if ($settings.saveChatHistory ?? true) {
					chat = await createNewChat(localStorage.token, {
						id: $chatId,
						title: $i18n.t('New Chat'),
						models: selectedModels,
						system: $settings.system ?? undefined,
						options: {
Timothy J. Baek's avatar
Timothy J. Baek committed
319
							...($settings.params ?? {})
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
						},
						messages: messages,
						history: history,
						tags: [],
						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 = '';
Timothy J. Baek's avatar
Timothy J. Baek committed
336
			document.getElementById('chat-textarea').style.height = '';
337
338
339
340
341
342
343
344
345
346
347
			files = [];

			// Send prompt
			await sendPrompt(userPrompt, userMessageId);
		}
	};

	const sendPrompt = async (prompt, parentId, modelId = null) => {
		const _chatId = JSON.parse(JSON.stringify($chatId));

		await Promise.all(
348
349
350
351
352
353
354
355
356
357
358
359
360
361
			(modelId
				? [modelId]
				: atSelectedModel !== undefined
				? [atSelectedModel.id]
				: selectedModels
			).map(async (modelId) => {
				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')
					);
362

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
363
					if (hasImages && !(model.info?.meta?.capabilities?.vision ?? true)) {
364
365
						toast.error(
							$i18n.t('Model {{modelName}} is not vision capable', {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
366
								modelName: model.name ?? model.id
367
368
369
							})
						);
					}
370

371
372
373
374
375
376
377
378
379
					// Create response message
					let responseMessageId = uuidv4();
					let responseMessage = {
						parentId: parentId,
						id: responseMessageId,
						childrenIds: [],
						role: 'assistant',
						content: '',
						model: model.id,
380
						modelName: model.name ?? model.id,
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
						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
						];
					}
396

397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
					await tick();

					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) {
									userContext = res.documents.reduce((acc, doc, index) => {
										const createdAtTimestamp = res.metadatas[index][0].created_at;
										const createdAtDate = new Date(createdAtTimestamp * 1000)
											.toISOString()
											.split('T')[0];
										acc.push(`${index + 1}. [${createdAtDate}]. ${doc[0]}`);
										return acc;
									}, []);
417
								}
418
419

								console.log(userContext);
420
421
							}
						}
422
423
					}
					responseMessage.userContext = userContext;
424

Timothy J. Baek's avatar
Timothy J. Baek committed
425
					if (webSearchEnabled) {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
426
						await getWebSearchResults(model.id, parentId, responseMessageId);
427
					}
428

429
					if (model?.owned_by === 'openai') {
430
431
432
						await sendPromptOpenAI(model, prompt, responseMessageId, _chatId);
					} else if (model) {
						await sendPromptOllama(model, prompt, responseMessageId, _chatId);
433
					}
434
435
				} else {
					toast.error($i18n.t(`Model {{modelId}} not found`, { modelId }));
436
				}
437
			})
438
439
440
441
442
		);

		await chats.set(await getChatList(localStorage.token));
	};

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
443
	const getWebSearchResults = async (model: string, parentId: string, responseId: string) => {
444
		const responseMessage = history.messages[responseId];
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
445
446
447
448
449
450

		responseMessage.status = {
			done: false,
			action: 'web_search',
			description: $i18n.t('Generating search query')
		};
451
		messages = messages;
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
452

Timothy J. Baek's avatar
Timothy J. Baek committed
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
		const prompt = history.messages[parentId].content;
		let searchQuery = prompt;
		if (prompt.length > 100) {
			searchQuery = await generateChatSearchQuery(model, prompt);
			if (!searchQuery) {
				toast.warning($i18n.t('No search query generated'));
				responseMessage.status = {
					...responseMessage.status,
					done: true,
					error: true,
					description: 'No search query generated'
				};
				messages = messages;
				return;
			}
468
		}
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
469

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
470
471
472
473
		responseMessage.status = {
			...responseMessage.status,
			description: $i18n.t("Searching the web for '{{searchQuery}}'", { searchQuery })
		};
474
		messages = messages;
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
475

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
476
477
		const results = await runWebSearch(localStorage.token, searchQuery);
		if (results === undefined) {
478
			toast.warning($i18n.t('No search results found'));
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
479
480
481
482
483
484
			responseMessage.status = {
				...responseMessage.status,
				done: true,
				error: true,
				description: 'No search results found'
			};
485
486
487
			messages = messages;
			return;
		}
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
488

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
489
490
491
		responseMessage.status = {
			...responseMessage.status,
			done: true,
Timothy J. Baek's avatar
Timothy J. Baek committed
492
493
			description: $i18n.t('Searched {{count}} sites', { count: results.filenames.length }),
			urls: results.filenames
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
494
495
496
		};

		if (responseMessage?.files ?? undefined === undefined) {
497
498
			responseMessage.files = [];
		}
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
499

500
		responseMessage.files.push({
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
501
			collection_name: results.collection_name,
502
			name: searchQuery,
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
503
504
			type: 'web_search_results',
			urls: results.filenames
505
		});
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
506

507
508
509
		messages = messages;
	};

510
511
512
513
514
515
516
517
518
519
520
521
522
523
	const sendPromptOllama = async (model, userPrompt, responseMessageId, _chatId) => {
		model = model.id;
		const responseMessage = history.messages[responseMessageId];

		// Wait until history/message have been updated
		await tick();

		// Scroll down
		scrollToBottom();

		const messagesBody = [
			$settings.system || (responseMessage?.userContext ?? null)
				? {
						role: 'system',
524
						content: `${promptTemplate($settings?.system ?? '', $user.name)}${
525
526
527
528
529
530
531
532
							responseMessage?.userContext ?? null
								? `\n\nUser Context:\n${(responseMessage?.userContext ?? []).join('\n')}`
								: ''
						}`
				  }
				: undefined,
			...messages
		]
Yanyutin753's avatar
Yanyutin753 committed
533
			.filter((message) => message?.content?.trim())
534
535
536
537
			.map((message, idx, arr) => {
				// Prepare the base message object
				const baseMessage = {
					role: message.role,
Timothy J. Baek's avatar
Timothy J. Baek committed
538
					content: message.content
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
				};

				// 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;
			}
		});

		const docs = messages
			.filter((message) => message?.files ?? null)
			.map((message) =>
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
572
573
574
				message.files.filter((item) =>
					['doc', 'collection', 'web_search_results'].includes(item.type)
				)
575
576
577
578
579
580
581
			)
			.flat(1);

		const [res, controller] = await generateChatCompletion(localStorage.token, {
			model: model,
			messages: messagesBody,
			options: {
Timothy J. Baek's avatar
Timothy J. Baek committed
582
				...($settings.params ?? {}),
583
				stop:
Timothy J. Baek's avatar
Timothy J. Baek committed
584
585
					$settings?.params?.stop ?? undefined
						? $settings.params.stop.map((str) =>
586
587
								decodeURIComponent(JSON.parse('"' + str.replace(/\"/g, '\\"') + '"'))
						  )
588
						: undefined,
589
590
				num_predict: $settings?.params?.max_tokens ?? undefined,
				repeat_penalty: $settings?.params?.frequency_penalty ?? undefined
591
592
593
594
			},
			format: $settings.requestFormat ?? undefined,
			keep_alive: $settings.keepAlive ?? undefined,
			docs: docs.length > 0 ? docs : undefined,
595
596
			citations: docs.length > 0,
			chat_id: $chatId
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
		});

		if (res && res.ok) {
			console.log('controller', controller);

			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;

					if (stopResponseFlag) {
						controller.abort('User: Stop Response');
						await cancelOllamaRequest(localStorage.token, currentRequestId);
616
					} else {
617
						const messages = createMessagesList(responseMessageId);
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
						const res = await chatCompleted(localStorage.token, {
							model: model,
							messages: messages.map((m) => ({
								id: m.id,
								role: m.role,
								content: m.content,
								timestamp: m.timestamp
							})),
							chat_id: $chatId
						}).catch((error) => {
							console.error(error);
							return null;
						});

						if (res !== null) {
							// Update chat history with the new messages
							for (const message of res.messages) {
Timothy J. Baek's avatar
Timothy J. Baek committed
635
636
								history.messages[message.id] = {
									...history.messages[message.id],
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
637
638
639
									...(history.messages[message.id].content !== message.content
										? { originalContent: history.messages[message.id].content }
										: {}),
Timothy J. Baek's avatar
Timothy J. Baek committed
640
641
									...message
								};
642
643
							}
						}
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
					}

					currentRequestId = null;

					break;
				}

				try {
					let lines = value.split('\n');

					for (const line of lines) {
						if (line !== '') {
							console.log(line);
							let data = JSON.parse(line);

							if ('citations' in data) {
								responseMessage.citations = data.citations;
								continue;
							}

							if ('detail' in data) {
								throw data;
							}

							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;
									}
								} else {
									responseMessage.done = true;

									if (responseMessage.content == '') {
										responseMessage.error = true;
684
										responseMessage.errorContent = 'Oops! No text generated from Ollama, Please try again.';
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
									}

									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
									};
									messages = messages;

									if ($settings.notificationEnabled && !document.hasFocus()) {
										const notification = new Notification(
											selectedModelfile
												? `${
														selectedModelfile.title.charAt(0).toUpperCase() +
														selectedModelfile.title.slice(1)
												  }`
												: `${model}`,
											{
												body: responseMessage.content,
												icon: selectedModelfile?.imageUrl ?? `${WEBUI_BASE_URL}/static/favicon.png`
											}
										);
									}

									if ($settings.responseAutoCopy) {
										copyToClipboard(responseMessage.content);
									}

									if ($settings.responseAutoPlayback) {
										await tick();
										document.getElementById(`speak-button-${responseMessage.id}`)?.click();
									}
								}
							}
						}
					}
				} catch (error) {
					console.log(error);
					if ('detail' in error) {
						toast.error(error.detail);
					}
					break;
				}

				if (autoScroll) {
					scrollToBottom();
				}
			}

			if ($chatId == _chatId) {
				if ($settings.saveChatHistory ?? true) {
					chat = await updateChatById(localStorage.token, _chatId, {
						messages: messages,
Timothy J. Baek's avatar
Timothy J. Baek committed
744
745
						history: history,
						models: selectedModels
746
747
748
749
750
751
752
753
754
755
					});
					await chats.set(await getChatList(localStorage.token));
				}
			}
		} else {
			if (res !== null) {
				const error = await res.json();
				console.log(error);
				if ('detail' in error) {
					toast.error(error.detail);
756
					responseMessage.errorContent = error.detail;
757
758
				} else {
					toast.error(error.error);
759
					responseMessage.errorContent = error.error;
760
761
762
763
764
				}
			} else {
				toast.error(
					$i18n.t(`Uh-oh! There was an issue connecting to {{provider}}.`, { provider: 'Ollama' })
				);
765
				responseMessage.errorContent = $i18n.t(`Uh-oh! There was an issue connecting to {{provider}}.`, {
766
767
768
769
770
					provider: 'Ollama'
				});
			}

			responseMessage.error = true;
771
			responseMessage.errorContent = $i18n.t(`Uh-oh! There was an issue connecting to {{provider}}.`, {
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
				provider: 'Ollama'
			});
			responseMessage.done = true;
			messages = messages;
		}

		stopResponseFlag = false;
		await tick();

		if (autoScroll) {
			scrollToBottom();
		}

		if (messages.length == 2 && messages.at(1).content !== '') {
			window.history.replaceState(history.state, '', `/c/${_chatId}`);
			const _title = await generateChatTitle(userPrompt);
			await setChatTitle(_chatId, _title);
		}
	};

	const sendPromptOpenAI = async (model, userPrompt, responseMessageId, _chatId) => {
		const responseMessage = history.messages[responseMessageId];

		const docs = messages
			.filter((message) => message?.files ?? null)
			.map((message) =>
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
798
799
800
				message.files.filter((item) =>
					['doc', 'collection', 'web_search_results'].includes(item.type)
				)
801
802
803
804
805
806
807
808
809
810
811
812
813
			)
			.flat(1);

		console.log(docs);

		scrollToBottom();

		try {
			const [res, controller] = await generateOpenAIChatCompletion(
				localStorage.token,
				{
					model: model.id,
					stream: true,
814
815
816
817
818
819
					stream_options:
						model.info?.meta?.capabilities?.usage ?? false
							? {
									include_usage: true
							  }
							: undefined,
820
821
822
823
					messages: [
						$settings.system || (responseMessage?.userContext ?? null)
							? {
									role: 'system',
824
									content: `${promptTemplate($settings?.system ?? '', $user.name)}${
825
826
827
828
829
830
831
832
										responseMessage?.userContext ?? null
											? `\n\nUser Context:\n${(responseMessage?.userContext ?? []).join('\n')}`
											: ''
									}`
							  }
							: undefined,
						...messages
					]
Yanyutin753's avatar
Yanyutin753 committed
833
						.filter((message) => message?.content?.trim())
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
						.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
														: 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
								  })
						})),
Timothy J. Baek's avatar
Timothy J. Baek committed
864
					seed: $settings?.params?.seed ?? undefined,
865
					stop:
Timothy J. Baek's avatar
Timothy J. Baek committed
866
867
						$settings?.params?.stop ?? undefined
							? $settings.params.stop.map((str) =>
868
869
870
									decodeURIComponent(JSON.parse('"' + str.replace(/\"/g, '\\"') + '"'))
							  )
							: undefined,
Timothy J. Baek's avatar
Timothy J. Baek committed
871
872
					temperature: $settings?.params?.temperature ?? undefined,
					top_p: $settings?.params?.top_p ?? undefined,
873
					frequency_penalty: $settings?.params?.frequency_penalty ?? undefined,
874
					max_tokens: $settings?.params?.max_tokens ?? undefined,
875
					docs: docs.length > 0 ? docs : undefined,
876
877
					citations: docs.length > 0,
					chat_id: $chatId
878
				},
Timothy J. Baek's avatar
Timothy J. Baek committed
879
				`${OPENAI_API_BASE_URL}`
880
881
882
883
884
885
886
887
888
			);

			// Wait until history/message have been updated
			await tick();

			scrollToBottom();

			if (res && res.ok && res.body) {
				const textStream = await createOpenAITextStream(res.body, $settings.splitLargeChunks);
889
				let lastUsage = null;
890
891

				for await (const update of textStream) {
892
					const { value, done, citations, error, usage } = update;
893
894
895
896
897
898
899
900
901
902
					if (error) {
						await handleOpenAIError(error, null, model, responseMessage);
						break;
					}
					if (done || stopResponseFlag || _chatId !== $chatId) {
						responseMessage.done = true;
						messages = messages;

						if (stopResponseFlag) {
							controller.abort('User: Stop Response');
903
						} else {
904
905
							const messages = createMessagesList(responseMessageId);

906
							const res = await chatCompleted(localStorage.token, {
Timothy J. Baek's avatar
Timothy J. Baek committed
907
								model: model.id,
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
								messages: messages.map((m) => ({
									id: m.id,
									role: m.role,
									content: m.content,
									timestamp: m.timestamp
								})),
								chat_id: $chatId
							}).catch((error) => {
								console.error(error);
								return null;
							});

							if (res !== null) {
								// Update chat history with the new messages
								for (const message of res.messages) {
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
923
924
925
926
927
928
929
									history.messages[message.id] = {
										...history.messages[message.id],
										...(history.messages[message.id].content !== message.content
											? { originalContent: history.messages[message.id].content }
											: {}),
										...message
									};
930
931
								}
							}
932
933
934
935
936
						}

						break;
					}

937
938
939
940
					if (usage) {
						lastUsage = usage;
					}

941
942
943
944
945
946
947
948
949
950
951
952
					if (citations) {
						responseMessage.citations = citations;
						continue;
					}

					if (responseMessage.content == '' && value == '\n') {
						continue;
					} else {
						responseMessage.content += value;
						messages = messages;
					}

953
954
					if (autoScroll) {
						scrollToBottom();
955
					}
956
				}
957

958
959
960
961
962
963
				if ($settings.notificationEnabled && !document.hasFocus()) {
					const notification = new Notification(`OpenAI ${model}`, {
						body: responseMessage.content,
						icon: `${WEBUI_BASE_URL}/static/favicon.png`
					});
				}
964

965
966
967
				if ($settings.responseAutoCopy) {
					copyToClipboard(responseMessage.content);
				}
968

969
970
971
				if ($settings.responseAutoPlayback) {
					await tick();
					document.getElementById(`speak-button-${responseMessage.id}`)?.click();
972
973
				}

974
975
976
977
				if (lastUsage) {
					responseMessage.info = { ...lastUsage, openai: true };
				}

978
979
980
				if ($chatId == _chatId) {
					if ($settings.saveChatHistory ?? true) {
						chat = await updateChatById(localStorage.token, _chatId, {
Timothy J. Baek's avatar
Timothy J. Baek committed
981
							models: selectedModels,
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
							messages: messages,
							history: history
						});
						await chats.set(await getChatList(localStorage.token));
					}
				}
			} else {
				await handleOpenAIError(null, res, model, responseMessage);
			}
		} catch (error) {
			await handleOpenAIError(error, null, model, responseMessage);
		}
		messages = messages;

		stopResponseFlag = false;
		await tick();

		if (autoScroll) {
			scrollToBottom();
		}

		if (messages.length == 2) {
			window.history.replaceState(history.state, '', `/c/${_chatId}`);

			const _title = await generateChatTitle(userPrompt);
			await setChatTitle(_chatId, _title);
		}
	};

	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;
		}

		responseMessage.error = true;
1038
		responseMessage.errorContent =
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
			$i18n.t(`Uh-oh! There was an issue connecting to {{provider}}.`, {
				provider: model.name ?? model.id
			}) +
			'\n' +
			errorMessage;
		responseMessage.done = true;

		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) {
				await sendPrompt(userPrompt, userMessage.id);
			} else {
				await sendPrompt(userPrompt, userMessage.id, message.model);
			}
		}
	};

	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) {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1081
				if (model?.owned_by === 'openai') {
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
					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 model = $models.find((model) => model.id === selectedModels[0]);

			const titleModelId =
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1106
				model?.owned_by === 'openai' ?? false
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
					? $settings?.title?.modelExternal ?? selectedModels[0]
					: $settings?.title?.model ?? selectedModels[0];
			const titleModel = $models.find((model) => model.id === titleModelId);

			console.log(titleModel);
			const title = await generateTitle(
				localStorage.token,
				$settings?.title?.prompt ??
					$i18n.t(
						"Create a concise, 3-5 word phrase as a header for the following query, strictly adhering to the 3-5 word limit and avoiding the use of the word 'title':"
					) + ' {{prompt}}',
				titleModelId,
				userPrompt,
Timothy J. Baek's avatar
Timothy J. Baek committed
1120
				$chatId,
1121
1122
				titleModel?.owned_by === 'openai' ?? false
					? `${OPENAI_API_BASE_URL}`
1123
1124
1125
1126
1127
1128
1129
1130
1131
					: `${OLLAMA_API_BASE_URL}/v1`
			);

			return title;
		} else {
			return `${userPrompt}`;
		}
	};

Timothy J. Baek's avatar
Timothy J. Baek committed
1132
	const generateChatSearchQuery = async (modelId: string, prompt: string) => {
1133
1134
		const model = $models.find((model) => model.id === modelId);
		const taskModelId =
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1135
			model?.owned_by === 'openai' ?? false
1136
1137
1138
				? $settings?.title?.modelExternal ?? modelId
				: $settings?.title?.model ?? modelId;
		const taskModel = $models.find((model) => model.id === taskModelId);
Timothy J. Baek's avatar
Timothy J. Baek committed
1139

1140
1141
1142
		const previousMessages = messages
			.filter((message) => message.role === 'user')
			.map((message) => message.content);
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1143

1144
1145
1146
1147
		return await generateSearchQuery(
			localStorage.token,
			taskModelId,
			previousMessages,
Timothy J. Baek's avatar
Timothy J. Baek committed
1148
			prompt,
1149
1150
			taskModel?.owned_by === 'openai' ?? false
				? `${OPENAI_API_BASE_URL}`
1151
1152
1153
1154
				: `${OLLAMA_API_BASE_URL}/v1`
		);
	};

1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
	const setChatTitle = async (_chatId, _title) => {
		if (_chatId === $chatId) {
			title = _title;
		}

		if ($settings.saveChatHistory ?? true) {
			chat = await updateChatById(localStorage.token, _chatId, { title: _title });
			await chats.set(await getChatList(localStorage.token));
		}
	};

	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();

		chat = await updateChatById(localStorage.token, $chatId, {
			tags: tags
		});

		_tags.set(await getAllChatTags(localStorage.token));
	};

	const deleteTag = async (tagName) => {
		const res = await deleteTagById(localStorage.token, $chatId, tagName);
		tags = await getTags();

		chat = await updateChatById(localStorage.token, $chatId, {
			tags: tags
		});

		_tags.set(await getAllChatTags(localStorage.token));
	};
</script>

<svelte:head>
	<title>
		{title
			? `${title.length > 30 ? `${title.slice(0, 30)}...` : title} | ${$WEBUI_NAME}`
			: `${$WEBUI_NAME}`}
	</title>
</svelte:head>

{#if !chatIdProp || (loaded && chatIdProp)}
	<div
		class="min-h-screen max-h-screen {$showSidebar
			? 'md:max-w-[calc(100%-260px)]'
			: ''} w-full max-w-full flex flex-col"
	>
		<Navbar
			{title}
			bind:selectedModels
			bind:showModelSelector
			shareEnabled={messages.length > 0}
			{chat}
			{initNewChat}
		/>
Timothy J. Baek's avatar
Timothy J. Baek committed
1217

1218
		{#if $banners.length > 0 && !$chatId && selectedModels.length <= 1}
Timothy J. Baek's avatar
Timothy J. Baek committed
1219
1220
1221
			<div
				class="absolute top-[4.25rem] w-full {$showSidebar ? 'md:max-w-[calc(100%-260px)]' : ''}"
			>
Timothy J. Baek's avatar
Timothy J. Baek committed
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
				<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>
Timothy J. Baek's avatar
Timothy J. Baek committed
1242
1243
1244
			</div>
		{/if}

1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
		<div class="flex flex-col flex-auto">
			<div
				class=" pb-2.5 flex flex-col justify-between w-full flex-auto overflow-auto h-0 max-w-full"
				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}
					/>
				</div>
			</div>
		</div>
	</div>

	<MessageInput
		bind:files
		bind:prompt
		bind:autoScroll
Timothy J. Baek's avatar
Timothy J. Baek committed
1279
		bind:webSearchEnabled
Timothy J. Baek's avatar
Timothy J. Baek committed
1280
		bind:atSelectedModel
1281
		{selectedModels}
1282
1283
1284
1285
1286
		{messages}
		{submitPrompt}
		{stopResponse}
	/>
{/if}