以下是把cohere 接口轉換成openai接口的代碼

addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request))
})

async function handleRequest(request) {
  if (request.method === "OPTIONS") {
    return new Response("", {
      headers: {
        'Access-Control-Allow-Origin': '*',
        "Access-Control-Allow-Headers": '*'
      }, 
      status: 204
    })
  }

  const url = new URL(request.url)
  const search = url.searchParams
  let body = {}
  try {
    body = await request.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 
    }
  }

  let 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";

  let prompt_tokens = 0;
  let completion_tokens = 0;

  body.messages.forEach(message => {
    prompt_tokens += message.content.split(/\s+/).length;
  });

  const resp = await fetch('https://api.cohere.ai/v1/chat', {
    method: "POST",
    body: JSON.stringify(data),
    headers: {
      'content-type': 'application/json',
      "Authorization": request.headers.get('authorization') || "bearer " + search.get('key')
    }
  })
  if (resp.status !== 200) return resp;

  const created = parseInt(Date.now() / 1000);

  if (!data.stream) {
    try {
      const ddd = await resp.json()
      completion_tokens = ddd.text.split(/\s+/).length;
    } 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 () => {
    const reader = resp.body.getReader();
    let totalText = "";
    const decoder = new TextDecoder('utf-8', {stream: true});

    (async () => {
      const encoder = new TextEncoder();
      let isEnd = false;

      while (!isEnd) {
        await sleep(20);
        const msgs = totalText.split('\n');
        let index = 0;
        for (; index < msgs.length; index++) {
          try {
            let msg = JSON.parse(msgs[index])
            if (msg.text) {
              completion_tokens += msg.text.split(/\s+/).length;
              const 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
  })
}

function sleep(ms) {
  return new Promise((r) => {
    setTimeout(r, ms);
  })
}

以下是把workers 接口轉換成openai接口的代碼

// 主要的请求处理函数
async function handleRequest(request) {
  try {
    console.log('Received request:', request.url);

    // 检查环境变量是否存在
    if (typeof ACCOUNT_ID === 'undefined' || typeof API_TOKEN === 'undefined' || typeof AI_GATEWAY_ID === 'undefined') {
      throw new Error('Missing required environment variables. Please check your Worker configuration.');
    }

    // 构建 AI Gateway 的基础 URL
    const AI_GATEWAY_URL = `https://gateway.ai.cloudflare.com/v1/${ACCOUNT_ID}/${AI_GATEWAY_ID}/workers-ai`;

    // 处理 CORS 预检请求
    if (request.method === "OPTIONS") {
      return handleCORS(request);
    }

    // 解析请求的 URL
    const url = new URL(request.url);
    const path = url.pathname;
    const method = request.method;

    // 处理 GET 请求（用于测试）
    if (method === 'GET') {
      return new Response('Workers AI Proxy is active. Please send a POST request.', {
        headers: {
          'Content-Type': 'text/plain',
          'Access-Control-Allow-Origin': '*',
        }
      });
    }

    // 仅处理 POST 请求
    if (method === 'POST') {
      const body = await request.json();

      // 确保模型名称以 '@cf/' 开头
      if (body.model && !body.model.startsWith('@cf/')) {
        body.model = '@cf/' + body.model;
      }

      console.log('Sending request to AI Gateway:', JSON.stringify(body));

      // 将请求转发到 AI Gateway
      const gatewayResponse = await fetch(`${AI_GATEWAY_URL}${path}`, {
        method: 'POST',
        headers: {
          'Authorization': `Bearer ${API_TOKEN}`,
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(body)
      });

      if (!gatewayResponse.ok) {
        const errorText = await gatewayResponse.text();
        console.error('AI Gateway Error:', errorText);
        return new Response(JSON.stringify({
          error: `AI Gateway responded with ${gatewayResponse.status}: ${errorText}`
        }), {
          status: gatewayResponse.status,
          headers: { 
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'POST, OPTIONS',
            'Access-Control-Allow-Headers': 'Content-Type, Authorization',
          }
        });
      }

      // 检查是否为流式响应
      const isStream = gatewayResponse.headers.get('content-type')?.includes('text/event-stream');

      if (isStream) {
        return new Response(gatewayResponse.body, {
          headers: {
            'Content-Type': 'text/event-stream',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'POST, OPTIONS',
            'Access-Control-Allow-Headers': 'Content-Type, Authorization',
          }
        });
      } else {
        const gatewayResult = await gatewayResponse.json();
        console.log('Received response from AI Gateway:', JSON.stringify(gatewayResult));
        return new Response(JSON.stringify(gatewayResult), {
          headers: { 
            'Content-Type': 'application/json',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'POST, OPTIONS',
            'Access-Control-Allow-Headers': 'Content-Type, Authorization',
          }
        });
      }
    }

    // 对于其他请求，返回 404
    return new Response('Not Found', { status: 404 });
  } catch (error) {
    console.error('Unhandled error:', error);
    return new Response(JSON.stringify({ 
      error: true,
      message: 'An unexpected error occurred',
      details: error.message
    }), {
      status: 500,
      headers: { 
        'Content-Type': 'application/json',
        'Access-Control-Allow-Origin': '*',
      }
    });
  }
}

// 处理 CORS 预检请求的函数
function handleCORS(request) {
  return new Response(null, {
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'POST, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization',
    }
  });
}

// 设置事件监听器
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request));
});

現在我想將兩個代碼合併，當遇到模型名稱是右側這些command-r,command-r-plus,command-r-08-2024,command-r-plus-08-2024,c4ai-aya-23-35b時，使用cohere接口到openai接口部分，當模型名稱不是我列出的那些時，使用workers接口轉換到openai接口部分，請幫我合併。並給我完整合併代碼。