Mathew K Analytics

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.…

⬇ 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 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)
Hello! How can I assist you today?

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)
The sky appears blue because of a phenomenon called **Rayleigh scattering**. When sunlight enters Earth’s atmosphere, it is made up of different colors of light, each with different wavelengths. The shorter wavelengths (blue and violet light) are scattered in all directions by the gases and particles in the atmosphere much more than the longer wavelengths (like red and yellow).

Although violet light is scattered even more than blue, our eyes are more sensitive to blue light and less sensitive to violet. Also, some of the violet light is absorbed by the upper atmosphere. As a result, the scattered light that predominantly reaches our eyes from all directions in the sky is blue, making the sky appear blue during the day.

In short: the sky is blue because molecules in the air scatter blue light from the sun more than they scatter other colors.
# 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)
The capital of France is Paris.

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 are numerical vector representations of data, such as words or images, that capture their semantic meaning and relationships in a continuous space.

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))
1536

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)
Hi! How can I assist you today?

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))
Tutor says: In Python, a variable is a name that refers to a value stored in the computer's memory. It acts like a container that holds data which can be used and changed throughout a program. You create a variable by giving it a name and assigning it a value using the equals sign (`=`).

For example:

```python
age = 25
name = "Alice"
temperature = 36.6
```

Here, `age`, `name`, and `temperature` are variables storing an integer, a string, and a floating-point number, respectively. You can use these variables later in your program to access or modify their values.

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)
Sure! An elephant is a very big animal that lives in places like Africa and Asia. It has thick, gray skin and big, floppy ears. One special thing about elephants is their long nose called a trunk, which they use to smell, grab things, and even spray water. Elephants have big tusks made of ivory, which look like long, curved teeth. They are very strong and gentle animals and often live in groups called herds. Elephants also like to eat plants, leaves, and fruits. They are one of the biggest animals that live on land!
# 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)
Photosynthesis is like a magic trick that plants do! They take sunlight, water, and air, and turn them into food to grow big and strong. It's how plants eat!

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.