Skip to main content

Using Chat Completions API

In this lesson, we’ll explore how to use the Chat Completions API to have a multi-turn conversation with the model using roles like system, user, and assistant.

Prerequisites

Make sure you have:

  • Python 3.8 or later
  • Installed the OpenAI Python SDK:
pip install openai

The Code

Here's a basic script that sends a message to the gpt-4o-mini model using chat format:

from openai import OpenAI

client = OpenAI()

response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a helpful assistant that answers concisely."},
{"role": "user", "content": input("Provide your input: ")}
]
)

print("Assistant:", response.choices[0].message.content)

Explanation

  • client = OpenAI(): Initializes the client using your environment’s default API key.

  • model="gpt-4o-mini": We use the lightweight GPT-4 Omni model.

  • messages=[...]: A list of messages that simulate a conversation.

    • system: Sets the assistant's behavior.
    • user: Represents user input.
  • response.choices[0].message.content: Retrieves the assistant’s reply.

Note

The chat.completions.create method is ideal for applications requiring rich interactions, like customer support bots, virtual assistants, or dialogue-based tools.