OpenAI API Cheatsheet
Installation
pip install openai
Basic Setup
from openai import OpenAI
import os
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
Chat Completion (Non-Streaming)
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What is Python?"}
],
temperature=0.7, # 0 = deterministic, 2 = very random
max_tokens=500, # Max words in response
)
reply = response.choices[0].message.content
print(reply)
print(f"Tokens used: {response.usage.total_tokens}")
Chat Completion (Streaming)
stream = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Tell me a story"}],
stream=True,
)
full_response = ""
for chunk in stream:
if chunk.choices[0].delta.content:
content = chunk.choices[0].delta.content
print(content, end="") # Print as it arrives
full_response += content
messages = [
{"role": "system", "content": "You speak like a pirate."},
{"role": "user", "content": "Hello!"},
{"role": "assistant", "content": "Ahoy, matey!"},
{"role": "user", "content": "What's the weather?"},
]
Error Handling
try:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Hello"}]
)
except openai.AuthenticationError:
print("Invalid API key. Check your .env file.")
except openai.RateLimitError:
print("Rate limited. Waiting before retrying...")
time.sleep(10)
except openai.APIError as e:
print(f"API error: {e}")
Function Calling (for agents)
tools = [
{
"type": "function",
"function": {
"name": "get_weather",
"description": "Get the weather for a city",
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string"}
},
"required": ["city"]
}
}
}
]
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "What's the weather in Paris?"}],
tools=tools,
tool_choice="auto"
)
# Check if the model wants to call a function
if response.choices[0].message.tool_calls:
tool_call = response.choices[0].message.tool_calls[0]
function_name = tool_call.function.name
arguments = json.loads(tool_call.function.arguments)
print(f"Calling {function_name} with {arguments}")
Available Models (2025)
| Model |
Best For |
Context Window |
gpt-4o |
Best overall |
128K tokens |
gpt-4o-mini |
Budget, fast |
128K tokens |
gpt-4-turbo |
Legacy high-quality |
128K tokens |
gpt-3.5-turbo |
Legacy budget |
16K tokens |