How to list available OpenAI models in python
Quick answer
Use the
OpenAI Python SDK v1 to list available models by calling client.models.list(). This returns a list of all accessible models, including their IDs and details.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the official OpenAI Python SDK and set your API key as an environment variable.
- Run
pip install openaito install the SDK. - Set your API key in your environment:
export OPENAI_API_KEY='your_api_key'(Linux/macOS) orsetx OPENAI_API_KEY "your_api_key"(Windows).
pip install openai Step by step
Use the OpenAI client to list all available models. The models.list() method returns metadata about each model.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
response = client.models.list()
for model in response.data:
print(f"Model ID: {model.id}") output
Model ID: gpt-4o Model ID: gpt-4o-mini Model ID: gpt-4o Model ID: o1 Model ID: o1-mini Model ID: o3-mini ...
Common variations
You can also retrieve detailed model info by ID using client.models.retrieve(model_id). For asynchronous usage, use asyncio with the SDK's async client. Different SDKs like Anthropic or LangChain have their own methods to list models.
import asyncio
from openai import OpenAI
async def list_models_async():
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
response = await client.models.list()
for model in response.data:
print(f"Async Model ID: {model.id}")
asyncio.run(list_models_async()) output
Async Model ID: gpt-4o Async Model ID: gpt-4o-mini Async Model ID: gpt-4o ...
Troubleshooting
If you get an authentication error, verify your OPENAI_API_KEY environment variable is set correctly. If the list is empty or incomplete, check your API plan and permissions. Network errors may require retry logic or checking your internet connection.
Key Takeaways
- Use
client.models.list()from the OpenAI Python SDK v1 to get all available models. - Always set your API key securely via environment variables, never hardcode it.
- You can retrieve detailed info for a specific model with
client.models.retrieve(model_id). - Async calls are supported with Python's
asyncioand the OpenAI SDK. - Check API key and network if you encounter authentication or connectivity issues.