Calling OpenAI API Service using Python

Renjith Ravindranathan
techbeatly
Published in
2 min readApr 7, 2023

--

OpenAI Logo

In this short article, I will demonstrate with a sample code how we can interact with OpenAI API Service using python library. Sending the request to the service and also getting the response is quite straightforward and there are numerous possibility on the application integration side using API. So lets see how its done.

Pre-requisites

  1. OpenAI Account
  2. Python3

Setup

  1. First step is to get the API_KEY token generated from your OpenAI account. The link is here. This enables you to interact with the service.
  2. Include the API_KEY, MODEL and ROLE in the environment variables before running your python Program.

Currently there are two gpt models being supported by OpenAI API Service

gpt-3.5-turbo
gpt-4

The roles can be either of the below

#Basically a chat conversation is formatted with a system message first, followed by user and assistant messages.

system
user
assistant

3. The python code added below enables to user to send a single request to the API service and get the response back.

import os
import openai
import sys

api_key = os.getenv('API_KEY')
gpt_model = os.getenv('MODEL')
role =…

--

--

Renjith Ravindranathan
techbeatly

A DevOps engineer by profession, Dad, Traveler & sometimes, like to tweak around stuff inside memory constrained devices. Currently living in the Netherlands.