使用以下代碼 部屬在workers pages 會傳回 "error": "AI Gateway responded with 400:…
- User
使用以下代碼 部屬在workers pages 會傳回 "error": "AI Gateway responded with 400: {"success":false,"errors":[{"code":7003,"message":"Could not route to \/accounts\/ACCOUNT_ID\/ai\/v1\/chat\/completions, perhaps your object identifier is invalid?"},{"code":7000,"message":"No route for that URI"}],"messages":[],"result":null},請給出完整修改代碼
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 }, }); }}, };
- Assistant