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…
- CourseOpenAI
- Lesson19 of 14
- Video16 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 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
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)
# 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)
# 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)
# 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))
# 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)
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()
# 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)
# 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)
# 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))
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.



