OpenAI API: chat.completions and Streaming
OpenAI client, messages list, system/user/assistant roles, streaming with stream=True.
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-...")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