Ai Engineering Core / Chat Completion API & SDK

Chat Completion API

👶 Before we begin with Coding, let’s do the setup:

  1. Create a new file named part2.ipynb inside the level1 folder.

  2. Open the file and make sure a Python kernel is selected. If no kernel is selected, choose the appropriate one before proceeding.


🤫 Step 1: Loading Environment Variables

▶️ Create a new code cell and run it:

import os
from dotenv import load_dotenv

load_dotenv(override=True)
api_key = os.getenv('OPENAI_API_KEY')

if not api_key:
    print("No API key was found - please head over to the troubleshooting notebook in this folder to identify & fix!")
elif not api_key.startswith("sk-proj-"):
    print("An API key was found, but it doesn't start sk-proj-; please check you're using the right key - see troubleshooting notebook")
else:
    print("API key found and looks good so far!")

☎️ Step 2: Endpoint Payload Setup and Calling API

▶️ Create a new code cell and run it: Payload Setup

import requests

headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}

payload = {
    "model": "gpt-5-nano",
    "messages": [
        {"role": "user", "content": "Tell me a fun fact"}]
}

payload ## prints the payload

▶️ Create a new code cell and run it: Calling the Endpoint

response = requests.post(
    "<https://api.openai.com/v1/chat/completions>",
    headers=headers,
    json=payload
)

response.json() ## prints the response

▶️ Create a new code cell and run it: Prints Exact Relevant Response

response.json()["choices"][0]["message"]["content"]

❓What is API Endpoint?

An API endpoint is simply a specific URL where you send your request to get something done.

Think of it like this:

🏪 An API is like a restaurant
📋 An endpoint is like a specific item on the menu

You don't just walk in and say "give me food" — you order something specific. Similarly, you don't just call an API in general, you call a specific endpoint for a specific action.

🔗 In practice, it looks like this:

<https://api.anthropic.com/v1/messages>

This is an endpoint. It tells the server:

  • 🌐 Where to go — api.anthropic.com

  • 📂 What action to perform — /v1/messages (send a message to a model)

📬 Real world analogy:

Concept

Real World

API World

🏢 Server

Post office

api.anthropic.com

📍 Endpoint

Counter number

/v1/messages

📦 Request

Your parcel

Your JSON data

📨 Response

Receipt/reply

Model's output

So in short:

🎯 An endpoint is the specific address you hit to trigger a specific action on a server.