@studious-lms/server 1.5.0 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +15 -3
- package/dist/index.js.map +1 -1
- package/dist/lib/config/cors.d.ts.map +1 -1
- package/dist/lib/config/cors.js +3 -2
- package/dist/lib/config/cors.js.map +1 -1
- package/dist/lib/pusher.d.ts +7 -1
- package/dist/lib/pusher.d.ts.map +1 -1
- package/dist/lib/pusher.js +9 -3
- package/dist/lib/pusher.js.map +1 -1
- package/dist/models/attendance.d.ts +16 -7
- package/dist/models/attendance.d.ts.map +1 -1
- package/dist/models/attendance.js +17 -2
- package/dist/models/attendance.js.map +1 -1
- package/dist/models/conversation.d.ts +17 -17
- package/dist/pipelines/aiLabChat.d.ts +20 -9
- package/dist/pipelines/aiLabChat.d.ts.map +1 -1
- package/dist/pipelines/aiLabChat.js +62 -74
- package/dist/pipelines/aiLabChat.js.map +1 -1
- package/dist/pipelines/aiNewtonChat.d.ts +13 -4
- package/dist/pipelines/aiNewtonChat.d.ts.map +1 -1
- package/dist/pipelines/aiNewtonChat.js +39 -27
- package/dist/pipelines/aiNewtonChat.js.map +1 -1
- package/dist/pipelines/pdfToWorksheet.d.ts +31 -2
- package/dist/pipelines/pdfToWorksheet.d.ts.map +1 -1
- package/dist/pipelines/pdfToWorksheet.js +160 -28
- package/dist/pipelines/pdfToWorksheet.js.map +1 -1
- package/dist/routers/_app.d.ts +18 -4
- package/dist/routers/_app.d.ts.map +1 -1
- package/dist/routers/assignment.d.ts.map +1 -1
- package/dist/routers/assignment.js +64 -4
- package/dist/routers/assignment.js.map +1 -1
- package/dist/routers/labChat.d.ts +1 -0
- package/dist/routers/labChat.d.ts.map +1 -1
- package/dist/routers/message.d.ts +3 -0
- package/dist/routers/message.d.ts.map +1 -1
- package/dist/routers/newtonChat.d.ts +1 -0
- package/dist/routers/newtonChat.d.ts.map +1 -1
- package/dist/routers/worksheet.d.ts +4 -2
- package/dist/routers/worksheet.d.ts.map +1 -1
- package/dist/routers/worksheet.js +16 -6
- package/dist/routers/worksheet.js.map +1 -1
- package/dist/services/announcement.js +4 -4
- package/dist/services/announcement.js.map +1 -1
- package/dist/services/assignment.d.ts.map +1 -1
- package/dist/services/assignment.js +16 -6
- package/dist/services/assignment.js.map +1 -1
- package/dist/services/attendance.d.ts.map +1 -1
- package/dist/services/attendance.js +68 -4
- package/dist/services/attendance.js.map +1 -1
- package/dist/services/labChat.d.ts +8 -1
- package/dist/services/labChat.d.ts.map +1 -1
- package/dist/services/labChat.js +101 -42
- package/dist/services/labChat.js.map +1 -1
- package/dist/services/message.d.ts +3 -0
- package/dist/services/message.d.ts.map +1 -1
- package/dist/services/message.js +8 -2
- package/dist/services/message.js.map +1 -1
- package/dist/services/newtonChat.d.ts +1 -0
- package/dist/services/newtonChat.d.ts.map +1 -1
- package/dist/services/newtonChat.js +40 -17
- package/dist/services/newtonChat.js.map +1 -1
- package/dist/services/worksheet.d.ts +15 -6
- package/dist/services/worksheet.d.ts.map +1 -1
- package/dist/services/worksheet.js +58 -12
- package/dist/services/worksheet.js.map +1 -1
- package/dist/utils/inference.d.ts +50 -1
- package/dist/utils/inference.d.ts.map +1 -1
- package/dist/utils/inference.js +167 -2
- package/dist/utils/inference.js.map +1 -1
- package/dist/workers/index.js +13 -3
- package/dist/workers/index.js.map +1 -1
- package/dist/workers/processors/aiLabChat.d.ts +7 -0
- package/dist/workers/processors/aiLabChat.d.ts.map +1 -0
- package/dist/workers/processors/aiLabChat.js +52 -0
- package/dist/workers/processors/aiLabChat.js.map +1 -0
- package/dist/workers/processors/aiNewtonChat.d.ts +7 -0
- package/dist/workers/processors/aiNewtonChat.d.ts.map +1 -0
- package/dist/workers/processors/aiNewtonChat.js +57 -0
- package/dist/workers/processors/aiNewtonChat.js.map +1 -0
- package/dist/workers/processors/createRunJobWorker.d.ts +46 -0
- package/dist/workers/processors/createRunJobWorker.d.ts.map +1 -0
- package/dist/workers/processors/createRunJobWorker.js +118 -0
- package/dist/workers/processors/createRunJobWorker.js.map +1 -0
- package/dist/workers/processors/gradeWorksheet.d.ts +6 -0
- package/dist/workers/processors/gradeWorksheet.d.ts.map +1 -0
- package/dist/workers/processors/gradeWorksheet.js +19 -0
- package/dist/workers/processors/gradeWorksheet.js.map +1 -0
- package/dist/workers/processors/pdfToWorksheet.d.ts +5 -6
- package/dist/workers/processors/pdfToWorksheet.d.ts.map +1 -1
- package/dist/workers/processors/pdfToWorksheet.js +15 -95
- package/dist/workers/processors/pdfToWorksheet.js.map +1 -1
- package/dist/workers/processors/studentProgressChat.d.ts +8 -0
- package/dist/workers/processors/studentProgressChat.d.ts.map +1 -0
- package/dist/workers/processors/studentProgressChat.js +27 -0
- package/dist/workers/processors/studentProgressChat.js.map +1 -0
- package/dist/workers/queues.d.ts +20 -4
- package/dist/workers/queues.d.ts.map +1 -1
- package/dist/workers/queues.js +3 -3
- package/dist/workers/queues.js.map +1 -1
- package/package.json +3 -3
- package/src/index.ts +12 -1
- package/src/lib/config/cors.ts +1 -0
- package/src/lib/pusher.ts +7 -1
- package/src/models/attendance.ts +15 -0
- package/src/pipelines/aiLabChat.ts +70 -78
- package/src/pipelines/aiNewtonChat.ts +47 -31
- package/src/pipelines/pdfToWorksheet.ts +224 -32
- package/src/routers/assignment.ts +74 -3
- package/src/routers/worksheet.ts +25 -4
- package/src/services/announcement.ts +2 -2
- package/src/services/assignment.ts +18 -4
- package/src/services/attendance.ts +87 -2
- package/src/services/labChat.ts +107 -47
- package/src/services/message.ts +6 -0
- package/src/services/newtonChat.ts +46 -25
- package/src/services/worksheet.ts +71 -10
- package/src/utils/inference.ts +209 -1
- package/src/workers/index.ts +11 -1
- package/src/workers/processors/aiLabChat.ts +65 -0
- package/src/workers/processors/aiNewtonChat.ts +75 -0
- package/src/workers/processors/createRunJobWorker.ts +164 -0
- package/src/workers/processors/gradeWorksheet.ts +16 -0
- package/src/workers/processors/pdfToWorksheet.ts +12 -114
- package/src/workers/processors/studentProgressChat.ts +28 -0
- package/src/workers/queues.ts +20 -5
- package/tests/integration/routers/attendance.test.ts +60 -1
package/src/utils/inference.ts
CHANGED
|
@@ -8,7 +8,7 @@ import { prisma } from '../lib/prisma.js';
|
|
|
8
8
|
import { chatChannel, pusher } from '../lib/pusher.js';
|
|
9
9
|
import { ensureAIUserExists, getAIUserId } from './aiUser.js';
|
|
10
10
|
import { env } from '../lib/config/env.js';
|
|
11
|
-
import { Prisma } from '@prisma/client';
|
|
11
|
+
import { JobStatus, Prisma } from '@prisma/client';
|
|
12
12
|
import { ZodSchema } from 'zod';
|
|
13
13
|
import { zodTextFormat } from 'openai/helpers/zod';
|
|
14
14
|
|
|
@@ -276,6 +276,214 @@ export async function sendAIMessage(
|
|
|
276
276
|
};
|
|
277
277
|
}
|
|
278
278
|
|
|
279
|
+
interface AIMessageSenderInfo {
|
|
280
|
+
displayName?: string;
|
|
281
|
+
profilePicture?: string | null;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function buildAISenderInfo(customSender?: AIMessageSenderInfo) {
|
|
285
|
+
return {
|
|
286
|
+
id: getAIUserId(),
|
|
287
|
+
username: 'Newton_AI',
|
|
288
|
+
profile: {
|
|
289
|
+
displayName: customSender?.displayName ?? 'Newton AI',
|
|
290
|
+
profilePicture: customSender?.profilePicture ?? null,
|
|
291
|
+
},
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/**
|
|
296
|
+
* Create an AI message placeholder in PENDING state and broadcast it.
|
|
297
|
+
*
|
|
298
|
+
* The AI message lifecycle == job lifecycle: this row is the bubble the
|
|
299
|
+
* client renders for "AI is thinking..." and is later flipped by
|
|
300
|
+
* {@link completePendingAIMessage} / {@link failPendingAIMessage}.
|
|
301
|
+
*/
|
|
302
|
+
export async function createPendingAIMessage(
|
|
303
|
+
conversationId: string,
|
|
304
|
+
options: {
|
|
305
|
+
customSender?: AIMessageSenderInfo;
|
|
306
|
+
} = {},
|
|
307
|
+
): Promise<{
|
|
308
|
+
id: string;
|
|
309
|
+
conversationId: string;
|
|
310
|
+
createdAt: Date;
|
|
311
|
+
senderId: string;
|
|
312
|
+
status: JobStatus;
|
|
313
|
+
}> {
|
|
314
|
+
await ensureAIUserExists();
|
|
315
|
+
|
|
316
|
+
const aiMessage = await prisma.message.create({
|
|
317
|
+
data: {
|
|
318
|
+
content: '',
|
|
319
|
+
senderId: getAIUserId(),
|
|
320
|
+
conversationId,
|
|
321
|
+
status: JobStatus.PENDING,
|
|
322
|
+
},
|
|
323
|
+
});
|
|
324
|
+
|
|
325
|
+
logger.info('AI placeholder message created', {
|
|
326
|
+
messageId: aiMessage.id,
|
|
327
|
+
conversationId,
|
|
328
|
+
});
|
|
329
|
+
|
|
330
|
+
const senderInfo = buildAISenderInfo(options.customSender);
|
|
331
|
+
|
|
332
|
+
try {
|
|
333
|
+
await pusher.trigger(chatChannel(conversationId), 'new-message', {
|
|
334
|
+
id: aiMessage.id,
|
|
335
|
+
content: '',
|
|
336
|
+
senderId: getAIUserId(),
|
|
337
|
+
conversationId: aiMessage.conversationId,
|
|
338
|
+
status: JobStatus.PENDING,
|
|
339
|
+
createdAt: aiMessage.createdAt,
|
|
340
|
+
sender: senderInfo,
|
|
341
|
+
mentionedUserIds: [],
|
|
342
|
+
meta: {},
|
|
343
|
+
attachments: [],
|
|
344
|
+
});
|
|
345
|
+
} catch (error) {
|
|
346
|
+
logger.error('Failed to broadcast pending AI message:', {
|
|
347
|
+
error,
|
|
348
|
+
messageId: aiMessage.id,
|
|
349
|
+
});
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
return {
|
|
353
|
+
id: aiMessage.id,
|
|
354
|
+
conversationId: aiMessage.conversationId,
|
|
355
|
+
createdAt: aiMessage.createdAt,
|
|
356
|
+
senderId: aiMessage.senderId,
|
|
357
|
+
status: JobStatus.PENDING,
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
/**
|
|
362
|
+
* Fill a PENDING AI message with its generated content and flip it to
|
|
363
|
+
* COMPLETED. Broadcasts a `message-updated` event so clients that already
|
|
364
|
+
* rendered the placeholder can patch it in place.
|
|
365
|
+
*/
|
|
366
|
+
export async function completePendingAIMessage(
|
|
367
|
+
messageId: string,
|
|
368
|
+
content: string,
|
|
369
|
+
options: {
|
|
370
|
+
attachments?: { connect: { id: string }[] };
|
|
371
|
+
meta?: Record<string, any>;
|
|
372
|
+
customSender?: AIMessageSenderInfo;
|
|
373
|
+
} = {},
|
|
374
|
+
): Promise<{
|
|
375
|
+
id: string;
|
|
376
|
+
content: string;
|
|
377
|
+
conversationId: string;
|
|
378
|
+
createdAt: Date;
|
|
379
|
+
status: JobStatus;
|
|
380
|
+
}> {
|
|
381
|
+
const updated = await prisma.message.update({
|
|
382
|
+
where: { id: messageId },
|
|
383
|
+
data: {
|
|
384
|
+
content,
|
|
385
|
+
status: JobStatus.COMPLETED,
|
|
386
|
+
...(options.attachments && {
|
|
387
|
+
attachments: {
|
|
388
|
+
connect: options.attachments.connect,
|
|
389
|
+
},
|
|
390
|
+
}),
|
|
391
|
+
...(options.meta !== undefined && {
|
|
392
|
+
meta: options.meta as Prisma.InputJsonValue,
|
|
393
|
+
}),
|
|
394
|
+
},
|
|
395
|
+
include: {
|
|
396
|
+
attachments: true,
|
|
397
|
+
},
|
|
398
|
+
});
|
|
399
|
+
|
|
400
|
+
logger.info('AI message completed', {
|
|
401
|
+
messageId: updated.id,
|
|
402
|
+
conversationId: updated.conversationId,
|
|
403
|
+
contentLength: content.length,
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
const senderInfo = buildAISenderInfo(options.customSender);
|
|
407
|
+
|
|
408
|
+
try {
|
|
409
|
+
await pusher.trigger(chatChannel(updated.conversationId), 'message-updated', {
|
|
410
|
+
id: updated.id,
|
|
411
|
+
content: updated.content,
|
|
412
|
+
senderId: updated.senderId,
|
|
413
|
+
conversationId: updated.conversationId,
|
|
414
|
+
status: updated.status,
|
|
415
|
+
createdAt: updated.createdAt,
|
|
416
|
+
sender: senderInfo,
|
|
417
|
+
mentionedUserIds: [],
|
|
418
|
+
meta: updated.meta ?? {},
|
|
419
|
+
attachments: updated.attachments.map((attachment) => ({
|
|
420
|
+
id: attachment.id,
|
|
421
|
+
attachmentId: attachment.id,
|
|
422
|
+
name: attachment.name,
|
|
423
|
+
type: attachment.type,
|
|
424
|
+
size: attachment.size,
|
|
425
|
+
path: attachment.path,
|
|
426
|
+
})),
|
|
427
|
+
});
|
|
428
|
+
} catch (error) {
|
|
429
|
+
logger.error('Failed to broadcast completed AI message:', {
|
|
430
|
+
error,
|
|
431
|
+
messageId,
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
return {
|
|
436
|
+
id: updated.id,
|
|
437
|
+
content: updated.content,
|
|
438
|
+
conversationId: updated.conversationId,
|
|
439
|
+
createdAt: updated.createdAt,
|
|
440
|
+
status: (updated.status ?? JobStatus.COMPLETED) as JobStatus,
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* Flip a PENDING AI message to FAILED and broadcast the status change.
|
|
446
|
+
* Does NOT throw — failure paths in the pipelines call this in catch blocks
|
|
447
|
+
* and we do not want broadcast/DB errors to mask the original error.
|
|
448
|
+
*/
|
|
449
|
+
export async function failPendingAIMessage(
|
|
450
|
+
messageId: string,
|
|
451
|
+
options: { reason?: string } = {},
|
|
452
|
+
): Promise<void> {
|
|
453
|
+
try {
|
|
454
|
+
const updated = await prisma.message.update({
|
|
455
|
+
where: { id: messageId },
|
|
456
|
+
data: { status: JobStatus.FAILED },
|
|
457
|
+
select: { id: true, conversationId: true, status: true },
|
|
458
|
+
});
|
|
459
|
+
|
|
460
|
+
logger.info('AI message marked as failed', {
|
|
461
|
+
messageId: updated.id,
|
|
462
|
+
conversationId: updated.conversationId,
|
|
463
|
+
reason: options.reason,
|
|
464
|
+
});
|
|
465
|
+
|
|
466
|
+
try {
|
|
467
|
+
await pusher.trigger(chatChannel(updated.conversationId), 'message-updated', {
|
|
468
|
+
id: updated.id,
|
|
469
|
+
conversationId: updated.conversationId,
|
|
470
|
+
status: updated.status,
|
|
471
|
+
});
|
|
472
|
+
} catch (broadcastError) {
|
|
473
|
+
logger.error('Failed to broadcast failed AI message:', {
|
|
474
|
+
error: broadcastError,
|
|
475
|
+
messageId,
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
} catch (error) {
|
|
479
|
+
logger.error('Failed to mark AI message as failed:', {
|
|
480
|
+
error,
|
|
481
|
+
messageId,
|
|
482
|
+
reason: options.reason,
|
|
483
|
+
});
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
|
|
279
487
|
/** Responses API user parts use `type: "input_*"`; chat completions use `text` / `image_url` / etc. */
|
|
280
488
|
function isResponseInputWithInputParts(
|
|
281
489
|
content: OpenAI.Chat.Completions.ChatCompletionMessageParam[] | ResponseInput
|
package/src/workers/index.ts
CHANGED
|
@@ -12,9 +12,19 @@ import { Worker } from 'bullmq';
|
|
|
12
12
|
import { prisma } from '../lib/prisma.js';
|
|
13
13
|
import { logger } from '../utils/logger.js';
|
|
14
14
|
import { bullConnection } from './connection.js';
|
|
15
|
+
import { aiLabChatWorker } from './processors/aiLabChat.js';
|
|
16
|
+
import { aiNewtonChatWorker } from './processors/aiNewtonChat.js';
|
|
17
|
+
import { gradeWorksheetWorker } from './processors/gradeWorksheet.js';
|
|
15
18
|
import { pdfToWorksheetWorker } from './processors/pdfToWorksheet.js';
|
|
19
|
+
import { studentProgressChatWorker } from './processors/studentProgressChat.js';
|
|
16
20
|
|
|
17
|
-
const workers: Worker<any>[] = [
|
|
21
|
+
const workers: Worker<any>[] = [
|
|
22
|
+
pdfToWorksheetWorker,
|
|
23
|
+
gradeWorksheetWorker,
|
|
24
|
+
aiLabChatWorker,
|
|
25
|
+
aiNewtonChatWorker,
|
|
26
|
+
studentProgressChatWorker,
|
|
27
|
+
];
|
|
18
28
|
|
|
19
29
|
logger.info('Workers ready', {
|
|
20
30
|
pid: process.pid,
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import {
|
|
2
|
+
generateAndSendLabIntroduction,
|
|
3
|
+
generateAndSendLabResponse,
|
|
4
|
+
} from '../../pipelines/aiLabChat.js';
|
|
5
|
+
import { prisma } from '../../lib/prisma.js';
|
|
6
|
+
import { isAIUser } from '../../utils/aiUser.js';
|
|
7
|
+
import { createRunJobWorker } from './createRunJobWorker.js';
|
|
8
|
+
|
|
9
|
+
export const aiLabChatWorker = createRunJobWorker({
|
|
10
|
+
type: 'AI_LAB_CHAT',
|
|
11
|
+
workerOptions: {
|
|
12
|
+
// Lab responses can produce PDFs and large schemas; cap concurrency to
|
|
13
|
+
// keep memory under control and to honour upstream model rate limits.
|
|
14
|
+
concurrency: 1,
|
|
15
|
+
limiter: { max: 5, duration: 60_000 },
|
|
16
|
+
},
|
|
17
|
+
run: async ({ conversationId, aiMessageId }) => {
|
|
18
|
+
const labChat = await prisma.labChat.findFirst({
|
|
19
|
+
where: { conversationId },
|
|
20
|
+
select: {
|
|
21
|
+
id: true,
|
|
22
|
+
classId: true,
|
|
23
|
+
context: true,
|
|
24
|
+
class: { select: { subject: true } },
|
|
25
|
+
},
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
if (!labChat) {
|
|
29
|
+
throw new Error(
|
|
30
|
+
`LabChat for conversationId=${conversationId} not found`,
|
|
31
|
+
);
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// The AI message is a placeholder we created before enqueue; the
|
|
35
|
+
// pipeline fills it in. Look up the most recent non-AI message in the
|
|
36
|
+
// conversation to feed the response generator. If none exists, this is
|
|
37
|
+
// the introductory message at the top of a brand-new lab chat.
|
|
38
|
+
const triggeringMessage = await prisma.message.findFirst({
|
|
39
|
+
where: {
|
|
40
|
+
conversationId,
|
|
41
|
+
senderId: { not: 'AI_ASSISTANT' },
|
|
42
|
+
},
|
|
43
|
+
orderBy: { createdAt: 'desc' },
|
|
44
|
+
select: { id: true, content: true, senderId: true },
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
if (!triggeringMessage || isAIUser(triggeringMessage.senderId)) {
|
|
48
|
+
await generateAndSendLabIntroduction(
|
|
49
|
+
labChat.id,
|
|
50
|
+
conversationId,
|
|
51
|
+
labChat.context,
|
|
52
|
+
labChat.class?.subject || 'Lab',
|
|
53
|
+
aiMessageId,
|
|
54
|
+
);
|
|
55
|
+
return { labChatId: labChat.id, kind: 'introduction', aiMessageId };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
await generateAndSendLabResponse(labChat.id, triggeringMessage.content, {
|
|
59
|
+
classId: labChat.classId,
|
|
60
|
+
aiMessageId,
|
|
61
|
+
});
|
|
62
|
+
|
|
63
|
+
return { labChatId: labChat.id, aiMessageId };
|
|
64
|
+
},
|
|
65
|
+
});
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import {
|
|
2
|
+
generateAndSendNewtonIntroduction,
|
|
3
|
+
generateAndSendNewtonResponse,
|
|
4
|
+
} from '../../pipelines/aiNewtonChat.js';
|
|
5
|
+
import { prisma } from '../../lib/prisma.js';
|
|
6
|
+
import { isAIUser } from '../../utils/aiUser.js';
|
|
7
|
+
import { createRunJobWorker } from './createRunJobWorker.js';
|
|
8
|
+
|
|
9
|
+
export const aiNewtonChatWorker = createRunJobWorker({
|
|
10
|
+
type: 'AI_NEWTON_CHAT',
|
|
11
|
+
workerOptions: {
|
|
12
|
+
concurrency: 2,
|
|
13
|
+
limiter: { max: 10, duration: 60_000 },
|
|
14
|
+
},
|
|
15
|
+
run: async ({ conversationId, aiMessageId }) => {
|
|
16
|
+
const newtonChat = await prisma.newtonChat.findFirst({
|
|
17
|
+
where: { conversationId },
|
|
18
|
+
select: {
|
|
19
|
+
id: true,
|
|
20
|
+
submission: {
|
|
21
|
+
select: {
|
|
22
|
+
id: true,
|
|
23
|
+
assignment: {
|
|
24
|
+
select: {
|
|
25
|
+
id: true,
|
|
26
|
+
title: true,
|
|
27
|
+
instructions: true,
|
|
28
|
+
class: { select: { subject: true } },
|
|
29
|
+
},
|
|
30
|
+
},
|
|
31
|
+
},
|
|
32
|
+
},
|
|
33
|
+
},
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
if (!newtonChat) {
|
|
37
|
+
throw new Error(
|
|
38
|
+
`NewtonChat for conversationId=${conversationId} not found`,
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Resolve the triggering student message (if any). On a brand-new
|
|
43
|
+
// tutor session there are no student messages yet, so we run the
|
|
44
|
+
// introduction path; otherwise we run the response path against the
|
|
45
|
+
// most recent non-AI message.
|
|
46
|
+
const triggeringMessage = await prisma.message.findFirst({
|
|
47
|
+
where: {
|
|
48
|
+
conversationId,
|
|
49
|
+
senderId: { not: 'AI_ASSISTANT' },
|
|
50
|
+
},
|
|
51
|
+
orderBy: { createdAt: 'desc' },
|
|
52
|
+
select: { id: true, content: true, senderId: true },
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
if (!triggeringMessage || isAIUser(triggeringMessage.senderId)) {
|
|
56
|
+
await generateAndSendNewtonIntroduction(
|
|
57
|
+
newtonChat.id,
|
|
58
|
+
conversationId,
|
|
59
|
+
newtonChat.submission.id,
|
|
60
|
+
aiMessageId,
|
|
61
|
+
);
|
|
62
|
+
return { newtonChatId: newtonChat.id, kind: 'introduction', aiMessageId };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
await generateAndSendNewtonResponse(
|
|
66
|
+
newtonChat.id,
|
|
67
|
+
triggeringMessage.content,
|
|
68
|
+
conversationId,
|
|
69
|
+
newtonChat.submission,
|
|
70
|
+
aiMessageId,
|
|
71
|
+
);
|
|
72
|
+
|
|
73
|
+
return { newtonChatId: newtonChat.id, aiMessageId };
|
|
74
|
+
},
|
|
75
|
+
});
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `createRunJobWorker` — shared factory for every BullMQ processor in this app.
|
|
3
|
+
*
|
|
4
|
+
* Wraps the boilerplate that every RunJob-backed worker needs:
|
|
5
|
+
* - Idempotent skip if the RunJob already SUCCEEDED (recovery after a crash
|
|
6
|
+
* that lost the BullMQ ack).
|
|
7
|
+
* - Status transitions: PENDING/RUNNING → RUNNING (with attempts++) → SUCCEEDED.
|
|
8
|
+
* - Failure handling: record latest error every attempt, flip to FAILED only
|
|
9
|
+
* on the final retry.
|
|
10
|
+
* - Standardised structured logging on `error` / `failed` / `completed`.
|
|
11
|
+
*
|
|
12
|
+
* A processor implementation only has to provide its `RunJobType`, optional
|
|
13
|
+
* BullMQ options (concurrency, limiter, etc.), and a `run` callback that does
|
|
14
|
+
* the actual work. The callback receives the typed `JobInputs[type]` payload
|
|
15
|
+
* and a context object with `runJobId`, `bullJobId`, `attempt`, plus the
|
|
16
|
+
* `userId` / `classId` from the original `enqueueRunJob` call.
|
|
17
|
+
*/
|
|
18
|
+
import { Worker, type Job, type WorkerOptions } from 'bullmq';
|
|
19
|
+
import { Prisma, type RunJobType } from '@prisma/client';
|
|
20
|
+
import { bullConnection } from '../connection.js';
|
|
21
|
+
import { prisma } from '../../lib/prisma.js';
|
|
22
|
+
import { logger } from '../../utils/logger.js';
|
|
23
|
+
import { QUEUE_NAMES, type JobInputs } from '../queues.js';
|
|
24
|
+
|
|
25
|
+
export interface RunJobContext {
|
|
26
|
+
runJobId: string;
|
|
27
|
+
bullJobId: string | undefined;
|
|
28
|
+
/** 1-indexed attempt number of the current run. */
|
|
29
|
+
attempt: number;
|
|
30
|
+
/** From `EnqueueOptions.userId` on the producer side. */
|
|
31
|
+
userId: string | null;
|
|
32
|
+
/** From `EnqueueOptions.classId` on the producer side. */
|
|
33
|
+
classId: string | null;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export interface CreateRunJobWorkerOptions<T extends RunJobType> {
|
|
37
|
+
type: T;
|
|
38
|
+
/** BullMQ `WorkerOptions` minus `connection`, which is supplied by the helper. */
|
|
39
|
+
workerOptions?: Omit<WorkerOptions, 'connection'>;
|
|
40
|
+
/**
|
|
41
|
+
* The actual work. Return any JSON-serialisable value (or `null`) — it gets
|
|
42
|
+
* persisted to `RunJob.result` for the client to read back.
|
|
43
|
+
*/
|
|
44
|
+
run: (
|
|
45
|
+
input: JobInputs[T],
|
|
46
|
+
ctx: RunJobContext,
|
|
47
|
+
) => Promise<Prisma.InputJsonValue | null>;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
type WorkerData<T extends RunJobType> = JobInputs[T] & { runJobId: string };
|
|
51
|
+
|
|
52
|
+
export function createRunJobWorker<T extends RunJobType>({
|
|
53
|
+
type,
|
|
54
|
+
workerOptions,
|
|
55
|
+
run,
|
|
56
|
+
}: CreateRunJobWorkerOptions<T>): Worker<WorkerData<T>> {
|
|
57
|
+
const name = QUEUE_NAMES[type];
|
|
58
|
+
|
|
59
|
+
const worker = new Worker<WorkerData<T>>(
|
|
60
|
+
name,
|
|
61
|
+
async (job: Job<WorkerData<T>>) => {
|
|
62
|
+
const { runJobId, ...rest } = job.data;
|
|
63
|
+
// The destructured rest is `Omit<JobInputs[T] & { runJobId }, 'runJobId'>`,
|
|
64
|
+
// which TS can't simplify back to `JobInputs[T]` while `T` is generic.
|
|
65
|
+
const input = rest as unknown as JobInputs[T];
|
|
66
|
+
|
|
67
|
+
const existing = await prisma.runJob.findUnique({
|
|
68
|
+
where: { id: runJobId },
|
|
69
|
+
select: { status: true, result: true, userId: true, classId: true },
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
if (existing?.status === 'SUCCEEDED') {
|
|
73
|
+
logger.info(`${name} RunJob already succeeded; skipping re-run`, {
|
|
74
|
+
runJobId,
|
|
75
|
+
bullJobId: job.id,
|
|
76
|
+
});
|
|
77
|
+
return existing.result;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
await prisma.runJob.update({
|
|
81
|
+
where: { id: runJobId },
|
|
82
|
+
data: {
|
|
83
|
+
status: 'RUNNING',
|
|
84
|
+
startedAt: existing?.status === 'RUNNING' ? undefined : new Date(),
|
|
85
|
+
attempts: { increment: 1 },
|
|
86
|
+
},
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
const result = await run(input, {
|
|
90
|
+
runJobId,
|
|
91
|
+
bullJobId: job.id,
|
|
92
|
+
attempt: job.attemptsMade + 1,
|
|
93
|
+
userId: existing?.userId ?? null,
|
|
94
|
+
classId: existing?.classId ?? null,
|
|
95
|
+
});
|
|
96
|
+
|
|
97
|
+
await prisma.runJob.update({
|
|
98
|
+
where: { id: runJobId },
|
|
99
|
+
data: {
|
|
100
|
+
status: 'SUCCEEDED',
|
|
101
|
+
finishedAt: new Date(),
|
|
102
|
+
error: null,
|
|
103
|
+
result: result === null ? Prisma.JsonNull : result,
|
|
104
|
+
},
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
return result;
|
|
108
|
+
},
|
|
109
|
+
{ connection: bullConnection, ...workerOptions },
|
|
110
|
+
);
|
|
111
|
+
|
|
112
|
+
worker.on('error', (err) => {
|
|
113
|
+
logger.error(`${name} worker error`, {
|
|
114
|
+
error: err.message,
|
|
115
|
+
stack: err.stack,
|
|
116
|
+
});
|
|
117
|
+
});
|
|
118
|
+
|
|
119
|
+
worker.on('failed', async (job, err) => {
|
|
120
|
+
if (!job) return;
|
|
121
|
+
|
|
122
|
+
const runJobId = job.data?.runJobId;
|
|
123
|
+
const isFinalAttempt = job.attemptsMade >= (job.opts.attempts ?? 1);
|
|
124
|
+
|
|
125
|
+
logger.error(`${name} job failed`, {
|
|
126
|
+
bullJobId: job.id,
|
|
127
|
+
runJobId,
|
|
128
|
+
attempt: job.attemptsMade,
|
|
129
|
+
finalAttempt: isFinalAttempt,
|
|
130
|
+
error: err.message,
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
if (!runJobId) return;
|
|
134
|
+
|
|
135
|
+
await prisma.runJob
|
|
136
|
+
.update({
|
|
137
|
+
where: { id: runJobId },
|
|
138
|
+
data: {
|
|
139
|
+
error: err.message,
|
|
140
|
+
...(isFinalAttempt
|
|
141
|
+
? { status: 'FAILED', finishedAt: new Date() }
|
|
142
|
+
: {}),
|
|
143
|
+
},
|
|
144
|
+
})
|
|
145
|
+
.catch((updateError) => {
|
|
146
|
+
logger.error(`Failed to record ${name} failure on RunJob`, {
|
|
147
|
+
runJobId,
|
|
148
|
+
error:
|
|
149
|
+
updateError instanceof Error
|
|
150
|
+
? updateError.message
|
|
151
|
+
: String(updateError),
|
|
152
|
+
});
|
|
153
|
+
});
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
worker.on('completed', (job) => {
|
|
157
|
+
logger.info(`${name} job completed`, {
|
|
158
|
+
bullJobId: job.id,
|
|
159
|
+
runJobId: job.data?.runJobId,
|
|
160
|
+
});
|
|
161
|
+
});
|
|
162
|
+
|
|
163
|
+
return worker;
|
|
164
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { gradeWorksheetPipeline } from '../../pipelines/gradeWorksheet.js';
|
|
2
|
+
import { createRunJobWorker } from './createRunJobWorker.js';
|
|
3
|
+
|
|
4
|
+
export const gradeWorksheetWorker = createRunJobWorker({
|
|
5
|
+
type: 'GRADE_WORKSHEET',
|
|
6
|
+
workerOptions: {
|
|
7
|
+
concurrency: 2,
|
|
8
|
+
// Each pipeline run can fan out to many per-question inferences; keep
|
|
9
|
+
// throughput modest until we measure real-world usage.
|
|
10
|
+
limiter: { max: 5, duration: 60_000 },
|
|
11
|
+
},
|
|
12
|
+
run: async ({ worksheetResponseId }) => {
|
|
13
|
+
await gradeWorksheetPipeline(worksheetResponseId);
|
|
14
|
+
return { worksheetResponseId };
|
|
15
|
+
},
|
|
16
|
+
});
|
|
@@ -1,119 +1,17 @@
|
|
|
1
|
-
import { Worker, type Job } from 'bullmq';
|
|
2
|
-
import { Prisma } from '@prisma/client';
|
|
3
|
-
import { bullConnection } from '../connection.js';
|
|
4
|
-
import { prisma } from '../../lib/prisma.js';
|
|
5
|
-
import { logger } from '../../utils/logger.js';
|
|
6
1
|
import { pdfToWorksheet } from '../../pipelines/pdfToWorksheet.js';
|
|
2
|
+
import { createRunJobWorker } from './createRunJobWorker.js';
|
|
7
3
|
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
classId: string;
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
async function process(job: Job<PdfToWorksheetJobData>) {
|
|
15
|
-
const { runJobId, gcsUrl, classId } = job.data;
|
|
16
|
-
|
|
17
|
-
// If a previous attempt already succeeded for this RunJob (rare race after a
|
|
18
|
-
// crash that lost the BullMQ ack), return the prior result instead of
|
|
19
|
-
// re-running the AI call and creating a duplicate worksheet.
|
|
20
|
-
const existing = await prisma.runJob.findUnique({
|
|
21
|
-
where: { id: runJobId },
|
|
22
|
-
select: { status: true, result: true },
|
|
23
|
-
});
|
|
24
|
-
if (existing?.status === 'SUCCEEDED') {
|
|
25
|
-
logger.info('pdfToWorksheet RunJob already succeeded; skipping re-run', {
|
|
26
|
-
runJobId,
|
|
27
|
-
bullJobId: job.id,
|
|
28
|
-
});
|
|
29
|
-
return existing.result;
|
|
30
|
-
}
|
|
31
|
-
|
|
32
|
-
await prisma.runJob.update({
|
|
33
|
-
where: { id: runJobId },
|
|
34
|
-
data: {
|
|
35
|
-
status: 'RUNNING',
|
|
36
|
-
startedAt: existing?.status === 'RUNNING' ? undefined : new Date(),
|
|
37
|
-
attempts: { increment: 1 },
|
|
38
|
-
},
|
|
39
|
-
});
|
|
40
|
-
|
|
41
|
-
const worksheet = await pdfToWorksheet(gcsUrl, classId);
|
|
42
|
-
|
|
43
|
-
const result = worksheet ? { worksheetId: worksheet.id, name: worksheet.name } : null;
|
|
44
|
-
|
|
45
|
-
await prisma.runJob.update({
|
|
46
|
-
where: { id: runJobId },
|
|
47
|
-
data: {
|
|
48
|
-
status: 'SUCCEEDED',
|
|
49
|
-
finishedAt: new Date(),
|
|
50
|
-
error: null,
|
|
51
|
-
result: result === null ? Prisma.JsonNull : (result as Prisma.InputJsonValue),
|
|
52
|
-
},
|
|
53
|
-
});
|
|
54
|
-
|
|
55
|
-
return result;
|
|
56
|
-
}
|
|
57
|
-
|
|
58
|
-
export const pdfToWorksheetWorker = new Worker<PdfToWorksheetJobData>(
|
|
59
|
-
'pdfToWorksheet',
|
|
60
|
-
process,
|
|
61
|
-
{
|
|
62
|
-
connection: bullConnection,
|
|
63
|
-
// Conservative defaults — tune once we have real-world numbers.
|
|
4
|
+
export const pdfToWorksheetWorker = createRunJobWorker({
|
|
5
|
+
type: 'PDF_TO_WORKSHEET',
|
|
6
|
+
workerOptions: {
|
|
64
7
|
concurrency: 2,
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
8
|
+
// 5 jobs / minute, e.g. to stay under OpenAI rate limits.
|
|
9
|
+
limiter: { max: 5, duration: 60_000 },
|
|
10
|
+
},
|
|
11
|
+
run: async ({ gcsUrl, classId, worksheetId }) => {
|
|
12
|
+
const worksheet = await pdfToWorksheet(gcsUrl, classId, { worksheetId });
|
|
13
|
+
return worksheet
|
|
14
|
+
? { worksheetId: worksheet.id, name: worksheet.name }
|
|
15
|
+
: null;
|
|
69
16
|
},
|
|
70
|
-
);
|
|
71
|
-
|
|
72
|
-
pdfToWorksheetWorker.on('error', (err) => {
|
|
73
|
-
logger.error('pdfToWorksheet worker error', {
|
|
74
|
-
error: err.message,
|
|
75
|
-
stack: err.stack,
|
|
76
|
-
});
|
|
77
|
-
});
|
|
78
|
-
|
|
79
|
-
pdfToWorksheetWorker.on('failed', async (job, err) => {
|
|
80
|
-
if (!job) return;
|
|
81
|
-
|
|
82
|
-
const runJobId = job.data?.runJobId;
|
|
83
|
-
const isFinalAttempt = job.attemptsMade >= (job.opts.attempts ?? 1);
|
|
84
|
-
|
|
85
|
-
logger.error('pdfToWorksheet job failed', {
|
|
86
|
-
bullJobId: job.id,
|
|
87
|
-
runJobId,
|
|
88
|
-
attempt: job.attemptsMade,
|
|
89
|
-
finalAttempt: isFinalAttempt,
|
|
90
|
-
error: err.message,
|
|
91
|
-
});
|
|
92
|
-
|
|
93
|
-
if (!runJobId) return;
|
|
94
|
-
|
|
95
|
-
// Always record the latest error message on the RunJob row.
|
|
96
|
-
// Only flip to FAILED on the final attempt — earlier failures are still
|
|
97
|
-
// "RUNNING" because BullMQ is going to retry.
|
|
98
|
-
await prisma.runJob.update({
|
|
99
|
-
where: { id: runJobId },
|
|
100
|
-
data: {
|
|
101
|
-
error: err.message,
|
|
102
|
-
...(isFinalAttempt
|
|
103
|
-
? { status: 'FAILED', finishedAt: new Date() }
|
|
104
|
-
: {}),
|
|
105
|
-
},
|
|
106
|
-
}).catch((updateError) => {
|
|
107
|
-
logger.error('Failed to record pdfToWorksheet failure on RunJob', {
|
|
108
|
-
runJobId,
|
|
109
|
-
error: updateError instanceof Error ? updateError.message : String(updateError),
|
|
110
|
-
});
|
|
111
|
-
});
|
|
112
|
-
});
|
|
113
|
-
|
|
114
|
-
pdfToWorksheetWorker.on('completed', (job) => {
|
|
115
|
-
logger.info('pdfToWorksheet job completed', {
|
|
116
|
-
bullJobId: job.id,
|
|
117
|
-
runJobId: job.data?.runJobId,
|
|
118
|
-
});
|
|
119
17
|
});
|