Lesson 18 · OpenAI
How to Build a Simple AI Assistant Using OpenAI and Python: Step-by-Step Tutorial
Welcome to your hands-on guide. We will learn how to use the OpenAI API to build smart assistants. No experience is needed. We will take each step slowly.…
- CourseOpenAI
- Lesson18 of 14
- Video22 min
- FormatJupyter notebook · 12 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 hands-on guide.
- We will learn how to use the OpenAI API to build smart assistants.
- No experience is needed. We will take each step slowly.
What is the OpenAI API?#
- The OpenAI API lets you talk to cutting edge artificial intelligence models.
- You can use it to create chatbots, language tools, and more.
- It is like a bridge that connects your program to the AI engine.
Setup Steps#
- You need Python installed on your computer.
- You will also need an OpenAI account with an API key.
- Your API key is saved to the environment for you.
- We will install the openai library next.
# Import warnings and suppress them.
import warnings; warnings.filterwarnings("ignore")
import numpy as np
np.random.seed(42)
# Make sure the openai library is installed.
!pip install --quiet openai
# Import needed libraries.
import os
from openai import OpenAI
# Access your OpenAI API key from the environment.
API_key = os.environ["OPENAI_API_KEY"]
# Create an OpenAI client to use models.
client = OpenAI(api_key=API_key)
Key Concepts: Prompts, Models, and Responses#
- Prompts are messages you send to the AI.
- The model is the specific brain that will answer your prompt.
- A response is what the AI sends back to you.
- You can choose different models for speed, cost, or smartness.
# Start a conversation using the Chat Completions endpoint.
response = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[{"role": "user", "content": "Hello!"}]
)
print(response.choices[0].message.content)
Handling More Complex Prompts#
- You can ask the AI to help with many topics.
- Try sending a longer question or a specific request.
- The AI will do its best to answer clearly.
# Send a more detailed question to the model.
user_question = "Why is the sky blue?"
response = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[{"role": "user", "content": user_question}]
)
print(response.choices[0].message.content)
# Try sending your own prompt.
your_text = input("Type a question for the AI assistant: ")
response = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[{"role": "user", "content": your_text}]
)
print(response.choices[0].message.content)
Using the Responses Endpoint#
- The responses endpoint is for completion, not chat.
- It answers single questions or generates text for you.
- Use it when you want one-time answers.
# Use the responses endpoint for a single prompt.
resp = client.responses.create(
model="gpt-4.1-mini",
input="Explain embeddings in one sentence."
)
print(resp.output[0].content[0].text)
Embeddings: Turning Text into Numbers#
- Embeddings are a way to turn text into lists of numbers.
- This helps computers compare words and meanings.
- Use embeddings for tasks like search or grouping similar ideas.
# Get embeddings for a sentence.
embed = client.embeddings.create(
model="text-embedding-3-small",
input=["Machine learning is fun"]
)
print(len(embed.data[0].embedding))
Error Handling and Safety#
- Always handle errors to avoid breaking your program.
- The API may fail if your key is wrong, or there is no internet.
- Use try and except to keep your code safe.
# Try to call the API, and catch errors if they happen.
try:
response = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[{"role": "user", "content": "Say Hi"}]
)
print(response.choices[0].message.content)
except Exception as e:
print("An error happened:", e)
Best Practices with the OpenAI API#
- Keep your API key private. Never share it.
- Handle errors to avoid crashing.
- Experiment with smaller models to save time and money.
- Always follow usage policies and limits.
# Mini Project: Build a simple tutoring assistant.
def get_tutor_response(question):
response = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[
{"role": "system", "content": "You are a helpful school tutor."},
{"role": "user", "content": question}
]
)
return response.choices[0].message.content
ask = input("Ask the Tutor Assistant a question: ")
print("Tutor says:", get_tutor_response(ask))
Troubleshooting Tips#
- Problems connecting? Check your internet.
- Errors about keys? Make sure your API key is set up.
- Model not found? Double check the model name.
- Check your spelling and indentation.
# Challenge 1: Get the model to describe an animal for a child.
animal = input("Pick an animal: ")
response = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[
{"role": "system", "content": "You explain things for children."},
{"role": "user", "content": f"Describe a {animal}."}
]
)
print(response.choices[0].message.content)
# Challenge 2: Ask the assistant to explain a tricky word.
hard_word = input("Type a hard word you want to understand: ")
response = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[
{"role": "system", "content": "You simplify complex words."},
{"role": "user", "content": f"Explain the word '{hard_word}' as if I am five years old."}
]
)
print(response.choices[0].message.content)
Recap: What You Learned#
- Connecting to the OpenAI API in Python.
- Sending chat and response prompts.
- Using embeddings to represent text.
- Handling errors and protecting your API key.
- Creating your own smart tutor.
Ready for More? Like and Subscribe!#
- Practice what you have learned by building simple helpers.
- Watch more tutorials to boost your skills.
- Ask your questions in the comments.
- Click like and subscribe for updates.
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



