I’ve been having a play with the OpenAI API in Python and wanted to write up what I found. The setup is straightforward and there are a few practical things you can do with it right away.
Getting started
You need Python 3.7 or newer, an API key from openai.com, and the openai package:
pip install openai
Example 1: Text generation
The chat completions endpoint is the main one you will work with. Here is a basic translation example:
from openai import OpenAI
client = OpenAI(api_key="your-key-here")
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "user", "content": "Translate this to French: 'Hello, how are you today?'"}
],
temperature=0.7
)
print(response.choices[0].message.content)
The temperature parameter controls how creative the output is. Lower values give more predictable results; higher values make it more varied.
Example 2: Sentiment analysis
You can use the same endpoint for classification tasks. Here I am asking it to assess the sentiment of a product review:
from openai import OpenAI
client = OpenAI(api_key="your-key-here")
response = client.chat.completions.create(
model="gpt-3.5-turbo",
messages=[
{"role": "user", "content": "What is the sentiment of this review? 'The product works well and saves me a lot of time. Really pleased with it.'"}
]
)
print(response.choices[0].message.content)
The response comes back as plain text. If you need structured output for processing programmatically, ask the model to respond in JSON format and parse it from there.
There is plenty more the API can handle: summarisation, data extraction, code generation and so on. The OpenAI documentation covers the full range of options.