-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.ts
345 lines (286 loc) · 9.48 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
import { App, ButtonComponent, Editor, MarkdownView, Notice, Plugin, PluginSettingTab, Setting, TextAreaComponent } from 'obsidian';
import OpenAI from 'openai';
const OpenAIModels = ["gpt-4o", "gpt-4o-mini", "gpt-4-turbo", "gpt-4-turbo-preview", "gpt-4", "gpt-4-32k", "gpt-3.5-turbo"] as const;
type OpenAIModel = typeof OpenAIModels[number];
interface ReversePrompterSettings {
openAIApiKey: string;
prompt: string;
prefix: string;
postfix: string;
model: OpenAIModel;
includePath: boolean;
regex: string;
}
const DEFAULT_PROMPT = "You are a writing assistant. Your role is to help a user write. \n" +
"Infer the type of writing from the user's input and ask insightful and interesting questions to help the user write more. \n" +
"Your questions should be open-ended and encourage the user to think creatively. \n" +
"Focus your questions on helping the writer keep moving quickly through and prevent writers block. \n" +
"The user may provide you with the document file path. \n" +
"If you see other AI questions, ensure your questions are different. \n" +
"Write nothing other than one question. "
const DEFAULT_SETTINGS: ReversePrompterSettings = {
openAIApiKey: '',
prompt: DEFAULT_PROMPT,
prefix: '> AI: ',
postfix: '\n',
model: 'gpt-4o',
includePath: true,
regex: "^(#+)|(-{3,})"
}
export default class ReversePrompter extends Plugin {
settings: ReversePrompterSettings;
inProgress = false;
getContentTillLastHeading(editor: Editor, cursorPos: CodeMirror.Position): string {
const cursorOffset = editor.posToOffset(cursorPos);
const re = new RegExp(this.settings.regex, 'gim');
const matches = editor.getValue().matchAll(re);
const invertedMatchIndexes = Array.from(matches, (match) => {
if (match.index !== undefined) {
return {
match: match[0],
index: match.index
}
}
}).filter(m => m !== undefined).reverse();
for (const match of invertedMatchIndexes) {
if (match === undefined) continue;
// Behind cursor only
if (match.index > cursorOffset) continue;
// We don't want to count the heading characters itself
const startPos = editor.offsetToPos(match.index + match.match.length);
const checkContent = editor.getRange(startPos, cursorPos);
if (checkContent.trim().length > 0) {
return editor.getRange(editor.offsetToPos(match.index), cursorPos);
}
}
// no match found so go till top of doc
return editor.getValue().substring(0, cursorOffset);
}
getText(view: MarkdownView, editor: Editor){
let txt = "";
if (this.settings.includePath){
const title = view.file?.path;
if (title){
txt += `File: ${title}\n`
}
}
if (editor.somethingSelected()){
txt += editor.getSelection();
} else {
txt += this.getContentTillLastHeading(editor, editor.getCursor());
}
return txt
}
async *requestReversePrompt(text: string) {
if (this.inProgress){
new Notice('Another request is in progress');
return;
}
if (this.settings.openAIApiKey.length === 0){
new Notice('OpenAI API Key is not set');
return;
}
if (text.length < 2){
new Notice('Text is too short');
return;
}
this.inProgress = true;
new Notice('Requesting reverse prompt...');
const openai = new OpenAI({
apiKey: this.settings.openAIApiKey,
dangerouslyAllowBrowser: true
});
const chatStream = await openai.chat.completions.create({
messages: [
{ role: 'system', content: this.settings.prompt },
{ role: 'user', content: text }
],
model: this.settings.model,
stream: true
});
for await (const chunk of chatStream) {
const data = chunk.choices[0]?.delta?.content || ''
yield data;
}
this.inProgress = false;
}
async generateReversePrompt(view: MarkdownView, editor: Editor){
const text = this.getText(view, editor);
// console.log("Sending text to OpenAI:\n" + text);
const iterator = await this.requestReversePrompt(text);
if (!iterator) return;
if (editor.somethingSelected()){
const end = editor.listSelections().reduce((acc, selection) => {
return Math.max(acc, Math.max(selection.anchor.line, selection.head.line));
}, editor.getCursor().line);
editor.setCursor(end, 0)
}
const currentLine = editor.getCursor().line;
const currentLineContent = editor.getLine(currentLine);
// Ensure we are on an empty line
if (currentLineContent != ""){
// Shift to the end of the line and add a new line
editor.setCursor(currentLine, currentLineContent.length);
editor.replaceSelection('\n');
}
editor.replaceSelection(this.settings.prefix);
// let response = '';
for await (const chunk of iterator){
editor.replaceSelection(chunk);
// response += chunk;
}
// console.log("OpenAI Response: ", response);
editor.replaceSelection(this.settings.postfix);
}
async onload() {
await this.loadSettings();
this.addRibbonIcon('step-forward', 'Generate reverse prompt', async (evt: MouseEvent) => {
const view = this.app.workspace.getActiveViewOfType(MarkdownView);
if (view) {
await this.generateReversePrompt(view, view.editor);
}
});
this.addCommand({
id: 'reverse-prompt',
name: 'Generate reverse prompt',
editorCallback: async (editor: Editor, view: MarkdownView) => {
await this.generateReversePrompt(view, editor);
}
});
this.addSettingTab(new ReversePrompterSettingsTab(this.app, this));
}
onunload() {
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
}
type SettingsMap = {
[key: string]: Setting;
}
class ReversePrompterSettingsTab extends PluginSettingTab {
plugin: ReversePrompter;
settings: SettingsMap = {};
constructor(app: App, plugin: ReversePrompter) {
super(app, plugin);
this.plugin = plugin;
this.containerEl.id = 'reverse-prompter-settings';
}
configureResetButton(button: ButtonComponent, settingKey: string, completeCallback: () => void){
button.setButtonText("Reset")
button.onClick(async () => {
// @ts-ignore Could fix this or move on with life.
const defaultSettingValue = DEFAULT_SETTINGS[settingKey];
// Update text input, does not trigger onChange
const input: TextAreaComponent[] = this.settings[settingKey].components.filter(c => 'inputEl' in c) as TextAreaComponent[]
if (input.length > 0){
input[0].setValue(defaultSettingValue);
}
// @ts-ignore Could fix this or move on with life.
this.plugin.settings[settingKey] = defaultSettingValue;
await this.plugin.saveSettings();
completeCallback();
})
}
addSetting(key: string): Setting {
const setting = new Setting(this.containerEl)
this.settings[key] = setting;
return setting;
}
display(): void {
this.containerEl.empty();
this.addSetting('openAIApiKey')
.setName('OpenAI API key')
.setDesc('Enter your OpenAI API key')
.addText(text => text
.setPlaceholder('Enter your OpenAI API key')
.setValue(this.plugin.settings.openAIApiKey)
.onChange(async (value) => {
this.plugin.settings.openAIApiKey = value;
await this.plugin.saveSettings();
}));
this.addSetting('model')
.setName('Model')
.setDesc('OpenAI model to use for reverse prompt generation')
.addDropdown(dropdown => {
OpenAIModels.forEach(model => {
dropdown.addOption(model, model);
});
dropdown.setValue(this.plugin.settings.model);
dropdown.onChange(async (value) => {
this.plugin.settings.model = value as OpenAIModel;
await this.plugin.saveSettings();
});
});
this.addSetting('prompt')
.setName("Prompt")
.setDesc("Prompt for the reverse prompt")
.addTextArea(textArea => {
textArea.inputEl.id = "reverse-prompter-prompt";
textArea.setPlaceholder("Enter the prompt")
textArea.setValue(this.plugin.settings.prompt)
textArea.onChange(async (value) => {
this.plugin.settings.prompt = value;
await this.plugin.saveSettings();
})
textArea.inputEl.rows = 10;
})
.addButton(button => {
this.configureResetButton(button, 'prompt', () => {
new Notice("Prompt reset to default");
});
});
this.addSetting('includePath')
.setName('Include file path')
.addToggle(toggle => toggle
.setValue(this.plugin.settings.includePath)
.onChange(async (value) => {
this.plugin.settings.includePath = value;
await this.plugin.saveSettings();
}));
this.addSetting('prefix')
.setName('AI response prefix')
.addTextArea(text => text
.setValue(this.plugin.settings.prefix)
.onChange(async (value) => {
this.plugin.settings.prefix = value;
await this.plugin.saveSettings();
}))
.addButton(button => {
this.configureResetButton(button, 'prefix', () => {
new Notice("Prefix reset to default");
});
});
this.addSetting('postfix')
.setName('AI response postfix')
.addTextArea(text => text
.setValue(this.plugin.settings.postfix)
.onChange(async (value) => {
this.plugin.settings.postfix = value;
await this.plugin.saveSettings();
}))
.addButton(button => {
this.configureResetButton(button, 'postfix', () => {
new Notice("Postfix reset to default");
});
});
this.addSetting('regex')
.setName('Divider regex')
.addTextArea(text => {
text.inputEl.id = "reverse-prompter-regex";
text.setValue(this.plugin.settings.regex)
text.onChange(async (value) => {
this.plugin.settings.regex = value;
await this.plugin.saveSettings();
})
})
.addButton(button => {
this.configureResetButton(button, 'regex', () => {
new Notice("Regex reset to default");
});
});
}
}