Adobe Apple AWS CertNexus Check Point Cisco Citrix CMMC CompTIA Dell Training EC-Council F5 Networks Google IBM ISACA ISC2 ITIL Lean Six Sigma Oracle Palo Alto Python PMI Red Hat Salesforce SAP SHRM Tableau VMware Microsoft 365 AI Applied Skills Azure Copilot Dynamics Office Power Platform Security SharePoint SQL Server Teams Windows Client/Server
Agile / Scrum AI / Machine Learning Business Analysis Cloud Cybersecurity Data & Analytics DevOps Human Resources IT Service Management Leadership & Pro Dev Networking Programming Project Management Service Desk Virtualization
AWS Agile / Scrum Business Analysis CertNexus Cisco Citrix CompTIA EC-Council Google ITIL Microsoft Azure Microsoft 365 Microsoft Dynamics 365 Microsoft Power Platform Microsoft Security PMI Red Hat Tableau View All Certifications
ChatGPT API Python Guide Taylor Karl / Monday, February 12, 2024 / Categories: Resources, Programming 9664 0 Introduction Welcome to this tutorial on using the ChatGPT API from OpenAI with Python! ChatGPT is a state-of-the-art language model that can generate human-like responses to text-based inputs. With its ability to understand context and generate coherent responses, ChatGPT has become a popular tool for chatbots and conversational agents in a variety of industries. In this tutorial, we will walk you through the process of setting up and using the ChatGPT API with Python. We’ll cover everything from installing the necessary packages to making requests to the API and processing the responses. By the end of this tutorial, you’ll have a solid foundation for building your own chatbot or conversational agent using the power of ChatGPT and Python. So, whether you’re a seasoned developer or just getting started with AI and natural language processing, let’s dive in and learn how to use the ChatGPT API with Python! OpenAI API Account Let’s quickly go through the process of getting you set-up with an OpenAI Account. First, you’ll need to sign up for an account if you don’t already have one at https://platform.openai.com/signup, where you can create an account via multiple options: Once you’ve set up your account, its time to create an API key! Setting Up OpenAI API Key Once you’ve created an account and logged in, we need to create an API key to use with our Python API call later. Navigate to your API key page at platform.openai.com/account/api-keys which will look like this: Then click on the button that says “Create new secret key” which will then create your new key. Copy and paste this somewhere safe on your computer, since you only get to view it once! Once you have this API key, you’re ready to switch over to Python to use the key to make a programmatic API call to ChatGPT in Python via the API! Setting up ChatGPT API Key in Python Now that we have our API key, we can set it up in Python with the os library. To set-up and save an OpenAI api key in Python with the os library module, follow these steps: First, make sure you have an OpenAI account and have generated an API key as we described above in the previous section! Once you have your API key, open up your Python environment and import the os library module. import os Next, create a new environment variable to store your API key. You can do this using the os.environ dictionary. os.environ["OPENAI_API_KEY"] = "your_api_key_here" To verify that your API key has been successfully stored as an environment variable, you can print it out to the console using the get() method. print(os.environ.get("OPENAI_API_KEY")) This should output your API key to the console. Finally, you can save your API key in a separate file for security purposes. Create a new file called .env in the root directory of your project and add the following line: OPENAI_API_KEY=your_api_key_here Make sure to replace your_api_key_here with your actual API key. To access your API key from the .env file, install the python-dotenv package using pip: pip install python-dotenv Then, at the beginning of your Python script, load the environment variables from the .env file using the load_dotenv() function from dotenv. from dotenv import load_dotenv load_dotenv() Finally, access your API key as an environment variable in your Python script using os.getenv(). api_key = os.getenv("OPENAI_API_KEY") Now you can use your API key to access the OpenAI API in your Python script. ChatGPT API Call with Python Now that we have the API Key set-up in Python, we can install OpenAI’s Python library with: pip install openai Make sure to upgrade to the latest version to utilize the Chat API, older versions of OpenAI Python api don’t have the Chat API installed. Next we set-up and connect our API key. Depending on how you completed the previous steps, you should be able to just assign the key with the following code: import openai # CONNECT TO API KEY openai.api_key = os.getenv("OPENAI_API_KEY") # ALTERNATIVELY openai.api_key = 'your-api-string-but-this-is-not-best-safety-practice!' Next we need to set-up the actual API call to the ChatGPT API. We need to state the model used ‘gpt-3.5-turbo’ and also provide a messages list, which retains the conversation between the user (you) and the assistant (ChatGPT). Here is a simple example of an initial call with the user saying “Hello!”: completion = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[ {"role": "user", "content": "Hello!"} ] ) print(completion.choices[0].message) This should output something similar to: { "content": "Hello there! How can I assist you today?", "role": "assistant" } Notice the form factor of the messages, its a list of dictionaries. The dictionary should have a role key stating whether the content should be attributed to the ChatGPT API model or the the human user. We then append these dictionaries to the list in order. This is because the API call is designed to be a conversation, with each item in the list representing a user input or the assistant (ChatGPT API) output. Let’s expand this to be a full conversation so you can see how you can create a back and forth conversation. We can simply append the reply message dictionary back to our messages list for the API call: completion = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[ {"role": "user", "content": "Hello!"}, # We'll add the reply back in! { "content": "Hello there! How can I assist you today?", "role": "assistant" }, # Now we add our response: {"role": "user", "content": "I am good, briefly, what is the definition of AI?"}, ] ) print(completion.choices[0].message) This will return back something like: { "content": "AI stands for Artificial Intelligence, which refers to the development of computer-based systems that are capable of performing tasks that typically require human intelligence, such as learning, problem-solving, decision-making, and natural language processing. AI systems use algorithms, statistical models and data to generate insights and make decisions without explicit prior programming.", "role": "assistant" } If we only wanted to grab the output text, we could just grab it with the key, meaning we could use: # Get just the output string completion.choices[0].message['content'] ChatGPT API System Parameter We can also add a system role as an initial dictionary in the list, the default system role content is “You are a helpful assistant”. But if we edit this, we can actually give our ChatGPT API call “personality”, since we can instruct the system to take on a particular system role personality. We do this via a system role as the first dictionary in the list. Here is an example of editing the system parameter call: completion = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[ # Edit the system {"role":'system','content':'You are very curt and only ever speak a few words. Use as few words as possible when replying.'}, {"role": "user", "content": "What is AI?"}, ], ) print(completion.choices[0].message) Notice how the system role at the start of our messages list defines how the ChatGPT API should respond. Here was the output: { "content": "Artificial Intelligence.", "role": "assistant" } Notice how it only answered in just two words! We can also get more creative: completion = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[ # Edit the system {"role":'system','content':'You are very tired and only want to answer questions about bedtime.'}, {"role": "user", "content": "What is AI?"}, ], ) print(completion.choices[0].message) Which gives an output of: { "content": "AI stands for artificial intelligence, which refers to the ability of machines and computer programs to mimic human intelligence and perform tasks that usually require human intelligence, such as visual perception, speech recognition, decision-making, and natural language processing. But back to bedtime related questions please.", "role": "assistant" } Example Interactive ChatGPT API Script Let’s look at an example script project that will automatically add back in the reply to the list, then let the user continue the conversation, essentially our own Python version of the official ChatGPT website: print("Type 'quit' to end chat") messages = [] user_input = '' while user_input != 'quit': # Get user input user_input = input('') # Add to messages list messages.append({'role':'user','content':user_input}) # Send to ChatGPT API completion = openai.ChatCompletion.create( max_tokens = 3500, model="gpt-3.5-turbo", messages=messages) # Grab Assistant Messages and append to messages list reply = completion.choices[0].message messages.append(reply) # Print out reply for user to respond to: print(reply['content']) # Then we keep this loop going until user says quit Notice how we also took advantage of the max_tokens to increase the size of the potential dialogue. The GPT-4 APIs will have up to 8k and 32k token limits, there are even developments of models with up to 100k tokens, that is the size of the first Harry Potter novel! Conclusion Now that you’ve seen how simple it is to use the ChatGPT API with Python, you can start building your own chatbots and take your interactions with users to the next level. By utilizing the power of GPT-3, you can create highly personalized experiences that will keep users engaged and coming back for more. With its flexible usage and customization options, the ChatGPT API is an invaluable tool for any developer looking to create cutting-edge conversational AI applications. Interested in learning more about Python, Machine Learning, and Data Science? Check out our full catalog of courses! Print