As we all know, the OpenAI API website has been blocked, and users from mainland China cannot access it. Although we cannot directly use ChatGPT, we can still access it through the local deployment method provided by OpenAI using the API key. However, with the blocking of its API website, local deployment also requires some magic to use. In fact, we can solve the problem of the OpenAI API being blocked and enjoy using ChatGPT without relying on magic by using Cloudflare Workers.
Preparation#
- Your own domain name (because Workers is also blocked)
- Transfer your domain's NS to Cloudflare
Transferring the Domain to Cloudflare DNS#
Log in to the Cloudflare homepage, find "Add Site", enter your domain name, and follow the steps to complete the setup. It usually takes about an hour for the resolution to be completed. This part is relatively simple, so I will focus on deploying workers.
Starting the Workers Deployment#
Go back to the homepage of the control panel, find "Workers" in the left sidebar, and go in. In the upper right corner, you will see "Create a Service". Let's create a service here.
Then, give this service a name and click "Create Service" directly.
Once created, you will be automatically redirected to this service. Click "Quick Edit" in the upper right corner.
Then, replace the code in 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!
However, at this point, your workers cannot be accessed yet. We still need to bind the domain name that you just transferred to Cloudflare.
Go back to the project and find "Triggers"!
Then, bind the domain name!
Now, you can happily use this domain name as the API interface domain for OpenAI!