使用Cloudflare worker构建chatgpt api专用接口

api.openai.com被墙了,无法直接通过chatgpt的api来实现对话功能。
怎么办呢?我的办法是让chatgpt自救。

基于api的chatbox,openai translator等应用都需要通过api.openai.com进行会话。

既然现在被墙了,就要找个替代方案了。和chatgpt友好交流后,它给了我一个使用cloudflare的方案和下面一段代码

先登录cloudflare,进入worker,创建新的service

把下面这段代码粘贴在service里并保存部署。

下面是全部代码:

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

async function handleRequest(request) {
  const url = new URL(request.url);
  const fetchAPI = request.url.replace(url.host, "api.openai.com");

  // CORS 参数
  const corsHeaders = {
    "Access-Control-Allow-Origin": "*",
    "Access-Control-Allow-Methods": "OPTIONS, POST",
    "Access-Control-Allow-Headers": "*"
  };

  // 处理 OPTIONS 请求
  if (request.method === "OPTIONS") {
    return new Response(null, { headers: corsHeaders });
  }

  // 验证是否携带了有效的 Authorization 参数
  const authKey = request.headers.get("Authorization");
  if (!authKey) {
    return new Response("Not allowed", { status: 403 });
  }

  // 构造请求参数
  let body;
  if (request.method === "POST") {
    body = await request.json();
  }
  const payload = {
    method: request.method,
    headers: {
      "Content-Type": "application/json",
      Authorization: authKey
    },
    body: typeof body === "object" ? JSON.stringify(body) : "{}"
  };
  if (["HEAD", "GET"].includes(request.method)) {
    delete payload.body;
  }

  // 发送请求到 OpenAI API
  const response = await fetch(fetchAPI, payload);

  // 处理响应结果
  if (body && body.stream !== true) {
    const results = await response.json();
    return new Response(JSON.stringify(results), {
      status: response.status,
      headers: {
        "Content-Type": "application/json",
        ...corsHeaders
      }
    });
  } else {
    return new Response(response.body, {
      status: response.status,
      statusText: response.statusText,
      headers: {
        ...response.headers,
        ...corsHeaders
      }
    });
  }
}

最后,再为这个worker服务添加一个个人域名就可以了。

留下评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注