OpenAI API: chat.completions and Streaming
OpenAI client, messages list, system/user/assistant roles, streaming with stream=True.
OpenAI API: chat.completions and Streaming is a free Learn AI with Python lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Learn AI with Python learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Meet the OpenAI Python SDK
The openai Python package is the official way to talk to OpenAI models like GPT-4o. Install it with pip install openai and you get a single OpenAI client class that handles authentication, retries, and request building for you.
Every call you make goes through this client, so creating it once and reusing it is the standard pattern.
pip install openai
from openai import OpenAICreating the Client
Instantiate the client with OpenAI(). By default it reads your key from the OPENAI_API_KEY environment variable, which keeps secrets out of your source code.
You can also pass the key explicitly, but environment variables are the recommended approach for production apps.
from openai import OpenAI
# Reads OPENAI_API_KEY from the environment
client = OpenAI()
# Or pass it explicitly (not recommended)
client = OpenAI(api_key="sk-...")The messages List
Chat models are driven by a list of messages. Each message is a dict with a role and content. The three core roles are system (instructions), user (the human), and assistant (the model).
This list is the full conversation context the model sees on every call.
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "What is the capital of France?"}
]Your First Completion
Call client.chat.completions.create() with a model and your messages. The reply text lives at response.choices[0].message.content.
The API returns a list of choices, but for normal use you read the first one.
response = client.chat.completions.create(
model="gpt-4o",
messages=messages
)
print(response.choices[0].message.content)Controlling Output with Parameters
Two parameters shape the response: temperature (0 = deterministic, higher = more creative) and max_tokens (caps the reply length). Lower temperatures suit factual tasks; higher suits brainstorming.
response = client.chat.completions.create(
model="gpt-4o",
messages=messages,
temperature=0.2,
max_tokens=300
)Why Stream Responses?
Without streaming, you wait for the entire reply before seeing anything. With streaming, tokens arrive as they are generated, so a UI can display text in real time like ChatGPT does.
You enable it with stream=True, which changes the return value from a single object into an iterator.
Enabling Streaming
Pass stream=True to create(). Instead of a completed response, you now get a generator that yields chunks as the model produces them.
stream = client.chat.completions.create(
model="gpt-4o",
messages=messages,
stream=True
)Iterating Over Chunks
Loop over the stream. Each chunk carries a partial piece of text in chunk.choices[0].delta.content. Early and final chunks may have None there, so guard against it before printing.
for chunk in stream:
delta = chunk.choices[0].delta.content
if delta is not None:
print(delta, end="", flush=True)Understanding delta vs message
In a normal response you read message.content (the whole reply). In a stream you read delta.content (just the new piece). The word delta means "the change" since the last chunk.
Concatenating all deltas reconstructs the full message.
full_text = ""
for chunk in stream:
piece = chunk.choices[0].delta.content or ""
full_text += piece
print("\nFinal:", full_text)Multi-Turn Conversations
To keep a conversation going, append the assistant's reply back into messages and then add the next user message. The model is stateless, so YOU maintain the history.
messages.append({"role": "assistant", "content": response.choices[0].message.content})
messages.append({"role": "user", "content": "And its population?"})
follow_up = client.chat.completions.create(model="gpt-4o", messages=messages)Inspecting Token Usage
Non-streamed responses include a usage object with prompt_tokens, completion_tokens, and total_tokens. This is how you track and budget API cost, since billing is per token.
print(response.usage.prompt_tokens)
print(response.usage.completion_tokens)
print(response.usage.total_tokens)Quick Check
Test your understanding of streaming.
Recap: Chat Completions and Streaming
You learned to create an OpenAI client, build a messages list with system/user/assistant roles, and call chat.completions.create(). You read normal replies from choices[0].message.content.
With stream=True you iterate chunks and read delta.content for real-time output, maintain history by appending replies, and track cost via the usage object.
Frequently asked questions
Is the “OpenAI API: chat.completions and Streaming” lesson free?
Yes — the full text of “OpenAI API: chat.completions and Streaming” is free to read here on the web, and the Learn AI with Python course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn AI with Python course, upgrade to CoddyKit PRO.
What will I learn in “OpenAI API: chat.completions and Streaming”?
OpenAI client, messages list, system/user/assistant roles, streaming with stream=True. You practise Learn AI with Python with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start Learn AI with Python?
No prior experience is required. Learn AI with Python on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “OpenAI API: chat.completions and Streaming” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this Learn AI with Python lesson?
Yes. Every Learn AI with Python lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- OpenAI API: chat.completions and Streaming
- Anthropic Claude API in Python
- Function Calling and Tool Use with LLMs
- Prompt Engineering for Production LLM Apps