Mathew K Analytics

Lesson 19 · OpenAI

How to Diagnose and Resolve Common OpenAI API Issues for Reliable Integration

Welcome to your first hands-on journey with the OpenAI API. You will learn how to perform basic operations with modern AI in Python. No previous API…

⬇ 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 hands-on journey with the OpenAI API.
  • You will learn how to perform basic operations with modern AI in Python.
  • No previous API experience is needed for this lesson.
  • Let us get started!

What is the OpenAI API?#

  • The OpenAI API lets your programs interact with smart language and media models.
  • These models can understand text, generate content, and much more.
  • API stands for Application Programming Interface.
  • You will use Python to send instructions to the API and receive results.
import warnings; warnings.filterwarnings("ignore")
import numpy as np
np.random.seed(42)
# We turn off Python warnings for a cleaner learning experience

Preparing Your Environment#

  • Before using the OpenAI API, you need a few things ready:
  • An OpenAI account and API key
  • Python installed on your machine (version 3.7 or higher is recommended)
  • The openai Python package
  • Your API key is set as an environment variable for security
# If you have not installed the openai package, use this command in your terminal:
print('pip install openai')

# You will not run this in Python, but in your command line or Anaconda prompt
pip install openai
import os
from openai import OpenAI

# Now you have the tools and modules needed for OpenAI access
# Securely load your API key from the system environment
API_key = os.environ["OPENAI_API_KEY"]

# This way, your private key is not shown directly in your code.
# Initialize the OpenAI client for API calls
client = OpenAI(api_key=API_key)

# This client is your gateway to talk with OpenAIs models

Exploring Safe API Usage#

  • Never share your API key publicly.
  • Watch out for automation that sends too many requests too quickly.
  • Always review the output, especially before using it in important tasks.
  • Keep your software and packages updated.
# Let us try a basic chat completion using the OpenAI API
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?
# Let us send a custom question to the chat model
user_message = input("Type your question for the AI: ")

chat_response = client.chat.completions.create(
    model='gpt-4.1-mini',
    messages=[{"role": "user", "content": user_message}]
)
print(chat_response.choices[0].message.content)
Artificial intelligence (AI) is a branch of computer science focused on creating systems or machines that can perform tasks typically requiring human intelligence. These tasks include learning, reasoning, problem-solving, understanding natural language, recognizing patterns, and making decisions. AI can range from simple algorithms to advanced models like machine learning and deep learning, enabling computers to improve their performance over time without being explicitly programmed for every specific task.
# Using the Responses endpoint for direct completions
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, images, or sentences—that capture their meaningful features and relationships in a continuous, low-dimensional space.
# Let us see how embeddings work with the OpenAI API
embed = client.embeddings.create(
    model='text-embedding-3-small',
    input=['Machine learning is fun']
)
print(len(embed.data[0].embedding))
1536
# Simple error handling: What if something goes wrong?
try:
    bad_client = OpenAI(api_key="wrong_key")
    bad_client.chat.completions.create(
        model='gpt-4.1-mini',
        messages=[{"role": "user", "content": "Hello"}]
    )
except Exception as e:
    print("An error happened:", e)
An error happened: Error code: 401 - {'error': {'message': 'Incorrect API key provided: wrong_key. You can find your API key at https://platform.openai.com/account/api-keys.', 'type': 'invalid_request_error', 'param': None, 'code': 'invalid_api_key'}}

Best Practices When Using the OpenAI API#

  • Keep your API key safe and never post it online.
  • Use environment variables for secrets, not hardcoding.
  • Add error handling so your program keeps running if there is a problem.
  • Start with smaller models to avoid high costs while testing.
  • Check your usage and understand the billing details.
# Mini Project: Make the AI a helpful chatbot
def simple_chat():
    print("Type 'bye' to stop chatting.")
    while True:
        user = input("You: ")
        if user.lower() == "bye":
            print("Chat ended.")
            break
        reply = client.chat.completions.create(
            model='gpt-4.1-mini',
            messages=[{"role": "user", "content": user}]
        )
        print("AI:", reply.choices[0].message.content)

simple_chat()
Type 'bye' to stop chatting.
AI: Using Python involves writing and running Python code to perform tasks or solve problems. Here's a beginner-friendly guide to get you started:

### 1. Install Python
- **Download Python** from the official website: [python.org](https://www.python.org/downloads/)
- Follow the installation instructions for your operating system (Windows, macOS, Linux).
- Make sure to check the option to **add Python to your system PATH** during installation on Windows.

### 2. Write Python Code
You can write Python code in various ways:

- **Interactive Mode (REPL):**
  - Open your terminal (Command Prompt, PowerShell, Terminal).
  - Type `python` or `python3` and press Enter.
  - You can type Python commands directly and see their output immediately.
  
- **Script Mode:**
  - Use a text editor (like Notepad, VS Code, Sublime Text) or an IDE (like PyCharm).
  - Save your Python code in a file with a `.py` extension. For example, `hello.py`.
  - Example content of `hello.py`:
    ```python
    print("Hello, world!")
    ```
    
### 3. Run Python Code
- If you used a script file (`hello.py`), run it from the terminal:
  ```bash
  python hello.py
  ```
- If you are in interactive mode, your code runs as soon as you press Enter.

### 4. Learn Python Basics
Here are some fundamental concepts to start with:
- Variables and Data Types (`int`, `float`, `str`, `bool`)
- Control Flow (`if`, `else`, `elif`, loops)
- Functions (`def` keyword)
- Lists, Tuples, Dictionaries
- Modules and Packages (importing libraries)

### Example of a simple Python program:
```python
name = input("Enter your name: ")
print(f"Hello, {name}!")
```

### 5. Use Resources to Learn More
- [Official Python Tutorial](https://docs.python.org/3/tutorial/)
- Online courses like Codecademy, Coursera, Udemy
- Practice sites like LeetCode, HackerRank

---

If you want, I can help you write specific Python code or explain any concept in more detail!
Chat ended.
# Troubleshooting: Common issues with the OpenAI API
try:
    response = client.chat.completions.create(
        model='gpt-4.1-mini',
        messages=[{"role": "user", "content": "Test"}]
    )
    print("API is working!")
except Exception as error:
    print("If you see an error, check these:")
    print("Is your API key correct?")
    print("Are you connected to the internet?")
    print("Are you using the right model name?")
    print('Error details:', error)
API is working!
# Challenge Exercise 1: Try sending your own creative prompt
prompt = input("Give the AI a creative task to do: ")
result = client.chat.completions.create(
    model='gpt-4.1-mini',
    messages=[{"role": "user", "content": prompt}]
)
print(result.choices[0].message.content)
Beneath the velvet midnight skies,  
The stars like whispered secrets rise,  
Each tiny spark a timeless light,  
A dance of dreams within the night.
# Challenge Exercise 2: Experiment with another endpoint
sentence = input("Give me a sentence to turn into an embedding: ")
em = client.embeddings.create(
    model='text-embedding-3-small',
    input=[sentence]
)
print("Vector length:", len(em.data[0].embedding))
Vector length: 1536

Recap: What did you learn?#

  • You learned how to use the OpenAI API in Python.
  • You practiced making requests to chat and responses endpoints.
  • You discovered embeddings and how to handle errors.
  • You built a simple chatbot project.
  • You now know how to troubleshoot and safely use the API.

Thanks for learning! What is next?#

  • Try more OpenAI endpoints like audio transcription or text to speech.
  • Practice different prompts to see what the AI can do.
  • Watch other beginner projects on this channel.
  • If you enjoyed this lesson, please like and subscribe for more Python and AI tutorials!

Found this useful?

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