How To Build Your Own ChatGPT API With Express_js
As AI is going so popular, I felt the need to explain how someone could build his own ChatGPT API using one of the prebuilt models provided by the ChatGPT inventor, OpenAI.
I will show you how to create your own chatGPT_API with a step-by-step guide using Express.js, and OpenAI dependencies.
So let us get started…
1| Navigate to OpenAI Platform website
firstly, we will navigate to OpenAI platform website?https://platform.openai.com, then from the OpenAI platform we will get two things: first is the api_key that we will use to get access to OpenAI API, second is the module we want to use, and just below, you’ll find how to get them.
1.Click on the profile and then click on View API keys.
2.Click on the Create new secret key and copy the API_Key. Then when you go back and go to examples and choose natural language to OpenAI API, then you'll find out what instances we need to build and which pre-built model we will use.
2| The server
Now we will build the server and for that we need to install some dependencies which are : first is?express?to build the rest API and?nodemon?to run the server each time we save,?CORS?for cross-origin requests and?openai?for the OpenAI instances and?dotenv?to get access to environment variables.
Installing dependencies :
领英推荐
Build the API :
I need to import the configuration and OpenAIApi from openai module, and then create the configuration and openai instances. Then we create the routes for our restAPI, and for that we will use Get and Post methods to create the completion using the pre_built model?text-divinci-003,?just as I explained above.
We need to make sure that the server is listening to our requests.
We need to add some modification to our package.json file, in scripts we add?start?script, and we also add?type?as module.
3 | Testing Your ChatGPT API
The last thing to do is to send some requests with get and post methods and see what will be the responses that will come back to us.
Get Method from the browser :
POST Method from Postman :
As you can see, we send a post request to the API we’ve just built and we get exactly the response we expected.
Finally, I hope you have enjoyed this post, and you could leave a comment or a question just below.