Lesson 16 · OpenAI
Managing Errors and Rate Limits in OpenAI API Integrations for Reliable Applications
Learn how to use artificial intelligence models in your code. We will cover setup, safe use, and real-world examples. No experience needed we start from the…
- CourseOpenAI
- Lesson16 of 14
- Video25 min
- FormatJupyter notebook · 18 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbWelcome to the OpenAI API with Python#
- Learn how to use artificial intelligence models in your code.
- We will cover setup, safe use, and real-world examples.
- No experience needed we start from the basics.
What is the OpenAI API?#
- The OpenAI API lets you access advanced AI directly from your programs.
- You can use it for chatbots, writing help, audio, and more.
- It connects your code to powerful machine learning models.
Why should you learn the OpenAI API?#
- AI skills will help you automate boring tasks.
- Get creative by building apps with language, vision, or audio understanding.
- Stand out with real world AI projects in your portfolio.
# Suppress extra warning messages to keep things clean
import warnings; warnings.filterwarnings("ignore")
import numpy as np
np.random.seed(42)
# Install the OpenAI package so we can use the API
!pip install --quiet openai
# Always import the package before using it
from openai import OpenAI
import os
# Get the API key from your environment
API_key = os.environ["OPENAI_API_KEY"]
# Make the OpenAI client instance for talking to the API
client = OpenAI(api_key=API_key)
Key Concepts Prompts, Models, Completion#
- Prompt: The message you send to the AI.
- Model: The brain that answers you, such as gpt-4o or gpt-4.1.
- Completion: The AI's written reply to your message.
- We use a 'messages' list for chat style AI, or just 'input' for quick answers.
# Basic Chat Completion Hello World
response = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[{"role": "user", "content": "Hello!"}]
)
print(response.choices[0].message.content)
# Try changing the prompt
prompt = input("What do you want to ask the chat model? ")
custom_response = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[{"role": "user", "content": prompt}]
)
print(custom_response.choices[0].message.content)
# Let's try the responses endpoint for single answer tasks
resp = client.responses.create(
model="gpt-4.1-mini",
input="Summarize what an API key is."
)
print(resp.output[0].content[0].text)
# What other models are available?
available_models = [
"gpt-4o",
"gpt-4.1",
"gpt-4.1-mini",
"text-embedding-3-small",
"whisper-1",
"gpt-4o-mini-tts",
]
print("Some OpenAI models:", available_models)
# Get vector embeddings for search and machine learning
embed = client.embeddings.create(
model="text-embedding-3-small",
input=["Machine learning is fun"]
)
print(len(embed.data[0].embedding))
# Speech to text with Whisper
audio_file = open('sample.wav', 'rb')
transcript = client.audio.transcriptions.create(
model="whisper-1",
file=audio_file
)
print(transcript.text)
# Turn text into speech with TTS
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())
Error Handling How to Handle Mistakes#
- AI models can fail if prompts or keys are wrong.
- Always check responses before using them.
- Use try-except to catch and explain errors for users.
# Example: Catching an API error
try:
broken_response = client.chat.completions.create(
model="bad-model-name",
messages=[{"role": "user", "content": "hi"}]
)
except Exception as error:
print("Something went wrong:", error)
# API Rate Limits Slow down if you send too many requests
import time
for i in range(3):
try:
short_resp = client.responses.create(
model="gpt-4.1-mini",
input="Say round number {}.".format(i))
print(short_resp.output[0].content[0].text)
except Exception as e:
print("Please wait. Error:", e)
time.sleep(2)
# Best Practice: Always check your replies
out = client.responses.create(
model="gpt-4.1-mini",
input="What is the capital of France?"
)
answer = out.output[0].content[0].text
if answer and "Paris" in answer:
print("Looks correct:", answer)
else:
print("Unexpected answer:", answer)
# Mini Project: Make a Function Calling Chatbot
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)
# Challenge: Ask the user for their own math question
user_math = input("Give me a math question to solve, like 'Add 10 and 15': ")
math_response = client.chat.completions.create(
model="gpt-4.1",
messages=[{"role": "user", "content": user_math}],
functions=[
{
"name": "add",
"description": "Add two numbers",
"parameters": {
"type": "object",
"properties": {
"a": {"type": "number"},
"b": {"type": "number"}
},
"required": ["a", "b"]
}
}
],
function_call="auto"
)
print(math_response)
# Challenge: Make OpenAI tell a joke
joke_resp = client.responses.create(
model="gpt-4.1-mini",
input="Tell me a funny programming joke."
)
print(joke_resp.output[0].content[0].text)
Recap What have you learned?#
- How to talk to OpenAI models using Python.
- The use of chat, short answers, speech, and functions.
- Best practices for safety, error handling, and experiments.
- You can now start building AI apps and projects.
Try it yourself and subscribe for more!#
- Play with the code and come up with your own prompts.
- Share your projects and results with us.
- Subscribe for more AI lessons and hands-on tutorials.
- You can do this AI is for everyone!
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



