Mathew K Analytics

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…

⬇ 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

Welcome 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)
 
Hello! How can I assist you today?
# 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)
 
Artificial intelligence is the development of computer systems that can perform tasks typically requiring human intelligence, such as learning, reasoning, and problem-solving.
# 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)
 
An API key is a unique identifier used to authenticate and authorize access to an application programming interface (API). It helps control and monitor how the API is used, ensuring that only authorized users or systems can make requests. API keys are typically included in API requests to track usage, prevent abuse, and provide access management.
# 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)
 
Some OpenAI models: ['gpt-4o', 'gpt-4.1', 'gpt-4.1-mini', 'text-embedding-3-small', 'whisper-1', 'gpt-4o-mini-tts']
# 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))
 
1536
# 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)
 
Welcome to OpenAI.
# 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)
 
Something went wrong: Error code: 404 - {'error': {'message': 'The model `bad-model-name` does not exist or you do not have access to it.', 'type': 'invalid_request_error', 'param': None, 'code': 'model_not_found'}}
# 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)
 
Round number 0.
Round number 1.
Round number 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)
 
Looks correct: The capital of France is Paris.
# 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)
 
ChatCompletion(id='chatcmpl-ChNZQHYhNjwLKKTkDwEOtAX7GNiB7', 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=1764454744, 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)))
# 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)
 
ChatCompletion(id='chatcmpl-ChNbS712zDg6xbyAY9aQMC56urxJd', 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":7,"b":9}', name='add'), tool_calls=None))], created=1764454870, 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)))
# 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)
 
Sure! Here's a classic one for you:

Why do programmers prefer dark mode?

Because light attracts bugs! 🐛😄

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.