Module 2: OpenAI API - Introduction

First Request with the OpenAI Python SDK

Capsule overview

Time to write code. In this capsule you'll make your first successful request to GPT-3.5.

You'll see:

  • Installing the OpenAI SDK (v1.x)
  • The simplest possible request (5 lines)
  • A response from GPT-3.5
  • The anatomy of a request/response

By the end, you'll understand the basic flow: Message → API → Response

Time: 20 minutes
Difficulty: Low


🎯 Objectives

  • ✅ Install the official OpenAI SDK
  • ✅ Make your first request (GPT-3.5)
  • ✅ Receive and display the response
  • ✅ Understand the JSON format

📦 Step 1: Install the OpenAI SDK

1.1 The correct version (v1.x):

⚠️ Important: The OpenAI SDK had breaking changes in 2023:

  • SDK v0.x (old): openai.Completion.create()
  • SDK v1.x (new): client.chat.completions.create()

This module uses v1.x (the 2024-2026 standard).


1.2 Installation:

pip install openai

Expected output:

Collecting openai
  Downloading openai-1.12.0-py3-none-any.whl (...)
Installing collected packages: openai
Successfully installed openai-1.12.0

Installed version:

pip show openai

It should be v1.x:

Name: openai
Version: 1.12.0  # OK (v1.x)

If you see v0.x: Update with pip install --upgrade openai


1.3 Additional dependencies:

pip install python-dotenv  # For .env (if you didn't install it in capsule 02)

💻 Step 2: First Request (Minimal Code)

2.1 Project structure:

your-project/
├── .env                 # API key (created in capsule 02)
├── .gitignore          # Prevents a leak
└── first_request.py    # Your first code (we create it now)

2.2 Complete code (first_request.py):

from dotenv import load_dotenv
import os
from openai import OpenAI

# 1. Load the API key from .env
load_dotenv()
api_key = os.getenv("OPENAI_API_KEY")

# 2. Create the OpenAI client
client = OpenAI(api_key=api_key)

# 3. Make a request to GPT-3.5
response = client.chat.completions.create(
    model="gpt-3.5-turbo",
    messages=[
        {"role": "user", "content": "Hi, how are you?"}
    ]
)

# 4. Show the response
print(response.choices[0].message.content)

Only 5 lines of logic! (without imports and comments)


2.3 Run it:

python first_request.py

Expected output:

Hello! I'm here to help. What can I assist you with today?

If you see this: ✅ Congratulations! You just talked to GPT-3.5.


🔍 Step 3: Anatomy of the Request

3.1 Line-by-line breakdown:

Line 1-2: Imports

from dotenv import load_dotenv
import os
from openai import OpenAI
  • load_dotenv(): Reads the .env file
  • os.getenv(): Accesses environment variables
  • OpenAI: The official SDK v1.x client

Line 3-5: API Key

load_dotenv()
api_key = os.getenv("OPENAI_API_KEY")
  • Loads .env → Looks for OPENAI_API_KEY
  • Stores it in the api_key variable

Debugging:

print(f"API Key: {api_key[:10]}...")  # Show the first 10 chars
# Output: sk-proj-ab...

Line 6-7: Client

client = OpenAI(api_key=api_key)
  • Creates an instance of the client
  • Authenticates with your API key
  • Reusable (don't create one on every request)

Line 8-13: Request

response = client.chat.completions.create(
    model="gpt-3.5-turbo",           # Model to use
    messages=[                        # Array of messages
        {"role": "user", "content": "Hi, how are you?"}
    ]
)

Mandatory parameters:

  • model: String (e.g.: "gpt-3.5-turbo", "gpt-4")
  • messages: Array of objects with role and content

Optional parameters (you'll see them in capsule 05):

  • temperature: 0.0-2.0 (creativity)
  • max_tokens: Int (maximum length)
  • top_p, frequency_penalty, etc.

Line 14-15: Response

print(response.choices[0].message.content)
  • response.choices: Array (GPT can give multiple responses)
  • [0]: The first response (by default only one)
  • .message.content: The generated text

3.2 Full response (JSON):

If you print the full response:

print(response)

Output:

ChatCompletion(
  id='chatcmpl-abc123',
  object='chat.completion',
  created=1704123456,
  model='gpt-3.5-turbo-0125',
  choices=[
    Choice(
      index=0,
      message=ChatCompletionMessage(
        role='assistant',
        content='Hello! I'm here to help. What can I assist you with today?'
      ),
      finish_reason='stop'
    )
  ],
  usage=CompletionUsage(
    prompt_tokens=15,
    completion_tokens=18,
    total_tokens=33
  )
)

Important fields:

  • id: Unique identifier of the request
  • model: Model used (may differ from what was requested)
  • choices[0].message.content: THE RESPONSE
  • usage.total_tokens: Tokens spent (to calculate cost)

🧪 Step 4: Experiments

Experiment 1: Change the message

Modify the request line:

messages=[
    {"role": "user", "content": "Explain what Python is in 20 words"}
]

Run it:

python first_request.py

Expected output:

Python is an interpreted, high-level programming language 
with clear syntax, used in data science, web, and more.

Experiment 2: Use GPT-4

⚠️ Cost: GPT-4 is 15-20x more expensive than GPT-3.5

Change the model:

response = client.chat.completions.create(
    model="gpt-4-turbo",  # Was: gpt-3.5-turbo
    messages=[...]
)

Observe:

  • Latency: ~3s (vs 1.5s GPT-3.5)
  • Response: Slightly better quality
  • Cost: 15x higher

For learning: Use GPT-3.5 (enough and economical)


Experiment 3: Token usage

Add after the print:

print(f"\nTokens used: {response.usage.total_tokens}")
print(f"  - Prompt: {response.usage.prompt_tokens}")
print(f"  - Completion: {response.usage.completion_tokens}")

Output:

Tokens used: 33
  - Prompt: 15
  - Completion: 18

Cost calculation (GPT-3.5):

Input: 15 tokens × $0.50/1M = $0.0000075
Output: 18 tokens × $1.50/1M = $0.000027
Total: $0.0000345 (~$0.00003 per request)

For 1000 requests: ~$0.03


🔧 Step 5: Improvements to the Code

5.1 Basic error handling:

from dotenv import load_dotenv
import os
from openai import OpenAI

load_dotenv()
api_key = os.getenv("OPENAI_API_KEY")

if not api_key:
    print("❌ ERROR: OPENAI_API_KEY not found in .env")
    exit(1)

client = OpenAI(api_key=api_key)

try:
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[
            {"role": "user", "content": "Hi, how are you?"}
        ]
    )
    print(response.choices[0].message.content)
    
except Exception as e:
    print(f"❌ ERROR: {e}")

What it prevents:

  • Missing API key
  • Network errors
  • Rate limiting
  • Unexpected crashes

5.2 Reusable function:

from dotenv import load_dotenv
import os
from openai import OpenAI

load_dotenv()
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

def ask_gpt(prompt: str) -> str:
    """
    Send a prompt to GPT-3.5 and return the response.
    
    Args:
        prompt: The user's message
        
    Returns:
        The response generated by GPT-3.5
    """
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[{"role": "user", "content": prompt}]
    )
    return response.choices[0].message.content

# Usage
answer = ask_gpt("What is Python?")
print(answer)

answer2 = ask_gpt("Give me an example of a list in Python")
print(answer2)

Advantage: You reuse the logic without copying code.


🐛 Troubleshooting

Error: "ModuleNotFoundError: No module named 'openai'"

Cause: The SDK isn't installed

Solution:

pip install openai

Error: "AuthenticationError: Incorrect API key"

Cause: Wrong API key or not loaded

Solution:

# Debug: Verify the key loads
api_key = os.getenv("OPENAI_API_KEY")
print(f"API Key: {api_key}")

# If it's None: .env is not in the correct directory
# If it's wrong: Regenerate it in the dashboard

Error: "RateLimitError: Rate limit reached"

Cause: Too many requests in a short time

Solution:

import time
time.sleep(1)  # Wait 1s between requests

Free tier limits:

  • GPT-3.5: 60 requests/min
  • GPT-4: 3 requests/min

Error: "Timeout"

Cause: Slow network or a slow API

Solution:

client = OpenAI(
    api_key=api_key,
    timeout=30.0  # 30 seconds (default: 10min)
)

📊 Summary

What you learned:

  1. Installing the SDK:

    • pip install openai (v1.x)
    • Verify the correct version
  2. Basic request (5 lines):

    client = OpenAI(api_key=api_key)
    response = client.chat.completions.create(
        model="gpt-3.5-turbo",
        messages=[{"role": "user", "content": "..."}]
    )
    print(response.choices[0].message.content)
  3. Anatomy of the response:

    • choices[0].message.content: The response
    • usage.total_tokens: Tokens spent
    • model: Model used
  4. Debugging:

    • Verify the API key loads correctly
    • Print the full response to inspect it
    • Handle errors with try/except

Checklist:

  • SDK v1.x installed
  • First request successful
  • GPT-3.5 output visible
  • Experimented with different prompts
  • Reusable function created

If all are ✅: Ready for conversations with context!


🔗 Additional resources

  1. OpenAI Python SDK Docs - Official GitHub
  2. Chat Completions API - Reference
  3. Migration Guide v0→v1 - If you used the old SDK

➡️ Next step

Next capsule: 04-conversations-with-context.md

So far, each request is independent (GPT doesn't remember). In the next capsule:

  • You'll implement conversation history
  • GPT will remember previous messages
  • You'll create a real chatbot (multiple exchanges)

Time: 30 minutes
Code: ~30 lines


Estimated time: 20 minutes
Next: 04-conversations-with-context.md