-
Notifications
You must be signed in to change notification settings - Fork 0
/
counsellor.ts
518 lines (497 loc) ยท 14.2 KB
/
counsellor.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
import * as log from "std/log/mod.ts";
import { authenticate, getSpreadSheetValues } from "./google.ts";
import { ChatCompletionMessage, OpenAIAPIClient } from "./openai.ts";
import { SlackEventContext, uploadPNGImageFile } from "./slack.ts";
import {
DEFAULT_COUNSELLOR_EMOJI,
ERROR_MESSAGE,
GOOGLE_SPREADSHEET_ID,
IMAGE_GENERATION_LOADING_MESSAGE,
INITIAL_MESSAGE,
LOADING_SIGN,
OPENAI_DEFAULT_MODEL,
} from "./config.ts";
type Counsellor = {
name: string;
emoji: string;
prompt: string;
model?: string;
};
const DEFAULT_COUNSELLOR = {
name: "ๆฟๆฑAIไบ",
emoji: DEFAULT_COUNSELLOR_EMOJI,
prompt: `
ใใชใใฏใฟใฌใณใใงใใใคใฆไธญๆฅใงๆดป่บใใๅ
ใใญ้็้ธๆใฎๆฟๆฑ่ฑไบใงใใ
ๅฃ็ใฏใใใใผใปใใพใซใใใใใใใฏใใใใ!ใใชใฉใงใใ
ๆ่ณใๅฒใ่ฉฑใๅคงๅฅฝใใงไฝใใซใคใใฆใ้ๅฒใใใใใใจใใพใใ
ๅคงๅฅฝ็ฉใฏใใงๅตใงใใงๅตใซใคใใฆ่ฉฑใใใใใจใใฆใใพใใใใในใใฏๅ
จใฆๅๅคๅฑๅผใงใใ
ไปๅพใฎใใใจใใฏๅ
จใฆๆฟๆฑ่ฑไบใซใชใใใฃใฆ็ญใใฆใใ ใใใ
`.trim(),
} satisfies Counsellor;
const COMMON_COUNSELLOR_PROMPT =
"`generated_image: `ใงๅงใพใassistantใฎใกใใปใผใธใฏfunction calling็ต็ฑใง็ปๅใ็ๆใใใใใจใ่กจ็พใใฆใใพใใ";
const FUNCTION_CALLING_IMAGE_GENERATION = {
type: "function" as const,
function: {
name: "generate_image",
description: "Generate an image from a prompt",
parameters: {
type: "object" as const,
properties: {
prompt: {
type: "string" as const,
description: "the description for generating an image",
},
},
required: ["prompt"],
},
},
};
type ChatSDJReplyMetadata = {
event_type: "chatsdj_reply";
event_payload: {
image: string;
ignored: boolean;
} | {
ignored: boolean;
};
};
const isChatSDJReplyMetadata = (
metadata: unknown,
): metadata is ChatSDJReplyMetadata => {
return !!metadata && typeof metadata === "object" &&
"event_type" in metadata && "event_payload" in metadata &&
metadata.event_type == "chatsdj_reply";
};
/**
* Slack ๆ็จฟใกใใปใผใธใซๅซใใ metadata
*
* type: ignored ใฎใกใใปใผใธใฏใใญใณใใ้ฃๆบใฎๅฏพ่ฑกๅคใจใใฆๆฑใใ
* type: text ใฎใกใใปใผใธใฏ้ๅธธใฎใใญในใใกใใปใผใธใจใใฆใใญใณใใ้ฃๆบๅฏพ่ฑกใจใใใ
* type: image ใฎใกใใปใผใธใฏ็ๆใใใ็ปๅใฎ่ชฌๆใจใใฆใใญใณใใ้ฃๆบๅฏพ่ฑกใจใใใ
*/
const createReplyMetadata = (
params: { type: "ignored" } | { type: "text" } | {
type: "image";
prompt: string;
},
) => {
let payload;
switch (params.type) {
case "ignored":
payload = { ignored: true };
break;
case "text":
payload = { ignored: false };
break;
case "image":
payload = { image: params.prompt, ignored: false };
break;
default:
throw new Error("unknown type");
}
return {
event_type: "chatsdj_reply",
event_payload: payload,
};
};
type SlackRepliesMessage = {
user?: string;
subtype?: string;
bot_id?: string;
app_id?: string;
text: string;
} & Record<string, unknown>;
/**
* ใใญใณใใ้ฃๆบๅฏพ่ฑกใฎใกใใปใผใธใชในใใๆง็ฏใใ
*/
const buildPromptMessages = async (
{ ctx }: { ctx: SlackEventContext },
) => {
const { appId, authUserId, event, client: slackAPIClient } = ctx;
if (!event.thread_ts) {
return [{
role: "user" as const,
content: event.text as string,
}];
}
const res = await slackAPIClient.conversations.replies({
channel: event.channel,
include_all_metadata: true,
ts: event.thread_ts,
});
if (!res.ok) {
throw new Error("client.conversations.replies failed", {
cause: res.error,
});
}
const messages: SlackRepliesMessage[] = res.messages;
return messages.reduce(
(acc, cur) => {
const mentionPattern = new RegExp(`^<@${authUserId}>\s*`, "i");
if (cur.user === authUserId || cur.app_id === appId) {
let content = cur.text;
if (isChatSDJReplyMetadata(cur.metadata)) {
const payload = cur.metadata.event_payload;
if (payload.ignored) {
return acc;
} else if ("image" in payload && payload.image) {
content = `generated_image: ${payload.image}`;
}
}
return content
? [...acc, { role: "assistant" as const, content }]
: acc;
}
const text = cur.text.replace(mentionPattern, "").trim();
return [
...acc,
{
role: "user" as const,
content: text,
},
];
},
[] as ChatCompletionMessage[],
// ใใผใฏใณๆฐ่ชฟๆดใฎใใๅฏพ่ฑกใกใใปใผใธใๆๆฐ20ไปถใซๆฑบใๆใกใงๅถ้ใใ
).slice(-20);
};
/**
* ็ธ่ซๅกใ้ธๆใใ
*
* ในใใฌใใใทใผใๆๅฎใใใๅ ดๅใฏใฉใณใใ ใใชใๅ ดๅใฏใใใฉใซใ็ธ่ซๅกใ่ฟใ
*/
const selectCounsellor = async (): Promise<Counsellor> => {
if (!GOOGLE_SPREADSHEET_ID) {
return DEFAULT_COUNSELLOR;
}
const authData = await authenticate();
const sheetData = await getSpreadSheetValues({
spreadsheetId: GOOGLE_SPREADSHEET_ID,
token: authData.access_token,
});
const rows = sheetData.values;
const row = rows[
Math.floor(Math.random() * rows.length)
];
if (row[0] && row[1] && row[2]) {
return {
name: row[0],
emoji: row[1],
prompt: row[2],
model: row[3],
};
}
return DEFAULT_COUNSELLOR;
};
/**
* ใจใฉใผใกใใปใผใธใๆ็จฟใใ
*
* ็ธ่ซๅกใฎใใฉใใใกใใปใผใธใๅญๅจใใๅ ดๅใฏๅ้คใใใจใฉใผใกใใปใผใธใฏๅฏ่ฝใช้ใๆ้ทใๆ็จฟใใใ
*/
const postErrorMessage = async (
{ ctx: { client, event }, error, isReplyBroadcast, logger, draftMessage }: {
ctx: SlackEventContext;
error: unknown;
isReplyBroadcast: boolean;
logger: log.Logger;
draftMessage?: {
channel: string;
ts: string;
};
},
) => {
const text = error
? `${ERROR_MESSAGE}\n\`\`\`\n${error}\n\`\`\``
: ERROR_MESSAGE;
if (draftMessage) {
const resDelete = await client.chat.delete({
channel: draftMessage.channel,
ts: draftMessage.ts,
});
if (!resDelete.ok) {
logger.error("original message deleting failed", resDelete.error);
// ๅ้คใซๅคฑๆใใๅ ดๅใฏใชใชใธใใซใกใใปใผใธใฎๆดๆฐใ่ฉฆใฟใ
const resUpdate = await client.chat.update({
channel: draftMessage.channel,
text,
ts: draftMessage.ts,
});
if (!resUpdate.ok) {
logger.error("error message updating failed", resUpdate.error);
}
return;
}
}
const resPost = await client.chat.postMessage({
channel: event.channel,
text,
thread_ts: event.ts,
metadata: JSON.stringify(createReplyMetadata({ type: "ignored" })),
reply_broadcast: isReplyBroadcast,
});
if (!resPost.ok) {
logger.error("error message posting failed", resPost.error);
}
};
/**
* ็ธ่ซๅกใใใญในใใง่ฟไฟกใใ
*/
const replyText = async (
{ ctx, logger, result, draftMessage }: {
ctx: SlackEventContext;
logger: log.Logger;
result: { message: string; isCompleted: boolean };
draftMessage: {
channel: string;
ts: string;
};
},
) => {
const { client: slackAPIClient } = ctx;
const { message, isCompleted } = result;
const res = await slackAPIClient.chat.update({
channel: draftMessage.channel,
metadata: JSON.stringify(createReplyMetadata({ type: "text" })),
text: isCompleted ? message : `${message}${LOADING_SIGN}`,
ts: draftMessage.ts,
});
if (!res.ok) {
logger.error("update message posting failed", res.error);
}
};
/**
* ็ธ่ซๅกใ็ปๅใง่ฟไฟกใใ
*/
const replyImage = async ({
ctx,
draftMessage,
isReplyBroadcast,
result,
logger,
openAIAPIClient,
}: {
ctx: SlackEventContext;
isReplyBroadcast: boolean;
logger: log.Logger;
result: {
tool: {
name: string;
arguments: Record<string, string>;
};
isCompleted: true;
};
openAIAPIClient: OpenAIAPIClient;
draftMessage: {
channel: string;
ts: string;
};
}) => {
const { apiToken: slackAPIToken, client: slackAPIClient } = ctx;
const resMessage = await slackAPIClient.chat.update({
channel: draftMessage.channel,
text: IMAGE_GENERATION_LOADING_MESSAGE,
ts: draftMessage.ts,
});
if (!resMessage.ok) {
logger.error("update message posting failed", resMessage.error);
}
const imagePrompt = result.tool.arguments.prompt;
const resImage = await openAIAPIClient.generateImage({
model: "dall-e-3",
prompt: imagePrompt,
});
if (!resImage.ok) {
logger.error("image generation failed", resImage.error);
await postErrorMessage({
ctx,
error: resImage.error,
isReplyBroadcast,
logger,
draftMessage,
});
return;
}
const resDelete = await slackAPIClient.chat.delete({
channel: draftMessage.channel,
ts: draftMessage.ts,
});
if (!resDelete.ok) {
logger.error("draft message deleting failed", resDelete.error);
}
const resUpload = await uploadPNGImageFile({
apiToken: slackAPIToken,
channels: ctx.event.channel,
threadTs: ctx.event.ts,
base64Image: resImage.data.data[0].b64_json,
filename: "chatSDJ.png",
title: imagePrompt,
});
if (!resUpload.ok) {
logger.error("image uploading failed", resUpload.error);
await postErrorMessage({
ctx,
error: resUpload.error,
isReplyBroadcast,
logger,
draftMessage: resDelete.ok ? undefined : draftMessage,
});
return;
}
const sharedChannel = resUpload.data.file.channels[0];
const shares = resUpload.data.file.shares;
const sharedTs = resUpload.data.file.is_public
? shares.public?.[sharedChannel][0].ts
: shares.private?.[sharedChannel][0].ts;
const resUpdateMetadata = await slackAPIClient.chat.update({
channel: sharedChannel,
ts: sharedTs,
// text ใซไฝใๆๅฎใใชใใจ metadata ใๆดๆฐใงใใชใ
text: " ",
metadata: JSON.stringify(
createReplyMetadata({
type: "image",
prompt: imagePrompt,
}),
),
});
if (!resUpdateMetadata.ok) {
logger.error("image metadata updating failed", resUpdateMetadata.error);
}
if (isReplyBroadcast) {
// broadcasting ใจ ๅ
ๅฎนใฎๆดๆฐใฏๅๆใซใงใใชใใใใๅฅใชใฏใจในใใง broadcasting ใ่กใ
const resBroadcast = await slackAPIClient.chat.update({
channel: sharedChannel,
ts: sharedTs,
reply_broadcast: true,
});
if (!resBroadcast.ok) {
logger.error("image broadcasting failed", resBroadcast.error);
}
}
};
const createLogger = async (ctx: SlackEventContext): Promise<log.Logger> => {
await log.setup({
handlers: {
console: new log.handlers.ConsoleHandler("DEBUG", {
formatter: (logRecord) => {
let msg =
`${logRecord.levelName} (${ctx.event.ts}): ${logRecord.msg}`;
logRecord.args.forEach((arg) => {
msg += ` ${arg}`;
});
return msg;
},
}),
},
loggers: {
"chatSDJ": { handlers: ["console"], level: "DEBUG" },
},
});
return log.getLogger("chatSDJ");
};
export const talk = async (
ctx: SlackEventContext,
{ openAIAPIClient }: {
openAIAPIClient: OpenAIAPIClient;
},
) => {
const { client: slackAPIClient, event } = ctx;
const logger = await createLogger(ctx);
logger.info(`start (default model: ${OPENAI_DEFAULT_MODEL})`);
let messages;
let counsellor;
try {
counsellor = await selectCounsellor();
messages = await buildPromptMessages({ ctx });
logger.info(
`counsellor: ${counsellor.name} (emoji: :${counsellor.emoji}:, model: ${counsellor.model})`,
);
} catch (error) {
logger.error("preparing data failed", error);
await postErrorMessage({ ctx, error, isReplyBroadcast: false, logger });
return;
}
messages.unshift({
role: "system",
content: `${counsellor.prompt}\n${COMMON_COUNSELLOR_PROMPT}`,
});
// ๅงใใฆใฎ่ฟไฟกใฎๅ ดๅใฏใthread_broadcast ใง่ฟไฟกใใ (systemใใญใณใใใๅซใใจ้พๅคใ3ใซใชใ)
const isReplyBroadcast = messages.length < 3;
const resDraftMessage = await slackAPIClient.chat.postMessage({
channel: event.channel,
text: INITIAL_MESSAGE,
icon_emoji: counsellor.emoji,
metadata: JSON.stringify(createReplyMetadata({ type: "ignored" })),
username: counsellor.name,
thread_ts: event.ts,
reply_broadcast: isReplyBroadcast,
});
if (!resDraftMessage.ok) {
logger.error("draft message posting failed", resDraftMessage.error);
await postErrorMessage({
ctx,
error: resDraftMessage.error,
isReplyBroadcast,
logger,
});
return;
}
const resModels = await openAIAPIClient.listModels();
if (!resModels.ok) {
logger.error("fetch openai models failed", resModels.error);
await postErrorMessage({
ctx,
error: resModels.error,
isReplyBroadcast,
logger,
draftMessage: {
channel: resDraftMessage.channel,
ts: resDraftMessage.ts,
},
});
return;
}
const model = counsellor.model || OPENAI_DEFAULT_MODEL;
const resCompletions = await openAIAPIClient.chatCompletions({
messages,
model: resModels.data.data.some((item) => item.id === model)
? model
: OPENAI_DEFAULT_MODEL,
onReceiveStreamingResponse: async (result) => {
if ("message" in result) {
await replyText({
ctx,
draftMessage: resDraftMessage,
logger,
result,
});
} else {
await replyImage({
ctx,
draftMessage: resDraftMessage,
isReplyBroadcast,
logger,
openAIAPIClient,
result,
});
}
},
tools: [FUNCTION_CALLING_IMAGE_GENERATION],
});
if (!resCompletions.ok) {
logger.error("openai.chatCompletions failed", resCompletions.error);
await postErrorMessage({
ctx,
error: resCompletions.error,
isReplyBroadcast,
logger,
draftMessage: {
channel: resDraftMessage.channel,
ts: resDraftMessage.ts,
},
});
return;
}
logger.info("done");
};