Calling OpenAI API Service using Python
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
- OpenAI Account
- Python3
Setup
- 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.
- 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 =…