Mathew K Analytics

Lesson 3 · OpenAI

Mastering OpenAI Models: Enhance AI Responses with Python Embeddings

Welcome to your guide for getting started You will learn step by step how to use the OpenAI API Let us get started! The OpenAI API lets you interact with…

⬇ 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

Learn the OpenAI API in Python#

  • Welcome to your guide for getting started
  • You will learn step by step how to use the OpenAI API
  • Let us get started!

What is the OpenAI API?#

  • The OpenAI API lets you interact with advanced AIs using Python
  • You can generate text, summarize, answer questions, work with images, and more
  • OpenAI's models help you build apps that can "think" like a human
import warnings; warnings.filterwarnings("ignore")
import numpy as np
np.random.seed(42)
# Suppress warning messages for a cleaner experience

Setting up: Install OpenAI library#

  • Before you can use OpenAI, make sure the library is installed
  • Usually, you run pip install openai in the terminal
  • We will use it directly in this notebook
# Import the required OpenAI library
from openai import OpenAI
# Create an OpenAI client instance
client = OpenAI()

About your API key#

  • Your API key lets you use OpenAI services
  • It is stored securely in environment settings
  • You do NOT need to type in a key during this lesson
# Access your OpenAI API key from environment settings
import os
API_key = os.environ["OPENAI_API_KEY"]

What can the OpenAI API do?#

  • Generate chat messages and answers
  • Summarize and rewrite text
  • Turn speech into text and vice versa
  • Analyze or embed information into numbers
  • Power chatbots, assistants, and smart apps

Core idea: Chat completions#

  • The chat completion is how you talk to the model
  • You send messages, and the AI sends back a reply
  • You choose the model size: large models are smarter but slower
# Basic Chat Completion
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 help you today?

Try it: Ask anything!#

  • Let us ask the AI something new in your own words
  • You can type any question or prompt you want
  • The AI will do its best to answer
# Prompt the user for a question to ask the model
user_prompt = input("Type your question to AI: ")
response2 = client.chat.completions.create(
    model='gpt-4.1-mini',
    messages=[{"role": "user", "content": user_prompt}]
)
print(response2.choices[0].message.content)
AI is increasingly integrated into many aspects of daily life, enhancing convenience, efficiency, and personalization. Here are some common uses of AI in everyday activities:

1. **Virtual Assistants:** AI-powered assistants like Siri, Google Assistant, and Alexa help with tasks such as setting reminders, checking the weather, playing music, and answering questions.

2. **Personalized Recommendations:** Streaming services (Netflix, Spotify), shopping platforms (Amazon), and social media (Instagram, Facebook) use AI to suggest content, products, or connections based on your preferences and behavior.

3. **Smart Home Devices:** AI enables smart thermostats, lights, security cameras, and appliances to learn your habits and optimize energy use, enhance security, or improve convenience.

4. **Navigation and Travel:** GPS apps (Google Maps, Waze) use AI to analyze traffic data in real-time and provide efficient routes or estimated arrival times.

5. **Communication:** Email services use AI to filter spam and categorize messages; predictive text and speech recognition improve typing and accessibility.

6. **Health and Fitness:** Wearable devices and apps track activity, monitor vital signs, and provide personalized health insights or coaching.

7. **Financial Management:** AI helps detect fraudulent transactions, manage budgets, and provide investment advice via robo-advisors.

8. **Customer Service:** AI chatbots provide instant support on websites and apps, answering common questions or troubleshooting issues.

9. **Photography:** Smartphone cameras use AI for scene recognition, enhancing image quality, and facial recognition for organizing photos.

10. **Education:** AI-powered apps offer personalized learning experiences, language translation, and tutoring support.

These examples show how AI makes daily tasks easier, more efficient, and more tailored to individual needs.

Quick tip: Choosing models#

  • OpenAI offers different models for speed and power
  • Small models are fast and cheap
  • Large models can answer complex questions but may cost more
# Try changing the model to a bigger one
response_big = client.chat.completions.create(
    model='gpt-4.1',
    messages=[{"role": "user", "content": "Tell me a fun fact about space."}]
)
print(response_big.choices[0].message.content)
Sure! Here’s a fun fact: 

**A day on Venus is longer than a year on Venus!**  
It takes Venus about 243 Earth days to rotate once on its axis (that's one Venus day), but only about 225 Earth days to orbit the Sun (one Venus year). So, surprisingly, a day on Venus is longer than its year!
# Handle model errors gracefully
try:
    bad_response = client.chat.completions.create(
        model='nonexistent-model',
        messages=[{"role": "user", "content": "test"}]
    )
except Exception as error:
    print("There was an error: ", error)
There was an error:  Error code: 404 - {'error': {'message': 'The model `nonexistent-model` does not exist or you do not have access to it.', 'type': 'invalid_request_error', 'param': None, 'code': 'model_not_found'}}

Other OpenAI API abilities#

  • Summarization: shrink long text to short answers
  • Embeddings: turn sentences into vector numbers
  • Function calling: ask AI to trigger your code functions
  • Speech: convert voice to text, or text to audio
# Summarize a passage using the API
long_text = """OpenAI has developed language models that are helpful for students, teachers, and anyone who works with information. These tools can explain things, write emails, and help you find answers fast."""
summary = client.chat.completions.create(
    model='gpt-4.1-mini',
    messages=[{"role": "user", "content": f"Summarize: {long_text}"}]
)
print(summary.choices[0].message.content)
OpenAI has created language models that assist students, teachers, and information workers by explaining concepts, writing emails, and quickly providing answers.
# Get an embedding for a short sentence
embed = client.embeddings.create(
    model='text-embedding-3-small',
    input=['Machine learning is fun']
)
print(len(embed.data[0].embedding))
1536
# Use function calling to let AI add numbers
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-Chf5GI8K6dVRSsFgf1uihbkbWp3Mx', 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=1764522066, 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)))
# Convert speech to text (requires a .wav file named sample.wav)
audio_file = open('sample.wav', 'rb')
transcript = client.audio.transcriptions.create(
    model='whisper-1',
    file=audio_file
)
print(transcript.text)
Welcome to OpenAI.
# Convert text to speech (requires playing audio)
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())

print("Audio saved as voice.mp3")
Audio saved as voice.mp3

PROJECT: Your own chatbot#

  • Let us build a simple chatbot that replies to your questions
  • This will show how to use a chat loop with OpenAI
  • You can keep chatting until you say stop
# Simple chatbot loop: ask until you type 'stop'
print("Chatbot online! Type 'stop' to end.")
while True:
    user_msg = input("You: ")
    if user_msg.strip().lower() == 'stop':
        print("Chatbot stopped.")
        break
    reply = client.chat.completions.create(
        model='gpt-4.1-mini',
        messages=[{"role": "user", "content": user_msg}]
    )
    print("AI:", reply.choices[0].message.content)
Chatbot online! Type 'stop' to end.
AI: I'm doing great, thank you! How can I assist you today?
AI: Sure! Here's one for you:

Why did the scarecrow win an award?  
Because he was outstanding in his field!
Chatbot stopped.

Troubleshooting tips#

  • If you see errors, check your API key or spelling
  • If responses are slow, try a smaller model
  • If audio does not work, check the file name and format

Challenge: Generate a vacation plan#

  • Write code to ask the AI for a 3-day vacation itinerary to Paris
  • Print the result

Challenge: Help with study tips#

  • Use the API to generate 5 helpful study tips
  • Try customizing the output style

Recap: What you have learned#

  • How to set up and use the OpenAI API
  • How chat completions work
  • How to handle errors and troubleshoot
  • How to use advanced features like speech and functions

Thanks for learning OpenAI in Python!#

  • Try more ideas and keep exploring
  • Subscribe for more coding lessons
  • Happy coding!

Found this useful?

All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.