forked from lossless-group/perplexed-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
1432 lines (1260 loc) · 62.6 KB
/
main.ts
File metadata and controls
1432 lines (1260 loc) · 62.6 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
import { App, Editor, Notice, Plugin, PluginSettingTab, Setting } from 'obsidian';
import * as dotenv from 'dotenv';
// Import services
import { PerplexityService } from './src/services/perplexityService';
import { PerplexicaService } from './src/services/perplexicaService';
import { LMStudioService } from './src/services/lmStudioService';
import { PromptsService } from './src/services/promptsService';
// Import modals
import { PerplexityModal } from './src/modals/PerplexityModal';
import { PerplexicaModal } from './src/modals/PerplexicaModal';
import { LMStudioModal } from './src/modals/LMStudioModal';
import { URLUpdateModal } from './src/modals/URLUpdateModal';
import { ArticleGeneratorModal } from './src/modals/ArticleGeneratorModal';
import { TextEnhancementModal } from './src/modals/TextEnhancementModal';
import { TextEnhancementWithImagesModal } from './src/modals/TextEnhancementWithImagesModal';
// Load environment variables
dotenv.config({ path: `${process.cwd()}/.env` });
interface PerplexedPluginSettings {
mySetting: string;
localLLMPath: string;
requestBodyTemplate: string;
perplexityRequestTemplate: string;
perplexityApiKey: string;
perplexicaEndpoint: string;
perplexityEndpoint: string;
lmStudioEndpoint: string;
lmStudioRequestTemplate: string;
defaultModel: string;
defaultOptimizationMode: string;
defaultFocusMode: string;
defaultLMStudioModel: string;
// Display Settings
headerPosition: 'top' | 'bottom';
// Prompt Settings
prompts: {
// System prompts
perplexitySystemPrompt: string;
perplexicaSystemPrompt: string;
lmStudioDefaultSystemPrompt: string;
// Placeholder text
perplexityQueryPlaceholder: string;
perplexicaQueryPlaceholder: string;
lmStudioQueryPlaceholder: string;
lmStudioSystemPromptPlaceholder: string;
articleTermPlaceholder: string;
// Article generator template
articleGeneratorTemplate: string;
// Deep Research article generator template
deepResearchArticleTemplate: string;
// Image prompts
imageReferencesPrompt: string;
// Text enhancement prompt
enhancePrompt: string;
// Text enhancement with images prompt
enhanceWithImagesPrompt: string;
};
}
const DEFAULT_SETTINGS: PerplexedPluginSettings = {
mySetting: 'default',
// Use host.docker.internal to connect to the host machine from Docker containers
localLLMPath: 'http://host.docker.internal:3030/api/search',
perplexicaEndpoint: 'http://localhost:3030/api/search',
perplexityEndpoint: 'https://api.perplexity.ai/chat/completions',
lmStudioEndpoint: 'http://localhost:1234/v1/chat/completions',
headerPosition: 'top',
requestBodyTemplate: `{
"chatModel": {
"provider": "ollama",
"name": "llama3.2:latest"
},
"embeddingModel": {
"provider": "ollama",
"name": "llama3.2:latest"
},
"optimizationMode": "speed",
"focusMode": "webSearch",
"query": "What is Perplexica's architecture?",
"history": [
{
"role": "user",
"content": "What is Perplexica's architecture?"
}
],
"systemInstructions": "{{PERPLEXICA_SYSTEM_PROMPT}}",
"stream": false,
"maxTokens": 2048,
"temperature": 0.7
}`,
perplexityApiKey: process.env.PERPLEXITY_API_KEY || '',
perplexityRequestTemplate: `{
"model": "llama-3.1-sonar-small-128k-online",
"messages": [
{
"role": "system",
"content": "{{PERPLEXITY_SYSTEM_PROMPT}}"
},
{
"role": "user",
"content": "What is Perplexity AI's approach to search?"
}
],
"max_tokens": 2048,
"temperature": 0.7,
"top_p": 0.9,
"return_citations": true,
"search_domain_filter": [],
"return_images": false,
"return_related_questions": false,
"search_recency_filter": "month",
"top_k": 0,
"stream": false,
"presence_penalty": 0,
"frequency_penalty": 1
}`,
lmStudioRequestTemplate: `{
"model": "ibm/granite-3.2-8b",
"messages": [
{
"role": "user",
"content": "Hello, can you help me with this question?"
}
],
"max_tokens": 2048,
"temperature": 0.7,
"stream": false
}`,
defaultModel: 'llama3.2:latest',
defaultOptimizationMode: 'speed',
defaultFocusMode: 'webSearch',
defaultLMStudioModel: 'ibm/granite-3.2-8b',
// Prompt Settings
prompts: {
// System prompts
perplexitySystemPrompt: "You are a helpful AI assistant. Provide clear, concise, and accurate information with proper citations.",
perplexicaSystemPrompt: "You are a helpful AI assistant. Provide clear, concise, and accurate information.",
lmStudioDefaultSystemPrompt: "You are a helpful AI assistant. Provide clear, concise, and accurate information.",
// Placeholder text
perplexityQueryPlaceholder: "What would you like to ask Perplexity?",
perplexicaQueryPlaceholder: "What would you like to ask Perplexica?",
lmStudioQueryPlaceholder: "What would you like to ask?",
lmStudioSystemPromptPlaceholder: "You are a helpful AI assistant...",
articleTermPlaceholder: "e.g., AI Copilots, AI Studios, Machine Learning, etc.",
// Article generator template
articleGeneratorTemplate: `Write a comprehensive one-page article about "{TERM}".
Structure the article as follows:
1. **Introduction** (2-3 sentences)
- Define the term and its significance
- Provide context for why it matters
2. **Main Content** (3-4 paragraphs)
- Explain the concept in detail
- Include practical examples and use cases
- Discuss benefits and potential applications
- Address any challenges or considerations
3. **Current State and Trends** (1-2 paragraphs)
- Discuss current adoption and market status
- Mention key players or technologies
- Highlight recent developments
4. **Future Outlook** (1 paragraph)
- Predict future developments
- Discuss potential impact
5. **Conclusion** (1-2 sentences)
- Summarize key points
- End with a forward-looking statement
**Important Guidelines:**
- Keep the total length to approximately one page (500-800 words)
- Use clear, accessible language
- Include specific examples and real-world applications
- Make it engaging and informative for a general audience
- Use markdown formatting for structure`,
// Deep Research article generator template
deepResearchArticleTemplate: `Conduct comprehensive research and write an in-depth article about "{TERM}".
**Research Requirements:**
- Conduct exhaustive research across hundreds of sources
- Analyze multiple perspectives and viewpoints
- Include academic, industry, and expert sources
- Provide detailed citations and references
- Examine historical context and evolution
- Consider global implications and regional variations
**Article Structure:**
1. **Executive Summary** (1 paragraph)
- Concise overview of key findings
- Main conclusions and implications
2. **Introduction and Definition** (2-3 paragraphs)
- Comprehensive definition and scope
- Historical context and evolution
- Current significance and relevance
3. **Comprehensive Analysis** (6-8 paragraphs)
- Detailed examination of core concepts
- Multiple perspectives and approaches
- Industry applications and use cases
- Technical implementation details
- Market analysis and competitive landscape
- Regulatory and ethical considerations
4. **Current State and Market Dynamics** (3-4 paragraphs)
- Global adoption patterns and trends
- Key players, technologies, and platforms
- Regional variations and cultural factors
- Economic impact and market size
- Recent developments and breakthroughs
5. **Challenges and Opportunities** (2-3 paragraphs)
- Technical challenges and limitations
- Implementation barriers and solutions
- Future opportunities and potential
- Risk factors and mitigation strategies
6. **Future Outlook and Predictions** (2-3 paragraphs)
- Short-term developments (1-2 years)
- Medium-term trends (3-5 years)
- Long-term implications (5+ years)
- Strategic recommendations
7. **Conclusion** (1-2 paragraphs)
- Synthesis of key findings
- Strategic implications
- Call to action or forward-looking statement
**Research Guidelines:**
- Include diverse source types (academic, industry, news, expert opinions)
- Provide detailed citations for all claims
- Analyze conflicting viewpoints and evidence
- Consider global and regional perspectives
- Include quantitative data where available
- Examine both benefits and risks
- Address ethical and societal implications
**Quality Standards:**
- Academic rigor with practical relevance
- Balanced analysis of multiple perspectives
- Evidence-based conclusions
- Clear, professional writing style
- Comprehensive bibliography`,
// Image prompts
imageReferencesPrompt: "**Image References:**\nPlease include the following image references throughout your response where appropriate:\n- [IMAGE 1: Relevant diagram or illustration related to the topic]\n- [IMAGE 2: Practical example or use case visualization]\n- [IMAGE 3: Additional supporting visual content]",
// Text enhancement prompt
enhancePrompt: "Please enhance the following text by improving clarity, adding relevant details, expanding on key points, and making it more comprehensive and engaging. Maintain the original meaning and tone while making it more informative and well-structured:\n\n{TEXT}",
// Text enhancement with images prompt
enhanceWithImagesPrompt: "Please provide 1-3 relevant images for the following text. Return ONLY the image markers in the format [IMAGE 1: description], [IMAGE 2: description], etc. Each image should illustrate a key concept, example, or visual representation related to the text. Do not include any other text or explanation:\n\n{TEXT}"
}
};
export default class PerplexedPlugin extends Plugin {
public settings: PerplexedPluginSettings = DEFAULT_SETTINGS;
private statusBarItemEl: HTMLElement | null = null;
private ribbonIconEl: HTMLElement | null = null;
// Service instances
private perplexityService!: PerplexityService | null;
private perplexicaService!: PerplexicaService | null;
private lmStudioService!: LMStudioService | null;
private promptsService!: PromptsService | null;
async onload(): Promise<void> {
try {
console.log('Perplexed Plugin: Starting initialization...');
await this.loadSettings();
console.log('Perplexed Plugin: Settings loaded successfully');
// Initialize prompts service first
try {
this.promptsService = new PromptsService(this.settings.prompts);
console.log('Perplexed Plugin: PromptsService initialized successfully');
} catch (error) {
console.error('Perplexed Plugin: Failed to initialize PromptsService:', error);
new Notice('Failed to initialize PromptsService');
this.promptsService = null;
}
// Initialize services with error handling - only if promptsService is available
if (this.promptsService) {
try {
this.perplexityService = new PerplexityService({
perplexityApiKey: this.settings.perplexityApiKey,
perplexityEndpoint: this.settings.perplexityEndpoint,
promptsService: this.promptsService,
requestTemplate: this.settings.perplexityRequestTemplate,
headerPosition: this.settings.headerPosition
});
console.log('Perplexed Plugin: PerplexityService initialized successfully');
} catch (error) {
console.error('Perplexed Plugin: Failed to initialize PerplexityService:', error);
new Notice('Failed to initialize PerplexityService');
this.perplexityService = null;
}
try {
this.perplexicaService = new PerplexicaService({
perplexicaEndpoint: this.settings.perplexicaEndpoint,
localLLMPath: this.settings.localLLMPath,
defaultModel: this.settings.defaultModel,
promptsService: this.promptsService,
requestTemplate: this.settings.requestBodyTemplate
});
console.log('Perplexed Plugin: PerplexicaService initialized successfully');
} catch (error) {
console.error('Perplexed Plugin: Failed to initialize PerplexicaService:', error);
new Notice('Failed to initialize PerplexicaService');
this.perplexicaService = null;
}
try {
this.lmStudioService = new LMStudioService({
lmStudioEndpoint: this.settings.lmStudioEndpoint,
promptsService: this.promptsService,
requestTemplate: this.settings.lmStudioRequestTemplate
});
console.log('Perplexed Plugin: LMStudioService initialized successfully');
} catch (error) {
console.error('Perplexed Plugin: Failed to initialize LMStudioService:', error);
new Notice('Failed to initialize LMStudioService');
this.lmStudioService = null;
}
} else {
// If promptsService failed, set all other services to null
this.perplexityService = null;
this.perplexicaService = null;
this.lmStudioService = null;
console.log('Perplexed Plugin: Skipping service initialization due to PromptsService failure');
}
// Debug: Log current settings
console.log('Perplexed Plugin: Current Perplexica Path:', this.settings.perplexicaEndpoint);
console.log('Perplexed Plugin: Full settings:', JSON.stringify(this.settings, null, 2));
// This adds a settings tab so the user can configure various aspects of the plugin
this.addSettingTab(new PerplexedSettingTab(this.app, this));
console.log('Perplexed Plugin: Settings tab added successfully');
// Register commands with error handling
try {
this.registerPerplexicaCommands();
console.log('Perplexed Plugin: Perplexica commands registered successfully');
} catch (error) {
console.error('Perplexed Plugin: Failed to register Perplexica commands:', error);
}
try {
this.registerPerplexityCommands();
console.log('Perplexed Plugin: Perplexity commands registered successfully');
} catch (error) {
console.error('Perplexed Plugin: Failed to register Perplexity commands:', error);
}
try {
this.registerLMStudioCommands();
console.log('Perplexed Plugin: LM Studio commands registered successfully');
} catch (error) {
console.error('Perplexed Plugin: Failed to register LM Studio commands:', error);
}
try {
this.registerArticleGeneratorCommands();
console.log('Perplexed Plugin: Article generator commands registered successfully');
} catch (error) {
console.error('Perplexed Plugin: Failed to register article generator commands:', error);
}
try {
this.registerTextEnhancementCommands();
console.log('Perplexed Plugin: Text enhancement commands registered successfully');
} catch (error) {
console.error('Perplexed Plugin: Failed to register text enhancement commands:', error);
}
try {
this.registerTextEnhancementWithImagesCommands();
console.log('Perplexed Plugin: Get related images commands registered successfully');
} catch (error) {
console.error('Perplexed Plugin: Failed to register get related images commands:', error);
}
// Add debug command to check command status
this.addCommand({
id: 'perplexed-debug-commands',
name: 'Debug: Check Perplexed Commands',
callback: () => {
this.debugCommands();
}
});
// Add command to reset prompts to defaults
this.addCommand({
id: 'perplexed-reset-prompts',
name: 'Reset Prompts to Default',
callback: async () => {
await this.resetPromptsToDefault();
}
});
// Add command to reinitialize services
this.addCommand({
id: 'perplexed-reinitialize-services',
name: 'Reinitialize Perplexed Services',
callback: async () => {
await this.reinitializeServices();
}
});
console.log('Perplexed Plugin: Initialization completed successfully');
new Notice('Perplexed Plugin loaded successfully');
} catch (error) {
console.error('Perplexed Plugin: Critical initialization error:', error);
new Notice('Perplexed Plugin failed to load properly');
}
}
onunload(): void {
this.statusBarItemEl?.remove();
this.ribbonIconEl?.remove();
}
private async loadSettings() {
const savedData = await this.loadData();
this.settings = Object.assign({}, DEFAULT_SETTINGS, savedData);
// Ensure new fields are always present (migration for existing users)
if (!this.settings.prompts.deepResearchArticleTemplate) {
this.settings.prompts.deepResearchArticleTemplate = DEFAULT_SETTINGS.prompts.deepResearchArticleTemplate;
await this.saveSettings();
}
if (!this.settings.prompts.enhancePrompt) {
this.settings.prompts.enhancePrompt = DEFAULT_SETTINGS.prompts.enhancePrompt;
await this.saveSettings();
}
if (!this.settings.prompts.enhanceWithImagesPrompt) {
this.settings.prompts.enhanceWithImagesPrompt = DEFAULT_SETTINGS.prompts.enhanceWithImagesPrompt;
await this.saveSettings();
}
}
public async saveSettings(): Promise<void> {
try {
await this.saveData(this.settings);
} catch (error) {
console.error('Failed to save settings:', error);
new Notice('Failed to save settings');
}
}
// Delegate methods to services
public async queryPerplexity(query: string, model: string, stream: boolean, editor: Editor, options?: {
return_citations?: boolean;
return_images?: boolean;
return_related_questions?: boolean;
search_recency_filter?: string;
}): Promise<void> {
if (!this.perplexityService) {
throw new Error('Perplexity service not initialized');
}
await this.perplexityService.queryPerplexity(query, model, stream, editor, options);
}
public async queryPerplexica(query: string, focusMode: string, optimizationMode: string, stream: boolean, editor: Editor, options?: {
return_images?: boolean;
}): Promise<void> {
if (!this.perplexicaService) {
throw new Error('Perplexica service not initialized');
}
await this.perplexicaService.queryPerplexica(query, focusMode, optimizationMode, stream, editor, options);
}
public async queryLMStudio(query: string, model: string, stream: boolean, editor: Editor, options?: {
max_tokens?: number;
temperature?: number;
top_p?: number;
system_prompt?: string;
return_images?: boolean;
}): Promise<void> {
if (!this.lmStudioService) {
throw new Error('LM Studio service not initialized');
}
await this.lmStudioService.queryLMStudio(query, model, stream, editor, options);
}
// Getter for prompts service
public getPromptsService(): PromptsService | null {
return this.promptsService;
}
private registerPerplexicaCommands(): void {
// Command to update Perplexica URL
this.addCommand({
id: 'update-perplexica-url',
name: 'Update Perplexica URL',
callback: () => {
const modal = new URLUpdateModal(this.app, {
title: 'Update Perplexica API URL',
label: 'Perplexica API URL',
placeholder: 'http://localhost:3030/api/search',
currentValue: this.settings.perplexicaEndpoint,
onSave: async (newUrl: string) => {
this.settings.perplexicaEndpoint = newUrl;
await this.saveSettings();
}
});
modal.open();
}
});
// Command to show current settings
this.addCommand({
id: 'show-perplexica-settings',
name: 'Show Perplexica Settings',
callback: () => {
new Notice(`Current Perplexica URL: ${this.settings.perplexicaEndpoint}`);
console.log('Perplexica Settings:', this.settings);
}
});
// Command to ask Perplexica
this.addCommand({
id: 'ask-perplexica',
name: 'Ask Perplexica',
editorCallback: (editor: Editor) => {
try {
if (!this.perplexicaService) {
new Notice('Perplexica service not initialized. Please check console for errors and try the debug command.');
console.error('Perplexica service is not initialized');
return;
}
if (!this.promptsService) {
new Notice('Prompts service not initialized. Please check console for errors and try the debug command.');
console.error('Prompts service is not initialized');
return;
}
const modal = new PerplexicaModal(this.app, editor, this.perplexicaService, this.promptsService);
modal.open();
} catch (error) {
console.error('Error opening Perplexica modal:', error);
new Notice('Failed to open Perplexica modal. Check console for details.');
}
}
});
}
private registerPerplexityCommands(): void {
try {
// Command to update Perplexity URL
this.addCommand({
id: 'update-perplexity-url',
name: 'Update Perplexity URL',
callback: () => {
const modal = new URLUpdateModal(this.app, {
title: 'Update Perplexity API URL',
label: 'Perplexity API URL',
placeholder: 'https://api.perplexity.ai/chat/completions',
currentValue: this.settings.perplexityEndpoint,
onSave: async (newUrl: string) => {
this.settings.perplexityEndpoint = newUrl;
await this.saveSettings();
}
});
modal.open();
}
});
// Command to show current Perplexity settings
this.addCommand({
id: 'show-perplexity-settings',
name: 'Show Perplexity Settings',
callback: () => {
new Notice(`Current Perplexity URL: ${this.settings.perplexityEndpoint}`);
console.log('Perplexity Settings:', this.settings);
}
});
// Command to ask Perplexity
this.addCommand({
id: 'ask-perplexity',
name: 'Ask Perplexity',
editorCallback: (editor: Editor) => {
try {
if (!this.perplexityService) {
new Notice('Perplexity service not initialized. Please check console for errors and try the debug command.');
console.error('Perplexity service is not initialized');
return;
}
if (!this.promptsService) {
new Notice('Prompts service not initialized. Please check console for errors and try the debug command.');
console.error('Prompts service is not initialized');
return;
}
const modal = new PerplexityModal(this.app, editor, this.perplexityService, this.promptsService);
modal.open();
} catch (error) {
console.error('Error opening Perplexity modal:', error);
new Notice('Failed to open Perplexity modal. Check console for details.');
}
}
});
// Add a fallback command that shows service status
this.addCommand({
id: 'perplexity-service-status',
name: 'Check Perplexity Service Status',
callback: () => {
if (this.perplexityService) {
new Notice('Perplexity service is initialized and ready');
console.log('Perplexity service status: OK');
} else {
new Notice('Perplexity service is NOT initialized. Check console for errors.');
console.error('Perplexity service status: FAILED');
}
}
});
console.log('Perplexed Plugin: Perplexity commands registered successfully');
} catch (error) {
console.error('Perplexed Plugin: Error registering Perplexity commands:', error);
throw error;
}
}
private registerLMStudioCommands(): void {
// Command to update LM Studio URL
this.addCommand({
id: 'update-lmstudio-url',
name: 'Update LM Studio URL',
callback: () => {
const modal = new URLUpdateModal(this.app, {
title: 'Update LM Studio API URL',
label: 'LM Studio API URL',
placeholder: 'http://localhost:1234/v1/chat/completions',
currentValue: this.settings.lmStudioEndpoint,
onSave: async (newUrl: string) => {
this.settings.lmStudioEndpoint = newUrl;
await this.saveSettings();
}
});
modal.open();
}
});
// Command to show current LM Studio settings
this.addCommand({
id: 'show-lmstudio-settings',
name: 'Show LM Studio Settings',
callback: () => {
new Notice(`Current LM Studio URL: ${this.settings.lmStudioEndpoint}`);
console.log('LM Studio Settings:', this.settings);
}
});
// Command to ask LM Studio
this.addCommand({
id: 'ask-lmstudio',
name: 'Ask LM Studio',
editorCallback: (editor: Editor) => {
try {
if (!this.lmStudioService) {
new Notice('LM Studio service not initialized. Please check console for errors and try the debug command.');
console.error('LM Studio service is not initialized');
return;
}
if (!this.promptsService) {
new Notice('Prompts service not initialized. Please check console for errors and try the debug command.');
console.error('Prompts service is not initialized');
return;
}
const modal = new LMStudioModal(this.app, editor, this.lmStudioService, this.promptsService);
modal.open();
} catch (error) {
console.error('Error opening LM Studio modal:', error);
new Notice('Failed to open LM Studio modal. Check console for details.');
}
}
});
}
private registerArticleGeneratorCommands(): void {
// Register Article Generator command
this.addCommand({
id: 'generate-article',
name: 'Generate One-Page Article',
editorCallback: (editor: Editor) => {
try {
if (!this.perplexityService) {
new Notice('Perplexity service not initialized. Please check console for errors and try the debug command.');
console.error('Perplexity service is not initialized');
return;
}
if (!this.promptsService) {
new Notice('Prompts service not initialized. Please check console for errors and try the debug command.');
console.error('Prompts service is not initialized');
return;
}
new ArticleGeneratorModal(this.app, editor, this.perplexityService, this.promptsService).open();
} catch (error) {
console.error('Error opening Article Generator modal:', error);
new Notice('Failed to open Article Generator modal. Check console for details.');
}
}
});
}
private registerTextEnhancementCommands(): void {
// Register Text Enhancement command
this.addCommand({
id: 'enhance-text',
name: 'Enhance Selected Text with Perplexity',
editorCallback: (editor: Editor) => {
try {
const selectedText = editor.getSelection();
if (!selectedText || selectedText.trim() === '') {
new Notice('Please select some text to enhance');
return;
}
if (!this.perplexityService) {
new Notice('Perplexity service not initialized. Please check console for errors and try the debug command.');
console.error('Perplexity service is not initialized');
return;
}
if (!this.promptsService) {
new Notice('Prompts service not initialized. Please check console for errors and try the debug command.');
console.error('Prompts service is not initialized');
return;
}
new TextEnhancementModal(this.app, editor, this.perplexityService, this.promptsService, selectedText).open();
} catch (error) {
console.error('Error opening Text Enhancement modal:', error);
new Notice('Failed to open Text Enhancement modal. Check console for details.');
}
}
});
}
private registerTextEnhancementWithImagesCommands(): void {
// Register Get Related Images command
this.addCommand({
id: 'enhance-text-with-images',
name: 'Get Related Images for Selected Text',
editorCallback: (editor: Editor) => {
try {
const selectedText = editor.getSelection();
if (!selectedText || selectedText.trim() === '') {
new Notice('Please select some text to get related images for');
return;
}
if (!this.perplexityService) {
new Notice('Perplexity service not initialized. Please check console for errors and try the debug command.');
console.error('Perplexity service is not initialized');
return;
}
if (!this.promptsService) {
new Notice('Prompts service not initialized. Please check console for errors and try the debug command.');
console.error('Prompts service is not initialized');
return;
}
new TextEnhancementWithImagesModal(this.app, editor, this.perplexityService, this.promptsService, selectedText).open();
} catch (error) {
console.error('Error opening Get Related Images modal:', error);
new Notice('Failed to open Get Related Images modal. Check console for details.');
}
}
});
}
private debugCommands(): void {
console.log('=== Perplexed Plugin Debug Information ===');
console.log('Plugin instance:', this);
console.log('Settings:', this.settings);
console.log('Services status:');
console.log('- PromptsService:', this.promptsService ? 'Initialized' : 'NOT INITIALIZED');
console.log('- PerplexityService:', this.perplexityService ? 'Initialized' : 'NOT INITIALIZED');
console.log('- PerplexicaService:', this.perplexicaService ? 'Initialized' : 'NOT INITIALIZED');
console.log('- LMStudioService:', this.lmStudioService ? 'Initialized' : 'NOT INITIALIZED');
// Check if commands are registered in Obsidian
const registeredCommands = this.app.commands.commands;
const perplexedCommands = Object.keys(registeredCommands).filter(cmd =>
cmd.startsWith('perplexed') ||
cmd.includes('perplexity') ||
cmd.includes('perplexica') ||
cmd.includes('lmstudio') ||
cmd.includes('generate-article') ||
cmd.includes('enhance-text')
);
console.log('Registered Perplexed commands:', perplexedCommands);
if (perplexedCommands.length === 0) {
new Notice('No Perplexed commands found! Check console for details.');
} else {
new Notice(`Found ${perplexedCommands.length} Perplexed commands. Check console for details.`);
}
console.log('=== End Debug Information ===');
}
private async resetPromptsToDefault(): Promise<void> {
try {
console.log('Perplexed Plugin: Resetting prompts to default...');
new Notice('Resetting prompts to default values...');
// Reset all prompt settings to default values
this.settings.prompts = { ...DEFAULT_SETTINGS.prompts };
// Save the updated settings
await this.saveSettings();
// Reinitialize the prompts service with new settings
if (this.promptsService) {
this.promptsService.updateSettings(this.settings.prompts);
console.log('Perplexed Plugin: PromptsService updated with default settings');
}
new Notice('✅ Prompts reset to default values successfully');
console.log('Perplexed Plugin: Prompts reset to default successfully');
} catch (error) {
console.error('Perplexed Plugin: Failed to reset prompts to default:', error);
new Notice('❌ Failed to reset prompts to default. Check console for details.');
}
}
private async reinitializeServices(): Promise<void> {
try {
console.log('Perplexed Plugin: Reinitializing services...');
new Notice('Reinitializing Perplexed services...');
// Reinitialize prompts service first
try {
this.promptsService = new PromptsService(this.settings.prompts);
console.log('Perplexed Plugin: PromptsService reinitialized successfully');
} catch (error) {
console.error('Perplexed Plugin: Failed to reinitialize PromptsService:', error);
this.promptsService = null;
}
// Reinitialize other services only if promptsService is available
if (this.promptsService) {
try {
this.perplexityService = new PerplexityService({
perplexityApiKey: this.settings.perplexityApiKey,
perplexityEndpoint: this.settings.perplexityEndpoint,
promptsService: this.promptsService,
requestTemplate: this.settings.perplexityRequestTemplate,
headerPosition: this.settings.headerPosition
});
console.log('Perplexed Plugin: PerplexityService reinitialized successfully');
} catch (error) {
console.error('Perplexed Plugin: Failed to reinitialize PerplexityService:', error);
this.perplexityService = null;
}
try {
this.perplexicaService = new PerplexicaService({
perplexicaEndpoint: this.settings.perplexicaEndpoint,
localLLMPath: this.settings.localLLMPath,
defaultModel: this.settings.defaultModel,
promptsService: this.promptsService,
requestTemplate: this.settings.requestBodyTemplate
});
console.log('Perplexed Plugin: PerplexicaService reinitialized successfully');
} catch (error) {
console.error('Perplexed Plugin: Failed to reinitialize PerplexicaService:', error);
this.perplexicaService = null;
}
try {
this.lmStudioService = new LMStudioService({
lmStudioEndpoint: this.settings.lmStudioEndpoint,
promptsService: this.promptsService,
requestTemplate: this.settings.lmStudioRequestTemplate
});
console.log('Perplexed Plugin: LMStudioService reinitialized successfully');
} catch (error) {
console.error('Perplexed Plugin: Failed to reinitialize LMStudioService:', error);
this.lmStudioService = null;
}
} else {
// If promptsService failed, set all other services to null
this.perplexityService = null;
this.perplexicaService = null;
this.lmStudioService = null;
console.log('Perplexed Plugin: Skipping service reinitialization due to PromptsService failure');
}
new Notice('Services reinitialization completed. Check console for details.');
console.log('Perplexed Plugin: Services reinitialization completed');
} catch (error) {
console.error('Perplexed Plugin: Error during services reinitialization:', error);
new Notice('Failed to reinitialize services. Check console for details.');
}
}
}
class PerplexedSettingTab extends PluginSettingTab {
plugin: PerplexedPlugin;
constructor(app: App, plugin: PerplexedPlugin) {
super(app, plugin);
this.plugin = plugin;
}
// Helper method to safely update prompts service
private updatePromptsService(): void {
const promptsService = this.plugin.getPromptsService();
if (promptsService) {
promptsService.updateSettings(this.plugin.settings.prompts);
}
}
display(): void {
const { containerEl } = this;
containerEl.empty();
containerEl.createEl('h2', { text: 'Perplexed Plugin Settings' });
// Perplexity Section
const perplexityHeader = containerEl.createEl('h3', { text: 'Perplexity (Remote Service)' });
perplexityHeader.style.color = 'var(--text-accent)';
containerEl.createEl('p', {
text: 'Configure settings for the hosted Perplexity AI service',
cls: 'setting-item-description'
});
new Setting(containerEl)
.setName('Endpoint')
.setDesc('API endpoint for Perplexity service')
.addText(text => text
.setPlaceholder('https://api.perplexity.ai/chat/completions')
.setValue(this.plugin.settings.perplexityEndpoint)
.onChange(async (value: string) => {
this.plugin.settings.perplexityEndpoint = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName('API Key')
.setDesc('Your Perplexity API key (required for remote service)')
.addText(text => text
.setPlaceholder('pplx-xxxxxxxxxxxxxxxxxxxxx')
.setValue(this.plugin.settings.perplexityApiKey)
.onChange(async (value: string) => {
this.plugin.settings.perplexityApiKey = value;
await this.plugin.saveSettings();
})
);
new Setting(containerEl)
.setName('Header Position')
.setDesc('Where to place the query header in generated articles')
.addDropdown(dropdown => dropdown
.addOption('top', 'Top of article')
.addOption('bottom', 'Bottom of article')
.setValue(this.plugin.settings.headerPosition)
.onChange(async (value: string) => {
this.plugin.settings.headerPosition = value as 'top' | 'bottom';
await this.plugin.saveSettings();
})
);
// Perplexity Request Template
const perplexityJsonSetting = new Setting(containerEl)