-
Notifications
You must be signed in to change notification settings - Fork 296
Expand file tree
/
Copy pathprocess-knowledge-base-documents-orchestrator.ts
More file actions
168 lines (146 loc) · 5.28 KB
/
process-knowledge-base-documents-orchestrator.ts
File metadata and controls
168 lines (146 loc) · 5.28 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
import { logger, metadata, tags, task } from '@trigger.dev/sdk';
import { processKnowledgeBaseDocumentTask } from './process-knowledge-base-document';
const BATCH_SIZE = 10; // Process 10 documents at a time
/**
* Orchestrator task to process multiple Knowledge Base documents in parallel batches
* Similar to vendor-questionnaire-orchestrator, this manages the processing of multiple documents
*/
export const processKnowledgeBaseDocumentsOrchestratorTask = task({
id: 'process-knowledge-base-documents-orchestrator',
retry: {
maxAttempts: 3,
},
maxDuration: 60 * 60, // 1 hour (in seconds) for large document batches
run: async (payload: { documentIds: string[]; organizationId: string }) => {
await tags.add([`org:${payload.organizationId}`]);
logger.info('Starting Knowledge Base documents processing orchestrator', {
organizationId: payload.organizationId,
documentCount: payload.documentIds.length,
});
if (payload.documentIds.length === 0) {
logger.info('No documents to process');
return {
success: true,
processed: 0,
failed: 0,
};
}
// Initialize metadata for tracking progress
metadata.set('documentsTotal', payload.documentIds.length);
metadata.set('documentsCompleted', 0);
metadata.set('documentsFailed', 0);
metadata.set('documentsRemaining', payload.documentIds.length);
metadata.set('currentBatch', 0);
metadata.set(
'totalBatches',
Math.ceil(payload.documentIds.length / BATCH_SIZE),
);
// Initialize individual document statuses - all start as 'pending'
payload.documentIds.forEach((documentId, index) => {
metadata.set(`document_${documentId}_status`, 'pending');
});
const results: Array<{
documentId: string;
success: boolean;
chunkCount?: number;
error?: string;
}> = [];
// Process documents in batches
for (let i = 0; i < payload.documentIds.length; i += BATCH_SIZE) {
const batch = payload.documentIds.slice(i, i + BATCH_SIZE);
const batchNumber = Math.floor(i / BATCH_SIZE) + 1;
const totalBatches = Math.ceil(payload.documentIds.length / BATCH_SIZE);
logger.info(`Processing batch ${batchNumber}/${totalBatches}`, {
batchSize: batch.length,
documentIds: batch,
});
// Update metadata
metadata.set('currentBatch', batchNumber);
// Mark documents as processing
batch.forEach((documentId) => {
metadata.set(`document_${documentId}_status`, 'processing');
});
// Use batchTriggerAndWait - this runs tasks in parallel and waits for all to complete
const batchItems = batch.map((documentId) => ({
payload: {
documentId,
organizationId: payload.organizationId,
},
}));
const batchHandle =
await processKnowledgeBaseDocumentTask.batchTriggerAndWait(batchItems);
// Process batch results
batchHandle.runs.forEach((run, batchIdx) => {
const documentId = batch[batchIdx];
if (run.ok && run.output) {
const taskResult = run.output;
if (taskResult.success) {
results.push({
documentId,
success: true,
chunkCount: taskResult.chunkCount,
});
metadata.set(`document_${documentId}_status`, 'completed');
metadata.increment('documentsCompleted');
} else {
results.push({
documentId,
success: false,
error: taskResult.error,
});
metadata.set(`document_${documentId}_status`, 'failed');
metadata.increment('documentsFailed');
}
} else {
// Task failed
const errorMessage =
run.ok === false && run.error
? run.error instanceof Error
? run.error.message
: String(run.error)
: 'Unknown error';
logger.error('Document processing task failed', {
documentId,
error: errorMessage,
});
results.push({
documentId,
success: false,
error: errorMessage,
});
metadata.set(`document_${documentId}_status`, 'failed');
metadata.increment('documentsFailed');
}
});
// Update remaining count
const completed =
results.filter((r) => r.success).length +
results.filter((r) => !r.success).length;
metadata.set(
'documentsRemaining',
payload.documentIds.length - completed,
);
logger.info(`Batch ${batchNumber}/${totalBatches} completed`, {
batchSize: batch.length,
successful: results.filter((r) => r.success).length,
failed: results.filter((r) => !r.success).length,
});
}
const successful = results.filter((r) => r.success).length;
const failed = results.filter((r) => !r.success).length;
logger.info('Knowledge Base documents processing orchestrator completed', {
organizationId: payload.organizationId,
total: payload.documentIds.length,
successful,
failed,
});
// Mark as completed
metadata.set('completed', true);
return {
success: true,
processed: successful,
failed,
results,
};
},
});