avatarMircea Iosif

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

4759

Abstract

n>></span> <span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"sidebar"</span>></span> {/* Chat avatar */} <span class="hljs-tag"></<span class="hljs-name">div</span>></span>

<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"chatbox"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"chat-messages"</span>&gt;</span>
    {/* Message history */}  
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"chat-input"</span>&gt;</span>  
    {/* Text input */}
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

<span class="hljs-tag"></<span class="hljs-name">div</span>></span></span> )</pre></div><p id="d468">This splits our app into a <code>sidebar</code> and <code>chatbox</code> - prime real estate for a chat avatar and message history.</p><p id="eed3">Inside those containers, add UI elements like:</p><div id="0e08"><pre><span class="hljs-comment">// Sidebar</span> <img className=<span class="hljs-string">"avatar"</span> src=<span class="hljs-string">"bot.svg"</span>
/>

<span class="hljs-comment">// Messages</span> <span class="language-xml"><span class="hljs-tag"><<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"messages"</span>></span> { chatLog.map((msg, index) => ( <span class="hljs-tag"><<span class="hljs-name">ChatMessage</span> <span class="hljs-attr">key</span>=<span class="hljs-string">{index}</span> <span class="hljs-attr">message</span>=<span class="hljs-string">{msg}</span> /></span> )) } <span class="hljs-tag"></<span class="hljs-name">div</span>></span></span>

<span class="hljs-comment">// Input </span> <span class="language-xml"><span class="hljs-tag"><<span class="hljs-name">textarea</span> <span class="hljs-attr">rows</span>=<span class="hljs-string">{1}</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Type your message..."</span> /></span></span>

<span class="language-xml"><span class="hljs-tag"><<span class="hljs-name">button</span>></span> <span class="hljs-tag"><<span class="hljs-name">img</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"send.svg"</span> /></span>
<span class="hljs-tag"></<span class="hljs-name">button</span>></span></span></pre></div><p id="d6d7">Using standard React techniques like mapping over state to render a chat interface. For your custom chatbot avatar, drop in any <code>.svg</code> or image.</p><p id="ff50">Lastly, style your chatbot UI by adding a <code>styles</code> object:</p><div id="1cf9"><pre><span class="hljs-keyword">const</span> styles = { <span class="hljs-attr">app</span>: css<span class="language-css"> <span class="hljs-attribute">display</span>: flex; <span class="hljs-attribute">height</span>: <span class="hljs-number">100vh</span>; </span>, <span class="hljs-attr">sidebar</span>: css<span class="language-css"> <span class="hljs-attribute">width</span>: <span class="hljs-number">220px</span>; <span class="hljs-attribute">background</span>: <span class="hljs-number">#ddd</span>; </span> }</pre></div><p id="dbb8">And so on for colors, sizing, flex behavior — tailoring it to your needs.</p><p id="34bf">Our frontend design is nearly complete! We have a graphical chat interface rendering in React — the final piece is piping in the AI.</p><h1 id="77e4">Step 4 — Connect the OpenAI API</h1><p id="13df">Now for the fun part — integrating OpenAI’s natural language model into our chatbot.</p><p id="5434">First, install the <code>openai</code> npm package at the root of your Next.js app:</p><div id="dde1"><pre>npm install openai</pre></div><p id="09d8">Then in your index page, import the openai library:</p><div id="df9a"><pre><span class="hljs-keyword">import</span> { <span class="hljs-title class_">Configuration</span>, <span class="hljs-title class_">OpenAIApi</span> } <span class="hljs-keyword">from</span> <span class="hljs-string">'openai'</span></pre></div><p id="9845">Instantiate a configuration object with your secret key:</p><div id="2a9e"><pre><span class="hljs-type">const</span> configuration = <span class="hl

Options

js-keyword">new</span> <span class="hljs-built_in">Configuration</span>({ apiKey: process.env.OPENAI_API_KEY, });

<span class="hljs-type">const</span> openai = <span class="hljs-keyword">new</span> <span class="hljs-built_in">OpenAIApi</span>(configuration);</pre></div><p id="944f">This safely handles authentication. Now we can query GPT-3!</p><p id="deab">Inside your text input, add a submit handler:</p><div id="2edb"><pre><span class="hljs-tag"><<span class="hljs-name">textarea</span> <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Chat with me..."</span> <span class="hljs-attr">onKeyUp</span>=<span class="hljs-string">{handleSubmit}</span> /></span></pre></div><p id="effa">Where <code>handleSubmit</code> passes the text to OpenAI:</p><div id="7069"><pre>async <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleSubmit</span>(<span class="hljs-params">e</span>) </span>{

<span class="hljs-comment">// Prevent default form behavior</span> e.<span class="hljs-title function_ invoke__">preventDefault</span>()

<span class="hljs-comment">// Get user text input</span> <span class="hljs-keyword">const</span> <span class="hljs-variable constant_">userMessage</span> = e.target.value

<span class="hljs-comment">// Chatbot response</span> <span class="hljs-keyword">const</span> <span class="hljs-variable constant_">botResponse</span> = await openai.<span class="hljs-title function_ invoke__">createCompletion</span>({ <span class="hljs-attr">model</span>: <span class="hljs-string">"text-davinci-003"</span>, <span class="hljs-attr">prompt</span>: <span class="hljs-title function_ invoke__">generatePrompt</span>(userMessage), <span class="hljs-attr">temperature</span>: <span class="hljs-number">0.5</span>, })

<span class="hljs-comment">// Display response</span> <span class="hljs-title function_ invoke__">setChatLog</span>(prevState => ([ ...prevState, { <span class="hljs-attr">user</span>: userMessage, <span class="hljs-attr">bot</span>: botResponse.data.choices[<span class="hljs-number">0</span>].text } ]))

}</pre></div><p id="6697">Breaking this down:</p><ul><li>Prevent the form refresh with <code>preventDefault</code></li><li>Grab user’s chat input text</li><li>Send it to GPT-3 model <code>text-davinci-003</code></li><li>Pass text as prompt to complete</li><li>Store response + history in state</li></ul><p id="d0bd">Lastly, we need to construct the actual <code>prompt</code> that primes GPT-3's next reply:</p><div id="b1f9"><pre><span class="hljs-keyword">function</span> <span class="hljs-title function_">generatePrompt</span>(<span class="hljs-params">msg</span>) { <span class="hljs-keyword">let</span> prompt = chatLog.<span class="hljs-title function_">map</span>( <span class="hljs-function"><span class="hljs-params">chat</span> =></span> <span class="hljs-string"><span class="hljs-subst">${chat.user}</span>: <span class="hljs-subst">${chat.userText}</span>\nAI: <span class="hljs-subst">${chat.botText}</span></span> ).<span class="hljs-title function_">join</span>(<span class="hljs-string">'\n'</span>) + <span class="hljs-string">\nHuman: <span class="hljs-subst">${msg}</span>\nAI:</span>

<span class="hljs-keyword">return</span> prompt; }</pre></div><p id="f17b">This formats the user message history into an AI-ready prompt that elicits the next chained response.</p><p id="39d2">And we’re done! With just ~100 lines of code you now have your own functional AI chatbot web app using Next.js and OpenAI 💪</p><h1 id="9402">Step 5 — Deploy the Web App</h1><p id="8720">To share your conversational AI with the world, deploy the web app live with Vercel:</p><div id="c54e"><pre>npm install -g vercel vercel</pre></div><p id="bc28">Follow the prompts to connect your GitHub/GitLab repo and push to production!</p><p id="5ef0">Now anyone can access your AI assistant online. No server configuration needed thanks to serverless platforms.</p><h1 id="fbf1">Key Takeaways</h1><p id="8ccf">And that’s it! We:</p><ul><li>Built an AI chatbot web app in React</li><li>Utilized Next.js for SSR with Vercel</li><li>Integrated OpenAI’s GPT-3 for natural language</li><li>Created a prompt-based conversational agent</li></ul><p id="2b89">You now have the blueprint to assemble intelligent chatbots customizable for business use cases like customer service, ecommerce stores, virtual assistants, and more.</p><p id="de1a">The capabilities of AI chatbots are expanding rapidly. I hope you feel empowered to build your own after following this tutorial!</p><p id="55ed">Let me know what chat experiences you create in the comments below!</p></article></body>

Building a chatbot with GPT-3.5 and Next.js

Create a GPT-3 Chatbot Web App!

Photo from Freepik

Introduction

Chatbots powered by artificial intelligence are becoming increasingly popular, providing businesses and websites with automated conversational agents that can interact with customers.

In this tutorial, we’ll use React framework Next.js to build the frontend and integrate the powerful natural language AI of OpenAI’s GPT-3 to create our own chatbot web app.

Even with no prior experience in AI or chatbots, by following this tutorial step-by-step you’ll gain the ability to build interactive AIs from scratch.

Overview

Here’s a quick rundown of what we’ll cover:

  • Set up a Next.js app — Get our React environment & project started
  • Sign up for an OpenAI API key — Gain access to GPT-3
  • Create chatbot UI — Build a text chat interface using React
  • Connect OpenAI API — Link chat app frontend to backend AI
  • Deploy finished web app — Get our chatbot online!

Excited? The steps below will take you through building your own AI chatbot web app that can hold natural conversations on any topic you choose.

Step 1 — Set up a Next.js App

First, we’ll set up a Next.js project as the framework for our chatbot’s frontend. Next.js is perfect for this use case as it handles server-side rendering and static site generation right out of the box.

To start, make sure Node.js is installed on your development machine then run:

npm create next-app

This will scaffold a fresh Next.js project for you. Navigate into the new directory then run:

npm run dev

You should now see your hello world app running at http://localhost:3000!

With our React environment ready, let’s shift gears and get access to OpenAI’s GPT-3 model.

Step 2 — Sign Up for an OpenAI API Key

In order for our frontend to communicate with OpenAI’s backend servers, we’ll need an API key:

  1. Go to openai.com and sign up for a free account
  2. Once registered, click your profile picture > View API keys
  3. Copy the secret key — this identifies you to OpenAI

Treat your OpenAI secret key like a password and keep it secure. Now we’re ready to start integrating AI!

Step 3 — Create the Chatbot UI in React

With our Next.js foundation setup and API access granted, we can start constructing our chatbot’s user interface using React components.

Inside pages/index.js, delete the default contents and add:

// UI & layout 
import { useState } from 'react'  

export default function ChatPage() {

  const [chatLog, setChatLog] = useState([])  

  return (
    <div>
      {/* Chat interface */}
    </div>
  )
}

This initializes a chatLog hook to track conversational history and lays the groundwork for our chat UI.

Next, build out the graphical interface using standard React and flexbox:

return (
  <div className="app">
    <div className="sidebar">
      {/* Chat avatar */}
    </div>

    <div className="chatbox">
      <div className="chat-messages">
        {/* Message history */}  
      </div>

      <div className="chat-input">  
        {/* Text input */}
      </div>
    </div>
  </div>
)

This splits our app into a sidebar and chatbox - prime real estate for a chat avatar and message history.

Inside those containers, add UI elements like:

// Sidebar
<img 
  className="avatar"
  src="bot.svg"  
/>

// Messages
<div className="messages">
  {
    chatLog.map((msg, index) => (
      <ChatMessage 
        key={index} 
        message={msg} 
      />
    ))
  }
</div>

// Input 
<textarea 
  rows={1}
  placeholder="Type your message..." 
/>

<button>
  <img src="send.svg" />  
</button>

Using standard React techniques like mapping over state to render a chat interface. For your custom chatbot avatar, drop in any .svg or image.

Lastly, style your chatbot UI by adding a styles object:

const styles = {
  app: css`
    display: flex;
    height: 100vh;
  `,
  sidebar: css` 
    width: 220px; 
    background: #ddd; 
  ` 
}

And so on for colors, sizing, flex behavior — tailoring it to your needs.

Our frontend design is nearly complete! We have a graphical chat interface rendering in React — the final piece is piping in the AI.

Step 4 — Connect the OpenAI API

Now for the fun part — integrating OpenAI’s natural language model into our chatbot.

First, install the openai npm package at the root of your Next.js app:

npm install openai

Then in your index page, import the openai library:

import { Configuration, OpenAIApi } from 'openai'

Instantiate a configuration object with your secret key:

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

const openai = new OpenAIApi(configuration);

This safely handles authentication. Now we can query GPT-3!

Inside your text input, add a submit handler:

<textarea
  placeholder="Chat with me..."
  onKeyUp={handleSubmit} 
/>

Where handleSubmit passes the text to OpenAI:

async function handleSubmit(e) {

  // Prevent default form behavior
  e.preventDefault()   

  // Get user text input
  const userMessage = e.target.value

  // Chatbot response
  const botResponse = await openai.createCompletion({
    model: "text-davinci-003",
    prompt: generatePrompt(userMessage),
    temperature: 0.5,
  })

  // Display response
  setChatLog(prevState => ([
    ...prevState, 
    {
      user: userMessage,
      bot: botResponse.data.choices[0].text
    }
  ]))

}

Breaking this down:

  • Prevent the form refresh with preventDefault
  • Grab user’s chat input text
  • Send it to GPT-3 model text-davinci-003
  • Pass text as prompt to complete
  • Store response + history in state

Lastly, we need to construct the actual prompt that primes GPT-3's next reply:

function generatePrompt(msg) {
  let prompt = chatLog.map(
    chat => `${chat.user}: ${chat.userText}\nAI: ${chat.botText}`
  ).join('\n') + `\nHuman: ${msg}\nAI:`

  return prompt;
}

This formats the user message history into an AI-ready prompt that elicits the next chained response.

And we’re done! With just ~100 lines of code you now have your own functional AI chatbot web app using Next.js and OpenAI 💪

Step 5 — Deploy the Web App

To share your conversational AI with the world, deploy the web app live with Vercel:

npm install -g vercel 
vercel

Follow the prompts to connect your GitHub/GitLab repo and push to production!

Now anyone can access your AI assistant online. No server configuration needed thanks to serverless platforms.

Key Takeaways

And that’s it! We:

  • Built an AI chatbot web app in React
  • Utilized Next.js for SSR with Vercel
  • Integrated OpenAI’s GPT-3 for natural language
  • Created a prompt-based conversational agent

You now have the blueprint to assemble intelligent chatbots customizable for business use cases like customer service, ecommerce stores, virtual assistants, and more.

The capabilities of AI chatbots are expanding rapidly. I hope you feel empowered to build your own after following this tutorial!

Let me know what chat experiences you create in the comments below!

ChatGPT
Chatbots
Nextjs
Web Development
Apps
Recommended from ReadMedium