So you want to jump into the AI Bandwagon and start using ChatGPT via the OpenAI API, this is the howto to get started for you. We will cover how to setup the environment, provide a few working examples how to call your OpenAI APIs from Python.
Create a .venv for your dependencies.
For this guide we will use Python 3.12 which is the latest version as of this writing. Its always a good practice to setup a new .venv for your project to separate dependencies from other projects.
I like to create a project for the demo, and check which version of Python3.12 Im working with. For this Im working on WSL2 on Ubuntu22.04, to install it you can check out How to install Python 3.12 (Latest) on Ubuntu WSL
robert@DESKTOP-9FOROU3:~# mkdir openai-demo
robert@DESKTOP-9FOROU3:~# cd openai-demo/
robert@DESKTOP-9FOROU3:~/openai-demo# python3.12 --version
Python 3.12.1
Create the .venv and activate it. We are using python3.12
robert@DESKTOP-9FOROU3:~/openai-demo# python3.12 -m venv .venv --without-pip
robert@DESKTOP-9FOROU3:~/openai-demo# source .venv/bin/activate
(.venv) root@DESKTOP-9FOROU3:~/openai-demo#
PIP Install openai
Now installed the required packages. Simple enough. Since we are working with .venv I use pip3.12 to make sure packages get installed on the right python interpreter.
(.venv) robert@DESKTOP-9FOROU3:~/openai-demo# pip3.12 install openai
Collecting openai
Generating your API Keys
Before we can move on to the Hello World Script, You will need to generate your OpenAI API Key. Below are some screenshots on how to do the process. You can find your API Keys on the following link https://beta.openai.com/account/api-keys

Please note that you will be charged based on your monthly usage. The cost structure is as follows: 750 words (aka 1000 tokens). Below is a table representing the cost per 1000 tokens:
| Model | Cost |
| GPT-4 (8k Context) | $0.03 |
| GPT-4 (32k Context) | $0.06 |
| GPT-3 (Davinci) | $0.02 |
| GPT-3.5 Turbo | $0.002 (10x cheaper than GPT-3) |
Hello World OpenAI Code
Below is a sample Script to get the OpenAI API working. This code already uses the ChatGPT 3.5 Turbo Model to make use of the most cost effective model.
import openai
openai.organization = "XXX"
openai.api_key = "XXX"
model_name="gpt-3.5-turbo"
def main():
message = {
'role': 'user',
'content': "Hello World. Can you say Hello Back?"
}
response = openai.ChatCompletion.create(
model=model_name,
messages=[message]
)
chatbot_response = response.choices[0].message['content']
print(chatbot_response.strip())
if __name__ == "__main__":
main()
(.venv) robert@DESKTOP-9FOROU3:~$ python3.12 hello-word-2.py
Hello!
Success!, We get a Hello Back from ChatGPT, we have succesfully completed our Hello World for OpenAI API.
Look at some of our other content.
If you are a developer working with OpenAI, Python, Linux, WSL we might have other content that is interesting for you.
Leave a comment