-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
1520 lines (1317 loc) · 53.8 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
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
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
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
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
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
786
787
788
789
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
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
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
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { appendMediaToMessage, extension_prompt_types, getRequestHeaders, saveSettingsDebounced, setExtensionPrompt, substituteParamsExtended } from '../../../../script.js';
import { appendFileContent, uploadFileAttachment } from '../../../chats.js';
import { doExtrasFetch, extension_settings, getApiUrl, getContext, modules, renderExtensionTemplateAsync } from '../../../extensions.js';
import { registerDebugFunction } from '../../../power-user.js';
import { SECRET_KEYS, secret_state, writeSecret } from '../../../secrets.js';
import { POPUP_RESULT, POPUP_TYPE, callGenericPopup } from '../../../popup.js';
import { extractTextFromHTML, isFalseBoolean, isTrueBoolean, onlyUnique, trimToEndSentence, trimToStartSentence, getStringHash, regexFromString } from '../../../utils.js';
import { SlashCommandParser } from '../../../slash-commands/SlashCommandParser.js';
import { SlashCommand } from '../../../slash-commands/SlashCommand.js';
import { ARGUMENT_TYPE, SlashCommandArgument, SlashCommandNamedArgument } from '../../../slash-commands/SlashCommandArgument.js';
import { commonEnumProviders } from '../../../slash-commands/SlashCommandCommonEnumsProvider.js';
import { localforage } from '../../../../lib.js';
import { textgen_types, textgenerationwebui_settings } from '../../../textgen-settings.js';
const storage = localforage.createInstance({ name: 'SillyTavern_WebSearch' });
const extensionPromptMarker = '___WebSearch___';
const WEBSEARCH_SOURCES = {
SERPAPI: 'serpapi',
EXTRAS: 'extras',
PLUGIN: 'plugin',
SEARXNG: 'searxng',
TAVILY: 'tavily',
KOBOLDCPP: 'koboldcpp',
};
const VISIT_TARGETS = {
MESSAGE: 0,
DATA_BANK: 1,
};
/**
* @typedef {Object} RegexRule
* @property {string} pattern Regular expression pattern
* @property {string} query Web search query
*/
const defaultSettings = {
triggerPhrases: [
'search for',
'look up',
'find me',
'tell me',
'explain me',
'can you',
'how to',
'how is',
'how do you',
'ways to',
'who is',
'who are',
'who was',
'who were',
'who did',
'what is',
'what\'s',
'what are',
'what\'re',
'what was',
'what were',
'what did',
'what do',
'where are',
'where\'re',
'where\'s',
'where is',
'where was',
'where were',
'where did',
'where do',
'where does',
'where can',
'how do i',
'where do i',
'how much',
'definition of',
'what happened',
'why does',
'why do',
'why did',
'why is',
'why are',
'why were',
'when does',
'when do',
'when did',
'when is',
'when was',
'when were',
'how does',
'meaning of',
],
insertionTemplate: '***\nRelevant information from the web ({{query}}):\n{{text}}\n***',
cacheLifetime: 60 * 60 * 24 * 7, // 1 week
position: extension_prompt_types.IN_PROMPT,
depth: 2,
maxWords: 10,
budget: 2000,
source: WEBSEARCH_SOURCES.SERPAPI,
extras_engine: 'google',
visit_enabled: false,
visit_target: VISIT_TARGETS.MESSAGE,
visit_count: 3,
visit_file_header: 'Web search results for "{{query}}"\n\n',
visit_block_header: '---\nInformation from {{link}}\n\n{{text}}\n\n',
visit_blacklist: [
'youtube.com',
'twitter.com',
'facebook.com',
'instagram.com',
],
use_backticks: true,
use_trigger_phrases: true,
use_regex: false,
use_function_tool: false,
regex: [],
searxng_url: '',
searxng_preferences: '',
};
/**
* Ensures that the provided string ends with a newline.
* @param {string} text String to ensure an ending newline
* @returns {string} String with an ending newline
*/
function ensureEndNewline(text) {
return text.endsWith('\n') ? text : text + '\n';
}
function createRegexRule() {
const rule = { pattern: '', query: '' };
extension_settings.websearch.regex.push(rule);
saveSettingsDebounced();
renderRegexRules();
}
async function renderRegexRules() {
$('#websearch_regex_list').empty();
for (const rule of extension_settings.websearch.regex) {
const template = $(await renderExtensionTemplateAsync('third-party/Extension-WebSearch', 'regex'));
template.find('.websearch_regex_pattern').val(rule.pattern).on('input', function () {
rule.pattern = String($(this).val());
saveSettingsDebounced();
});
template.find('.websearch_regex_query').val(rule.query).on('input', function () {
rule.query = String($(this).val());
saveSettingsDebounced();
});
template.find('.websearch_regex_delete').on('click', () => {
if (!confirm('Are you sure?')) {
return;
}
const index = extension_settings.websearch.regex.indexOf(rule);
extension_settings.websearch.regex.splice(index, 1);
saveSettingsDebounced();
renderRegexRules();
});
$('#websearch_regex_list').append(template);
}
}
async function isSearchAvailable() {
if (extension_settings.websearch.source === WEBSEARCH_SOURCES.SERPAPI && !secret_state[SECRET_KEYS.SERPAPI]) {
console.debug('WebSearch: no SerpApi key found');
return false;
}
if (extension_settings.websearch.source === WEBSEARCH_SOURCES.EXTRAS && !modules.includes('websearch')) {
console.debug('WebSearch: no websearch Extras module');
return false;
}
if (extension_settings.websearch.source === WEBSEARCH_SOURCES.PLUGIN && !(await probeSeleniumSearchPlugin())) {
console.debug('WebSearch: no websearch server plugin');
return false;
}
if (extension_settings.websearch.source === WEBSEARCH_SOURCES.SEARXNG && !extension_settings.websearch.searxng_url) {
console.debug('WebSearch: no SearXNG URL');
return false;
}
if (extension_settings.websearch.source === WEBSEARCH_SOURCES.TAVILY && !secret_state[SECRET_KEYS.TAVILY]) {
console.debug('WebSearch: no Tavily key found');
return false;
}
if (extension_settings.websearch.source === WEBSEARCH_SOURCES.KOBOLDCPP && !textgenerationwebui_settings.server_urls[textgen_types.KOBOLDCPP]) {
console.debug('WebSearch: no KoboldCpp server URL');
return false;
}
return true;
}
/**
* Determines whether the function tool can be used.
* @returns {boolean} Whether the function tool can be used
*/
function canUseFunctionTool() {
const { isToolCallingSupported } = SillyTavern.getContext();
if (typeof isToolCallingSupported !== 'function') {
console.debug('WebSearch: tool calling is not supported');
return false;
}
return isToolCallingSupported();
}
async function onWebSearchPrompt(chat, _maxContext, _abort, type) {
if (type === 'quiet') {
console.debug('WebSearch: quiet prompt, ignoring');
return;
}
if (extension_settings.websearch.use_function_tool && canUseFunctionTool()) {
console.debug('WebSearch: using the function tool');
return;
}
if (!extension_settings.websearch.enabled) {
console.debug('WebSearch: extension is disabled');
return;
}
if (!chat || !Array.isArray(chat) || chat.length === 0) {
console.debug('WebSearch: chat is empty');
return;
}
const startTime = Date.now();
try {
console.debug('WebSearch: resetting the extension prompt');
setExtensionPrompt(extensionPromptMarker, '', extension_settings.websearch.position, extension_settings.websearch.depth);
const isAvailable = await isSearchAvailable();
if (!isAvailable) {
return;
}
// Find the latest user message
let searchQuery = '';
let triggerMessage = null;
for (let message of chat.slice().reverse()) {
if (message.is_system) {
continue;
}
if (message.mes && message.is_user) {
if (isBreakCondition(message.mes)) {
break;
}
const query = extractSearchQuery(message.mes);
if (!query) {
continue;
}
searchQuery = query;
triggerMessage = message;
break;
}
}
if (!searchQuery) {
console.debug('WebSearch: no user message found');
return;
}
const { text, links } = await performSearchRequest(searchQuery, { useCache: true });
if (!text) {
console.debug('WebSearch: search failed');
return;
}
if (extension_settings.websearch.visit_enabled && triggerMessage && Array.isArray(links) && links.length > 0) {
const messageId = Number(triggerMessage.index);
const visitResult = await visitLinksAndAttachToMessage(searchQuery, links, messageId);
if (visitResult && visitResult.file) {
triggerMessage.extra = Object.assign((triggerMessage.extra || {}), { file: visitResult.file });
triggerMessage.mes = await appendFileContent(triggerMessage, triggerMessage.mes);
}
}
// Insert the result into the prompt
let template = extension_settings.websearch.insertionTemplate;
if (!template) {
console.debug('WebSearch: no insertion template found, using default');
template = defaultSettings.insertionTemplate;
}
if (!(/{{text}}/i.test(template))) {
console.debug('WebSearch: insertion template does not contain {{text}} macro, appending');
template += '\n{{text}}';
}
const extensionPrompt = substituteParamsExtended(template, { text: text, query: searchQuery });
setExtensionPrompt(extensionPromptMarker, extensionPrompt, extension_settings.websearch.position, extension_settings.websearch.depth);
console.log('WebSearch: prompt updated', extensionPrompt);
} catch (error) {
console.error('WebSearch: error while processing the request', error);
} finally {
console.log('WebSearch: finished in', Date.now() - startTime, 'ms');
}
}
function isBreakCondition(message) {
if (message && message.trim().startsWith('!')) {
console.debug('WebSearch: message starts with an exclamation mark, stopping');
return true;
}
return false;
}
/**
* Extracts the search query from the message.
* @param {string} message Message to extract the search query from
* @returns {string} Search query
*/
function extractSearchQuery(message) {
if (message && message.trim().startsWith('.')) {
console.debug('WebSearch: message starts with a dot, ignoring');
return;
}
message = processInputText(message);
if (!message) {
console.debug('WebSearch: processed message is empty');
return;
}
console.log('WebSearch: processed message', message);
if (extension_settings.websearch.use_backticks) {
// Remove triple backtick blocks
message = message.replace(/```[^`]+```/gi, '');
// Find the first backtick-enclosed substring
const match = message.match(/`([^`]+)`/i);
if (match) {
const query = match[1].trim();
console.debug('WebSearch: backtick-enclosed substring found', query);
return query;
}
}
if (extension_settings.websearch.use_regex) {
for (const rule of extension_settings.websearch.regex) {
const regex = regexFromString(rule.pattern);
if (regex && regex.test(message)) {
const groups = message.match(regex);
const query = substituteParamsExtended(rule.query).replace(/\$(\d+)/g, (_, i) => groups[i] || '');
console.debug('WebSearch: regex rule matched', rule.pattern, query);
return query;
}
}
}
if (extension_settings.websearch.use_trigger_phrases) {
// Find the first index of the trigger phrase in the message
let triggerPhraseIndex = -1;
let triggerPhraseActual = '';
const triggerPhrases = extension_settings.websearch.triggerPhrases;
for (let i = 0; i < triggerPhrases.length; i++) {
const triggerPhrase = triggerPhrases[i].toLowerCase();
const indexOf = message.indexOf(triggerPhrase);
if (indexOf !== -1) {
console.debug(`WebSearch: trigger phrase found "${triggerPhrase}" at index ${indexOf}`);
triggerPhraseIndex = indexOf;
triggerPhraseActual = triggerPhrase;
break;
}
}
if (triggerPhraseIndex === -1) {
console.debug('WebSearch: no trigger phrase found');
return;
}
// Extract the relevant part of the message (after the trigger phrase)
message = message.substring(triggerPhraseIndex + triggerPhraseActual.length).trim();
console.log('WebSearch: extracted query', message);
// Limit the number of words
const maxWords = extension_settings.websearch.maxWords;
message = message.split(' ').slice(0, maxWords).join(' ');
console.log('WebSearch: query after word limit', message);
return message;
}
}
/**
* Pre-process search query input text.
* @param {string} text Input text
* @returns {string} Processed text
*/
function processInputText(text) {
// Convert to lowercase
text = text.toLowerCase();
// Remove punctuation
text = text.replace(/[\\.,@#!?$%&;:{}=_~[\]]/g, '');
// Remove double quotes (including region-specific ones)
text = text.replace(/["“”]/g, '');
// Remove carriage returns
text = text.replace(/\r/g, '');
// Replace newlines with spaces
text = text.replace(/[\n]+/g, ' ');
// Collapse multiple spaces into one
text = text.replace(/\s+/g, ' ');
// Trim
text = text.trim();
return text;
}
/**
* Checks if the provided link is allowed to be visited or blacklisted.
* @param {string} link Link to check
* @returns {boolean} Whether the link is allowed
*/
function isAllowedUrl(link) {
try {
const url = new URL(link);
const isBlacklisted = extension_settings.websearch.visit_blacklist.some(y => url.hostname.includes(y));
if (isBlacklisted) {
console.debug('WebSearch: blacklisted link', link);
}
return !isBlacklisted;
} catch (error) {
console.debug('WebSearch: invalid link', link);
return false;
}
}
/**
* Visits the provided web links and extracts the text from the resulting HTML.
* @param {string} query Search query
* @param {string[]} links Array of links to visit
* @returns {Promise<string>} Extracted text
*/
async function visitLinks(query, links) {
if (!Array.isArray(links)) {
console.debug('WebSearch: not an array of links');
return '';
}
links = links.filter(isAllowedUrl);
if (links.length === 0) {
console.debug('WebSearch: no links to visit');
return '';
}
const visitCount = extension_settings.websearch.visit_count;
const visitPromises = [];
for (let i = 0; i < Math.min(visitCount, links.length); i++) {
const link = links[i];
visitPromises.push(visitLink(link));
}
const visitResult = await Promise.allSettled(visitPromises);
let linkResult = '';
for (let result of visitResult) {
if (result.status === 'fulfilled' && result.value) {
const { link, text } = result.value;
if (text) {
linkResult += ensureEndNewline(substituteParamsExtended(extension_settings.websearch.visit_block_header, { query: query, text: text, link: link }));
}
}
}
if (!linkResult) {
console.debug('WebSearch: no text to attach');
return '';
}
const fileHeader = ensureEndNewline(substituteParamsExtended(extension_settings.websearch.visit_file_header, { query: query }));
const fileText = fileHeader + linkResult;
return fileText;
}
/**
* Visits the provided web links and attaches the resulting text to the chat as a file.
* @param {string} query Search query
* @param {string[]} links Web links to visit
* @param {number} messageId Message ID that triggered the search
* @returns {Promise<{fileContent: string, file: object}>} File content and file object
*/
async function visitLinksAndAttachToMessage(query, links, messageId) {
if (isNaN(messageId)) {
console.debug('WebSearch: invalid message ID');
return;
}
const context = getContext();
const message = context.chat[messageId];
if (!message) {
console.debug('WebSearch: failed to find the message');
return;
}
if (message?.extra?.file) {
console.debug('WebSearch: message already has a file attachment');
return;
}
if (!message.extra) {
message.extra = {};
}
try {
if (extension_settings.websearch.visit_target === VISIT_TARGETS.DATA_BANK) {
const fileExists = await isFileExistsInDataBank(query);
if (fileExists) {
return;
}
}
const fileName = `websearch - ${query} - ${Date.now()}.txt`;
const fileText = await visitLinks(query, links);
if (!fileText) {
return;
}
if (extension_settings.websearch.visit_target === VISIT_TARGETS.DATA_BANK) {
await uploadToDataBank(fileName, fileText);
} else {
const base64Data = window.btoa(unescape(encodeURIComponent(fileText)));
const uniqueFileName = `${Date.now()}_${getStringHash(fileName)}.txt`;
const fileUrl = await uploadFileAttachment(uniqueFileName, base64Data);
if (!fileUrl) {
console.debug('WebSearch: failed to upload the file');
return;
}
message.extra.file = {
url: fileUrl,
size: fileText.length,
name: fileName,
};
const messageElement = $(`.mes[mesid="${messageId}"]`);
if (messageElement.length === 0) {
console.debug('WebSearch: failed to find the message element');
return;
}
appendMediaToMessage(message, messageElement);
return { fileContent: fileText, file: message.extra.file };
}
} catch (error) {
console.error('WebSearch: failed to attach the file', error);
}
}
/**
* Checks if the file for the search query already exists in the Data Bank.
* @param {string} query Search query
* @returns {Promise<boolean>} Whether the file exists
*/
async function isFileExistsInDataBank(query) {
try {
const { getDataBankAttachmentsForSource } = await import('../../../chats.js');
const attachments = await getDataBankAttachmentsForSource('chat');
const existingAttachment = attachments.find(x => x.name.startsWith(`websearch - ${query} - `));
if (existingAttachment) {
console.debug('WebSearch: file for such query already exists in the Data Bank');
return true;
}
return false;
} catch (error) {
// Prevent visiting links if the Data Bank is not available
toastr.error('Data Bank module is not available');
console.error('WebSearch: failed to check if the file exists in the Data Bank', error);
return true;
}
}
/**
* Uploads the file to the Data Bank.
* @param {string} fileName File name
* @param {string} fileText File text
* @returns {Promise<void>}
*/
async function uploadToDataBank(fileName, fileText) {
try {
const { uploadFileAttachmentToServer } = await import('../../../chats.js');
const file = new File([fileText], fileName, { type: 'text/plain' });
await uploadFileAttachmentToServer(file, 'chat');
} catch (error) {
console.error('WebSearch: failed to import the chat module', error);
}
}
/**
* Visits the provided web link and extracts the text from the resulting HTML.
* @param {string} link Web link to visit
* @returns {Promise<{link: string, text:string}>} Extracted text
*/
async function visitLink(link) {
try {
const result = await fetch('/api/search/visit', {
method: 'POST',
headers: getRequestHeaders(),
body: JSON.stringify({ url: link }),
});
if (!result.ok) {
console.debug(`WebSearch: visit request failed with status ${result.statusText}`, link);
return;
}
const data = await result.blob();
const text = await extractTextFromHTML(data, 'p'); // Only extract text from <p> tags
console.debug('WebSearch: visit result', link, text);
return { link, text };
} catch (error) {
console.error('WebSearch: visit failed', error);
}
}
/**
* Performs a search query via SerpApi.
* @param {string} query Search query
* @returns {Promise<{textBits: string[], links: string[]}>} Lines of search results.
*/
async function doSerpApiQuery(query) {
// Perform the search
const result = await fetch('/api/search/serpapi', {
method: 'POST',
headers: getRequestHeaders(),
body: JSON.stringify({ query }),
});
if (!result.ok) {
const text = await result.text();
console.debug('WebSearch: search request failed', result.statusText, text);
return;
}
const data = await result.json();
console.debug('WebSearch: search response', data);
// Extract the relevant information
// Order: 1. Answer Box, 2. Knowledge Graph, 3. Organic Results (max 5), 4. Related Questions (max 5)
let textBits = [];
let links = [];
if (Array.isArray(data.organic_results)) {
links.push(...data.organic_results.map(x => x.link).filter(x => x));
}
if (data.answer_box) {
switch (data.answer_box.type) {
case 'organic_result':
textBits.push(data.answer_box.snippet || data.answer_box.result || data.answer_box.title);
if (data.answer_box.list) {
textBits.push(data.answer_box.list.join('\n'));
}
if (data.answer_box.table) {
textBits.push(data.answer_box.table.join('\n'));
}
break;
case 'translation_result':
textBits.push(data.answer_box.translation?.target?.text);
break;
case 'calculator_result':
textBits.push(`Answer: ${data.answer_box.result}`);
break;
case 'population_result':
textBits.push(`${data.answer_box.place} ${data.answer_box.population}`);
break;
case 'currency_converter':
textBits.push(data.answer_box.result);
break;
case 'finance_results':
textBits.push(`${data.answer_box.title} ${data.answer_box.exchange} ${data.answer_box.stock} ${data.answer_box.price} ${data.answer_box.currency}`);
break;
case 'weather_result':
textBits.push(`${data.answer_box.location}; ${data.answer_box.weather}; ${data.answer_box.temperature} ${data.answer_box.unit}`);
break;
case 'flight_duration':
textBits.push(data.answer_box.duration);
break;
case 'dictionary_results':
textBits.push(data.answer_box.definitions?.join('\n'));
break;
case 'time':
textBits.push(`${data.answer_box.result} ${data.answer_box.date}`);
break;
default:
textBits.push(data.answer_box.result || data.answer_box.answer || data.answer_box.title);
break;
}
}
if (data.knowledge_graph) {
textBits.push(data.knowledge_graph.description || data.knowledge_graph.snippet || data.knowledge_graph.merchant_description || data.knowledge_graph.title);
}
const MAX_RESULTS = 10;
for (let i = 0; i < MAX_RESULTS; i++) {
if (Array.isArray(data.organic_results)) {
const result = data.organic_results[i];
if (result) {
textBits.push(result.snippet);
}
}
if (Array.isArray(data.related_questions)) {
const result = data.related_questions[i];
if (result) {
textBits.push(`${result.question} ${result.snippet}`);
}
}
}
return { textBits, links };
}
/**
* Performs a search query via Extras API.
* @param {string} query Search query
* @returns {Promise<{textBits: string[], links: string[]}>} Lines of search results.
*/
async function doExtrasApiQuery(query) {
const url = new URL(getApiUrl());
url.pathname = '/api/websearch';
const result = await doExtrasFetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Bypass-Tunnel-Reminder': 'bypass',
},
body: JSON.stringify({
query: query,
engine: extension_settings.websearch.extras_engine,
}),
});
if (!result.ok) {
const text = await result.text();
console.debug('WebSearch: search request failed', result.statusText, text);
return;
}
const data = await result.json();
console.debug('WebSearch: search response', data);
const textBits = data.results.split('\n');
const links = Array.isArray(data.links) ? data.links : [];
return { textBits, links };
}
/**
* Performs a search query via the Selenium search plugin.
* @param {string} query Search query
* @returns {Promise<{textBits: string[], links: string[]}>} Lines of search results.
*/
async function doSeleniumPluginQuery(query) {
const result = await fetch('/api/plugins/selenium/search', {
method: 'POST',
headers: getRequestHeaders(),
body: JSON.stringify({
query: query,
engine: extension_settings.websearch.extras_engine,
}),
});
if (!result.ok) {
const text = await result.text();
console.debug('WebSearch: search request failed', result.statusText, text);
return;
}
const data = await result.json();
console.debug('WebSearch: search response', data);
const textBits = data.results.split('\n');
const links = Array.isArray(data.links) ? data.links : [];
return { textBits, links };
}
/**
* Performs a search query via Tavily.
* @param {string} query Search query
* @returns {Promise<{textBits: string[], links: string[]}>} Lines of search results.
*/
async function doTavilyQuery(query) {
const result = await fetch('/api/search/tavily', {
method: 'POST',
headers: getRequestHeaders(),
body: JSON.stringify({ query }),
});
if (!result.ok) {
console.debug('WebSearch: search request failed', result.statusText);
return;
}
const textBits = [];
const links = [];
const data = await result.json();
if (data.answer) {
textBits.push(data.answer);
}
if (Array.isArray(data.results)) {
data.results.forEach(x => {
textBits.push(`${x.title}\n${x.content}`);
links.push(x.url);
});
}
return { textBits, links };
}
/**
* Performs a search query via KoboldCpp.
* @param {string} query Search query
* @returns {Promise<{textBits: string[], links: string[]}>} Lines of search results.
*/
async function doKoboldCppQuery(query) {
const url = textgenerationwebui_settings.server_urls[textgen_types.KOBOLDCPP];
const result = await fetch('/api/search/koboldcpp', {
method: 'POST',
headers: getRequestHeaders(),
body: JSON.stringify({ url, query }),
});
if (!result.ok) {
console.debug('WebSearch: search request failed', result.statusText);
return;
}
const textBits = [];
const links = [];
const data = await result.json();
for (const result of data) {
textBits.push([result.title, result.desc, result.content].filter(x => x).join('\n'));
links.push(result.url);
}
return { textBits, links };
}
/**
* Performs a search query via SearXNG.
* @param {string} query Search query
* @returns {Promise<{textBits: string[], links: string[]}>} Extracted text
*/
async function doSearxngQuery(query) {
const result = await fetch('/api/search/searxng', {
method: 'POST',
headers: getRequestHeaders(),
body: JSON.stringify({ query, baseUrl: extension_settings.websearch.searxng_url, preferences: extension_settings.websearch.searxng_preferences }),
});
if (!result.ok) {
console.debug('WebSearch: search request failed', result.statusText);
return;
}
const data = await result.text();
const doc = new DOMParser().parseFromString(data, 'text/html');
const textBits = Array.from(doc.querySelectorAll('#urls p.content')).map(x => x.textContent.trim()).filter(x => x);
const links = Array.from(doc.querySelectorAll('#urls .url_header, #urls .url_wrapper')).map(x => x.getAttribute('href')).filter(x => x);
if (doc.querySelector('.infobox')) {
const infoboxText = doc.querySelector('.infobox p')?.textContent?.trim();
const infoboxLink = doc.querySelector('.infobox a')?.getAttribute('href');
if (infoboxText) {
textBits.unshift(infoboxText);
}
if (infoboxLink) {
links.unshift(infoboxLink);
}
}
return { textBits, links };
}
/**
* Probes the Selenium search plugin to check if it's available.
* @returns {Promise<boolean>} Whether the plugin is available
*/
async function probeSeleniumSearchPlugin() {
try {
const result = await fetch('/api/plugins/selenium/probe', {
method: 'POST',
headers: getRequestHeaders(),
});
if (!result.ok) {
console.debug('WebSearch: plugin probe failed', result.statusText);
return false;
}
return true;
} catch (error) {
console.error('WebSearch: plugin probe failed', error);
return false;
}
}
/**
*
* @param {string} query Search query
* @param {SearchRequestOptions} options Search request options
* @typedef {{useCache?: boolean}} SearchRequestOptions
* @returns {Promise<{text:string, links: string[]}>} Extracted text
*/
async function performSearchRequest(query, options = { useCache: true }) {
// Check if the query is cached
const cacheKey = `query_${query}`;
const cacheLifetime = extension_settings.websearch.cacheLifetime;
const cachedResult = await storage.getItem(cacheKey);
if (options.useCache && cachedResult) {
console.debug('WebSearch: cached result found', cachedResult);
// Check if the cache is expired
if (cachedResult.timestamp + cacheLifetime * 1000 < Date.now()) {
console.debug('WebSearch: cached result is expired, requerying');
await storage.removeItem(cacheKey);
} else {
console.debug('WebSearch: cached result is valid');
return { text: cachedResult.text, links: cachedResult.links };
}
}
/**
* @returns {Promise<{textBits: string[], links: string[]}>}
*/
async function callSearchSource() {
try {
switch (extension_settings.websearch.source) {
case WEBSEARCH_SOURCES.SERPAPI:
return await doSerpApiQuery(query);
case WEBSEARCH_SOURCES.EXTRAS:
return await doExtrasApiQuery(query);
case WEBSEARCH_SOURCES.PLUGIN:
return await doSeleniumPluginQuery(query);
case WEBSEARCH_SOURCES.SEARXNG:
return await doSearxngQuery(query);
case WEBSEARCH_SOURCES.TAVILY:
return await doTavilyQuery(query);
case WEBSEARCH_SOURCES.KOBOLDCPP:
return await doKoboldCppQuery(query);
default:
throw new Error(`Unrecognized search source: ${extension_settings.websearch.source}`);
}
} catch (error) {
console.error('WebSearch: search failed', error);
return { textBits: [], links: [] };
}
}
const { textBits, links } = await callSearchSource();
const budget = extension_settings.websearch.budget;
let text = '';
for (let i of textBits.filter(onlyUnique)) {
if (i) {
// Incomplete sentences confuse the model, so we trim them
if (i.endsWith('...')) {
i = i.slice(0, -3);
i = trimToEndSentence(i).trim();
}