Write A ChatGPT Chatbot With Node.js

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
what's going on guys so in this video I'm going to show you step by step how to build an AI chat bot using node.js and the chat GPT API with the GPT 3.5 turbo model so you'll essentially have chat gbt running in your terminal and I'm going to give you a quick demo before we start so I have the program running and I can send any request I want to the API I'll just say hello and we get hello how can I assist you today and I'm just going to say what is the capital of Florida and it's going to give me back the capital of Florida is Tallahassee now the way that we're going to write this code is so it we save our chat history and we send that with each request that way we can have an ongoing conversation so I should be able to say what is the population and it should know what I'm talking about okay so as of 21 population of Tallahassee blah blah blah so it knows that I'm referencing what I just asked all right and then you can also ask for like code samples well I'll say how do I write a fetch request in JavaScript and it does take a second all right so if we look up here to make a fetch request in JavaScript you use the fetch function and it gives us an example and then it tells us what the example does and I could easily copy this and put it into my my own code and I could ask questions about it I could reference it in any way all right so I think it's pretty cool you can just have this open on your desktop and if you need information on whatever you can just go ahead and prompt it and then to exit we just type exit and there we go so now we're out of the program so that's what we're going to build and we're going to use the official open AI library for node.js that's what this is and then we're going to use a prep package called re-line sync which allows us to prompt the user so we're going to use this this question method and that's where that's how we're able to continuously type it and have a conversation with the bot all right we'll also be using dot EnV to store our API key and then colors to give you know give us colors in the console and then this is the final code this is the repository I'll have the link to this in the description and I'll probably use this for ongoing projects to show you some of the new features with the API such as function calls that's something that I want to get into we'll probably get into within the next month or so and I'll probably use this as a starting point all right so that's it let's go ahead and get into it thank you all right guys so I have an empty folder called chat gbt chat bot so just create that folder and open up your text editor whether it's vs code or whatever it is you're using as well as a terminal and the first thing we're going to do is in this folder we're going to run npm and knit which will initialize a package.json file and it's going to ask us some questions in the package name I'm actually going to call chat bot because if you do decide to use npm Link and run this as a global command that's going to be the command that you run and then the version we can use that description I'll say chat bot powered by chat chat GPT and then index that's fine that's fine keywords author of course you can put your own name here and let's say MIT for the license okay so now we have our package.json now as far as dependencies go let's say npm install and open AI is the the library we're going to be using to make our request to chat chat GPT and then I'm also going to install readline Dash sync that's going to allow us to interact with the user and ask a question and we can answer and so on basically give us that conversation uh that conversation flow and then we're going to install dot EnV so that we can store our AP API key in that and then I'm also going to install colors which is optional but it does look better when there's you know different colors so you can tell who the user is and who the bot is so let's go ahead and install those all right now I'm going to open up my package.json here and I'm going to just add a start script you can run it with you know node index or we can run npm start so in here let's say node and then index.js now another thing I'm going to do is add a type module because I want to use es modules instead of using the common JS syntax so let's go ahead and add a type and set that to module if you want to if you want to use common JS then you don't have to you don't have to do this all right so now that we've done that let's create our index.js which is our entry point and the first thing I want to do actually the first thing we have to do is is get our API key so let's go over to open Ai and let's see my I'm not logged in here so you just want to get your key whether you have a free account or a paid account you can go right here view API keys and you can create a new key I already have mine so I'm not going to create a new one but just go ahead and click create it'll show it and then you can copy it and then what you're going to do with that is come to your application and create in the root here a DOT EnV file and this is where your your global environment variables will go so I'm just going to grab my key real quick so I'm creating a variable called open AI API key and then I'm setting it here so just go ahead and do that make sure you use your own I'm going to delete this one after anyway and then save that so we're going to start by importing a few things from the openai library and those two things are going to be the configuration class and then open so uppercase o a uppercase Ai and then uppercase a pi I believe that's how it's formatted and the first thing we want to do actually we're going to also import dot EnV because we need to uh we need to get our API key and in order to use dot EnV we have to call the config method so let's say dot env.config okay now what we want to do is create a configuration object so we'll call this configuration and set that equal to a new uppercase C configuration object and then that's going to take in an object literal with the API key and we can get that with process dot EnV Dot and then open AI underscore API underscore key okay now we need to take this configuration object and we need to pass it into a new instance of this here so I'm going to create a variable called open AI all lowercase set that to new open AI API and we're going to pass in the configuration object that we just created so now we're ready to make requests with this object so I'm going to create a very actually you know what since we're using we're going to use a method on this object called create chat completion and that's a synchronous so we need to use the sync await so let's create an async function and we'll call it Main and then we're going to call that function down here and then what I'll do is create a variable called chat completion and let's set that to a weight and then take our open AI object and call create chat completion okay and that's going to take in a couple things so pass in an object with the model the model that we're using is gpt-3.5 Dash Turbo and then we're also going to pass in messages and this is going to be an array now we're only sending one message but you can send multiple messages so it still has to be an array even though it's just one message it's going to be an object and it's going to have two things a row and in this case the role is user because we're the one making the request the user when we get a response back the role of that response will be assistant because that's the API so we're the user and we want to send the content of whatever we want to say to basically to chat GPT so I'm just going to say what is the capital of Massachusetts I mean you can say anything whatever you want if you want to say something different but that's what that's the text that's the prompt that I'm sending to chat GPT through this API through this Library all right now let's see what that gives us so still within the main function but outside of that that chat completion variable let's just log chat completion and see what that gives us so we can run npm start so this is what it gives us a whole bunch of stuff up here that we don't really need to pay attention to but in this data object there's the ID there's the the model and then the choices is really what we want to pay attention to because that's that's where the answer to this is so let's say instead of just logging the whole object we'll say chat completion dot data and then dot choices which we can see is an array with one object in it so let's say choices and then zero to see what that one object is so let's clear that we'll run it again and now what we get back is an object with an index since we only sent one message this index will always be zero but if there are multiple messages sent then we'd have multiple indexes and the reason it finished is because it stopped because we we just asked a question it answered and then this message object as you can see has a role of assistant where the user this is the assistant and then the content says the capital of Massachusetts is Boston so what we really want is this content value in this message object so here let's say dot message and then dot content and then if we clear this up and run this again we should just see the answer there we go all right so this is this is how the API Works making a request and getting a response so now that we know that let's move on to create the actual chat bot where we can go on and have a conversation and what I want to do is actually put this stuff in a separate file because you might want to use this this open AI object somewhere else you might want to call either this method or another one because there's a bunch of different things different apis you can use for different things so what I'm going to do is create a folder called config and in config I'll create let's say open AI dot Js or we'll call it open dash AI dot JS and then I'm going to move this stuff see we're going to take this and move that into here and then all I want to do is export this variable so down here we'll say export default and remember I'm using the con the es module syntax if you're using common JS then you would do module dot exports but I'm going to do export default open AI and then come back here and we should then just be able to bring in we'll say import open AI from and then dot slash config slash open Ai and we have to do dot JS if we're using the import the es module syntax with node.js all right so let's just make sure that this still works I'm going to save it I'm going to run it and we get the same response good now as far as read line sync we need to bring that in so let's start by importing we'll say import read line sync and we're going to import that from uh from read line Dash sync and then we might as well bring in colors as well so we'll import colors from colors and again this is completely optional but I think it's nice to have different colors for the for the bot and for the user so as far as as how read line sync works I want to show you that I'm going to actually just get rid of all this right now because I just wanted to show you how that works but for the read line sync the way that that works let's create a variable called username and we'll set that to read line sync and then we're going to use the question method so if we say dot question and we'll say may I have your name and then right under that I'm going to console log and we'll say let's put some backticks in here we'll just say hello and then username okay so I'm going to run this file again and you'll see it says may I have your name and then it allows me to type so I'm going to put in Brad and it says hello Brad so that's basically how this is going to work this this readline sync we're going to be using this question method so we can get rid of that and the first thing I want to happen when we run this file and we call this function is for it to just greet us and say welcome to the chat bot program you can start chatting with the bot so let's do a console log and I want this to be green so what we can do is say colors and I want it to also be bold so I'm going to use bold and then dot green and then put my message in there and I'll say welcome we'll say welcome to the chat bot program and then let's copy that down and then this text here is going to say you can start chatting with the bot all right so let's run the file again and you can see that it's it's bold and green now it obviously it does doesn't do anything else yet because we have nothing else here so now what I want to do is instead of just having instead of just having the question right in the function like this because if I do that it's only going to ask it's only going to do it once right I want it to Key I want the conversation to keep going so I'm going to have a while loop and basically I'm just going to say while true so it'll just continuously Loop until we we break out of it and the way we're going to break out of it is by typing exit and I'll add that in a second but first we want to be able to get the input from the user so let's say const and we'll say user let's say user input and we're going to say read linesync Dot question okay and I want this to be yellow so I'm going to say colors dot yellow and this I'm not actually going to ask a question here I just wanted to say the word you before whatever we type so I'm going to say U h u colon space like that all right so if I were to save this and then run this again so it says welcome to the chat program you can start chatting and it says you colon and then I can type so I'll just say hello and hit enter now it's just going to keep doing that because we have it in a while loop right and we're not doing anything else with that input we're not doing anything with the input we're just we're typing it in we hit enter it runs again it says you again and lets us type but it's not actually doing anything so we can we can get out of this though by doing control or command C so that will clear us out for now but I want a way to get out without having to do that I want to be able to type exit so under that user input I'm actually going to open up a try catch and in the catch we'll just do a console let's do a we'll do a console.error and we can actually we can make the arrow red too so we'll do colors dot red and then whatever that error is okay now in the try we do one I'm just going to put a comment here and say call the API with the user input and we'll do that in a second but I want a way to escape out of the out of that Loop so let's say if so basically I want to check to see if the user types in exit so let's say if the user input and then we'll make it all lowercase so two lowercase if that is equal to exit then I want to return so let's see if that works so I'm going to run npm start and we'll say hello okay it doesn't nothing else happens but if I do exit then it gets me out of the program which is what I want so now let's implement the API and we're going to do it the same way that we did that I just showed you let's create a variable here I'll just call it completion and let's set that to a weight and we're going to use the open AI object and then the create chat completion method and then we're going to pass into that an object and remember we pass in the model which is going to be the GPT Dash 3.5 Dash turbo model and then we want to pass in messages which is going to be an array of objects that has a role which for us is going to be user and also has the content now in this case the content is going to be the user input okay so whatever we type in here when it says U and then we type it in that's going to get sent to the API now we got to get the the response from that so let's go right underneath that and let's say get get completion Text slash content so we'll say const and I'll call this completion content or completion text and let's set that to completion and remember how that's formatted we want to go into data which is an object that has a choices array and then that choices array has one item in it so we want to get that so we'll use the index of zero then we have a message object with content so that'll give us the direct text that we want all right and then what we'll do is come down here and let's see we're going to go under this if statement and we want to then console.l log the Bots answer so here we're going to say colors and I'm going to make this green so where where the user is yellow the bot is green so in here let's say bot colon space and then I'm just going to add on to this the completion text like that now when we exit I also want it to say say goodbye or whatever and we could man like we could hard code goodbye or some kind of message but if we put in exit it'll get sent to chat gbt and it will know that we're escaping and it will come up with its own message so we can actually put this in here as well and that should work you know how we expect so let's save this and let's go ahead and try it out so we'll run npm start it says U I'm going to say hello and the bot says hi there how can I assist you today I'm going to say what is the capital of Florida and there we go the capital of Florida is Tallahassee now we have an issue if you just want this to be uh you know a one-off thing where you just ask one question you get an answer that's fine but what if I say What is the population if I do that it's going to tell me that it doesn't know what the hell I'm talking about so to answer this question specific information is needed so basically it's not seeing the last answer and that's because when we send our data our messages we're only sending this so we basically have to have a way to store our conversation history and send that with our requests so let's do that next so I'm going to go ahead and hit exit type exit and you'll notice that it says goodbye if you have any more questions feel free to ask and that's because of this right here we added on the completion text when we type exit that completion text is this so we don't even have to manually put in goodbye or whatever so let's go ahead and come up to the top here right above the loop and let's initialize let's say const chat history and we're going to set that to just an empty array so let's say store conversation history okay and then what we're going to do is go see into the try and let's go above where we call the API and we're going to construct the messages by iterating over the history array so let's create a variable called messages and then we're going to set that to the chat history and we're going to use map so we're going to map over that and then say and then in here actually let's use parentheses because we're passing in a function and then we're passing in some brackets with the roll and the content and we just want this to be an object so I'm going to put another set of parentheses because I'm returning an object that has the role and the content all right so let's just put a comment here just to be clear on what this does so we'll say construct construct messages by iterating over the history all right now we want to add the latest user input to the message array so right under that let's say add latest user input so we'll say messages dot push because we're pushing onto the array an object with role which is going to be user and content which is going to be the user input now instead of passing that directly in here we're going to pass in messages okay now the last thing we want to do in order for this to work is update the chat history with the user input and assistance response so when it responds to us that also needs to be saved to the chat history so that's going to go at the very bottom right so under the console log here let's say update history with we'll say with user input and assistant response so we'll do that by taking chat history and we're going to push onto that we're going to push say user and then whatever the user input is and then I'll just copy that down and we're also going to push on the assistant and that's going to be the completion text and that should do it so now let's try it again I'm actually going to try it in the regular terminal here I would say npm start obviously you have to be in the folder so we'll say hello I'll say what is the capital of Florida Capital Florida is Tallahassee now say what is the population and there we go as of 2021 the estimated population is around 197 700. so what's happening is we're no longer just sending a single message to the API we're sending the entire history all right so that's going to be it for for what I want to do with this but there's so much more you could add to this you can make it so that your logs are saved in files you could call different apis you know integrate different apis for weather and and whatever else you could implement the new function calls which I'm actually going to make a video on soon and I'm probably going to use the same script and just add to it but yeah you could just keep this open on your desktop and if you have any questions about anything you could just ask and it'll even generate code samples let's say create a python script that makes a simple request to an API obviously we're dealing with the terminal so we are kind of limited in our output but it should work all right so there we go and you can see right here certainly here's an example of a simple python script and everything is in this block right here so we could just simply copy that and put it into our into our file and then it explains exactly what the code does you could even make it so that when you ask for a code you can have it create a file you create a python file with that code in it I mean there's so much you can do and you can edit the prompt what we're doing here is sending whatever we enter as the content but you could prefix this with something you know like speak to the user as if you were a travel agent or something like that you can prefix this with whatever you'd like we're just sending the straight input so it's pretty simple all right so that's it guys hopefully you enjoyed this little project and feel free to use it add on to it and I will see you next time
Info
Channel: Traversy Media
Views: 61,215
Rating: undefined out of 5
Keywords: chatgpt, chat gpt, node.js, chatgpt api, chatgpt node.js, open ai, open ai api, ai, chatbot, node.js chatbot, chatgpt chatbot
Id: 1YU83Lw58eo
Channel Id: undefined
Length: 28min 38sec (1718 seconds)
Published: Fri Jun 30 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.