Call OpenAI models directly from Python, beyond the ChatGPT interface.
Sign up at platform.openai.com and create a key.
# 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 keyOption A — Jupyter Notebook (recommended for learning):
jupyter notebook openai_api_project.ipynbOption B — Python script (all demos at once):
python openai_demo.py| 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 |
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?"},
]# Deterministic
chat("Name a color.", temperature=0.0) # → "Red" every time
# Creative
chat("Name a color.", temperature=1.5) # → wildly different each run# Short answer
chat("Explain gravity.", max_tokens=20)
# Detailed answer
chat("Explain gravity.", max_tokens=500).
├── .env.example # API key template — copy to .env
├── openai_demo.py # Runnable script (all demos)
├── openai_api_project.ipynb # Jupyter notebook walkthrough
└── README.md
- Never commit your
.env— add it to.gitignore - The notebook uses
gpt-4o-miniby default (cheapest model) - This project uses openai >= 1.0 syntax (
OpenAI()client), not the deprecatedopenai.ChatCompletion.create()from pre-2024 tutorials