Chat.svelte 43.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
		showCallOverlay,
28
		tools,
29
		currentChatPage
30
	} from '$lib/stores';
31
32
33
	import {
		convertMessagesToHistory,
		copyToClipboard,
Timothy J. Baek's avatar
Timothy J. Baek committed
34
		extractSentencesForAudio,
Timothy J. Baek's avatar
Timothy J. Baek committed
35
		getUserPosition,
36
37
38
		promptTemplate,
		splitStream
	} from '$lib/utils';
39

40
	import { generateChatCompletion } from '$lib/apis/ollama';
41
42
43
44
45
46
47
48
49
50
	import {
		addTagById,
		createNewChat,
		deleteTagById,
		getAllChatTags,
		getChatById,
		getChatList,
		getTagsById,
		updateChatById
	} from '$lib/apis/chats';
Timothy J. Baek's avatar
Timothy J. Baek committed
51
	import { generateOpenAIChatCompletion } from '$lib/apis/openai';
Timothy J. Baek's avatar
Timothy J. Baek committed
52
53
54
	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
55
	import { getAndUpdateUserLocation, getUserSettings } from '$lib/apis/users';
56
	import { chatCompleted, generateTitle, generateSearchQuery, chatAction } from '$lib/apis';
57

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

67
68
69
70
	const i18n: Writable<i18nType> = getContext('i18n');

	export let chatIdProp = '';
	let loaded = false;
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
71
72
	const eventTarget = new EventTarget();

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

Timothy J. Baek's avatar
Timothy J. Baek committed
79
80
81
	let showEventConfirmation = false;
	let eventConfirmationTitle = '';
	let eventConfirmationMessage = '';
Timothy J. Baek's avatar
Timothy J. Baek committed
82
83
	let eventConfirmationInput = false;
	let eventConfirmationInputPlaceholder = '';
84
	let eventConfirmationInputValue = '';
Timothy J. Baek's avatar
Timothy J. Baek committed
85
86
	let eventCallback = null;

87
88
89
	let showModelSelector = true;

	let selectedModels = [''];
90
	let atSelectedModel: Model | undefined;
91

Timothy J. Baek's avatar
Timothy J. Baek committed
92
93
94
	let selectedModelIds = [];
	$: selectedModelIds = atSelectedModel !== undefined ? [atSelectedModel.id] : selectedModels;

Timothy J. Baek's avatar
Timothy J. Baek committed
95
	let selectedToolIds = [];
Timothy J. Baek's avatar
Timothy J. Baek committed
96
	let webSearchEnabled = false;
97

98
99
100
101
102
	let chat = null;
	let tags = [];

	let title = '';
	let prompt = '';
Timothy J. Baek's avatar
Timothy J. Baek committed
103
104

	let chatFiles = [];
105
106
107
108
109
110
111
	let files = [];
	let messages = [];
	let history = {
		messages: {},
		currentId: null
	};

112
113
	let params = {};

114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
	$: 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 () => {
130
131
			console.log(chatIdProp);
			if (chatIdProp && (await loadChat())) {
132
133
134
135
136
137
138
139
140
141
142
143
				await tick();
				loaded = true;

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

Timothy J. Baek's avatar
Timothy J. Baek committed
144
	const chatEventHandler = async (event, cb) => {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
145
		if (event.chat_id === $chatId) {
Timothy J. Baek's avatar
Timothy J. Baek committed
146
			await tick();
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
147
148
149
150
151
152
153
			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') {
Timothy J. Baek's avatar
Timothy J. Baek committed
154
				if (message?.statusHistory) {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
155
					message.statusHistory.push(data);
156
				} else {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
157
					message.statusHistory = [data];
158
				}
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
159
			} else if (type === 'citation') {
Timothy J. Baek's avatar
Timothy J. Baek committed
160
				if (message?.citations) {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
161
					message.citations.push(data);
162
				} else {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
163
					message.citations = [data];
164
				}
Timothy J. Baek's avatar
Timothy J. Baek committed
165
166
			} else if (type === 'message') {
				message.content += data.content;
Timothy J. Baek's avatar
Timothy J. Baek committed
167
168
			} else if (type === 'replace') {
				message.content = data.content;
Timothy J. Baek's avatar
Timothy J. Baek committed
169
170
			} else if (type === 'confirmation') {
				eventCallback = cb;
Timothy J. Baek's avatar
Timothy J. Baek committed
171
172
173
174
175
176
177
178
179
180

				eventConfirmationInput = false;
				showEventConfirmation = true;

				eventConfirmationTitle = data.title;
				eventConfirmationMessage = data.message;
			} else if (type === 'input') {
				eventCallback = cb;

				eventConfirmationInput = true;
Timothy J. Baek's avatar
Timothy J. Baek committed
181
182
183
184
				showEventConfirmation = true;

				eventConfirmationTitle = data.title;
				eventConfirmationMessage = data.message;
Timothy J. Baek's avatar
Timothy J. Baek committed
185
				eventConfirmationInputPlaceholder = data.placeholder;
186
				eventConfirmationInputValue = data?.value ?? '';
Timothy J. Baek's avatar
Timothy J. Baek committed
187
			} else {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
188
				console.log('Unknown message type', data);
Timothy J. Baek's avatar
Timothy J. Baek committed
189
190
191
192
193
194
			}

			messages = messages;
		}
	};

195
	onMount(async () => {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
196
		const onMessageHandler = async (event) => {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
			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
229
230
		};
		window.addEventListener('message', onMessageHandler);
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
231

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

Timothy J. Baek's avatar
Timothy J. Baek committed
234
		if (!$chatId) {
235
236
237
238
239
			chatId.subscribe(async (value) => {
				if (!value) {
					await initNewChat();
				}
			});
240
241
242
243
244
		} else {
			if (!($settings.saveChatHistory ?? true)) {
				await goto('/');
			}
		}
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
245
246
247

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

			$socket.off('chat-events');
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
250
		};
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
	});

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

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

		autoScroll = true;

		title = '';
		messages = [];
		history = {
			messages: {},
			currentId: null
		};
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
269
270

		chatFiles = [];
271
		params = {};
272
273
274
275
276
277

		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) {
278
			console.log($config?.default_models.split(',') ?? '');
279
280
281
282
283
284
285
			selectedModels = $config?.default_models.split(',');
		} else {
			selectedModels = [''];
		}

		if ($page.url.searchParams.get('q')) {
			prompt = $page.url.searchParams.get('q') ?? '';
286
287
288
289
			selectedToolIds = ($page.url.searchParams.get('tool_ids') ?? '')
				.split(',')
				.map((id) => id.trim())
				.filter((id) => id);
Timothy J. Baek's avatar
Timothy J. Baek committed
290

291
292
293
294
295
296
297
298
299
300
			if (prompt) {
				await tick();
				submitPrompt(prompt);
			}
		}

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

301
302
303
304
305
306
307
		const userSettings = await getUserSettings(localStorage.token);

		if (userSettings) {
			settings.set(userSettings.ui);
		} else {
			settings.set(JSON.parse(localStorage.getItem('settings') ?? '{}'));
		}
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336

		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;

337
338
339
340
341
342
343
344
				const userSettings = await getUserSettings(localStorage.token);

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

345
				params = chatContent?.params ?? {};
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
346
				chatFiles = chatContent?.files ?? [];
347

348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
				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;
		}
	};

370
371
372
373
374
375
376
377
378
	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
379
	const chatCompletedHandler = async (chatId, modelId, responseMessageId, messages) => {
380
381
382
383
384
		await mermaid.run({
			querySelector: '.mermaid'
		});

		const res = await chatCompleted(localStorage.token, {
Timothy J. Baek's avatar
Timothy J. Baek committed
385
			model: modelId,
386
387
388
389
			messages: messages.map((m) => ({
				id: m.id,
				role: m.role,
				content: m.content,
Timothy J. Baek's avatar
Timothy J. Baek committed
390
				info: m.info ? m.info : undefined,
391
392
				timestamp: m.timestamp
			})),
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
393
			chat_id: chatId,
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
394
395
			session_id: $socket?.id,
			id: responseMessageId
396
		}).catch((error) => {
Timothy J. Baek's avatar
Timothy J. Baek committed
397
398
399
			toast.error(error);
			messages.at(-1).error = { content: error };

400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
			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
				};
			}
		}
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
415
416
417
418
419
420
421

		if ($chatId == chatId) {
			if ($settings.saveChatHistory ?? true) {
				chat = await updateChatById(localStorage.token, chatId, {
					models: selectedModels,
					messages: messages,
					history: history,
Timothy J. Baek's avatar
Timothy J. Baek committed
422
423
					params: params,
					files: chatFiles
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
424
				});
425

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
426
				currentChatPage.set(1);
427
				await chats.set(await getChatList(localStorage.token, $currentChatPage));
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
428
429
			}
		}
430
431
	};

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
432
	const chatActionHandler = async (chatId, actionId, modelId, responseMessageId) => {
433
434
435
436
437
438
439
440
441
		const res = await chatAction(localStorage.token, actionId, {
			model: modelId,
			messages: messages.map((m) => ({
				id: m.id,
				role: m.role,
				content: m.content,
				info: m.info ? m.info : undefined,
				timestamp: m.timestamp
			})),
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
442
			chat_id: chatId,
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
			session_id: $socket?.id,
			id: responseMessageId
		}).catch((error) => {
			toast.error(error);
			messages.at(-1).error = { content: error };
			return null;
		});

		if (res !== null) {
			// Update chat history with the new messages
			for (const message of res.messages) {
				history.messages[message.id] = {
					...history.messages[message.id],
					...(history.messages[message.id].content !== message.content
						? { originalContent: history.messages[message.id].content }
						: {}),
					...message
				};
			}
		}
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
463
464
465
466
467
468
469

		if ($chatId == chatId) {
			if ($settings.saveChatHistory ?? true) {
				chat = await updateChatById(localStorage.token, chatId, {
					models: selectedModels,
					messages: messages,
					history: history,
Timothy J. Baek's avatar
Timothy J. Baek committed
470
471
					params: params,
					files: chatFiles
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
472
				});
473

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
474
				currentChatPage.set(1);
475
				await chats.set(await getChatList(localStorage.token, $currentChatPage));
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
476
477
			}
		}
478
479
	};

480
481
482
483
484
485
486
487
488
489
	const getChatEventEmitter = async (modelId: string, chatId: string = '') => {
		return setInterval(() => {
			$socket?.emit('usage', {
				action: 'chat',
				model: modelId,
				chat_id: chatId
			});
		}, 1000);
	};

490
	//////////////////////////
Timothy J. Baek's avatar
Timothy J. Baek committed
491
	// Chat functions
492
493
	//////////////////////////

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
494
	const submitPrompt = async (userPrompt, { _raw = false } = {}) => {
495
		let _responses = [];
496
497
498
499
500
501
502
503
504
505
506
		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');
507
508
509
510
511
512
513
		} 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
514
515
516
517
		} else if (
			files.length > 0 &&
			files.filter((file) => file.type !== 'image' && file.status !== 'processed').length > 0
		) {
518
519
520
521
522
523
524
			// 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
525
526
527
528
529
530
531
532
			// 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
533
			const _files = JSON.parse(JSON.stringify(files));
Timothy J. Baek's avatar
Timothy J. Baek committed
534
535
536
537
538
539
540
			chatFiles.push(..._files.filter((item) => ['doc', 'file', 'collection'].includes(item.type)));
			chatFiles = chatFiles.filter(
				// Remove duplicates
				(item, index, array) =>
					array.findIndex((i) => JSON.stringify(i) === JSON.stringify(item)) === index
			);

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
541
542
			files = [];

Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
543
			prompt = '';
544
545
546
547
548
549
550
551
552

			// 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
553
				files: _files.length > 0 ? _files : undefined,
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
				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
569
			_responses = await sendPrompt(userPrompt, userMessageId, { newChat: true });
570
		}
571
572

		return _responses;
573
574
	};

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
575
	const sendPrompt = async (prompt, parentId, { modelId = null, newChat = false } = {}) => {
576
		let _responses = [];
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
577
578
579
580
581

		// If modelId is provided, use it, else use selected model
		let selectedModelIds = modelId
			? [modelId]
			: atSelectedModel !== undefined
Timothy J. Baek's avatar
Timothy J. Baek committed
582
583
				? [atSelectedModel.id]
				: selectedModels;
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621

		// 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
622
		if (newChat && messages.length == 2) {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
623
624
625
626
627
628
			if ($settings.saveChatHistory ?? true) {
				chat = await createNewChat(localStorage.token, {
					id: $chatId,
					title: $i18n.t('New Chat'),
					models: selectedModels,
					system: $settings.system ?? undefined,
629
					params: params,
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
630
631
632
633
634
					messages: messages,
					history: history,
					tags: [],
					timestamp: Date.now()
				});
635

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
636
				currentChatPage.set(1);
637
				await chats.set(await getChatList(localStorage.token, $currentChatPage));
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
638
639
640
641
642
643
644
				await chatId.set(chat.id);
			} else {
				await chatId.set('local');
			}
			await tick();
		}

645
646
647
		const _chatId = JSON.parse(JSON.stringify($chatId));

		await Promise.all(
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
648
			selectedModelIds.map(async (modelId) => {
649
650
651
652
653
654
655
656
				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')
					);
657

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
658
					if (hasImages && !(model.info?.meta?.capabilities?.vision ?? true)) {
659
660
						toast.error(
							$i18n.t('Model {{modelName}} is not vision capable', {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
661
								modelName: model.name ?? model.id
662
663
664
							})
						);
					}
665

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
666
667
					let responseMessageId = responseMessageIds[modelId];
					let responseMessage = history.messages[responseMessageId];
668
669
670
671
672
673
674
675
676
677

					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
678
679
									userContext = res.documents[0].reduce((acc, doc, index) => {
										const createdAtTimestamp = res.metadatas[0][index].created_at;
680
681
682
										const createdAtDate = new Date(createdAtTimestamp * 1000)
											.toISOString()
											.split('T')[0];
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
683
684
										return `${acc}${index + 1}. [${createdAtDate}]. ${doc}\n`;
									}, '');
685
								}
686
687

								console.log(userContext);
688
689
							}
						}
690
691
					}
					responseMessage.userContext = userContext;
692

693
					const chatEventEmitter = await getChatEventEmitter(model.id, _chatId);
Timothy J. Baek's avatar
Timothy J. Baek committed
694
					if (webSearchEnabled) {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
695
						await getWebSearchResults(model.id, parentId, responseMessageId);
696
					}
697

698
					let _response = null;
699
					if (model?.owned_by === 'openai') {
700
						_response = await sendPromptOpenAI(model, prompt, responseMessageId, _chatId);
701
					} else if (model) {
702
						_response = await sendPromptOllama(model, prompt, responseMessageId, _chatId);
703
					}
704
					_responses.push(_response);
705
706

					if (chatEventEmitter) clearInterval(chatEventEmitter);
707
708
				} else {
					toast.error($i18n.t(`Model {{modelId}} not found`, { modelId }));
709
				}
710
			})
711
712
		);

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
713
		currentChatPage.set(1);
714
		await chats.set(await getChatList(localStorage.token, $currentChatPage));
715

716
		return _responses;
717
718
719
	};

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

722
		const responseMessage = history.messages[responseMessageId];
Timothy J. Baek's avatar
Timothy J. Baek committed
723
		const userMessage = history.messages[responseMessage.parentId];
724
725
726
727
728
729
730
731

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

		// Scroll down
		scrollToBottom();

		const messagesBody = [
732
			params?.system || $settings.system || (responseMessage?.userContext ?? null)
733
734
				? {
						role: 'system',
Timothy J. Baek's avatar
Timothy J. Baek committed
735
						content: `${promptTemplate(
736
							params?.system ?? $settings?.system ?? '',
Timothy J. Baek's avatar
Timothy J. Baek committed
737
738
739
740
741
							$user.name,
							$settings?.userLocation
								? await getAndUpdateUserLocation(localStorage.token)
								: undefined
						)}${
Timothy J. Baek's avatar
Timothy J. Baek committed
742
							(responseMessage?.userContext ?? null)
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
743
								? `\n\nUser Context:\n${responseMessage?.userContext ?? ''}`
744
745
								: ''
						}`
Timothy J. Baek's avatar
Timothy J. Baek committed
746
					}
747
748
749
				: undefined,
			...messages
		]
Yanyutin753's avatar
Yanyutin753 committed
750
			.filter((message) => message?.content?.trim())
751
752
753
754
			.map((message, idx, arr) => {
				// Prepare the base message object
				const baseMessage = {
					role: message.role,
Timothy J. Baek's avatar
Timothy J. Baek committed
755
					content: message.content
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
				};

				// 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
786
		let files = JSON.parse(JSON.stringify(chatFiles));
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
787
		if (model?.info?.meta?.knowledge ?? false) {
Timothy J. Baek's avatar
Timothy J. Baek committed
788
			files.push(...model.info.meta.knowledge);
Timothy J. Baek's avatar
Timothy J. Baek committed
789
		}
Timothy J. Baek's avatar
Timothy J. Baek committed
790
791
792
793
794
795
		files.push(
			...(userMessage?.files ?? []).filter((item) =>
				['doc', 'file', 'collection'].includes(item.type)
			),
			...(responseMessage?.files ?? []).filter((item) => ['web_search_results'].includes(item.type))
		);
796

Timothy J. Baek's avatar
Timothy J. Baek committed
797
798
799
800
801
802
803
804
805
		eventTarget.dispatchEvent(
			new CustomEvent('chat:start', {
				detail: {
					id: responseMessageId
				}
			})
		);

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

807
		const [res, controller] = await generateChatCompletion(localStorage.token, {
808
			stream: true,
Timothy J. Baek's avatar
Timothy J. Baek committed
809
			model: model.id,
810
811
			messages: messagesBody,
			options: {
812
				...(params ?? $settings.params ?? {}),
813
				stop:
Timothy J. Baek's avatar
Timothy J. Baek committed
814
					(params?.stop ?? $settings?.params?.stop ?? undefined)
815
816
						? (params?.stop.split(',').map((token) => token.trim()) ?? $settings.params.stop).map(
								(str) => decodeURIComponent(JSON.parse('"' + str.replace(/\"/g, '\\"') + '"'))
Timothy J. Baek's avatar
Timothy J. Baek committed
817
							)
818
						: undefined,
819
820
821
				num_predict: params?.max_tokens ?? $settings?.params?.max_tokens ?? undefined,
				repeat_penalty:
					params?.frequency_penalty ?? $settings?.params?.frequency_penalty ?? undefined
822
823
824
			},
			format: $settings.requestFormat ?? undefined,
			keep_alive: $settings.keepAlive ?? undefined,
Timothy J. Baek's avatar
Timothy J. Baek committed
825
			tool_ids: selectedToolIds.length > 0 ? selectedToolIds : undefined,
Timothy J. Baek's avatar
Timothy J. Baek committed
826
			files: files.length > 0 ? files : undefined,
Timothy J. Baek's avatar
Timothy J. Baek committed
827
			session_id: $socket?.id,
828
829
			chat_id: $chatId,
			id: responseMessageId
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
		});

		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');
848
					} else {
849
						const messages = createMessagesList(responseMessageId);
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
850
						await chatCompletedHandler(_chatId, model.id, responseMessageId, messages);
851
852
					}

853
					_response = responseMessage.content;
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
					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;
							}

874
875
876
							if (data.done == false) {
								if (responseMessage.content == '' && data.message.content == '\n') {
									continue;
877
								} else {
878
									responseMessage.content += data.message.content;
Timothy J. Baek's avatar
Timothy J. Baek committed
879

880
881
882
883
									if (navigator.vibrate && ($settings?.hapticFeedback ?? false)) {
										navigator.vibrate(5);
									}

Timothy J. Baek's avatar
Timothy J. Baek committed
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
									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] }
											})
										);
									}

900
									messages = messages;
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
								}
							} 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
926
927
928
929
									const notification = new Notification(`${model.id}`, {
										body: responseMessage.content,
										icon: `${WEBUI_BASE_URL}/static/favicon.png`
									});
930
931
								}

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
932
								if ($settings?.responseAutoCopy ?? false) {
933
934
									copyToClipboard(responseMessage.content);
								}
935

Timothy J. Baek's avatar
Timothy J. Baek committed
936
								if ($settings.responseAutoPlayback && !$showCallOverlay) {
937
938
									await tick();
									document.getElementById(`speak-button-${responseMessage.id}`)?.click();
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
								}
							}
						}
					}
				} 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
960
						history: history,
961
						models: selectedModels,
Timothy J. Baek's avatar
Timothy J. Baek committed
962
963
						params: params,
						files: chatFiles
964
					});
965

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
966
					currentChatPage.set(1);
967
					await chats.set(await getChatList(localStorage.token, $currentChatPage));
968
969
970
971
972
973
974
975
				}
			}
		} 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
976
					responseMessage.error = { content: error.detail };
977
978
				} else {
					toast.error(error.error);
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
979
					responseMessage.error = { content: error.error };
980
981
982
983
984
				}
			} 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
985
986
987
988
989
				responseMessage.error = {
					content: $i18n.t(`Uh-oh! There was an issue connecting to {{provider}}.`, {
						provider: 'Ollama'
					})
				};
990
991
992
993
994
995
996
			}
			responseMessage.done = true;
			messages = messages;
		}

		stopResponseFlag = false;
		await tick();
Timothy J. Baek's avatar
Timothy J. Baek committed
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013

		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
				}
			})
		);
1014
1015
1016
1017
1018

		if (autoScroll) {
			scrollToBottom();
		}

1019
		if (messages.length == 2 && messages.at(1).content !== '' && selectedModels[0] === model.id) {
1020
1021
1022
1023
			window.history.replaceState(history.state, '', `/c/${_chatId}`);
			const _title = await generateChatTitle(userPrompt);
			await setChatTitle(_chatId, _title);
		}
1024
1025

		return _response;
1026
1027
1028
	};

	const sendPromptOpenAI = async (model, userPrompt, responseMessageId, _chatId) => {
1029
		let _response = null;
Timothy J. Baek's avatar
Timothy J. Baek committed
1030

1031
		const responseMessage = history.messages[responseMessageId];
Timothy J. Baek's avatar
Timothy J. Baek committed
1032
		const userMessage = history.messages[responseMessage.parentId];
1033

Timothy J. Baek's avatar
Timothy J. Baek committed
1034
		let files = JSON.parse(JSON.stringify(chatFiles));
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
1035
		if (model?.info?.meta?.knowledge ?? false) {
Timothy J. Baek's avatar
Timothy J. Baek committed
1036
			files.push(...model.info.meta.knowledge);
Timothy J. Baek's avatar
Timothy J. Baek committed
1037
		}
Timothy J. Baek's avatar
Timothy J. Baek committed
1038
1039
1040
1041
1042
1043
		files.push(
			...(userMessage?.files ?? []).filter((item) =>
				['doc', 'file', 'collection'].includes(item.type)
			),
			...(responseMessage?.files ?? []).filter((item) => ['web_search_results'].includes(item.type))
		);
1044
1045
1046

		scrollToBottom();

Timothy J. Baek's avatar
Timothy J. Baek committed
1047
1048
1049
1050
1051
1052
1053
1054
		eventTarget.dispatchEvent(
			new CustomEvent('chat:start', {
				detail: {
					id: responseMessageId
				}
			})
		);
		await tick();
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1055

1056
1057
1058
1059
1060
		try {
			const [res, controller] = await generateOpenAIChatCompletion(
				localStorage.token,
				{
					stream: true,
1061
					model: model.id,
1062
					stream_options:
Timothy J. Baek's avatar
Timothy J. Baek committed
1063
						(model.info?.meta?.capabilities?.usage ?? false)
1064
1065
							? {
									include_usage: true
Timothy J. Baek's avatar
Timothy J. Baek committed
1066
								}
1067
							: undefined,
1068
					messages: [
1069
						params?.system || $settings.system || (responseMessage?.userContext ?? null)
1070
1071
							? {
									role: 'system',
Timothy J. Baek's avatar
Timothy J. Baek committed
1072
									content: `${promptTemplate(
1073
										params?.system ?? $settings?.system ?? '',
Timothy J. Baek's avatar
Timothy J. Baek committed
1074
1075
1076
1077
1078
										$user.name,
										$settings?.userLocation
											? await getAndUpdateUserLocation(localStorage.token)
											: undefined
									)}${
Timothy J. Baek's avatar
Timothy J. Baek committed
1079
										(responseMessage?.userContext ?? null)
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
1080
											? `\n\nUser Context:\n${responseMessage?.userContext ?? ''}`
1081
1082
											: ''
									}`
Timothy J. Baek's avatar
Timothy J. Baek committed
1083
								}
1084
1085
1086
							: undefined,
						...messages
					]
Yanyutin753's avatar
Yanyutin753 committed
1087
						.filter((message) => message?.content?.trim())
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
						.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
Timothy J. Baek's avatar
Timothy J. Baek committed
1099
														: (message?.raContent ?? message.content)
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
											},
											...message.files
												.filter((file) => file.type === 'image')
												.map((file) => ({
													type: 'image_url',
													image_url: {
														url: file.url
													}
												}))
										]
Timothy J. Baek's avatar
Timothy J. Baek committed
1110
									}
1111
1112
1113
1114
								: {
										content:
											arr.length - 1 !== idx
												? message.content
Timothy J. Baek's avatar
Timothy J. Baek committed
1115
1116
												: (message?.raContent ?? message.content)
									})
1117
						})),
1118
					seed: params?.seed ?? $settings?.params?.seed ?? undefined,
1119
					stop:
Timothy J. Baek's avatar
Timothy J. Baek committed
1120
						(params?.stop ?? $settings?.params?.stop ?? undefined)
1121
1122
							? (params?.stop.split(',').map((token) => token.trim()) ?? $settings.params.stop).map(
									(str) => decodeURIComponent(JSON.parse('"' + str.replace(/\"/g, '\\"') + '"'))
Timothy J. Baek's avatar
Timothy J. Baek committed
1123
								)
1124
							: undefined,
1125
1126
1127
1128
1129
					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
1130
					tool_ids: selectedToolIds.length > 0 ? selectedToolIds : undefined,
Timothy J. Baek's avatar
Timothy J. Baek committed
1131
					files: files.length > 0 ? files : undefined,
Timothy J. Baek's avatar
Timothy J. Baek committed
1132
					session_id: $socket?.id,
1133
1134
					chat_id: $chatId,
					id: responseMessageId
1135
				},
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1136
				`${WEBUI_BASE_URL}/api`
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
			);

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

			scrollToBottom();

			if (res && res.ok && res.body) {
				const textStream = await createOpenAITextStream(res.body, $settings.splitLargeChunks);

				for await (const update of textStream) {
1148
					const { value, done, citations, error, usage } = update;
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
					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');
1159
						} else {
1160
1161
							const messages = createMessagesList(responseMessageId);

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1162
							await chatCompletedHandler(_chatId, model.id, responseMessageId, messages);
1163
1164
						}

1165
1166
						_response = responseMessage.content;

1167
1168
1169
						break;
					}

1170
					if (usage) {
1171
						responseMessage.info = { ...usage, openai: true };
1172
1173
					}

1174
1175
1176
1177
1178
1179
1180
1181
1182
					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
1183

1184
1185
1186
1187
						if (navigator.vibrate && ($settings?.hapticFeedback ?? false)) {
							navigator.vibrate(5);
						}

Timothy J. Baek's avatar
Timothy J. Baek committed
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
						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] }
								})
							);
						}

1204
1205
1206
						messages = messages;
					}

1207
1208
					if (autoScroll) {
						scrollToBottom();
1209
					}
1210
				}
1211

1212
				if ($settings.notificationEnabled && !document.hasFocus()) {
Timothy J. Baek's avatar
Timothy J. Baek committed
1213
					const notification = new Notification(`${model.id}`, {
1214
1215
1216
1217
						body: responseMessage.content,
						icon: `${WEBUI_BASE_URL}/static/favicon.png`
					});
				}
1218

1219
1220
1221
				if ($settings.responseAutoCopy) {
					copyToClipboard(responseMessage.content);
				}
1222

Timothy J. Baek's avatar
Timothy J. Baek committed
1223
				if ($settings.responseAutoPlayback && !$showCallOverlay) {
1224
					await tick();
Timothy J. Baek's avatar
Timothy J. Baek committed
1225

1226
					document.getElementById(`speak-button-${responseMessage.id}`)?.click();
1227
1228
1229
1230
1231
				}

				if ($chatId == _chatId) {
					if ($settings.saveChatHistory ?? true) {
						chat = await updateChatById(localStorage.token, _chatId, {
Timothy J. Baek's avatar
Timothy J. Baek committed
1232
							models: selectedModels,
1233
							messages: messages,
1234
							history: history,
Timothy J. Baek's avatar
Timothy J. Baek committed
1235
1236
							params: params,
							files: chatFiles
1237
						});
1238

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1239
						currentChatPage.set(1);
1240
						await chats.set(await getChatList(localStorage.token, $currentChatPage));
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
					}
				}
			} 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
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
		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
1271

1272
1273
1274
1275
		if (autoScroll) {
			scrollToBottom();
		}

1276
		if (messages.length == 2 && selectedModels[0] === model.id) {
1277
1278
1279
1280
1281
			window.history.replaceState(history.state, '', `/c/${_chatId}`);

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

		return _response;
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
	};

	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
1312
		responseMessage.error = {
Timothy J. Baek's avatar
fix  
Timothy J. Baek committed
1313
1314
1315
1316
1317
1318
			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
1319
		};
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
		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
1338
1339
				// If user message has only one model selected, sendPrompt automatically selects it for regeneration
				await sendPrompt(userPrompt, userMessage.id);
1340
			} else {
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1341
1342
1343
				// 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 });
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
			}
		}
	};

	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
1360
				if (model?.owned_by === 'openai') {
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
					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
1384
				selectedModels[0],
1385
				userPrompt,
Timothy J. Baek's avatar
Timothy J. Baek committed
1386
1387
1388
1389
1390
				$chatId
			).catch((error) => {
				console.error(error);
				return 'New Chat';
			});
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404

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

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1406
			currentChatPage.set(1);
1407
			await chats.set(await getChatList(localStorage.token, $currentChatPage));
1408
1409
1410
		}
	};

Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1411
1412
	const getWebSearchResults = async (model: string, parentId: string, responseId: string) => {
		const responseMessage = history.messages[responseId];
Timothy J. Baek's avatar
Timothy J. Baek committed
1413
		const userMessage = history.messages[parentId];
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423

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

Timothy J. Baek's avatar
Timothy J. Baek committed
1424
		const prompt = userMessage.content;
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
		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;
		}
	};

1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
	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
1505
1506
<audio id="audioElement" src="" style="display: none;" />

Timothy J. Baek's avatar
Timothy J. Baek committed
1507
1508
1509
1510
<EventConfirmDialog
	bind:show={showEventConfirmation}
	title={eventConfirmationTitle}
	message={eventConfirmationMessage}
Timothy J. Baek's avatar
Timothy J. Baek committed
1511
1512
	input={eventConfirmationInput}
	inputPlaceholder={eventConfirmationInputPlaceholder}
1513
	inputValue={eventConfirmationInputValue}
Timothy J. Baek's avatar
Timothy J. Baek committed
1514
	on:confirm={(e) => {
Timothy J. Baek's avatar
Timothy J. Baek committed
1515
1516
1517
1518
1519
		if (e.detail) {
			eventCallback(e.detail);
		} else {
			eventCallback(true);
		}
Timothy J. Baek's avatar
Timothy J. Baek committed
1520
1521
1522
1523
1524
1525
	}}
	on:cancel={() => {
		eventCallback(false);
	}}
/>

Timothy J. Baek's avatar
Timothy J. Baek committed
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
{#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
1536

1537
1538
{#if !chatIdProp || (loaded && chatIdProp)}
	<div
Timothy J. Baek's avatar
Timothy J. Baek committed
1539
		class="h-screen max-h-[100dvh] {$showSidebar
1540
			? 'md:max-w-[calc(100%-260px)]'
Timothy J. Baek's avatar
Timothy J. Baek committed
1541
			: ''} w-full max-w-full flex flex-col"
1542
	>
Timothy J. Baek's avatar
Timothy J. Baek committed
1543
1544
1545
1546
1547
1548
1549
1550
1551
		{#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
1552
				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
1553
1554
1555
			/>
		{/if}

1556
1557
1558
1559
		<Navbar
			{title}
			bind:selectedModels
			bind:showModelSelector
Timothy J. Baek's avatar
Timothy J. Baek committed
1560
			bind:showControls
1561
1562
1563
1564
			shareEnabled={messages.length > 0}
			{chat}
			{initNewChat}
		/>
Timothy J. Baek's avatar
Timothy J. Baek committed
1565

Timothy J. Baek's avatar
Timothy J. Baek committed
1566
		{#if $banners.length > 0 && messages.length === 0 && !$chatId && selectedModels.length <= 1}
Timothy J. Baek's avatar
Timothy J. Baek committed
1567
			<div
Timothy J. Baek's avatar
Timothy J. Baek committed
1568
1569
				class="absolute top-[4.25rem] w-full {$showSidebar
					? 'md:max-w-[calc(100%-260px)]'
Timothy J. Baek's avatar
refac  
Timothy J. Baek committed
1570
					: ''} {showControls ? 'lg:pr-[24rem]' : ''} z-20"
Timothy J. Baek's avatar
Timothy J. Baek committed
1571
			>
Timothy J. Baek's avatar
Timothy J. Baek committed
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
				<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
1592
1593
1594
			</div>
		{/if}

1595
		<div class="flex flex-col flex-auto z-10">
1596
			<div
1597
1598
1599
				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]'
					: ''}"
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
				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}
1621
						{chatActionHandler}
1622
1623
1624
					/>
				</div>
			</div>
Timothy J. Baek's avatar
Timothy J. Baek committed
1625

1626
			<div class={showControls ? 'lg:pr-[24rem]' : ''}>
Timothy J. Baek's avatar
Timothy J. Baek committed
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
				<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>
1648
		</div>
1649

Timothy J. Baek's avatar
Timothy J. Baek committed
1650
1651
1652
1653
1654
1655
1656
1657
1658
		<ChatControls
			models={selectedModelIds.reduce((a, e, i, arr) => {
				const model = $models.find((m) => m.id === e);
				if (model) {
					return [...a, model];
				}
				return a;
			}, [])}
			bind:show={showControls}
Timothy J. Baek's avatar
Timothy J. Baek committed
1659
			bind:chatFiles
Timothy J. Baek's avatar
Timothy J. Baek committed
1660
1661
			bind:params
		/>
1662
1663
	</div>
{/if}