banner
老言

老言博客

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

Solving the issue of being unable to access OpenAI's API with Cloudflare Workers

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.

a.png

Preparation#

  1. Your own domain name (because Workers is also blocked)
  2. 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.

WX20230421-105607@2x.png

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.

wk.jpg

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

1111.jpg

Once created, you will be automatically redirected to this service. Click "Quick Edit" in the upper right corner.

222.png

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"!

333.png

Then, bind the domain name!

yuming.gif

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

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