Mathew K Analytics

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

⬇ 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 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
Requirement already satisfied: openai in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (2.8.1)
Requirement already satisfied: anyio<5,>=3.5.0 in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from openai) (4.9.0)
Requirement already satisfied: distro<2,>=1.7.0 in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from openai) (1.9.0)
Requirement already satisfied: httpx<1,>=0.23.0 in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from openai) (0.28.1)
Requirement already satisfied: jiter<1,>=0.10.0 in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from openai) (0.12.0)
Requirement already satisfied: pydantic<3,>=1.9.0 in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from openai) (2.11.9)
Requirement already satisfied: sniffio in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from openai) (1.3.1)
Requirement already satisfied: tqdm>4 in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from openai) (4.67.1)
Requirement already satisfied: typing-extensions<5,>=4.11 in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from openai) (4.15.0)
Requirement already satisfied: idna>=2.8 in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from anyio<5,>=3.5.0->openai) (3.10)
Requirement already satisfied: certifi in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from httpx<1,>=0.23.0->openai) (2025.8.3)
Requirement already satisfied: httpcore==1.* in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from httpx<1,>=0.23.0->openai) (1.0.8)
Requirement already satisfied: h11<0.15,>=0.13 in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from httpcore==1.*->httpx<1,>=0.23.0->openai) (0.14.0)
Requirement already satisfied: annotated-types>=0.6.0 in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from pydantic<3,>=1.9.0->openai) (0.7.0)
Requirement already satisfied: pydantic-core==2.33.2 in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from pydantic<3,>=1.9.0->openai) (2.33.2)
Requirement already satisfied: typing-inspection>=0.4.0 in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from pydantic<3,>=1.9.0->openai) (0.4.0)
Requirement already satisfied: colorama in c:\users\makmw\appdata\local\programs\python\python312\lib\site-packages (from tqdm>4->openai) (0.4.6)
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)
Hello! How can I assist you today?

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)
In Python, a **function** is a reusable block of code that performs a specific task. Functions help organize code, make it more readable, and avoid repetition by allowing you to call the same code multiple times from different places in your program.

### Defining a Function
You define a function using the `def` keyword, followed by the function name, parentheses `()`, and a colon `:`. Inside the function, you write the code that you want to execute when the function is called.

```python
def greet():
    print("Hello, world!")
```

### Calling a Function
After defining a function, you can call it by using its name followed by parentheses:

```python
greet()  # This will output: Hello, world!
```

### Functions with Parameters
Functions can take inputs called parameters or arguments to perform operations based on those inputs:

```python
def greet(name):
    print("Hello, " + name + "!")

greet("Alice")  # Output: Hello, Alice!
```

### Returning Values
Functions can also return values using the `return` statement:

```python
def add(a, b):
    return a + b

result = add(3, 5)
print(result)  # Output: 8
```

---

**In summary:**  
A function in Python is a named block of code designed to perform a specific action, possibly taking inputs and optionally returning a result. Functions improve code modularity and reusability.
# 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)
AI says: Weather is the condition of the atmosphere at a particular place and time, including factors like temperature, humidity, wind, and precipitation. It results from complex interactions between the sun, the Earth's atmosphere, bodies of water, and land.

Here’s a basic overview of how weather works:

1. **Energy from the Sun:** The sun heats the Earth's surface unevenly because of the planet's tilt and varying surface materials (water, land, ice). This uneven heating causes temperature differences.

2. **Air Movement:** Warm air rises because it is less dense, and cooler air sinks. This movement creates wind and air currents. As warm air rises, it cools and can cause moisture to condense, forming clouds.

3. **Water Cycle:** Water evaporates from oceans, lakes, and other bodies of water, turning into water vapor. As the moist air rises and cools, the vapor condenses into droplets, forming clouds. Eventually, these droplets can fall as precipitation (rain, snow, sleet, or hail).

4. **Pressure Systems:** Areas of high and low pressure form as air temperature and density vary. Low-pressure areas usually bring clouds and storms, while high-pressure areas tend to bring clear skies.

5. **Local Geography:** Mountains, oceans, and other features influence local weather patterns by affecting wind, humidity, and temperature.

All these factors combine constantly, causing changing weather conditions that we experience daily. Meteorologists use instruments and models to understand and predict these changes.

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)
Embeddings are numerical vector representations of data that capture its semantic meaning, enabling machines to process and compare complex information like words, images, or graphs efficiently.
# 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))
1536
# 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)
Welcome to OpenAI.
# 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)
ChatCompletion(id='chatcmpl-ChWOergEH6HDXqD1fz5GoCVXKdVDq', choices=[Choice(finish_reason='function_call', index=0, logprobs=None, message=ChatCompletionMessage(content=None, refusal=None, role='assistant', annotations=[], audio=None, function_call=FunctionCall(arguments='{"a":3,"b":5}', name='add'), tool_calls=None))], created=1764488672, model='gpt-4.1-2025-04-14', object='chat.completion', service_tier='default', system_fingerprint='fp_09249d7c7b', usage=CompletionUsage(completion_tokens=17, prompt_tokens=50, total_tokens=67, completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=0, audio_tokens=0, reasoning_tokens=0, rejected_prediction_tokens=0), prompt_tokens_details=PromptTokensDetails(audio_tokens=0, cached_tokens=0)))
# 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)
asst_fXK0SeXcG1NVyDsnCyX86kJg

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)
Hello! How can I assist you today?
# 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)
AI summary: The story describes a walk to the park where the narrator observed ducks playing in the pond.
# 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)
List: 1. Buy groceries  
2. Finish homework  
3. Walk the dog  
4. Call a friend

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)
Ask a Python question, or type 'quit' to stop.
Assistant: A **for loop** is a control flow statement used in programming to repeat a block of code a certain number of times or iterate over a sequence (like a list, array, or range). It allows you to automate repetitive tasks without writing the same code multiple times.

### Basic idea:
- Initialize a variable (often called a loop counter).
- Check a condition to see if the loop should continue.
- Execute the block of code inside the loop.
- Update the loop variable (like incrementing the counter).
- Repeat until the condition is no longer true.

### Example in Python:

```python
for i in range(5):
    print(i)
```

This loop will print numbers 0 to 4. Here, `range(5)` generates the sequence `[0, 1, 2, 3, 4]`, and the loop variable `i` takes on each value in sequence.

### For loop syntax varies in different languages but generally has similar components:

- **Initialization:** Set the loop variable.
- **Condition:** Determine when to stop looping.
- **Iteration:** Change the loop variable each time through the loop.

### Example in C:

```c
for (int i = 0; i < 5; i++) {
    printf("%d\n", i);
}
```

### Summary:
A **for loop** efficiently repeats code a specified number of times or iterates over items in a collection, making your programs more concise and easier to manage.
Assistant: Sure! I can help you make a list. What kind of list would you like to create? For example, a shopping list, a to-do list, a list of ideas, or something else? Let me know!
Goodbye!

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.