Lesson 13 · OpenAI
Mastering OpenAI Tools API: Seamlessly Integrate External Apps with Python
Welcome! In this lesson you will learn how to use the OpenAI API in Python. The OpenAI API allows you to access powerful artificial intelligence models from…
- CourseOpenAI
- Lesson13 of 14
- Video23 min
- FormatJupyter notebook · 17 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 API in Python#
- Welcome! In this lesson you will learn how to use the OpenAI API in Python.
- The OpenAI API allows you to access powerful artificial intelligence models from your code.
- We are going to walk through everything you need, step by step.
- By the end, you will know how to make requests and create your own AI-powered projects.
What is the OpenAI API?#
- The OpenAI API gives you access to state-of-the-art artificial intelligence models.
- You can use it for chat assistants, writing, coding help, and many more creative tasks.
- This lesson will show you how to talk to these models from your Python code.
Setup and Installation#
- You are going to need the OpenAI Python library.
- If you already have it, you can skip installation.
- Install any missing libraries using pip as shown below.
import warnings; warnings.filterwarnings("ignore")
import numpy as np
np.random.seed(42)
# Let us import warnings and suppress warnings just in case.
# This keeps our output clean and beginner friendly.
!pip install --quiet openai
# We install the OpenAI library using pip.
# Pip is Python's package manager.
Core Concepts of the OpenAI API#
- To use the API you must import the library and authenticate with an API key.
- An API key is like a password for your code. Keep it secret.
- OpenAI provides models for chat, text generation, speech, images, and more.
- Each feature has its own method. We are going to look at the most popular ones.
import os
from openai import OpenAI
# We import os and the OpenAI client.
# os lets us access environment variables.
# Environment variables can securely store your API key.
API_key = os.environ["OPENAI_API_KEY"]
# We load our API key from the environment.
# Never share your API key in your code.
client = OpenAI()
# We create a client instance. This lets us make requests to OpenAI's API.
Making Your First Chat Request#
- You can use the OpenAI API to have a conversation with an AI model.
- The Chat Completions endpoint lets you send a message and get a smart reply.
- Let us try a basic example to get a response.
# OpenAI API Chat Completions Setup
response = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[{"role": "user", "content": "Hello!"}]
)
print(response.choices[0].message.content)
Understanding the Chat Code#
- You send messages as dictionaries with a role and some content.
- Each message is like a turn in a chat. The role tells the model who is talking.
- The model returns a reply, and you can print or use that reply in your code.
- You can adjust the model for speed, cost, or accuracy.
# Try customizing your own user prompt:
user_prompt = input("Type your question for the AI: ")
chat_response = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[{"role": "user", "content": user_prompt}]
)
print(chat_response.choices[0].message.content)
Using Text Generation for Instructions and Answers#
- Besides chat, you can request direct answers using the Responses endpoint.
- This is helpful when you want a simple answer to a question or command.
- Let us try asking for a summary.
# OpenAI API Responses Endpoint Setup
resp = client.responses.create(
model="gpt-4.1-mini",
input="Explain embeddings in one sentence."
)
print(resp.output[0].content[0].text)
# Try your own direct instruction:
quick_instr = input("Type a command for the model: ")
out = client.responses.create(
model="gpt-4.1-mini",
input=quick_instr
)
print(out.output[0].content[0].text)
Working with Embeddings#
- Embeddings turn text into numeric vectors. Vectors help computers measure meaning and similarity.
- These are very useful for search engines, categorizing text, or detecting intent.
- Let us generate an embedding for a short phrase.
# OpenAI API Embeddings Setup
embed = client.embeddings.create(
model="text-embedding-3-small",
input=["Machine learning is fun"]
)
print(len(embed.data[0].embedding))
# Try your own embedding phrase:
user_text = input("Type a sentence to embed: ")
result = client.embeddings.create(
model="text-embedding-3-small",
input=[user_text]
)
print("First five numbers:", result.data[0].embedding[:5])
Speech to Text: Transcribe Audio with OpenAI#
- The API can also turn spoken words into text using speech-to-text.
- You must provide an audio file and select the model. The result is a written transcription.
- Here is a quick example with a sample file.
# OpenAI API Speech to Text Setup
audio_file = open('sample.wav', 'rb')
transcript = client.audio.transcriptions.create(
model='whisper-1',
file=audio_file
)
print(transcript.text)
# Text to Speech: Generate Voice from Text
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())
Catching Errors and Handling Troubleshooting#
- If something goes wrong, the API will raise exceptions.
- Always use try and except to handle problems, especially with input or networking.
- Let us see a simple error handling example.
try:
bad_resp = client.chat.completions.create(
model="does-not-exist",
messages=[{"role": "user", "content": "Hi"}]
)
except Exception as e:
print("Caught error:", e)
# We try to use a fake model name, which should fail.
# The except block catches and reports the error message.
Best Practices for OpenAI API Usage#
- Keep your API key safe and do not expose it.
- Limit the number of requests to avoid high costs.
- Always read the API documentation for the latest features.
- Try smaller models first for quick experiments.
# Mini Project: Build a Simple Chatbot Function
def simple_chatbot(prompt):
result = client.chat.completions.create(
model="gpt-4.1-mini",
messages=[{"role": "user", "content": prompt}]
)
return result.choices[0].message.content
user_message = input("Say something to the bot: ")
bot_reply = simple_chatbot(user_message)
print("Bot says:", bot_reply)
Challenge 1: Create a Summarizer Function#
- Make a function called summarize that takes a text and returns a two sentence summary.
- Use the Responses API endpoint for this.
- Try it out with your own input.
def summarize(text):
response = client.responses.create(
model="gpt-4.1-mini",
input=f"Summarize this in two sentences: {text}"
)
return response.output[0].content[0].text
to_summarize = input("Enter text to summarize: ")
print("Summary:", summarize(to_summarize))
Challenge 2: Experiment with Embeddings Similarity#
- Ask the user for two sentences.
- Compare their embeddings using cosine similarity.
- A higher similarity means more similar meaning.
- Print the similarity score.
import numpy as np
def cosine_similarity(a, b):
return np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
text1 = input("First sentence: ")
text2 = input("Second sentence: ")
embeds = client.embeddings.create(
model="text-embedding-3-small",
input=[text1, text2]
)
vec1 = np.array(embeds.data[0].embedding)
vec2 = np.array(embeds.data[1].embedding)
sim = cosine_similarity(vec1, vec2)
print(f"Similarity score: {sim:.2f}")
Recap: What You Have Learned#
- You now know how to install and use the OpenAI API in Python.
- You have tried chat, text, embeddings, speech, and error handling.
- You completed hands-on challenges and a mini project.
- With this knowledge, you can start building real AI-powered applications.
What is Next? And Please Subscribe!#
- You did it! You have finished your first OpenAI API lesson.
- Try more ideas and create your own projects using what you have learned.
- Like and subscribe for more Python and A I tutorials.
- Leave a comment with your questions or project ideas.
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



