DEV Community

Eduard Constantin
Eduard Constantin

Posted on • Edited on

5 1 1

[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.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

The best way to debug slow web pages cover image

The best way to debug slow web pages

Tools like Page Speed Insights and Google Lighthouse are great for providing advice for front end performance issues. But what these tools can’t do, is evaluate performance across your entire stack of distributed services and applications.

Watch video

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay