-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue-handler.js
More file actions
266 lines (224 loc) Β· 10 KB
/
Copy pathqueue-handler.js
File metadata and controls
266 lines (224 loc) Β· 10 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
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
// ===================
// == Queue Handler ==
// ===================
// This file contains the queue handler for LLaMA.
// It sets up the queue and the queue handler, and
// exports the queue for use in other files.
// import environment variables from .env file
import dotenv from 'dotenv';
dotenv.config();
import { createClient } from 'redis';
import bullmqPkg from 'bullmq';
const { Queue, Worker } = bullmqPkg;
import { createBullBoard } from '@bull-board/api';
import { BullMQAdapter } from '@bull-board/api/bullMQAdapter.js';
import { ExpressAdapter } from '@bull-board/express';
import { fetchChatCompletion, fetchBedrockChatCompletion } from './llm-api.js';
import { addToCollection, deleteFromCollection } from './chroma.js';
import { embedText } from './embedding.js';
import { toBoolean, generateGUID, delay } from './utils.js';
const REDIS_HOST = process.env.REDIS_HOST || "127.0.0.1";
const REDIS_PORT = process.env.REDIS_PORT || 6379;
const REDIS_USER = process.env.REDIS_USER || "default";
const REDIS_PASSWORD = process.env.REDIS_PASSWORD || "";
const COMPLETED_JOB_CLEANUP_DELAY = parseInt(process.env.COMPLETED_JOB_CLEANUP_DELAY) || 1000 * 60 * 5;
const VERBOSE_LOGGING = toBoolean(process.env.VERBOSE_LOGGING) || false;
const LLM_BEDROCK = toBoolean(process.env.LLM_BEDROCK) || false;
// -------------------------
// -- Heartbeat for Redis --
// -------------------------
export async function redisHeartbeat() {
try {
const redisClient = createClient({
url: `redis://${REDIS_USER}:${REDIS_PASSWORD}@${REDIS_HOST}:${REDIS_PORT}`
});
await redisClient.connect();
console.log(`(γ) β Redis Online β ${REDIS_HOST}:${REDIS_PORT}`);
await redisClient.disconnect();
} catch (error) {
console.log(`X β Redis Offline: ${error}`);
console.log(` redis://${REDIS_HOST}:${REDIS_PORT}`);
process.exit(1); // Exit the process with an error code
}
}
// ---------------------------
// -- Create a BullMQ queue --
// ---------------------------
const llamaQueue = new Queue('llama-requests', { connection: {
host: REDIS_HOST,
port: REDIS_PORT,
username: REDIS_USER,
password: REDIS_PASSWORD
}});
// ----------------------------------------------
// -- make the queue available by returning it --
// ----------------------------------------------
export function setupLlamaQueue() {
return llamaQueue;
}
// --------------------------------------
// -- setup the queue handler routines --
// --------------------------------------
// This function sets up the queue handler routines
// (dashboard, queue processing, and cleanup)
export function setupQueueHandler(app, responseStreams, INACTIVE_THRESHOLD, ACTIVE_CLIENTS, CHUNK_TOKEN_SIZE, CHUNK_TOKEN_OVERLAP, total_slots) {
// -----------------------
// -- Set up Bull Board --
// -----------------------
const bullBoardAdapter = new BullMQAdapter(llamaQueue);
const serverAdapter = new ExpressAdapter();
createBullBoard({
queues: [bullBoardAdapter],
serverAdapter: serverAdapter,
});
serverAdapter.setBasePath('/admin/queues');
app.use('/admin/queues', serverAdapter.getRouter());
// ------------------------------------------------
// -- Process queue with limited concurrent jobs --
// ------------------------------------------------
const worker = new Worker('llama-requests', async (job) => {
// Check if the job was flagged as inactive
if (job.data.clientNotActive) {
console.log(`Skipping inactive job: ${job.id}`);
return;
}
const { requestId } = job.data;
const res = responseStreams.get(requestId);
if (!res) return; // If response stream is not found, skip processing
try {
await streamLlamaData(job.data.fullPrompt, res, job, ACTIVE_CLIENTS, CHUNK_TOKEN_SIZE, CHUNK_TOKEN_OVERLAP); // Pass the entire job object
responseStreams.delete(requestId); // Clean up after streaming
} catch (error) {
console.log(`Error streaming data: ${job.id}`);
// console.log('Error streaming data:', error);
if (error.message.includes('slot unavailable')) {
await handleSlotUnavailableError(job); // Pass the entire job object here
}
}
}, {
connection: {
host: REDIS_HOST,
port: REDIS_PORT,
username: REDIS_USER,
password: REDIS_PASSWORD
},
concurrency: total_slots
});
// ------------------------------------------
// -- Cleanup routine for inactive clients --
// ------------------------------------------
setInterval(async () => {
const queuedJobs = await llamaQueue.getJobs(['waiting']);
for (let job of queuedJobs) {
if (!ACTIVE_CLIENTS.has(job.data.requestId) && !job.data.clientNotActive) {
job.data.clientNotActive = true;
try {
await job.remove(); // Remove the job from the queue
console.log(`Flagged job as inactive: ${job.id}`);
} catch (error) {
console.log(`Error flagging job as inactive: ${job.id}`);
}
}
}
}, INACTIVE_THRESHOLD);
// ----------------------------------------
// -- Cleanup routine for completed jobs --
// ----------------------------------------
setInterval(async () => {
const completedJobs = await llamaQueue.getJobs(['completed']);
const timeDelay = Date.now() - COMPLETED_JOB_CLEANUP_DELAY;
for (let job of completedJobs) {
if (job.finishedOn && job.finishedOn < timeDelay) {
await job.remove();
if (VERBOSE_LOGGING) { console.log(`Removed completed job: ${job.id}`); }
try {
await job.remove(); // Remove the job from the queue
if (VERBOSE_LOGGING) { console.log(`Removed completed job: ${job.id}`); }
} catch (error) {
console.log(`Error removing completed job: ${job.id}`);
}
}
}
}, COMPLETED_JOB_CLEANUP_DELAY);
}
// --------------------------------------
// -- Handle "slot unavailable" errors --
// --------------------------------------
async function handleSlotUnavailableError(job) {
const jobId = job.id;
if (VERBOSE_LOGGING) { console.warn('slot unavailable, retrying job:', jobId); }
try {
await delay(2000); // Delay before retrying
// Generate a new unique job ID for retry
const retryJobId = `retry-${jobId}-${Date.now()}`;
if (VERBOSE_LOGGING) { console.log('Retrying job with new ID:', retryJobId); }
// Remove the original job from the queue
await job.remove()
.catch(async error => {
console.log(`Error removing job: ${job.id}`);
});
// remove failed job from Chroma
await deleteFromCollection(job.opts.collectionName, job.opts.promptGUID);
// Re-add the job with the same data and the new job ID
await llamaQueue.add('chat-retry', job.data, { jobId: retryJobId, delay: 2000 });
} catch (retryError) {
console.log('Error retrying job:', retryError, 'Original job ID:', jobId);
}
}
// -----------------------------------
// -- Stream LLaMA data to response --
// -----------------------------------
export async function streamLlamaData(prompt, res, job, ACTIVE_CLIENTS, CHUNK_TOKEN_SIZE, CHUNK_TOKEN_OVERLAP) {
try {
let collectionName = job.opts.collectionName;
let jobName = job.name;
let fullResponse = ''; // Store the full response in memory for embedding
// create a short prompt for logging
const lastPrompt = prompt[prompt.length - 1].content;
const shortPrompt = lastPrompt.slice(-70);
console.log(`β β β starting response to: ...${shortPrompt}`);
// Stream the data to the response
if (LLM_BEDROCK) {
for await (const chunk of fetchBedrockChatCompletion(prompt)) {
let content = chunk;
res.write(`${content}`);
fullResponse += content; // Append the chunk to the full response
}
} else {
for await (const chunk of fetchChatCompletion(prompt)) {
let content = chunk;
res.write(`${content}`);
fullResponse += content; // Append the chunk to the full response
}
}
// Embed the full response
if (jobName === 'chat' && fullResponse !== '') {
const textChunksAndEmbeddings = await embedText(fullResponse, CHUNK_TOKEN_SIZE, CHUNK_TOKEN_OVERLAP).catch(console.log);
for (const textChunksAndEmbedding of textChunksAndEmbeddings) {
// add each chunk to the collection
addToCollection(
collectionName,
generateGUID(),
textChunksAndEmbedding.embedding,
{ source: "assistant", tokenCount: textChunksAndEmbedding.tokenCount, dateAdded: Date.now() },
textChunksAndEmbedding.text,
).catch(error => {
console.log('Error adding to collection:', error);
});
}
}
ACTIVE_CLIENTS.delete(job.id); // Remove the client from the active list
console.log(`β β β ended response to: ...${shortPrompt}`);
} catch (error) {
if (error.message.includes('slot unavailable')) {
await handleSlotUnavailableError(job); // Use job here
} else {
console.log('Error streaming data:', error);
res.end('Error streaming data');
}
} finally {
if (!res.writableEnded) {
res.end();
}
}
}