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

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

Timothy J. Baek's avatar
Timothy J. Baek committed
10
11
12
13
	import type { Writable } from 'svelte/store';
	import type { i18n as i18nType } from 'i18next';
	import { OLLAMA_API_BASE_URL, OPENAI_API_BASE_URL, WEBUI_BASE_URL } from '$lib/constants';

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

39
	import { generateChatCompletion } from '$lib/apis/ollama';
40
41
42
43
44
45
46
47
48
49
	import {
		addTagById,
		createNewChat,
		deleteTagById,
		getAllChatTags,
		getChatById,
		getChatList,
		getTagsById,
		updateChatById
	} from '$lib/apis/chats';
Timothy J. Baek's avatar
Timothy J. Baek committed
50
	import { generateOpenAIChatCompletion } from '$lib/apis/openai';
Timothy J. Baek's avatar
Timothy J. Baek committed
51
52
53
	import { runWebSearch } from '$lib/apis/rag';
	import { createOpenAITextStream } from '$lib/apis/streaming';
	import { queryMemory } from '$lib/apis/memories';
Timothy J. Baek's avatar
Timothy J. Baek committed
54
	import { getAndUpdateUserLocation, getUserSettings } from '$lib/apis/users';
Timothy J. Baek's avatar
Timothy J. Baek committed
55
	import { chatCompleted, generateTitle, generateSearchQuery } from '$lib/apis';
56

Timothy J. Baek's avatar
Timothy J. Baek committed
57
	import Banner from '../common/Banner.svelte';
58
59
60
	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
refac  
Timothy J. Baek committed
61
	import CallOverlay from './MessageInput/CallOverlay.svelte';
Timothy J. Baek's avatar
Timothy J. Baek committed
62
	import { error } from '@sveltejs/kit';
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
63

64
65
66
67
68
	const i18n: Writable<i18nType> = getContext('i18n');

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

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
69
70
	const eventTarget = new EventTarget();

71
72
73
74
75
76
77
78
	let stopResponseFlag = false;
	let autoScroll = true;
	let processing = '';
	let messagesContainerElement: HTMLDivElement;

	let showModelSelector = true;

	let selectedModels = [''];
79
	let atSelectedModel: Model | undefined;
80

Timothy J. Baek's avatar
Timothy J. Baek committed
81
82
83
	let selectedModelIds = [];
	$: selectedModelIds = atSelectedModel !== undefined ? [atSelectedModel.id] : selectedModels;

Timothy J. Baek's avatar
Timothy J. Baek committed
84
	let selectedToolIds = [];
Timothy J. Baek's avatar
Timothy J. Baek committed
85
	let webSearchEnabled = false;
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
	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 () => {
115
116
			console.log(chatIdProp);
			if (chatIdProp && (await loadChat())) {
117
118
119
120
121
122
123
124
125
126
127
128
129
				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
130
		if (!$chatId) {
131
132
133
134
135
			chatId.subscribe(async (value) => {
				if (!value) {
					await initNewChat();
				}
			});
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
		} else {
			if (!($settings.saveChatHistory ?? true)) {
				await goto('/');
			}
		}
	});

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

	const initNewChat = async () => {
		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) {
165
			console.log($config?.default_models.split(',') ?? '');
166
167
168
169
170
171
172
			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
173

174
175
176
177
178
179
180
181
182
183
			if (prompt) {
				await tick();
				submitPrompt(prompt);
			}
		}

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

184
185
186
187
188
189
190
		const userSettings = await getUserSettings(localStorage.token);

		if (userSettings) {
			settings.set(userSettings.ui);
		} else {
			settings.set(JSON.parse(localStorage.getItem('settings') ?? '{}'));
		}
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219

		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;

220
221
222
223
224
225
226
227
				const userSettings = await getUserSettings(localStorage.token);

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

228
				await settings.set({
229
230
231
					...$settings,
					system: chatContent.system ?? $settings.system,
					params: chatContent.options ?? $settings.params
232
				});
233

234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
				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;
		}
	};

256
257
258
259
260
261
262
263
264
	const createMessagesList = (responseMessageId) => {
		const message = history.messages[responseMessageId];
		if (message.parentId) {
			return [...createMessagesList(message.parentId), message];
		} else {
			return [message];
		}
	};

Timothy J. Baek's avatar
Timothy J. Baek committed
265
	const chatCompletedHandler = async (modelId, messages) => {
266
267
268
269
270
		await mermaid.run({
			querySelector: '.mermaid'
		});

		const res = await chatCompleted(localStorage.token, {
Timothy J. Baek's avatar
Timothy J. Baek committed
271
			model: modelId,
272
273
274
275
			messages: messages.map((m) => ({
				id: m.id,
				role: m.role,
				content: m.content,
Timothy J. Baek's avatar
Timothy J. Baek committed
276
				info: m.info ? m.info : undefined,
277
278
279
280
				timestamp: m.timestamp
			})),
			chat_id: $chatId
		}).catch((error) => {
Timothy J. Baek's avatar
Timothy J. Baek committed
281
282
283
			toast.error(error);
			messages.at(-1).error = { content: error };

284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
			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
				};
			}
		}
	};

301
302
303
304
305
306
307
308
309
310
	const getChatEventEmitter = async (modelId: string, chatId: string = '') => {
		return setInterval(() => {
			$socket?.emit('usage', {
				action: 'chat',
				model: modelId,
				chat_id: chatId
			});
		}, 1000);
	};

311
	//////////////////////////
Timothy J. Baek's avatar
Timothy J. Baek committed
312
	// Chat functions
313
314
	//////////////////////////

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
315
	const submitPrompt = async (userPrompt, { _raw = false } = {}) => {
316
		let _responses = [];
317
318
319
320
321
322
323
324
325
326
327
		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');
328
329
330
331
332
333
334
		} 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.`
				)
			);
Timothy J. Baek's avatar
Timothy J. Baek committed
335
336
337
338
		} else if (
			files.length > 0 &&
			files.filter((file) => file.type !== 'image' && file.status !== 'processed').length > 0
		) {
339
340
341
342
343
344
345
			// 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 {
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
346
347
348
349
350
351
352
353
			// Reset chat input textarea
			const chatTextAreaElement = document.getElementById('chat-textarea');

			if (chatTextAreaElement) {
				chatTextAreaElement.value = '';
				chatTextAreaElement.style.height = '';
			}

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
354
355
356
			const _files = JSON.parse(JSON.stringify(files));
			files = [];

Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
357
			prompt = '';
358
359
360
361
362
363
364
365
366

			// Create user message
			let userMessageId = uuidv4();
			let userMessage = {
				id: userMessageId,
				parentId: messages.length !== 0 ? messages.at(-1).id : null,
				childrenIds: [],
				role: 'user',
				content: userPrompt,
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
367
				files: _files.length > 0 ? _files : undefined,
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
				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();
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
383
			_responses = await sendPrompt(userPrompt, userMessageId, { newChat: true });
384
		}
385
386

		return _responses;
387
388
	};

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
389
	const sendPrompt = async (prompt, parentId, { modelId = null, newChat = false } = {}) => {
390
		let _responses = [];
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435

		// If modelId is provided, use it, else use selected model
		let selectedModelIds = modelId
			? [modelId]
			: atSelectedModel !== undefined
			? [atSelectedModel.id]
			: selectedModels;

		// Create response messages for each selected model
		const responseMessageIds = {};
		for (const modelId of selectedModelIds) {
			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,
					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
					];
				}

				responseMessageIds[modelId] = responseMessageId;
			}
		}
		await tick();

		// Create new chat if only one message in messages
Timothy J. Baek's avatar
Timothy J. Baek committed
436
		if (newChat && messages.length == 2) {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
			if ($settings.saveChatHistory ?? true) {
				chat = await createNewChat(localStorage.token, {
					id: $chatId,
					title: $i18n.t('New Chat'),
					models: selectedModels,
					system: $settings.system ?? undefined,
					options: {
						...($settings.params ?? {})
					},
					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();
		}

459
460
461
		const _chatId = JSON.parse(JSON.stringify($chatId));

		await Promise.all(
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
462
			selectedModelIds.map(async (modelId) => {
463
464
465
466
467
468
469
470
				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')
					);
471

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
472
					if (hasImages && !(model.info?.meta?.capabilities?.vision ?? true)) {
473
474
						toast.error(
							$i18n.t('Model {{modelName}} is not vision capable', {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
475
								modelName: model.name ?? model.id
476
477
478
							})
						);
					}
479

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
480
481
					let responseMessageId = responseMessageIds[modelId];
					let responseMessage = history.messages[responseMessageId];
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499

					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;
									}, []);
500
								}
501
502

								console.log(userContext);
503
504
							}
						}
505
506
					}
					responseMessage.userContext = userContext;
507

508
					const chatEventEmitter = await getChatEventEmitter(model.id, _chatId);
Timothy J. Baek's avatar
Timothy J. Baek committed
509
					if (webSearchEnabled) {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
510
						await getWebSearchResults(model.id, parentId, responseMessageId);
511
					}
512

513
					let _response = null;
514
					if (model?.owned_by === 'openai') {
515
						_response = await sendPromptOpenAI(model, prompt, responseMessageId, _chatId);
516
					} else if (model) {
517
						_response = await sendPromptOllama(model, prompt, responseMessageId, _chatId);
518
					}
519
					_responses.push(_response);
520
521

					if (chatEventEmitter) clearInterval(chatEventEmitter);
522
523
				} else {
					toast.error($i18n.t(`Model {{modelId}} not found`, { modelId }));
524
				}
525
			})
526
527
528
		);

		await chats.set(await getChatList(localStorage.token));
529
		return _responses;
530
531
532
	};

	const sendPromptOllama = async (model, userPrompt, responseMessageId, _chatId) => {
533
534
		let _response = null;

535
536
537
538
539
540
541
542
543
544
545
546
		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',
Timothy J. Baek's avatar
Timothy J. Baek committed
547
548
549
550
551
552
553
						content: `${promptTemplate(
							$settings?.system ?? '',
							$user.name,
							$settings?.userLocation
								? await getAndUpdateUserLocation(localStorage.token)
								: undefined
						)}${
554
555
556
557
558
559
560
561
							responseMessage?.userContext ?? null
								? `\n\nUser Context:\n${(responseMessage?.userContext ?? []).join('\n')}`
								: ''
						}`
				  }
				: undefined,
			...messages
		]
Yanyutin753's avatar
Yanyutin753 committed
562
			.filter((message) => message?.content?.trim())
563
564
565
566
			.map((message, idx, arr) => {
				// Prepare the base message object
				const baseMessage = {
					role: message.role,
Timothy J. Baek's avatar
Timothy J. Baek committed
567
					content: message.content
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
				};

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

Timothy J. Baek's avatar
Timothy J. Baek committed
598
		let files = [];
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
599
		if (model?.info?.meta?.knowledge ?? false) {
Timothy J. Baek's avatar
Timothy J. Baek committed
600
			files = model.info.meta.knowledge;
Timothy J. Baek's avatar
Timothy J. Baek committed
601
		}
Timothy J. Baek's avatar
Timothy J. Baek committed
602
		const lastUserMessage = messages.filter((message) => message.role === 'user').at(-1);
Timothy J. Baek's avatar
Timothy J. Baek committed
603

Timothy J. Baek's avatar
Timothy J. Baek committed
604
605
		files = [
			...files,
Timothy J. Baek's avatar
Timothy J. Baek committed
606
607
			...(lastUserMessage?.files?.filter((item) =>
				['doc', 'file', 'collection', 'web_search_results'].includes(item.type)
Timothy J. Baek's avatar
Timothy J. Baek committed
608
609
610
			) ?? []),
			...(responseMessage?.files?.filter((item) =>
				['doc', 'file', 'collection', 'web_search_results'].includes(item.type)
Timothy J. Baek's avatar
Timothy J. Baek committed
611
			) ?? [])
Timothy J. Baek's avatar
Timothy J. Baek committed
612
		].filter(
Timothy J. Baek's avatar
Timothy J. Baek committed
613
			// Remove duplicates
Timothy J. Baek's avatar
Timothy J. Baek committed
614
615
616
			(item, index, array) =>
				array.findIndex((i) => JSON.stringify(i) === JSON.stringify(item)) === index
		);
617

Timothy J. Baek's avatar
Timothy J. Baek committed
618
619
620
621
622
623
624
625
626
		eventTarget.dispatchEvent(
			new CustomEvent('chat:start', {
				detail: {
					id: responseMessageId
				}
			})
		);

		await tick();
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
627

628
		const [res, controller] = await generateChatCompletion(localStorage.token, {
Timothy J. Baek's avatar
Timothy J. Baek committed
629
			model: model.id,
630
631
			messages: messagesBody,
			options: {
Timothy J. Baek's avatar
Timothy J. Baek committed
632
				...($settings.params ?? {}),
633
				stop:
Timothy J. Baek's avatar
Timothy J. Baek committed
634
635
					$settings?.params?.stop ?? undefined
						? $settings.params.stop.map((str) =>
636
637
								decodeURIComponent(JSON.parse('"' + str.replace(/\"/g, '\\"') + '"'))
						  )
638
						: undefined,
639
640
				num_predict: $settings?.params?.max_tokens ?? undefined,
				repeat_penalty: $settings?.params?.frequency_penalty ?? undefined
641
642
643
			},
			format: $settings.requestFormat ?? undefined,
			keep_alive: $settings.keepAlive ?? undefined,
Timothy J. Baek's avatar
Timothy J. Baek committed
644
			tool_ids: selectedToolIds.length > 0 ? selectedToolIds : undefined,
Timothy J. Baek's avatar
Timothy J. Baek committed
645
			files: files.length > 0 ? files : undefined,
Timothy J. Baek's avatar
Timothy J. Baek committed
646
			citations: files.length > 0 ? true : undefined,
647
			chat_id: $chatId
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
		});

		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');
666
					} else {
667
						const messages = createMessagesList(responseMessageId);
Timothy J. Baek's avatar
Timothy J. Baek committed
668
						await chatCompletedHandler(model.id, messages);
669
670
					}

671
					_response = responseMessage.content;
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
					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;
							}

692
693
694
							if (data.done == false) {
								if (responseMessage.content == '' && data.message.content == '\n') {
									continue;
695
								} else {
696
									responseMessage.content += data.message.content;
Timothy J. Baek's avatar
Timothy J. Baek committed
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713

									const sentences = extractSentencesForAudio(responseMessage.content);
									sentences.pop();

									// dispatch only last sentence and make sure it hasn't been dispatched before
									if (
										sentences.length > 0 &&
										sentences[sentences.length - 1] !== responseMessage.lastSentence
									) {
										responseMessage.lastSentence = sentences[sentences.length - 1];
										eventTarget.dispatchEvent(
											new CustomEvent('chat', {
												detail: { id: responseMessageId, content: sentences[sentences.length - 1] }
											})
										);
									}

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

								if (responseMessage.content == '') {
									responseMessage.error = {
										code: 400,
										content: `Oops! No text generated from Ollama, Please try again.`
									};
								}

								responseMessage.context = data.context ?? null;
								responseMessage.info = {
									total_duration: data.total_duration,
									load_duration: data.load_duration,
									sample_count: data.sample_count,
									sample_duration: data.sample_duration,
									prompt_eval_count: data.prompt_eval_count,
									prompt_eval_duration: data.prompt_eval_duration,
									eval_count: data.eval_count,
									eval_duration: data.eval_duration
								};
								messages = messages;

								if ($settings.notificationEnabled && !document.hasFocus()) {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
740
741
742
743
									const notification = new Notification(`${model.id}`, {
										body: responseMessage.content,
										icon: `${WEBUI_BASE_URL}/static/favicon.png`
									});
744
745
								}

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
746
								if ($settings?.responseAutoCopy ?? false) {
747
748
									copyToClipboard(responseMessage.content);
								}
749

Timothy J. Baek's avatar
Timothy J. Baek committed
750
								if ($settings.responseAutoPlayback && !$showCallOverlay) {
751
752
									await tick();
									document.getElementById(`speak-button-${responseMessage.id}`)?.click();
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
								}
							}
						}
					}
				} 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
774
775
						history: history,
						models: selectedModels
776
777
778
779
780
781
782
783
784
785
					});
					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);
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
786
					responseMessage.error = { content: error.detail };
787
788
				} else {
					toast.error(error.error);
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
789
					responseMessage.error = { content: error.error };
790
791
792
793
794
				}
			} else {
				toast.error(
					$i18n.t(`Uh-oh! There was an issue connecting to {{provider}}.`, { provider: 'Ollama' })
				);
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
795
796
797
798
799
				responseMessage.error = {
					content: $i18n.t(`Uh-oh! There was an issue connecting to {{provider}}.`, {
						provider: 'Ollama'
					})
				};
800
801
802
803
804
805
806
			}
			responseMessage.done = true;
			messages = messages;
		}

		stopResponseFlag = false;
		await tick();
Timothy J. Baek's avatar
Timothy J. Baek committed
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823

		let lastSentence = extractSentencesForAudio(responseMessage.content)?.at(-1) ?? '';
		if (lastSentence) {
			eventTarget.dispatchEvent(
				new CustomEvent('chat', {
					detail: { id: responseMessageId, content: lastSentence }
				})
			);
		}
		eventTarget.dispatchEvent(
			new CustomEvent('chat:finish', {
				detail: {
					id: responseMessageId,
					content: responseMessage.content
				}
			})
		);
824
825
826
827
828
829
830
831
832
833

		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);
		}
834
835

		return _response;
836
837
838
	};

	const sendPromptOpenAI = async (model, userPrompt, responseMessageId, _chatId) => {
839
		let _response = null;
840
841
		const responseMessage = history.messages[responseMessageId];

Timothy J. Baek's avatar
Timothy J. Baek committed
842
		let files = [];
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
843
		if (model?.info?.meta?.knowledge ?? false) {
Timothy J. Baek's avatar
Timothy J. Baek committed
844
			files = model.info.meta.knowledge;
Timothy J. Baek's avatar
Timothy J. Baek committed
845
		}
Timothy J. Baek's avatar
Timothy J. Baek committed
846
		const lastUserMessage = messages.filter((message) => message.role === 'user').at(-1);
Timothy J. Baek's avatar
Timothy J. Baek committed
847
848
		files = [
			...files,
Timothy J. Baek's avatar
Timothy J. Baek committed
849
850
			...(lastUserMessage?.files?.filter((item) =>
				['doc', 'file', 'collection', 'web_search_results'].includes(item.type)
Timothy J. Baek's avatar
Timothy J. Baek committed
851
852
853
			) ?? []),
			...(responseMessage?.files?.filter((item) =>
				['doc', 'file', 'collection', 'web_search_results'].includes(item.type)
Timothy J. Baek's avatar
Timothy J. Baek committed
854
			) ?? [])
Timothy J. Baek's avatar
Timothy J. Baek committed
855
		].filter(
Timothy J. Baek's avatar
Timothy J. Baek committed
856
			// Remove duplicates
Timothy J. Baek's avatar
Timothy J. Baek committed
857
858
859
			(item, index, array) =>
				array.findIndex((i) => JSON.stringify(i) === JSON.stringify(item)) === index
		);
860
861
862

		scrollToBottom();

Timothy J. Baek's avatar
Timothy J. Baek committed
863
864
865
866
867
868
869
870
		eventTarget.dispatchEvent(
			new CustomEvent('chat:start', {
				detail: {
					id: responseMessageId
				}
			})
		);
		await tick();
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
871

872
873
874
875
876
877
		try {
			const [res, controller] = await generateOpenAIChatCompletion(
				localStorage.token,
				{
					model: model.id,
					stream: true,
878
879
880
881
882
883
					stream_options:
						model.info?.meta?.capabilities?.usage ?? false
							? {
									include_usage: true
							  }
							: undefined,
884
885
886
887
					messages: [
						$settings.system || (responseMessage?.userContext ?? null)
							? {
									role: 'system',
Timothy J. Baek's avatar
Timothy J. Baek committed
888
889
890
891
892
893
894
									content: `${promptTemplate(
										$settings?.system ?? '',
										$user.name,
										$settings?.userLocation
											? await getAndUpdateUserLocation(localStorage.token)
											: undefined
									)}${
895
896
897
898
899
900
901
902
										responseMessage?.userContext ?? null
											? `\n\nUser Context:\n${(responseMessage?.userContext ?? []).join('\n')}`
											: ''
									}`
							  }
							: undefined,
						...messages
					]
Yanyutin753's avatar
Yanyutin753 committed
903
						.filter((message) => message?.content?.trim())
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
						.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
934
					seed: $settings?.params?.seed ?? undefined,
935
					stop:
Timothy J. Baek's avatar
Timothy J. Baek committed
936
937
						$settings?.params?.stop ?? undefined
							? $settings.params.stop.map((str) =>
938
939
940
									decodeURIComponent(JSON.parse('"' + str.replace(/\"/g, '\\"') + '"'))
							  )
							: undefined,
Timothy J. Baek's avatar
Timothy J. Baek committed
941
942
					temperature: $settings?.params?.temperature ?? undefined,
					top_p: $settings?.params?.top_p ?? undefined,
943
					frequency_penalty: $settings?.params?.frequency_penalty ?? undefined,
944
					max_tokens: $settings?.params?.max_tokens ?? undefined,
Timothy J. Baek's avatar
Timothy J. Baek committed
945
					tool_ids: selectedToolIds.length > 0 ? selectedToolIds : undefined,
Timothy J. Baek's avatar
Timothy J. Baek committed
946
					files: files.length > 0 ? files : undefined,
Timothy J. Baek's avatar
Timothy J. Baek committed
947
948
					citations: files.length > 0 ? true : undefined,

949
					chat_id: $chatId
950
				},
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
951
				`${WEBUI_BASE_URL}/api`
952
953
954
955
956
957
958
959
960
			);

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

			scrollToBottom();

			if (res && res.ok && res.body) {
				const textStream = await createOpenAITextStream(res.body, $settings.splitLargeChunks);
961
				let lastUsage = null;
962
963

				for await (const update of textStream) {
964
					const { value, done, citations, error, usage } = update;
965
966
967
968
969
970
971
972
973
974
					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');
975
						} else {
976
977
							const messages = createMessagesList(responseMessageId);

Timothy J. Baek's avatar
Timothy J. Baek committed
978
							await chatCompletedHandler(model.id, messages);
979
980
						}

981
982
						_response = responseMessage.content;

983
984
985
						break;
					}

986
987
988
989
					if (usage) {
						lastUsage = usage;
					}

990
991
992
993
994
995
996
997
998
					if (citations) {
						responseMessage.citations = citations;
						continue;
					}

					if (responseMessage.content == '' && value == '\n') {
						continue;
					} else {
						responseMessage.content += value;
Timothy J. Baek's avatar
Timothy J. Baek committed
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015

						const sentences = extractSentencesForAudio(responseMessage.content);
						sentences.pop();

						// dispatch only last sentence and make sure it hasn't been dispatched before
						if (
							sentences.length > 0 &&
							sentences[sentences.length - 1] !== responseMessage.lastSentence
						) {
							responseMessage.lastSentence = sentences[sentences.length - 1];
							eventTarget.dispatchEvent(
								new CustomEvent('chat', {
									detail: { id: responseMessageId, content: sentences[sentences.length - 1] }
								})
							);
						}

1016
1017
1018
						messages = messages;
					}

1019
1020
					if (autoScroll) {
						scrollToBottom();
1021
					}
1022
				}
1023

1024
				if ($settings.notificationEnabled && !document.hasFocus()) {
Timothy J. Baek's avatar
Timothy J. Baek committed
1025
					const notification = new Notification(`${model.id}`, {
1026
1027
1028
1029
						body: responseMessage.content,
						icon: `${WEBUI_BASE_URL}/static/favicon.png`
					});
				}
1030

1031
1032
1033
				if ($settings.responseAutoCopy) {
					copyToClipboard(responseMessage.content);
				}
1034

Timothy J. Baek's avatar
Timothy J. Baek committed
1035
				if ($settings.responseAutoPlayback && !$showCallOverlay) {
1036
					await tick();
Timothy J. Baek's avatar
Timothy J. Baek committed
1037

1038
					document.getElementById(`speak-button-${responseMessage.id}`)?.click();
1039
1040
				}

1041
1042
1043
1044
				if (lastUsage) {
					responseMessage.info = { ...lastUsage, openai: true };
				}

1045
1046
1047
				if ($chatId == _chatId) {
					if ($settings.saveChatHistory ?? true) {
						chat = await updateChatById(localStorage.token, _chatId, {
Timothy J. Baek's avatar
Timothy J. Baek committed
1048
							models: selectedModels,
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
							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();

Timothy J. Baek's avatar
Timothy J. Baek committed
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
		let lastSentence = extractSentencesForAudio(responseMessage.content)?.at(-1) ?? '';
		if (lastSentence) {
			eventTarget.dispatchEvent(
				new CustomEvent('chat', {
					detail: { id: responseMessageId, content: lastSentence }
				})
			);
		}

		eventTarget.dispatchEvent(
			new CustomEvent('chat:finish', {
				detail: {
					id: responseMessageId,
					content: responseMessage.content
				}
			})
		);
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1083

1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
		if (autoScroll) {
			scrollToBottom();
		}

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

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

		return _response;
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
	};

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

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1124
		responseMessage.error = {
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
1125
1126
1127
1128
1129
1130
			content:
				$i18n.t(`Uh-oh! There was an issue connecting to {{provider}}.`, {
					provider: model.name ?? model.id
				}) +
				'\n' +
				errorMessage
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1131
		};
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
		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) {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1150
1151
				// If user message has only one model selected, sendPrompt automatically selects it for regeneration
				await sendPrompt(userPrompt, userMessage.id);
1152
			} else {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1153
1154
1155
				// If there are multiple models selected, use the model of the response message for regeneration
				// e.g. many model chat
				await sendPrompt(userPrompt, userMessage.id, { modelId: message.model });
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
			}
		}
	};

	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
1172
				if (model?.owned_by === 'openai') {
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
					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,
Timothy J. Baek's avatar
Timothy J. Baek committed
1196
				selectedModels[0],
1197
				userPrompt,
Timothy J. Baek's avatar
Timothy J. Baek committed
1198
1199
1200
1201
1202
				$chatId
			).catch((error) => {
				console.error(error);
				return 'New Chat';
			});
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220

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

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

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1221
1222
	const getWebSearchResults = async (model: string, parentId: string, responseId: string) => {
		const responseMessage = history.messages[responseId];
Timothy J. Baek's avatar
Timothy J. Baek committed
1223
		const userMessage = history.messages[parentId];
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233

		responseMessage.statusHistory = [
			{
				done: false,
				action: 'web_search',
				description: $i18n.t('Generating search query')
			}
		];
		messages = messages;

Timothy J. Baek's avatar
Timothy J. Baek committed
1234
		const prompt = userMessage.content;
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
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
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
		let searchQuery = await generateSearchQuery(localStorage.token, model, messages, prompt).catch(
			(error) => {
				console.log(error);
				return prompt;
			}
		);

		if (!searchQuery) {
			toast.warning($i18n.t('No search query generated'));
			responseMessage.statusHistory.push({
				done: true,
				error: true,
				action: 'web_search',
				description: 'No search query generated'
			});

			messages = messages;
		}

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

1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
	const getTags = async () => {
		return await getTagsById(localStorage.token, $chatId).catch(async (error) => {
			return [];
		});
	};
</script>

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

Timothy J. Baek's avatar
Timothy J. Baek committed
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
<audio id="audioElement" src="" style="display: none;" />

{#if $showCallOverlay}
	<CallOverlay
		{submitPrompt}
		{stopResponse}
		bind:files
		modelId={selectedModelIds?.at(0) ?? null}
		chatId={$chatId}
		{eventTarget}
	/>
{/if}
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1327

1328
1329
{#if !chatIdProp || (loaded && chatIdProp)}
	<div
Timothy J. Baek's avatar
Timothy J. Baek committed
1330
		class="h-screen max-h-[100dvh] {$showSidebar
1331
			? 'md:max-w-[calc(100%-260px)]'
Timothy J. Baek's avatar
Timothy J. Baek committed
1332
			: ''} w-full max-w-full flex flex-col"
1333
	>
Timothy J. Baek's avatar
Timothy J. Baek committed
1334
1335
1336
1337
1338
1339
1340
1341
1342
		{#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
Timothy J. Baek's avatar
Timothy J. Baek committed
1343
				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"
Timothy J. Baek's avatar
Timothy J. Baek committed
1344
1345
1346
			/>
		{/if}

1347
1348
1349
1350
1351
1352
1353
1354
		<Navbar
			{title}
			bind:selectedModels
			bind:showModelSelector
			shareEnabled={messages.length > 0}
			{chat}
			{initNewChat}
		/>
Timothy J. Baek's avatar
Timothy J. Baek committed
1355

Timothy J. Baek's avatar
Timothy J. Baek committed
1356
		{#if $banners.length > 0 && messages.length === 0 && !$chatId && selectedModels.length <= 1}
Timothy J. Baek's avatar
Timothy J. Baek committed
1357
			<div
Timothy J. Baek's avatar
Timothy J. Baek committed
1358
1359
				class="absolute top-[4.25rem] w-full {$showSidebar
					? 'md:max-w-[calc(100%-260px)]'
Timothy J. Baek's avatar
Timothy J. Baek committed
1360
					: ''} z-20"
Timothy J. Baek's avatar
Timothy J. Baek committed
1361
			>
Timothy J. Baek's avatar
Timothy J. Baek committed
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
				<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
1382
1383
1384
			</div>
		{/if}

Timothy J. Baek's avatar
Timothy J. Baek committed
1385
		<div class="flex flex-col flex-auto z-10">
1386
			<div
Timothy J. Baek's avatar
Timothy J. Baek committed
1387
				class=" pb-2.5 flex flex-col justify-between w-full flex-auto overflow-auto h-0 max-w-full z-10"
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
				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>
Timothy J. Baek's avatar
Timothy J. Baek committed
1412
1413
1414
1415
			<MessageInput
				bind:files
				bind:prompt
				bind:autoScroll
Timothy J. Baek's avatar
Timothy J. Baek committed
1416
				bind:selectedToolIds
Timothy J. Baek's avatar
Timothy J. Baek committed
1417
1418
				bind:webSearchEnabled
				bind:atSelectedModel
Timothy J. Baek's avatar
Timothy J. Baek committed
1419
1420
1421
1422
1423
1424
1425
				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;
				}, [])}
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1426
				transparentBackground={$settings?.backgroundImageUrl ?? false}
Timothy J. Baek's avatar
Timothy J. Baek committed
1427
1428
1429
1430
1431
				{selectedModels}
				{messages}
				{submitPrompt}
				{stopResponse}
			/>
1432
1433
1434
		</div>
	</div>
{/if}