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



