-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathworker.js
More file actions
477 lines (413 loc) · 13.1 KB
/
worker.js
File metadata and controls
477 lines (413 loc) · 13.1 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
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
const MODEL_NAME = "@cf/openai/gpt-oss-120b";
const CORS_HEADERS = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "*",
"Access-Control-Allow-Methods": "POST, GET, OPTIONS",
};
function jsonResponse(payload, status = 200, extraHeaders = {}) {
return new Response(JSON.stringify(payload), {
status,
headers: {
"Content-Type": "application/json",
...CORS_HEADERS,
...extraHeaders,
},
});
}
function sseEvent(eventType, content) {
return `event: ${eventType}\ndata: ${JSON.stringify({ type: eventType, content })}\n\n`;
}
function parseArgumentsObject(value) {
if (value == null) return {};
if (typeof value === "object" && !Array.isArray(value)) return value;
if (typeof value !== "string") return {};
const raw = value.trim();
if (!raw) return {};
try {
const parsed = JSON.parse(raw);
return parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : {};
} catch {
return {};
}
}
function normalizeToolCall(candidate) {
if (!candidate || typeof candidate !== "object") return null;
let name = candidate.name || candidate.tool || candidate.function_name;
let argumentsValue = candidate.arguments ?? candidate.parameters ?? candidate.args;
const hasToolShape =
argumentsValue !== undefined ||
candidate.function != null ||
candidate.tool_calls != null ||
candidate.function_call != null ||
String(candidate.type || "").toLowerCase().includes("function");
if (candidate.function && typeof candidate.function === "object") {
name = name || candidate.function.name;
if (argumentsValue === undefined) {
argumentsValue =
candidate.function.arguments ??
candidate.function.parameters ??
candidate.function.args;
}
}
if (!hasToolShape) return null;
if (typeof name !== "string" || !name.trim()) return null;
return {
name: name.trim(),
parameters: parseArgumentsObject(argumentsValue),
};
}
function collectToolCalls(value, seen = new WeakSet(), depth = 0) {
if (depth > 6 || value == null) return [];
if (Array.isArray(value)) {
return value.flatMap((item) => collectToolCalls(item, seen, depth + 1));
}
if (typeof value !== "object") return [];
if (seen.has(value)) return [];
seen.add(value);
const calls = [];
const direct = normalizeToolCall(value);
if (direct) calls.push(direct);
if (Array.isArray(value.tool_calls)) {
for (const toolCall of value.tool_calls) {
const normalized = normalizeToolCall(toolCall);
if (normalized) calls.push(normalized);
}
}
if (value.function_call && typeof value.function_call === "object") {
const normalized = normalizeToolCall(value.function_call);
if (normalized) calls.push(normalized);
}
const nestedKeys = ["choices", "message", "delta", "output", "content", "response"];
for (const key of nestedKeys) {
if (value[key] !== undefined) {
calls.push(...collectToolCalls(value[key], seen, depth + 1));
}
}
return calls;
}
function extractToolCallPayload(value) {
const collected = collectToolCalls(value);
if (collected.length === 0) return "";
const uniqueBySig = new Map();
for (const call of collected) {
const sig = JSON.stringify(call);
if (!uniqueBySig.has(sig)) {
uniqueBySig.set(sig, call);
}
}
const calls = Array.from(uniqueBySig.values());
return JSON.stringify(calls.length === 1 ? calls[0] : calls);
}
function extractTextFromOutput(output) {
if (!Array.isArray(output)) return "";
const chunks = [];
for (const item of output) {
if (!item) continue;
if (item.type === "reasoning") continue;
if (typeof item.text === "string") {
chunks.push(item.text);
continue;
}
if (!Array.isArray(item.content)) continue;
for (const part of item.content) {
if (!part) continue;
if (part.type === "reasoning_text") continue;
if (typeof part.text === "string") {
chunks.push(part.text);
} else if (typeof part.output_text === "string") {
chunks.push(part.output_text);
} else if (typeof part.content === "string") {
chunks.push(part.content);
}
}
}
if (chunks.length > 0) {
return chunks.join("");
}
return "";
}
function extractContent(value) {
if (value == null) return "";
if (typeof value === "string") return value;
if (typeof value === "number" || typeof value === "boolean") return String(value);
if (Array.isArray(value)) {
return value.map((item) => extractContent(item)).join("");
}
if (typeof value !== "object") return "";
if (typeof value.response === "string") return value.response;
if (typeof value.output_text === "string") return value.output_text;
if (typeof value.text === "string") return value.text;
if (typeof value.content === "string") return value.content;
if (Array.isArray(value.choices)) {
const choiceChunks = [];
for (const choice of value.choices) {
if (!choice) continue;
const fromDelta = extractContent(choice.delta);
const fromMessage = extractContent(choice.message);
const fromText = extractContent(choice.text);
if (fromDelta) choiceChunks.push(fromDelta);
if (fromMessage) choiceChunks.push(fromMessage);
if (fromText) choiceChunks.push(fromText);
}
if (choiceChunks.length > 0) {
return choiceChunks.join("");
}
}
if (Array.isArray(value.content)) {
return value.content.map((part) => extractContent(part)).join("");
}
if (value.delta != null) {
return extractContent(value.delta);
}
if (value.message != null) {
return extractContent(value.message);
}
if (value.output != null) {
return extractTextFromOutput(value.output) || extractContent(value.output);
}
return "";
}
function parseIncomingPayload(body) {
if (!body || typeof body !== "object") {
throw new Error("JSON object body is required");
}
const aiInput = {};
const passthroughKeys = [
"lora",
"response_format",
"raw",
"stream",
"max_tokens",
"temperature",
"top_p",
"top_k",
"seed",
"repetition_penalty",
"frequency_penalty",
"presence_penalty",
"functions",
"tools",
"reasoning",
"instructions",
];
for (const key of passthroughKeys) {
if (body[key] !== undefined) {
aiInput[key] = body[key];
}
}
if (typeof body.prompt === "string" && body.prompt.trim()) {
aiInput.prompt = body.prompt;
} else if (Array.isArray(body.messages) && body.messages.length > 0) {
aiInput.messages = body.messages;
} else if (body.input !== undefined) {
aiInput.input = body.input;
} else if (Array.isArray(body.requests) && body.requests.length > 0) {
aiInput.requests = body.requests;
} else {
throw new Error("Provide one of: prompt, messages, input, or requests");
}
if (aiInput.stream === undefined) {
aiInput.stream = true;
}
if (aiInput.max_tokens === undefined) {
aiInput.max_tokens = 128000;
}
return aiInput;
}
function chunkTextForSSE(text, maxChunkLength = 80) {
const chunks = [];
if (!text) return chunks;
const words = text.split(/(\s+)/);
let current = "";
for (const part of words) {
if (!part) continue;
if ((current + part).length > maxChunkLength && current) {
chunks.push(current);
current = part;
} else {
current += part;
}
}
if (current) {
chunks.push(current);
}
return chunks;
}
async function streamTextResponseAsSSE(textResponse, writer, encoder) {
let emittedTokenCount = 0;
let buffer = "";
const emitPayloadLine = async (line) => {
const normalized = line.trim();
if (!normalized || normalized.startsWith("event:")) {
return;
}
const payload = normalized.startsWith("data:")
? normalized.slice(5).trim()
: normalized;
if (!payload || payload === "[DONE]" || payload === "DONE") {
return;
}
try {
const parsed = JSON.parse(payload);
const content = extractContent(parsed);
if (content) {
await writer.write(encoder.encode(sseEvent("token", content)));
emittedTokenCount += 1;
}
} catch {
await writer.write(encoder.encode(sseEvent("token", payload)));
emittedTokenCount += 1;
}
};
const flushBuffer = async () => {
if (!buffer.trim()) return;
await emitPayloadLine(buffer);
buffer = "";
};
if (textResponse && typeof textResponse.getReader === "function") {
const reader = textResponse.getReader();
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
if (!value) continue;
const chunk = value instanceof Uint8Array ? new TextDecoder().decode(value) : String(value);
buffer += chunk;
let newlineIdx = buffer.indexOf("\n");
while (newlineIdx !== -1) {
const line = buffer.slice(0, newlineIdx);
buffer = buffer.slice(newlineIdx + 1);
await emitPayloadLine(line);
newlineIdx = buffer.indexOf("\n");
}
}
await flushBuffer();
} finally {
reader.releaseLock();
}
return emittedTokenCount;
}
if (textResponse && typeof textResponse[Symbol.asyncIterator] === "function") {
for await (const chunk of textResponse) {
const content = extractContent(chunk);
if (content) {
await writer.write(encoder.encode(sseEvent("token", content)));
emittedTokenCount += 1;
}
}
return emittedTokenCount;
}
const content = extractContent(textResponse);
if (content) {
await writer.write(encoder.encode(sseEvent("token", content)));
emittedTokenCount += 1;
}
return emittedTokenCount;
}
function streamAsSSE(aiResponse, fallbackResolver) {
const { readable, writable } = new TransformStream();
const writer = writable.getWriter();
const encoder = new TextEncoder();
(async () => {
try {
let emitted = await streamTextResponseAsSSE(aiResponse, writer, encoder);
if (emitted === 0 && typeof fallbackResolver === "function") {
const fallbackResponse = await fallbackResolver();
const fallbackToolPayload = extractToolCallPayload(fallbackResponse);
if (fallbackToolPayload) {
await writer.write(encoder.encode(sseEvent("token", fallbackToolPayload)));
emitted += 1;
} else {
const fallbackText = extractContent(fallbackResponse);
for (const chunk of chunkTextForSSE(fallbackText)) {
await writer.write(encoder.encode(sseEvent("token", chunk)));
emitted += 1;
}
}
}
if (emitted === 0) {
await writer.write(encoder.encode(sseEvent("error", "No content generated")));
}
await writer.write(encoder.encode(sseEvent("done", "")));
} catch (error) {
await writer.write(
encoder.encode(
sseEvent("error", error instanceof Error ? error.message : "Unknown streaming error")
)
);
} finally {
await writer.close();
}
})();
return new Response(readable, {
headers: {
"content-type": "text/event-stream",
"Cache-Control": "no-cache",
Connection: "keep-alive",
...CORS_HEADERS,
},
});
}
/**
* Cloudflare Worker entry point
*/
export default {
async fetch(request, env) {
const url = new URL(request.url);
const { pathname } = url;
if (request.method === "OPTIONS") {
return new Response(null, { status: 204, headers: CORS_HEADERS });
}
if (request.method === "GET" && pathname === "/health") {
return jsonResponse({
status: "ok",
model_loaded: true,
model: MODEL_NAME,
});
}
if (request.method === "POST" && pathname === "/chat") {
try {
const body = await request.json();
const aiInput = parseIncomingPayload(body);
if (aiInput.stream) {
const streamInput = { ...aiInput, stream: true };
const streamResult = await env.AI.run(MODEL_NAME, streamInput);
return streamAsSSE(streamResult, async () => {
const fallbackInput = { ...aiInput, stream: false };
return env.AI.run(MODEL_NAME, fallbackInput);
});
}
const result = await env.AI.run(MODEL_NAME, { ...aiInput, stream: false });
return jsonResponse(result);
} catch (error) {
return jsonResponse(
{ error: error instanceof Error ? error.message : "Unknown error" },
400
);
}
}
if (request.method === "GET" && pathname === "/") {
try {
const response = await env.AI.run(MODEL_NAME, {
instructions: "You are a concise assistant. Reply in at most 60 words.",
input: "What is the origin of the phrase Hello, World?",
max_tokens: 80,
temperature: 0.2,
});
return jsonResponse({
model: MODEL_NAME,
answer: extractContent(response),
});
} catch (error) {
return jsonResponse(
{ error: error instanceof Error ? error.message : "Unknown error" },
500
);
}
}
return new Response("Not Found", {
status: 404,
headers: CORS_HEADERS,
});
},
};