Lesson 14 · OpenAI
Master the OpenAI Assistants API: Build Interactive & Intelligent Python Applications
Welcome to this beginner friendly lesson! We will explore how to connect Python with the OpenAI API. You will learn about setup, safety, practical examples,…
- CourseOpenAI
- Lesson14 of 14
- Video23 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 .ipynbIntroduction to the OpenAI API in Python#
- Welcome to this beginner friendly lesson!
- We will explore how to connect Python with the OpenAI API.
- You will learn about setup, safety, practical examples, and hands-on exercises.
- Let us get started.
What is the OpenAI API?#
- The OpenAI API lets your Python code talk to powerful AI models.
- You can generate text, chat, analyze data, and more.
- Imagine asking a computer questions, and it responds like a helpful person.
- The API makes these conversations possible.
Why Learn the OpenAI API?#
- The OpenAI API opens doors to smart chatbots, automation, and creative tools.
- Learning these skills can help in jobs, research, and personal projects.
- Anyone can use the API with basic Python knowledge.
Setup: Requirements & Installation#
- You need Python 3.8 or newer installed.
- You need an OpenAI account with an API key.
- The "openai" Python library must be installed.
- Let us check how to set it up now.
import numpy as np
np.random.seed(42)
# Install the official OpenAI SDK if you do not have it
!pip install --upgrade openai
import warnings; warnings.filterwarnings("ignore")
# Always import the OpenAI client in your script
from openai import OpenAI
# Import os to read keys from your environment
import os
# Your API key should be in your environment already
API_key = os.environ["OPENAI_API_KEY"]
# Create an OpenAI client using your key
client = OpenAI(api_key=API_key)
OpenAI Client: Key Safety Tips#
- Never share your API key with anyone.
- Do not hardcode the key in scripts; use environment variables.
- Keys allow billing and control your account usage.
- Treat your API key like a password.
# Let us try a simple chat completion call
response = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[{"role": "user", "content": "Hello!"}]
)
print(response.choices[0].message.content)
How Does It Work?#
- The "messages" list tells the AI what you want.
- The "model" value picks which AI you use.
- The AI then predicts a response and sends it back.
- You only need to print it to view what is generated.
# Let us try asking a question about Python
response = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[{"role": "user", "content": "What is a function in Python?"}]
)
print(response.choices[0].message.content)
# Try changing the user message to see different responses
my_message = input("What do you want to ask the AI? ")
response = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[{"role": "user", "content": my_message}]
)
print("AI says:", response.choices[0].message.content)
Exploring Model Options#
- Different models have different strengths and costs.
- Use "gpt-4.1-mini" for fast, basic replies.
- Use "gpt-4.1" or larger for higher quality answers.
- Check the latest OpenAI docs for model details.
# Use the Responses endpoint to get useful completions
resp = client.responses.create(
model="gpt-4.1-mini",
input="Explain embeddings in one sentence."
)
print(resp.output[0].content[0].text)
# Get text embeddings (vector representations) from your input
embed = client.embeddings.create(
model="text-embedding-3-small",
input=["Machine learning is fun"]
)
print(len(embed.data[0].embedding))
# Speech to text: transcribe audio to written words
audio_file = open('sample.wav', 'rb')
transcript = client.audio.transcriptions.create(
model='whisper-1',
file=audio_file
)
print(transcript.text)
# Text to speech: turn text into spoken voice
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())
# Use function calling to let AI trigger your code
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)
# Create an assistant using the beta Assistants API
assistant = client.beta.assistants.create(
name='Tutor',
model='gpt-4.1',
instructions='You provide educational help.'
)
print(assistant.id)
Handling Errors Carefully#
- The API may raise exceptions for network problems or wrong keys.
- Wrap your calls in try-except to handle these safely.
- This will avoid crashes in your script.
- Let us see an example in code.
# Use try-except to safely catch API errors
try:
response = client.chat.completions.create(
model='gpt-4.1-mini',
messages=[{"role": "user", "content": "Hello!"}]
)
print(response.choices[0].message.content)
except Exception as e:
print("Something went wrong:", e)
# Challenge 1: Ask the AI to summarize a short story you provide
user_story = input("Type a short story for the AI to summarize: ")
summary = client.chat.completions.create(
model='gpt-4.1-mini',
messages=[
{"role": "user", "content": f"Summarize this story: {user_story}"}
]
)
print("AI summary:", summary.choices[0].message.content)
# Challenge 2: Use the API to turn instructions into a list
instructions = input("Enter instructions, comma separated: ")
task = client.chat.completions.create(
model='gpt-4.1-mini',
messages=[
{"role": "user", "content": f"Turn these instructions into a numbered list: {instructions}"}
]
)
print("List:", task.choices[0].message.content)
Mini Project: Build a Simple Python Study Assistant#
- We will make a chat assistant that answers your Python questions.
- Your assistant will remember your questions in a loop.
- Type "quit" to stop the conversation.
- Let us write the code for your assistant!
# Python Study Assistant: Q and A loop
print("Ask a Python question, or type 'quit' to stop.")
while True:
question = input("You: ")
if question.lower() == "quit":
print("Goodbye!")
break
answer = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[
{"role": "user", "content": question}
]
)
print("Assistant:", answer.choices[0].message.content)
Troubleshooting Tips#
- Check your API key if you see authentication errors.
- Make sure the openai library is up to date.
- Look at error messages for clues if your script fails.
- Check your internet connection before making API calls.
Recap: What Did You Learn?#
- You learned how to install, set up, and use the OpenAI API with Python.
- You explored chat, completions, embeddings, audio, and assistants.
- You wrote code, handled errors, and built a Python study assistant.
- Keep practicing to become confident with AI APIs!
Thank You and Next Steps!#
- Great work on finishing this lesson.
- Like, subscribe, and leave your questions below.
- Try new ideas and share your projects.
- See you in the next tutorial!
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



