Mathew K Analytics

Lesson 2 · OpenAI

How to Install and Set Up the OpenAI Python SDK: A Step-by-Step Guide

Welcome to your first steps with the OpenAI API in Python. This lesson will help you set up, understand, and safely use the API. You will learn by typing…

⬇ Download notebookOpen in Colab ↗

What you'll learn

Data

No separate download needed — the notebook creates or downloads everything it uses.

📓 Full notebook

Download .ipynb

Introduction to the OpenAI API in Python#

  • Welcome to your first steps with the OpenAI API in Python.

  • This lesson will help you set up, understand, and safely use the API.

  • You will learn by typing and running code, just like a real programmer.

  • Are you ready to build with artificial intelligence? Let us begin!

What is the OpenAI API?#

  • The OpenAI API lets you use powerful models like ChatGPT in your apps.

  • These models can answer questions, write text, summarize, and more.

  • The API works over the internet, so you can use it from anywhere.

  • Whether you are building a chatbot or a helper, this API is your starting point.

Why does the OpenAI API matter?#

  • You can use artificial intelligence models without needing special hardware.
  • Anyone can build tools that understand and generate language.
  • The API makes advanced AI safe and easy to use.
  • Let us explore its power together.
# Suppress warnings so they do not distract us
import warnings; warnings.filterwarnings("ignore")
 
# Let us check our Python version for compatibility
import sys
import numpy as np
np.random.seed(42)
print("Your Python version:", sys.version)
Your Python version: 3.12.1 (tags/v3.12.1:2305ca5, Dec  7 2023, 22:03:25) [MSC v.1937 64 bit (AMD64)]

How to set up the OpenAI Python SDK#

  • The SDK is a software toolkit for Python. It helps connect your code to the OpenAI API.
  • You install it using pip, which is Python's tool for packages.
  • If you are running in Google Colab or Jupyter, use the command below.
# Install the openai SDK if you do not have it
!pip install --upgrade openai
Requirement already satisfied: openai in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (2.8.1)
Requirement already satisfied: anyio<5,>=3.5.0 in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from openai) (4.9.0)
Requirement already satisfied: distro<2,>=1.7.0 in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from openai) (1.9.0)
Requirement already satisfied: httpx<1,>=0.23.0 in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from openai) (0.28.1)
Requirement already satisfied: jiter<1,>=0.10.0 in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from openai) (0.12.0)
Requirement already satisfied: pydantic<3,>=1.9.0 in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from openai) (2.11.9)
Requirement already satisfied: sniffio in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from openai) (1.3.1)
Requirement already satisfied: tqdm>4 in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from openai) (4.67.1)
Requirement already satisfied: typing-extensions<5,>=4.11 in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from openai) (4.15.0)
Requirement already satisfied: idna>=2.8 in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from anyio<5,>=3.5.0->openai) (3.10)
Requirement already satisfied: certifi in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from httpx<1,>=0.23.0->openai) (2025.8.3)
Requirement already satisfied: httpcore==1.* in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from httpx<1,>=0.23.0->openai) (1.0.8)
Requirement already satisfied: h11<0.15,>=0.13 in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from httpcore==1.*->httpx<1,>=0.23.0->openai) (0.14.0)
Requirement already satisfied: annotated-types>=0.6.0 in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from pydantic<3,>=1.9.0->openai) (0.7.0)
Requirement already satisfied: pydantic-core==2.33.2 in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from pydantic<3,>=1.9.0->openai) (2.33.2)
Requirement already satisfied: typing-inspection>=0.4.0 in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from pydantic<3,>=1.9.0->openai) (0.4.0)
Requirement already satisfied: colorama in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from tqdm>4->openai) (0.4.6)
# Import the OpenAI Python package
from openai import OpenAI
 
# Now, we create the API client
client = OpenAI()
# Let us check if your API key is available
import os
API_key = os.environ["OPENAI_API_KEY"]
print("API key found and loaded from environment.")
API key found and loaded from environment.

How does the OpenAI API work?#

  • You send questions or instructions to the API using your client.
  • The API returns responses generated by large powerful models.
  • Each endpoint does something different, like chat or embeddings.
  • We will try some of the most useful features together.
# OpenAI API  Chat Completions Setup
from openai import OpenAI
client = OpenAI()
 
# Basic Chat Completion
response = client.chat.completions.create(
    model='gpt-4.1-mini',
    messages=[{"role": "user", "content": "Hello!"}]
)
print(response.choices[0].message.content)
Hello! How can I assist you today?
# OpenAI API  Responses Endpoint Setup
from openai import OpenAI
client = OpenAI()
 
resp = client.responses.create(
    model='gpt-4.1-mini',
    input='Explain embeddings in one sentence.'
)
print(resp.output[0].content[0].text)
Embeddings are numerical vector representations of data, such as words or images, that capture their semantic meaning and relationships in a continuous, high-dimensional space.

Key concepts: Models, Endpoints, and Tokens#

  • A model like 'gpt-4.1-mini' is a type of AI brain trained to talk or complete tasks.
  • An endpoint is a special address for each task, like chat or audio.
  • Each request uses tokens, which are pieces of words. Tokens affect cost and speed.
  • We will pick simple models to keep things efficient and easy.
# OpenAI API  Embeddings Setup
from openai import OpenAI
client = OpenAI()
 
embed = client.embeddings.create(
    model='text-embedding-3-small',
    input=['Machine learning is fun']
)
print(len(embed.data[0].embedding))
1536
# OpenAI API  Speech to Text Setup
from openai import OpenAI
client = OpenAI()
 
audio_file = open('sample.wav', 'rb')
transcript = client.audio.transcriptions.create(
    model='whisper-1',
    file=audio_file
)
print(transcript.text)
Welcome to OpenAI.
# OpenAI API  Text to Speech Setup
from openai import OpenAI
client = OpenAI()
 
with open('voice.mp3', 'wb') as f:
    audio = client.audio.speech.create(
        model='gpt-4o-mini-tts',
        voice='alloy',
        input='Hello world!'
    )
    f.write(audio.read())

Safety and Best Practices for Beginners#

  • Never share your API keys or include them in videos or public code.
  • Use simple, smaller models while you are learning. They are faster and cost less.
  • Watch out for costs. Each call may use credits or dollars.
  • Always review results, since the AI can make mistakes.
# OpenAI API  Function Calling Setup
from openai import OpenAI
client = OpenAI()
 
def add(a, b):
    return a + b
 
resp = client.chat.completions.create(
    model='gpt-4.1',
    messages=[{"role": "user", "content": "Add 3 and 5"}],
    functions=[
        {
            "name": "add",
            "description": "Add two numbers",
            "parameters": {
                "type": "object",
                "properties": {
                    "a": {"type": "number"},
                    "b": {"type": "number"}
                },
                "required": ["a", "b"]
            }
        }
    ],
    function_call='auto'
)
print(resp)
ChatCompletion(id='chatcmpl-CheRDvxuwp8PJKOPLWI6eMYAEywKO', choices=[Choice(finish_reason='function_call', index=0, logprobs=None, message=ChatCompletionMessage(content=None, refusal=None, role='assistant', annotations=[], audio=None, function_call=FunctionCall(arguments='{"a":3,"b":5}', name='add'), tool_calls=None))], created=1764519583, model='gpt-4.1-2025-04-14', object='chat.completion', service_tier='default', system_fingerprint='fp_09249d7c7b', usage=CompletionUsage(completion_tokens=17, prompt_tokens=50, total_tokens=67, completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=0, audio_tokens=0, reasoning_tokens=0, rejected_prediction_tokens=0), prompt_tokens_details=PromptTokensDetails(audio_tokens=0, cached_tokens=0)))
# API call error handling example
try:
    broken_resp = client.chat.completions.create(
        model='does-not-exist',
        messages=[{"role": "user", "content": "Hello!"}]
    )
    print(broken_resp.choices[0].message.content)
except Exception as e:
    print("Error! That model probably does not exist. Details:", e)
Error! That model probably does not exist. Details: Error code: 404 - {'error': {'message': 'The model `does-not-exist` does not exist or you do not have access to it.', 'type': 'invalid_request_error', 'param': None, 'code': 'model_not_found'}}

Mini Project: Build a simple Chatbot#

  • Now, let us make a basic chatbot that will answer anything you type.
  • This project will bring together what you have learned so far.
  • You will type something, send it to the API, and see the model's reply.
  • Ready? Let us get typing!
# Simple Chatbot using the Chat Completions endpoint
user_msg = input("Type your message to the chatbot: ")
response = client.chat.completions.create(
    model='gpt-4.1-mini',
    messages=[{"role": "user", "content": user_msg}]
)
print("Chatbot says:", response.choices[0].message.content)
Chatbot says: Rainbows form due to the interaction of sunlight with raindrops in the atmosphere. Here’s a step-by-step explanation of the process:

1. **Refraction:** When sunlight enters a raindrop, it slows down and bends because light changes speed when it passes from air (a less dense medium) into water (a denser medium). This bending of light is called refraction.

2. **Dispersion:** White sunlight is made up of different colors, each with different wavelengths. As the light refracts inside the raindrop, these colors spread out or disperse because each color bends by a slightly different amount.

3. **Reflection:** The dispersed light reflects off the inside surface of the raindrop.

4. **Refraction (again):** When the reflected light exits the raindrop, it refracts once more, bending again as it passes from water back into air.

The combination of these refractions and internal reflection causes the light to spread out into a spectrum, creating a circular arc of colors that we see as a rainbow. The typical order of colors from the outer edge to the inner edge of a rainbow is red, orange, yellow, green, blue, indigo, and violet (often remembered by the acronym ROYGBIV).

To see a rainbow, the sun needs to be behind the observer and rain in front, with the light being refracted and reflected inside the raindrops at a specific angle (approximately 42 degrees for the primary rainbow) relative to the line between the observer and the sun.

Troubleshooting tips#

  • If you see errors, check your API key and package version.
  • Make sure the models you use exist and are spelled right.
  • The API needs internet. It will not work if you are offline.
  • When in doubt, review official OpenAI documentation for updates.
# Challenge 1: Try another OpenAI endpoint
# Use the chat endpoint to ask "What is the capital of France?"
challenge_resp = client.chat.completions.create(
    model='gpt-4.1-mini',
    messages=[{"role": "user", "content": "What is the capital of France?"}]
)
print('Challenge 1 answer:', challenge_resp.choices[0].message.content)
Challenge 1 answer: The capital of France is Paris.
# Challenge 2: Try embeddings with your own text
your_text = input("Type a sentence you want to embed: ")
my_embed = client.embeddings.create(
    model='text-embedding-3-small',
    input=[your_text]
)
print("Challenge 2: Your embedding vector length is:", len(my_embed.data[0].embedding))
Challenge 2: Your embedding vector length is: 1536

What you learned today#

  • How to set up and connect to the OpenAI API in Python.
  • Sending chat, completion, and embedding requests.
  • Using the API for speech to text and text to speech.
  • Best practices for beginners.
  • You built a simple chatbot and solved hands-on challenges!
  • Keep exploring and inventing new things.

Subscribe for more hands-on Python and AI lessons!#

  • Like, subscribe, and comment if you enjoyed this video.
  • Share what you build and keep learning.
  • See you in the next lesson!

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.