OpenAI API example

Uncomment and run the following lines to install the required packages

#!pip install openai
#!pip install dotenv
import openai
from dotenv import load_dotenv
import os

# Load environment variables from .env files

# This one is for PRIVATE keys. Make sure it is not shared publicly (e.g. use gitignore).
dotenv=load_dotenv(dotenv_path="00_PRIVATE.env")

# This one is for publicly available configuration variables.
dotenv=load_dotenv(dotenv_path="config.env")

print(os.getenv("TEST_ENVVARS"))
Environment variables are read OK!
If you need to set additional ones add them to config.env
# Get the API key from environment variable
openai.api_key = os.getenv("OPENAI_API_KEY")

Open a connection to the OpenAI API

import openai 

client = openai.OpenAI()

Let us get a list of available models. Only the first 7 will be printed to avoid cluttering the output.

models = client.models.list()

for model in models.data[:7]:
  print(model)
Model(id='gpt-4-0613', created=1686588896, object='model', owned_by='openai')
Model(id='gpt-4', created=1687882411, object='model', owned_by='openai')
Model(id='gpt-3.5-turbo', created=1677610602, object='model', owned_by='openai')
Model(id='o4-mini-deep-research-2025-06-26', created=1750866121, object='model', owned_by='system')
Model(id='codex-mini-latest', created=1746673257, object='model', owned_by='system')
Model(id='gpt-4o-realtime-preview-2025-06-03', created=1748907838, object='model', owned_by='system')
Model(id='gpt-4o-audio-preview-2025-06-03', created=1748908498, object='model', owned_by='system')

Basic example of a prompt to classify the sentiment of a text

  • First we use Python to create a prompt that will be sent to the OpenAI API.

  • The prompt is a string that contains the text to be classified, the task to be performed, and the format of the answer.

  • It is very important to specify the format of the answer, as it will help the model to understand what is expected, and avoid unnecessary token processing with the associated costs.

task = 'Is the sentiment positive or negative?'
answer_format = 'Answer ("Positive"/"Negative")'

Let us consider two very simple examples:

text_neg = "Worst customer service ever. I will never buy from this company again."
text_pos = "Best customer service ever. I will definitely buy from this company again."

The corresponding prompts are:

prompt_pos =  f'{text_pos}\n{task}\n{answer_format}'
prompt_pos
'Best customer service ever. I will definitely buy from this company again.\nIs the sentiment positive or negative?\nAnswer ("Positive"/"Negative")'
prompt_neg =  f'{text_neg}\n{task}\n{answer_format}'
prompt_neg
'Worst customer service ever. I will never buy from this company again.\nIs the sentiment positive or negative?\nAnswer ("Positive"/"Negative")'

Now to get the model to classify the sentiment of the text, we will use the OpenAI API. The following doce block is the one for which we are actually charged, so it is important to keep it as simple as possible.

You need a valid OpenAI API key to run the following code. You can get one from

https://platform.openai.com/signup (payment info required).

And you can track your expenses here:

https://platform.openai.com/usage

response_pos = client.chat.completions.create(
                model='gpt-4o',
                messages=[{'role':'user', 'content':prompt_pos}])
response_pos.choices[0].message.content
'Positive'

Similarly for the negative sentiment example:

response_neg = client.chat.completions.create(
                model='gpt-4o',
                messages=[{'role':'user', 'content':prompt_neg}])
response_neg.choices[0].message.content
'Negative'