DEV Community

Othman Adi
Othman Adi

Posted on

Building a Web-based Chat Assistant with OpenAI Integration {PART.1}

Imagine this: A user-friendly, efficient, and interactive web-based chat assistant, capable of communicating with users, providing them with useful responses in a snap, all while looking sleek and modern. Sounds exciting, doesn't it? But wait, there's more! This chat assistant isn't just any regular botβ€”it's powered by OpenAI, an artificial intelligence model that can understand context, make decisions, and converse like a human.

In this step-by-step guide, we're going to merge the world of AI with intuitive web design. We'll cover everything from importing necessary components, designing a user interface with Bootstrap, animating with CSS, and finally, incorporating OpenAI's robust capabilities. But that's not all. We will wrap it all up by deploying our web application onto the web using Render, a fantastic platform that makes deployment as easy as pie.

Importing the Needed Bootstrap Components and Imports

Let's start with setting up our React application. We import the necessary Bootstrap components we will need, along with the standard React and CSS imports.

The Bootstrap components imported from "react-bootstrap" give us access to reusable components for easier layout and styling. We've imported the Container, Row, Col, Button, CloseButton, FormControl, InputGroup, and ListGroup for this project.

import './App.css';
import {
    Container,
    Row,
    Col,
    Button,
    CloseButton,
    FormControl,
    InputGroup,
    ListGroup,
} from "react-bootstrap";
import React, { useState } from "react";
Enter fullscreen mode Exit fullscreen mode

In index.js, we're importing Bootstrap's CSS file to apply the Bootstrap styles to our app:

import 'bootstrap/dist/css/bootstrap.min.css';
Enter fullscreen mode Exit fullscreen mode

Building the UI with Bootstrap

The application uses Bootstrap for its User Interface. We're using Bootstrap's grid system to structure our chat assistant. The grid system uses containers, rows, and columns to layout and align content.

The Container wraps the whole application and applies a padding around our application. Row and Col are used to create the grid system. This helps align our components in a clean, responsive way.

Adding the CSS

We've added custom CSS to provide animation and unique styles to our application.

/* This CSS applies a sliding effect for the chat container from its hidden state (at the bottom) to its original position */
.slide-up {
    animation: slide-up 0.5s forwards;
}

@keyframes slide-up {
    0% {
        transform: translateY(100%);
    }
    100% {
        transform: translateY(0);
    }
}

/* This CSS applies a fade-out effect to the chatbox when the closing button is clicked */
.fade-out {
    animation: fade-out 0.5s forwards;
}

@keyframes fade-out {
    0% {
        opacity: 1;
    }
    100% {
        opacity: 0;
    }
}
Enter fullscreen mode Exit fullscreen mode

Adding the UX with JavaScript

Now comes the interaction part. With the help of JavaScript, we add interactivity to our chat assistant. This is where the user can input their message, and the AI generates its response.

We set up state variables to hold our messages, the current message, and whether the chat window is visible. We also create functions for opening and closing the chat, and sending and submitting messages.

In our JSX, we've set up event handlers so that when you click the "Open Chat" button, the chat window will open. When you press Enter in the message box, your message will be sent, and when you click the close button, the chat window will close.

const [showChat, setShowChat] = useState(false); // Controls chat window visibility
const [isClosing, setIsClosing] = useState(false); // Controls chat window closing animation
const [messages, setMessages] = useState([]); // Stores the messages
const [currentMessage, setCurrentMessage] = useState(""); // Stores the current message
const messagesEndRef = React.useRef(null); // A reference to the end of the messages list

const closeChat = () => {
    setIsClosing(true);
    setTimeout(() => setShowChat(false), 500);
}

const openChat = () => {
    setIsClosing(false);
    setShowChat(true);
}
Enter fullscreen mode Exit fullscreen mode

Integrating OpenAI

To fetch an AI-generated response, we use the Fetch API to make a POST request to the OpenAI API. We send our user's message as part of the body in our request

. The AI processes this message and returns a response. This response is added to our list of messages.

The fetch function returns a promise. In the then block, we convert the response to JSON. If the response from the OpenAI API includes choices, we take the first choice, trim it, and add it as a new message to our list of messages.

fetch('<https://api.openai.com/v1/engines/text-davinci-003/completions>', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer YOUR-API-KEY'
    },
    body: JSON.stringify({
        "prompt": `The assistant is supposed to help you.\\nUser: ${userMessage}\\nAssistant:`,
        "max_tokens": 2000,
        "temperature": 0.3,
    })
})
.then(response => response.json())
.then(data => {
    if (data.choices && data.choices.length > 0) {
        const aiMessage = data.choices[0].text.trim();
        setMessages(prevMessages => [...prevMessages, `AI: ${aiMessage}`]);
    } else {
        console.error('No choices in response:', data);
    }
})
.catch(error => console.error('Error:', error));
Enter fullscreen mode Exit fullscreen mode

Deploying on Render

Finally, to make our chatbot accessible to the world, we use the platform "Render", which is similar to Heroku or Netlify. Render allows you to automatically build and deploy your web applications directly from your GitHub repository. The final step would be to push your code to a GitHub repository and set up automated deployment on Render.

Hopefully, this in-depth explanation helps clarify the process. Feel free to ask any further questions you might have about any part of the code or process!

Complete code gist

App.js

main Component page for Website chat assistant

index.js

bootstrap import

style.css

main component style

And that's a wrap, folks! I hope you found this tutorial insightful. But guess what? There's a whole lot more where this came from! If you'd like to tag along on this coding adventure, then let's make it official:

Follow me @othmanadi on GitHub for a peek at my projects and code snippets that didn't make it to the articles. If you're a fan of networking and professional growth, my LinkedIn is where it's at.

For the visual learners out there, I've got something special for you too. Check out my YouTube channel for tutorials, coding challenges, and more.

And, of course, for the behind-the-scenes stuff and some well-deserved leisure content, you can find me on Instagram.

Looking forward to connecting with all of you and continuing our coding journey together! Stay curious, keep learning, and happy coding!

Top comments (0)