佬友原帖(怎么都不能落下V佬):
1. 修改worker代码,其实就佬友代码基础上加了 /chat/completions 支持
addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
if (request.method === "OPTIONS") {
return new Response(null, {
headers: {
'Access-Control-Allow-Origin': '*',
"Access-Control-Allow-Headers": '*'
}, status: 204
})
}
const path = new URL(request.url).pathname
// 确保请求是 POST 请求,并且路径正确
if (request.method === "POST" && (path === "/v1/chat/completions" || path === '/chat/completions')) {
const url = 'https://multillm.ai-pro.org/api/openai-completion'; // 目标 API 地址
const headers = new Headers(request.headers);
// 添加或修改需要的 headers
headers.set('Content-Type', 'application/json');
// 获取请求的 body 并解析 JSON
const requestBody = await request.json();
const stream = requestBody.stream; // 获取 stream 参数
// 构造新的请求
const newRequest = new Request(url, {
method: 'POST',
headers: headers,
body: JSON.stringify(requestBody) // 使用修改后的 body
});
try {
// 向目标 API 发送请求并获取响应
const response = await fetch(newRequest);
const responseData = await response.json(); // 解析响应数据
// 如果 stream 参数为 true,则使用事件流格式发送响应
if (stream) {
return new Response(eventStream(responseData), {
headers: {
'Access-Control-Allow-Origin': '*',
"Access-Control-Allow-Headers": '*',
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
}
});
} else {
// 如果不是流式响应,则直接返回响应数据
return new Response(JSON.stringify(responseData), {
status: response.status,
headers: response.headers
});
}
} catch (e) {
// 如果请求失败,返回错误信息
return new Response(JSON.stringify({ error: 'Unable to reach the backend API' }), { status: 502 });
}
} else {
// 如果请求方法不是 POST 或路径不正确,返回错误
return new Response('Not found', { status: 404 });
}
}
function eventStream(data) {
// Simplified eventStream function that does not split the content into chunks
return `data: ${JSON.stringify({
id: data.id,
object: 'chat.completion.chunk',
created: data.created,
model: data.model,
system_fingerprint: data.system_fingerprint,
choices: [{
index: 0,
delta: { role: 'assistant', content: data.choices[0].message.content },
logprobs: null,
finish_reason: data.choices[0].finish_reason
}]
})}\n\n`;
}