Build Your Serverless SQL Generator App Using GPT-3 and Next.js
Tags: serverless, nextjs, gpt3, openai
Published: 2022-02-20 18:54:34

You can create a simple serverless app which is creating **SQL** queries from regular English syntax like this:

`Create a SQL request to find all users who visited from Chrome and Safari`

This can be very useful, especially for **BigQuery** SQL queries from **Google Analytics**.

If you want to jump to the GitHub repo, you can get it from [here](https://github.com/raufsamestone/open-ai-sql)

It’s really funny to create complex SQL queries like this. Before you begin, you have to know about your Open AI account billing methods from [here](https://openai.com/api/pricing/). 

<hr/>

Basically, multiple models, each with different capabilities and price points. **Ada** is the fastest model, while **Davinci** is the most powerful.

**Example token usage:** Prices are per 1,000 tokens. You can think of tokens as pieces of words, where 1,000 tokens are about 750 words. This paragraph is 35 tokens.

Your each model request calculated on your dashboard: 

![Open AI Dashboard](https://res.cloudinary.com/raufsamestone/image/upload/v1645378010/blog-contents/open-ai-sql/uxp0hifpftfcairhajjq.png) 

In this project, I use **[GPT-3 Engine and Ada model](https://beta.openai.com/docs/engines/gpt-3)** by the way.

![Demo screen shot](https://res.cloudinary.com/raufsamestone/image/upload/v1645376610/blog-contents/open-ai-sql/mde55vrtjxe8peqaclbf.png)

## Create your Open AI account

Go to [Open AI](http://beta.openai.com) and create a new account if you don’t have one. Go to API Keys from [here](https://beta.openai.com/account/api-keys) and make sure you have an API Key.

Do not share your API key with others, or expose it in the browser or other client-side code. So, I recommended using .env. 

![Your open-ai API key ](https://res.cloudinary.com/raufsamestone/image/upload/v1645376830/blog-contents/open-ai-sql/pgpa9dw24zwwcnq0qpgm.png)

## Create your app

Create an empty Next.js app:

```jsx
yarn create-next-app
```

Add **[openai](https://www.npmjs.com/package/openai)** package using yarn:

```jsx
yarn add openai
```

Then create a new API file for your CPT-3 requests: 

```jsx
//pages/api/ai.js

const { Configuration, OpenAIApi } = require("openai");

const configuration = new Configuration({
  apiKey: process.env.OPENAI_API_KEY,
});

const openai = new OpenAIApi(configuration);

export default async function handler(req, res) {
  let promptData = req.body.promptData;
  const response = await openai.createCompletion("text-ada-001", {
    prompt: promptData,
    temperature: 0.3,
    max_tokens: 60,
    top_p: 1,
    frequency_penalty: 0,
    presence_penalty: 0,
  });
  res.status(200).json({ data: `${response.data.choices[0].text}` });
}
```

Build POST function for the JSON responses:

```jsx
//pages/index.js

useEffect(() => {
    const fetchData = async () => {
      if (search) {
        setIsLoading(true);
        const res = await fetch(`/api/ai`, {
          body: JSON.stringify({
            promptData: search,
          }),
          headers: {
            "Content-Type": "application/json",
          },
          method: "POST",
        });
        const data = await res.json();
        setData(data);
        setIsLoading(false);
      }
    };
    fetchData();
  }, [search])
```

Your full index.js code should be like this: 

```jsx
//pages/index.js

import Head from "next/head";
import Image from "next/image";
import styles from "../styles/Home.module.css";
import { useState, useEffect } from "react";

export default function Home() {
  const [data, setData] = useState({ data: "" });
  const [query, setQuery] = useState();
  const [search, setSearch] = useState();
  const [isLoading, setIsLoading] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      if (search) {
        setIsLoading(true);
        const res = await fetch(`/api/ai`, {
          body: JSON.stringify({
            promptData: search,
          }),
          headers: {
            "Content-Type": "application/json",
          },
          method: "POST",
        });
        const data = await res.json();
        setData(data);
        setIsLoading(false);
      }
    };
    fetchData();
  }, [search]);

  const defaultPrompt =
    "Create a SQL request to find all users who visited from Chrome and Safari";

  return (
    <div className={styles.container}>
      <Head>
        <title>Create Next App</title>
        <meta name="description" content="Generated by create next app" />
        <link rel="icon" href="/favicon.ico" />
      </Head>

      <main className={styles.main}>
        <h1 className={styles.title}>
          Welcome to <br />{" "}
          <a href="https://openai.com/api/">Open AI SQL Generator</a>
        </h1>

        <div>
          <div>
            <h3>Your SQL request: </h3>
            <textarea
              type="text"
              cols="50"
              rows="3"
              placeholder={defaultPrompt}
              defaultValue={defaultPrompt}
              value={query}
              onChange={(event) => setQuery(event.target.value)}
            />
            <br />
            <button
              type="button"
              className={styles.button}
              onClick={() => setSearch(query)}
            >
              Generate
            </button>
            {isLoading ? (
              <div>Loading ...</div>
            ) : (
              <>
                <p className={styles.description}>Your SQL query 👇</p>
                <code className={styles.code}>{data.data} </code>
              </>
            )}
          </div>
        </div>
      </main>
    </div>
  );
}
```

Build your app, and start to create new SQL requests. ⚡️

```jsx
yarn dev
```

<hr/>

Please feel free to clone my repository [here](http://github.com/raufsamestone/open-ai-sql/)

Sources: 
- [https://harishgarg.com/writing/how-to-build-a-serverless-gpt-3-powered-using-nextjs-react/](https://harishgarg.com/writing/how-to-build-a-serverless-gpt-3-powered-using-nextjs-react/)
- [https://www.twilio.com/blog/getting-started-with-openai-s-gpt-3-in-node-js](https://www.twilio.com/blog/getting-started-with-openai-s-gpt-3-in-node-js)