-
-
Notifications
You must be signed in to change notification settings - Fork 149
/
cloudflare-worker.js
365 lines (349 loc) · 10.1 KB
/
cloudflare-worker.js
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
const version = '0.6.0';
addEventListener('fetch', (event) => {
event.respondWith(handleRequest(event.request));
});
const CLAUDE_API_KEY = ''; // Optional: default claude api key if you don't want to pass it in the request header
const CLAUDE_BASE_URL = 'https://api.anthropic.com/v1/messages'; // Changed to messages endpoint
const MAX_TOKENS = 4096;
function getAPIKey(headers) {
const authorization = headers.authorization;
if (authorization) {
return authorization.split(' ')[1] || CLAUDE_API_KEY;
}
return CLAUDE_API_KEY;
}
function formatStreamResponseJson(claudeResponse) {
switch (claudeResponse.type) {
case 'message_start':
return {
id: claudeResponse.message.id,
model: claudeResponse.message.model,
inputTokens: claudeResponse.message.usage.input_tokens,
};
case 'content_block_start':
case 'ping':
return null;
case 'content_block_delta':
return {
content: claudeResponse.delta.text,
};
case 'content_block_stop':
return null;
case 'message_delta':
return {
stopReason: claudeResponse.delta.stop_reason,
outputTokens: claudeResponse.usage.output_tokens,
};
case 'message_stop':
return null;
default:
return null;
}
}
function claudeToChatGPTResponse(claudeResponse, metaInfo, stream = false) {
const timestamp = Math.floor(Date.now() / 1000);
const completionTokens = metaInfo.outputTokens || 0;
const promptTokens = metaInfo.inputTokens || 0;
if (metaInfo.stopReason && stream) {
return {
id: metaInfo.id,
object: 'chat.completion.chunk',
created: timestamp,
model: metaInfo.model,
choices: [
{
index: 0,
delta: {},
logprobs: null,
finish_reason: 'stop',
},
],
usage: {
prompt_tokens: promptTokens,
completion_tokens: completionTokens,
total_tokens: promptTokens + completionTokens,
},
};
}
const content = claudeResponse.content;
const result = {
id: metaInfo.id || 'unknown',
created: timestamp,
model: metaInfo.model,
usage: {
prompt_tokens: promptTokens,
completion_tokens: completionTokens,
total_tokens: promptTokens + completionTokens,
},
choices: [
{
index: 0,
finish_reason: metaInfo.stopReason === 'end_turn' ? 'stop' : null,
},
],
};
const message = {
role: 'assistant',
content: content || '',
};
if (!stream) {
result.object = 'chat.completion';
result.choices[0].message = message;
} else {
result.object = 'chat.completion.chunk';
result.choices[0].delta = message;
}
return result;
}
async function streamJsonResponseBodies(response, writable, model) {
const reader = response.body.getReader();
const writer = writable.getWriter();
const encoder = new TextEncoder();
const decoder = new TextDecoder();
let buffer = '';
const metaInfo = {
model,
};
while (true) {
const { done, value } = await reader.read();
if (done) {
writer.write(encoder.encode('data: [DONE]'));
break;
}
const currentText = decoder.decode(value, { stream: true }); // stream: true is important here,fix the bug of incomplete line
buffer += currentText;
console.log('🚀 ~ streamJsonResponseBodies ~ buffer:', buffer);
const regex = /event:\s*.*?\s*\ndata:\s*(.*?)(?=\n\n|\s*$)/gs;
let match;
while ((match = regex.exec(buffer)) !== null) {
try {
const decodedLine = JSON.parse(match[1].trim());
const formatedChunk = formatStreamResponseJson(decodedLine);
if (formatedChunk === null) {
continue;
}
metaInfo.id = formatedChunk.id ?? metaInfo.id;
metaInfo.model = formatedChunk.model ?? metaInfo.model;
metaInfo.inputTokens =
formatedChunk.inputTokens ?? metaInfo.inputTokens;
metaInfo.outputTokens =
formatedChunk.outputTokens ?? metaInfo.outputTokens;
metaInfo.stopReason = formatedChunk.stopReason ?? metaInfo.stopReason;
const transformedLine = claudeToChatGPTResponse(
formatedChunk,
metaInfo,
true
);
writer.write(
encoder.encode(`data: ${JSON.stringify(transformedLine)}\n\n`)
);
} catch (e) {}
// 从buffer中移除已处理的部分
buffer = buffer.slice(match.index + match[0].length);
}
}
await writer.close();
}
async function handleRequest(request) {
if (request.method === 'GET') {
const path = new URL(request.url).pathname;
if (path === '/v1/models') {
return new Response(
JSON.stringify({
object: 'list',
data: models_list,
}),
{
status: 200,
headers: { 'Content-Type': 'application/json' },
}
);
}
return new Response('Not Found', { status: 404 });
} else if (request.method === 'OPTIONS') {
return handleOPTIONS();
} else if (request.method === 'POST') {
const headers = Object.fromEntries(request.headers);
const apiKey = getAPIKey(headers);
if (!apiKey) {
return new Response('Not Allowed', {
status: 403,
});
}
const requestBody = await request.json();
const { model, messages, temperature, stop, stream } = requestBody;
const claudeModel = model;
// Convert OpenAI API request to Claude API request
const systemMessage = messages.find((message) => message.role === 'system');
const claudeRequestBody = {
model: claudeModel,
messages: messages.filter((message) => message.role !== 'system'),
temperature,
max_tokens: MAX_TOKENS,
stop_sequences: stop,
system: systemMessage?.content,
stream,
};
const claudeResponse = await fetch(CLAUDE_BASE_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-api-key': apiKey,
'anthropic-version': '2023-06-01',
},
body: JSON.stringify(claudeRequestBody),
});
if (!stream) {
const claudeResponseBody = await claudeResponse.json();
const formatedResult = {
id: claudeResponseBody.id,
model: claudeResponseBody.model,
inputTokens: claudeResponseBody.usage.input_tokens,
outputTokens: claudeResponseBody.usage.output_tokens,
stopReason: claudeResponseBody.stop_reason,
};
const openAIResponseBody = claudeToChatGPTResponse(
{ content: claudeResponseBody.content[0].text },
formatedResult
);
if (openAIResponseBody === null) {
return new Response('Error processing Claude response', {
status: 500,
});
}
return new Response(JSON.stringify(openAIResponseBody), {
status: claudeResponse.status,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Credentials': 'true',
},
});
} else {
// Implement streaming logic here
const { readable, writable } = new TransformStream();
streamJsonResponseBodies(claudeResponse, writable);
return new Response(readable, {
headers: {
'Content-Type': 'text/event-stream',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Credentials': 'true',
},
});
}
} else {
return new Response('Method not allowed', { status: 405 });
}
}
function handleOPTIONS() {
return new Response(null, {
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': '*',
'Access-Control-Allow-Headers': '*',
'Access-Control-Allow-Credentials': 'true',
},
});
}
const models_list = [
{
id: 'gpt-3.5-turbo',
object: 'model',
created: 1677610602,
owned_by: 'openai',
permission: [
{
id: 'modelperm-YO9wdQnaovI4GD1HLV59M0AV',
object: 'model_permission',
created: 1683753011,
allow_create_engine: false,
allow_sampling: true,
allow_logprobs: true,
allow_search_indices: false,
allow_view: true,
allow_fine_tuning: false,
organization: '*',
group: null,
is_blocking: false,
},
],
root: 'gpt-3.5-turbo',
parent: null,
},
{
id: 'gpt-3.5-turbo-0613',
object: 'model',
created: 1677649963,
owned_by: 'openai',
permission: [
{
id: 'modelperm-tsdKKNwiNtHfnKWWTkKChjoo',
object: 'model_permission',
created: 1683753015,
allow_create_engine: false,
allow_sampling: true,
allow_logprobs: true,
allow_search_indices: false,
allow_view: true,
allow_fine_tuning: false,
organization: '*',
group: null,
is_blocking: false,
},
],
root: 'gpt-3.5-turbo-0613',
parent: null,
},
{
id: 'gpt-4',
object: 'model',
created: 1678604602,
owned_by: 'openai',
permission: [
{
id: 'modelperm-nqKDpzYoZMlqbIltZojY48n9',
object: 'model_permission',
created: 1683768705,
allow_create_engine: false,
allow_sampling: false,
allow_logprobs: false,
allow_search_indices: false,
allow_view: false,
allow_fine_tuning: false,
organization: '*',
group: null,
is_blocking: false,
},
],
root: 'gpt-4',
parent: null,
},
{
id: 'gpt-4-0613',
object: 'model',
created: 1678604601,
owned_by: 'openai',
permission: [
{
id: 'modelperm-PGbNkIIZZLRipow1uFL0LCvV',
object: 'model_permission',
created: 1683768678,
allow_create_engine: false,
allow_sampling: false,
allow_logprobs: false,
allow_search_indices: false,
allow_view: false,
allow_fine_tuning: false,
organization: '*',
group: null,
is_blocking: false,
},
],
root: 'gpt-4-0613',
parent: null,
},
];