Skip to content

iamwujiabao/OpenAI-API-in-Python

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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

About

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

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages