ChatGPT and Python API

Abhishek Maheshwarappa
3 min readMar 13, 2023

How to use ChatGPT with Python API

Introduction

ChatGPT an AI system that can interact with humans in normal conversational way. OpenAI released ChatGPT in November 2022, since then it has more 100 million active users, making it the fastest growing consumer application in the history.

Photo by Rolf van Root on Unsplash

ChatGPT model is currently using gpt-3.5-turbo, which transformer-based model which is priced at $0.002 per tokens. (Read more about pricing here)

ChatGPT is an AI system that lets you ask any questions and will respond in human like conversation.

Photo by Levart_Photographer on Unsplash

If you are not a fan of theory want to get to the crux of the code, link for the code is here.

ChatGPT use-case:

  1. Build own application
  2. Provide code suggestions
  3. Draft Email
  4. Create ChatBot
  5. Translate the languages
  6. Much more…!!

What is GPT — 3.5 -turbo?

GPT-3.5-turbo is one of the recent versions of GPT-3.5 model and optimized for chat, whereas GPT-3.5 was optimized for text completion.

ChatGPT API

Generally GPT models consume unstructured text, which is represented to the model as a sequence of “tokens.” But with ChatGPT, the model uses sequences of messages together with some metadata.

How to use the python API for ChatGPT?

  1. Create a account in the OpenAI
Screen shot from OpenAI

2. After adding billing information, one gets $18 of promotion credit to use and generate the API keys which is required to use a python API.
Note: Make sure to you copy the key.

3. Install OpenAI in any environment you want test, you can use Google Colab

pip install openai

4. Once installed, copy the API key generated in step two.

import openai
openai.api_key = "Use your OpenAI API key"

5. One can get a response from ChatGPT by using this method openai.ChatCompletion.create()

6. Method takes in two inputs

a. a model
b. message or question to the model



completion = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=[{"role": "user", "content": "Tell the world about the ChatGPT API in the style of a pirate."}]
)

print(completion)

Google Colab

I have created an example on Colab Notebook which can be used to play with python ChatGPT API.

ChatGPT — Google — Colab — here is the link

Note : Put your OpenAI api key to get response.

References

  1. https://openai.com/
  2. https://openai.com/blog/chatgpt

--

--