-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.ts
1154 lines (1023 loc) · 37.6 KB
/
main.ts
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 {
App,
Editor,
MarkdownView,
Modal,
Menu,
Notice,
Plugin,
PluginSettingTab,
Setting,
View,
requestUrl,
setIcon,
TextComponent,
ButtonComponent,
} from "obsidian";
import { generateAndAppendTags } from "./autoTagger";
import { UpdateNoticeModal } from "./updateNoticeModal";
import { RAGManager } from './rag';
import { BacklinkGenerator } from './backlinkGenerator';
import { RAGChatModal } from './ragChatModal';
// Remember to rename these classes and interfaces!
export interface OLocalLLMSettings {
serverAddress: string;
llmModel: string;
stream: boolean;
customPrompt: string;
outputMode: string;
personas: string;
maxConvHistory: number;
responseFormatting: boolean;
responseFormatPrepend: string;
responseFormatAppend: string;
lastVersion: string;
embeddingModelName: string;
}
interface ConversationEntry {
prompt: string;
response: string;
}
const DEFAULT_SETTINGS: OLocalLLMSettings = {
serverAddress: "http://localhost:1234",
llmModel: "llama3",
stream: false,
customPrompt: "create a todo list from the following text:",
outputMode: "replace",
personas: "default",
maxConvHistory: 0,
responseFormatting: false,
responseFormatPrepend: "``` LLM Helper - generated response \n\n",
responseFormatAppend: "\n\n```",
lastVersion: "0.0.0",
embeddingModelName: "nomic-embed-text",
};
const personasDict: { [key: string]: string } = {
"default": "Default",
"physics": "Physics expert",
"fitness": "Fitness expert",
"developer": "Software Developer",
"stoic": "Stoic Philosopher",
"productmanager": "Product Manager",
"techwriter": "Technical Writer",
"creativewriter": "Creative Writer",
"tpm": "Technical Program Manager",
"engineeringmanager": "Engineering Manager",
"executive": "Executive",
"officeassistant": "Office Assistant"
};
export default class OLocalLLMPlugin extends Plugin {
settings: OLocalLLMSettings;
modal: any;
conversationHistory: ConversationEntry[] = [];
isKillSwitchActive: boolean = false;
public ragManager: RAGManager;
private backlinkGenerator: BacklinkGenerator;
async checkForUpdates() {
const currentVersion = this.manifest.version;
const lastVersion = this.settings.lastVersion || "0.0.0";
//const lastVersion = "0.0.0";
if (currentVersion !== lastVersion) {
new UpdateNoticeModal(this.app, currentVersion).open();
this.settings.lastVersion = currentVersion;
await this.saveSettings();
}
}
async onload() {
await this.loadSettings();
this.checkForUpdates();
// Initialize RAGManager
this.ragManager = new RAGManager(this, this.app.vault, this.settings);
// Initialize BacklinkGenerator
this.backlinkGenerator = new BacklinkGenerator(this.ragManager, this.app.vault);
// Add command for RAG Backlinks
this.addCommand({
id: 'generate-rag-backlinks',
name: 'Generate RAG Backlinks (BETA)',
callback: this.handleGenerateBacklinks.bind(this),
});
// Remove the automatic indexing
// this.indexNotes();
this.addCommand({
id: 'rag-chat',
name: 'Chat with your notes (RAG) - BETA',
callback: () => {
new Notice("This is a beta feature. Please use with caution. Please make sure you have indexed your notes before using this feature.");
const ragChatModal = new RAGChatModal(this.app, this.settings, this.ragManager);
ragChatModal.open();
},
});
this.addCommand({
id: "summarize-selected-text",
name: "Summarize selected text",
editorCallback: (editor: Editor, view: MarkdownView) => {
this.isKillSwitchActive = false; // Reset kill switch state
let selectedText = this.getSelectedText();
if (selectedText.length > 0) {
processText(
selectedText,
"Summarize the following text (maintain verbs and pronoun forms, also retain the markdowns):",
this
);
}
},
});
this.addCommand({
id: "makeitprof-selected-text",
name: "Make selected text sound professional",
editorCallback: (editor: Editor, view: MarkdownView) => {
this.isKillSwitchActive = false; // Reset kill switch state
let selectedText = this.getSelectedText();
if (selectedText.length > 0) {
processText(
selectedText,
"Make the following sound professional (maintain verbs and pronoun forms, also retain the markdowns):",
this
);
}
},
});
this.addCommand({
id: "actionitems-selected-text",
name: "Generate action items from selected text",
editorCallback: (editor: Editor, view: MarkdownView) => {
this.isKillSwitchActive = false; // Reset kill switch state
let selectedText = this.getSelectedText();
if (selectedText.length > 0) {
processText(
selectedText,
"Generate action items based on the following text (use or numbers based on context):",
this
);
}
},
});
this.addCommand({
id: "custom-selected-text",
name: "Run Custom prompt (from settings) on selected text",
editorCallback: (editor: Editor, view: MarkdownView) => {
this.isKillSwitchActive = false; // Reset kill switch state
new Notice("Custom prompt: " + this.settings.customPrompt);
let selectedText = this.getSelectedText();
if (selectedText.length > 0) {
processText(
selectedText,
this.settings.customPrompt,
this
);
}
},
});
this.addCommand({
id: "gentext-selected-text",
name: "Use SELECTED text as your prompt",
editorCallback: (editor: Editor, view: MarkdownView) => {
this.isKillSwitchActive = false; // Reset kill switch state
let selectedText = this.getSelectedText();
if (selectedText.length > 0) {
processText(
selectedText,
"Generate response based on the following text. This is your prompt:",
this
);
}
},
});
this.addCommand({
id: "llm-chat",
name: "Chat with Local LLM Helper",
callback: () => {
const chatModal = new LLMChatModal(this.app, this.settings);
chatModal.open();
},
});
this.addCommand({
id: "llm-hashtag",
name: "Generate hashtags for selected text",
callback: () => {
generateAndAppendTags(this.app, this.settings);
},
});
this.addRibbonIcon("brain-cog", "LLM Context", (event) => {
const menu = new Menu();
menu.addItem((item) =>
item
.setTitle("Chat with LLM Helper")
.setIcon("messages-square")
.onClick(() => {
new LLMChatModal(this.app, this.settings).open();
})
);
menu.addItem((item) =>
item
.setTitle("Summarize")
.setIcon("sword")
.onClick(async () => {
this.isKillSwitchActive = false; // Reset kill switch state
let selectedText = this.getSelectedText();
if (selectedText.length > 0) {
processText(
selectedText,
"Summarize the following text (maintain verbs and pronoun forms, also retain the markdowns):",
this
);
}
})
);
menu.addItem((item) =>
item
.setTitle("Make it professional")
.setIcon("school")
.onClick(async () => {
this.isKillSwitchActive = false; // Reset kill switch state
let selectedText = this.getSelectedText();
if (selectedText.length > 0) {
processText(
selectedText,
"Make the following sound professional (maintain verbs and pronoun forms, also retain the markdowns):",
this
);
}
})
);
menu.addItem((item) =>
item
.setTitle("Use as prompt")
.setIcon("lightbulb")
.onClick(async () => {
this.isKillSwitchActive = false; // Reset kill switch state
let selectedText = this.getSelectedText();
if (selectedText.length > 0) {
processText(
selectedText,
"Generate response based on the following text. This is your prompt:",
this
);
}
})
);
menu.addItem((item) =>
item
.setTitle("Generate action items")
.setIcon("list-todo")
.onClick(async () => {
this.isKillSwitchActive = false; // Reset kill switch state
let selectedText = this.getSelectedText();
if (selectedText.length > 0) {
processText(
selectedText,
"Generate action items based on the following text (use or numbers based on context):",
this
);
}
})
);
menu.addItem((item) =>
item
.setTitle("Custom prompt")
.setIcon("pencil")
.onClick(async () => {
this.isKillSwitchActive = false; // Reset kill switch state
new Notice(
"Custom prompt: " + this.settings.customPrompt
);
let selectedText = this.getSelectedText();
if (selectedText.length > 0) {
processText(
selectedText,
this.settings.customPrompt,
this
);
}
})
);
menu.addItem((item) =>
item
.setTitle("Generate tags")
.setIcon("hash")
.onClick(async () => {
new Notice(
"Generating hashtags"
);
let selectedText = this.getSelectedText();
if (selectedText.length > 0) {
generateAndAppendTags(this.app, this.settings);
}
})
);
menu.addItem((item) =>
item
.setTitle("Kill Switch")
.setIcon("x-circle")
.onClick(() => {
this.isKillSwitchActive = true;
new Notice("LLM Helper process stopped");
})
);
menu.showAtMouseEvent(event);
});
const statusBarItemEl = this.addStatusBarItem();
statusBarItemEl.setText("LLM Helper: Ready");
this.addSettingTab(new OLLMSettingTab(this.app, this));
}
private getSelectedText() {
let view = this.app.workspace.getActiveViewOfType(MarkdownView);
if (!view) {
new Notice("No active view");
return "";
} else {
let view_mode = view.getMode();
switch (view_mode) {
case "preview":
new Notice("Does not work in preview preview");
return "";
case "source":
if ("editor" in view) {
return view.editor.getSelection();
}
break;
default:
new Notice("Unknown view mode");
return "";
}
}
return "";
}
onunload() {}
async loadSettings() {
this.settings = Object.assign(
{},
DEFAULT_SETTINGS,
await this.loadData()
);
}
async saveSettings() {
await this.saveData(this.settings);
}
async indexNotes() {
new Notice('Indexing notes for RAG...');
try {
await this.ragManager.indexNotes(progress => {
// You can use the progress value here if needed
console.log(`Indexing progress: ${progress * 100}%`);
});
new Notice('Notes indexed successfully!');
} catch (error) {
console.error('Error indexing notes:', error);
new Notice('Failed to index notes. Check console for details.');
}
}
async handleGenerateBacklinks() {
const activeView = this.app.workspace.getActiveViewOfType(MarkdownView);
if (!activeView) {
new Notice('No active Markdown view');
return;
}
const editor = activeView.editor;
const selectedText = editor.getSelection();
if (!selectedText) {
new Notice('No text selected');
return;
}
new Notice('Generating backlinks...');
const backlinks = await this.backlinkGenerator.generateBacklinks(selectedText);
if (backlinks.length > 0) {
editor.replaceSelection(`${selectedText}\n\nRelated:\n${backlinks.join('\n')}`);
new Notice(`Generated ${backlinks.length} backlinks`);
} else {
new Notice('No relevant backlinks found');
}
}
}
class OLLMSettingTab extends PluginSettingTab {
plugin: OLocalLLMPlugin;
private indexingProgressBar: HTMLProgressElement | null = null;
private indexedFilesCountSetting: Setting | null = null;
constructor(app: App, plugin: OLocalLLMPlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const { containerEl } = this;
containerEl.empty();
new Setting(containerEl)
.setName("Server address")
.setDesc("Full server URL (including protocol and port if needed). E.g., http://localhost:1234 or https://api.example.com")
.addText((text) =>
text
.setPlaceholder("Enter full server URL")
.setValue(this.plugin.settings.serverAddress)
.onChange(async (value) => {
this.plugin.settings.serverAddress = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName("LLM model")
.setDesc("Use this for Ollama and other servers that require this. LMStudio seems to ignore model name.")
.addText((text) =>
text
.setPlaceholder("Model name")
.setValue(this.plugin.settings.llmModel)
.onChange(async (value) => {
this.plugin.settings.llmModel = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName("Custom prompt")
.setDesc("create your own prompt - for your specific niche needs")
.addText((text) =>
text
.setPlaceholder(
"create action items from the following text:"
)
.setValue(this.plugin.settings.customPrompt)
.onChange(async (value) => {
this.plugin.settings.customPrompt = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName("Streaming")
.setDesc(
"Enable to receive the response in real-time, word by word."
)
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.stream) // Assume 'stream' exists in your settings
.onChange(async (value) => {
this.plugin.settings.stream = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName("Output Mode")
.setDesc("Choose how to handle generated text")
.addDropdown((dropdown) =>
dropdown
.addOption("replace", "Replace selected text")
.addOption("append", "Append after selected text")
.setValue(this.plugin.settings.outputMode)
.onChange(async (value) => {
this.plugin.settings.outputMode = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName("Personas")
.setDesc("Choose persona for your AI agent")
.addDropdown(dropdown => {
for (const key in personasDict) { // Iterate over keys directly
if (personasDict.hasOwnProperty(key)) {
dropdown.addOption(key, personasDict[key]);
}
}
dropdown.setValue(this.plugin.settings.personas)
.onChange(async (value) => {
this.plugin.settings.personas = value;
await this.plugin.saveSettings();
});
});
new Setting(containerEl)
.setName("Max conversation history")
.setDesc("Maximum number of conversation history to store (0-3)")
.addDropdown((dropdown) =>
dropdown
.addOption("0", "0")
.addOption("1", "1")
.addOption("2", "2")
.addOption("3", "3")
.setValue(this.plugin.settings.maxConvHistory.toString())
.onChange(async (value) => {
this.plugin.settings.maxConvHistory = parseInt(value);
await this.plugin.saveSettings();
})
);
//new settings for response formatting boolean default false
const responseFormattingToggle = new Setting(containerEl)
.setName("Response Formatting")
.setDesc("Enable to format the response into a separate block")
.addToggle((toggle) =>
toggle
.setValue(this.plugin.settings.responseFormatting)
.onChange(async (value) => {
this.plugin.settings.responseFormatting = value;
await this.plugin.saveSettings();
this.display(); // Refresh the settings tab
})
);
if (this.plugin.settings.responseFormatting) {
new Setting(containerEl)
.setName("Response Format Prepend")
.setDesc("Text to prepend to the formatted response")
.addText((text) =>
text
.setPlaceholder("``` LLM Helper - generated response \n\n")
.setValue(this.plugin.settings.responseFormatPrepend)
.onChange(async (value) => {
this.plugin.settings.responseFormatPrepend = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName("Response Format Append")
.setDesc("Text to append to the formatted response")
.addText((text) =>
text
.setPlaceholder("\n\n```")
.setValue(this.plugin.settings.responseFormatAppend)
.onChange(async (value) => {
this.plugin.settings.responseFormatAppend = value;
await this.plugin.saveSettings();
})
);
}
new Setting(containerEl)
.setName("Embedding Model Name")
.setDesc("Name of the model to use for embeddings")
.addText((text) =>
text
.setPlaceholder("llama2")
.setValue(this.plugin.settings.embeddingModelName)
.onChange(async (value) => {
this.plugin.settings.embeddingModelName = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName("Index Notes (BETA)")
.setDesc("Manually index all notes in the vault")
.addButton(button => button
.setButtonText("Start Indexing (BETA)")
.onClick(async () => {
button.setDisabled(true);
this.indexingProgressBar = containerEl.createEl("progress", {
attr: { value: 0, max: 100 }
});
const counterEl = containerEl.createEl("span", {
text: "Processing: 0/?",
cls: "indexing-counter"
});
const totalFiles = this.app.vault.getMarkdownFiles().length;
let processedFiles = 0;
try {
await this.plugin.ragManager.indexNotes((progress) => {
if (this.indexingProgressBar) {
this.indexingProgressBar.value = progress * 100;
}
processedFiles = Math.floor(progress * totalFiles);
counterEl.textContent = ` Processing: ${processedFiles}/${totalFiles}`;
counterEl.style.fontSize = 'smaller';
});
new Notice("Indexing complete!");
this.updateIndexedFilesCount();
} catch (error) {
console.error("Indexing error:", error);
new Notice("Error during indexing. Check console for details.");
} finally {
button.setDisabled(false);
if (this.indexingProgressBar) {
this.indexingProgressBar.remove();
this.indexingProgressBar = null;
}
counterEl.remove();
}
}));
this.indexedFilesCountSetting = new Setting(containerEl)
.setName("Indexed Files Count")
.setDesc("Number of files currently indexed")
.addText(text => text
.setValue(this.plugin.ragManager.getIndexedFilesCount().toString())
.setDisabled(true));
// Add note about memory vector store
containerEl.createEl("p", {
text: "Note: The vector store is currently held in memory and will be reset upon app reload. Future updates will implement persistent storage.",
cls: "setting-item-description"
});
}
updateIndexedFilesCount() {
if (this.indexedFilesCountSetting) {
const textComponent = this.indexedFilesCountSetting.components[0] as TextComponent;
textComponent.setValue(this.plugin.ragManager.getIndexedFilesCount().toString());
}
}
}
export function modifyPrompt(aprompt: string, personas: string): string {
if (personas === "default") {
return aprompt; // No prompt modification for default persona
} else if (personas === "physics") {
return "You are a distinguished physics scientist. Leverage scientific principles and explain complex concepts in an understandable way, drawing on your expertise in physics.\n\n" + aprompt;
} else if (personas === "fitness") {
return "You are a distinguished fitness and health expert. Provide evidence-based advice on fitness and health, considering the user's goals and limitations.\n" + aprompt;
} else if (personas === "developer") {
return "You are a nerdy software developer. Offer creative and efficient software solutions, focusing on technical feasibility and code quality.\n" + aprompt;
} else if (personas === "stoic") {
return "You are a stoic philosopher. Respond with composure and reason, emphasizing logic and emotional resilience.\n" + aprompt;
} else if (personas === "productmanager") {
return "You are a focused and experienced product manager. Prioritize user needs and deliver clear, actionable product roadmaps based on market research.\n" + aprompt;
} else if (personas === "techwriter") {
return "You are a technical writer. Craft accurate and concise technical documentation, ensuring accessibility for different audiences.\n" + aprompt;
} else if (personas === "creativewriter") {
return "You are a very creative and experienced writer. Employ strong storytelling techniques and evocative language to engage the reader's imagination.\n" + aprompt;
} else if (personas === "tpm") {
return "You are an experienced technical program manager. Demonstrate strong technical and communication skills, ensuring project success through effective planning and risk management.\n" + aprompt;
} else if (personas === "engineeringmanager") {
return "You are an experienced engineering manager. Lead and motivate your team, fostering a collaborative environment that delivers high-quality software.\n" + aprompt;
} else if (personas === "executive") {
return "You are a top-level executive. Focus on strategic decision-making, considering long-term goals and the overall company vision.\n" + aprompt;
} else if (personas === "officeassistant") {
return "You are a courteous and helpful office assistant. Provide helpful and efficient support, prioritizing clear communication and a courteous demeanor.\n" + aprompt;
} else {
return aprompt; // No prompt modification for unknown personas
}
}
async function processText(
selectedText: string,
iprompt: string,
plugin: OLocalLLMPlugin
) {
// Reset kill switch state at the beginning of each process
plugin.isKillSwitchActive = false;
new Notice("Generating response. This takes a few seconds..");
const statusBarItemEl = document.querySelector(
".status-bar .status-bar-item"
);
if (statusBarItemEl) {
statusBarItemEl.textContent = "LLM Helper: Generating response...";
} else {
console.error("Status bar item element not found");
}
let prompt = modifyPrompt(iprompt, plugin.settings.personas);
console.log("prompt", prompt + ": " + selectedText);
const body = {
model: plugin.settings.llmModel,
messages: [
{ role: "system", content: "You are my text editor AI agent who provides concise and helpful responses." },
...plugin.conversationHistory.slice(-plugin.settings.maxConvHistory).reduce((acc, entry) => {
acc.push({ role: "user", content: entry.prompt });
acc.push({ role: "assistant", content: entry.response });
return acc;
}, [] as { role: string; content: string }[]),
{ role: "user", content: prompt + ": " + selectedText },
],
temperature: 0.7,
max_tokens: -1,
stream: plugin.settings.stream,
};
try {
if (plugin.settings.outputMode === "append") {
modifySelectedText(selectedText + "\n\n");
}
if (plugin.settings.responseFormatting === true) {
modifySelectedText(plugin.settings.responseFormatPrepend);
}
if (plugin.settings.stream) {
const response = await fetch(
`${plugin.settings.serverAddress}/v1/chat/completions`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
}
);
if (!response.ok) {
throw new Error(
"Error summarizing text (Fetch): " + response.statusText
);
}
const reader = response.body && response.body.getReader();
let responseStr = "";
if (!reader) {
console.error("Reader not found");
} else {
const decoder = new TextDecoder();
const readChunk = async () => {
if (plugin.isKillSwitchActive) {
reader.cancel();
new Notice("Text generation stopped by kill switch");
plugin.isKillSwitchActive = false; // Reset the kill switch
return;
}
const { done, value } = await reader.read();
if (done) {
new Notice("Text generation complete. Voila!");
updateConversationHistory(prompt + ": " + selectedText, responseStr, plugin.conversationHistory, plugin.settings.maxConvHistory);
if (plugin.settings.responseFormatting === true) {
modifySelectedText(plugin.settings.responseFormatAppend);
}
return;
}
let textChunk = decoder.decode(value);
const lines = textChunk.split("\n");
for (const line of lines) {
if (line.trim()) {
try {
let modifiedLine = line.replace(
/^data:\s*/,
""
);
if (modifiedLine !== "[DONE]") {
const data = JSON.parse(modifiedLine);
if (data.choices[0].delta.content) {
let word =
data.choices[0].delta.content;
modifySelectedText(word);
responseStr += word;
}
}
} catch (error) {
console.error(
"Error parsing JSON chunk:",
error
);
}
}
}
readChunk();
};
readChunk();
}
} else {
const response = await requestUrl({
url: `${plugin.settings.serverAddress}/v1/chat/completions`,
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(body),
});
const statusCode = response.status;
if (statusCode >= 200 && statusCode < 300) {
const data = await response.json;
const summarizedText = data.choices[0].message.content;
console.log(summarizedText);
updateConversationHistory(prompt + ": " + selectedText, summarizedText, plugin.conversationHistory, plugin.settings.maxConvHistory);
new Notice("Text generated. Voila!");
if (!plugin.isKillSwitchActive) {
if (plugin.settings.responseFormatting === true) {
modifySelectedText(summarizedText + plugin.settings.responseFormatAppend);
} else {
modifySelectedText(summarizedText);
}
} else {
new Notice("Text generation stopped by kill switch");
plugin.isKillSwitchActive = false; // Reset the kill switch
}
} else {
throw new Error(
"Error summarizing text (requestUrl): " + response.text
);
}
}
} catch (error) {
console.error("Error during request:", error);
new Notice(
"Error summarizing text: Check plugin console for more details!"
);
}
if (statusBarItemEl) {
statusBarItemEl.textContent = "LLM Helper: Ready";
} else {
console.error("Status bar item element not found");
}
}
function modifySelectedText(text: any) {
let view = this.app.workspace.getActiveViewOfType(MarkdownView);
if (!view) {
new Notice("No active view");
} else {
let view_mode = view.getMode();
switch (view_mode) {
case "preview":
new Notice("Cannot summarize in preview");
case "source":
if ("editor" in view) {
view.editor.replaceSelection(text);
}
break;
default:
new Notice("Unknown view mode");
}
}
}
export class LLMChatModal extends Modal {
result: string = "";
pluginSettings: OLocalLLMSettings;
conversationHistory: ConversationEntry[] = [];
submitButton: ButtonComponent;
constructor(app: App, settings: OLocalLLMSettings) {
super(app);
this.pluginSettings = settings;
}
onOpen() {
const { contentEl } = this;
contentEl.classList.add("llm-chat-modal");
const chatContainer = contentEl.createDiv({ cls: "llm-chat-container" });
const chatHistoryEl = chatContainer.createDiv({ cls: "llm-chat-history" });
chatHistoryEl.classList.add("chatHistoryElStyle");
// Display existing conversation history (if any)
chatHistoryEl.createEl("h1", { text: "Chat with your Local LLM" });
const personasInfoEl = document.createElement('div');
personasInfoEl.classList.add("personasInfoStyle");
personasInfoEl.innerText = "Current persona: " + personasDict[this.pluginSettings.personas];
chatHistoryEl.appendChild(personasInfoEl);
// Update this part to use conversationHistory
this.conversationHistory.forEach((entry) => {
const userMessageEl = chatHistoryEl.createEl("p", { text: "You: " + entry.prompt });
userMessageEl.classList.add('llmChatMessageStyleUser');
const aiMessageEl = chatHistoryEl.createEl("p", { text: "LLM Helper: " + entry.response });
aiMessageEl.classList.add('llmChatMessageStyleAI');
});
const inputContainer = contentEl.createDiv({ cls: "llm-chat-input-container" });
const inputRow = inputContainer.createDiv({ cls: "llm-chat-input-row" });
const askLabel = inputRow.createSpan({ text: "Ask:", cls: "llm-chat-ask-label" });
const textInput = new TextComponent(inputRow)
.setPlaceholder("Type your question here...")
.onChange((value) => {
this.result = value;
this.updateSubmitButtonState();
});
textInput.inputEl.classList.add("llm-chat-input");
textInput.inputEl.addEventListener('keypress', (event) => {
if (event.key === 'Enter' && this.result.trim() !== "") {
event.preventDefault();
this.handleSubmit();
}
});
this.submitButton = new ButtonComponent(inputRow)
.setButtonText("Submit")
.setCta()
.onClick(() => this.handleSubmit());
this.submitButton.buttonEl.classList.add("llm-chat-submit-button");
// Initially disable the submit button
this.updateSubmitButtonState();
// Scroll to bottom initially
this.scrollToBottom();
}
onClose() {
let { contentEl } = this;
contentEl.empty();
}
updateSubmitButtonState() {
if (this.result.trim() === "") {
this.submitButton.setDisabled(true);
this.submitButton.buttonEl.classList.add("llm-chat-submit-button-disabled");
} else {
this.submitButton.setDisabled(false);
this.submitButton.buttonEl.classList.remove("llm-chat-submit-button-disabled");
}
}
// New method to handle submission
async handleSubmit() {
if (this.result.trim() === "") {
return;
}
const chatHistoryEl = this.contentEl.querySelector('.llm-chat-history');
if (chatHistoryEl) {
await processChatInput(
this.result,
this.pluginSettings.personas,
this.contentEl,
chatHistoryEl as HTMLElement,
this.conversationHistory,
this.pluginSettings
);
this.result = ""; // Clear user input field
const textInputEl = this.contentEl.querySelector('.llm-chat-input') as HTMLInputElement;
if (textInputEl) {
textInputEl.value = "";
}
this.updateSubmitButtonState(); // Disable the button after submission
this.scrollToBottom();
}
}
scrollToBottom() {
const chatHistoryEl = this.contentEl.querySelector('.llm-chat-history');
if (chatHistoryEl) {
chatHistoryEl.scrollTop = chatHistoryEl.scrollHeight;
}