|
Cloudflare Work 代码
该代码可用于在 Cloudflare Workers 上部署一个简单的 API,转发请求至 `https://multillm.ai-pro.org/api/openai-completion` 并返回响应。
## 代码
```javascript
addEventListener("fetch", event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
if (request.method === "POST" && new URL(request.url).pathname === "/v1/chat/completions") {
const url = 'https://multillm.ai-pro.org/api/openai-completion';
const headers = new Headers(request.headers);
headers.set('Content-Type', 'application/json');
const requestBody = await request.json();
const stream = requestBody.stream;
const newRequest = new Request(url, {
method: 'POST',
headers: headers,
body: JSON.stringify(requestBody)
});
try {
const response = await fetch(newRequest);
if (stream) {
const { readable, writable } = new TransformStream();
response.body.pipeTo(writable);
return new Response(readable, {
headers: response.headers
});
} else {
return new Response(response.body, {
status: response.status,
headers: response.headers
});
}
} catch (e) {
return new Response(JSON.stringify({ error: 'Unable to reach the backend API' }), { status: 502 });
}
} else {
return new Response('Not found', { status: 404 });
}
}
```
## 使用示例
```bash
curl --location 'https://ai-pro-free.aivvm.com/v1/chat/completions' \
--header 'Content-Type: application/json' \
--data '{
"model": "gpt-4-turbo",
"messages": [
{
"role": "user", "content": "鲁迅为什么打周树人"
}],
"stream": true
}'
```
## 来源
[https://ai-pro.org](https://ai-pro.org) |
|