"kubernetes/vscode:/vscode.git/clone" did not exist on "18463d935e734383cf928b0215674cc896723f20"
Chat.svelte 39.6 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
Timothy J. Baek committed
63
	import ChatControls from './ChatControls.svelte';
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
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();

Timothy J. Baek's avatar
Timothy J. Baek committed
71
	let showControls = false;
72
73
74
75
76
77
78
79
	let stopResponseFlag = false;
	let autoScroll = true;
	let processing = '';
	let messagesContainerElement: HTMLDivElement;

	let showModelSelector = true;

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

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

Timothy J. Baek's avatar
Timothy J. Baek committed
85
	let selectedToolIds = [];
Timothy J. Baek's avatar
Timothy J. Baek committed
86
	let webSearchEnabled = false;
87

88
89
90
91
92
93
94
95
96
97
98
99
	let chat = null;
	let tags = [];

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

100
101
	let params = {};

102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
	$: 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 () => {
118
119
			console.log(chatIdProp);
			if (chatIdProp && (await loadChat())) {
120
121
122
123
124
125
126
127
128
129
130
131
				await tick();
				loaded = true;

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

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
132
133
	const chatEventHandler = async (event) => {
		if (event.chat_id === $chatId) {
Timothy J. Baek's avatar
Timothy J. Baek committed
134
			await tick();
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
135
136
137
138
139
140
141
			console.log(event);
			let message = history.messages[event.message_id];

			const type = event?.data?.type ?? null;
			const data = event?.data?.data ?? null;

			if (type === 'status') {
142
				if (message.statusHistory) {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
143
					message.statusHistory.push(data);
144
				} else {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
145
					message.statusHistory = [data];
146
				}
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
147
			} else if (type === 'citation') {
148
				if (message.citations) {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
149
					message.citations.push(data);
150
				} else {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
151
					message.citations = [data];
152
				}
Timothy J. Baek's avatar
Timothy J. Baek committed
153
			} else {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
154
				console.log('Unknown message type', data);
Timothy J. Baek's avatar
Timothy J. Baek committed
155
156
157
158
159
160
			}

			messages = messages;
		}
	};

161
	onMount(async () => {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
162
		const onMessageHandler = async (event) => {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
			if (event.origin === window.origin) {
				// Replace with your iframe's origin
				console.log('Message received from iframe:', event.data);
				if (event.data.type === 'input:prompt') {
					console.log(event.data.text);

					const inputElement = document.getElementById('chat-textarea');

					if (inputElement) {
						prompt = event.data.text;
						inputElement.focus();
					}
				}

				if (event.data.type === 'action:submit') {
					console.log(event.data.text);

					if (prompt !== '') {
						await tick();
						submitPrompt(prompt);
					}
				}

				if (event.data.type === 'input:prompt:submit') {
					console.log(event.data.text);

					if (prompt !== '') {
						await tick();
						submitPrompt(event.data.text);
					}
				}
			}
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
195
196
		};
		window.addEventListener('message', onMessageHandler);
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
197

Timothy J. Baek's avatar
Timothy J. Baek committed
198
		$socket.on('chat-events', chatEventHandler);
Timothy J. Baek's avatar
Timothy J. Baek committed
199

Timothy J. Baek's avatar
Timothy J. Baek committed
200
		if (!$chatId) {
201
202
203
204
205
			chatId.subscribe(async (value) => {
				if (!value) {
					await initNewChat();
				}
			});
206
207
208
209
210
		} else {
			if (!($settings.saveChatHistory ?? true)) {
				await goto('/');
			}
		}
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
211
212
213

		return () => {
			window.removeEventListener('message', onMessageHandler);
Timothy J. Baek's avatar
Timothy J. Baek committed
214
215

			$socket.off('chat-events');
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
216
		};
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
	});

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

	const initNewChat = async () => {
		window.history.replaceState(history.state, '', `/`);
		await chatId.set('');

		autoScroll = true;

		title = '';
		messages = [];
		history = {
			messages: {},
			currentId: null
		};
235
		params = {};
236
237
238
239
240
241

		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) {
242
			console.log($config?.default_models.split(',') ?? '');
243
244
245
246
247
248
249
			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
250

251
252
253
254
255
256
257
258
259
260
			if (prompt) {
				await tick();
				submitPrompt(prompt);
			}
		}

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

261
262
263
264
265
266
267
		const userSettings = await getUserSettings(localStorage.token);

		if (userSettings) {
			settings.set(userSettings.ui);
		} else {
			settings.set(JSON.parse(localStorage.getItem('settings') ?? '{}'));
		}
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

		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;

297
298
299
300
301
302
303
304
				const userSettings = await getUserSettings(localStorage.token);

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

305
				params = chatContent?.params ?? {};
306

307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
				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;
		}
	};

329
330
331
332
333
334
335
336
337
	const createMessagesList = (responseMessageId) => {
		const message = history.messages[responseMessageId];
		if (message.parentId) {
			return [...createMessagesList(message.parentId), message];
		} else {
			return [message];
		}
	};

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
338
	const chatCompletedHandler = async (modelId, responseMessageId, messages) => {
339
340
341
342
343
		await mermaid.run({
			querySelector: '.mermaid'
		});

		const res = await chatCompleted(localStorage.token, {
Timothy J. Baek's avatar
Timothy J. Baek committed
344
			model: modelId,
345
346
347
348
			messages: messages.map((m) => ({
				id: m.id,
				role: m.role,
				content: m.content,
Timothy J. Baek's avatar
Timothy J. Baek committed
349
				info: m.info ? m.info : undefined,
350
351
				timestamp: m.timestamp
			})),
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
352
353
354
			chat_id: $chatId,
			session_id: $socket?.id,
			id: responseMessageId
355
		}).catch((error) => {
Timothy J. Baek's avatar
Timothy J. Baek committed
356
357
358
			toast.error(error);
			messages.at(-1).error = { content: error };

359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
			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
				};
			}
		}
	};

376
377
378
379
380
381
382
383
384
385
	const getChatEventEmitter = async (modelId: string, chatId: string = '') => {
		return setInterval(() => {
			$socket?.emit('usage', {
				action: 'chat',
				model: modelId,
				chat_id: chatId
			});
		}, 1000);
	};

386
	//////////////////////////
Timothy J. Baek's avatar
Timothy J. Baek committed
387
	// Chat functions
388
389
	//////////////////////////

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
390
	const submitPrompt = async (userPrompt, { _raw = false } = {}) => {
391
		let _responses = [];
392
393
394
395
396
397
398
399
400
401
402
		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');
403
404
405
406
407
408
409
		} 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
410
411
412
413
		} else if (
			files.length > 0 &&
			files.filter((file) => file.type !== 'image' && file.status !== 'processed').length > 0
		) {
414
415
416
417
418
419
420
			// 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
421
422
423
424
425
426
427
428
			// 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
429
430
431
			const _files = JSON.parse(JSON.stringify(files));
			files = [];

Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
432
			prompt = '';
433
434
435
436
437
438
439
440
441

			// 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
442
				files: _files.length > 0 ? _files : undefined,
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
				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
458
			_responses = await sendPrompt(userPrompt, userMessageId, { newChat: true });
459
		}
460
461

		return _responses;
462
463
	};

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
464
	const sendPrompt = async (prompt, parentId, { modelId = null, newChat = false } = {}) => {
465
		let _responses = [];
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510

		// 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
511
		if (newChat && messages.length == 2) {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
512
513
514
515
516
517
			if ($settings.saveChatHistory ?? true) {
				chat = await createNewChat(localStorage.token, {
					id: $chatId,
					title: $i18n.t('New Chat'),
					models: selectedModels,
					system: $settings.system ?? undefined,
518
					params: params,
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
519
520
521
522
523
524
525
526
527
528
529
530
531
					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();
		}

532
533
534
		const _chatId = JSON.parse(JSON.stringify($chatId));

		await Promise.all(
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
535
			selectedModelIds.map(async (modelId) => {
536
537
538
539
540
541
542
543
				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')
					);
544

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
545
					if (hasImages && !(model.info?.meta?.capabilities?.vision ?? true)) {
546
547
						toast.error(
							$i18n.t('Model {{modelName}} is not vision capable', {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
548
								modelName: model.name ?? model.id
549
550
551
							})
						);
					}
552

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
553
554
					let responseMessageId = responseMessageIds[modelId];
					let responseMessage = history.messages[responseMessageId];
555
556
557
558
559
560
561
562
563
564

					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) {
Timothy J. Baek's avatar
Timothy J. Baek committed
565
566
									userContext = res.documents[0].reduce((acc, doc, index) => {
										const createdAtTimestamp = res.metadatas[0][index].created_at;
567
568
569
										const createdAtDate = new Date(createdAtTimestamp * 1000)
											.toISOString()
											.split('T')[0];
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
570
571
										return `${acc}${index + 1}. [${createdAtDate}]. ${doc}\n`;
									}, '');
572
								}
573
574

								console.log(userContext);
575
576
							}
						}
577
578
					}
					responseMessage.userContext = userContext;
579

580
					const chatEventEmitter = await getChatEventEmitter(model.id, _chatId);
Timothy J. Baek's avatar
Timothy J. Baek committed
581
					if (webSearchEnabled) {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
582
						await getWebSearchResults(model.id, parentId, responseMessageId);
583
					}
584

585
					let _response = null;
586
					if (model?.owned_by === 'openai') {
587
						_response = await sendPromptOpenAI(model, prompt, responseMessageId, _chatId);
588
					} else if (model) {
589
						_response = await sendPromptOllama(model, prompt, responseMessageId, _chatId);
590
					}
591
					_responses.push(_response);
592
593

					if (chatEventEmitter) clearInterval(chatEventEmitter);
594
595
				} else {
					toast.error($i18n.t(`Model {{modelId}} not found`, { modelId }));
596
				}
597
			})
598
599
600
		);

		await chats.set(await getChatList(localStorage.token));
601
		return _responses;
602
603
604
	};

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

607
608
609
610
611
612
613
614
615
		const responseMessage = history.messages[responseMessageId];

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

		// Scroll down
		scrollToBottom();

		const messagesBody = [
616
			params?.system || $settings.system || (responseMessage?.userContext ?? null)
617
618
				? {
						role: 'system',
Timothy J. Baek's avatar
Timothy J. Baek committed
619
						content: `${promptTemplate(
620
							params?.system ?? $settings?.system ?? '',
Timothy J. Baek's avatar
Timothy J. Baek committed
621
622
623
624
625
							$user.name,
							$settings?.userLocation
								? await getAndUpdateUserLocation(localStorage.token)
								: undefined
						)}${
626
							responseMessage?.userContext ?? null
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
627
								? `\n\nUser Context:\n${responseMessage?.userContext ?? ''}`
628
629
630
631
632
633
								: ''
						}`
				  }
				: undefined,
			...messages
		]
Yanyutin753's avatar
Yanyutin753 committed
634
			.filter((message) => message?.content?.trim())
635
636
637
638
			.map((message, idx, arr) => {
				// Prepare the base message object
				const baseMessage = {
					role: message.role,
Timothy J. Baek's avatar
Timothy J. Baek committed
639
					content: message.content
640
641
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
				};

				// 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
670
		let files = [];
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
671
		if (model?.info?.meta?.knowledge ?? false) {
Timothy J. Baek's avatar
Timothy J. Baek committed
672
			files = model.info.meta.knowledge;
Timothy J. Baek's avatar
Timothy J. Baek committed
673
		}
Timothy J. Baek's avatar
Timothy J. Baek committed
674
		const lastUserMessage = messages.filter((message) => message.role === 'user').at(-1);
Timothy J. Baek's avatar
Timothy J. Baek committed
675

Timothy J. Baek's avatar
Timothy J. Baek committed
676
677
		files = [
			...files,
Timothy J. Baek's avatar
Timothy J. Baek committed
678
679
			...(lastUserMessage?.files?.filter((item) =>
				['doc', 'file', 'collection', 'web_search_results'].includes(item.type)
Timothy J. Baek's avatar
Timothy J. Baek committed
680
681
682
			) ?? []),
			...(responseMessage?.files?.filter((item) =>
				['doc', 'file', 'collection', 'web_search_results'].includes(item.type)
Timothy J. Baek's avatar
Timothy J. Baek committed
683
			) ?? [])
Timothy J. Baek's avatar
Timothy J. Baek committed
684
		].filter(
Timothy J. Baek's avatar
Timothy J. Baek committed
685
			// Remove duplicates
Timothy J. Baek's avatar
Timothy J. Baek committed
686
687
688
			(item, index, array) =>
				array.findIndex((i) => JSON.stringify(i) === JSON.stringify(item)) === index
		);
689

Timothy J. Baek's avatar
Timothy J. Baek committed
690
691
692
693
694
695
696
697
698
		eventTarget.dispatchEvent(
			new CustomEvent('chat:start', {
				detail: {
					id: responseMessageId
				}
			})
		);

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

700
		const [res, controller] = await generateChatCompletion(localStorage.token, {
701
			stream: true,
Timothy J. Baek's avatar
Timothy J. Baek committed
702
			model: model.id,
703
704
			messages: messagesBody,
			options: {
705
				...(params ?? $settings.params ?? {}),
706
				stop:
707
708
					params?.stop ?? $settings?.params?.stop ?? undefined
						? (params?.stop ?? $settings.params.stop).map((str) =>
709
710
								decodeURIComponent(JSON.parse('"' + str.replace(/\"/g, '\\"') + '"'))
						  )
711
						: undefined,
712
713
714
				num_predict: params?.max_tokens ?? $settings?.params?.max_tokens ?? undefined,
				repeat_penalty:
					params?.frequency_penalty ?? $settings?.params?.frequency_penalty ?? undefined
715
716
717
			},
			format: $settings.requestFormat ?? undefined,
			keep_alive: $settings.keepAlive ?? undefined,
Timothy J. Baek's avatar
Timothy J. Baek committed
718
			tool_ids: selectedToolIds.length > 0 ? selectedToolIds : undefined,
Timothy J. Baek's avatar
Timothy J. Baek committed
719
			files: files.length > 0 ? files : undefined,
Timothy J. Baek's avatar
Timothy J. Baek committed
720
			session_id: $socket?.id,
721
722
			chat_id: $chatId,
			id: responseMessageId
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
		});

		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');
741
					} else {
742
						const messages = createMessagesList(responseMessageId);
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
743
						await chatCompletedHandler(model.id, responseMessageId, messages);
744
745
					}

746
					_response = responseMessage.content;
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
					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;
							}

767
768
769
							if (data.done == false) {
								if (responseMessage.content == '' && data.message.content == '\n') {
									continue;
770
								} else {
771
									responseMessage.content += data.message.content;
Timothy J. Baek's avatar
Timothy J. Baek committed
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788

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

789
									messages = messages;
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
								}
							} 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
815
816
817
818
									const notification = new Notification(`${model.id}`, {
										body: responseMessage.content,
										icon: `${WEBUI_BASE_URL}/static/favicon.png`
									});
819
820
								}

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
821
								if ($settings?.responseAutoCopy ?? false) {
822
823
									copyToClipboard(responseMessage.content);
								}
824

Timothy J. Baek's avatar
Timothy J. Baek committed
825
								if ($settings.responseAutoPlayback && !$showCallOverlay) {
826
827
									await tick();
									document.getElementById(`speak-button-${responseMessage.id}`)?.click();
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
								}
							}
						}
					}
				} 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
849
						history: history,
850
851
						models: selectedModels,
						params: params
852
853
854
855
856
857
858
859
860
861
					});
					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
862
					responseMessage.error = { content: error.detail };
863
864
				} else {
					toast.error(error.error);
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
865
					responseMessage.error = { content: error.error };
866
867
868
869
870
				}
			} 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
871
872
873
874
875
				responseMessage.error = {
					content: $i18n.t(`Uh-oh! There was an issue connecting to {{provider}}.`, {
						provider: 'Ollama'
					})
				};
876
877
878
879
880
881
882
			}
			responseMessage.done = true;
			messages = messages;
		}

		stopResponseFlag = false;
		await tick();
Timothy J. Baek's avatar
Timothy J. Baek committed
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899

		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
				}
			})
		);
900
901
902
903
904
905
906
907
908
909

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

		return _response;
912
913
914
	};

	const sendPromptOpenAI = async (model, userPrompt, responseMessageId, _chatId) => {
915
		let _response = null;
916
917
		const responseMessage = history.messages[responseMessageId];

Timothy J. Baek's avatar
Timothy J. Baek committed
918
		let files = [];
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
919
		if (model?.info?.meta?.knowledge ?? false) {
Timothy J. Baek's avatar
Timothy J. Baek committed
920
			files = model.info.meta.knowledge;
Timothy J. Baek's avatar
Timothy J. Baek committed
921
		}
Timothy J. Baek's avatar
Timothy J. Baek committed
922
		const lastUserMessage = messages.filter((message) => message.role === 'user').at(-1);
Timothy J. Baek's avatar
Timothy J. Baek committed
923
924
		files = [
			...files,
Timothy J. Baek's avatar
Timothy J. Baek committed
925
926
			...(lastUserMessage?.files?.filter((item) =>
				['doc', 'file', 'collection', 'web_search_results'].includes(item.type)
Timothy J. Baek's avatar
Timothy J. Baek committed
927
928
929
			) ?? []),
			...(responseMessage?.files?.filter((item) =>
				['doc', 'file', 'collection', 'web_search_results'].includes(item.type)
Timothy J. Baek's avatar
Timothy J. Baek committed
930
			) ?? [])
Timothy J. Baek's avatar
Timothy J. Baek committed
931
		].filter(
Timothy J. Baek's avatar
Timothy J. Baek committed
932
			// Remove duplicates
Timothy J. Baek's avatar
Timothy J. Baek committed
933
934
935
			(item, index, array) =>
				array.findIndex((i) => JSON.stringify(i) === JSON.stringify(item)) === index
		);
936
937
938

		scrollToBottom();

Timothy J. Baek's avatar
Timothy J. Baek committed
939
940
941
942
943
944
945
946
		eventTarget.dispatchEvent(
			new CustomEvent('chat:start', {
				detail: {
					id: responseMessageId
				}
			})
		);
		await tick();
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
947

948
949
950
951
952
		try {
			const [res, controller] = await generateOpenAIChatCompletion(
				localStorage.token,
				{
					stream: true,
953
					model: model.id,
954
955
956
957
958
959
					stream_options:
						model.info?.meta?.capabilities?.usage ?? false
							? {
									include_usage: true
							  }
							: undefined,
960
					messages: [
961
						params?.system || $settings.system || (responseMessage?.userContext ?? null)
962
963
							? {
									role: 'system',
Timothy J. Baek's avatar
Timothy J. Baek committed
964
									content: `${promptTemplate(
965
										params?.system ?? $settings?.system ?? '',
Timothy J. Baek's avatar
Timothy J. Baek committed
966
967
968
969
970
										$user.name,
										$settings?.userLocation
											? await getAndUpdateUserLocation(localStorage.token)
											: undefined
									)}${
971
										responseMessage?.userContext ?? null
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
972
											? `\n\nUser Context:\n${responseMessage?.userContext ?? ''}`
973
974
975
976
977
978
											: ''
									}`
							  }
							: undefined,
						...messages
					]
Yanyutin753's avatar
Yanyutin753 committed
979
						.filter((message) => message?.content?.trim())
980
981
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
						.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
								  })
						})),
1010
					seed: params?.seed ?? $settings?.params?.seed ?? undefined,
1011
					stop:
1012
1013
						params?.stop ?? $settings?.params?.stop ?? undefined
							? (params?.stop ?? $settings.params.stop).map((str) =>
1014
1015
1016
									decodeURIComponent(JSON.parse('"' + str.replace(/\"/g, '\\"') + '"'))
							  )
							: undefined,
1017
1018
1019
1020
1021
					temperature: params?.temperature ?? $settings?.params?.temperature ?? undefined,
					top_p: params?.top_p ?? $settings?.params?.top_p ?? undefined,
					frequency_penalty:
						params?.frequency_penalty ?? $settings?.params?.frequency_penalty ?? undefined,
					max_tokens: params?.max_tokens ?? $settings?.params?.max_tokens ?? undefined,
Timothy J. Baek's avatar
Timothy J. Baek committed
1022
					tool_ids: selectedToolIds.length > 0 ? selectedToolIds : undefined,
Timothy J. Baek's avatar
Timothy J. Baek committed
1023
					files: files.length > 0 ? files : undefined,
Timothy J. Baek's avatar
Timothy J. Baek committed
1024
					session_id: $socket?.id,
1025
1026
					chat_id: $chatId,
					id: responseMessageId
1027
				},
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1028
				`${WEBUI_BASE_URL}/api`
1029
1030
1031
1032
1033
1034
1035
1036
1037
			);

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

			scrollToBottom();

			if (res && res.ok && res.body) {
				const textStream = await createOpenAITextStream(res.body, $settings.splitLargeChunks);
1038
				let lastUsage = null;
1039
1040

				for await (const update of textStream) {
1041
					const { value, done, citations, error, usage } = update;
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
					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');
1052
						} else {
1053
1054
							const messages = createMessagesList(responseMessageId);

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1055
							await chatCompletedHandler(model.id, responseMessageId, messages);
1056
1057
						}

1058
1059
						_response = responseMessage.content;

1060
1061
1062
						break;
					}

1063
1064
1065
1066
					if (usage) {
						lastUsage = usage;
					}

1067
1068
1069
1070
1071
1072
1073
1074
1075
					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
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092

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

1093
1094
1095
						messages = messages;
					}

1096
1097
					if (autoScroll) {
						scrollToBottom();
1098
					}
1099
				}
1100

1101
				if ($settings.notificationEnabled && !document.hasFocus()) {
Timothy J. Baek's avatar
Timothy J. Baek committed
1102
					const notification = new Notification(`${model.id}`, {
1103
1104
1105
1106
						body: responseMessage.content,
						icon: `${WEBUI_BASE_URL}/static/favicon.png`
					});
				}
1107

1108
1109
1110
				if ($settings.responseAutoCopy) {
					copyToClipboard(responseMessage.content);
				}
1111

Timothy J. Baek's avatar
Timothy J. Baek committed
1112
				if ($settings.responseAutoPlayback && !$showCallOverlay) {
1113
					await tick();
Timothy J. Baek's avatar
Timothy J. Baek committed
1114

1115
					document.getElementById(`speak-button-${responseMessage.id}`)?.click();
1116
1117
				}

1118
1119
1120
1121
				if (lastUsage) {
					responseMessage.info = { ...lastUsage, openai: true };
				}

1122
1123
1124
				if ($chatId == _chatId) {
					if ($settings.saveChatHistory ?? true) {
						chat = await updateChatById(localStorage.token, _chatId, {
Timothy J. Baek's avatar
Timothy J. Baek committed
1125
							models: selectedModels,
1126
							messages: messages,
1127
1128
							history: history,
							params: params
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
						});
						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
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
		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
1161

1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
		if (autoScroll) {
			scrollToBottom();
		}

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

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

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

	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
1202
		responseMessage.error = {
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
1203
1204
1205
1206
1207
1208
			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
1209
		};
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
		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
1228
1229
				// If user message has only one model selected, sendPrompt automatically selects it for regeneration
				await sendPrompt(userPrompt, userMessage.id);
1230
			} else {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1231
1232
1233
				// 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 });
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
			}
		}
	};

	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
1250
				if (model?.owned_by === 'openai') {
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
					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
1274
				selectedModels[0],
1275
				userPrompt,
Timothy J. Baek's avatar
Timothy J. Baek committed
1276
1277
1278
1279
1280
				$chatId
			).catch((error) => {
				console.error(error);
				return 'New Chat';
			});
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298

			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
1299
1300
	const getWebSearchResults = async (model: string, parentId: string, responseId: string) => {
		const responseMessage = history.messages[responseId];
Timothy J. Baek's avatar
Timothy J. Baek committed
1301
		const userMessage = history.messages[parentId];
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311

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

Timothy J. Baek's avatar
Timothy J. Baek committed
1312
		const prompt = userMessage.content;
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
		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;
		}
	};

1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
	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
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
<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
1405

1406
1407
{#if !chatIdProp || (loaded && chatIdProp)}
	<div
Timothy J. Baek's avatar
Timothy J. Baek committed
1408
		class="h-screen max-h-[100dvh] {$showSidebar
1409
			? 'md:max-w-[calc(100%-260px)]'
Timothy J. Baek's avatar
Timothy J. Baek committed
1410
			: ''} w-full max-w-full flex flex-col"
1411
	>
Timothy J. Baek's avatar
Timothy J. Baek committed
1412
1413
1414
1415
1416
1417
1418
1419
1420
		{#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
1421
				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
1422
1423
1424
			/>
		{/if}

1425
1426
1427
1428
		<Navbar
			{title}
			bind:selectedModels
			bind:showModelSelector
Timothy J. Baek's avatar
Timothy J. Baek committed
1429
			bind:showControls
1430
1431
1432
1433
			shareEnabled={messages.length > 0}
			{chat}
			{initNewChat}
		/>
Timothy J. Baek's avatar
Timothy J. Baek committed
1434

Timothy J. Baek's avatar
Timothy J. Baek committed
1435
		{#if $banners.length > 0 && messages.length === 0 && !$chatId && selectedModels.length <= 1}
Timothy J. Baek's avatar
Timothy J. Baek committed
1436
			<div
Timothy J. Baek's avatar
Timothy J. Baek committed
1437
1438
				class="absolute top-[4.25rem] w-full {$showSidebar
					? 'md:max-w-[calc(100%-260px)]'
Timothy J. Baek's avatar
Timothy J. Baek committed
1439
					: ''} z-20"
Timothy J. Baek's avatar
Timothy J. Baek committed
1440
			>
Timothy J. Baek's avatar
Timothy J. Baek committed
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
				<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
1461
1462
1463
			</div>
		{/if}

1464
		<div class="flex flex-col flex-auto z-10">
1465
			<div
1466
1467
1468
				class=" pb-2.5 flex flex-col justify-between w-full flex-auto overflow-auto h-0 max-w-full z-10 scrollbar-hidden {showControls
					? 'lg:pr-[24rem]'
					: ''}"
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
				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
1493

1494
			<div class={showControls ? 'lg:pr-[24rem]' : ''}>
Timothy J. Baek's avatar
Timothy J. Baek committed
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
				<MessageInput
					bind:files
					bind:prompt
					bind:autoScroll
					bind:selectedToolIds
					bind:webSearchEnabled
					bind:atSelectedModel
					availableToolIds={selectedModelIds.reduce((a, e, i, arr) => {
						const model = $models.find((m) => m.id === e);
						if (model?.info?.meta?.toolIds ?? false) {
							return [...new Set([...a, ...model.info.meta.toolIds])];
						}
						return a;
					}, [])}
					transparentBackground={$settings?.backgroundImageUrl ?? false}
					{selectedModels}
					{messages}
					{submitPrompt}
					{stopResponse}
				/>
			</div>
1516
		</div>
1517
1518

		<ChatControls bind:show={showControls} bind:params />
1519
1520
	</div>
{/if}