DEV Community

Eduard Constantin
Eduard Constantin

Posted on • Updated on

[Storybook GPT] Connect to OpenAI API in NextJS 13

In this post, I will show you how to connect to the amazing OpenAI API using NextJS 13, the latest and greatest version of the React framework that powers millions of websites.

To use OpenAI's chat API, first we need to get an API key from here, you need to sign up for an account and request access to the API.
Then we'll need to install the OpenAI package in our Next.js 13 project. You can do this by running the following command in the terminal:

npm install openai
Enter fullscreen mode Exit fullscreen mode

Once the package is installed, we can use it to create a function that can receive a React component and return a Storybook story by passing the component through OpenAI API.

import { Configuration, OpenAIApi } from "openai";

export async function convertComponent(component) {
const prompt = `Convert this React component into a Storybook component:\n\n${component}`;
  const configuration = new Configuration({
    apiKey: process.env.OPENAI_API_KEY,
  });
  const openai = new OpenAIApi(configuration);
  const response = await openai.createCompletion({
    model: "text-davinci-003",
    prompt: prompt,
    max_tokens: 1024,
    temperature: 0.7,
    top_p: 1.0,
    frequency_penalty: 1,
    presence_penalty: 0.5,
    stop: ['\n\n'],
  });

  return response.data.choices[0].text.trim();
}
Enter fullscreen mode Exit fullscreen mode

With the provided prompt, if we send this component as an input:

import React from 'react';
function MyButton() {
  function handleClick() {
    alert('You clicked me!');
  }

  return (
    <button onClick={handleClick}>
      Click me
    </button>
  );
}
export default MyButton;
Enter fullscreen mode Exit fullscreen mode

This is the response it returns:

// MyButton.stories.js
import React from 'react';
import { action } from '@storybook/addon-actions';
import MyButton from './MyButton';

export default {
  title: 'MyButton',
  component: MyButton,
};

export const Default = () => <MyButton />;

export const WithText = () => <MyButton>Click me</MyButton>;

export const WithAction = () => (
  <MyButton onClick={action('button-click')}>
    Click me
  </MyButton>
);
Enter fullscreen mode Exit fullscreen mode

Pretty amazing I'd say. Now, with the converter function set up, we can create a simple user interface for users to interact with the API. The interface will allow the users to enter their own API key and the React component code in two separate text inputs. Then, it will display the generated Storybook story in a disabled text area.

Top comments (0)