Lesson 17 · OpenAI
OpenAI Python Error Handling and API Best Practices
Welcome to your first lesson on using the OpenAI API. We will learn how to talk to AI models from your own Python code. Let us start by exploring what the…
- CourseOpenAI
- Lesson17 of 14
- Video4 min
- FormatJupyter notebook · 16 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbGetting Started with the OpenAI API in Python#
- Welcome to your first lesson on using the OpenAI API.
- We will learn how to talk to AI models from your own Python code.
- Let us start by exploring what the OpenAI API can do.
What is the OpenAI API?#
- The OpenAI API lets you access advanced artificial intelligence models.
- You can generate text, analyze meaning, and much more.
- All you need is an API key and an internet connection.
Why Use the OpenAI API?#
- It saves you from building huge AI models yourself.
- You can write simple code to solve hard problems.
- Many real world apps use this approach, like chatbots and voice tools.
import warnings; warnings.filterwarnings("ignore")
import numpy as np
np.random.seed(42)
# This line tells Python to ignore any warning messages.
Installing the openai Package#
- The openai library connects Python code to the OpenAI API.
- Let us check if it is installed.
- If not, we will install it together.
try:
import openai
except ImportError:
import sys
!{sys.executable} -m pip install openai
# We try to import openai.
# If it is not installed we install it automatically.
API Key: Keeping Your Credentials Safe#
- You need an API key to connect to OpenAI.
- The API key is like your personal password for the API.
- It is already saved in the environment, so we do not need to enter it here.
import os
# Let us fetch your API key from the environment safely.
API_key = os.environ["OPENAI_API_KEY"]
# We do not print out the API key to keep it secret.
Introducing the OpenAI Client#
- The openai library gives us a Client object.
- This object is our main tool to talk to the API.
- Let us start by creating a client instance.
from openai import OpenAI
client = OpenAI()
# OpenAI provides a client to connect and make requests.
# Creating the client does not send any data yet.
Key Concepts: Models, Prompts, and Responses#
- Model: The specific AI brain we use, like gpt-4.1-mini.
- Prompt: The message or question we send to the model.
- Response: The model's answer to our prompt.
- You can chat, summarize, generate code, and more.
# Let us try a simple chat completion request.
response = client.chat.completions.create(
model='gpt-4.1-mini',
messages=[{"role": "user", "content": "Hello!"}]
)
print(response.choices[0].message.content)
# Let us prompt the user for their name and greet them using ChatGPT.
user_name = input("What is your name? ")
message = f"Say hello to {user_name}!"
chat_response = client.chat.completions.create(
model='gpt-4.1-mini',
messages=[{"role": "user", "content": message}]
)
print(chat_response.choices[0].message.content)
Exploring Different Endpoints of the API#
- There are special API tools for different jobs.
- For example, you can ask for text, embeddings, sound, or run code.
- Let us try making text embeddings next.
# This creates an embedding for a short sentence.
embed = client.embeddings.create(
model='text-embedding-3-small',
input=['Machine learning is fun']
)
print(len(embed.data[0].embedding))
# Let us perform text to speech and get audio back.
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())
# Speech to text: transcribing an audio file.
audio_file = open('sample.wav', 'rb')
transcript = client.audio.transcriptions.create(
model='whisper-1',
file=audio_file
)
print(transcript.text)
# Let us use the Responses endpoint for precise output formatting.
resp = client.responses.create(
model='gpt-4.1-mini',
input='Explain embeddings in one sentence.'
)
print(resp.output[0].content[0].text)
# Handling errors the safe way.
try:
broken = client.chat.completions.create(
model='bad-model-name',
messages=[{"role": "user", "content": "Hi!"}]
)
except Exception as e:
print("Something went wrong:", e)
# A simple function call example with the API.
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)
Good Practices for the OpenAI API#
- Never share your API key. Protect it like a password.
- Test with small models at first. Upgrade models for higher quality when needed.
- Catch errors so your app does not crash if the network fails.
- Limit sensitive information sent to the API.
# Mini project: build a chatbot that remembers your favorite color.
color = input("What is your favorite color? ")
prompt = f"Remember my favorite color is {color}. What color did I say?"
rem_chat = client.chat.completions.create(
model='gpt-4.1-mini',
messages=[{"role": "user", "content": prompt}]
)
print('The bot remembers:', rem_chat.choices[0].message.content)
# Troubleshooting: missing key or network errors.
try:
test = client.chat.completions.create(
model='gpt-4.1-mini',
messages=[{"role": "user", "content": "Am I connected?"}]
)
print('Success! You are online.')
except Exception as error:
print('Connection failed:', error)
Challenge Exercise 1#
- Ask the user for a hobby.
- Have the chat API suggest one creative use for their hobby.
- Print the result.
# Here is a solution for Challenge 1.
hobby = input("What is your hobby? ")
hobby_prompt = f"Give me one creative way to use my hobby: {hobby}"
c_resp = client.chat.completions.create(
model='gpt-4.1-mini',
messages=[{"role": "user", "content": hobby_prompt}]
)
print(c_resp.choices[0].message.content)
Challenge Exercise 2#
- Write a function that asks the model to summarize any text you provide.
- Test the function with a few sample sentences of your choice.
# Solution for Exercise 2: summarize user provided text.
def ask_for_summary(text):
prompt = f"Summarize this: {text}"
result = client.chat.completions.create(
model='gpt-4.1-mini',
messages=[{"role": "user", "content": prompt}]
)
return result.choices[0].message.content
to_summarize = input("Type any text for summary: ")
print(ask_for_summary(to_summarize))
Recap of What You Learned#
- You explored different parts of the OpenAI API.
- You sent chat messages, made embeddings, voice, and handled errors.
- You also built mini projects and solved challenges.
- Great job reaching this milestone!
Want More? Subscribe and Keep Learning!#
- Try out your own creative projects with what you learned.
- Subscribe to the channel to stay updated on new Python lessons.
- See you next time!
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



