Working with AI APIs

Getting Started with OpenAI API

Learn how to set up and use the OpenAI API to build AI-powered applications with GPT models.

Getting Started with OpenAI API

The OpenAI API gives you programmatic access to GPT models. This topic covers setup, authentication, and building your first AI-powered application.

Setting Up

1. Create an Account

Sign up at platform.openai.com and add a payment method. New accounts get free credits to start.

2. Get Your API Key

Navigate to API Keys in your dashboard and create a new secret key. Store it securely — you won't be able to see it again.

bash
# Set as environment variable
export OPENAI_API_KEY="sk-your-key-here"

3. Install the SDK

bash
# Python
pip install openai

# Node.js
npm install openai

Your First API Call

Python

python
from openai import OpenAI

client = OpenAI()  # Uses OPENAI_API_KEY env variable

response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "What is the capital of France?"}
    ]
)

print(response.choices[0].message.content)
# Output: "The capital of France is Paris."

Node.js

javascript
import OpenAI from 'openai';

const openai = new OpenAI(); // Uses OPENAI_API_KEY env variable

const response = await openai.chat.completions.create({
    model: "gpt-4o",
    messages: [
        { role: "system", content: "You are a helpful assistant." },
        { role: "user", content: "What is the capital of France?" }
    ]
});

console.log(response.choices[0].message.content);

Understanding the Messages Format

The chat API uses a conversation format with three roles:

python
messages = [
    # System message: Sets the AI's behavior
    {"role": "system", "content": "You are a Python tutor."},

    # User messages: What the human says
    {"role": "user", "content": "How do I read a file?"},

    # Assistant messages: Previous AI responses (for context)
    {"role": "assistant", "content": "You can use open()..."},

    # Continue the conversation
    {"role": "user", "content": "What about binary files?"}
]

Key Parameters

python
response = client.chat.completions.create(
    model="gpt-4o",           # Model to use
    messages=messages,          # Conversation history
    temperature=0.7,            # Creativity (0-2)
    max_tokens=1000,            # Max response length
    top_p=1.0,                  # Nucleus sampling
    frequency_penalty=0.0,      # Reduce repetition
    presence_penalty=0.0,       # Encourage new topics
    stop=["\n\n"],              # Stop sequences
)

Model Options

ModelBest ForCost
gpt-4oMost capable, multimodal$$
gpt-4o-miniFast, cost-effective$
gpt-4-turboComplex reasoning$$$
o1Advanced reasoning, math$$$$

Streaming Responses

For real-time output, use streaming:

python
stream = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Write a haiku about coding"}],
    stream=True
)

for chunk in stream:
    if chunk.choices[0].delta.content:
        print(chunk.choices[0].delta.content, end="")

Working with Images (Vision)

GPT-4o can understand images:

python
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {
            "role": "user",
            "content": [
                {"type": "text", "text": "What's in this image?"},
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "https://example.com/photo.jpg"
                    }
                }
            ]
        }
    ]
)

Structured Output (JSON Mode)

Force the model to return valid JSON:

python
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[
        {
            "role": "system",
            "content": "Extract product info as JSON with keys: name, price, category"
        },
        {
            "role": "user",
            "content": "The iPhone 15 Pro costs $999 and is a smartphone."
        }
    ],
    response_format={"type": "json_object"}
)

import json
data = json.loads(response.choices[0].message.content)
# {"name": "iPhone 15 Pro", "price": 999, "category": "smartphone"}

Error Handling

python
from openai import OpenAI, APIError, RateLimitError, APIConnectionError

client = OpenAI()

try:
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[{"role": "user", "content": "Hello"}]
    )
except RateLimitError:
    print("Rate limit hit — wait and retry")
except APIConnectionError:
    print("Network issue — check your connection")
except APIError as e:
    print(f"API error: {e.status_code} - {e.message}")

Tracking Usage and Costs

python
response = client.chat.completions.create(
    model="gpt-4o",
    messages=[{"role": "user", "content": "Hello"}]
)

usage = response.usage
print(f"Input tokens:  {usage.prompt_tokens}")
print(f"Output tokens: {usage.completion_tokens}")
print(f"Total tokens:  {usage.total_tokens}")

Best Practices

  1. Store API keys securely — Use environment variables, never hardcode
  2. Set max_tokens — Prevent unexpectedly long (expensive) responses
  3. Use the cheapest model that works — Start with gpt-4o-mini, upgrade if needed
  4. Implement retries — Network and rate limit errors are transient
  5. Cache responses — Identical prompts don't need repeated API calls
  6. Monitor usage — Set billing alerts on your OpenAI dashboard

Quick Reference

python
# Minimal setup
from openai import OpenAI
client = OpenAI()

# Simple completion
response = client.chat.completions.create(
    model="gpt-4o-mini",
    messages=[{"role": "user", "content": "Your prompt here"}],
    temperature=0.7,
    max_tokens=500
)

answer = response.choices[0].message.content

In the next topic, we'll explore the Anthropic Claude API, which offers a different approach with longer context windows and a focus on safety.