How to use ChatGPT API with Python

Learn to build a Python chatbot using OpenAI's ChatGPT API. The tutorial covers account setup, API key generation, installing the OpenAI package, and creating two functions to handle user input and generate responses. The host demonstrates the bot answering sports questions, writing poems, and handling multiple languages, then discusses cost savings and rate limits.
Chapters
Why did the tomato turn red? Because it saw the salad dressing. All right, so as a start, if you haven't signed up for an account for ChatGPT, for example, you would just need to go to openai.com and from there sign up for an account. Most of the time you will need a Gmail account, so find any Gmail account that you have, sign up for it, and you will get free credits. For example, here you can see I have $18 of free credits that you can use. As you can see here, I've used $0.55 so far. Once you're here and you have an account, you need API keys. To play around with the code. If it's the first time logging in, you will not have any secret API keys right there, so you will need to generate a new secret key. And remember that once it's generated, you need to copy that and put it somewhere, because once you close or click OK here, you will not be able to see it again. You will not be able to find it. But don't worry, if you do that, you just go ahead and delete whichever one you, you don't need, and then you can create another one from there as well. So I'll be deleting that, and I'll use the old one that I have, and then I'll also delete that since Y'all will probably be able to see which one I'm using. Once you've gotten your keys, let's go to an example of how you would be able to implement this with Python. Come here to the guides and come to chat completion, which will be ChatGPT. And as you can see, this ChatGPT is powered by GPT-3.5 Turbo. Here's an example of an API call that you would make to get data from or to get responses from ChatGPT. And this is an example that we'll be able to use. So I'll go ahead and copy this boilerplate code here and we'll run it as well and see if we'll get what we need with this code. As you can see from here, we need to install OpenAI OpenAI first. So pip install— I'm going to install it quietly so it doesn't print a whole bunch of logs on my screen. And from there, you just do openai, and you run that, and it should show you loading here. And first of all, it's connecting, and then it's going to load it. We should get a check mark here once it's done. While this is happening as well, remember that you need your API key to be able to run this code. So remember how you went and got your API key? So this is where you would paste it. So I'll paste mine here that I already have. We need to assign it to a variable. So that it'll be able to be used by the code that we'll be writing. So to do that, you need to do openai.api_key. And this is our API key. Let's run that as well. So you have to remember that you have to run all the cells in Jupyter Notebook, I mean. So when we run this, you see you're getting the error right here. So what you need to do first is you need to import OpenAI first. And this is right here in our code here as well in the beginning. So we just need to put that before we put assigning API key. So once we're done with that, then it's good and clean and it's done. The next part now will be to run the code that we have here, the boilerplate that they already gave us. So basically what it does here is, so it says you need to be using OpenAI Python version 0.27.0 for the code below to work. And if you just install the new OpenAI pip install like we do up there, you should have it already. Over here we have this OpenAI module which we already called and chat completion. Which basically if you hover over it, it'll tell you all the information about it. From here we need to load the model and the model here that we're using is GPT-3.5 Turbo, which is the new one that got released for the API. And we have to load in the messages explicitly. For example, you want to tell it, you know, be a therapist for example, right? So for this one, the example they gave was you are a helpful assistant and that would be the system message. That's basically like how you tell it in the beginning, how you sometimes tell ChatGPT, hey, I want you to be a, I don't know, a soccer commentator, or you want you to be a doctor, for example, act like a doctor or something, or act like a rapper or something, for example. And it should remember that context, but sometimes it loses that context. So you have to remind it several times, sometimes in your prompt. But in this case, if you want to set that up in the beginning so that it remembers that all the time, you can set that up. And then as a user, you are giving it content and telling it, hey, this is an example of how you would usually type it up on a chat and then send it up to it and it gives you back a response. So you're the user and the content you're giving to this API to run for you, or the query itself is who won the World Cup Series in 2020. And then the assistant is actually the ChatGPT responding back to you. And that's the role for it. And the content it's giving you back is the Los Angeles Lakers, the Los Angeles Dodgers, sorry, won the World Series in 2020. And then you as a user, again, you're telling it, hey, where was it played? And we're expecting it for it to give us an answer back as an assistant for this. So let's see if it's going to do that. So let's run this. And you can see in this JSON output that it gives us a message. If you come to the message and come the content. The content which is the assistant is giving us is the 2020 World Series was played at Globe Life Field in Arlington, Texas. And as you can see, it's given us a response. So that was the boilerplate. I want to do something a little bit more fun with this so that you can actually have fun building it and working with it. I want to build like a chat response thing where I'm able to kind of do like a live chat with it, like how you would do on the ChatGPT platform right now on OpenAI. I want to build something like that. Just remember you have to pip install OpenAI. And then import openai, and then you have to set your API key right here. And also, just as a reminder, don't even try copying mine here because I'm going to delete this. It's not going to work probably by the time I post this video. So I want to make my code have everything in functions to make it easier. It's going to be a few lines of Python anyway. So the first function I want to have is the one that generates the response, the one that holds that code we just ran a few moments ago to produce output. So that's what I want to have, that code first. And I'll call that function generate_response. Generate_response. And I just want that function to take in a query, for example, right? Or a prompt in this case. Let's call it a prompt. I want it to take a prompt from the user and give me back an output, which is a response from ChatGPT. That's all this code will do. And then the next function I want to have is a function that gets the user input. So let's just call it get_user_input. You'll be using the input function to ask the user for input, and then the user will be able to enter a question. ChatGPT will respond. And then I'll have a while loop, and this while loop will be just kind of the code running. So let's get started. Let's get started with this first one. And the first one, they want to implement this generate_response_prompt. Write a function here, generate_response, and I want it to take a prompt from the user. With this code, the first thing I want to set is the model. Of course, model is one of the parameters that the OpenAI Chat Completion API takes as one of the parameters. So to set that up, I'll just put model and I'll set the model to what we will be using here, which will be the ChatGPT-5 Turbo. And the response, because I want this to be a response from OpenAI, I want to put it on a variable so that I can access it easily. So openai.chat_completion. Create. And with this function, I want it to take the model. As you can see up here, this function takes 2 parameters, one being model and one being message. So you're basically giving it the model that you want, which is the current model that got released, and the message will be what you're asking the model to, to produce. Actually, essentially, I want this to be prompt. They are JSON. The prompt will be in JSON. But the brackets, the message takes a list of inputs as we saw earlier. So, so far we have a model, we have a function here that we've given the 2 parameters of model and also we've given it the prompt from the user. So once we get a response back from ChatGPT from this API, what we want to do is we want to grab the message that it responded back for us to be able to display that on the screen, right? So how we'll do this is we'll do output We do output text, and this output text variable will hold the message, which will be the response up there. And these are just some of the, like, walking down through the, the JSON path of this output or response until we get to the message. Get the first from the list and we'll get the message. And then from the message, we want to get content, and we'll also want to strip message. So anything that's Not part of the message. We want to strip that away. I want to have a variable that will hold the chats that we get back. So we'll just instantiate the chats. So once we get the output from here, I want to append message to the chat so that we're able to remember. If you had like, for example, a database, you could send it to the database if you want to at this point so that you have a history of your chats, for example, with the ChatGPT. But in this case, I want to just have the responses from ChatGPT stored somewhere in this variable so that I can access them. So here I want to append the role. The assistant name will be ChatGPT just for context. And the content will be the message that we get from this. We'll append it to this chats list. And from here, the last thing we want to do is just return output text. And also want to return chats. And now we have a function here that does the first thing that we need, which is generating the response. So it won't generate a response without us giving it something, right, to generate for us. We will give it a question for it to answer for us. So let's go ahead and create a function for user input. And this doesn't take any parameters. And so user input, we'll just call it user prompt, for example. And the user prompt will hold the query that we want to ask ChatGPT to generate a response for. So here I just want to put something that will make it easier for us to be able to read. So I would say, you, and then we So you will be you prompting you, hey, type something here. And then the response, I want it to be assistant, and then kind of iterate over it like that. So you versus the assistant chatting, or you and the assistant chatting in this case. And then prompt, final prompt that will send it to the function up top, still in a JSON format. So the role, and this is the user, which is you. From the user, this will be the content we'll be sending over to ChatGPT. So this prompt variable, what it does is basically taking the user input, which is you typing what you need to ask ChatGPT, and adding that to this prompt, which then will take this prompt and give it to ChatGPT to generate a response for us that we'll need. So this is the setup of it, which role is you as the user, and then the content will be what you type in here, and then we take that as entire variable and feed it to ChatGPT and it will respond back. Because that's how it understands our needs and answers our needs the same way. So from there, what we want to do is we want to return. Once we've gotten to this point, we have 2 functions already. So the next piece is putting everything together inside a while loop so that this code runs over and over as we ask it questions. So 1 1, we know is 2. So it's true. Basically, it's just the same as writing true, right? So instead of typing all this, just write true. While true, do this. Now we have chats instantiated as a variable that will hold the chats that we get from ChatGPT. The next thing now is to call the user input function, but we want to put it inside a variable so that we can feed it into generate response function. And you can name it whatever you want. I'm just naming it query in this case. Our query will be stored in the query variable here. So the next thing is to generate response. So in this one we don't need to really have it in a variable. So generate response and we want to feed it prompt will be our query. And after that we'll get our responses back from ChatGPT. So what we need to do now is iterate over the output. So within the chats that will be stored within this chats, We want to get the role for each chat. What we are saying here is all the responses that we get back from ChatGPT will look something like this. So the role will be role, for example, the role will be assistant because it's the assistant giving us a response. And then the content will be the response we get back from ChatGPT, which will be like a string of words response that we'll get from ChatGPT. Finally, what we want to do is print message that we get. So we want to print role plus, in Python it's concatenating 2 things together. Role, I want to have a comma in between what it's going to print. I want it to be like assistant and then the message it prints out. Also concatenate message that we get from ChatGPT. Let's go ahead and give it a try and run it and see what we get from this code that we've written. We basically want to ask ChatGPT something. What is your name? Oh, we're getting an error. So messages is a required property. So let's go ahead and fix that. It's supposed to be messages, not message. So let's run that again. It should print an output right here underneath. And as you can see, it has printed a message. So it says, I am an AI language model called OpenAI GPT-3. I don't have an actual name, but you can refer to me GPT-3, how may I assist you today? So that you can see that this is an example of how you would usually chat with ChatGPT, right? So let's ask it a, I guess, a more complex question. It's taking a minute here to load, and as you'd expect, it will be the same way. And boom, we have a response from it here. So it says, see, I am not— I didn't do physics myself, so I don't know if this is true. If you did physics, please comment below and let me know if it's correct. So it does explain actually what it does here, and doesn't make sense to me, but looks correct. Okay, so It kind of knows some science, right? So let's see what else we can ask it. Maybe generate a poem for me, or let's say write me a short poem. And as you can see, it has generated a poem. Now let's ask it if it knows some languages. I speak Swahili and Kalenjin. So let me just test that. I'm originally from Kenya, so let's test that. Yes. So let's see. As an AI language model, I do not have the capability to understand language in the same way as humans do, but I am programmed to recognize and process Swahili text inputs. Okay, so an example sentence in Swahili. So sometimes you'll get these errors and it will say the model is currently overloaded with other requests. This happens exactly the same way it usually happens when you go on ChatGPT and it tells you their servers are overloaded or something like that. So the main thing that I've found is just rerunning the code again and it will just work fine again, like how it would on the regular. Let's start again. So this time let's ask it, give me a few sentences Swahili. Okay, so we've got some sentences here. Asante sana kwa misava waku. Thank you very much for your help. Na taka ku vangea swahili vuswiri bya yi. I want to speak Swahili better. These are actually pretty accurate. Jin sigani u na jiski leyo? How are you feeling today? Nawamba misava waku wu chileyo. I apologize for being late. Sawunana kesho. We will see each other tomorrow. All right, let's ask if it knows Sheng. So basically, Sheng is a mix of English and Swahili in Kenya, and the youth kind of speak. So let's see if it understands what that is in the first place. Okay, so it did print. It did understand some stuff. So it says one of the examples is Sikwizi chapa ningumu zinapote hevihivi. Nowadays money is tough to come by. It disappears quickly. Okay, so you can see from just this example here of the power of this API of what you can actually do with it. And the awesome part too is that it doesn't cost much. It doesn't cost like previously. So it's like 90% cost reduction. So you'll be able to use this a lot. And especially if you have those free credits. If you don't, you have to buy some, but you'll be able to use it a lot and build products, integrate this in your apps, or you have this even in your portfolio, for example. All right, last one. Let's ask it to tell us a joke. Tell me a joke. All right, here's the joke. Why did the tomato turn red? Because it saw the salad dressing. And I'm actually going to end it there. That was good. In my next video, I'll try exploring the Whisper API. And with Whisper, what you can do with it is take an audio or record an audio and give it to Whisper, and it's going to give you basically a transcript of the conversation going on within that audio. And that could be really good because you can speak to it. Imagine combining ChatGPT API with Whisper API, for example. You can build a bot that you can talk to it, it converts it into sentences, which is a transcript with the Whisper API. And then from there it loads that to ChatGPT like how we've done here today. And then ChatGPT generates the message. And then maybe you have a voice command or a voice API as well that maybe can speak in different tones. Maybe you can speak as Morgan Freeman or Snoop Dogg or whoever really. And it takes that message from ChatGPT response and it speaks it out. So you can basically have a one-on-one conversation with it. You can talk to it, and then a few seconds later, it responds to you in the voice of the person that you want. Until then, stay tuned and subscribe.
More from Tony

Summarize Videos and Research Companies with CrewAI + Gemini Models [Quickstart Guide]

How to Make Your AI Agents More Reliable with CrewAI Task Guardrails (Step-by-Step Tutorial)








