Google Gemini AI Course for Beginners

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
dive into the cuttingedge realm of artificial intelligence with this comprehensive video course on Google's AI model Gemini Guided by Ana Kubo this course will teach you how to use the Gemini API and how to build an AI chat bot powered by gini if you are new to the world of AI this is the perfect video for you my name is Ana kuo and I a software developer as well as course creator here on free Camp as well as on my own channel in this video course we will be learning about AI as developers through the use of Google's AI model Gemini now as some of you may or may not know we can use AI chatbots in order to ask questions about the world generate images or even have full-on chat using information we fed in before but how does this even happen and how can I build my own AI chatbot well this is exactly what we'll be covering today in fact here is a full list of what we will be looking at throughout this video we will start off with this introduction and then move on to to have a look at what Gemini actually is Follow by looking at AI so that we actually understand it next we will look at llms or large language models followed by getting our API key in Pre for making out our final project we will then quickly cover tokenization before moving on to some of the models that we can access with Gemini and then of course we're going to build out our ay code buddy so what are we waiting for let's do it what is Gemini in the least amount of words Gemini is a series of multimodal generative AI models developed by Google Gemini models can accept text and image in prompts depending on what model variation you choose and output text responses what this means is that we can feed in text prompts such as what day of the week is it today and we can receive responses back such as it is Wednesday and not only that we can feed in images as prompts too so I can feed in a picture of a cat in a hat and we can ask what is in the photo and we should receive back a text response pretty cool right we can do this by interacting with the Gemini app previously known as bod we can do so pretty easily by typing the prompt here and we can then even see a history of all our previous chats so here I am writing a prompt in text and receiving the text back as well as continuing a whole chat that takes into account the previous messages I sent or here I am uploading images and asking questions about them or if you actually want to use this core technology to build your own apps you can also interact with a Gemini API by interacting with the API or application programming interface we can do exactly what the Gemini app UI does so for example putting in text inputs and receiving a text input back by using the Gemini pro model and the generate content method from it and we can also use the generate content method from the gemino provision model in order to prompt with text and or images and receive text back as well as build multi-turn conversations with the Gemini pro model using the generate content method as well as some extra configuration we will also look at creating embedding using the embedding 001 model with the embed content method but for that we need to understand what embeddings actually are first we will go into these models and the methods they come with and how to use them individually later on just for now know that these are the most popular at the time of recording and a few more do exist but we will not be covering them in this particular course okay so we got it to recap Gemini is a series of multimodal generative AI models developed by Google that you can interact with via an API or via the app of the same name of Gemini what is ai ai or artificial intelligence is the simulation of human intelligent processes by machines I say simulation as artificial intelligence is not sense it at least not yet anyways meaning it cannot think for itself as much as it may seem it does often when we say AI we most of the time are referring to a firm called machine learning machine learning works by using large amounts of training data that is then analyzed for correlations and patterns these patterns are then used to predict outcomes based on the training data provided so for example if I was to feed this training data basically summarizing what each paragraph is about so for example that we are feing data saying that a paragraph that looks like this should be categorized as Finance the second paragraph should be put in the category of fashion and so on with some code we should be able to train our AI model to correctly guess what future paragraphs are about and that's it so if we were to get a paragraph that says Bad Bunny had some black adeda sneakers that were from 4 2022 this was a great something something then thanks to our training data the AI model should guess with some percentage of accuracy that the topic for this paragraph should be fashion of course that is a super super basic example and we would need way more data than these five paragraphs right here but you get the idea as of now rapidly improving generative AI techniques can create realistic text responses and even images music and other media thanks to the huge amounts of training data and talented developers working on it today large language models large language models or llms are machine learning models sometimes referred to as AI model models that can comprehend and generate human language text so in fact we already had a look at a super super basic example of one it was when we fed training data into our AI model so that it could accurately predict what category a paragraph would belong to at their most basic level large language models are like sophisticated autocomplete applications just like guessing a category that a paragraph can belong to we can train models to take an input of Tex text such as you can lead a horse to water and have the llm output text statistically return but you can't make it drink as the following text suggestion based on patterns learned from the training data in fact you can use this basic property of llms for various applications you can use it to generate poetry short stories metors blog posts and other creative copy or convert structured data to free form text or even extract and summarize information from Fe form text generate code translate or build a chatbot like we we doing today so now some of you may ask is there a Randomness in llm responses or are they deterministic this your answer is yes to both when you prompt an nlm its text response is generated in two stages in the first stage the llm processes the input prompt and generates a probability distribution over Poss I tokens or words that are likely to come next for example if you prompt with the input text the dog jumped over there dot dot dot the llm will produce an array of probable next words so as you can see here the word fence has the highest probability score as opposed to ledge or blanket this process is deterministic an llm will produce the same distribution every time it's input the same prompt text in the second stage the llm converts these distributions into actual text responses through one of several decoding strategies a simple decoding strategy might select the most likely token at every time step this process would always be deterministic however you could inste choose to generate response by randomly sampling over the distribution returned by the model this process would be random you can control the degree of Randomness allowed in this decoding process by setting the temp temperature a temperature of zero means only the most likely tokens are selected and there's no Randomness conversely a high temperature injects a high degree of Randomness into the tokens selected by the model leading to more unexpected surprising model responses okay so now that we've understood that let's work on actually getting our apiq to work with Gemini just like most apis the Gemini API uses API key key is for authentication in this section I'm going to show you how to get your own API key for when it comes to communicating with the API from the applications that we will be building today remember make sure not to share or upload your API key anywhere public if you do someone might take it use it in their own project and use up all of your free tokens or rack up a huge credit card bill if you have a card attached this also includes exposing in any client side code by this I mean building an app without a backend and deploying it onto the internet the code in this case will be visible simply by inspecting it like so someone will then be able to go and take it from here for their own use to use this key safely requests must be rooted through your own backend server where your API key can be securely loaded from environment variable or Key Management Service okay so let's do it let's get our API key okay so first we're just going to start off on this URL currently at at the time of recording this is what it is and we're going to choose to build with Gemini we just take us here and then we're going to click on AI google.de now you might be required to sign in or because I am using Google Chrome I could just go ahead and get API key in Google AI studio so I'm just going to click here and taada once you are here so essentially you can write prompts here if you would like such as what day is it and hit enter and the chat will work you can actually select the model from a drop down here and you can also select the temperature the temperature is something that we covered in the previous section and essentially as we know allows us to be more deterministic with our answers so that is something that you can set you can be more deterministic or less Det DET terministic okay so we get the response back great now to get your API key all you're going to do is click here so I'm going to go ahead and select that and we're going to create an API key so go ahead and select create API key and I'm just going to search for generative language client it's actually the only Google Cloud project that we have and go ahead and select create API key in existing project so now we have our API key make sure to copy this and of course keep it safe and do not share it or put it in any code that can be visible to anyone on the internet okay cool that is just because you could use up all your credits or if you have a credit card attached it could of course take up all your pennies from your credit card amazing and of course you can delete API keys and create new ones if you want so for example example if one is compromised and that's it I hope that was easy to understand great now that we have our API Keys let's get to looking at the available models to our disposal after learning about tokenization when using long proms it might be useful to count tokens before sending any content to the model if you want to be specific about it you can use one of the models at our disposal it is the gemino prob model we touched on previously along with the count tokens method you can get it with this car command I will show you how to do this in a bit however as a general rule of thumb for Gemini models a token is equivalent to about four characters 100 tokens are about 60 to 80 English words okay so let's do it okay so all I'm going to do in order to get a template for the code is head over to the rest API and then I'm going to just go to count tokens and this will tell me the method that we're going to use from the model the Gemini pro model so we're going to use this in order to write our own curl command so let's go ahead and get with our terminal I'm going to write curl just like so as the header content type we're going to have application Json and then as the content we're going to have this object which takes an array of another object and then the text that we want to essentially find out how many tokens make it up so as the text I'm just going to write let's go ahead and go up there let's do write a story about a magic backpack and then we're going to have to put in our API keys so making sure that this is the same so generative language googleapis.com slv1 beta models Gemini Pro and then the method count tokens and then we're going to put in our API key here that we just saved so go ahead and just whack in your own like so and hit enter and amazing so we now know that this string this string takes up eight tokens great and that's it models as we know we can interact with the Gemini API by interacted with the API we get access to all the Gemini generative AI models and their methods including these for right here as a recap we can have text only input and use the generate content method to generate a response from the Gemini pro model given an input message and we can also use the generate content method from the gerini Pro Vision model in order to prompt with text and or images and receive text back as well as build multi-turn conversations with the gemo pro model using the generate content method as well as some extra configuration we will also look at creating embeddings using the embedding Z 01 model with the embed content method but for that we need to understand what embeddings actually are first so let's have a look at how these four work for this cause we'll be using node.js make sure to have node.js version 18 and above installed and npm installed first off we would need to initialize the generative AI model we would need to do this for all the scenarios in order for this to work you will need to install the SDK package right here okay so here is the code we will be using to initialize the generative model if you want to have a look at it this time we're going to be going to node.js as we're going to start building out a nodejs app so let's go ahead and do it we're going to initialize the generative model after of course installing this package so let's get up our code editors of choice I'm just going to create a new project I'm just going to call this scratch pad okay so just like that and create it so here we are has an empty project and I'm just going to get out my terminal so I'm going to click here making sure that we are in the scratch pad and I'm just going to initialize this so npm in it for this to essentially spin up a package Json file with the correct configuration so let's go ahead and choose package name default version one description I'm going to keep empty I'm just going to literally go through all of these and choose the defaults is this okay and yes and my package Json file should be in here now great now let's go ahead and install that dependency so I'm just going to go back in here let's copy that and I'm going to do npm install Google generative AI so please be aware of the version of this package that we will be using for this tutorial if you are using this in the future and something isn't working it could be down to the version you are using in which case you'll have to revert back to this so for example if it's here just go back to this and then run npmi again to install this package but of course we don't need to do that cuz this is the version that we want to use for this project great now while we are here I'm just also going to write a start script so start and node we're going to listen out to changes on an index ch s file that is fine if we want to listen out to constant changes we can use noem one in which case we need to install the package noem one 2 and once that is done we should be able to use a start script so this is the script I just wrote to essentially run an index GS file and listen out to changes on it so let's go ahead and create that index GS file so it's a Javascript file I'm going to call it index JS just like so wonderful so this is is looking good I'm happy with all of this let's just shut this down now okay I'm going to make this a little bit bigger for you so now I can use npm Run start and this will start off listening out to the index JS file that is good and now we're going to essentially initialize the generative model so let's go ahead and do this const and we're going to get Google Google generative AI from Google generative AI okay so that's how you need to write it and maybe let's just minimize these for now so great once you have that we're going to get Google generative AI we're going to pass our API key into it okay so we're going to pass it through so that we can use Google generative AI for the purpose of this tutorial I'm just going to pass in the API key like so and now we have all of its method and properties to our disposal so let's save them as something I'm going to save them as gen AI great now if you do want to be super safe and you don't kind of even want to leave your API key even in here for demo purposes you can create a EnV file so you would just go ahead and create a new file call ITV and this is essentially for secrets so I'm going to call this API key and just paste in my API key in order to access this so This value by its property I can now just use process EnV and then API key okay however we do need a package for this uh so let's go ahead and do that I'm just going to open this up again making sure that we are in scratch pad and we need to install a package called EnV so that we can use EnV okay in this project and of course we need to also require it so require EnV config great so let's get rid of that for now and this is still running wonderful so that is now doing its thing we've initialized the generative model so that we can now like I said get all the methods and properties from it they're all stored under gen AI so I grab gen Ai and for example I can use get generative model and we can pick which model we want so for example I could go ahead and put model and then we would put Gemini Pro or anything like that okay so we're going to put in the string of Gemini Pro and then let's also save this to the C model as that the model we will be using for this tutorial wonderful so that that is it of course if you need to change the model please go ahead and change the text here making sure that it is spelled exactly the same as in the documentation meaning that if you want Gemini provision it has to be spelled like this or if there's any more in the future that you want to use just again refer to the documentation to get that spelling correct wonderful let's move on this is the final code okay so just to make sure this works I'm just going to conso log out the model and great everything looks as if it's working well okay so now let's move on and work on the generating text from text only input when the prompt input includes only text okay we just want text we want a text prompt and we want some text returned back to us from the model for that we need to use the gemino pro model with the generate context method okay so that's what we're going to be doing next I'm going to show you how to do it so this I would say is the most basic one uh I would of course need to initialize the model so let's go back to where we left off so here we are where we left off I'm just going to get rid of this console log once again this is me initializing the model so I can use it and once we have done that perhaps let's go ahead and write a function for this so I'm going to make this an async function let's call it run just like so and in this function is actually where I'm going to Define what model we want to use so I'm just going to whack that in there like so the model is going to be Gemini Pro as we said the next thing we need to do is Define a prompt so that prompt again maybe let's keep it the same so write a story about a magic backpack and now let's get the result so we essentially need to send over that prompt right so we're going to get this prompt and we're going to put it in to the generate content method and it lives on the Gino pro model so let's grab that model and let's get the generate content method from it and I'm just going to pass through the prompt and we're going to have to await this as this is an async methods we're going to have to wait for that to come back to us and once we have that result we're going to get the response from it but uhoh this is also async so we need to await it and let's save the return of this as something I'm going to save it as response and once we have that response I'm going to get the text from it and call it like so and just save this under text okay so there we go so let's just console log this text out so we can see what is going on and I'm just going to call this function so just like that let's hit save and great so this is the text that comes back so we've prompted the text of write a story about a magic backpack and we get a story about a magic backpack we get the text coming back to us so in the qut little town of Willow Creek a mixed Rolling Hills and Whispering Willows there's a curious young girl named Ana no way that is me little did she know that the ordinary bpack held a secret that would change her life forever so this is pretty cool I don't know if that's kind of creepily meant to be based on me or if that is a complete coincidence but I'm really into this I will read the story when I have time wonderful I'm really happy with this once again this is the full code that you will need in order to create text prompts okay so now let's look at generating text from text and image input so this is multi modal Gemini actually provides a multimodal model called Gemini provision so not Gemini Pro it's Gemini provision and we can input both text and images if we want so let's go ahead and do it I'm going to show you a super basic example so you can build out your nodejs out with it once again we're going to be inputting both text and images using the Gemini provision model with the generate content method from it to generate text input okay great so this time what I'm going to do well let's go ahead and go back to where we started so let just going to move this out here and delete this whole function so here is where we started off last time we did say we want the model to be Gemini Pro Vision so I'm just going to replace that and now we're going to also require another package that's going to allow us to essentially work with image files a little bit better it's the package called FS so FS require FS which means we need to install it so once again I'm going to do npm ifs in order to install that dependency you will see it show up in the package Json so if you look in here this is the version of FS that we are using so just keep that in mind and once again revert back to this if you're viewing this in the future and something doesn't seem to be working great let's move on now we're going to first have to convert local file information to a Google generative AI part object and in order to do this I'm going to write a function so the function here I'm going to call it file to generative part we're going to pass through two things a path and a mime type okay and then we're just going to return an object I'm going write inline data and this is also going to be an object I'm going to pass through some data to it which essentially we're going to buff from FS read path and then we are going to get all of this and append to string base 64 and we're also going to pass through the mime type okay so whatever we pass through into this function we're going to put here and here so that essentially will create a generative part to our files now let's go ahead and write our async function again again that will run this thing so async function run just like so once again we're going to get that model so Define our model in here and then let's also Define our prompt so const prompt what's different between these pictures so just like that and then let's get both our images so image Parts we're going to have two I'm going to use the function we just wrote we're going to pause through the file okay so I'm just going to put the files I'm going to put two in I'm going to put a picture of a cat so I'm just going to put on the same level as the index GS so we can just write the file name so there we go there it is I'm just going to type it out so cat. JPEG and this is an image JPEG and then let's do the other one so this time I'm just going to drag in another picture this one is going to be of Rick and Morty we have this one and then we have this one too okay so now I'm also going to write the path to the Rick and morti file this is a JPEG file image JPEG okay again we can just put through the file names as these files live on the same level as the index JS file great so those are the two images we will be comparing now once again let's work on getting the result so const result equals we're going to await the model we are using the generate content method and I'm going to pass through an array so we're going to pass through the prompt and the image part okay this generate content method lives on a different model this time it lives on the Gemini provision model so we can pass through two images along with the prompt and now once we have that let's get the response so response equals result but we're going to have to await it and we're going to get the response and then we're going to get the text so let's define that text and we're going to get the response and we're going to get the text from it like so and just console log out the text so great now let's run this so just like so and Tada the first picture is of a cat and the second picture is of a character from the anime series one punch man I don't know if that's true I'm pretty sure it's uh Rick and myty so I don't really know what one punch man is but hey that's close enough okay so great that is how you would essentially use the generate content method from the Gemini provision model let's move on so I'm just going to clean this up for the next one let's get out this model I'm just going to put everything back to where it was and I'm going to delete everything in here so we can start with this and we don't need that one either any now let's look at building a multi-time conversation chatbot so using Gemini we can also essentially create chatbots that will essentially take all the history of your chat previously in order to take into context your next questions to build a multi-time conversation so like a chat we're going to use the Gemini pro model and initialize the chat by calling start chat and then use send message to send a new user message which she'll also append the message and the response to the chat history okay so there are two possible options for roles associated with this we're going to have the user and this is the role which provides the prompt and we're also going to have the model which is essentially the role which provides the response this role can be used when calling start chat with existing history so let's go ahead and do it let's go back to our code so once again this is the start point that we have started at throughout this course I'm going to change the model to be Gemini Pro so that is now our model so let's go ahead and write our function so I'm going to write an async function let's call it run so just like so and now what we're going to do well I'm just going to stick that in here like we have been doing previously and let's go ahead and essentially start the chat so I'm going to get the model and it comes with a method called start chat so start chat is the method that we're going to use and we're essentially going to pass through an object let's go ahead and also store this as something so I'm going to save this as the cons chat just like so and in here well we're going to pass through the history it's going to be an array there's going to be multiple objects in here the first object is going to be of the role user so let's pretend this is a previous question that we asked so I'm going to say that as the user I asked hello I have two dogs in my house so let's have a question and of a statement and then let's also say that the model responded with great to meet you what would you like to know okay so that is the history essentially now let's also Define our message so let's define our message here and we let's say we want to ask a followup question of how many PS are in my house okay so that is a good message uh so that is really it we've got the history we've got the new question we want to ask so let's go ahead and get the result right so result equals we going to await chat okay because that's what we've defined here and we're going to send message that's another method that comes with it I'm going to just pass through the new message like so so once we have all of that so the history and our new message I'm going to get the response and we're going to await the result response and once we have that we going to need the text from it so text response text and I'm just going to console log out the text don't forget to call this as well and now let's run this function and call it and great if you have two dogs and each dog have four pors then there are eight pors in your house amazing so this is what we're going to be using in order to build out our own chatw coming up soon for the final project let's just look at one last thing and that is creating embeddings next so once again I'm just going to get rid of all this let's move out the model and let's start with this code so we can start freshh now finally I want to talk a little bit about creating embeddings this is a bit more on the advanced side embedding is a technique used to represent information as a list of floating points essentially so floating Point numbers in an array with Gemini you can represent text words sentences and blocks of text in a vectorized form making it easier to compare and contrast embeddings so for example two text that share a similar subject matter or sentiment should have similar embeddings which can be identified through mathematical comparison techniques such as cosign similarity so that is what an embedding looks like essentially this array of all these numbers represents a word or a sentence and this is how we essentially look for terms with similar meaning so similar semantic meaning if you want to learn more about embeddings please do check out this amazing video that I have on free code camp that will be a deep dive into this subject for now however I'm going to show you how to make your own embeddings so let's go ahead and do that so this is going to use the batch embed content method or the embed content method that lives on the embed 001 model so let's go ahead and change it up so we're not going to use this model anymore we're going to use em embedding 01 okay and let's go ahead and Define our function again so async function run let's move the model into here like so let's get the text the quick brown fox jumps over the lazy dog now let's get the result await model embed content as that is the method we're going to use I'm going to pause through that text okay and now let's get the result and get the embedding from it and I'm going to save this under the const embedding just like so and let's just console log out the embedding okay and if I run this you will see that this piece of text the quick brown fox jumped over the lazy dog is represented by this Vector so this array full of all these numbers okay all of these right here this is the embedding it's got 668 more items and if you were to perhaps change this to the quick B fox jumped over the lazy C and run this this embedding that is created will be more similar so this one right here will have more similarity in numbers to this one than perhaps the quick brown fox jumped over the lazy helicopter okay because cat and dog are relatively similar as opposed to a helicopter so that is a quick crash course in embeddings and how essentially they're used in order to find words of similar meaning so I hope that was really interesting once again do check out that Vector embeddings video If you do find this interesting I would like you take your knowledge to the next level otherwise let's move on let's actually get to using one of these to build out our project project coming up soon okay so let's do it I'm just going to go ahead and create a new project so let's go ahead and select new project and this is going to be a react app so this will essentially spin up a react app for me thanks to the MPX create react app commat so let's go ahead and call this something I'm just going to call this Gemini app maybe let's stick react to the front Okay so this is essentially going to be stored in my webstorm project directory on my computer I'm just going to click create and wait for that to spin up the app along with all the preconfigured files that we need so this is wonderful this going to save us a bunch of time let's just wait for that to do its thing in the meantime I'm just going to go to the Gemini documentation so here we are here is the URL if you need it and we're just going to work on getting our API key so let's go ahead and build with Gemini and let's click on this link right here AI Google Dev and it should take us to our dashboard of course please do make sure that you are signed in so I'm just going to go ahead and sign in here and I'm just signing in with my Google account so please go ahead and do the same and now we are free to get our API key so that is something we're going to do as a reminder I'm just going to go to the API here what we're going to be doing is creating an app that uses the Gemini pro model and now we're going to just go to node.js as we are going to be building in node.js for this project and we're going to build a multi-turn conversation chat so if you click on here here is build multi- turn conversation chat we're going to use the Gemini pro model for this allow us to do so and essentially we're going to be taking this code from here so if you get stucke please refer to the documentation for now however we also need to get our API key so let's go ahead and do it you scroll down here and click on get an API key just click on here and it should get a key for you so that you can communicate with the API however make sure to keep this safe you don't want someone seeing in your key and racking up loads and loads on your credit card if you choose to attach a credit card to this eventually so let's go ahead and do this I'm going to head over to Google AI Studio get API key in Google AI studio and you should be able to get the API key now if you can't it could be because it is not available in your region so just keep that in mind great okay let's go back to our app so once this is done you will see all the node modules that you need as well as a source directory of all the files that have been added as well as a package Json along with all the dependencies that we will be using so far so these are the latest dependencies and the versions of them that we are using for this project please make sure to always keep the dependencies the same version okay just in case you're doing this in the future and you know something's changed and you want to still build this app just revert back to these versions that you see here as well as the versions that we will be installing so first off however I'm just going to clean this up a little bit so on the index GS file I'm just going to delete the report web vitals from here as we will not be doing that we also won't be doing any testing and I'm going to get rid of the semic codons just because that is my personal preference so that is all that should be in the index JS file just save that like I said I'm just going to delete these three files right here so the logo the report where vitals and the setup tests so just do the same delete anyway now in the index CSS we're going to start from scratch I'm going to delete everything from this file the app test JS is also going to be deleted as I don't want to do any tests so no test for you today let's also get rid of the app CSS files this is a small app so I'm just going to keep all the styling in the index CSS file and now the appjs file once again I'm just going to essentially delete all of this from it and let's delete all of that so we can start fresh so that should be in here I'm going to make this a functional expression as well just because that is my preference okay great so all you should have in the source directory is this appjs file that looks like this the index CSS file that is empty and the index JS file should look like this wonderful let's move on now let's go ahead and start store our secret somewhere so I'm going to create a new file it's a EnV file and we're going to add our API key in here so our Google generative AI key so let's go ahead and call this Google gen AI key you can call it whatever you wish and I'm just going to paste in my unique key like so great and that's it so now we are ready to continue we essentially can start building I'm just going to going to build out a simple front and forther so we can get started with the meia stuff soon so let's go ahead and do it let's go ahead and create a simple chat so in here what I'm going to do is let's create a wrapping div let's give it the class name app let's also have a section in here this is going to be the search section so I'm going to give it the class name of you guessed it search section just going to minimize that for now and I'm just going to have a paragraph element what do you want to know okay and then let's have a button that says surprise me in case we you know want to be surprised with something so surprise me just like that uh let's maybe also give this a class name I'm going to give the class name of surprise and in fact what I am going to do is actually put this in the paragraph element you will see why so in fact maybe let's run this I'm going to get up my terminal and I'm just going to do npm Run start and in fact because we're going to have a front end a b a backend I'm going to get that script I'm just going to Define it as the frontend script and we're also going to have a backend script okay so backend and this is going to be no demon so that's a package that we're going to have to install to listen out for constant changes on the server JS file which we are yet to write that's going to hold that whole back end so maybe let's go ahead and create that file new file it's a Javascript file I'm going to call it server JS okay cool and let's continue so before we forget let's actually install that package so maybe let's go ahead and do that now npmi noemon and that will essentially install it so it will just add to these dependencies right here noemon has just been added along with its version so okay let's start our front end I'm going to do npm run Start Front End again making sure you're just in that app and TDA it's spun up our front end along with the elements that we've essentially added I'm just going to inspect this so we can work with it a little bit better great this is looking looking good let's move on so let's just minimize that for now and let's continue adding elements so we've got that P element next I'm going to have a div and this is actually going to be a container so I'm going to wrap let's call this the input container as this container is going to wrap an input element so here is my input element and as all input it's going to have a value at the moment I'm just going to leave it like so let's also have a placeholder for it uh maybe let's have something like when is Christmas okay very simple question um we'll have an onchange which will essentially change the value for us and save it in the state of this app but for now I'm just going to keep it empty of course we haven't written that function yet cool I'm also going to do something and I'm going to have a button here it's going to say ask me and then another button so we're going to have two buttons but we're going to show them conditionally so ask me or clear so at the moment you can see both buttons but I want to be able to only show the ask me button if there's no error then show this button so if this is true show this element however if there is an error then we show this button which means we need to save that error and I'm going to save it to state so we might as well just go ahead and import use state from react we're not going to be using use effect so let's get rid of that and now I can set the error so that is the Syntax for saving state to the app okay at the moment there is no error or but we can actually just keep this as null for now or in fact this is going to be a string so I'm going to just save it as that at the moment this has been assigned to the value of error and if we want to change it we use set error so if there is an error at the moment there isn't we should see this because there is no error right so let's have a look and the ask me button is showing however if I change this to something when is wrong and save it then it will say clear because an error does exist okay so hopefully that makes sense so we have those two buttons and now outside of this div let's also show the error if one exists so if an error does exist I'm going to show this P element that shows the error otherwise if it doesn't exist this won't show at all cool now we're also going to have a div and this is actually going to show the search results so you know whatever comes back from the API but of course there going to be multiple it's going to be a history so it's going to be multiple chants so class name search result I will call it and here we're going to essentially map items onto something it's going to be a div and this div is going to hold a p element that is just going to be the answer so let's go ahead and give this the class name of answer okay and this div will have a key because when you map onto things you need a key so I'm just going to leave that blank for now great and that really is it okay hopefully that was painless of course it doesn't look very nice for now the magic of styling will literally transform this so let's go ahead and do it I'm just going to go ahead and get my index CS file so let's get into the source let's get an index CS C SS file and now all I'm going to do it's going to say that all the fonts so font family is going to be sand serif no backup okay just sand serif being really basic here really kind of streamlining this project margin zero padding is going to be zero let's make the whole width of this 100 of the viewport width the height of this 100 of the viewport height and then the background color is just going to be like this off white that I picked out earlier and then the text color again it's not going to be black it's just going to be a gray so that's the short hand for writing seven seven s s six sevens display Flex we're going to initialize Flex box just so we can make sure that everything is in the center from like to left great all P elements in here again I'm just going to change the font weight to be 200 and I'm going to change the font size as well so I want the font size of all the elements the P elements to be exactly 14 pixels now the app itself so the element with the class name of app so this one right here I'm going to go ahead and make sure that it's width is smaller okay 80 viewport width uh and I'm actually going to give it a margin of 10 viewport width again to make up to that 100 and the height is going to be 80 viewport Hye okay great and that's going to contain everything in it um I think what shall we do let's have the search section so that is the first element in there I'm just going to make sure that it's 100% of the element with the class name of app the height of it is again going to be 100% uh let's use display Place flex and Direction column to make sure everything goes from top to bottom and that's really it okay so that section essentially is the same as the app so perhaps we can even go ahead and just give this the class name of app and just make this a div so I'm just going to delete that for now okay we're really streamlining things here so there we go and this just means that I can let's go ahead and add this like that and get rid of the search section completely great now let's go ahead and get the search results so the search results is here it lives inside the app let's maybe format this a little bit better so I'm just going to use webstorm to code format code and that is much better so the search result singular make sure that is singular I'm going to do margin top to space it out from the element above 10 pixels and I'm going to do overflow scroll so we can scroll through all the results and we don't have to scroll the actual page okay great now let's pick out the little things so I'm going to pick out this button by the class name of surprise so do surprise let's give it a background color I'm going to go ahead and use another color that I have pre-picked out EC e cf1 I'm also going to change the color of the text to be black and then let's add a border radius of five pixels to round it off this should be that and let's also add a font weight to this text uh let's go ahead with 600 and the padding four pixels on the top and bottom and 12 pixels on the left and right the margin of this again this I'm going zero at the top zero on the right two pixels on the bottom and five pixels on the left and the border of this is going to be none okay so if you're interested in how this is looking so far here we go this is looking good let's carry on so now I'm going to style the input container so I'm going to find the element with a class name of itut container the width of this is going to be 100% H and now I'm going to add a border to this it's going to be a solid border 0.5 pixels in width and again caaca is the color I have picked out for it the Box sizing of this is going to be border box so that the border is actually on the inside and let's round it off so border radius maybe let's make it six pixel this time and the Box Shadow I'm going to give it is going to be rgba for transparency 0 0 82 with 0.15 opacity okay and once again we're going to a blur a spread and great now inside the input container I want to grab the input that lives in it uh I'm just going to get the rid of the border the padding for this let's go ahead with 13 pixels on the top and bottom and 14 pixels on the left and right once again box sizing I'm going to go with border box the font size I'm going to go with 15 pixels outline none this will just get rid of the blue outline when you interact with the input and the width of this is going to be 90% of the parent with the font weight of this being 200 okay so now the input looks like this I'm going to use display Flex on this input container so that each item is kind of next to each other the rather than stacked and there we go let's do the button next so in fact maybe let's also work on the placeholder text so I can do this by graph grabing the input that lives inside the input holder and then if I want to get the placeholder text I can change it like so uh yeah let's go with this color and let's just make this a little bit like that so there we go much better in my opinion okay now let's do the button that lives inside the input container so any button that lives inside the input container is going to have this styling I'm going to give it a minwidth of 10% uh border of course is going to be none and let's also just add a border on the left side okay to differentiate from the input let's give it one pixel solid and Y I'm happy with that gray let's also make sure the background color is white and the text color is going to be this one that I used before the font weight I'm going to go with bold and cursor I'm going to add a cursor that is a pointer just for fun okay just make sure that that is light that and let's see what it looks like so I love this so much let's move on I think maybe let's add overflow hidden to the input so once again let's go maybe to the input container this time I'm just going to go with overflow hidden just so that this is a bit more rounded off at the edges on a fo okay that's nearly finished so I'm also going to add some styling to any button that lives inside the input container and if it's active so this is how you grab an active button that lives inside the input container make sure that space is there I'm going to just change the background color to be ca ca ca so kind of grade out when it's active and finally let's also style anything with the class of answer and for us that is these P elements so I'm just going to go ahead and add a padding to each one of 13 pixels at the top and bottom 14 pixels on the left and right let's also add a border of solid 0.5 pixels uh ca ca C okay so kind of similar styling repeating I'm also going to give them a background color let's make it white so # FFF a margin of 5 pixels a font size of 15 pixels a font weight of 200 and a border radius of six so wonderful I'm really happy with how this is looking so far okay let's work on linking up the surprise me button first so let's get rid of this for now and up here I essentially want to get a random value to work with so we've saved errors another thing I want to save is the value and the value is simply going to be the text that we are writing in here but we also want to generate some randomly so this is super simple to do all I'm going to do is Define our surprise options like so and it is going to be an array so that is good for us to use and I'm just going to put in some random options so who want the latest [Music] Noel piece prize can be one question we can also have where does pizza come from that's a great question uh and how do you make a BLT sandwich and clearly very hungry CU these are all very food focused pretty much apart from the first one so once we have our surprise options I'm just going to write a super simple function con surprise and all it's going to do is get a random value from this array so in order to get a random value yes thank You tab n we get the surprise options we open up the array we then get math floor which will round down to the nearest integer and we simply get the surprise options length and multiply it by math random and math random will return back a uh number from zero to just under one so if you multiply it by the length it'll always be just under three and we round it down so it could be either zero one or two and if we pass through zero into the array we'll get about this if you pass through one we'll get this and if you pass through two we will get that so that is how we get a random value and then I'm going to get random value and I'm going to pass it through to Z value so we're essentially at the beginning setting value to be this however if we call this function we will get a random value from here and reset this value using set value to be one of these three so now where should we do this well I think if we press the surprise button right so onclick of this I just want to call that function okay wonderful so maybe we should also add an option to disable this and I think this should be disabled if a chat history already exists right so maybe let's set const chat history set chat history and this will be an empty array so now if chat history exists we want this to be disabled but for now of course it's not and the other thing we want to pass through here is the value so we can actually see it in the input so on change we also need to set value of this I'm going to pass through the E Target value of whatever we type into the input itself of course we need to make this a function like so and pass through e so now this value so this value here can be changed in two ways right either if we click here on surprise me or if we start typing in here so let's try it out maybe as chat history you know if is an empty array up here we should probably change it to something if no chat history exists then we can do it there we go so this is looking good we're getting a random value each time or we can type in our own question like so and that will be saved to the value here so we can send it over to our API so let's do it so let's go ahead and write a function here and going to call it get response as that is essentially what we want to do we were going to get a response from the API just make sure to spell response correctly uh this is going to be an async function so let's just go ahead and whack that in here first off however if no value exists and we essentially click on the ask me button right so if you click on here and no value exists we want an error to show up essentially so I'm going to set an error and it's just going to say error please ask a question okay and we can of course show that too so maybe let's go ahead and put that here we already have so that will show up if there is an error and we're just going to return out of this great now we're going to try something so try and catch we're going to use the try and catch blocks I'm going to try something and if it doesn't work we're just going to catch any error we going to console error the error and we're also going to set the error so we're not going to use what comes back to us I'm just writing a super basic error that doesn't really give us much insight into what went wrong but if you want to take this a step further uh please do you can use this error to write some custom error messages cool so that's what we're going to do and now what are we going to send over to the back end well I think we're going to space this up a bit uh we're going to Define our options first okay and this is going to be a post method we are also going to be sending over the whole chat history so we're going to use Jason stringify I'm going to create an object and in that object we're going to send over all the chat history okay and we're also going to send over a message which is the lat lest text that we want to send through so essentially we're sending over whatever we type in here and if there is a chat history of previous questions we're going to send that over as well great let's also set our headers so we're going to choose content type Json for that that is correct and now as the response we're going to await Fetch and we can set our own Endo so let's say that we want our back end to be on Port 8,000 000 and I'm just going to make the end point Gemini and we're going to send through all these options with it so that is our response and of course once that comes back to us we're going to get text from it like so and save this as something we're going to await it though as it isn't asynchronous method so we need to await that and then let's save it as data and I'm just going to conso lock the data for now so we can see what's coming back great so now let's actually work on our back end so in here like I said we're going to define the port I did say this would be Port 8,000 so that's all I have done we are going to have to import a few packages or dependencies to help us here so let's just go ahead and open up a new tab making sure you're still in react Gemini app and I'm going to install Express which is going to help us with routing qu which is going to help us get rid of those pest Sky Blocks by qus messages when you're sending stuff from the front end to the back end and so on we're also going to use the EnV package to store secrets in our EnV file as you just saw and we are also going to need Google generative AI so let's go ahead and import that too so great that is the packages that we're going to need for this project so let's just wait for that to do its thing and let's continue so of course we're going to need Express require Express and we're going to wait for all of this wonderfulness from the package uh to come back and we're going to save it as Express and once we have it we're going to release it so this will essentially release methods and properties that come with Express and if we save it under a con so for example app we can now use app to get any method so for example to use method from it uh so great we're going to do that we're also going to require cor so const cores require cuse again this is to get past those pesky blocked by cuse messages when sending stuff from the front end to the back end and so on uh and we also going to also pass Jason from the front end so hence we need to use express Jason here great so let's just minimize that for now we also are going to require and we did import the EMV package so that we can essentially work with Secrets like our Google API key cool the other thing we're going to do is get Google generative AI from require and then the package at Google generative AI okay so there we go we've got everything nearly set up the other thing we're actually going to do is get that API key that we stored in our backend so I'm going to use Google generative Ai and I'm just going to PA through that API key okay I'm going to pass it through here so we can just go process EnV and then whatever we called our API key in our EnV file which was Google gen AI key so I'm just going to paste it in like so okay wonderful let's move on I'm also just going to listen out to check that everything is working as it should passing through the port as the first parameter and as the second parameter is a callback function I'm just going to do console log listening on Port and then I'll port number cool so now if we run this so for example here in the package Json we did write our script to listen out for anything on the server JS file so now I can do npm Run start backend and it should start our back end listening on Port 8,000 everything is working as it should cool so now let's write our root we wrote a post request to the endpoint Gemini as you saw here so now what do we want to send over to this back end to this end point well it's essentially all of this right so let's actually do that and you can send stuff over and you can get it by going to wreck body and then that should bring back this whole body right here and if you want to get the history from it I can simply do do history so maybe let's actually console log this so we can see what is going on and I'm also going to console log the rec body message as that is another thing that we are sending over so let's just see this works for now I'm just going to get up here my back end so we can see what's being sent so now if I go ahead and send some text when is Christmas for example and now let's hook up the ask me button so let's actually get this whole get response function and attach it to the ask me button so on click of this we want to get a response so let's go ahead and do it ask me and let's go back in here and look in the ser GS file in the terminal we get two things being consell that we get the history which yes is an empty array as we set that up here and we also get the value which is when it's Christmas so we save the value up here but then we also said the value should be the message so great we are sending stuff over we're sending over the chat history and the value because we are going into the request body history and into the request body message so request body history request reest body message we're sending that over now let's send it over to Google so let's go ahead and do it okay all I'm going to do is get gen AI once again this is just from the documentation that I showed you earlier we're going to do get generative model and we're going to pass through the model that we discussed so let's define the model here it is the Gemini pro model and I'm just going to save this as model so we've just defined it this should be gen AI as we defined here and now let's define the chat the chat well we're going to get the model and we're going to use the method start chat that comes with it and we're going to create an object and we're just going to pass through the history which again we already have it's this so request body history cool and now let's also Define the message so we Define our chat and now the message is just simply going to be request body message so that's a lot simpler okay so I'm just going to delete that for now as we don't really need it the next thing we need to do is actually get the result of what comes back so const result equals we're going to await we're going to get the chat so what we defined here and we're going to send a message and we're going to send through this message to the chat as well so along with the history we're sending through the message too and now we're going to get the result and we're going to get the response from it and as this is a asynchronous function we need to await it and let's save this as the response so just like so so and then when we get the response we need to get it text okay and let's save this as text so just like that okay and now I'm just going to do res send the text to send it back to our front end make sure this is send message and once we get it back here well at the moment we're just console logging it out so now all I need to do is essentially map them onto here we need to save the history so I'm going to set chat history however when working with arrays we need to essentially set the old state which I'm going to choose to call Old chat history we need to release it back into the array and then the data well I'm going to actually create a new object that is in line with the data that already exists so the way that Google modeled it so we're going to have a user and the user essentially asks this question which is our value and then we're also going to have another object and this role is going to be the model and it's going to be what comes back to us so this is what the model said or essentially the AI said and it's going to be the data that comes back so the piece of text great and once we have done that we can set the value to be an empty string again wonderful so now that we have that chat history I'm just going to scroll down here and we're going to map it onto this so let's get the chat history and we're going to map we're going to map it onto this whole div just like so and what we're going to do is map let's open up our parentheses once more and we're going to map each chat item as well as the index I'm going to pass through the index as the key it's not really used hence I use this and now for each chat item I'm essentially going to put it in here I'm going to get the chat item roll so it's either going to be user or model and then I'm just going to get the chat item parts and wonderful I'm really happy with this and maybe let's format this file once more the last thing I want to do is just clear the chat history the value and the error if we want to clear everything so I'm going to do so on the clear button so on click of this I want to clear right so let's define this function let's just do so here so const clear and I'm just going to set the value to be null set the error to be null and set the chat history to be an empty array again great and that's it so let's try it out I'm just going to type in when is Christmas and if you hit ask me it should come back with two messages that was my message so when it's Christmas and then whatever the model responded with which is December 25th now I can go ahead and ask a follow-up question to this conversation meaning it's taking into context the previous messages so I can simply write are you sure obviously are you sure by itself won't mean much but with the context we know we're talking about Christmas so if I typeing are you sure the model will come back with yes I am sure that Christmas on December 25th okay and then you can continue with other questions so it will continue the multi- chat conversation amazing so this is working as it should I love it let me know what you think below
Info
Channel: freeCodeCamp.org
Views: 180,163
Rating: undefined out of 5
Keywords:
Id: DJtX3S7qx2s
Channel Id: undefined
Length: 78min 59sec (4739 seconds)
Published: Thu Feb 22 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.