The first time I used ChatGPT I was absolutely astounded by this powerful tool and the possibilities seemed endless. In typical fashion, once I found out that an API was available, I decided to have a poke around with it using Python π
I was pleasantly surprised as to the simplicity of calling the API and put together a sample that uses the recently released gpt-3.5-turbo model and provides the ability to fire a question off and see the response from OpenAI within a terminal.
Step 1 – Obtain OpenAI API key
After creating an account with OpenAI, your API key can be obtained using this URL – https://platform.openai.com/account/api-keys
Step 2 – Install the OpenAI Python module
I launched a terminal and ran the following to install the OpenAI Python module.
pip install openapi
Step 3 – It’s showtime!
Here is the script:
import openai
# Set the OpenAPI key, replace KEY with your actual key
openai.api_key = key = "KEY"
# Set the model to be used
engine = "gpt-3.5-turbo"
# Prompt for a question
question = input("What's your question?: ")
# Submit the question, using the default values for everything - https://platform.openai.com/docs/api-reference/completions
response = openai.ChatCompletion.create(
model= engine,
messages=[
{"role": "user", "content": question},
],
)
print(response['choices'][0]['message']['content'])
Here is the script in action – I asked it to create a Python script for me to calculate the date 100 days from now and it didn’t let me down π.

Leave a comment