Mathew K Analytics

Lesson 4 · OpenAI

Understanding Chat Completions API: Building Conversational AI with OpenAI

Learn how to use the OpenAI API, Get started with chat completions, embeddings, and more. No previous experience needed! The API connects your Python code…

⬇ 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

Welcome to OpenAI API in Python#

  • Learn how to use the OpenAI API,
  • Get started with chat completions, embeddings, and more.
  • No previous experience needed!

What is the OpenAI API?#

  • The API connects your Python code to advanced AI models,
  • Like ChatGPT, for language, code, audio, and more.
  • It lets you build smart, interactive applications easily.

Why should you use it?#

  • Automate writing, chatting, summarizing text,
  • Build assistants, chatbots, search tools, and more.
  • Add intelligence to your projects with just a few lines.
import warnings; warnings.filterwarnings("ignore")
import numpy as np
np.random.seed(42)
# This line disables unwanted warning messages.
import os
# os gives access to system settings, like environment variables.
API_key = os.environ["OPENAI_API_KEY"]
# Fetch the OpenAI API key from your environment settings.
from openai import OpenAI
# Import the main OpenAI client library.
client = OpenAI()
# Set up a client instance, ready for requests.

Key Concepts to Know#

  • Model: The AI engine, such as 'gpt-4.1-mini'.
  • Completion: The text or result generated for your prompt.
  • Endpoint: The specific function, like chat or embedding.
# Let us try a 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 assist you today?

How Chat Completion Works#

  • You send messages in a list.
  • Each message can have a 'role': user, assistant, or system.
  • The assistant replies based on all previous messages.
# You can control the conversation with roles.
messages = [
    {"role": "system", "content": "You are a helpful Python tutor."},
    {"role": "user", "content": "What is a variable?"}
]
response = client.chat.completions.create(
    model="gpt-4.1-mini",
    messages=messages
)
print(response.choices[0].message.content)
A variable in programming is a named location in memory used to store data that can be changed during the execution of a program. You can think of it as a container that holds information, such as numbers, text, or more complex data types. Variables allow you to label and manipulate data easily.

For example, in Python:

```python
age = 25
name = "Alice"
```

Here, `age` and `name` are variables. `age` stores the number 25, and `name` stores the string "Alice". You can use these variables later in your code to perform operations or display information.
# You can send longer multi-turn conversations.
chat_history = [
    {"role": "system", "content": "You are a math assistant."},
    {"role": "user", "content": "What is 2 plus 2?"},
    {"role": "assistant", "content": "2 plus 2 is 4."},
    {"role": "user", "content": "What is 3 times 5?"}
]
resp = client.chat.completions.create(
    model="gpt-4.1-mini",
    messages=chat_history
)
print(resp.choices[0].message.content)
3 times 5 is 15.

Embeddings: Understanding Text with Vectors#

  • Embeddings turn words or sentences into numbers.
  • This helps AI compare meanings, search, and cluster text.
  • They are useful for search engines and data science.
# Request text embeddings and inspect the result.
embed = client.embeddings.create(
    model="text-embedding-3-small",
    input=["Machine learning is fun"]
)
print(len(embed.data[0].embedding))
1536

How to Handle Errors Safely#

  • Always catch exceptions when calling the API.
  • This helps you show friendly messages if something goes wrong.
  • Use try and except blocks.
# Wrap your API call with error handling.
try:
    response = client.chat.completions.create(
        model="gpt-4.1-mini",
        messages=[{"role": "user", "content": "Will not crash!"}]
    )
    print(response.choices[0].message.content)
except Exception as e:
    print("Oops, something went wrong:", str(e))
Could you please provide more details or clarify your request? I'd like to help but need a bit more information about what you mean by "Will not crash!" Are you referring to software, hardware, a specific application, or something else?

Best Practices for API Usage#

  • Keep your API key secret.
  • Control costs by using smaller models if possible.
  • Add pauses if you make many requests.
  • Review the API documentation for updates.
# Simple user prompt with input()
user_query = input("What would you like to ask the AI? ")
result = client.chat.completions.create(
    model="gpt-4.1-mini",
    messages=[{"role": "user", "content": user_query}]
)
print(result.choices[0].message.content)
Python is a high-level, interpreted programming language known for its readability, simplicity, and versatility. It was created by Guido van Rossum and first released in 1991. Python supports multiple programming paradigms, including procedural, object-oriented, and functional programming.

Key features of Python include:

- **Easy to learn and use:** Python has a clear and readable syntax, which makes it a great choice for beginners.
- **Extensive standard library:** It comes with a large collection of modules and packages that support various tasks such as file handling, web development, data analysis, and more.
- **Cross-platform:** Python runs on many operating systems, including Windows, macOS, and Linux.
- **Community support:** It has a vast and active community, contributing to numerous third-party libraries and frameworks.
- **Applications:** Python is widely used in web development, data science, artificial intelligence, automation, scientific computing, and more.

Overall, Python is a popular programming language valued for its ease of use and broad applicability.
# Mini Project: Basic Chatbot Loop
while True:
    user_msg = input("You: ")
    if user_msg.lower().strip() in ["exit", "quit"]:
        print("Goodbye!")
        break
    reply = client.chat.completions.create(
        model="gpt-4.1-mini",
        messages=[{"role": "user", "content": user_msg}]
    )
    print("AI:", reply.choices[0].message.content)
AI: Sure! Here's one for you:

Why don't scientists trust atoms?

Because they make up everything!
Goodbye!
# Troubleshooting: Check for common issues.
try:
    check = client.chat.completions.create(
        model="gpt-4.1-mini",
        messages=[{"role": "user", "content": "Test connection"}]
    )
    print("API working fine.")
except Exception as error:
    print("Check your API key or network. Error:", error)
API working fine.

Challenge Exercise 1: Custom Prompt#

  • Change the prompt to ask the assistant your favorite question.
  • What is the most interesting answer you can get?

Challenge Exercise 2: Multi-Turn Conversation#

  • Build a chat history with at least three user and assistant turns.
  • Guide the assistant using a helpful system prompt.

Recap: What You Learned Today#

  • You connected Python to the OpenAI API.
  • You ran chat completions and embeddings.
  • You made your own chatbot!
  • You practiced error handling and best practices.

Thank You and Next Steps!#

  • Like and subscribe for more Python and AI lessons.
  • Practice by building your own fun mini-projects.
  • Happy coding with OpenAI!

Found this useful?

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