Your first OpenAI call
The single most-asked-about line of Python in 2026: how do I actually call ChatGPT from code? This lesson answers it.
You are sending a polite letter to a smart pen friend. You include who you are, what you want, and where to send the reply. The API call is the envelope.
Three things every API call needs:
- The model id (e.g.
gpt-4o-mini) - The messages array (see Module 3.2)
- Optional parameters (
temperature,max_tokens,response_format)
The provider returns a structured response with the assistant message, token usage, and finish reason.
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()
client = OpenAI()
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[
{"role": "system", "content": "You are a tutor. Reply in 2 sentences."},
{"role": "user", "content": "Explain RAG to a beginner."},
],
temperature=0.4,
max_tokens=200,
)
print(response.choices[0].message.content)
print("Usage:", response.usage.total_tokens)
That is a complete, runnable program.
Quick recall
3 prompts · think before you flip
Prompt 1 of 3
What three inputs does every chat completion need?
Quiz time
1 question · tap an answer to check it
1. The assistant's text is at
Finished lesson 5.3?
Mark complete to update your module progress and unlock the streak.
Loading