forked from simonx1/claude-to-chatgpt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcloudflare-worker.js
322 lines (304 loc) · 8.67 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
const version = '0.4.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'; // Change this if you are using a self-hosted endpoint
const MAX_TOKENS = 9016; // Max tokens to sample, change it if you want to sample more tokens, maximum is 100000.
const role_map = {
system: 'Human',
user: 'Human',
assistant: 'Assistant',
};
const stop_reason_map = {
stop_sequence: 'stop',
max_tokens: 'length',
};
function convertMessagesToPrompt(messages) {
let prompt = '';
for (const message of messages) {
const role = message['role'];
const content = message['content'];
const transformed_role = role_map[role] || 'Human';
prompt += `\n\n${transformed_role}: ${content}`;
}
prompt += '\n\nAssistant: ';
return prompt;
}
function getAPIKey(headers) {
const authorization = headers.authorization;
if (authorization) {
return authorization.split(' ')[1] || CLAUDE_API_KEY;
}
return CLAUDE_API_KEY;
}
function claudeToChatGPTResponse(claudeResponse, stream = false) {
const completion = claudeResponse['completion'];
const timestamp = Math.floor(Date.now() / 1000);
const completionTokens = completion.split(' ').length;
const result = {
id: `chatcmpl-${timestamp}`,
created: timestamp,
model: 'gpt-3.5-turbo-0613',
usage: {
prompt_tokens: 0,
completion_tokens: completionTokens,
total_tokens: completionTokens,
},
choices: [
{
index: 0,
finish_reason: claudeResponse['stop_reason']
? stop_reason_map[claudeResponse['stop_reason']]
: null,
},
],
};
const message = {
role: 'assistant',
content: completion,
};
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) {
const reader = response.body.getReader();
const writer = writable.getWriter();
const encoder = new TextEncoder();
const decoder = new TextDecoder();
let buffer = '';
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.replace(/event: (completion|ping)\s*|\r/gi,'');
const substr = buffer.split('\n\n'), lastMsg = substr.length - 1;
0 !== substr[lastMsg].length ? buffer = substr[lastMsg] : buffer = '';
// if meet new line, then write the buffer to the writer
for (let i = 0; i < lastMsg; i++) {
try {
const decodedLine = JSON.parse(substr[i].slice(5));
const completion = decodedLine['completion'];
const stop_reason = decodedLine['stop_reason'];
let transformedLine = {};
if (stop_reason) {
transformedLine = claudeToChatGPTResponse(
{
completion: '',
stop_reason: stop_reason,
},
true
);
} else {
transformedLine = claudeToChatGPTResponse(
{
...decodedLine,
completion: completion,
},
true
);
}
writer.write(
encoder.encode(`data: ${JSON.stringify(transformedLine)}\n\n`)
);
} catch (e) {}
}
}
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_map[model] || 'claude-2';
// OpenAI API 转换为 Claude API
const prompt = convertMessagesToPrompt(messages);
const claudeRequestBody = {
prompt,
model: claudeModel,
temperature,
max_tokens_to_sample: MAX_TOKENS,
stop_sequences: stop,
stream,
};
const claudeResponse = await fetch(`${CLAUDE_BASE_URL}/v1/complete`, {
method: 'POST',
headers: {
accept: 'application/json',
'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 openAIResponseBody = claudeToChatGPTResponse(claudeResponseBody);
return new Response(JSON.stringify(openAIResponseBody), {
status: claudeResponse.status,
headers: { 'Content-Type': 'application/json' },
});
} else {
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,
},
];
const model_map = {
'gpt-3.5-turbo': 'claude-instant-1',
'gpt-3.5-turbo-0613': 'claude-instant-1',
'gpt-4': 'claude-2',
'gpt-4-0613': 'claude-2',
};