How to build an API with Functions and ChatGPT
Learn about the required process to create an API with Functions and ChatGPT and have the response shown on the Azion Preview Deployment.
Learn about the required process to create an API with Functions and ChatGPT and have the response shown on the Azion Preview Deployment.
To do so, you need to:
- Be registered on OpenAI.
- Have your OpenAI API key.
- Have your OpenAI organization ID.
To start creating your API, proceed as follows:
- Access Azion Console > Functions.
- Click on + Function.
- Choose a name for your function.
- In the Code tab, delete the placeholder function that is inside the code editor.
- Add your OpenAI API key and organization ID to the code as a comment:
- Copy and paste the following
const:
- Write the following prompt inside the function, right below the OpenAI credentials that were pasted on step 5:
- Select the prompt > click on it with the right button > choose ChatGPT: Generate. Wait a few seconds for it to complete the request.
The expected output should be similar to:
- Add the
handleRequestfunction, containing aswitch case, with aGETand aPOSTmethod:
- The
POSTmethod returns aJSONobject, that was generated by theChatGPT: Generateoption. - The
GETmethod returns the HTMLconstthat was declared on step 6.
- Copy and paste the
PreviewProviderfunction, responsible for simulating requests:
- Add the
addEventListenerfunction, which triggers the whole processing of the function:
- Click with the right button anywhere inside the code editor and select Format Document.
At this point, your function should look like this:
If you want, you can switch the method inside the PreviewProvider function and get a live preview of the responses on the Azion Preview Deployment.
- Click the Save button.
Now, the function is ready to be instantiated in an application. Check how to instantiate and execute the functions in your application and try it out.