Mathew K Analytics

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…

⬇ 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

Getting 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)
Hello! How can I assist you today?

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)
The capital of France is Paris.

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)
Embeddings are numerical vector representations of data, such as words or images, that capture their semantic meaning and relationships in a continuous, high-dimensional space.
# 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)
Machine learning is used in a wide range of applications across various fields, including:

1. **Healthcare:** Diagnosing diseases, personalized treatment plans, drug discovery, medical imaging analysis.
2. **Finance:** Fraud detection, algorithmic trading, credit scoring, risk management.
3. **Marketing:** Customer segmentation, recommendation systems, sentiment analysis, targeted advertising.
4. **Retail:** Inventory management, demand forecasting, product recommendations, supply chain optimization.
5. **Transportation:** Autonomous vehicles, route optimization, traffic prediction, demand forecasting.
6. **Natural Language Processing:** Language translation, chatbots, speech recognition, sentiment analysis.
7. **Image and Video Analysis:** Facial recognition, object detection, video surveillance, image enhancement.
8. **Manufacturing:** Predictive maintenance, quality control, automation, supply chain optimization.
9. **Cybersecurity:** Threat detection, anomaly detection, malware classification, intrusion detection.
10. **Entertainment:** Personalized content recommendations, game AI, content creation.
11. **Education:** Personalized learning, automated grading, student performance prediction.
12. **Energy:** Smart grid management, energy consumption forecasting, fault detection.

Overall, machine learning enables systems to improve automatically through experience, making processes more efficient, accurate, and scalable.

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))
1536
# 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])
First five numbers: [-0.00397814717143774, -0.02215598151087761, -0.024774979799985886, 0.007323266007006168, 0.03711282089352608]

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)
Welcome to OpenAI.
# 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.
Caught error: Error code: 404 - {'error': {'message': 'The model `does-not-exist` does not exist or you do not have access to it.', 'type': 'invalid_request_error', 'param': None, 'code': 'model_not_found'}}

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)
Bot says: Improving your Python skills involves a mix of practice, learning new concepts, and working on projects. Here are some effective strategies to help you get better at Python:

1. **Practice Regularly**  
   - Try to code every day, even if it’s just for 20-30 minutes. Consistency is key.

2. **Work on Projects**  
   - Build small projects related to your interests—web apps, games, data analysis, automation scripts, etc. Projects help you learn to solve real problems.

3. **Learn the Fundamentals Thoroughly**  
   - Make sure you understand basic concepts like data types, control structures, functions, classes and objects, exception handling, and file I/O.

4. **Use Online Platforms for Practice**  
   - Websites like LeetCode, HackerRank, CodeSignal, and Exercism offer coding challenges that help sharpen problem-solving skills.

5. **Read Python Code Written by Others**  
   - Reading open-source projects or well-written code helps you understand different coding styles and best practices.

6. **Study Advanced Topics**  
   - Once comfortable with basics, move to decorators, generators, context managers, metaclasses, concurrency (asyncio, threading), and libraries for specific areas like NumPy, Pandas, Flask/Django, etc.

7. **Follow Tutorials and Take Courses**  
   - Look for high-quality tutorials or courses (on platforms like Coursera, Udemy, edX) to get structured learning paths.

8. **Contribute to Open Source**  
   - Try contributing to open-source Python projects on GitHub. It gives you experience collaborating and working on larger codebases.

9. **Read Books**  
   - Some recommended Python books:  
     - *“Automate the Boring Stuff with Python”* by Al Sweigart  
     - *“Fluent Python”* by Luciano Ramalho  
     - *“Effective Python”* by Brett Slatkin

10. **Join Communities**  
    - Participate in communities like Stack Overflow, Reddit’s r/learnpython, or Python Discord servers to ask questions and help others.

11. **Practice Writing Clean Code**  
    - Learn PEP 8 style guidelines and aim to write readable, maintainable code.

If you want, I can help suggest specific resources or project ideas tailored to your current skill level.

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))
Summary: OpenAI creates advanced AI models aimed at addressing real-world challenges. Their technology is designed to help people accomplish their goals more efficiently.

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}")
Similarity score: 0.50

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.