DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for Build Your Serverless SQL Generator App Using GPT-3 and Next.js
Berkay
Berkay

Posted on • Originally published at raufsamestone.com

Build Your Serverless SQL Generator App Using GPT-3 and Next.js

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

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.


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

In this project, I use GPT-3 Engine and Ada model by the way.

Demo screen shot

Create your Open AI account

Go to Open AI and create a new account if you don’t have one. Go to API Keys from here 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

Create your app

Create an empty Next.js app:

yarn create-next-app
Enter fullscreen mode Exit fullscreen mode

Add openai package using yarn:

yarn add openai
Enter fullscreen mode Exit fullscreen mode

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

//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}` });
}
Enter fullscreen mode Exit fullscreen mode

Build POST function for the JSON responses:

//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])
Enter fullscreen mode Exit fullscreen mode

Your full index.js code should be like this:

//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>
  );
}
Enter fullscreen mode Exit fullscreen mode

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

yarn dev
Enter fullscreen mode Exit fullscreen mode

Please feel free to clone my repository here

Sources:

Top comments (0)

Want to rep DEV and be comfy at the same time?

Check out our classic DEV shirt β€” available in multiple colors.