OpenAI Chat Completion in Python Notebook

See how to create chat completions using OpenAI models in Python. This notebook covers sending a user prompt and system, assistant role messages setting a model and token limit, and printing the response.

This notebook was created with MLJAR Studio

MLJAR Studio is Python code editior with interactive code recipes and local AI assistant.
You have code recipes UI displayed at the top of code cells.

Documentation

MLJAR Studio imports packages automatically so you don't have to worry about it:

# import packages
import os
from dotenv import load_dotenv
from openai import OpenAI, AuthenticationError

Firstly, create the OpenAI client connection:

# load .env file
load_dotenv()

# get api key from environment
api_key = os.environ["OPENAI_KEY"]

# create OpenAI client
def create_client(api_key):
    try:
        client = OpenAI(api_key=api_key)
        client.models.list()
        return client
    except AuthenticationError:
        print("Incorrect API")
    return None

client = create_client(api_key)

You can create chat completion using the following recipe:

# create a chat completion
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "user", "content": "Where is the biggest aquapark in Europe?"},
    ],
    max_tokens=300
)

# get and print response
print(response.choices[0].message.content)

It is also possible to add system and assistant role messages:

# create a chat completion
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "You are in the playground and you are 5 years old."},
        {"role": "assistant", "content": "Janek took away your toy."},
        {"role": "user", "content": "How do you feel?"},
    ],
    max_tokens=300
)

# get and print response
print(response.choices[0].message.content)

REMEMBER! You can change the OpenAI model and the number of tokens you want to use, but this may affect the price. Check the OpenAI API Pricing

Conclusions

It was one of the most common uses of OpenAI models. After seeing this example notebook, you can chat with the OpenAI models locally.

Recipes used in the python-chat-completions.ipynb

All code recipes used in this notebook are listed below. You can click them to check their documentation.

Packages used in the python-chat-completions.ipynb

List of packages that need to be installed in your Python environment to run this notebook. Please note that MLJAR Studio automatically installs and imports required modules for you.

openai>=1.35.14

python-dotenv>=1.0.1