How to Connect ChatGPT from Python
ChatGPT is a state-of-the-art language model developed by OpenAI that can generate natural language responses to a variety of prompts.
Connecting to ChatGPT from Python is a straightforward process using the OpenAI API: sign up for a free API key, install the package, set up environment variables, and use openai.Completion.create()
to generate human-like text based on a given prompt.

In this article, we’ll walk through the steps required to connect to ChatGPT from Python(Pychram IDE and Terminal) using the OpenAI API.
Setting up your OpenAI API Key
The first step in connecting to ChatGPT from Python is to sign up for an OpenAI API key. You can sign up for a free API key by visiting the OpenAI website and creating an account.
Once you have logged in, You can find the “View API KEY” under your profile

Clicking that, Will show you an option to create a key and by using this key, We are going to connect to ChatGPT

Once you have your API key, save it as an environment variable on your computer so that you can access it from your Python code. You can do this by adding the following line to your .bashrc or .bash_profile file:
export OPENAI_API_KEY="your-api-key-goes-here"
Or, you can set the environment variable programmatically in Python by using the os module:
import os os.environ["OPENAI_API_KEY"] = "your-api-key-goes-here"
Installing the OpenAI Python Package
To connect to ChatGPT from Python, you’ll need to install the openai Python package. You can do this using pip:
pip install openai
Steps to install openai module in pycharm (MAC)
Step1: Install openai from the mac terminal
The below command will check if you have pip installed on your mac else it will install the latest version
% python3 -m ensurepip
Looking in links: /var/folders/w9/8cv64r4j77q1krr6v4htd3340000gn/T/tmp4jqtbwc3 Requirement already satisfied: setuptools in /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages (65.5.0) Requirement already satisfied: pip in /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages (22.3)
Install openai using pip
% python3 -m pip --version
pip 22.3 from /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pip (python 3.11)
% python3 -m pip install openai Downloading openai-0.27.0-py3-none-any.whl (70 kB) ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 70.1/70.1 kB 672.2 kB/s eta 0:00:00 Collecting openai Installing collected packages: openai Successfully installed openai-0.27.0
It will also install all the dependent packages and it will be ok
Step2: Create a project in pycharm
Creating a new project for ChatGPT with the latest python version 3.11

Step3: Add the openai module to this project
Go to -> pycharm -> preferences -> python interpreter

Click -> ‘+’ symbol and search for openai -> click ‘install package’

That’s it we are done with the setup, Now, we can run a sample python program to connect ChatGPT from Pycharm
Connecting to ChatGPT using the OpenAI API
To connect to ChatGPT from Python, you’ll need to use the OpenAI API. The openai.Completion.create() function allows you to send a prompt to the ChatGPT model and receive a response.
Example code:
import openai # Set up the OpenAI API client openai.api_key = "your-api-key-goes-here" # Set up the model and prompt model_engine = "gpt-3.5-turbo" prompt = "Can Chatgpt replace human?" # Generate a response completion = openai.Completion.create( engine=model_engine, prompt=prompt, max_tokens=100, n=1, stop=None, temperature=0.5, ) response = completion.choices[0].text print(response)
Output
ChatGPT cannot replace human beings entirely due to its lack of emotional intelligence, creativity, and intuition, but it can still be a valuable resource in many contexts.
In this example, we set the prompt variable to “Can Chatgpt replace human?“, and we use the openai.Completion.create() function to generate a response up to 1024 tokens in length. The generated response
Run from Terminal
If you are not using Pycharm, You can directly save the code as “chatgpt.py” and run it from the terminal and make it interactive by tweaking the code as below
import openai # Set up the OpenAI API client openai.api_key = "your-api-key-goes-here" # Set up the model and prompt model_engine = "gpt-3.5-turbo" prompt = input("Type Here: ") # Generate a response completion = openai.Completion.create( engine=model_engine, prompt=prompt, max_tokens=10, n=1, stop=None, temperature=0.5, ) response = completion.choices[0].text print(response)
We did a small change in the code to make it interactive, By getting the input from the user directly (using input ) You add a loop to create an interactive session-like experience with multiple Q& A. Save the above code as a file “chatgpt.py” and run it from terminal
% vi chatgpt.py
% python3 -m chatgpt.py Type Here: Hi
Output:
Hello! How can I assist you today?
NOTE: You may also get the below error, While running the above program,
openai.error.RateLimitError: You exceeded your current quota, please check your plan and billing details.
This means, Your ChatGPT plan has exceeded quota or you are using the free version 🙂
Reduce the max_tokens (Which can be denoted as a number of words) value to match the size of your completions. This quota value will be estimated from the max_tokens, So reducing it will decrease the chance of getting the above error
ChatGPT API parameters
Let’s understand the various parameters used in the ChatGPT API and can be customized based on our need
engine
: The parameter specifies which language model to use (“text-davinci-002” “gpt-3.5-turbo”)- prompt: the parameter is the text prompt to generate a response
max_tokens
: parameter sets the maximum number of tokens (words) that the model should generate and returntemperature
: the parameter controls the level of randomness in the generated textstop
: the parameter can be used to stop generating further tokens.
Conclusion
In conclusion, connecting to ChatGPT from Python is a simple process. By following the steps outlined in this tutorial, you can easily connect to ChatGPT and generate human-like text based on a given prompt.
Whether you’re looking to automate tasks, generate creative writing, or build chatbots, ChatGPT is a powerful tool that can help you achieve your goals. So why not give it a try and see what kind of amazing things you can create with ChatGPT and Python!
Good Luck with your Learning !!