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…
- CourseOpenAI
- Lesson2 of 14
- Video20 min
- FormatJupyter notebook · 14 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbIntroduction 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)
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
# 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.")
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)
# 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)
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))
# 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)
# 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)
# 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)
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)
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 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))
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.



