-
Notifications
You must be signed in to change notification settings - Fork 2
/
main.ts
485 lines (431 loc) · 16.2 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
import axios from "axios";
// Ref: https://pilotmoon.github.io/PopClip-Extensions/interfaces/PopClip.html
// Source: https://github.com/pilotmoon/PopClip-Extensions/blob/master/popclip.d.ts
interface PasteboardContent {
'public.utf8-plain-text'?: string
'public.html'?: string
'public.rtf'?: string
}
interface Input {
content: PasteboardContent
// data: { emails: RangedStrings; nonHttpUrls: RangedStrings; paths: RangedStrings; urls: RangedStrings }
html: string
markdown: string
matchedText: string
rtf: string
text: string
xhtml: string
}
interface Context {
hasFormatting: boolean
canPaste: boolean
canCopy: boolean
canCut: boolean
browserUrl: string
browserTitle: string
appName: string
appIdentifier: string
}
interface Modifiers {
/** Shift (⇧) key state. */
shift: boolean
/** Control (⌃) key state. */
control: boolean
/** Option (⌥) key state. */
option: boolean
/** Command (⌘) key state. */
command: boolean
}
interface Options {
apiType: "openai" | "azure"
apiBase: string
apiKey: string
apiVersion: string
model: string
temperature: string
reviseEnabled: boolean
revisePrimaryLanguage: string
reviseSecondaryLanguage: string
polishEnabled: boolean
polishPrimaryLanguage: string
polishSecondaryLanguage: string
translateEnabled: boolean
translatePrimaryLanguage: string
translateSecondaryLanguage: string
summarizeEnabled: boolean
summarizePrimaryLanguage: string
summarizeSecondaryLanguage: string
// prompts: string
}
interface PopClip {
context: Context
modifiers: Modifiers
showSuccess(): void
showFailure(): void
showText(text: string, options?: { preview?: boolean }): void
copyText(text: string): void
pasteText(text: string, options?: { restore?: boolean }): void
}
// Ref: https://platform.openai.com/docs/api-reference/chat/create
interface Message {
role: "user" | "system" | "assistant"
content: string
}
interface APIRequestData {
model: string
messages: Array<Message>
temperature?: number
top_p?: number
}
interface APIResponse {
data: {
choices: [{
message: Message
}];
}
}
type AllowedOneTimeActions = "revise" | "polish" | "translate" | "summarize"
type AllowedActions = "chat" | AllowedOneTimeActions
abstract class ChatGPTAction {
abstract beforeRequest(popclip: PopClip, input: Input, options: Options, action: AllowedActions): { allow: boolean, reason?: string }
abstract makeRequestData(popclip: PopClip, input: Input, options: Options, action: AllowedActions): APIRequestData | null
processResponse(popclip: PopClip, resp: APIResponse): string {
return resp.data.choices[0].message.content.trim()
}
onRequestError(popclip: PopClip, e: unknown) { }
doCleanup(): void { }
}
const InactiveChatHistoryResetIntervalMs = 20 * 1000 * 60 // 20 minutes.
// const MaxChatHistoryLength = 50
class ChatHistory {
readonly appIdentifier: string
private _lastActiveAt: Date
private _messages: Array<Message>
constructor(appIdentifier: string) {
this.appIdentifier = appIdentifier
this._lastActiveAt = new Date()
this._messages = []
}
isActive(): boolean {
return new Date().getTime() - this._lastActiveAt.getTime() < InactiveChatHistoryResetIntervalMs
}
clear() {
this._messages.length = 0
}
push(message: Message) {
this._messages.push(message)
this._lastActiveAt = new Date()
}
pop(): Message | undefined {
return this._messages.pop()
}
get lastActiveAt(): Date {
return this._lastActiveAt
}
get messages(): Array<Message> {
return this._messages
}
}
class ChatAction extends ChatGPTAction {
// Chat histories grouped by application identify.
private chatHistories: Map<string, ChatHistory>
constructor() {
super()
this.chatHistories = new Map()
}
private getChatHistory(appIdentifier: string): ChatHistory {
let chat = this.chatHistories.get(appIdentifier)
if (!chat) {
chat = new ChatHistory(appIdentifier)
this.chatHistories.set(appIdentifier, chat)
}
return chat
}
doCleanup() {
for (const [appid, chat] of this.chatHistories) {
if (!chat.isActive()) {
this.chatHistories.delete(appid)
}
}
}
beforeRequest(popclip: PopClip, input: Input, options: Options, action: AllowedActions): { allow: boolean, reason?: string } {
if (popclip.modifiers.shift) {
this.chatHistories.delete(popclip.context.appIdentifier)
const text = `${popclip.context.appName}(${popclip.context.appIdentifier})'s chat history has been cleared`
return { allow: false, reason: text }
}
return { allow: true }
}
makeRequestData(popclip: PopClip, input: Input, options: Options, action: AllowedActions): APIRequestData | null {
if (action !== "chat") {
return null
}
const chat = this.getChatHistory(popclip.context.appIdentifier)
chat.push({ role: "user", content: input.text })
return {
model: options.model,
messages: chat.messages,
temperature: Number(options.temperature),
}
}
onRequestError(popclip: PopClip, e: unknown) {
const chat = this.getChatHistory(popclip.context.appIdentifier)
chat.pop() // Pop out the user message.
}
processResponse(popclip: PopClip, resp: APIResponse): string {
const chat = this.getChatHistory(popclip.context.appIdentifier)
chat.push(resp.data.choices[0].message)
return resp.data.choices[0].message.content.trim()
}
}
class OneTimeAction extends ChatGPTAction {
private getPrompt(action: AllowedOneTimeActions, language: string): string {
switch (action) {
case "revise":
return `Please revise the text to improve its clarity, brevity, and coherence. Document the changes made and provide a concise explanation for each modification (IMPORTANT: reply with ${language} language).`
case "polish":
return `Please correct the grammar and polish the text while adhering as closely as possible to the original intention (IMPORTANT: reply with ${language} language).`
case "translate":
return `Please translate the text into ${language} and only provide me with the translated content without formating.`
case "summarize":
return `Please provide a concise summary of the text, ensuring that all significant points are included (IMPORTANT: reply with ${language} language).`
}
}
beforeRequest(popclip: PopClip, input: Input, options: Options, action: AllowedActions): { allow: boolean, reason?: string } {
return { allow: options[`${action}Enabled`] }
}
makeRequestData(popclip: PopClip, input: Input, options: Options, action: AllowedActions): APIRequestData | null {
if (action === "chat") {
return null
}
const language = popclip.modifiers.shift ? options[`${action}SecondaryLanguage`] : options[`${action}PrimaryLanguage`]
const prompt = this.getPrompt(action as AllowedOneTimeActions, language)
return {
model: options.model,
messages: [
// { role: "system", content: "You are a professional multilingual assistant who will help me revise, polish, or translate texts. Please strictly follow user instructions." },
{
role: "user", content: `${prompt}
The input text being used for this task is enclosed within triple quotation marks below the next line:
"""${input.text}"""`,
},
],
temperature: Number(options.temperature),
}
}
}
function makeClientOptions(options: Options): object {
const timeoutMs = 35000
if (options.apiType === "openai") {
return {
"baseURL": options.apiBase,
headers: { Authorization: `Bearer ${options.apiKey}` },
timeout: timeoutMs,
}
} else if (options.apiType === "azure") {
// Ref: https://learn.microsoft.com/en-us/azure/ai-services/openai/reference#chat-completions
return {
"baseURL": options.apiBase,
headers: { "api-key": `${options.apiKey}` },
params: {
"api-version": options.apiVersion,
},
timeout: timeoutMs,
}
}
throw new Error(`unsupported api type: ${options.apiType}`);
}
function isTerminalApplication(appName: string): boolean {
return appName === "iTerm2" || appName === "Terminal"
}
const chatGPTActions: Map<AllowedActions, ChatAction | OneTimeAction> = new Map();
function doCleanup() {
for (const [_, actionImpl] of chatGPTActions) {
actionImpl.doCleanup()
}
}
async function doAction(popclip: PopClip, input: Input, options: Options, action: AllowedActions) {
doCleanup()
const actionImpl = chatGPTActions.get(action)!
const guard = actionImpl.beforeRequest(popclip, input, options, action)
if (!guard.allow) {
if (guard.reason) {
popclip.showText(guard.reason)
popclip.showSuccess()
}
return
}
const requestData = actionImpl.makeRequestData(popclip, input, options, action)!
const openai = axios.create(makeClientOptions(options))
try {
const resp: APIResponse = await openai.post(
"chat/completions", requestData
)
const result = actionImpl.processResponse(popclip, resp)
if (popclip.context.canPaste) {
let toBePasted = `\n\n${result}\n`
if (!isTerminalApplication(popclip.context.appName) && popclip.context.canCopy) {
// Prevent the original selected text from being replaced.
toBePasted = `${input.text}\n\n${result}\n`
}
popclip.pasteText(toBePasted, { restore: true })
popclip.showSuccess()
} else {
popclip.copyText(result)
popclip.showText(result, { preview: true })
}
} catch (e) {
actionImpl.onRequestError(popclip, e)
// popclip.showFailure()
popclip.showText(String(e))
}
}
chatGPTActions.set("chat", new ChatAction())
chatGPTActions.set("revise", new OneTimeAction())
chatGPTActions.set("polish", new OneTimeAction())
chatGPTActions.set("translate", new OneTimeAction())
chatGPTActions.set("summarize", new OneTimeAction())
export const actions = [
{
title: "ChatGPTx: do what you want (click while holding shift(⇧) to force clear the history for this app)",
// icon: "symbol:arrow.up.message.fill", // icon: "iconify:uil:edit",
requirements: ["text"],
code: async (input: Input, options: Options, context: Context) => doAction(popclip, input, options, "chat"),
},
{
title: "ChatGPTx: revise text (click while holding shift(⇧) to use the secondary language)",
icon: "symbol:r.square.fill", // icon: "iconify:uil:edit",
requirements: ["text", "option-reviseEnabled=1"],
code: async (input: Input, options: Options, context: Context) => doAction(popclip, input, options, "revise"),
},
{
title: "ChatGPTx: polish text (click while holding shift(⇧) to use the secondary language)",
icon: "symbol:p.square.fill", // icon: "iconify:lucide:stars",
requirements: ["text", "option-polishEnabled=1"],
code: async (input: Input, options: Options, context: Context) => doAction(popclip, input, options, "polish"),
},
{
title: "ChatGPTx: translate text (click while holding shift(⇧) to use the secondary language)",
icon: "symbol:t.square.fill", // icon: "iconify:system-uicons:translate",
requirements: ["text", "option-translateEnabled=1"],
code: async (input: Input, options: Options, context: Context) => doAction(popclip, input, options, "translate"),
},
{
title: "ChatGPTx: summarize text (click while holding shift(⇧) to use the secondary language)",
icon: "symbol:s.square.fill", // icon: "iconify:system-uicons:translate",
requirements: ["text", "option-summarizeEnabled=1"],
code: async (input: Input, options: Options, context: Context) => doAction(popclip, input, options, "summarize"),
},
]
// Dynamic options:
//
// Prompt to list languages:
// list top 100 languages that you can understand and generate texts in,
// remove all dialects, such as Chinese dialects(but do include "Chinese Simplified" and "Chinese Traditional" ),
// reply in JSON format using both English and their corresponding native language, e.g. [{"english": "Chinese Simplified", "native": "简体中文"}].
//
// Please double check and count by yourself first.
//
// (Unfortunately, ChatGPT is unable to list 100 languages and I am exhausted from trying to make it accurate..)
import * as languages from "./top-languages-from-chatgpt.json"
const optionLanguagesValues: Array<string> = new Array()
const optionLanguagesValueLabels: Array<string> = new Array()
languages.sort((a, b) => {
if (a.english < b.english) {
return -1
} else if (a.english > b.english) {
return 1
}
return 0
}).forEach((value) => {
optionLanguagesValues.push(value.english)
optionLanguagesValueLabels.push(value.native)
})
const chatGPTActionsOptions: Array<any> = [
{
"identifier": "apiType",
"label": "API Type",
"type": "multiple",
"default value": "openai",
"values": [
"openai",
"azure"
]
},
{
"identifier": "apiBase",
"label": "API Base URL",
"description": "For Azure: https://{resource-name}.openai.azure.com/openai/deployments/{deployment-id}",
"type": "string",
"default value": "https://api.openai.com/v1"
},
{
"identifier": "apiKey",
"label": "API Key",
"type": "string",
},
{
"identifier": "model",
"label": "Model",
"type": "string",
"default value": "gpt-3.5-turbo"
},
{
"identifier": "apiVersion",
"label": "API Version (Azure only)",
"type": "string",
"default value": "2023-12-01-preview"
},
{
"identifier": "temperature",
"label": "Sampling Temperature",
"type": "string",
"description": ">=0, <=2. Higher values will result in a more random output, and vice versa.",
"default value": "1"
},
{
"identifier": "opinionedActions",
"label": "❤ OPINIONED ACTIONS",
"type": "heading",
"description": "Click while holding shift(⇧) to use the secondary language.",
}
]
new Array(
{ name: "revise", primary: "English", secondary: "Chinese Simplified" },
{ name: "polish", primary: "English", secondary: "Chinese Simplified" },
{ name: "translate", primary: "Chinese Simplified", secondary: "English" },
{ name: "summarize", primary: "Chinese Simplified", secondary: "English" },
).forEach((value) => {
const capitalizedName = value.name.charAt(0).toUpperCase() + value.name.slice(1)
chatGPTActionsOptions.push(
{
"identifier": value.name,
"label": `${capitalizedName} Texts`,
"type": "heading"
},
{
"identifier": `${value.name}Enabled`,
"label": "Enable",
"type": "boolean",
"inset": true
},
{
"identifier": `${value.name}PrimaryLanguage`,
"label": "Primary",
"type": "multiple",
"default value": `${value.primary}`,
"values": optionLanguagesValues,
"value labels": optionLanguagesValueLabels,
"inset": true
},
{
"identifier": `${value.name}SecondaryLanguage`,
"label": "Secondary",
"type": "multiple",
"default value": `${value.secondary}`,
"values": optionLanguagesValues,
"value labels": optionLanguagesValueLabels,
"inset": true
})
})
export const options = chatGPTActionsOptions