Lesson 6 · OpenAI
Master OpenAI Embeddings API with Effective Python Error Handling
This lesson will show how to use the OpenAI API for text embeddings in Python. No prior AI or coding experience is needed. Embeddings are a way of turning…
- CourseOpenAI
- Lesson6 of 14
- Video16 min
- FormatJupyter notebook · 10 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbGetting Started with the OpenAI Embeddings API#
This lesson will show how to use the OpenAI API for text embeddings in Python.
No prior AI or coding experience is needed.
Embeddings are a way of turning text into numbers for computers.
By the end, you will run your own embedding example!
Why Use Embeddings?#
Computers cannot understand text the way humans do.
Embeddings are vectors that let computers compare texts by meaning.
Embeddings help with search, recommendations, and more.
This is a basic building block for many real AI projects.
# Suppress any warning messages for a cleaner experience
import warnings; warnings.filterwarnings("ignore")
import numpy as np
np.random.seed(42)
# This keeps our notebook tidy and focused.
Installing the OpenAI API Library#
- To use the API, we need the openai package.
- If you do not have it, run pip install openai in your terminal.
- Once installed, you are ready for the next step.
# Let us import the key libraries
from openai import OpenAI
import os
# OpenAI is the main package for talking to the API.
# os lets us access environment variables safely.
# Set up your API key securely!
API_key = os.environ["OPENAI_API_KEY"]
client = OpenAI(api_key=API_key)
# This gives us a client we can use for all OpenAI requests.
What Are Embeddings?#
- An embedding is a list of numbers (a vector) that represents meaning.
- Similar text has embeddings close together. Unrelated text has embeddings far apart.
- With embeddings, you can find similar texts, cluster topics, and power smart search engines.
# Let us try our first embedding call!
texts = [
"OpenAI makes AI easy.",
"Machine learning is fun",
"Bananas are yellow."
]
embed = client.embeddings.create(
model='text-embedding-3-small',
input=texts
)
print("Number of texts embedded:", len(embed.data))
# What does an embedding look like?
embedding_vec = embed.data[0].embedding
print("First embedding vector (truncated):", embedding_vec[:10])
# Embeddings are lists of floats, which are just numbers.
Comparing Embeddings: Finding Similarity#
- You can measure how similar two texts are by comparing their embeddings.
- The math term for this is "cosine similarity".
- Higher values mean more similar. Lower values mean less related.
- Let us see this in action.
# Simple cosine similarity implementation
import math
def cosine_similarity(vec1, vec2):
dot = sum(a * b for a, b in zip(vec1, vec2))
norm1 = math.sqrt(sum(a * a for a in vec1))
norm2 = math.sqrt(sum(b * b for b in vec2))
return dot / (norm1 * norm2)
# Let us compute similarities between our texts
sim_0_1 = cosine_similarity(embed.data[0].embedding, embed.data[1].embedding)
sim_0_2 = cosine_similarity(embed.data[0].embedding, embed.data[2].embedding)
print("First vs Second text:", round(sim_0_1, 2))
print("First vs Third text:", round(sim_0_2, 2))
# Close scores mean the texts are related.
Best Practices for OpenAI Embeddings#
- Use small models for speed and cost unless you need higher quality.
- Remove extra spaces and odd characters from your text for better results.
- Store embeddings to save time and money later.
- Do not use full books, use short sentences or paragraphs.
- Never share your API key.
# Let us handle possible errors with our embedding call
try:
response = client.embeddings.create(
model='text-embedding-3-small',
input=["test"]
)
print("Success! Got an embedding.")
except Exception as e:
print("There was an error:", e)
Mini Project: Semantic Search Using Embeddings#
- Let us use embeddings to build a simple smart search.
- You type what you are looking for.
- The program finds the closest match in our texts.
# Take a search phrase from the user and find the best matching sentence
search = input("Type your search phrase: ")
search_embed = client.embeddings.create(
model='text-embedding-3-small',
input=[search]
)
sims = [cosine_similarity(search_embed.data[0].embedding, emb.embedding) for emb in embed.data]
best_idx = sims.index(max(sims))
print("Best match:", texts[best_idx])
# Quick troubleshooting tips if your code is not working
print("Check these if you get errors:")
print("- Is your OPENAI_API_KEY set in the environment?")
print("- Is your network connection active?")
print("- Did you spell model and function names correctly?")
Challenge 1: Try Your Own Sentences#
- Change the texts list to use your favorite sentences.
- Rerun the code and see what embeddings you get.
- What do you notice when comparing unrelated and related texts?
Challenge 2: Explore with New Search Phrases#
- Try typing different search phrases with the semantic search.
- Can you find different best matches?
- Try making the texts similar or very different and see what happens.
Recap: What You Learned#
- Set up your OpenAI API connection securely.
- Created text embeddings and saw what they look like.
- Compared how similar texts are using vectors.
- Built a mini semantic search engine!
Thank You for Learning with Us!#
- Try the code, change examples, and share your results!
- Subscribe for more AI tutorials and hands-on beginner guides.
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



