banner
老言

老言博客

There's no such thing as a free lunch except web3.
twitter
telegram
github
discord server

Using Cloudflare Workers to solve the issue of being unable to access the OpenAI API.

As we all know, OpenAI's API website has been blocked, and users from mainland China cannot access it. Although we cannot directly use ChatGPT, we can access it through OpenAI's provided API key for local deployment. However, with the blocking of its API website, local deployment also requires some magic to use. In fact, we can solve the problem of OpenAI's API being blocked and enjoy using ChatGPT without relying on magic by using Cloudflare Workers.

a.png

Preparation

  1. Your own domain name (because Workers is also blocked)
  2. Transfer your domain's NS to Cloudflare

Transfer Domain to Cloudflare DNS

Log in to the Cloudflare homepage, find "Add Site," enter your domain name, and follow the steps. It usually takes about an hour to complete the resolution. Here it is relatively simple, and I will focus on deploying workers.

WX20230421-105607@2x.png

Start Deploying Workers

Go back to the homepage of the control panel, find "Workers" in the left sidebar, and go in. In the upper right corner, there is a "Create Service" button. Let's create a service here.

wk.jpg

Then give this service a name and click "Create Service" directly.

1111.jpg

Once created, it will automatically return to this service. Click "Quick Edit" in the upper right corner.

222.png

Then replace the code on the left editor with the following code:

const TELEGRAPH_URL = 'https://api.openai.com';

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

async function handleRequest(request) {
  const url = new URL(request.url);
  url.host = TELEGRAPH_URL.replace(/^https?:\/\//, '');

  const modifiedRequest = new Request(url.toString(), {
    headers: request.headers,
    method: request.method,
    body: request.body,
    redirect: 'follow'
  });

  const response = await fetch(modifiedRequest);
  const modifiedResponse = new Response(response.body, response);

  // Add response header to allow cross-origin access
  modifiedResponse.headers.set('Access-Control-Allow-Origin', '*');

  return modifiedResponse;
}

Then click "Save and Deploy" at the bottom!

But at this point, your workers cannot be accessed yet. We still need to bind the domain name that we just transferred to Cloudflare.
Go back to the project and find "Triggers"!

333.png

Then bind the domain name!

yuming.gif

Now you can happily use this domain name as the API interface domain name for OpenAI!

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.