Build and Deploy Your Own ChatGPT AI App in JavaScript | OpenAI, Machine Learning

Build and Deploy Your Own ChatGPT AI App in JavaScript | OpenAI, Machine Learning

Building a JavaScript AI Chat Application with OpenAI's GPT-3

In this video, the presenter will guide viewers through building a chat application using OpenAI's newest machine learning model. The application will have an elegant user interface and the ability to communicate with Advanced GPT-3 model API. Viewers will learn how to use all OpenAI APIs to build any website they can imagine.

Introduction

  • The presenter introduces the topic of building a chat application using OpenAI's newest machine learning model.
  • The course is beginner-friendly and uses in-demand technologies such as HTML, CSS, JavaScript, Node.js, and Prisma for code highlighting.
  • Viewers will learn how to set up a vanilla JavaScript project using Veet, use Node.js for the server-side, create responsive layouts with pure CSS, handle events with JavaScript, render markdown from strings, make API requests catch errors right clean code and much more.

Demo of AI Chat Application

  • The presenter gives a quick demo of the AI chat application that viewers will be building.
  • The AI can introduce itself by typing "write code that says hello world I'm codex in Python C rust Ruby and JavaScript."
  • The AI can suggest five advanced project ideas in React or brush up on viewers' JavaScript skills by explaining map filter and reduce methods in JS.
  • Codex can also help practice coding skills by providing coding challenges or exercises.

Getting Started

  • To get started building the chat application, open an empty folder in Visual Studio Code and call it "open Ai_codex".
  • Drag and drop the folder into Visual Studio Code.
  • Expand Visual Studio Code and open up the terminal by going to view then terminal.

Creating Front End/Client

  • To create the front end/client side of the application:
  • Install Vue.js using npm install -g vue-cli
  • Create a new Vue.js project using vue create client
  • Install axios using npm install axios
  • Create a new component called Chat.vue in the src/components folder
  • Add code to the Chat.vue component to create the chat interface

Creating Back End/Server

  • To create the back end/server side of the application:
  • Install Express.js using npm install express
  • Create a new file called server.js in the root directory of the project
  • Add code to server.js to set up an Express server and handle API requests

Connecting Front End and Back End

  • To connect the front end/client and back end/server:
  • Update Chat.vue to make API requests to the server using axios
  • Update server.js to handle incoming API requests from Chat.vue and communicate with OpenAI's GPT-3 model API.

Deploying Application

  • To deploy the application:
  • Sign up for a free Heroku account.
  • Install Heroku CLI.
  • Use Heroku CLI to log in, create a new app, and deploy your application.

Creating a Vanilla JavaScript Repository

In this section, the speaker explains how to create a vanilla JavaScript repository and provides assets that will be used throughout the project.

Steps to Create a Vanilla JavaScript Repository

  • To create a vanilla JavaScript repository, run npm create Veet at latest client dash dash template space vanilla.
  • Select "vanilla" as the framework.
  • The new client folder will be generated. CD into it and run npm install to install all necessary packages.
  • Download the zipped assets from the link provided in the description and paste them into the client folder.
  • Get the style.css file from GitHub gist and override it with our code.
  • Move favicon from assets folder to public folder and delete veet.svg.
  • Delete counter.js file since it is not needed.
  • Update index.html by rendering favicon.ico instead of veet.svg, changing title to "Codex Your Coding AI", adding link tag for internal stylesheet, creating div with ID of app, creating self-closing div with ID of chat_container, creating form with textarea element named prompt, adding button of type submit with self-closing image that has source equal to assets/send.svg.

Running the Application

In this section, we learn how to run our application on localhost.

Steps to Run Application

  • Ensure you are inside the client folder by cding into it.
  • Run npm run Dev which starts application on localhost 5173.
  • Click on localhost 5173 link while holding Ctrl key.

Importing Icons and Targeting HTML Elements

In this section, we learn how to import icons from our assets and target HTML elements manually using document.querySelector.

Importing Icons

  • We import the bot icon from um/assets/bot.svg using import bot from um/assets/bot.svg.
  • We also import the user icon from um/assets/user.svg using import user from um/assets/user.svg.

Targeting HTML Elements

  • We target the form element by calling const form = document.querySelector('#form').
  • Similarly, we target the chat container by calling const chatContainer = document.querySelector('#chat_container').

Creating a Loading Function

In this section, we create a function that will display a loading indicator while messages are being loaded.

Creating a Variable for Loading Interval

  • We create a variable called loadInterval in the outer scope.
  • This variable will be used later on to fill in with data.

Creating a Loader Function

  • We create a function called loader that takes an element as input and returns something.
  • The loader function simply returns three dots which will be displayed as a loading indicator.
  • The loader function sets the text content of the element to an empty string at first.
  • Then it sets an interval of 300 milliseconds to add another dot to the text content until it reaches three dots.
  • If it reaches three dots, it resets back to an empty string.

Implementing Typing Functionality

In this section, we implement typing functionality for AI's response so that it appears as if AI is thinking before giving out its response.

Creating Type Text Function

  • We create a function called typeText that takes an element and text as input parameters.
  • The function sets the index to 0 at first.
  • Then it creates an interval of 20 milliseconds for each letter in the text.
  • If the index is less than the length of the text, it adds a character to the element's inner HTML and increments the index.
  • If it reaches the end of the text, it clears the interval.

Generating Unique IDs

In this section, we create a function that generates unique IDs for every message to be able to map over them.

Creating Generate Unique ID Function

  • We create a function called generateUniqueID.
  • To generate a unique ID, we use current time and date which is always unique by calling const timestamp = Date.now().
  • To make it even more random, we also get another random number by calling const randomNumber = Math.random().

Creating a Chat Application with AI

In this section, the speaker explains how to create a chat application with AI. They start by creating the logic for the application and then move on to implementing functionality.

Creating Chat Stripe

  • For each message, prompt, and answer in the finished version of the application, a new stripe appears with a new color that goes from darker gray to lighter gray.
  • Each message has an icon indicating whether it is from us or AI.
  • To implement this feature, create a function called "chat stripe" that takes parameters such as whether it's AI speaking or not and passes them unique IDs.

Handle Submit Function

  • The handle submit function is what triggers getting an AI-generated response.
  • Create a function called "handle submit" that takes an event as its first parameter and is an async function.
  • Prevent default behavior of browser when submitting form using e.preventDefault().
  • Generate user's chat stripe by getting into the chat container into its inner HTML and then saying plus equal to chat stripe we pass in false as it's not the AI it's us then we pass the data dot get which is going to be a prompt.
  • Generate unique ID for bot's message using generate unique ID function created before.

Creating the Chat Container

In this section, we create a chat container and add functionality to it.

Filling up the Chat Container

  • We fill up the chat container as we load the actual message.
  • We provide a unique ID as the third parameter.

Fetching Newly Created Div

  • We fetch the newly created div using document.getElementById() and passing in the unique ID.
  • A new unique ID is created for every single message.

Turning on Loader

  • We turn on the loader by passing in the message div.

Handling Submit Functionality

  • We add an event listener for a submit event to call handleSubmit function.
  • We add an event listener for keyup to handle submitting everything by pressing enter key instead of clicking button.

Testing Our Progress So Far

In this section, we test our progress so far by reloading our page and typing "hello there" into our chat container.

Checking Our Progress

  • After reloading our page, we type "hello there" into our chat container.
  • The AI responds with dots added to its response.

Creating Backend Application

In this section, we create a backend application that makes a call to OpenAI's GPT API.

Setting Up Server Folder

  • Close script.js file and collapse client folder.
  • Create a new server folder.
  • Go to view and then terminal.
  • Press Ctrl C and then y to stop running it.
  • Use D dot dot to move directory up and then CD into server folder.

Installing Dependencies

  • Run npm init -y to generate a new package.json file inside of our server.
  • Install dependencies using npm install cors, dotenv, express, and nodemon.
  • All dependencies will be installed in the package.json file.

Getting OpenAI API Key

  • Go to openai.com/API and click "Get Started".
  • Create an account or continue with Google.
  • Click on your profile and then "View API Keys".
  • Create a new secret key and copy it back into our code.

Conclusion

In this section, we conclude by discussing the power of OpenAI's GPT3 model and how we will use it to create our Codex application.

Discussing OpenAI's GPT3 Model

  • OpenAI's GPT3 model performs a variety of natural language tasks such as text completion, image generation, code completion, etc.
  • We will use it to create our Codex application.

Guided Steps for Creating Codex Application

  • Follow along with the video tutorial for step-by-step guidance on creating our Codex application.

Setting up the Server

In this section, we will import necessary packages and set up the server.

Importing Packages

  • We import Express from Express.
  • We import everything as dot EnV from dot EnV to get data from that EnV file.
  • We import course which allows us to make cross-origin requests.
  • We import configuration and open AI API from open API.

Initializing the Server

  • To use the dot Envy variables, we need to say dot env.config.
  • Create an instance of configuration by saying const configuration = new configuration(API key: process.env.open AI_API_key).
  • Create an instance of OpenAI by saying const openAI = new OpenAI.API(configuration).
  • Initialize our express application by saying const app = express().

Setting Up Middlewares

  • Use app.use(cors()) to allow cross-origin requests and allow our server to be called from the front end.
  • Use app.use(express.json()) to pass JSON from the front end to the back end.

Creating Routes

In this section, we will create routes for our server.

Creating a Dummy Route

  • Create a dummy root route by saying app.get('/', async (req, res) => res.status(200).send('Hello World!')).

Creating a Post Route

  • Create an app.post route with the forward slash route.
  • This time, the post request is asynchronous and accepts a request and a response.
  • Wrap everything in a try-catch block.
  • Get the prompt by saying const prompt = req.body.prompt.

Using OpenAI API

In this section, we will use OpenAI API to generate responses.

Creating a Response

  • Create a response by saying const response = await openAI.createCompletion(model: 'text-davinci-003', prompt: $prompt, temperature: 0.5, max_tokens: 3000).
  • The model is text-davinci-003.
  • Pass in the prompt as $prompt.
  • Set the temperature to 0.5 which means that it will take fewer risks when generating output.
  • Set the max tokens to 3000 which means that it can give pretty high-quality output.

Creating a Response from the AI

In this section, we learn how to create a response from the AI and send it back to the front end.

Sending Response Back to Front End

  • Use res.status(200).send() inside an object to send the response back to the front end.
  • Access the data using response.data.choices.text.
  • In case of an error, use res.status(500) and log the error.

Starting Server and Listening for Requests

In this section, we learn how to start our server and listen for new requests.

Starting Server

  • Use app.listen(5000) to start listening for new requests.
  • Add a callback function with console.log statement to let us know that we started successfully.

Running Our Server

In this section, we learn how to run our server.

Updating Package.json File

  • Remove test script and add a new script called server with command nodemon server.
  • Add "type": "module" in package.json file.

Running Server

  • Run server using command npm run server.

Connecting Front End and Back End

In this section, we learn how to connect the front end and back end.

Fetching Data from Server

  • Use const response = await fetch('http://localhost:5000', method: 'POST', headers: 'Content-Type': 'application/json', body: JSON.stringify(prompt: data.get('prompt'))); to fetch data from server.
  • Access the response using response.json().

Displaying Response on Front End

  • Clear interval using clearInterval(loadInterval) and set message div inner HTML to empty string.
  • If response is ok, parse the data and pass it to type text function. Else, display error message.

Fixing CSS and Loading Issues

In this section, the speaker notices that there is no proper CSS being added to the profile. They also identify an issue with the loading feature where it only shows one dot instead of three.

Identifying CSS and Loading Issues

  • The speaker notices that there is no proper CSS being added to the profile due to a typo in the class name.
  • They identify an issue with the loading feature where it only shows one dot instead of three.

Fixing Authorization Issue

  • The server returns a 401 error code, indicating an authorization issue with the API key.
  • The speaker reloads their terminal and runs npm run start again to fix the issue.
  • They console log process.env.openAPIkey inside of the server to check if it's defined.
  • The API key should be kept inside of the server since it's only used there.

Resolving Text Parsing Error

  • A text parsing error occurs when trying to use a method on undefined text.
  • The speaker adds a console log for parsedData and confirms that it's not empty.
  • They find a typo in their code where they typed chartAdd instead of charCodeAt.
  • After fixing this typo, they are able to successfully parse text input.

Creating Routes Using React Router Dom V6

In this section, the speaker demonstrates how to create routes using React Router Dom V6.

Creating Routes Using React Router Dom V6

  • The speaker imports necessary components and creates routes for home, about, work, and contact pages using React Router Dom V6.

Explaining Code Functionality

In this section, the speaker explains the functionality of a code function that takes two parameters and creates an interval that runs every 20 milliseconds.

Explaining Code Functionality

  • The speaker pastes a lengthy piece of code into the input field to demonstrate how OpenAI can explain code.
  • They explain that the code is a function that takes two parameters and creates an interval that runs every 20 milliseconds.
  • The function checks if the index is less than the length of the text and adds characters to inner HTML accordingly.

Handling Form Submission

This section covers how to handle form submission, add user input to the chat container, fetch data from the server to get the bot's response, and add it to the chat container.

Adding User Input and Bot Response

  • Handle form submission
  • Add user input to chat container as a chat stripe
  • Fetch data from server for bot's response
  • Add bot's response to chat container as another stripe

Typing Out Bot Response

  • Type out bot's response using type text

Event Listener for Submit and Key Up Events

  • Add event listener for both submit and key up events of the form element

AI Tool Creation

This section covers creating an AI tool that can help with coding by explaining different concepts, giving exercises, testing knowledge, etc.

Creating an AI Tool

  • Create an AI tool
  • Explain different concepts
  • Give exercises
  • Test knowledge

Benefits of Creating an AI Tool

  • It can help with coding
  • It can explain different concepts
  • It can give exercises
  • It can test knowledge

Deploying Application

This section covers deploying the application by publishing code to GitHub and deploying the server side for free using render.com.

Publishing Code to GitHub

  • Create a new repository on GitHub
  • Publish code to GitHub
  • Push repository to GitHub

Deploying Server Side for Free

  • Use render.com to deploy server side for free
  • Add name, region, branch, and root directory
  • Deploy server

JavaScript Mastery Course and Deployment

In this section, the speaker talks about the courses available on jsmastery.pro and how to deploy a server and front-end using Versel.

JavaScript Mastery Course

  • Check out jsmastery.pro for three complete courses.
  • Choose the Complete Path to JavaScript Mastery course to learn JavaScript basics.
  • Choose Film Power course to dive into React.
  • Choose NFT Marketplace application course to learn about web3.

Server Deployment

  • Deploy server on localhost 5000 by clicking the link in the code.
  • Add environment variables by heading to environment and clicking add environment variable.
  • Name of variable is open AI underscore API key. Copy string from code and paste it in.
  • Wait for deployment progress before checking if website is live.

Front-end Deployment

  • Deploy front end using Versel by going to verscel.com and clicking Start deploying.
  • Click continue with GitHub, choose codex from list, give it a name, change root directory from dot slash to client.
  • Click deploy after recognizing Veet as client side builder.
  • Push updated server endpoint URL through terminal by git adding Dot get commit update the server URL then git push.
  • Check deployments once built before testing new URL call.

Learning JavaScript

In this section, the speaker provides a step-by-step guide on learning JavaScript.

Steps for Learning JavaScript

  1. Learn basics such as variables, data types, functions, and control flow.
  1. Practice writing code by creating small programs once you understand basics.
  1. Move onto advanced concepts such as object-oriented programming and asynchronous programming through online tutorials.
  1. Build projects
  1. Keep learning

Acknowledgements

In this section, the speaker expresses gratitude towards OpenAI for creating an API that allows developers to build great products and towards the viewers for watching the video and improving their development skills.

  • The speaker thanks OpenAI for creating an amazing API that enables developers to build great products.
  • The speaker expresses gratitude towards the viewers for watching the video and improving their development skills.

Faster Learning with jsmastery.pro

In this section, the speaker encourages viewers who want to learn even faster to check out jsmastery.pro.

  • The speaker recommends jsmastery.pro as a resource for those who want to learn even faster.

Conclusion

In this section, the speaker concludes the video by thanking the audience.

  • The speaker thanks the audience.
Video description

With an elegant user interface that resembles the ChatGPT app, communication with advanced GPT3 model API, and most importantly, the ability to ask the AI for help regarding JavaScript, React, or any other programming language, giving it code and translating it to another programming language, and much more, this CodeGPT is the best AI-based web application that you can currently find on YouTube. ⭐JS Mastery Pro - jsmastery.pro/youtube 📙 Limited-time FREE 218-page Ultimate Next.js eBook - https://resource.jsmastery.pro/nextjs-ebook 📚 Materials/References: GitHub Code (give it a star ⭐) - https://github.com/adrianhajdin/project_openai_codex Assets - https://drive.google.com/file/d/1RhtfgrDaO7zoHIJgTUOZKYGdzTFJpe7V/view?usp=share_link Styles - https://gist.github.com/adrianhajdin/2059ca74452a18d1560aac9499f58900 If you're experiencing 401, 429, or similar issues, here are some potential solutions: - Proper API key from OpenAI: It's possible that you are not using a valid API key from OpenAI. You can get an API key by visiting https://beta.openai.com/account/api-keys. - Free credits offered by OpenAI: If you are using the free credits offered by OpenAI to use their models, you can check your usage at https://beta.openai.com/account/usage. If you have used up your free credits, you can check the pricing and upgrade your account at https://openai.com/api/pricing/. - Proper server deployment: Make sure you use the deployed link from Render at https://render.com/. If you are unsure how to deploy the project, follow the steps mentioned in the video. - After successfully deploying the link, make sure to paste the link in the script file of the client and push it to GitHub. This will allow Vercel to detect and deploy the application properly. Also, please note that the server link used in the Codex repository shared on GitHub has used all of its credits, so it will throw a 429 error and will not work. You will need to use your own server link by deploying it on Render or using another hosting service. 🐛Got stuck? Get your bugs resolved immediately - https://discord.com/servers/javascript-mastery-programming-coding-community-710138849350647871 🐦 Follow us on Twitter: https://twitter.com/jsmasterypro 🖼️ Follow us on Instagram: https://instagram.com/javascriptmastery 💼 Business Inquiries: contact@jsmastery.pro Time Stamps 👇 00:00:00 Intro 00:02:29 Demo 00:04:54 Setup 00:11:26 ChatGPT Frontend 00:25:58 OpenAI Server 00:39:05 Connecting client and server 00:50:57 Deployment

Build and Deploy Your Own ChatGPT AI App in JavaScript | OpenAI, Machine Learning | YouTube Video Summary | Video Highlight