Build a Recipe Generator with React and AI: Code Meets Kitchen

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hello everyone I am n and today we are going to build an AI powered recipe generator so in this video we will build the recipe generator using react node.js and open a GPT not only will this enhance your coding skills but it will also introduce you to the intersection of AI and everyday applications so before we start implementing this let's first see the demo of what we are going to build so in this project there are two cards on the front end the left one is for accepting the inputs for the recipe generator and the right one is for the actual recipe which will be fetched by calling the GPT API we have to enter all the inputs like the ingredients meal type quiz in preference cooking time and complexity so let me enter some values for ingredients I will enter tomato potato and onion for meal type I will select lunch for quiz in preference I will enter Continental for cooking time let's go with 30 to 60 minutes and for complexity intermediate let's click on generate recipe so the title is potato tomato and onion I don't know how to speak this Gren La continent talip something like that and then there are the ingredients let me zoom in some more and then the preparation steps and cooking tips serving how to sub this Etc so as you can see with the inputs that we have provided the open ai ai has provided us very detailed instructions on how to cook this recipe along with its name as well so if you want to create any application or website related to this business case then um this is how you need to approach this okay so now let's start to implement our recipe generator we will be using react in the front end and node in the back and so we cannot just use only react because we have to protect our API key behind the server so folder for client and folder for Server let's first open up the terminal and inside the terminal I will first create a new react app so CD client and npx create react app and then the app name which should be recipe gen press enter now while the app is setting up we can open up another terminal to set up our nodejs backend so CD server and npm in it and then y this will set up a basic application now in the server folder I will create a new file with the name server.js I will start implementing the backend server first so the first thing we need to do in the terminal is to install the dependencies the ones which we are going to need are npm install and then Express course and open AI so in this server.js first I will fetch the packages so packages for Express course and open AI we will use express to create our backend application by calling app equals to new Express and then we will also enable course for all the roots by simply using its middleware by calling app.use and then course let's also specify the port number on which we will be listening for the requests and finally we can call app. listen to be able to listen to the requests on the port 3001 so in our nodejs backend we will be using the server sent events to return the streaming AI output to our react client and it makes more sense to use these servers and events because then we will not have to wait for the entire response to be available on the server before we can return it to the client to create the server sent event endpoint we first have to call app.get and then we will have to provide the endpoint name which is going to be the recipe stream and then we will provide the call back function with the arguments for request and response and this is going to be an aror function first we will extract the input data from requests query next we will have to set the headers which are specific to the server sent events so the content type is going to be the event stream for cache control we are not going to Cache anything because we will be sending chunks of data and it's basically pointless to cash any of that for connection we are going to set the value as keep alive so until the connection is closed from either the server or the client we are going to keep it alive next up to send the events we will create a new function with the name send event this is going to accept the chunk the individual chunk of air response so I am going to implement this function in a while but before that let's focus on how we are going to call the open AIS GPT to get the response that we want to generate our recipe based on this data to do that I will simply create a new fun function with the name fetch openi completions stream this is going to accept two arguments the first one is the messages array which will contain our system prompt the second one is the call back function which is going to be the send event function when we will be calling this completion Sy streem function now in this function we have to do a series of steps first one is to specify the API key which we will need to call the open a backend API for the gpds that that we will use so this is the API key which I have generated in my account next we will have to initialize open AI by simply providing this API key as an argument which can be done by calling new open Ai and then providing this options object we also need to specify the AI model which we will use so I will be using the gp4 turbo which is the latest and fastest model now let's add the try and catch blocks to call the API so try and then catch so we have to call Open ai's chat completion function to fetch the response this can be done by calling the completions do create function and then providing an options object in this options object we have to provide the information about the AI model that we will be using and also we will send in the messages array which will contain our system prompt and finally we need to provide one more argument which is to set stream properties value to True which will simply indicate that we want the response in the format of a stream this can be fetched into the completion const and next for every Chunk we will be calling this call back function and that can be done by creating an async for of loop now for every chunk that we will receive with the completion object we will simply call the call back and provide the chunk as an argument and that is pretty much everything we need to do for calling the open a API now let's get back to our event streamings send event function now send event function is going to be somewhat complicated because we have to handle all the different conditions about the chunks data so first let's create a chunk response variable which will contain the actual response that we will um write to the response now with every Chunk we will know if it's the start of the chunk if it is the data or if it's the um you know final chunk when we have to finish then then within the chunk object the choices array finish reason is going to have the value of a stop so when that will be the case then we will simply write to the response an object with the value of action set to close like this so this is the format in which we have to write the server sent event data to the response data column followed with the actual data and then to new line characters also I'm stringify this object into Json so that on the client side we can simply call json. pars to again convert it into a Json object now if it is not finishing then it is either the start or it is the regular data so if it is the start then we can simply set the value for Action as start within the chunk response otherwise if it is the normal data then we can set the value of Chunk response as action equals to chunk and then chunk is going to be the the content of the chunk after this if and else condition we can simply write to the response whatever the value is there in the chunk response object and this is how we can create the send event function now it's time to call the fetch open AI completions stream function by providing the messages array and the Callback which we have just created to do that first we will have to create the prompt so the prompt I think most of you already know what an AI prompt is where we provide a set of instructions to the um large language model AI to let it know what kind of response we need so I'm going to first create an array with the name prompt this is empty initially now I will add all the prompt lines one by one for generating our recipe so let me just you know add some blank lines all right so first we are going to add the text generate a recipe that incorporates the following details and then I'm going to provide all the details as well by pushing them one by one into this prompt array ingredients meal type quiz and preferences and remember we fetched these from requests query now let's push to this prompt array three more lines please provide a detailed recipe including steps and preparation the recipe should highlight the fresh and vibrant flavors of the ingredients and also give the recipe a suitable name in its local language uh based on quiz and preference all right so that's our system prompt Now to create the messages array we simply have to create a new array with an object inside it the role is going to be system and the content is going to be our prompt which I have joined now finally we can simply call this fetch open AI completions stream function by providing the necessary arguments which it needs we also need to handle the close event of our event Stream So when it will be closed then we simply have to end the response and that is everything we need to do for our event stream all right let's format this document and let's now move on to our client side react code so for that I will open up the client folder and then the SRC folder let's open up app.js and first I will simply remove this header from over here and let's also remove the logo as well I'm going to import all the necessary um dependencies for user effect user F and user state that we will be using so first I will create the um recipe card which is going to have all the recipe inputs that we will need so for that I will create a new cons recipe card equals to all right in this I will create State variables for our recipe card inputs which are ingredients me type Quine quicking time and complexity now let's return the HTML and first I will add a parent div so this div is going to be the um the card div which is going to have the styling of a card so class name equals to all the card related classes let's add another div under this card div so for this I will add the X and Y padding now let's add the title and all the inputs one by one for the title we are using the text recipe generator and then these are all the inputs for these State variables and next we will also need a button to submit or save all of these values and then generate the recipe but we will not be adding the function to um send the request in this recipe card function we will be doing doing that in the parent app component but we will not be adding the function to um make the request to our nodejs server in the recip card component we will be doing that in its parent which will be the app component but over here we are going to provide the event on submit which will be simply called by our recipe card so this will be called by creating a new function handle submit and first we will wrap all the um input values in the recipe data object and then we will provide the onsubmit function with this data as an argument so finally let's also add the button which is going to be clicked to call this handle submit function so after our recipe card next we need to move on to the app component so inside app I will add two State variables the first one is going to be the recipe data and the next one is going to be the recipe text so recipe data is going to contain all of the input values the ingredients meal type and so on the recipe text is the actual text that will display the recipe which the AI has generated so the app component is going to return a div which is going to have the flex layout this div will contain our recipe input card and the um recipe output text card side by side so I'm just going to add the recipe card over here so recipe card and then let's create another um div for the recipe text card let's add The Styling information so in the class names I have added whes space preline to print the new lines correctly in this div for our recipe text now over here I will simply render the recipe Text Now the recipe card needs to have the on submit prop value provided to it but for that first we need to create the on submit function so let's do that to create the function I will simply create a new one with the name onsubmit this is going to be accepting the data and inside this function when this will be called it will simply mean that we will have to submit the data to the nodejs backend so first I'm just going to clear the existing recipe text and then we can set the recipe data with this data arguments value now when this data will be changed then we can simply call an effect function based on the dependency arrays value which is going to be the recipe data and we have to check if recipe data is not null because the default value is null if it's not null then we can simply call the um event streaming endpoint now the final part of this puzzle is how do we actually use the event streaming over here so for that first I'm going to create a new ref so Event Source ref equals to use ref with the initial value of null so we will be using the Event Source API which is available in the browsers so over here the first thing that I will do is I will create a new function with the name initialize event stream which is simply going to start the stream so all right first we will need the recipe inputs that we are going to provide to our event streaming endpoint as query parameters so this can be done by simply creating a new const by spreading out the existing recipe data and then we have to construct the query parameters this can be done by simply calling URL search params this is going to take care of all the encoding information required for sending all these inputs as parameters with our URL next we need the URL so our URL is the one which we are exposing from our nodejs backend so let's get back to our server.js and the URL is going to be um Local Host with Port 3001 yep over here it's 3001 and the endpoint is going to be recipe stream and with this URL we also have to provide the query parameters so URL is going to be Local Host 3001 and then this service andent event endpoint along with our query parameters now let's initialize a new event Source object into our ref that we have created so we have to call Event Source ref. current equals to new event source and now let's subscribe to the event sources on message event so this can be done by simply calling do on message equals to a new function which is going to accept the event as an argument now this event is going to be the data which we are sending from the server with each chunk that we are receiving from the open AI API so whenever this call back is going to be called with a chunk then this send event function will be called and based on the conditions that we have placed here the response is going to be written and whatever the response is we will receive it in our react front end so over here we just need to handle the response the first thing that we will do is to parse the events data into a valid Json this can be done by simply calling json. pass event. data next we need to handle the action values so we don't really need to handle the start action because we can simply start to update our reacts State when we start to receive the chunk but we need to handle the close event to be able to know when we need to close the um event source connection so let's do that so first if data do action is close then we have to close the event stream but we don't know yet how to do that so I'm going to create a new function to close the event stream this can be simply done by calling close on Event Source ref. current so I am going to create a new function to be able to close the event stream because we can then use it when initializing a new event stream as well so const close event stream equals to a new function over here I'm just going to first call Event Source ref. current dot close and let's also set it to null as well which is its default State all right so when the action is closed then we can simply call close event stream and if the action is chunk so if the action is data do action is chunk then we can update our recipe text state so let's do that set recipe text and we are going to use the previous value to append new value to it so this is going to return previous Plus data do chunk all right so like we have subscribed to the on message event we also have to subscribe to the on error event as well so what we are going to do is we will simply bind a function to the on error event which is going to close our Event Source now let's get back to our effect hook where we were monitoring the changes in the recipe data so when the recipe data will be updated then first we will close any existing event stream which is going on and then we will initialize a new event stream so I think that is all that we need to do for our recipe generator let me check once again if we have missed anything nope I think we are done over here now it's time to run our nodejs backend and also our react front end on Local Host so I'm going to write node and then server.js it says server running on Port 31 and now for react I'm going to write npm and then start so our UI is looking looking correct now let's check for any console errors there aren't any and now it's time to test this recipe generator I'm going to add the ingredients for the um let's add an apple and then a banana and then the meal type is going to be breakfast quiz in preference let's use French now let's click on generate recipe now it says on submit is not a function so the problem is I have uh missed to provide this on submit as a prop to our recipe card let's save it it says cannot read properties of null reading close I think I know what this error is about so in our close event stream I will first have to check if the Event Source ref. current is actually initialized or not so Event Source ref. current if it's not null or undefined then we can simply call um do close and then we can set it to null let's save it so there was one more error which I found while I was debugging and that is related to how we are calling the chat completions function so this is an async function so we have to use the await keyword before it now let's test again all right so I'm going to enter all the values again so apple and then banana and then for meal type I will select snack for preference let's use French for cooking time 30 to 60 Minutes complexity Advanced generate recipe all right so now the recipe is generating with this French name I don't even know how to speak it it says translated to English apple and flamb be banana turnovers and this is how we can um cook this recipe all right let's refresh again and try something else this time I'm going to use I don't know tomato potato and then onions meal type dinner for cuisin I will select Indian and cooking time 30 to 60 Minutes complexity intermediate click on generate recipe all right so now it says because I am from India I can read what it says it says Alo tomato K subzi I'm sure all the Indian viewers will be able to relate with this but in any case I think our recipe generator is working as per the instructions that we are giving to the um GPT aai so yeah that's how you can built an AI powered recipe generator using react and node.js if you found this video helpful and inspiring then please consider subscribing it encourages me to share more content like this thank you for watching and I will see you in the next video
Info
Channel: Code Radiance
Views: 1,797
Rating: undefined out of 5
Keywords: AI Recipe Generator, React JavaScript Framework, OpenAI GPT-3 Development, AI in Cooking, Machine Learning Culinary Applications, GPT-3 Recipe Creation, React and Node.js Projects, AI Cooking Algorithms, Building AI Applications, GPT-3 for Developers
Id: lAKkR4KzCe4
Channel Id: undefined
Length: 23min 45sec (1425 seconds)
Published: Tue Jan 16 2024
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.