Install the Python SDK
On this page
Install the Python SDK
The openai Python SDK is the official library for interacting with the API. This lesson walks you through installation and sets up a clean project structure that you will use throughout the rest of the course.
Prerequisites and Installation
You need Python 3.10 or newer—the minimum required by the openai SDK (version 3.42.1 as of November 2, 2026, per PyPI)—a package manager (pip or uv), and the API key you obtained in the previous lesson. Start by confirming your interpreter, since development machines often host multiple versions:
python --version
# Python 3.12.4
Installation takes a single command: pip install openai, or uv pip install openai if you use uv, which is significantly faster. However, make it a habit to work inside a virtual environment. This prevents the common scenario where, six months later, you discover two projects require incompatible versions of the same library.
# Create a virtual environment
python -m venv .venv
# Activate (Linux/macOS)
source .venv/bin/activate
# Activate (Windows)
.venv\Scripts\activate
# Install the SDK
pip install openai
Two companions appear in almost every project and deserve installation alongside the SDK. Pydantic helps define schemas for Structured Output, which you will see later; python-dotenv loads the .env file into environment variables.
# Install with support for Pydantic dataclasses
pip install openai pydantic
# Install with python-dotenv for environment variables
pip install openai python-dotenv
Finally, verify that the import works and note the installed version. This is the first piece of information to provide if you open a support ticket.
import openai
print(f"OpenAI SDK version: {openai.__version__}")
# Output: OpenAI SDK version: 1.68.0 (or newer)
One Client, All APIs
The SDK revolves around a single client object that exposes the entire platform via submodules. You do not need to instantiate anything new to switch from text generation to embeddings or moderation.
from openai import OpenAI
client = OpenAI()
# Responses API (text, function calling, structured output)
client.responses.create(...)
# Chat Completions API (legacy)
client.chat.completions.create(...)
# Embeddings
client.embeddings.create(...)
# Images
client.images.generate(...)
# Audio
client.audio.transcriptions.create(...)
client.audio.speech.create(...)
# Moderation
client.moderations.create(...)
Configure the Client for Your Context
The SDK defaults work for experimentation but fall short for web applications. The default timeout is ten minutes: in an HTTP API expected to respond within seconds, this means a stuck request ties up a worker for far too long. Reduce it, and increase the number of automatic retries, which defaults to two.
from openai import OpenAI
client = OpenAI(
timeout=60.0, # 60 seconds (default: 10 minutes)
max_retries=3, # 3 attempts on error (default: 2)
)
The base_url parameter addresses another need: routing calls through a corporate proxy that logs outbound traffic, or to a service exposing a compatible API.
# Useful for corporate proxies or compatible APIs
client = OpenAI(
base_url="https://your-proxy.company.com/v1"
)
Finally, if your application relies on asyncio—FastAPI, aiohttp, and the like—use AsyncOpenAI. The synchronous client would block the event loop during generation, negating the benefits of asynchronous code.
from openai import AsyncOpenAI
async_client = AsyncOpenAI()
# Usage with await
import asyncio
async def main():
response = await async_client.responses.create(
model="gpt-5.6-terra",
input="Hello!"
)
print(response.output_text)
asyncio.run(main())
# Output: Hello! How can I help you today?
Structure Your Project
Adopt an organization that isolates client configuration from the rest of your code right from the start. This avoids scattering dozens of OpenAI() calls throughout your project, each with its own settings.
my-project/
├── .env # API key (NEVER commit to git)
├── .gitignore # Includes .env
├── requirements.txt # Dependencies
├── src/
│ ├── __init__.py
│ ├── client.py # OpenAI client configuration
│ └── main.py # Entry point
└── tests/
└── test_api.py
The src/client.py file centralizes the client factory: the day you change the timeout or add a proxy, you only need to modify one location.
from openai import OpenAI
from dotenv import load_dotenv
load_dotenv()
def get_client() -> OpenAI:
"""Returns a configured OpenAI client."""
return OpenAI(
max_retries=3,
timeout=30.0
)
And requirements.txt pins the minimum expected versions:
openai>=1.60.0
python-dotenv>=1.0.0
pydantic>=2.0.0
Three Common Failures
A ModuleNotFoundError on openai almost always signals an inactive virtual environment or one different from where you installed the package. Locate the interpreter actually in use with which python on Linux and macOS, or where python on Windows, then reinstall with pip install --upgrade openai. An AuthenticationError points to the environment variable: print os.environ.get("OPENAI_API_KEY", "NOT DEFINED") to rule out issues—the .env file is not loaded if load_dotenv() was not called before instantiating the client. Finally, an error regarding an unknown parameter usually indicates an SDK too old for the feature you are using: pip install --upgrade openai resolves this.
Key Takeaways
- Install the SDK with
pip install openaiinside a virtual environment - The
OpenAI()client is the entry point for all APIs - Use
AsyncOpenAI()for asynchronous applications - Configure timeout and retries based on your needs
- Structure your project with a
.envfile and a centralized client