將這個workers代碼轉換成pages代碼 const corsHeaders = { 'Access-Control-Allow-Origin': '*',…
- User
將這個workers代碼轉換成pages代碼
const corsHeaders = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type, Authorization', };
async function handleRequest(request) { if (!ACCOUNT_ID || !API_TOKEN || !AI_GATEWAY_ID) { return new Response('Missing required environment variables.', { status: 500 }); }
const AI_GATEWAY_URL =
https://gateway.ai.cloudflare.com/v1/${ACCOUNT_ID}/${AI_GATEWAY_ID}/workers-ai;if (request.method === "OPTIONS") { return new Response(null, { headers: corsHeaders }); }
if (request.method === 'GET') { return new Response('Workers AI Proxy is active. Please send a POST request.', { headers: { 'Content-Type': 'text/plain', ...corsHeaders } }); }
if (request.method !== 'POST') { return new Response('Not Found', { status: 404 }); }
try { const body = await request.json(); if (body.model && !body.model.startsWith('@cf/')) { body.model = '@cf/' + body.model; }
const gatewayResponse = await fetch(AI_GATEWAY_URL + new URL(request.url).pathname, { method: 'POST', headers: { 'Authorization': `Bearer ${API_TOKEN}`, 'Content-Type': 'application/json', }, body: JSON.stringify(body) }); if (!gatewayResponse.ok) { const errorText = await gatewayResponse.text(); return new Response(JSON.stringify({ error: `AI Gateway responded with ${gatewayResponse.status}: ${errorText}` }), { status: gatewayResponse.status, headers: { 'Content-Type': 'application/json', ...corsHeaders } }); } const isStream = gatewayResponse.headers.get('content-type')?.includes('text/event-stream'); return new Response(gatewayResponse.body, { headers: { 'Content-Type': isStream ? 'text/event-stream' : 'application/json', ...corsHeaders } });} catch (error) { return new Response(JSON.stringify({ error: true, message: 'An unexpected error occurred', details: error.message }), { status: 500, headers: { 'Content-Type': 'application/json', ...corsHeaders } }); } }
addEventListener('fetch', event => event.respondWith(handleRequest(event.request)));
參考以下pages代碼
export default { async fetch(req, env, ctx) { if (req.method === "OPTIONS") { return new Response("", { headers: { 'Access-Control-Allow-Origin': '', "Access-Control-Allow-Headers": '' }, status: 204 }) }
var search = (new URL(req.url)).searchParams var body = {} try { body = await req.json() } catch (e) { body = { "messages": [{ "role": "user", "content": search.get('q') || "hello" }], "temperature": 0.5, "presence_penalty": 0, "frequency_penalty": 0, "top_p": 1, stream: true } } var 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"; var prompt_tokens = 0; // 初始化prompt tokens数量 var completion_tokens = 0; // 初始化completion tokens数量 // 计算prompt tokens body.messages.forEach(message => { prompt_tokens += message.content.split(/\s+/).length; // 简单的按空格分割单词统计token数 }); var resp = await fetch('https://api.cohere.ai/v1/chat', { method: "POST", body: JSON.stringify(data), headers: { 'content-type': 'application/json', "Authorization": req.headers.get('authorization') || "bearer " + search.get('key') } }) if (resp.status !== 200) return resp; var created = parseInt(Date.now() / 1000); if (!data.stream) { try { var ddd = await resp.json() completion_tokens = ddd.text.split(/\s+/).length; // 计算completion tokens } 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 () => { var reader = resp.body.getReader(); var totalText = ""; const decoder = new TextDecoder('utf-8', {stream: true}); ; (async () => { var encoder = new TextEncoder(); var isEnd = false; while (!isEnd) { await sleep(20); var msgs = totalText.split('\n'); var index = 0; for (; index < msgs.length; index++) { try { let msg = JSON.parse(msgs[index]) if (msg.text) { completion_tokens += msg.text.split(/\s+/).length; // 计算completion tokens var 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 })}, };
export function onRequest(context) { return exports.fetch(context.request) }
function sleep(ms) { return new Promise((r) => { setTimeout(r, ms); }) }
- Assistant
以下是將您提供的 Workers 代碼轉換為 Cloudflare Pages 的 Functions 代碼。這個轉換遵循了 Cloudflare Pages Functions 的結構,並確保所有功能和邏輯保持一致。
// 在 Cloudflare Pages 的 `functions` 目錄下創建一個檔案,例如 `api/proxy.js` export default { async fetch(request, env, context) { const corsHeaders = { 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': 'POST, OPTIONS', 'Access-Control-Allow-Headers': 'Content-Type, Authorization', }; // 檢查所需的環境變量是否存在 const { ACCOUNT_ID, API_TOKEN, AI_GATEWAY_ID } = env; if (!ACCOUNT_ID || !API_TOKEN || !AI_GATEWAY_ID) { return new Response('Missing required environment variables.', { status: 500 }); } const AI_GATEWAY_URL = `https://gateway.ai.cloudflare.com/v1/${ACCOUNT_ID}/${AI_GATEWAY_ID}/workers-ai`; // 處理預檢請求 (CORS) if (request.method === "OPTIONS") { return new Response(null, { headers: corsHeaders, status: 204 }); } // 處理 GET 請求 if (request.method === 'GET') { return new Response('Pages AI Proxy is active. Please send a POST request.', { headers: { 'Content-Type': 'text/plain', ...corsHeaders }, status: 200, }); } // 只接受 POST 方法 if (request.method !== 'POST') { return new Response('Not Found', { status: 404, headers: corsHeaders }); } try { const body = await request.json(); // 調整 model 名稱 if (body.model && !body.model.startsWith('@cf/')) { body.model = '@cf/' + body.model; } // 轉發請求到 AI Gateway const gatewayResponse = await fetch(AI_GATEWAY_URL + new URL(request.url).pathname, { method: 'POST', headers: { 'Authorization': `Bearer ${API_TOKEN}`, 'Content-Type': 'application/json', }, body: JSON.stringify(body), }); // 處理 Gateway 的非 2xx 回應 if (!gatewayResponse.ok) { const errorText = await gatewayResponse.text(); return new Response(JSON.stringify({ error: `AI Gateway responded with ${gatewayResponse.status}: ${errorText}` }), { status: gatewayResponse.status, headers: { 'Content-Type': 'application/json', ...corsHeaders }, }); } // 判斷是否為串流回應 const isStream = gatewayResponse.headers.get('content-type')?.includes('text/event-stream'); // 回傳最終回應 return new Response(gatewayResponse.body, { headers: { 'Content-Type': isStream ? 'text/event-stream' : 'application/json', ...corsHeaders, }, }); } catch (error) { // 處理意外錯誤 return new Response(JSON.stringify({ error: true, message: 'An unexpected error occurred', details: error.message }), { status: 500, headers: { 'Content-Type': 'application/json', ...corsHeaders }, }); } }, };說明
-
文件結構與導出格式:
- Workers 使用
addEventListener來監聽fetch事件。 - Pages Functions 則使用
export default來導出一個包含fetch方法的對象。
- Workers 使用
-
環境變量的訪問:
- 在 Workers 中,環境變量可以直接訪問。
- 在 Pages Functions 中,環境變量通過
env參數訪問 (env.ACCOUNT_ID、env.API_TOKEN、env.AI_GATEWAY_ID)。
-
CORS 處理:
- 保持了原有的 CORS 頭部設置,確保跨域請求能夠正常處理。
- 對於預檢請求(
OPTIONS),返回 204 狀態碼。
-
HTTP 方法處理:
GET方法回傳一個提示訊息。- 只接受
POST方法,其他方法返回 404。
-
請求轉發與錯誤處理:
- 將接收到的
POST請求轉發到 AI Gateway。 - 處理非成功回應,並將錯誤信息返回給客戶端。
- 判斷回應是否為串流,並設置相應的
Content-Type。
- 將接收到的
-
異常處理:
- 捕捉所有異常,並返回 500 狀態碼以及錯誤訊息。
部署步驟
-
創建 Pages 專案:
- 確保您已經有一個 Cloudflare Pages 專案。
- 在專案的根目錄下創建一個
functions目錄(如果還沒有的話)。
-
添加函數文件:
- 將上述代碼保存為
api/proxy.js或其他合適的路徑和名稱。
- 將上述代碼保存為
-
設置環境變量:
- 在 Cloudflare Pages 的專案設置中,添加必要的環境變量
ACCOUNT_ID、API_TOKEN和AI_GATEWAY_ID。
- 在 Cloudflare Pages 的專案設置中,添加必要的環境變量
-
部署:
- 將更改推送到儲存庫,Cloudflare Pages 會自動部署新的 Functions。
測試
部署完成後,您可以通過以下方式測試 API:
-
GET 請求:
curl -X GET https://your-pages-site.com/api/proxy您應該會收到
"Pages AI Proxy is active. Please send a POST request."的回應。 -
POST 請求:
curl -X POST https://your-pages-site.com/api/proxy \ -H "Content-Type: application/json" \ -d '{"model":"your-model","other":"data"}'替換
"your-model"和其他數據為實際值,並檢查是否正確轉發和處理。
注意事項
-
串流處理:
- 原始 Workers 代碼中有對
text/event-stream的特殊處理。如果您的應用需要類似的串流處理,請確保 Pages Functions 支援此功能。根據 Cloudflare 的最新文檔,Pages Functions 支持串流回應,但建議進行測試以確認行為符合預期。
- 原始 Workers 代碼中有對
-
安全性:
- 確保您的 API Token 和其他敏感環境變量妥善保護,不應暴露給客戶端。
-
日誌與調試:
- 使用 Cloudflare 的日誌功能來監控和調試您的 Pages Functions,確保它們按預期運行。
如有進一步的需求或問題,請隨時告知!
-