將這個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);
  })
}