Skip to content

Latest commit

 

History

History
96 lines (71 loc) · 2.17 KB

File metadata and controls

96 lines (71 loc) · 2.17 KB

OpenAI API in Python

Call OpenAI models directly from Python, beyond the ChatGPT interface.

Quick Start

1. Get an API key

Sign up at platform.openai.com and create a key.

2. Set up your environment

# Clone / download this project, then:
pip install openai python-dotenv

# Create your .env file from the template
cp .env.example .env
# Open .env and paste your API key

3. Run

Option A — Jupyter Notebook (recommended for learning):

jupyter notebook openai_api_project.ipynb

Option B — Python script (all demos at once):

python openai_demo.py

What's Covered

Section Concept
Basic call client.chat.completions.create()
System message Shaping model persona and behaviour
Temperature 0 = deterministic → 2 = creative
max_tokens Hard-capping output length
Multi-turn Keeping conversation history manually
Interactive Live input loop with memory

Key Concepts

Roles

messages = [
    {"role": "system",    "content": "You are a pirate."},
    {"role": "user",      "content": "What is 2+2?"},
    {"role": "assistant", "content": "Four, arrr!"},  # previous reply (multi-turn)
    {"role": "user",      "content": "And 3+3?"},
]

Temperature

# Deterministic
chat("Name a color.", temperature=0.0)   # → "Red" every time

# Creative
chat("Name a color.", temperature=1.5)   # → wildly different each run

max_tokens

# Short answer
chat("Explain gravity.", max_tokens=20)

# Detailed answer
chat("Explain gravity.", max_tokens=500)

Project Structure

.
├── .env.example          # API key template — copy to .env
├── openai_demo.py        # Runnable script (all demos)
├── openai_api_project.ipynb  # Jupyter notebook walkthrough
└── README.md

Important Notes

  • Never commit your .env — add it to .gitignore
  • The notebook uses gpt-4o-mini by default (cheapest model)
  • This project uses openai >= 1.0 syntax (OpenAI() client), not the deprecated openai.ChatCompletion.create() from pre-2024 tutorials