-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathfullsheet-rag.js
More file actions
4319 lines (3758 loc) · 180 KB
/
fullsheet-rag.js
File metadata and controls
4319 lines (3758 loc) · 180 KB
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
/**
* ============================================================================
* CARROTKERNEL FULLSHEET RAG SYSTEM
* ============================================================================
* Vectorizes character fullsheets and injects semantically relevant chunks
* instead of the entire fullsheet, reducing context consumption by 80-90%.
*
* Features:
* - Per-character vector collections (prevents trait mixing)
* - Semantic chunking by section headers (8 sections per fullsheet)
* - Top-K retrieval (default 3 chunks ~2400 chars vs 15000+ full sheet)
* - Independent system with experimental toggle
* - BunnymoTags format compatible
*
* Collection Pattern: carrotkernel_char_${characterName}
*
* @author CarrotKernel
* @version 1.0.0
*/
// ============================================================================
// IMPORTS
// ============================================================================
import {
eventSource,
event_types,
chat,
saveSettingsDebounced,
getRequestHeaders,
setExtensionPrompt,
extension_prompt_types,
extension_prompt_roles,
is_send_press,
} from '../../../../script.js';
import { getStringHash } from '../../../utils.js';
import { extension_settings, getContext } from '../../../extensions.js';
import { textgen_types, textgenerationwebui_settings } from '../../../textgen-settings.js';
import { oai_settings } from '../../../openai.js';
import { WebLlmVectorProvider } from '../../vectors/webllm.js';
import { EXTENSION_NAME } from './carrot-state.js';
// ============================================================================
// CONSTANTS
// ============================================================================
const extensionName = EXTENSION_NAME;
const MODULE_NAME = 'fullsheet-rag';
// Collection ID prefix for CarrotKernel fullsheets
const COLLECTION_PREFIX = 'carrotkernel_char_';
// Section header regex for fullsheet chunking - LANGUAGE-AGNOSTIC & VERY PERMISSIVE
// \S+ matches ANY Unicode non-whitespace (Chinese/Japanese/Korean/Arabic/Cyrillic/etc.)
// Examples: "## SECTION 1/8", "##セクション 1/8", "# 部分 1/8", "SECCIÓN 1/8", "##Раздел 1/8"
const SECTION_HEADER_REGEX = /^#{1,2}\s*\S+\s+\d+\/\d+/mi;
// Minimum size to be considered a fullsheet (3000 chars - more permissive)
const FULLSHEET_MIN_SIZE = 3000;
// BunnymoTags pattern - UNIVERSAL TAG STRUCTURE (works for ALL languages)
// [^\s>]+ matches ANY Unicode non-whitespace (not just English letters)
// Examples: <NAME:John>, <名前:太郎>, <NOMBRE:Juan>, <ИМЯ:Иван>, <이름:철수>, <اسم:أحمد>
const BUNNYMOTAGS_PATTERN = /<[^\s>]+:[^>]+>/;
// Prompt tag used when injecting results into the model
const RAG_PROMPT_TAG = 'carrotkernel_rag';
const RAG_BUTTON_CLASS = 'carrot-rag-fullsheet-button';
const vectorApiSourcesRequiringUrl = ['ollama', 'llamacpp', 'vllm', 'koboldcpp'];
const DEFAULT_SECTION_TITLE = 'Fullsheet';
const MAX_DEBUG_PREVIEW = 180;
const webllmProvider = new WebLlmVectorProvider();
function getCurrentContextLevel() {
const settings = extension_settings[extensionName]?.rag || {};
return settings.contextLevel || 'global';
}
function ensureRagState() {
// CRITICAL: Never overwrite extension_settings[extensionName] completely
// This would destroy all user settings on page refresh
if (!extension_settings[extensionName]) {
// Only initialize if it truly doesn't exist (first-time setup)
// Removed console.warn - initialization is silent
extension_settings[extensionName] = {};
}
if (!extension_settings[extensionName].rag) {
extension_settings[extensionName].rag = {};
}
if (!extension_settings[extensionName].rag.library) {
extension_settings[extensionName].rag.library = {};
}
return extension_settings[extensionName].rag;
}
function getContextualLibrary() {
const contextLevel = getCurrentContextLevel();
const context = getContext();
// Ensure base structure exists
ensureRagState();
const ragState = extension_settings[extensionName].rag;
if (!ragState.libraries) {
ragState.libraries = {
global: {},
character: {},
chat: {}
};
}
// Get the appropriate library based on context level
switch (contextLevel) {
case 'character':
const charId = context?.characterId;
if (charId !== null && charId !== undefined) {
if (!ragState.libraries.character[charId]) {
ragState.libraries.character[charId] = {};
}
return ragState.libraries.character[charId];
}
// Fallback to global if no character
return ragState.libraries.global;
case 'chat':
const chatId = context?.chatId;
if (chatId) {
if (!ragState.libraries.chat[chatId]) {
ragState.libraries.chat[chatId] = {};
}
return ragState.libraries.chat[chatId];
}
// Fallback to global if no chat
return ragState.libraries.global;
case 'global':
default:
return ragState.libraries.global;
}
}
/**
* Get ALL contextual libraries relevant to the current chat context
* Returns: { global: {...}, character: {...}, chat: {...} } with actual library objects
*/
function getAllContextualLibraries() {
const context = getContext();
ensureRagState();
const ragState = extension_settings[extensionName].rag;
if (!ragState.libraries) {
ragState.libraries = {
global: {},
character: {},
chat: {}
};
}
const result = {
global: ragState.libraries.global || {},
character: null,
chat: null
};
// Add character library if we have a character context
const charId = context?.characterId;
if (charId !== null && charId !== undefined) {
if (!ragState.libraries.character[charId]) {
ragState.libraries.character[charId] = {};
}
result.character = ragState.libraries.character[charId];
}
// Add chat library if we have a chat context
const chatId = context?.chatId;
if (chatId) {
if (!ragState.libraries.chat[chatId]) {
ragState.libraries.chat[chatId] = {};
}
result.chat = ragState.libraries.chat[chatId];
}
return result;
}
// ============================================================================
// VECTOR API HELPERS
// ============================================================================
/**
* Retrieve vector settings, preferring the core SillyTavern vectors extension configuration
* so CarrotKernel stays perfectly in sync with the built-in RAG pipeline.
* Falls back to local overrides only if the core extension isn't available yet.
*/
function getVectorSettings() {
const defaults = {
source: 'transformers',
use_alt_endpoint: false,
alt_endpoint_url: '',
togetherai_model: 'togethercomputer/m2-bert-80M-32k-retrieval',
openai_model: 'text-embedding-ada-002',
cohere_model: 'embed-english-v3.0',
ollama_model: 'mxbai-embed-large',
ollama_keep: false,
vllm_model: '',
webllm_model: '',
google_model: 'text-embedding-005',
};
const coreVectorSettings = extension_settings?.vectors;
if (coreVectorSettings) {
return {
source: coreVectorSettings.source ?? defaults.source,
use_alt_endpoint: coreVectorSettings.use_alt_endpoint ?? defaults.use_alt_endpoint,
alt_endpoint_url: coreVectorSettings.alt_endpoint_url ?? defaults.alt_endpoint_url,
togetherai_model: coreVectorSettings.togetherai_model ?? defaults.togetherai_model,
openai_model: coreVectorSettings.openai_model ?? defaults.openai_model,
cohere_model: coreVectorSettings.cohere_model ?? defaults.cohere_model,
ollama_model: coreVectorSettings.ollama_model ?? defaults.ollama_model,
ollama_keep: coreVectorSettings.ollama_keep ?? defaults.ollama_keep,
vllm_model: coreVectorSettings.vllm_model ?? defaults.vllm_model,
webllm_model: coreVectorSettings.webllm_model ?? defaults.webllm_model,
google_model: coreVectorSettings.google_model ?? defaults.google_model,
};
}
const ragSettings = extension_settings[extensionName]?.rag || {};
return {
source: ragSettings.vectorSource || defaults.source,
use_alt_endpoint: ragSettings.useAltUrl ?? defaults.use_alt_endpoint,
alt_endpoint_url: ragSettings.altUrl || defaults.alt_endpoint_url,
togetherai_model: ragSettings.togetheraiModel || defaults.togetherai_model,
openai_model: ragSettings.openaiModel || defaults.openai_model,
cohere_model: ragSettings.cohereModel || defaults.cohere_model,
ollama_model: ragSettings.ollamaModel || defaults.ollama_model,
ollama_keep: ragSettings.ollamaKeep ?? defaults.ollama_keep,
vllm_model: ragSettings.vllmModel || defaults.vllm_model,
webllm_model: ragSettings.webllmModel || defaults.webllm_model,
google_model: ragSettings.googleModel || defaults.google_model,
};
}
/**
* Builds the base body shared across vector API calls.
* Mirrors native Vectors extension logic so all backend providers keep working.
* @param {object} overrides
* @returns {object}
*/
function getVectorsRequestBody(overrides = {}) {
const vectors = getVectorSettings();
const body = Object.assign({}, overrides);
switch (vectors.source) {
case 'extras':
body.extrasUrl = extension_settings.apiUrl;
body.extrasKey = extension_settings.apiKey;
break;
case 'togetherai':
body.model = vectors.togetherai_model;
break;
case 'openai':
case 'mistral':
body.model = vectors.openai_model;
break;
case 'nomicai':
// No client configuration required; handled server-side with stored secret
break;
case 'cohere':
body.model = vectors.cohere_model;
break;
case 'ollama':
body.model = vectors.ollama_model;
body.apiUrl = vectors.use_alt_endpoint && vectors.alt_endpoint_url
? vectors.alt_endpoint_url
: textgenerationwebui_settings.server_urls[textgen_types.OLLAMA];
body.keep = !!vectors.ollama_keep;
break;
case 'llamacpp':
body.apiUrl = vectors.use_alt_endpoint && vectors.alt_endpoint_url
? vectors.alt_endpoint_url
: textgenerationwebui_settings.server_urls[textgen_types.LLAMACPP];
break;
case 'vllm':
body.model = vectors.vllm_model;
body.apiUrl = vectors.use_alt_endpoint && vectors.alt_endpoint_url
? vectors.alt_endpoint_url
: textgenerationwebui_settings.server_urls[textgen_types.VLLM];
break;
case 'webllm':
body.model = vectors.webllm_model;
break;
case 'palm':
body.model = vectors.google_model;
body.api = 'makersuite';
break;
case 'vertexai':
body.model = vectors.google_model;
body.api = 'vertexai';
body.vertexai_auth_mode = oai_settings.vertexai_auth_mode;
body.vertexai_region = oai_settings.vertexai_region;
body.vertexai_express_project_id = oai_settings.vertexai_express_project_id;
break;
default:
break;
}
return body;
}
/**
* Build additional arguments required by some embeddings backends.
* @param {string[]} items
* @returns {Promise<object>}
*/
async function getAdditionalVectorArgs(items) {
const vectors = getVectorSettings();
switch (vectors.source) {
case 'webllm': {
if (!items.length) return {};
const embeddings = await webllmProvider.embedTexts(items, vectors.webllm_model);
const result = {};
for (let i = 0; i < items.length; i++) {
result[items[i]] = embeddings[i];
}
return { embeddings: result };
}
case 'koboldcpp': {
if (!items.length) return {};
const response = await fetch('/api/backends/kobold/embed', {
method: 'POST',
headers: getRequestHeaders(),
body: JSON.stringify({
items: items,
server: vectors.use_alt_endpoint && vectors.alt_endpoint_url
? vectors.alt_endpoint_url
: textgenerationwebui_settings.server_urls[textgen_types.KOBOLDCPP],
}),
});
if (!response.ok) {
throw new Error('Failed to get KoboldCpp embeddings');
}
const { embeddings, model } = await response.json();
return { embeddings, model };
}
default:
return {};
}
}
/**
* Basic validation to help users notice incomplete configuration (e.g. Ollama without URL).
*/
function ensureVectorConfig() {
const vectors = getVectorSettings();
if (vectorApiSourcesRequiringUrl.includes(vectors.source) && !vectors.use_alt_endpoint && !vectors.alt_endpoint_url) {
CarrotDebug.error(`CarrotKernel RAG: Source "${vectors.source}" usually needs a server URL. Set one in the Vectors extension if you see embedding errors.`);
}
}
/**
* Get saved hashes for a collection (checks if collection exists)
*/
async function apiGetSavedHashes(collectionId) {
ensureVectorConfig();
const body = {
...getVectorsRequestBody(await getAdditionalVectorArgs([])),
collectionId: collectionId,
source: getVectorSettings().source,
};
debugLog('[API] apiGetSavedHashes request body:', body); // ADDED
const response = await fetch('/api/vector/list', {
method: 'POST',
headers: getRequestHeaders(),
credentials: 'same-origin',
body: JSON.stringify(body), // MODIFIED to use body var
});
if (!response.ok) {
const errorText = await response.text(); // ADDED
debugLog('[API] apiGetSavedHashes ERROR:', { status: response.status, text: errorText }); // ADDED
throw new Error(`Failed to get saved hashes for collection ${collectionId}. Status: ${response.status}. Message: ${errorText}`); // MODIFIED
}
const jsonResponse = await response.json(); // ADDED
debugLog('[API] apiGetSavedHashes SUCCESS response:', jsonResponse); // ADDED
return jsonResponse; // MODIFIED
}
/**
* Insert vector items into a collection
*/
async function apiInsertVectorItems(collectionId, items) {
ensureVectorConfig();
const args = await getAdditionalVectorArgs(items.map(item => item.text));
const body = {
...getVectorsRequestBody(args),
collectionId: collectionId,
items: items.map(item => ({
hash: item.hash,
text: item.text,
index: item.index,
})),
source: getVectorSettings().source,
};
debugLog('[API] apiInsertVectorItems request body:', body); // ADDED
const response = await fetch('/api/vector/insert', {
method: 'POST',
headers: getRequestHeaders(),
credentials: 'same-origin',
body: JSON.stringify(body), // MODIFIED
});
if (!response.ok) {
const errorText = await response.text(); // ADDED
debugLog('[API] apiInsertVectorItems ERROR:', { status: response.status, text: errorText }); // ADDED
throw new Error(`Failed to insert vector items for collection ${collectionId}. Status: ${response.status}. Message: ${errorText}`); // MODIFIED
}
debugLog('[API] apiInsertVectorItems SUCCESS'); // ADDED
}
/**
* Query a vector collection
*/
async function apiQueryCollection(collectionId, searchText, topK, threshold = 0.2) {
ensureVectorConfig();
const args = await getAdditionalVectorArgs([searchText]);
const response = await fetch('/api/vector/query', {
method: 'POST',
headers: getRequestHeaders(),
credentials: 'same-origin',
body: JSON.stringify({
...getVectorsRequestBody(args),
collectionId: collectionId,
searchText: searchText,
topK: topK,
source: getVectorSettings().source,
threshold: threshold,
}),
});
if (!response.ok) {
throw new Error(`Failed to query collection ${collectionId}`);
}
return await response.json();
}
/**
* Delete specific hashes from a vector collection
*/
async function apiDeleteVectorHashes(collectionId, hashes) {
ensureVectorConfig();
const response = await fetch('/api/vector/delete', {
method: 'POST',
headers: getRequestHeaders(),
credentials: 'same-origin',
body: JSON.stringify({
collectionId: collectionId,
hashes: hashes,
source: getVectorSettings().source,
}),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to delete vectors from ${collectionId}. Status: ${response.status}. Message: ${errorText}`);
}
return await response.json();
}
/**
* Delete an entire vector collection
*/
async function apiDeleteCollection(collectionId) {
ensureVectorConfig();
const response = await fetch('/api/vector/purge', {
method: 'POST',
headers: getRequestHeaders(),
credentials: 'same-origin',
body: JSON.stringify({
collectionId: collectionId,
source: getVectorSettings().source,
}),
});
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Failed to purge collection ${collectionId}. Status: ${response.status}. Message: ${errorText}`);
}
return await response.json();
}
/**
* Update chunks in the library with modified data from chunk visualizer
* Handles metadata updates (keywords, weights, links) and text changes (re-vectorization)
*
* @param {string} collectionId - Collection ID to update
* @param {Object} chunks - Modified chunks object { hash: chunkData, ... }
* @returns {Promise<void>}
*/
async function updateChunksInLibrary(collectionId, chunks) {
CarrotDebug.ui('📝 [updateChunksInLibrary] Starting update...', {
collectionId,
chunkCount: Object.keys(chunks).length
});
const library = getContextualLibrary();
if (!library[collectionId]) {
throw new Error(`Collection ${collectionId} not found in library`);
}
const chunksToRevectorize = [];
const updatedHashes = [];
// Process each modified chunk
for (const [hash, chunkData] of Object.entries(chunks)) {
const existingChunk = library[collectionId][hash];
if (!existingChunk) {
CarrotDebug.error(`⚠️ Chunk ${hash} not found in library - skipping`);
continue;
}
// Normalize chunk data structure (handle both flat and nested metadata)
const chunkText = chunkData.text;
const metadata = chunkData.metadata || chunkData;
// Check if text content changed (requires re-vectorization)
const textChanged = existingChunk.text !== chunkText;
if (textChanged) {
CarrotDebug.ui(`🔄 Text changed for chunk ${hash} - will re-vectorize`);
chunksToRevectorize.push({
hash: parseInt(hash),
text: chunkText,
index: metadata.index || 0,
metadata: {
...metadata,
// Ensure text is NOT stored in metadata (it's separate)
text: undefined
}
});
}
// Update library with new data (metadata + text)
// Spread metadata first, then override with text to ensure structure
const { text: _, ...metadataOnly } = metadata;
library[collectionId][hash] = {
text: chunkText,
...metadataOnly
};
updatedHashes.push(hash);
}
// Save updated library to extension_settings
saveSettingsDebounced();
CarrotDebug.ui(`✅ Updated ${updatedHashes.length} chunks in library`);
// Re-vectorize chunks with changed text
if (chunksToRevectorize.length > 0) {
CarrotDebug.ui(`🔬 Re-vectorizing ${chunksToRevectorize.length} chunks with text changes...`);
try {
// Delete old vectors
const hashesToDelete = chunksToRevectorize.map(c => c.hash);
await apiDeleteVectorHashes(collectionId, hashesToDelete);
CarrotDebug.ui(`🗑️ Deleted ${hashesToDelete.length} old vectors`);
// Insert new vectors with updated text
const itemsToInsert = chunksToRevectorize;
await apiInsertVectorItems(collectionId, itemsToInsert);
CarrotDebug.ui(`✅ Re-vectorized ${itemsToInsert.length} chunks`);
toastr.success(`Updated ${updatedHashes.length} chunks (${chunksToRevectorize.length} re-vectorized)`);
} catch (error) {
CarrotDebug.error('❌ Re-vectorization failed:', error);
toastr.error(`Failed to re-vectorize chunks: ${error.message}`);
throw error;
}
} else {
toastr.success(`Updated ${updatedHashes.length} chunks`);
}
CarrotDebug.ui('✅ [updateChunksInLibrary] Update complete');
}
// ============================================================================
// SETTINGS MANAGEMENT
// ============================================================================
/**
* Get RAG settings with defaults
*/
function getRAGSettings() {
const ragState = ensureRagState();
return {
enabled: ragState.enabled ?? false,
simpleChunking: ragState.simpleChunking ?? false,
chunkSize: ragState.chunkSize ?? 1000,
chunkOverlap: ragState.chunkOverlap ?? 300,
topK: ragState.topK ?? 3,
scoreThreshold: ragState.scoreThreshold ?? 0.15,
queryContext: ragState.queryContext ?? 3, // Number of recent messages to use for query
injectionDepth: ragState.injectionDepth ?? 4,
injectionRole: ragState.injectionRole ?? 'system',
autoVectorize: ragState.autoVectorize ?? true,
debugMode: ragState.debugMode ?? false,
smartCrossReference: ragState.smartCrossReference ?? true,
crosslinkThreshold: ragState.crosslinkThreshold ?? 0.25,
lastEmbeddingSource: ragState.lastEmbeddingSource ?? null,
lastEmbeddingModel: ragState.lastEmbeddingModel ?? null,
keywordFallback: ragState.keywordFallback ?? true,
keywordFallbackPriority: ragState.keywordFallbackPriority ?? false,
keywordFallbackLimit: ragState.keywordFallbackLimit ?? 2,
};
}
/**
* Save RAG settings
*/
function saveRAGSettings(ragSettings) {
const ragState = ensureRagState();
Object.assign(ragState, ragSettings);
saveSettingsDebounced();
}
/**
* Debug logging helper
*/
function debugLog(message, data = null) {
// Check BOTH extension enabled AND debug mode
const mainSettings = extension_settings[extensionName];
if (!mainSettings?.enabled) return; // Extension disabled - no logs
if (!mainSettings?.debugMode) return; // Debug mode off - no logs (use MAIN debug mode, not RAG-specific)
CarrotDebug.ui(`🔍 [CarrotKernel RAG] ${message}`, data || '');
}
// ============================================================================
// CHARACTER NAME & COLLECTION
// ============================================================================
/**
* Generate collection ID for a character
*
* @param {string} characterName - Character name
* @returns {string} Collection ID (e.g., "carrotkernel_char_Atsu")
*/
function generateCollectionId(characterName, contextOverride = null) {
// Sanitize character name (keep Unicode letters, numbers, and underscores)
// This preserves non-English characters while removing only problematic symbols
const sanitized = characterName
.replace(/[\s\-]+/g, '_') // Replace spaces and hyphens with underscores
.replace(/[^\p{L}\p{N}_]/gu, '_') // Keep Unicode letters (\p{L}), numbers (\p{N}), and underscores
.replace(/_+/g, '_') // Collapse multiple underscores
.replace(/^_|_$/g, '') // Remove leading/trailing underscores
.toLowerCase();
// Include context level in collection ID to prevent cross-contamination
const contextLevel = contextOverride || getCurrentContextLevel();
const context = getContext();
let collectionId = `${COLLECTION_PREFIX}${sanitized}`;
// Add context suffix based on storage level
switch(contextLevel) {
case 'chat':
const chatId = context?.chatId;
if (chatId) {
// Include chat ID to keep chat-level embeddings separate
const safeChatId = String(chatId).replace(/[^a-z0-9_]/gi, '_').toLowerCase();
collectionId += `_chat_${safeChatId}`;
}
break;
case 'character':
const charId = context?.characterId;
if (charId !== null && charId !== undefined) {
// Include character ID to keep character-level embeddings separate
collectionId += `_charid_${charId}`;
}
break;
case 'global':
default:
// Global uses just the character name (shared across all contexts)
break;
}
return collectionId;
}
// ============================================================================
// FULLSHEET CHUNKING
// ============================================================================
const STOP_WORDS = new Set([
'the', 'a', 'an', 'and', 'or', 'but', 'in', 'on', 'at', 'to', 'for', 'of', 'with', 'by', 'from', 'as',
'is', 'are', 'was', 'were', 'be', 'been', 'being', 'have', 'has', 'had', 'do', 'does', 'did', 'will',
'would', 'could', 'should', 'may', 'might', 'must', 'can', 'this', 'that', 'these', 'those', 'it', 'its',
'his', 'her', 'their', 'he', 'she', 'they', 'them', 'we', 'you', 'i'
]);
/**
* Very lightweight stemming to help keyword overlap (handles plural/past variations).
* @param {string} word
* @returns {string}
*/
function normalizeKeyword(word) {
// Check if case-sensitive matching is enabled
const caseSensitive = extension_settings[extensionName]?.rag?.caseSensitiveKeywords || false;
// If case-sensitive, preserve original case; otherwise lowercase
let normalized = caseSensitive ? word : word.toLowerCase();
// Apply stemming only if not case-sensitive (stemming requires lowercase)
if (!caseSensitive) {
const replacements = [
/(?:ing|ingly)$/,
/(?:edly|edly)$/,
/(?:edly)$/,
/(?:tion|tions)$/,
/(?:ment|ments)$/,
/(?:ness|nesses)$/,
/(?:ally|ally)$/,
/(?:ies)$/,
/(?:ers|er)$/,
/(?:less)$/,
/(?:ful)$/,
/(?:ous)$/,
/(?:ly)$/,
/(?:ed)$/,
/(?:es)$/,
/(?:s)$/,
];
for (const regex of replacements) {
if (regex.test(normalized)) {
normalized = normalized.replace(regex, '');
break;
}
}
if (normalized.length < 4) {
normalized = word.toLowerCase();
}
}
return normalized;
}
const KEYWORD_GROUPS = {
identity: {
priority: 35,
keywords: ['identity', 'introduction', 'name', 'titles', 'title', 'role', 'occupation', 'species', 'gender', 'pronouns', 'age', 'core context', 'summary', 'overview', 'genre', 'archetype'],
},
physical: {
priority: 45,
keywords: ['physical', 'appearance', 'body', 'physique', 'build', 'height', 'weight', 'hair', 'eyes', 'skin', 'hands', 'aura', 'presence', 'intimate details', 'style', 'fashion'],
tagHints: ['PHYS', 'BUILD', 'SKIN', 'HAIR', 'STYLE'],
regexes: [
{ pattern: '\\bphysic(?:al|s)?\\b', flags: 'i' },
{ pattern: '\\bappearance\\b', flags: 'i' },
{ pattern: '\\baura\\b', flags: 'i' },
],
},
psyche: {
priority: 55,
keywords: ['psyche', 'behavior', 'psychology', 'motivation', 'moral', 'value system', 'personality', 'desire', 'fear', 'habit', 'vulnerability', 'growth'],
},
relational: {
priority: 60,
keywords: ['relationship', 'dynamic', 'bond', 'social', 'loyalty', 'alliances', 'power dynamic', 'manipulation', 'possessive', 'protective', 'interaction'],
tagHints: ['CHEMISTRY', 'RELATIONSHIP', 'CONFLICT'],
regexes: [
{ pattern: '\\bpower dynamic', flags: 'i' },
{ pattern: '\\brelationship\\b', flags: 'i' },
],
},
linguistic: {
priority: 40,
keywords: ['linguistic', 'voice', 'tone', 'speech', 'language', 'dialect', 'accent', 'phrases', 'expressions', 'kaomoji', 'verbal', 'communication', 'words', 'word choice'],
},
origin: {
priority: 35,
keywords: ['origin', 'history', 'backstory', 'timeline', 'legacy', 'heritage', 'ancestry', 'milestones', 'past', 'foundation'],
},
aesthetic: {
priority: 30,
keywords: ['aesthetic', 'style', 'presentation', 'fashion', 'silhouette', 'design', 'color palette', 'visual identity'],
},
chemistry: {
priority: 90,
keywords: ['chemistry', 'spark', 'connection', 'compatibility', 'resonance', 'magnetism', 'charge'],
regexes: [
{ pattern: '\\bchemistry\\b', flags: 'i' },
{ pattern: '\\bmagn(?:etism|etic)\\b', flags: 'i' },
],
},
dere: {
priority: 85,
keywords: ['dere', 'sadodere', 'tsundere', 'yandere', 'oujidere', 'kuudere', 'dandere', 'archetype'],
tagHints: ['Dere'],
regexes: [{ pattern: '\\bdere\\b', flags: 'i' }],
},
attachment: {
priority: 95,
keywords: ['attachment', 'bonding', 'fearful-avoidant', 'anxious', 'security', 'validation', 'trust', 'connection approach', 'conflict integration'],
tagHints: ['ATTACHMENT'],
regexes: [
{ pattern: '\\battachment\\b', flags: 'i' },
{ pattern: '\\bavoidant\\b', flags: 'i' },
],
},
trauma: {
priority: 120,
keywords: ['trauma', 'wound', 'wounds', 'scar', 'scarred', 'trigger', 'triggered', 'ptsd', 'flashback', 'fight response', 'freeze response', 'flight response', 'healing', 'coping', 'psychological wound', 'resilience'],
tagHints: ['TRAUMA', 'WOUND'],
regexes: [
{ pattern: '\\btrauma\\b', flags: 'i' },
{ pattern: '\\btrigger(?:ed|s)?\\b', flags: 'i' },
{ pattern: '\\bflashback\\b', flags: 'i' },
{ pattern: '\\bptsd\\b', flags: 'i' },
],
},
boundaries: {
priority: 130,
keywords: ['boundary', 'boundaries', 'limit', 'limits', 'consent', 'personal space', 'crossing the line', 'violation', 'respect', 'perimeter', 'barrier', 'invasion', 'permission'],
tagHints: ['BOUNDARIES', 'CONSENT'],
regexes: [
{ pattern: '\\bboundar(?:y|ies)\\b', flags: 'i' },
{ pattern: '\\bhard\\s+limit(s)?\\b', flags: 'i' },
{ pattern: '\\bsoft\\s+limit(s)?\\b', flags: 'i' },
{ pattern: '\\bcross(?:ed)?\\s+the\\s+line\\b', flags: 'i' },
{ pattern: '\\bconsent\\b', flags: 'i' },
{ pattern: '\\bpersonal\\s+space\\b', flags: 'i' },
],
},
flirting: {
priority: 100,
keywords: ['flirt', 'flirting', 'seduce', 'seduction', 'tease', 'teasing', 'coax', 'coquette', 'playful touch', 'cruel flirting', 'charm'],
tagHints: ['FLIRTING'],
regexes: [
{ pattern: '\\bflirt(?:ing|s)?\\b', flags: 'i' },
{ pattern: '\\bseduce(?:s|d|r)?\\b', flags: 'i' },
{ pattern: '\\bteas(?:e|ing)\\b', flags: 'i' },
],
},
jealousy: {
priority: 110,
keywords: ['jealous', 'jealousy', 'envious', 'possessive', 'territorial', 'threatened', 'insecure', 'clingy'],
tagHints: ['JEALOUSY'],
regexes: [
{ pattern: '\\bjealous(?:y)?\\b', flags: 'i' },
{ pattern: '\\bpossessive\\b', flags: 'i' },
{ pattern: '\\bterritorial\\b', flags: 'i' },
],
},
arousal: {
priority: 105,
keywords: ['arousal', 'aroused', 'turned on', 'excited', 'lust', 'desire', 'yearning', 'heated', 'breathless', 'horny'],
tagHints: ['AROUSAL', 'NSFW'],
regexes: [
{ pattern: '\\barous(?:al|ed)\\b', flags: 'i' },
{ pattern: '\\blust(?:ful)?\\b', flags: 'i' },
{ pattern: '\\bturned\\s+on\\b', flags: 'i' },
],
},
conflict: {
priority: 90,
keywords: ['conflict', 'resolution', 'de-escalation', 'deescalation', 'mediation', 'negotiation', 'intervention', 'hostility', 'argument', 'dispute', 'reconciliation'],
tagHints: ['CONFLICT', 'RESOLUTION'],
regexes: [
{ pattern: '\bconflicts?\b', flags: 'i' },
{ pattern: '\bresolution\b', flags: 'i' },
{ pattern: '\bde-?escalat', flags: 'i' },
],
},
hiddenDepths: {
priority: 45,
keywords: ['hidden', 'secret', 'depths', 'private', 'shame', 'fear', 'mask', 'reality', 'vulnerable', 'concealed'],
},
tagSynthesis: {
priority: 25,
keywords: ['tag', 'synthesis', 'metadata', 'bunnymotags', 'summary', 'consolidated'],
},
};
const KEYWORD_PRESETS = [
{ match: /Character Title|Core Identity|Context/i, groups: ['identity'] },
{ match: /Physical Manifestation/i, groups: ['physical'] },
{ match: /Psyche|Behavioral Matrix|Psychological Analysis/i, groups: ['psyche'] },
{ match: /Relational Dynamics|Social Architecture|Relationship/i, groups: ['relational', 'jealousy', 'boundaries'] },
{ match: /Linguistic Signature|Communication DNA/i, groups: ['linguistic'] },
{ match: /Origin Story|Historical Tapestry/i, groups: ['origin'] },
{ match: /Aesthetic Expression|Style Philosophy/i, groups: ['aesthetic'] },
{ match: /Trauma|Resilience/i, groups: ['trauma'] },
{ match: /Boundar/i, groups: ['boundaries'] },
{ match: /Flirt|Flirtation|Flirtation Signature/i, groups: ['flirting', 'arousal'] },
{ match: /Attachment/i, groups: ['attachment'] },
{ match: /Chemistry/i, groups: ['chemistry', 'arousal', 'flirting'] },
{ match: /Dere/i, groups: ['dere', 'flirting'] },
{ match: /Jealousy Dynamics/i, groups: ['jealousy'] },
{ match: /Arousal Architecture/i, groups: ['arousal'] },
{ match: /Conflict Resolution/i, groups: ['conflict', 'boundaries'] },
{ match: /Boundary Architecture/i, groups: ['boundaries'] },
{ match: /Hidden Depths|Secret Architecture/i, groups: ['hiddenDepths'] },
{ match: /Tag Synthesis/i, groups: ['tagSynthesis'] },
];
const KEYWORD_GROUP_REGEX_RULES = KEYWORD_PRESETS
.filter(preset => preset.regexes)
.flatMap(preset => preset.regexes || []);
const KEYWORD_PRIORITY_CACHE = new Map();
const KEYWORD_REGEX_LOOKUP = [];
for (const [groupKey, data] of Object.entries(KEYWORD_GROUPS)) {
const priority = data.priority ?? 20;
if (Array.isArray(data.keywords)) {
for (const keyword of data.keywords) {
KEYWORD_PRIORITY_CACHE.set(normalizeKeyword(keyword), priority);
}
}
if (Array.isArray(data.regexes)) {
for (const regexEntry of data.regexes) {
KEYWORD_REGEX_LOOKUP.push({
group: groupKey,
pattern: regexEntry.pattern,
flags: regexEntry.flags || 'i',
priority,
});
}
}
}
const CUSTOM_KEYWORD_PRIORITY = 140;
function getKeywordPriority(keyword) {
return KEYWORD_PRIORITY_CACHE.get(normalizeKeyword(keyword)) ?? 20;
}
/**
* Extract ONLY truly semantic keywords from text - not every single word!
* Uses frequency analysis and importance weighting.
* @param {string} text
* @returns {string[]}
*/
/**
* Extract keywords using hybrid approach:
* 1. Title/topic words (language-agnostic)
* 2. Frequency analysis (language-agnostic)
* 3. Semantic mapping for English enhancement
*/
function extractKeywords(text, sectionTitle = '', topic = '') {
// Language-agnostic keyword extraction with weighted frequency analysis
const weightedKeywords = new Map(); // lowercase -> { word, weight, sources }
// STEP 1: Extract section title/header words BUT ONLY if they appear in the text
// This prevents headers from becoming keywords in unrelated sections
const titleText = (sectionTitle + ' ' + topic)
.replace(/[^\p{L}\s]/gu, ' ') // Keep all letters (Unicode), remove punctuation
.split(/\s+/)
.filter(w => w.length >= 3 && !STOP_WORDS.has(w.toLowerCase()));
const lowerText = text.toLowerCase();
titleText.forEach(word => {
const lower = word.toLowerCase();
// CRITICAL: Only add header word if it actually appears in THIS section's text
if (lowerText.includes(lower)) {
if (!weightedKeywords.has(lower)) {
weightedKeywords.set(lower, {
word: lower,
weight: 10.0, // HIGH base weight for section header (only when present in text)
sources: ['header']
});
} else {
const entry = weightedKeywords.get(lower);
entry.weight += 10.0;
entry.sources.push('header');
}
}
});
// STEP 2: Extract quoted words (HIGH WEIGHT - user explicitly quoted them)
const quotedMatches = text.matchAll(/["'"`]([\p{L}\s]{3,}?)["'"`]/gu);