以下是合并后的完整代码,根据您的需求,当模型名称是指定的那些时,使用 Cohere 接口转换为 OpenAI 接口部分;当模型名称不是指定的那些时,使用 Workers AI 接口转换为 OpenAI 接口部分。
// 设置事件监听器
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request));
});
// 主请求处理函数
async function handleRequest(request) {
// 处理 CORS 预检请求
if (request.method === "OPTIONS") {
return new Response(null, {
headers: {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
}
});
}
// 解析请求体
let body;
try {
body = await request.json();
} catch (e) {
return new Response('Invalid JSON body', { status: 400, headers: {
'Access-Control-Allow-Origin': '*',
} });
}
// 确保存在 body.messages
if (!body.messages || !Array.isArray(body.messages)) {
return new Response('Invalid request body: messages field is required', { status: 400, headers: {
'Access-Control-Allow-Origin': '*',
} });
}
const model = body.model || '';
// 使用 Cohere 接口的模型列表
const cohereModels = [
'command-r',
'command-r-plus',
'command-r-08-2024',
'command-r-plus-08-2024',
'c4ai-aya-23-35b'
];
if (cohereModels.includes(model)) {
// 使用 Cohere 处理函数
return await cohereHandler(request, body);
} else {
// 使用 Workers AI 处理函数
return await workersAiHandler(request, body);
}
}
// Cohere 到 OpenAI 的处理函数
async function cohereHandler(request, body) {
const url = new URL(request.url);
const search = url.searchParams;
let data = { chat_history: [] };
try {
for (let i = 0; i < body.messages.length - 1; i++) {
data.chat_history.push({
"role": body.messages[i].role === "assistant" ? "CHATBOT" : body.messages[i].role.toUpperCase(),
"message": body.messages[i].content
});
}
data.message = body.messages[body.messages.length - 1].content;
} catch (e) {
return new Response(e.message);
}
data.stream = body.stream === true;
if ((body.model+"").indexOf("net-") === 0) data.connectors = [{"id": "web-search"}];
for (let i in body) {
if (!/^(model|messages|stream)/i.test(i)) data[i] = body[i];
}
if (/^(net-)?command/.test(body.model)) data.model = body.model.replace(/^net-/,"");
if (!data.model) data.model = search.get('model') || "command-r";
let prompt_tokens = 0;
let completion_tokens = 0;
body.messages.forEach(message => {
prompt_tokens += message.content.split(/\s+/).length;
});
const resp = await fetch('https://api.cohere.ai/v1/chat', {
method: "POST",
body: JSON.stringify(data),
headers: {
'content-type': 'application/json',
"Authorization": request.headers.get('authorization') || "bearer " + search.get('key')
}
});
if (resp.status !== 200) return resp;
const created = parseInt(Date.now() / 1000);
if (!data.stream) {
let ddd;
try {
ddd = await resp.json();
completion_tokens = ddd.text.split(/\s+/).length;
} catch (e) {
ddd = { error: e.message };
}
return new Response(JSON.stringify({
"id": "chatcmpl-QXlha2FBbmROaXhpZUFyZUF3ZXNvbWUK",
"object": "chat.completion",
"created": created,
"model": data.model,
"choices": [{
"index": 0, "message": {
"role": "assistant",
"content": ddd.text || ddd.error
}, "logprobs": null, "finish_reason": "stop"
}],
"usage": {
"prompt_tokens": prompt_tokens,
"completion_tokens": completion_tokens,
"total_tokens": prompt_tokens + completion_tokens
},
"system_fingerprint": null
}), {
headers: {
'Access-Control-Allow-Origin': '*',
"Access-Control-Allow-Headers": '*',
'Content-Type': 'application/json; charset=UTF-8'
},
status: resp.status
});
}
const { readable, writable } = new TransformStream();
const my_stream_writer = writable.getWriter();
(async () => {
const reader = resp.body.getReader();
let totalText = "";
const decoder = new TextDecoder('utf-8', {stream: true});
(async () => {
const encoder = new TextEncoder();
let isEnd = false;
while (!isEnd) {
await sleep(20);
const msgs = totalText.split('\n');
let index = 0;
for (; index < msgs.length; index++) {
try {
let msg = JSON.parse(msgs[index]);
if (msg.text) {
completion_tokens += msg.text.split(/\s+/).length;
const txt = JSON.stringify({
"id": "chatcmpl-QXlha2FBbmROaXhpZUFyZUF3ZXNvbWUK",
"object": "chat.completion.chunk",
"created": created,
"model": data.model,
"choices": [{
"index": 0,
"delta": {
"role": "assistant",
"content": msg.text
},
"finish_reason": null
}]
});
my_stream_writer.write(encoder.encode('data: ' + txt + '\n\n'));
}
if (msg.is_finished) {
await my_stream_writer.write(encoder.encode(`data: {"id":"chatcmpl-QXlha2FBbmROaXhpZUFyZUF3ZXNvbWUK","object":"chat.completion.chunk","created":${created},"model":"${data.model}","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}\n\n`));
await my_stream_writer.close();
isEnd = true;
}
} catch (e) {
break;
}
}
if (index < msgs.length) {
totalText = msgs[msgs.length - 1];
} else {
totalText = "";
}
}
})();
while (true) {
const { done, value } = await reader.read();
if (done) break;
totalText += decoder.decode(value, {stream: true});
}
})();
return new Response(readable, {
headers: {
'Access-Control-Allow-Origin': '*',
"Access-Control-Allow-Headers": '*',
'Content-Type': 'text/event-stream; charset=UTF-8'
},
status: resp.status
});
}
// Sleep 函数
function sleep(ms) {
return new Promise((r) => {
setTimeout(r, ms);
});
}
// Workers AI 到 OpenAI 的处理函数
async function workersAiHandler(request, body) {
try {
console.log('Received request:', request.url);
// 检查环境变量是否存在
if (typeof ACCOUNT_ID === 'undefined' || typeof API_TOKEN === 'undefined' || typeof AI_GATEWAY_ID === 'undefined') {
throw new Error('Missing required environment variables. Please check your Worker configuration.');
}
// 构建 AI Gateway 的基础 URL
const AI_GATEWAY_URL = `https://gateway.ai.cloudflare.com/v1/${ACCOUNT_ID}/${AI_GATEWAY_ID}/workers-ai`;
// 解析请求的 URL
const url = new URL(request.url);
const path = url.pathname;
// 确保模型名称以 '@cf/' 开头
if (body.model && !body.model.startsWith('@cf/')) {
body.model = '@cf/' + body.model;
}
console.log('Sending request to AI Gateway:', JSON.stringify(body));
// 将请求转发到 AI Gateway
const gatewayResponse = await fetch(`${AI_GATEWAY_URL}${path}`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${API_TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(body)
});
if (!gatewayResponse.ok) {
const errorText = await gatewayResponse.text();
console.error('AI Gateway Error:', errorText);
return new Response(JSON.stringify({
error: `AI Gateway responded with ${gatewayResponse.status}: ${errorText}`
}), {
status: gatewayResponse.status,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
}
});
}
// 检查是否为流式响应
const isStream = gatewayResponse.headers.get('content-type')?.includes('text/event-stream');
if (isStream) {
return new Response(gatewayResponse.body, {
headers: {
'Content-Type': 'text/event-stream',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
}
});
} else {
const gatewayResult = await gatewayResponse.json();
console.log('Received response from AI Gateway:', JSON.stringify(gatewayResult));
return new Response(JSON.stringify(gatewayResult), {
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
}
});
}
} catch (error) {
console.error('Unhandled error:', error);
return new Response(JSON.stringify({
error: true,
message: 'An unexpected error occurred',
details: error.message
}), {
status: 500,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
}
});
}
}
// 环境变量(请在您的 Worker 配置中设置)
const ACCOUNT_ID = "your_account_id";
const API_TOKEN = "your_api_token";
const AI_GATEWAY_ID = "your_ai_gateway_id";
请将 ACCOUNT_ID、API_TOKEN 和 AI_GATEWAY_ID 替换为您真实的 Cloudflare Workers AI 网关配置。
此合并后的代码会根据请求的模型名称,选择使用 Cohere 接口还是 Workers AI 接口来转换为 OpenAI 接口,并返回相应的响应。