Unlock the Power of ChatGPT with the Python OpenAI Chat API

A practical example of how to interact with the OpenAI Chat API in Python

George Pipis


Image generated by DALL-E

Most of us are familiar with the ChatGPT UI, and we are impressed with the stunning results that it generates. Clearly, this is a revolution in the AI world. The UI of the ChatGPT is really friendly, and it allows us to start experimenting with different prompts, but in order to unlock its power, we need to interact with it programmatically. This will let us automate some tasks and build applications.

Python Library

We will need to download the openai library as follows:

pip install --upgrade openai

OpenAI Chat API

Using the Chat API, we can interact programmatically with the ChatGPT and more particularly with the gpt-3.5-turbo and gpt-4 models. The other benefit of using the Chat API instead of the UI, is that you can play with the parameters, such as model, role, temperature, top_p, n, stream, stop, max_tokens, and so on. You can find more info here.

The main difference between the Chat Completion model and the Text Completion model is that the Chat models take as input a series of prompts. However, this does not mean that the Chat models cannot be used for single-turn tasks without any conversations. Keep in mind that the gpt-3.5-turbo performs similarly to text-davinci-003 but it is 10 times cheaper, and as a result, it is recommended to use gpt-3.5-turbo for most use cases.

OpenAI Chat API Calls

An example of an API call looks like this:

# Note: you need to be using OpenAI Python v0.27.0 for the code below to work
import openai

{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "Who won the world series in 2020?"},
{"role": "assistant", "content": "The Los Angeles Dodgers won the World Series in 2020."},
{"role": "user", "content"…



George Pipis

Sr. Director, Data Scientist @ Persado | Co-founder of the Data Science blog: https://predictivehacks.com/