How to Use OpenAI ChatGPT API… In SQL | by Dario Radečić | Apr, 2024

Editor
2 Min Read


Could SQL be your next choice for building AI applications?

Photo by Resource Database on Unsplash

When it comes to ChatGPT and using the OpenAI API, SQL isn’t the first language that comes to mind. But it should — it’s the language of data, and the fact you can send HTTP requests from SQL opens up a world of possibilities.

Today’s article will show you how to write a custom Oracle SQL function using PL/SQL. It will take in a question string and return formatted JSON. Oracle’s dbms_cloud package will do most of the heavy lifting, as it’s responsible for making API calls. If you’re using a different database vendor, I’m sure you can find an alternative package and function set to do the job.

Let’s begin by covering the prerequisites you’ll need to follow along.

As mentioned in the introduction, I’m using Oracle SQL running on an always free instance of Autonomous Database 21c provisioned on Oracle Cloud. If you want to follow along, register for a free account, provision a database instance, and download a connection wallet.

The other thing you’ll need is the OpenAI API key. The linked article shows you how to get one in minutes.

And that’s pretty much it! Let’s get down to business.

The chat completion example we’ll implement in SQL is quite straightforward. OpenAI’s official documentation shows you what goes into making a request to their API:

Image 1 — OpenAI requests documentation (image by author)

Since there’s no third-party library for OpenAI in SQL (like in Python), you’ll have to opt for a more manual approach. The theory is — if you can run the above curl command and get a response back, you can do the same in SQL.

The easiest way to demonstrate this is through Postman. Populate the headers and JSON body of a new POST request to https://api.openai.com/v1/chat/completions and you should get a response similar to mine:

Share this Article
Please enter CoinGecko Free Api Key to get this plugin works.