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…
- CourseOpenAI
- Lesson3 of 14
- Video20 min
- FormatJupyter notebook · 14 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbLearn 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)
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)
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)
# 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)
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)
# 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))
# 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)
# 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)
# 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")
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)
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.



