ℹ️ Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 0 months ago |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | PASS | meta_canonical IS NULL OR = '' OR = src_unparsed | Not set |
| Property | Value |
|---|---|
| URL | https://pypi.org/project/openai/ |
| Last Crawled | 2026-04-09 18:23:03 (15 hours ago) |
| First Indexed | 2018-05-03 19:54:03 (7 years ago) |
| HTTP Status Code | 200 |
| Meta Title | openai · PyPI |
| Meta Description | The official Python library for the openai API |
| Meta Canonical | null |
| Boilerpipe Text | OpenAI Python API library
The OpenAI Python library provides convenient access to the OpenAI REST API from any Python 3.9+
application. The library includes type definitions for all request params and response fields,
and offers both synchronous and asynchronous clients powered by
httpx
.
It is generated from our
OpenAPI specification
with
Stainless
.
Documentation
The REST API documentation can be found on
platform.openai.com
. The full API of this library can be found in
api.md
.
Installation
# install from PyPI
pip
install
openai
Usage
The full API of this library can be found in
api.md
.
The primary API for interacting with OpenAI models is the
Responses API
. You can generate text from the model with the code below.
import
os
from
openai
import
OpenAI
client
=
OpenAI
(
# This is the default and can be omitted
api_key
=
os
.
environ
.
get
(
"OPENAI_API_KEY"
),
)
response
=
client
.
responses
.
create
(
model
=
"gpt-5.2"
,
instructions
=
"You are a coding assistant that talks like a pirate."
,
input
=
"How do I check if a Python object is an instance of a class?"
,
)
print
(
response
.
output_text
)
The previous standard (supported indefinitely) for generating text is the
Chat Completions API
. You can use that API to generate text from the model with the code below.
from
openai
import
OpenAI
client
=
OpenAI
()
completion
=
client
.
chat
.
completions
.
create
(
model
=
"gpt-5.2"
,
messages
=
[
{
"role"
:
"developer"
,
"content"
:
"Talk like a pirate."
},
{
"role"
:
"user"
,
"content"
:
"How do I check if a Python object is an instance of a class?"
,
},
],
)
print
(
completion
.
choices
[
0
]
.
message
.
content
)
While you can provide an
api_key
keyword argument,
we recommend using
python-dotenv
to add
OPENAI_API_KEY="My API Key"
to your
.env
file
so that your API key is not stored in source control.
Get an API key here
.
Workload Identity Authentication
For secure, automated environments like cloud-managed Kubernetes, Azure, and Google Cloud Platform, you can use workload identity authentication with short-lived tokens from cloud identity providers instead of long-lived API keys.
Kubernetes (service account tokens)
from
openai
import
OpenAI
from
openai.auth
import
k8s_service_account_token_provider
client
=
OpenAI
(
workload_identity
=
{
"client_id"
:
"your-client-id"
,
"identity_provider_id"
:
"idp-123"
,
"service_account_id"
:
"sa-456"
,
"provider"
:
k8s_service_account_token_provider
(
"/var/run/secrets/kubernetes.io/serviceaccount/token"
),
},
organization
=
"org-xyz"
,
project
=
"proj-abc"
,
)
response
=
client
.
chat
.
completions
.
create
(
model
=
"gpt-4"
,
messages
=
[{
"role"
:
"user"
,
"content"
:
"Hello!"
}],
)
Azure (managed identity)
from
openai
import
OpenAI
from
openai.auth
import
azure_managed_identity_token_provider
client
=
OpenAI
(
workload_identity
=
{
"client_id"
:
"your-client-id"
,
"identity_provider_id"
:
"idp-123"
,
"service_account_id"
:
"sa-456"
,
"provider"
:
azure_managed_identity_token_provider
(
resource
=
"https://management.azure.com/"
,
),
},
)
Google Cloud Platform (compute engine metadata)
from
openai
import
OpenAI
from
openai.auth
import
gcp_id_token_provider
client
=
OpenAI
(
workload_identity
=
{
"client_id"
:
"your-client-id"
,
"identity_provider_id"
:
"idp-123"
,
"service_account_id"
:
"sa-456"
,
"provider"
:
gcp_id_token_provider
(
audience
=
"https://api.openai.com/v1"
),
},
)
Custom subject token provider
from
openai
import
OpenAI
def
get_custom_token
()
->
str
:
return
"your-jwt-token"
client
=
OpenAI
(
workload_identity
=
{
"client_id"
:
"your-client-id"
,
"identity_provider_id"
:
"idp-123"
,
"service_account_id"
:
"sa-456"
,
"provider"
:
{
"token_type"
:
"jwt"
,
"get_token"
:
get_custom_token
,
},
}
)
You can also customize the token refresh buffer (default is 1200 seconds (20 minutes) before expiration):
from
openai
import
OpenAI
from
openai.auth
import
k8s_service_account_token_provider
client
=
OpenAI
(
workload_identity
=
{
"client_id"
:
"your-client-id"
,
"identity_provider_id"
:
"idp-123"
,
"service_account_id"
:
"sa-456"
,
"provider"
:
k8s_service_account_token_provider
(
"/var/token"
),
"refresh_buffer_seconds"
:
120.0
,
}
)
Vision
With an image URL:
prompt
=
"What is in this image?"
img_url
=
"https://upload.wikimedia.org/wikipedia/commons/thumb/d/d5/2023_06_08_Raccoon1.jpg/1599px-2023_06_08_Raccoon1.jpg"
response
=
client
.
responses
.
create
(
model
=
"gpt-5.2"
,
input
=
[
{
"role"
:
"user"
,
"content"
:
[
{
"type"
:
"input_text"
,
"text"
:
prompt
},
{
"type"
:
"input_image"
,
"image_url"
:
f
"
{
img_url
}
"
},
],
}
],
)
With the image as a base64 encoded string:
import
base64
from
openai
import
OpenAI
client
=
OpenAI
()
prompt
=
"What is in this image?"
with
open
(
"path/to/image.png"
,
"rb"
)
as
image_file
:
b64_image
=
base64
.
b64encode
(
image_file
.
read
())
.
decode
(
"utf-8"
)
response
=
client
.
responses
.
create
(
model
=
"gpt-5.2"
,
input
=
[
{
"role"
:
"user"
,
"content"
:
[
{
"type"
:
"input_text"
,
"text"
:
prompt
},
{
"type"
:
"input_image"
,
"image_url"
:
f
"data:image/png;base64,
{
b64_image
}
"
},
],
}
],
)
Async usage
Simply import
AsyncOpenAI
instead of
OpenAI
and use
await
with each API call:
import
os
import
asyncio
from
openai
import
AsyncOpenAI
client
=
AsyncOpenAI
(
# This is the default and can be omitted
api_key
=
os
.
environ
.
get
(
"OPENAI_API_KEY"
),
)
async
def
main
()
->
None
:
response
=
await
client
.
responses
.
create
(
model
=
"gpt-5.2"
,
input
=
"Explain disestablishmentarianism to a smart five year old."
)
print
(
response
.
output_text
)
asyncio
.
run
(
main
())
Functionality between the synchronous and asynchronous clients is otherwise identical.
With aiohttp
By default, the async client uses
httpx
for HTTP requests. However, for improved concurrency performance you may also use
aiohttp
as the HTTP backend.
You can enable this by installing
aiohttp
:
# install from PyPI
pip
install
openai
[
aiohttp
]
Then you can enable it by instantiating the client with
http_client=DefaultAioHttpClient()
:
import
os
import
asyncio
from
openai
import
DefaultAioHttpClient
from
openai
import
AsyncOpenAI
async
def
main
()
->
None
:
async
with
AsyncOpenAI
(
api_key
=
os
.
environ
.
get
(
"OPENAI_API_KEY"
),
# This is the default and can be omitted
http_client
=
DefaultAioHttpClient
(),
)
as
client
:
chat_completion
=
await
client
.
chat
.
completions
.
create
(
messages
=
[
{
"role"
:
"user"
,
"content"
:
"Say this is a test"
,
}
],
model
=
"gpt-5.2"
,
)
asyncio
.
run
(
main
())
Streaming responses
We provide support for streaming responses using Server Side Events (SSE).
from
openai
import
OpenAI
client
=
OpenAI
()
stream
=
client
.
responses
.
create
(
model
=
"gpt-5.2"
,
input
=
"Write a one-sentence bedtime story about a unicorn."
,
stream
=
True
,
)
for
event
in
stream
:
print
(
event
)
The async client uses the exact same interface.
import
asyncio
from
openai
import
AsyncOpenAI
client
=
AsyncOpenAI
()
async
def
main
():
stream
=
await
client
.
responses
.
create
(
model
=
"gpt-5.2"
,
input
=
"Write a one-sentence bedtime story about a unicorn."
,
stream
=
True
,
)
async
for
event
in
stream
:
print
(
event
)
asyncio
.
run
(
main
())
Realtime API
The Realtime API enables you to build low-latency, multi-modal conversational experiences. It currently supports text and audio as both input and output, as well as
function calling
through a WebSocket connection.
Under the hood the SDK uses the
websockets
library to manage connections.
The Realtime API works through a combination of client-sent events and server-sent events. Clients can send events to do things like update session configuration or send text and audio inputs. Server events confirm when audio responses have completed, or when a text response from the model has been received. A full event reference can be found
here
and a guide can be found
here
.
Basic text based example:
import
asyncio
from
openai
import
AsyncOpenAI
async
def
main
():
client
=
AsyncOpenAI
()
async
with
client
.
realtime
.
connect
(
model
=
"gpt-realtime"
)
as
connection
:
await
connection
.
session
.
update
(
session
=
{
"type"
:
"realtime"
,
"output_modalities"
:
[
"text"
]}
)
await
connection
.
conversation
.
item
.
create
(
item
=
{
"type"
:
"message"
,
"role"
:
"user"
,
"content"
:
[{
"type"
:
"input_text"
,
"text"
:
"Say hello!"
}],
}
)
await
connection
.
response
.
create
()
async
for
event
in
connection
:
if
event
.
type
==
"response.output_text.delta"
:
print
(
event
.
delta
,
flush
=
True
,
end
=
""
)
elif
event
.
type
==
"response.output_text.done"
:
print
()
elif
event
.
type
==
"response.done"
:
break
asyncio
.
run
(
main
())
However the real magic of the Realtime API is handling audio inputs / outputs, see this example
TUI script
for a fully fledged example.
Realtime error handling
Whenever an error occurs, the Realtime API will send an
error
event
and the connection will stay open and remain usable. This means you need to handle it yourself, as
no errors are raised directly
by the SDK when an
error
event comes in.
client
=
AsyncOpenAI
()
async
with
client
.
realtime
.
connect
(
model
=
"gpt-realtime"
)
as
connection
:
...
async
for
event
in
connection
:
if
event
.
type
==
'error'
:
print
(
event
.
error
.
type
)
print
(
event
.
error
.
code
)
print
(
event
.
error
.
event_id
)
print
(
event
.
error
.
message
)
Using types
Nested request parameters are
TypedDicts
. Responses are
Pydantic models
which also provide helper methods for things like:
Serializing back into JSON,
model.to_json()
Converting to a dictionary,
model.to_dict()
Typed requests and responses provide autocomplete and documentation within your editor. If you would like to see type errors in VS Code to help catch bugs earlier, set
python.analysis.typeCheckingMode
to
basic
.
Pagination
List methods in the OpenAI API are paginated.
This library provides auto-paginating iterators with each list response, so you do not have to request successive pages manually:
from
openai
import
OpenAI
client
=
OpenAI
()
all_jobs
=
[]
# Automatically fetches more pages as needed.
for
job
in
client
.
fine_tuning
.
jobs
.
list
(
limit
=
20
,
):
# Do something with job here
all_jobs
.
append
(
job
)
print
(
all_jobs
)
Or, asynchronously:
import
asyncio
from
openai
import
AsyncOpenAI
client
=
AsyncOpenAI
()
async
def
main
()
->
None
:
all_jobs
=
[]
# Iterate through items across all pages, issuing requests as needed.
async
for
job
in
client
.
fine_tuning
.
jobs
.
list
(
limit
=
20
,
):
all_jobs
.
append
(
job
)
print
(
all_jobs
)
asyncio
.
run
(
main
())
Alternatively, you can use the
.has_next_page()
,
.next_page_info()
, or
.get_next_page()
methods for more granular control working with pages:
first_page
=
await
client
.
fine_tuning
.
jobs
.
list
(
limit
=
20
,
)
if
first_page
.
has_next_page
():
print
(
f
"will fetch next page using these details:
{
first_page
.
next_page_info
()
}
"
)
next_page
=
await
first_page
.
get_next_page
()
print
(
f
"number of items we just fetched:
{
len
(
next_page
.
data
)
}
"
)
# Remove `await` for non-async usage.
Or just work directly with the returned data:
first_page
=
await
client
.
fine_tuning
.
jobs
.
list
(
limit
=
20
,
)
print
(
f
"next page cursor:
{
first_page
.
after
}
"
)
# => "next page cursor: ..."
for
job
in
first_page
.
data
:
print
(
job
.
id
)
# Remove `await` for non-async usage.
Nested params
Nested parameters are dictionaries, typed using
TypedDict
, for example:
from
openai
import
OpenAI
client
=
OpenAI
()
response
=
client
.
chat
.
responses
.
create
(
input
=
[
{
"role"
:
"user"
,
"content"
:
"How much ?"
,
}
],
model
=
"gpt-5.2"
,
response_format
=
{
"type"
:
"json_object"
},
)
File uploads
Request parameters that correspond to file uploads can be passed as
bytes
, or a
PathLike
instance or a tuple of
(filename, contents, media type)
.
from
pathlib
import
Path
from
openai
import
OpenAI
client
=
OpenAI
()
client
.
files
.
create
(
file
=
Path
(
"input.jsonl"
),
purpose
=
"fine-tune"
,
)
The async client uses the exact same interface. If you pass a
PathLike
instance, the file contents will be read asynchronously automatically.
Webhook Verification
Verifying webhook signatures is
optional but encouraged
.
For more information about webhooks, see
the API docs
.
Parsing webhook payloads
For most use cases, you will likely want to verify the webhook and parse the payload at the same time. To achieve this, we provide the method
client.webhooks.unwrap()
, which parses a webhook request and verifies that it was sent by OpenAI. This method will raise an error if the signature is invalid.
Note that the
body
parameter must be the raw JSON string sent from the server (do not parse it first). The
.unwrap()
method will parse this JSON for you into an event object after verifying the webhook was sent from OpenAI.
from
openai
import
OpenAI
from
flask
import
Flask
,
request
app
=
Flask
(
__name__
)
client
=
OpenAI
()
# OPENAI_WEBHOOK_SECRET environment variable is used by default
@app
.
route
(
"/webhook"
,
methods
=
[
"POST"
])
def
webhook
():
request_body
=
request
.
get_data
(
as_text
=
True
)
try
:
event
=
client
.
webhooks
.
unwrap
(
request_body
,
request
.
headers
)
if
event
.
type
==
"response.completed"
:
print
(
"Response completed:"
,
event
.
data
)
elif
event
.
type
==
"response.failed"
:
print
(
"Response failed:"
,
event
.
data
)
else
:
print
(
"Unhandled event type:"
,
event
.
type
)
return
"ok"
except
Exception
as
e
:
print
(
"Invalid signature:"
,
e
)
return
"Invalid signature"
,
400
if
__name__
==
"__main__"
:
app
.
run
(
port
=
8000
)
Verifying webhook payloads directly
In some cases, you may want to verify the webhook separately from parsing the payload. If you prefer to handle these steps separately, we provide the method
client.webhooks.verify_signature()
to
only verify
the signature of a webhook request. Like
.unwrap()
, this method will raise an error if the signature is invalid.
Note that the
body
parameter must be the raw JSON string sent from the server (do not parse it first). You will then need to parse the body after verifying the signature.
import
json
from
openai
import
OpenAI
from
flask
import
Flask
,
request
app
=
Flask
(
__name__
)
client
=
OpenAI
()
# OPENAI_WEBHOOK_SECRET environment variable is used by default
@app
.
route
(
"/webhook"
,
methods
=
[
"POST"
])
def
webhook
():
request_body
=
request
.
get_data
(
as_text
=
True
)
try
:
client
.
webhooks
.
verify_signature
(
request_body
,
request
.
headers
)
# Parse the body after verification
event
=
json
.
loads
(
request_body
)
print
(
"Verified event:"
,
event
)
return
"ok"
except
Exception
as
e
:
print
(
"Invalid signature:"
,
e
)
return
"Invalid signature"
,
400
if
__name__
==
"__main__"
:
app
.
run
(
port
=
8000
)
Handling errors
When the library is unable to connect to the API (for example, due to network connection problems or a timeout), a subclass of
openai.APIConnectionError
is raised.
When the API returns a non-success status code (that is, 4xx or 5xx
response), a subclass of
openai.APIStatusError
is raised, containing
status_code
and
response
properties.
All errors inherit from
openai.APIError
.
import
openai
from
openai
import
OpenAI
client
=
OpenAI
()
try
:
client
.
fine_tuning
.
jobs
.
create
(
model
=
"gpt-4o"
,
training_file
=
"file-abc123"
,
)
except
openai
.
APIConnectionError
as
e
:
print
(
"The server could not be reached"
)
print
(
e
.
__cause__
)
# an underlying Exception, likely raised within httpx.
except
openai
.
RateLimitError
as
e
:
print
(
"A 429 status code was received; we should back off a bit."
)
except
openai
.
APIStatusError
as
e
:
print
(
"Another non-200-range status code was received"
)
print
(
e
.
status_code
)
print
(
e
.
response
)
Error codes are as follows:
Status Code
Error Type
400
BadRequestError
401
AuthenticationError
403
PermissionDeniedError
404
NotFoundError
422
UnprocessableEntityError
429
RateLimitError
>=500
InternalServerError
N/A
APIConnectionError
Request IDs
For more information on debugging requests, see
these docs
All object responses in the SDK provide a
_request_id
property which is added from the
x-request-id
response header so that you can quickly log failing requests and report them back to OpenAI.
response
=
await
client
.
responses
.
create
(
model
=
"gpt-5.2"
,
input
=
"Say 'this is a test'."
,
)
print
(
response
.
_request_id
)
# req_123
Note that unlike other properties that use an
_
prefix, the
_request_id
property
is
public. Unless documented otherwise,
all
other
_
prefix properties,
methods and modules are
private
.
[!IMPORTANT]
If you need to access request IDs for failed requests you must catch the
APIStatusError
exception
import
openai
try
:
completion
=
await
client
.
chat
.
completions
.
create
(
messages
=
[{
"role"
:
"user"
,
"content"
:
"Say this is a test"
}],
model
=
"gpt-5.2"
)
except
openai
.
APIStatusError
as
exc
:
print
(
exc
.
request_id
)
# req_123
raise
exc
Retries
Certain errors are automatically retried 2 times by default, with a short exponential backoff.
Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict,
429 Rate Limit, and >=500 Internal errors are all retried by default.
You can use the
max_retries
option to configure or disable retry settings:
from
openai
import
OpenAI
# Configure the default for all requests:
client
=
OpenAI
(
# default is 2
max_retries
=
0
,
)
# Or, configure per-request:
client
.
with_options
(
max_retries
=
5
)
.
chat
.
completions
.
create
(
messages
=
[
{
"role"
:
"user"
,
"content"
:
"How can I get the name of the current day in JavaScript?"
,
}
],
model
=
"gpt-5.2"
,
)
Timeouts
By default requests time out after 10 minutes. You can configure this with a
timeout
option,
which accepts a float or an
httpx.Timeout
object:
from
openai
import
OpenAI
# Configure the default for all requests:
client
=
OpenAI
(
# 20 seconds (default is 10 minutes)
timeout
=
20.0
,
)
# More granular control:
client
=
OpenAI
(
timeout
=
httpx
.
Timeout
(
60.0
,
read
=
5.0
,
write
=
10.0
,
connect
=
2.0
),
)
# Override per-request:
client
.
with_options
(
timeout
=
5.0
)
.
chat
.
completions
.
create
(
messages
=
[
{
"role"
:
"user"
,
"content"
:
"How can I list all files in a directory using Python?"
,
}
],
model
=
"gpt-5.2"
,
)
On timeout, an
APITimeoutError
is thrown.
Note that requests that time out are
retried twice by default
.
Advanced
Logging
We use the standard library
logging
module.
You can enable logging by setting the environment variable
OPENAI_LOG
to
info
.
$
export
OPENAI_LOG
=
info
Or to
debug
for more verbose logging.
How to tell whether
None
means
null
or missing
In an API response, a field may be explicitly
null
, or missing entirely; in either case, its value is
None
in this library. You can differentiate the two cases with
.model_fields_set
:
if
response
.
my_field
is
None
:
if
'my_field'
not
in
response
.
model_fields_set
:
print
(
'Got json like
{}
, without a "my_field" key present at all.'
)
else
:
print
(
'Got json like {"my_field": null}.'
)
Accessing raw response data (e.g. headers)
The "raw" Response object can be accessed by prefixing
.with_raw_response.
to any HTTP method call, e.g.,
from
openai
import
OpenAI
client
=
OpenAI
()
response
=
client
.
chat
.
completions
.
with_raw_response
.
create
(
messages
=
[{
"role"
:
"user"
,
"content"
:
"Say this is a test"
,
}],
model
=
"gpt-5.2"
,
)
print
(
response
.
headers
.
get
(
'X-My-Header'
))
completion
=
response
.
parse
()
# get the object that `chat.completions.create()` would have returned
print
(
completion
)
These methods return a
LegacyAPIResponse
object. This is a legacy class as we're changing it slightly in the next major version.
For the sync client this will mostly be the same with the exception
of
content
&
text
will be methods instead of properties. In the
async client, all methods will be async.
A migration script will be provided & the migration in general should
be smooth.
.with_streaming_response
The above interface eagerly reads the full response body when you make the request, which may not always be what you want.
To stream the response body, use
.with_streaming_response
instead, which requires a context manager and only reads the response body once you call
.read()
,
.text()
,
.json()
,
.iter_bytes()
,
.iter_text()
,
.iter_lines()
or
.parse()
. In the async client, these are async methods.
As such,
.with_streaming_response
methods return a different
APIResponse
object, and the async client returns an
AsyncAPIResponse
object.
with
client
.
chat
.
completions
.
with_streaming_response
.
create
(
messages
=
[
{
"role"
:
"user"
,
"content"
:
"Say this is a test"
,
}
],
model
=
"gpt-5.2"
,
)
as
response
:
print
(
response
.
headers
.
get
(
"X-My-Header"
))
for
line
in
response
.
iter_lines
():
print
(
line
)
The context manager is required so that the response will reliably be closed.
Making custom/undocumented requests
This library is typed for convenient access to the documented API.
If you need to access undocumented endpoints, params, or response properties, the library can still be used.
Undocumented endpoints
To make requests to undocumented endpoints, you can make requests using
client.get
,
client.post
, and other
http verbs. Options on the client will be respected (such as retries) when making this request.
import
httpx
response
=
client
.
post
(
"/foo"
,
cast_to
=
httpx
.
Response
,
body
=
{
"my_param"
:
True
},
)
print
(
response
.
headers
.
get
(
"x-foo"
))
Undocumented request params
If you want to explicitly send an extra param, you can do so with the
extra_query
,
extra_body
, and
extra_headers
request
options.
Undocumented response properties
To access undocumented response properties, you can access the extra fields like
response.unknown_prop
. You
can also get all the extra fields on the Pydantic model as a dict with
response.model_extra
.
Configuring the HTTP client
You can directly override the
httpx client
to customize it for your use case, including:
Support for
proxies
Custom
transports
Additional
advanced
functionality
import
httpx
from
openai
import
OpenAI
,
DefaultHttpxClient
client
=
OpenAI
(
# Or use the `OPENAI_BASE_URL` env var
base_url
=
"http://my.test.server.example.com:8083/v1"
,
http_client
=
DefaultHttpxClient
(
proxy
=
"http://my.test.proxy.example.com"
,
transport
=
httpx
.
HTTPTransport
(
local_address
=
"0.0.0.0"
),
),
)
You can also customize the client on a per-request basis by using
with_options()
:
client
.
with_options
(
http_client
=
DefaultHttpxClient
(
...
))
Managing HTTP resources
By default the library closes underlying HTTP connections whenever the client is
garbage collected
. You can manually close the client using the
.close()
method if desired, or with a context manager that closes when exiting.
from
openai
import
OpenAI
with
OpenAI
()
as
client
:
# make requests here
...
# HTTP client is now closed
Microsoft Azure OpenAI
To use this library with
Azure OpenAI
, use the
AzureOpenAI
class instead of the
OpenAI
class.
[!IMPORTANT]
The Azure API shape differs from the core API shape which means that the static types for responses / params
won't always be correct.
from
openai
import
AzureOpenAI
# gets the API Key from environment variable AZURE_OPENAI_API_KEY
client
=
AzureOpenAI
(
# https://learn.microsoft.com/azure/ai-services/openai/reference#rest-api-versioning
api_version
=
"2023-07-01-preview"
,
# https://learn.microsoft.com/azure/cognitive-services/openai/how-to/create-resource?pivots=web-portal#create-a-resource
azure_endpoint
=
"https://example-endpoint.openai.azure.com"
,
)
completion
=
client
.
chat
.
completions
.
create
(
model
=
"deployment-name"
,
# e.g. gpt-35-instant
messages
=
[
{
"role"
:
"user"
,
"content"
:
"How do I output all files in a directory using Python?"
,
},
],
)
print
(
completion
.
to_json
())
In addition to the options provided in the base
OpenAI
client, the following options are provided:
azure_endpoint
(or the
AZURE_OPENAI_ENDPOINT
environment variable)
azure_deployment
api_version
(or the
OPENAI_API_VERSION
environment variable)
azure_ad_token
(or the
AZURE_OPENAI_AD_TOKEN
environment variable)
azure_ad_token_provider
An example of using the client with Microsoft Entra ID (formerly known as Azure Active Directory) can be found
here
.
Versioning
This package generally follows
SemVer
conventions, though certain backwards-incompatible changes may be released as minor versions:
Changes that only affect static types, without breaking runtime behavior.
Changes to library internals which are technically public but not intended or documented for external use.
(Please open a GitHub issue to let us know if you are relying on such internals.)
Changes that we do not expect to impact the vast majority of users in practice.
We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.
We are keen for your feedback; please open an
issue
with questions, bugs, or suggestions.
Determining the installed version
If you've upgraded to the latest version but aren't seeing any new features you were expecting then your python environment is likely still using an older version.
You can determine the version that is being used at runtime with:
import
openai
print
(
openai
.
__version__
)
Requirements
Python 3.9 or higher.
Contributing
See
the contributing documentation
. |
| Markdown | [Skip to main content](https://pypi.org/project/openai/#content)
Switch to mobile version
Warning Some features may not work without JavaScript. Please try enabling it if you encounter problems.
Join us in Long Beach, CA starting May 13, 2026. Grab your ticket and discounted hotel today before they’re gone! [REGISTER FOR PYCON US\!](https://us.pycon.org/2026/attend/information/)
[](https://pypi.org/)
- [Help](https://pypi.org/help/)
- [Docs](https://docs.pypi.org/)
- [Sponsors](https://pypi.org/sponsors/)
- [Log in](https://pypi.org/account/login/?next=https%3A%2F%2Fpypi.org%2Fproject%2Fopenai%2F)
- [Register](https://pypi.org/account/register/)
Menu
- [Help](https://pypi.org/help/)
- [Docs](https://docs.pypi.org/)
- [Sponsors](https://pypi.org/sponsors/)
- [Log in](https://pypi.org/account/login/?next=https%3A%2F%2Fpypi.org%2Fproject%2Fopenai%2F)
- [Register](https://pypi.org/account/register/)
# openai 2.31.0
pip install openai Copy PIP instructions
[Latest version](https://pypi.org/project/openai/)
Released: Apr 8, 2026
The official Python library for the openai API
### Navigation
- [Project description](https://pypi.org/project/openai/#description)
- [Release history](https://pypi.org/project/openai/#history)
- [Download files](https://pypi.org/project/openai/#files)
### Verified details
*These details have been [verified by PyPI](https://docs.pypi.org/project_metadata/#verified-details)*
###### Owner
- [OpenAI](https://pypi.org/org/openai/)
###### Maintainers
[ ddeville](https://pypi.org/user/ddeville/) [ dschnurr-openai](https://pypi.org/user/dschnurr-openai/) [ gdb](https://pypi.org/user/gdb/) [ hponde\_oai](https://pypi.org/user/hponde_oai/) [ jhallard](https://pypi.org/user/jhallard/) [ tomerkOpenAI](https://pypi.org/user/tomerkOpenAI/)
### Unverified details
*These details have **not** been verified by PyPI*
###### Project links
- [Homepage](https://github.com/openai/openai-python)
- [Repository](https://github.com/openai/openai-python)
###### Meta
- **License:** Apache Software License (Apache-2.0)
- **Author:** [OpenAI](mailto:support@openai.com)
- **Requires:** Python \>=3.9
- **Provides-Extra:** `aiohttp` , `datalib` , `realtime` , `voice-helpers`
###### Classifiers
- **Intended Audience**
- [Developers](https://pypi.org/search/?c=Intended+Audience+%3A%3A+Developers)
- **License**
- [OSI Approved :: Apache Software License](https://pypi.org/search/?c=License+%3A%3A+OSI+Approved+%3A%3A+Apache+Software+License)
- **Operating System**
- [MacOS](https://pypi.org/search/?c=Operating+System+%3A%3A+MacOS)
- [Microsoft :: Windows](https://pypi.org/search/?c=Operating+System+%3A%3A+Microsoft+%3A%3A+Windows)
- [OS Independent](https://pypi.org/search/?c=Operating+System+%3A%3A+OS+Independent)
- [POSIX](https://pypi.org/search/?c=Operating+System+%3A%3A+POSIX)
- [POSIX :: Linux](https://pypi.org/search/?c=Operating+System+%3A%3A+POSIX+%3A%3A+Linux)
- **Programming Language**
- [Python :: 3.9](https://pypi.org/search/?c=Programming+Language+%3A%3A+Python+%3A%3A+3.9)
- [Python :: 3.10](https://pypi.org/search/?c=Programming+Language+%3A%3A+Python+%3A%3A+3.10)
- [Python :: 3.11](https://pypi.org/search/?c=Programming+Language+%3A%3A+Python+%3A%3A+3.11)
- [Python :: 3.12](https://pypi.org/search/?c=Programming+Language+%3A%3A+Python+%3A%3A+3.12)
- [Python :: 3.13](https://pypi.org/search/?c=Programming+Language+%3A%3A+Python+%3A%3A+3.13)
- [Python :: 3.14](https://pypi.org/search/?c=Programming+Language+%3A%3A+Python+%3A%3A+3.14)
- **Topic**
- [Software Development :: Libraries :: Python Modules](https://pypi.org/search/?c=Topic+%3A%3A+Software+Development+%3A%3A+Libraries+%3A%3A+Python+Modules)
- **Typing**
- [Typed](https://pypi.org/search/?c=Typing+%3A%3A+Typed)
[Report project as malware](https://pypi.org/project/openai/submit-malware-report/)
- [Project description](https://pypi.org/project/openai/#description)
- [Project details](https://pypi.org/project/openai/#data)
- [Release history](https://pypi.org/project/openai/#history)
- [Download files](https://pypi.org/project/openai/#files)
## Project description
# OpenAI Python API library
[](https://pypi.org/project/openai/)
The OpenAI Python library provides convenient access to the OpenAI REST API from any Python 3.9+ application. The library includes type definitions for all request params and response fields, and offers both synchronous and asynchronous clients powered by [httpx](https://github.com/encode/httpx).
It is generated from our [OpenAPI specification](https://github.com/openai/openai-openapi) with [Stainless](https://stainlessapi.com/).
## Documentation
The REST API documentation can be found on [platform.openai.com](https://platform.openai.com/docs/api-reference). The full API of this library can be found in [api.md](https://github.com/openai/openai-python/tree/main/api.md).
## Installation
```
# install from PyPI
pip install openai
```
## Usage
The full API of this library can be found in [api.md](https://github.com/openai/openai-python/tree/main/api.md).
The primary API for interacting with OpenAI models is the [Responses API](https://platform.openai.com/docs/api-reference/responses). You can generate text from the model with the code below.
```
import os
from openai import OpenAI
client = OpenAI(
# This is the default and can be omitted
api_key=os.environ.get("OPENAI_API_KEY"),
)
response = client.responses.create(
model="gpt-5.2",
instructions="You are a coding assistant that talks like a pirate.",
input="How do I check if a Python object is an instance of a class?",
)
print(response.output_text)
```
The previous standard (supported indefinitely) for generating text is the [Chat Completions API](https://platform.openai.com/docs/api-reference/chat). You can use that API to generate text from the model with the code below.
```
from openai import OpenAI
client = OpenAI()
completion = client.chat.completions.create(
model="gpt-5.2",
messages=[
{"role": "developer", "content": "Talk like a pirate."},
{
"role": "user",
"content": "How do I check if a Python object is an instance of a class?",
},
],
)
print(completion.choices[0].message.content)
```
While you can provide an `api_key` keyword argument, we recommend using [python-dotenv](https://pypi.org/project/python-dotenv/) to add `OPENAI_API_KEY="My API Key"` to your `.env` file so that your API key is not stored in source control. [Get an API key here](https://platform.openai.com/settings/organization/api-keys).
### Workload Identity Authentication
For secure, automated environments like cloud-managed Kubernetes, Azure, and Google Cloud Platform, you can use workload identity authentication with short-lived tokens from cloud identity providers instead of long-lived API keys.
#### Kubernetes (service account tokens)
```
from openai import OpenAI
from openai.auth import k8s_service_account_token_provider
client = OpenAI(
workload_identity={
"client_id": "your-client-id",
"identity_provider_id": "idp-123",
"service_account_id": "sa-456",
"provider": k8s_service_account_token_provider(
"/var/run/secrets/kubernetes.io/serviceaccount/token"
),
},
organization="org-xyz",
project="proj-abc",
)
response = client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": "Hello!"}],
)
```
#### Azure (managed identity)
```
from openai import OpenAI
from openai.auth import azure_managed_identity_token_provider
client = OpenAI(
workload_identity={
"client_id": "your-client-id",
"identity_provider_id": "idp-123",
"service_account_id": "sa-456",
"provider": azure_managed_identity_token_provider(
resource="https://management.azure.com/",
),
},
)
```
#### Google Cloud Platform (compute engine metadata)
```
from openai import OpenAI
from openai.auth import gcp_id_token_provider
client = OpenAI(
workload_identity={
"client_id": "your-client-id",
"identity_provider_id": "idp-123",
"service_account_id": "sa-456",
"provider": gcp_id_token_provider(audience="https://api.openai.com/v1"),
},
)
```
#### Custom subject token provider
```
from openai import OpenAI
def get_custom_token() -> str:
return "your-jwt-token"
client = OpenAI(
workload_identity={
"client_id": "your-client-id",
"identity_provider_id": "idp-123",
"service_account_id": "sa-456",
"provider": {
"token_type": "jwt",
"get_token": get_custom_token,
},
}
)
```
You can also customize the token refresh buffer (default is 1200 seconds (20 minutes) before expiration):
```
from openai import OpenAI
from openai.auth import k8s_service_account_token_provider
client = OpenAI(
workload_identity={
"client_id": "your-client-id",
"identity_provider_id": "idp-123",
"service_account_id": "sa-456",
"provider": k8s_service_account_token_provider("/var/token"),
"refresh_buffer_seconds": 120.0,
}
)
```
### Vision
With an image URL:
```
prompt = "What is in this image?"
img_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d5/2023_06_08_Raccoon1.jpg/1599px-2023_06_08_Raccoon1.jpg"
response = client.responses.create(
model="gpt-5.2",
input=[
{
"role": "user",
"content": [
{"type": "input_text", "text": prompt},
{"type": "input_image", "image_url": f"{img_url}"},
],
}
],
)
```
With the image as a base64 encoded string:
```
import base64
from openai import OpenAI
client = OpenAI()
prompt = "What is in this image?"
with open("path/to/image.png", "rb") as image_file:
b64_image = base64.b64encode(image_file.read()).decode("utf-8")
response = client.responses.create(
model="gpt-5.2",
input=[
{
"role": "user",
"content": [
{"type": "input_text", "text": prompt},
{"type": "input_image", "image_url": f"data:image/png;base64,{b64_image}"},
],
}
],
)
```
## Async usage
Simply import `AsyncOpenAI` instead of `OpenAI` and use `await` with each API call:
```
import os
import asyncio
from openai import AsyncOpenAI
client = AsyncOpenAI(
# This is the default and can be omitted
api_key=os.environ.get("OPENAI_API_KEY"),
)
async def main() -> None:
response = await client.responses.create(
model="gpt-5.2", input="Explain disestablishmentarianism to a smart five year old."
)
print(response.output_text)
asyncio.run(main())
```
Functionality between the synchronous and asynchronous clients is otherwise identical.
### With aiohttp
By default, the async client uses `httpx` for HTTP requests. However, for improved concurrency performance you may also use `aiohttp` as the HTTP backend.
You can enable this by installing `aiohttp`:
```
# install from PyPI
pip install openai[aiohttp]
```
Then you can enable it by instantiating the client with `http_client=DefaultAioHttpClient()`:
```
import os
import asyncio
from openai import DefaultAioHttpClient
from openai import AsyncOpenAI
async def main() -> None:
async with AsyncOpenAI(
api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted
http_client=DefaultAioHttpClient(),
) as client:
chat_completion = await client.chat.completions.create(
messages=[
{
"role": "user",
"content": "Say this is a test",
}
],
model="gpt-5.2",
)
asyncio.run(main())
```
## Streaming responses
We provide support for streaming responses using Server Side Events (SSE).
```
from openai import OpenAI
client = OpenAI()
stream = client.responses.create(
model="gpt-5.2",
input="Write a one-sentence bedtime story about a unicorn.",
stream=True,
)
for event in stream:
print(event)
```
The async client uses the exact same interface.
```
import asyncio
from openai import AsyncOpenAI
client = AsyncOpenAI()
async def main():
stream = await client.responses.create(
model="gpt-5.2",
input="Write a one-sentence bedtime story about a unicorn.",
stream=True,
)
async for event in stream:
print(event)
asyncio.run(main())
```
## Realtime API
The Realtime API enables you to build low-latency, multi-modal conversational experiences. It currently supports text and audio as both input and output, as well as [function calling](https://platform.openai.com/docs/guides/function-calling) through a WebSocket connection.
Under the hood the SDK uses the [`websockets`](https://websockets.readthedocs.io/en/stable/) library to manage connections.
The Realtime API works through a combination of client-sent events and server-sent events. Clients can send events to do things like update session configuration or send text and audio inputs. Server events confirm when audio responses have completed, or when a text response from the model has been received. A full event reference can be found [here](https://platform.openai.com/docs/api-reference/realtime-client-events) and a guide can be found [here](https://platform.openai.com/docs/guides/realtime).
Basic text based example:
```
import asyncio
from openai import AsyncOpenAI
async def main():
client = AsyncOpenAI()
async with client.realtime.connect(model="gpt-realtime") as connection:
await connection.session.update(
session={"type": "realtime", "output_modalities": ["text"]}
)
await connection.conversation.item.create(
item={
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": "Say hello!"}],
}
)
await connection.response.create()
async for event in connection:
if event.type == "response.output_text.delta":
print(event.delta, flush=True, end="")
elif event.type == "response.output_text.done":
print()
elif event.type == "response.done":
break
asyncio.run(main())
```
However the real magic of the Realtime API is handling audio inputs / outputs, see this example [TUI script](https://github.com/openai/openai-python/blob/main/examples/realtime/push_to_talk_app.py) for a fully fledged example.
### Realtime error handling
Whenever an error occurs, the Realtime API will send an [`error` event](https://platform.openai.com/docs/guides/realtime-model-capabilities#error-handling) and the connection will stay open and remain usable. This means you need to handle it yourself, as *no errors are raised directly* by the SDK when an `error` event comes in.
```
client = AsyncOpenAI()
async with client.realtime.connect(model="gpt-realtime") as connection:
...
async for event in connection:
if event.type == 'error':
print(event.error.type)
print(event.error.code)
print(event.error.event_id)
print(event.error.message)
```
## Using types
Nested request parameters are [TypedDicts](https://docs.python.org/3/library/typing.html#typing.TypedDict). Responses are [Pydantic models](https://docs.pydantic.dev/) which also provide helper methods for things like:
- Serializing back into JSON, `model.to_json()`
- Converting to a dictionary, `model.to_dict()`
Typed requests and responses provide autocomplete and documentation within your editor. If you would like to see type errors in VS Code to help catch bugs earlier, set `python.analysis.typeCheckingMode` to `basic`.
## Pagination
List methods in the OpenAI API are paginated.
This library provides auto-paginating iterators with each list response, so you do not have to request successive pages manually:
```
from openai import OpenAI
client = OpenAI()
all_jobs = []
# Automatically fetches more pages as needed.
for job in client.fine_tuning.jobs.list(
limit=20,
):
# Do something with job here
all_jobs.append(job)
print(all_jobs)
```
Or, asynchronously:
```
import asyncio
from openai import AsyncOpenAI
client = AsyncOpenAI()
async def main() -> None:
all_jobs = []
# Iterate through items across all pages, issuing requests as needed.
async for job in client.fine_tuning.jobs.list(
limit=20,
):
all_jobs.append(job)
print(all_jobs)
asyncio.run(main())
```
Alternatively, you can use the `.has_next_page()`, `.next_page_info()`, or `.get_next_page()` methods for more granular control working with pages:
```
first_page = await client.fine_tuning.jobs.list(
limit=20,
)
if first_page.has_next_page():
print(f"will fetch next page using these details: {first_page.next_page_info()}")
next_page = await first_page.get_next_page()
print(f"number of items we just fetched: {len(next_page.data)}")
# Remove `await` for non-async usage.
```
Or just work directly with the returned data:
```
first_page = await client.fine_tuning.jobs.list(
limit=20,
)
print(f"next page cursor: {first_page.after}") # => "next page cursor: ..."
for job in first_page.data:
print(job.id)
# Remove `await` for non-async usage.
```
## Nested params
Nested parameters are dictionaries, typed using `TypedDict`, for example:
```
from openai import OpenAI
client = OpenAI()
response = client.chat.responses.create(
input=[
{
"role": "user",
"content": "How much ?",
}
],
model="gpt-5.2",
response_format={"type": "json_object"},
)
```
## File uploads
Request parameters that correspond to file uploads can be passed as `bytes`, or a [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike) instance or a tuple of `(filename, contents, media type)`.
```
from pathlib import Path
from openai import OpenAI
client = OpenAI()
client.files.create(
file=Path("input.jsonl"),
purpose="fine-tune",
)
```
The async client uses the exact same interface. If you pass a [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike) instance, the file contents will be read asynchronously automatically.
## Webhook Verification
Verifying webhook signatures is *optional but encouraged*.
For more information about webhooks, see [the API docs](https://platform.openai.com/docs/guides/webhooks).
### Parsing webhook payloads
For most use cases, you will likely want to verify the webhook and parse the payload at the same time. To achieve this, we provide the method `client.webhooks.unwrap()`, which parses a webhook request and verifies that it was sent by OpenAI. This method will raise an error if the signature is invalid.
Note that the `body` parameter must be the raw JSON string sent from the server (do not parse it first). The `.unwrap()` method will parse this JSON for you into an event object after verifying the webhook was sent from OpenAI.
```
from openai import OpenAI
from flask import Flask, request
app = Flask(__name__)
client = OpenAI() # OPENAI_WEBHOOK_SECRET environment variable is used by default
@app.route("/webhook", methods=["POST"])
def webhook():
request_body = request.get_data(as_text=True)
try:
event = client.webhooks.unwrap(request_body, request.headers)
if event.type == "response.completed":
print("Response completed:", event.data)
elif event.type == "response.failed":
print("Response failed:", event.data)
else:
print("Unhandled event type:", event.type)
return "ok"
except Exception as e:
print("Invalid signature:", e)
return "Invalid signature", 400
if __name__ == "__main__":
app.run(port=8000)
```
### Verifying webhook payloads directly
In some cases, you may want to verify the webhook separately from parsing the payload. If you prefer to handle these steps separately, we provide the method `client.webhooks.verify_signature()` to *only verify* the signature of a webhook request. Like `.unwrap()`, this method will raise an error if the signature is invalid.
Note that the `body` parameter must be the raw JSON string sent from the server (do not parse it first). You will then need to parse the body after verifying the signature.
```
import json
from openai import OpenAI
from flask import Flask, request
app = Flask(__name__)
client = OpenAI() # OPENAI_WEBHOOK_SECRET environment variable is used by default
@app.route("/webhook", methods=["POST"])
def webhook():
request_body = request.get_data(as_text=True)
try:
client.webhooks.verify_signature(request_body, request.headers)
# Parse the body after verification
event = json.loads(request_body)
print("Verified event:", event)
return "ok"
except Exception as e:
print("Invalid signature:", e)
return "Invalid signature", 400
if __name__ == "__main__":
app.run(port=8000)
```
## Handling errors
When the library is unable to connect to the API (for example, due to network connection problems or a timeout), a subclass of `openai.APIConnectionError` is raised.
When the API returns a non-success status code (that is, 4xx or 5xx response), a subclass of `openai.APIStatusError` is raised, containing `status_code` and `response` properties.
All errors inherit from `openai.APIError`.
```
import openai
from openai import OpenAI
client = OpenAI()
try:
client.fine_tuning.jobs.create(
model="gpt-4o",
training_file="file-abc123",
)
except openai.APIConnectionError as e:
print("The server could not be reached")
print(e.__cause__) # an underlying Exception, likely raised within httpx.
except openai.RateLimitError as e:
print("A 429 status code was received; we should back off a bit.")
except openai.APIStatusError as e:
print("Another non-200-range status code was received")
print(e.status_code)
print(e.response)
```
Error codes are as follows:
| Status Code | Error Type |
|---|---|
| 400 | `BadRequestError` |
| 401 | `AuthenticationError` |
| 403 | `PermissionDeniedError` |
| 404 | `NotFoundError` |
| 422 | `UnprocessableEntityError` |
| 429 | `RateLimitError` |
| \>=500 | `InternalServerError` |
| N/A | `APIConnectionError` |
## Request IDs
> For more information on debugging requests, see [these docs](https://platform.openai.com/docs/api-reference/debugging-requests)
All object responses in the SDK provide a `_request_id` property which is added from the `x-request-id` response header so that you can quickly log failing requests and report them back to OpenAI.
```
response = await client.responses.create(
model="gpt-5.2",
input="Say 'this is a test'.",
)
print(response._request_id) # req_123
```
Note that unlike other properties that use an `_` prefix, the `_request_id` property *is* public. Unless documented otherwise, *all* other `_` prefix properties, methods and modules are *private*.
> \[!IMPORTANT\]
> If you need to access request IDs for failed requests you must catch the `APIStatusError` exception
```
import openai
try:
completion = await client.chat.completions.create(
messages=[{"role": "user", "content": "Say this is a test"}], model="gpt-5.2"
)
except openai.APIStatusError as exc:
print(exc.request_id) # req_123
raise exc
```
## Retries
Certain errors are automatically retried 2 times by default, with a short exponential backoff. Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict, 429 Rate Limit, and \>=500 Internal errors are all retried by default.
You can use the `max_retries` option to configure or disable retry settings:
```
from openai import OpenAI
# Configure the default for all requests:
client = OpenAI(
# default is 2
max_retries=0,
)
# Or, configure per-request:
client.with_options(max_retries=5).chat.completions.create(
messages=[
{
"role": "user",
"content": "How can I get the name of the current day in JavaScript?",
}
],
model="gpt-5.2",
)
```
## Timeouts
By default requests time out after 10 minutes. You can configure this with a `timeout` option, which accepts a float or an [`httpx.Timeout`](https://www.python-httpx.org/advanced/timeouts/#fine-tuning-the-configuration) object:
```
from openai import OpenAI
# Configure the default for all requests:
client = OpenAI(
# 20 seconds (default is 10 minutes)
timeout=20.0,
)
# More granular control:
client = OpenAI(
timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0),
)
# Override per-request:
client.with_options(timeout=5.0).chat.completions.create(
messages=[
{
"role": "user",
"content": "How can I list all files in a directory using Python?",
}
],
model="gpt-5.2",
)
```
On timeout, an `APITimeoutError` is thrown.
Note that requests that time out are [retried twice by default](https://github.com/openai/openai-python/tree/main/#retries).
## Advanced
### Logging
We use the standard library [`logging`](https://docs.python.org/3/library/logging.html) module.
You can enable logging by setting the environment variable `OPENAI_LOG` to `info`.
```
$ export OPENAI_LOG=info
```
Or to `debug` for more verbose logging.
### How to tell whether `None` means `null` or missing
In an API response, a field may be explicitly `null`, or missing entirely; in either case, its value is `None` in this library. You can differentiate the two cases with `.model_fields_set`:
```
if response.my_field is None:
if 'my_field' not in response.model_fields_set:
print('Got json like {}, without a "my_field" key present at all.')
else:
print('Got json like {"my_field": null}.')
```
### Accessing raw response data (e.g. headers)
The "raw" Response object can be accessed by prefixing `.with_raw_response.` to any HTTP method call, e.g.,
```
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.with_raw_response.create(
messages=[{
"role": "user",
"content": "Say this is a test",
}],
model="gpt-5.2",
)
print(response.headers.get('X-My-Header'))
completion = response.parse() # get the object that `chat.completions.create()` would have returned
print(completion)
```
These methods return a [`LegacyAPIResponse`](https://github.com/openai/openai-python/tree/main/src/openai/_legacy_response.py) object. This is a legacy class as we're changing it slightly in the next major version.
For the sync client this will mostly be the same with the exception of `content` & `text` will be methods instead of properties. In the async client, all methods will be async.
A migration script will be provided & the migration in general should be smooth.
#### `.with_streaming_response`
The above interface eagerly reads the full response body when you make the request, which may not always be what you want.
To stream the response body, use `.with_streaming_response` instead, which requires a context manager and only reads the response body once you call `.read()`, `.text()`, `.json()`, `.iter_bytes()`, `.iter_text()`, `.iter_lines()` or `.parse()`. In the async client, these are async methods.
As such, `.with_streaming_response` methods return a different [`APIResponse`](https://github.com/openai/openai-python/tree/main/src/openai/_response.py) object, and the async client returns an [`AsyncAPIResponse`](https://github.com/openai/openai-python/tree/main/src/openai/_response.py) object.
```
with client.chat.completions.with_streaming_response.create(
messages=[
{
"role": "user",
"content": "Say this is a test",
}
],
model="gpt-5.2",
) as response:
print(response.headers.get("X-My-Header"))
for line in response.iter_lines():
print(line)
```
The context manager is required so that the response will reliably be closed.
### Making custom/undocumented requests
This library is typed for convenient access to the documented API.
If you need to access undocumented endpoints, params, or response properties, the library can still be used.
#### Undocumented endpoints
To make requests to undocumented endpoints, you can make requests using `client.get`, `client.post`, and other http verbs. Options on the client will be respected (such as retries) when making this request.
```
import httpx
response = client.post(
"/foo",
cast_to=httpx.Response,
body={"my_param": True},
)
print(response.headers.get("x-foo"))
```
#### Undocumented request params
If you want to explicitly send an extra param, you can do so with the `extra_query`, `extra_body`, and `extra_headers` request options.
#### Undocumented response properties
To access undocumented response properties, you can access the extra fields like `response.unknown_prop`. You can also get all the extra fields on the Pydantic model as a dict with [`response.model_extra`](https://docs.pydantic.dev/latest/api/base_model/#pydantic.BaseModel.model_extra).
### Configuring the HTTP client
You can directly override the [httpx client](https://www.python-httpx.org/api/#client) to customize it for your use case, including:
- Support for [proxies](https://www.python-httpx.org/advanced/proxies/)
- Custom [transports](https://www.python-httpx.org/advanced/transports/)
- Additional [advanced](https://www.python-httpx.org/advanced/clients/) functionality
```
import httpx
from openai import OpenAI, DefaultHttpxClient
client = OpenAI(
# Or use the `OPENAI_BASE_URL` env var
base_url="http://my.test.server.example.com:8083/v1",
http_client=DefaultHttpxClient(
proxy="http://my.test.proxy.example.com",
transport=httpx.HTTPTransport(local_address="0.0.0.0"),
),
)
```
You can also customize the client on a per-request basis by using `with_options()`:
```
client.with_options(http_client=DefaultHttpxClient(...))
```
### Managing HTTP resources
By default the library closes underlying HTTP connections whenever the client is [garbage collected](https://docs.python.org/3/reference/datamodel.html#object.__del__). You can manually close the client using the `.close()` method if desired, or with a context manager that closes when exiting.
```
from openai import OpenAI
with OpenAI() as client:
# make requests here
...
# HTTP client is now closed
```
## Microsoft Azure OpenAI
To use this library with [Azure OpenAI](https://learn.microsoft.com/azure/ai-services/openai/overview), use the `AzureOpenAI` class instead of the `OpenAI` class.
> \[!IMPORTANT\] The Azure API shape differs from the core API shape which means that the static types for responses / params won't always be correct.
```
from openai import AzureOpenAI
# gets the API Key from environment variable AZURE_OPENAI_API_KEY
client = AzureOpenAI(
# https://learn.microsoft.com/azure/ai-services/openai/reference#rest-api-versioning
api_version="2023-07-01-preview",
# https://learn.microsoft.com/azure/cognitive-services/openai/how-to/create-resource?pivots=web-portal#create-a-resource
azure_endpoint="https://example-endpoint.openai.azure.com",
)
completion = client.chat.completions.create(
model="deployment-name", # e.g. gpt-35-instant
messages=[
{
"role": "user",
"content": "How do I output all files in a directory using Python?",
},
],
)
print(completion.to_json())
```
In addition to the options provided in the base `OpenAI` client, the following options are provided:
- `azure_endpoint` (or the `AZURE_OPENAI_ENDPOINT` environment variable)
- `azure_deployment`
- `api_version` (or the `OPENAI_API_VERSION` environment variable)
- `azure_ad_token` (or the `AZURE_OPENAI_AD_TOKEN` environment variable)
- `azure_ad_token_provider`
An example of using the client with Microsoft Entra ID (formerly known as Azure Active Directory) can be found [here](https://github.com/openai/openai-python/blob/main/examples/azure_ad.py).
## Versioning
This package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:
1. Changes that only affect static types, without breaking runtime behavior.
2. Changes to library internals which are technically public but not intended or documented for external use. *(Please open a GitHub issue to let us know if you are relying on such internals.)*
3. Changes that we do not expect to impact the vast majority of users in practice.
We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.
We are keen for your feedback; please open an [issue](https://www.github.com/openai/openai-python/issues) with questions, bugs, or suggestions.
### Determining the installed version
If you've upgraded to the latest version but aren't seeing any new features you were expecting then your python environment is likely still using an older version.
You can determine the version that is being used at runtime with:
```
import openai
print(openai.__version__)
```
## Requirements
Python 3.9 or higher.
## Contributing
See [the contributing documentation](https://github.com/openai/openai-python/tree/main/CONTRIBUTING.md).
## Project details
### Verified details
*These details have been [verified by PyPI](https://docs.pypi.org/project_metadata/#verified-details)*
###### Owner
- [OpenAI](https://pypi.org/org/openai/)
###### Maintainers
[ ddeville](https://pypi.org/user/ddeville/) [ dschnurr-openai](https://pypi.org/user/dschnurr-openai/) [ gdb](https://pypi.org/user/gdb/) [ hponde\_oai](https://pypi.org/user/hponde_oai/) [ jhallard](https://pypi.org/user/jhallard/) [ tomerkOpenAI](https://pypi.org/user/tomerkOpenAI/)
### Unverified details
*These details have **not** been verified by PyPI*
###### Project links
- [Homepage](https://github.com/openai/openai-python)
- [Repository](https://github.com/openai/openai-python)
###### Meta
- **License:** Apache Software License (Apache-2.0)
- **Author:** [OpenAI](mailto:support@openai.com)
- **Requires:** Python \>=3.9
- **Provides-Extra:** `aiohttp` , `datalib` , `realtime` , `voice-helpers`
###### Classifiers
- **Intended Audience**
- [Developers](https://pypi.org/search/?c=Intended+Audience+%3A%3A+Developers)
- **License**
- [OSI Approved :: Apache Software License](https://pypi.org/search/?c=License+%3A%3A+OSI+Approved+%3A%3A+Apache+Software+License)
- **Operating System**
- [MacOS](https://pypi.org/search/?c=Operating+System+%3A%3A+MacOS)
- [Microsoft :: Windows](https://pypi.org/search/?c=Operating+System+%3A%3A+Microsoft+%3A%3A+Windows)
- [OS Independent](https://pypi.org/search/?c=Operating+System+%3A%3A+OS+Independent)
- [POSIX](https://pypi.org/search/?c=Operating+System+%3A%3A+POSIX)
- [POSIX :: Linux](https://pypi.org/search/?c=Operating+System+%3A%3A+POSIX+%3A%3A+Linux)
- **Programming Language**
- [Python :: 3.9](https://pypi.org/search/?c=Programming+Language+%3A%3A+Python+%3A%3A+3.9)
- [Python :: 3.10](https://pypi.org/search/?c=Programming+Language+%3A%3A+Python+%3A%3A+3.10)
- [Python :: 3.11](https://pypi.org/search/?c=Programming+Language+%3A%3A+Python+%3A%3A+3.11)
- [Python :: 3.12](https://pypi.org/search/?c=Programming+Language+%3A%3A+Python+%3A%3A+3.12)
- [Python :: 3.13](https://pypi.org/search/?c=Programming+Language+%3A%3A+Python+%3A%3A+3.13)
- [Python :: 3.14](https://pypi.org/search/?c=Programming+Language+%3A%3A+Python+%3A%3A+3.14)
- **Topic**
- [Software Development :: Libraries :: Python Modules](https://pypi.org/search/?c=Topic+%3A%3A+Software+Development+%3A%3A+Libraries+%3A%3A+Python+Modules)
- **Typing**
- [Typed](https://pypi.org/search/?c=Typing+%3A%3A+Typed)
## Release history [Release notifications](https://pypi.org/help/#project-release-notifications) \| [RSS feed](https://pypi.org/rss/project/openai/releases.xml)
This version

[2\.31.0 Apr 8, 2026](https://pypi.org/project/openai/2.31.0/)

[2\.30.0 Mar 25, 2026](https://pypi.org/project/openai/2.30.0/)

[2\.29.0 Mar 17, 2026](https://pypi.org/project/openai/2.29.0/)

[2\.28.0 Mar 13, 2026](https://pypi.org/project/openai/2.28.0/)

[2\.27.0 Mar 13, 2026](https://pypi.org/project/openai/2.27.0/)

[2\.26.0 Mar 5, 2026](https://pypi.org/project/openai/2.26.0/)

[2\.25.0 Mar 5, 2026](https://pypi.org/project/openai/2.25.0/)

[2\.24.0 Feb 24, 2026](https://pypi.org/project/openai/2.24.0/)

[2\.23.0 Feb 24, 2026](https://pypi.org/project/openai/2.23.0/)

[2\.22.0 Feb 23, 2026](https://pypi.org/project/openai/2.22.0/)

[2\.21.0 Feb 14, 2026](https://pypi.org/project/openai/2.21.0/)

[2\.20.0 Feb 10, 2026](https://pypi.org/project/openai/2.20.0/)

[2\.19.0 Feb 10, 2026](https://pypi.org/project/openai/2.19.0/)

[2\.18.0 Feb 9, 2026](https://pypi.org/project/openai/2.18.0/)

[2\.17.0 Feb 5, 2026](https://pypi.org/project/openai/2.17.0/)

[2\.16.0 Jan 27, 2026](https://pypi.org/project/openai/2.16.0/)

[2\.15.0 Jan 9, 2026](https://pypi.org/project/openai/2.15.0/)

[2\.14.0 Dec 19, 2025](https://pypi.org/project/openai/2.14.0/)

[2\.13.0 Dec 16, 2025](https://pypi.org/project/openai/2.13.0/)

[2\.12.0 Dec 15, 2025](https://pypi.org/project/openai/2.12.0/)

[2\.11.0 Dec 11, 2025](https://pypi.org/project/openai/2.11.0/)

[2\.9.0 Dec 4, 2025](https://pypi.org/project/openai/2.9.0/)

[2\.8.1 Nov 17, 2025](https://pypi.org/project/openai/2.8.1/)

[2\.8.0 Nov 13, 2025](https://pypi.org/project/openai/2.8.0/)

[2\.7.2 Nov 10, 2025](https://pypi.org/project/openai/2.7.2/)

[2\.7.1 Nov 4, 2025](https://pypi.org/project/openai/2.7.1/)

[2\.7.0 Nov 3, 2025](https://pypi.org/project/openai/2.7.0/)

[2\.6.1 Oct 24, 2025](https://pypi.org/project/openai/2.6.1/)

[2\.6.0 Oct 20, 2025](https://pypi.org/project/openai/2.6.0/)

[2\.5.0 Oct 17, 2025](https://pypi.org/project/openai/2.5.0/)

[2\.4.0 Oct 16, 2025](https://pypi.org/project/openai/2.4.0/)

[2\.3.0 Oct 10, 2025](https://pypi.org/project/openai/2.3.0/)

[2\.2.0 Oct 6, 2025](https://pypi.org/project/openai/2.2.0/)

[2\.1.0 Oct 2, 2025](https://pypi.org/project/openai/2.1.0/)

[2\.0.1 Oct 1, 2025](https://pypi.org/project/openai/2.0.1/)

[2\.0.0 Sep 30, 2025](https://pypi.org/project/openai/2.0.0/)

[1\.109.1 Sep 24, 2025](https://pypi.org/project/openai/1.109.1/)

[1\.109.0 Sep 23, 2025](https://pypi.org/project/openai/1.109.0/)

[1\.108.2 Sep 22, 2025](https://pypi.org/project/openai/1.108.2/)

[1\.108.1 Sep 19, 2025](https://pypi.org/project/openai/1.108.1/)

[1\.108.0 Sep 17, 2025](https://pypi.org/project/openai/1.108.0/)

[1\.107.3 Sep 15, 2025](https://pypi.org/project/openai/1.107.3/)

[1\.107.2 Sep 12, 2025](https://pypi.org/project/openai/1.107.2/)

[1\.107.1 Sep 10, 2025](https://pypi.org/project/openai/1.107.1/)

[1\.107.0 Sep 8, 2025](https://pypi.org/project/openai/1.107.0/)

[1\.106.1 Sep 4, 2025](https://pypi.org/project/openai/1.106.1/)

[1\.106.0 Sep 4, 2025](https://pypi.org/project/openai/1.106.0/)

[1\.105.0 Sep 3, 2025](https://pypi.org/project/openai/1.105.0/)

[1\.104.2 Sep 2, 2025](https://pypi.org/project/openai/1.104.2/)

[1\.104.1 Sep 2, 2025](https://pypi.org/project/openai/1.104.1/)

[1\.104.0 Sep 2, 2025](https://pypi.org/project/openai/1.104.0/)

[1\.103.0 Sep 2, 2025](https://pypi.org/project/openai/1.103.0/)

[1\.102.0 Aug 26, 2025](https://pypi.org/project/openai/1.102.0/)

[1\.101.0 Aug 21, 2025](https://pypi.org/project/openai/1.101.0/)

[1\.100.2 Aug 19, 2025](https://pypi.org/project/openai/1.100.2/)

[1\.100.1 Aug 18, 2025](https://pypi.org/project/openai/1.100.1/)

[1\.100.0 Aug 18, 2025](https://pypi.org/project/openai/1.100.0/)

[1\.99.9 Aug 12, 2025](https://pypi.org/project/openai/1.99.9/)

[1\.99.8 Aug 11, 2025](https://pypi.org/project/openai/1.99.8/)

[1\.99.7 Aug 11, 2025](https://pypi.org/project/openai/1.99.7/)

[1\.99.6 Aug 9, 2025](https://pypi.org/project/openai/1.99.6/)

[1\.99.5 Aug 8, 2025](https://pypi.org/project/openai/1.99.5/)

[1\.99.4 Aug 8, 2025](https://pypi.org/project/openai/1.99.4/)

[1\.99.3 Aug 7, 2025](https://pypi.org/project/openai/1.99.3/)

[1\.99.2 Aug 7, 2025](https://pypi.org/project/openai/1.99.2/)

[1\.99.1 Aug 5, 2025](https://pypi.org/project/openai/1.99.1/)

[1\.99.0 Aug 5, 2025](https://pypi.org/project/openai/1.99.0/)

[1\.98.0 Jul 30, 2025](https://pypi.org/project/openai/1.98.0/)

[1\.97.2 Jul 30, 2025](https://pypi.org/project/openai/1.97.2/)

[1\.97.1 Jul 22, 2025](https://pypi.org/project/openai/1.97.1/)

[1\.97.0 Jul 16, 2025](https://pypi.org/project/openai/1.97.0/)

[1\.96.1 Jul 15, 2025](https://pypi.org/project/openai/1.96.1/)

[1\.96.0 Jul 15, 2025](https://pypi.org/project/openai/1.96.0/)

[1\.95.1 Jul 11, 2025](https://pypi.org/project/openai/1.95.1/)

[1\.95.0 Jul 10, 2025](https://pypi.org/project/openai/1.95.0/)

[1\.94.0 Jul 10, 2025](https://pypi.org/project/openai/1.94.0/)

[1\.93.3 Jul 9, 2025](https://pypi.org/project/openai/1.93.3/)

[1\.93.2 Jul 8, 2025](https://pypi.org/project/openai/1.93.2/)

[1\.93.1 Jul 7, 2025](https://pypi.org/project/openai/1.93.1/)

[1\.93.0 Jun 27, 2025](https://pypi.org/project/openai/1.93.0/)

[1\.92.3 Jun 27, 2025](https://pypi.org/project/openai/1.92.3/)

[1\.92.2 Jun 26, 2025](https://pypi.org/project/openai/1.92.2/)

[1\.92.1 Jun 26, 2025](https://pypi.org/project/openai/1.92.1/)

[1\.92.0 Jun 26, 2025](https://pypi.org/project/openai/1.92.0/)

[1\.91.0 Jun 23, 2025](https://pypi.org/project/openai/1.91.0/)

[1\.90.0 Jun 20, 2025](https://pypi.org/project/openai/1.90.0/)

[1\.89.0 Jun 20, 2025](https://pypi.org/project/openai/1.89.0/)

[1\.88.0 Jun 17, 2025](https://pypi.org/project/openai/1.88.0/)

[1\.87.0 Jun 16, 2025](https://pypi.org/project/openai/1.87.0/)

[1\.86.0 Jun 10, 2025](https://pypi.org/project/openai/1.86.0/)

[1\.85.0 Jun 9, 2025](https://pypi.org/project/openai/1.85.0/)

[1\.84.0 Jun 3, 2025](https://pypi.org/project/openai/1.84.0/)

[1\.83.0 Jun 2, 2025](https://pypi.org/project/openai/1.83.0/)

[1\.82.1 May 29, 2025](https://pypi.org/project/openai/1.82.1/)

[1\.82.0 May 22, 2025](https://pypi.org/project/openai/1.82.0/)

[1\.81.0 May 21, 2025](https://pypi.org/project/openai/1.81.0/)

[1\.80.0 May 21, 2025](https://pypi.org/project/openai/1.80.0/)

[1\.79.0 May 16, 2025](https://pypi.org/project/openai/1.79.0/)

[1\.78.1 May 12, 2025](https://pypi.org/project/openai/1.78.1/)

[1\.78.0 May 8, 2025](https://pypi.org/project/openai/1.78.0/)

[1\.77.0 May 2, 2025](https://pypi.org/project/openai/1.77.0/)

[1\.76.2 Apr 29, 2025](https://pypi.org/project/openai/1.76.2/)

[1\.76.1 Apr 29, 2025](https://pypi.org/project/openai/1.76.1/)

[1\.76.0 Apr 23, 2025](https://pypi.org/project/openai/1.76.0/)

[1\.75.0 Apr 16, 2025](https://pypi.org/project/openai/1.75.0/)

[1\.74.1 Apr 16, 2025](https://pypi.org/project/openai/1.74.1/)

[1\.74.0 Apr 14, 2025](https://pypi.org/project/openai/1.74.0/)

[1\.73.0 Apr 12, 2025](https://pypi.org/project/openai/1.73.0/)

[1\.72.0 Apr 8, 2025](https://pypi.org/project/openai/1.72.0/)

[1\.71.0 Apr 7, 2025](https://pypi.org/project/openai/1.71.0/)

[1\.70.0 Mar 31, 2025](https://pypi.org/project/openai/1.70.0/)

[1\.69.0 Mar 27, 2025](https://pypi.org/project/openai/1.69.0/)

[1\.68.2 Mar 21, 2025](https://pypi.org/project/openai/1.68.2/)

[1\.68.1 Mar 21, 2025](https://pypi.org/project/openai/1.68.1/)

[1\.68.0 Mar 20, 2025](https://pypi.org/project/openai/1.68.0/)

[1\.67.0 Mar 19, 2025](https://pypi.org/project/openai/1.67.0/)

[1\.66.5 Mar 18, 2025](https://pypi.org/project/openai/1.66.5/)

[1\.66.3 Mar 12, 2025](https://pypi.org/project/openai/1.66.3/)

[1\.66.2 Mar 11, 2025](https://pypi.org/project/openai/1.66.2/)

[1\.66.1 Mar 11, 2025](https://pypi.org/project/openai/1.66.1/)

[1\.66.0 Mar 11, 2025](https://pypi.org/project/openai/1.66.0/)

[1\.65.5 Mar 9, 2025](https://pypi.org/project/openai/1.65.5/)

[1\.65.4 Mar 5, 2025](https://pypi.org/project/openai/1.65.4/)

[1\.65.3 Mar 4, 2025](https://pypi.org/project/openai/1.65.3/)

[1\.65.2 Mar 1, 2025](https://pypi.org/project/openai/1.65.2/)

[1\.65.1 Feb 27, 2025](https://pypi.org/project/openai/1.65.1/)

[1\.65.0 Feb 27, 2025](https://pypi.org/project/openai/1.65.0/)

[1\.64.0 Feb 22, 2025](https://pypi.org/project/openai/1.64.0/)

[1\.63.2 Feb 17, 2025](https://pypi.org/project/openai/1.63.2/)

[1\.63.1 Feb 17, 2025](https://pypi.org/project/openai/1.63.1/)

[1\.63.0 Feb 13, 2025](https://pypi.org/project/openai/1.63.0/)

[1\.62.0 Feb 12, 2025](https://pypi.org/project/openai/1.62.0/)

[1\.61.1 Feb 5, 2025](https://pypi.org/project/openai/1.61.1/)

[1\.61.0 Jan 31, 2025](https://pypi.org/project/openai/1.61.0/)

[1\.60.2 Jan 27, 2025](https://pypi.org/project/openai/1.60.2/)

[1\.60.1 Jan 24, 2025](https://pypi.org/project/openai/1.60.1/)

[1\.60.0 Jan 22, 2025](https://pypi.org/project/openai/1.60.0/)

[1\.59.9 Jan 20, 2025](https://pypi.org/project/openai/1.59.9/)

[1\.59.8 Jan 17, 2025](https://pypi.org/project/openai/1.59.8/)

[1\.59.7 Jan 13, 2025](https://pypi.org/project/openai/1.59.7/)

[1\.59.6 Jan 9, 2025](https://pypi.org/project/openai/1.59.6/)

[1\.59.5 Jan 8, 2025](https://pypi.org/project/openai/1.59.5/)

[1\.59.4 Jan 7, 2025](https://pypi.org/project/openai/1.59.4/)

[1\.59.3 Jan 3, 2025](https://pypi.org/project/openai/1.59.3/)

[1\.59.2 Jan 3, 2025](https://pypi.org/project/openai/1.59.2/)

[1\.58.1 Dec 17, 2024](https://pypi.org/project/openai/1.58.1/)

[1\.58.0 Dec 17, 2024](https://pypi.org/project/openai/1.58.0/)

[1\.57.4 Dec 13, 2024](https://pypi.org/project/openai/1.57.4/)

[1\.57.3 Dec 12, 2024](https://pypi.org/project/openai/1.57.3/)

[1\.57.2 Dec 10, 2024](https://pypi.org/project/openai/1.57.2/)

[1\.57.1 Dec 9, 2024](https://pypi.org/project/openai/1.57.1/)

[1\.57.0 Dec 5, 2024](https://pypi.org/project/openai/1.57.0/)

[1\.56.2 Dec 4, 2024](https://pypi.org/project/openai/1.56.2/)

[1\.56.1 Dec 3, 2024](https://pypi.org/project/openai/1.56.1/)

[1\.56.0 Dec 2, 2024](https://pypi.org/project/openai/1.56.0/)

[1\.55.3 Nov 28, 2024](https://pypi.org/project/openai/1.55.3/)

[1\.55.2 Nov 27, 2024](https://pypi.org/project/openai/1.55.2/)

[1\.55.1 Nov 25, 2024](https://pypi.org/project/openai/1.55.1/)

[1\.55.0 Nov 20, 2024](https://pypi.org/project/openai/1.55.0/)

[1\.54.5 Nov 19, 2024](https://pypi.org/project/openai/1.54.5/)

[1\.54.4 Nov 12, 2024](https://pypi.org/project/openai/1.54.4/)

[1\.54.3 Nov 6, 2024](https://pypi.org/project/openai/1.54.3/)

[1\.54.2 Nov 6, 2024](https://pypi.org/project/openai/1.54.2/)

[1\.54.1 Nov 5, 2024](https://pypi.org/project/openai/1.54.1/)

[1\.54.0 Nov 4, 2024](https://pypi.org/project/openai/1.54.0/)

[1\.53.1 Nov 4, 2024](https://pypi.org/project/openai/1.53.1/)

[1\.53.0 Oct 30, 2024](https://pypi.org/project/openai/1.53.0/)

[1\.52.2 Oct 23, 2024](https://pypi.org/project/openai/1.52.2/)

[1\.52.1 Oct 22, 2024](https://pypi.org/project/openai/1.52.1/)

[1\.52.0 Oct 17, 2024](https://pypi.org/project/openai/1.52.0/)

[1\.51.2 Oct 8, 2024](https://pypi.org/project/openai/1.51.2/)

[1\.51.1 Oct 7, 2024](https://pypi.org/project/openai/1.51.1/)

[1\.51.0 Oct 1, 2024](https://pypi.org/project/openai/1.51.0/)

[1\.50.2 Sep 27, 2024](https://pypi.org/project/openai/1.50.2/)

[1\.50.1 Sep 27, 2024](https://pypi.org/project/openai/1.50.1/)

[1\.50.0 Sep 26, 2024](https://pypi.org/project/openai/1.50.0/)

[1\.49.0 Sep 26, 2024](https://pypi.org/project/openai/1.49.0/)

[1\.48.0 Sep 25, 2024](https://pypi.org/project/openai/1.48.0/)

[1\.47.1 Sep 23, 2024](https://pypi.org/project/openai/1.47.1/)

[1\.47.0 Sep 20, 2024](https://pypi.org/project/openai/1.47.0/)

[1\.46.1 Sep 19, 2024](https://pypi.org/project/openai/1.46.1/)

[1\.46.0 Sep 17, 2024](https://pypi.org/project/openai/1.46.0/)

[1\.45.1 Sep 16, 2024](https://pypi.org/project/openai/1.45.1/)

[1\.45.0 Sep 12, 2024](https://pypi.org/project/openai/1.45.0/)

[1\.44.1 Sep 9, 2024](https://pypi.org/project/openai/1.44.1/)

[1\.44.0 Sep 6, 2024](https://pypi.org/project/openai/1.44.0/)

[1\.43.1 Sep 5, 2024](https://pypi.org/project/openai/1.43.1/)

[1\.43.0 Aug 29, 2024](https://pypi.org/project/openai/1.43.0/)

[1\.42.0 Aug 20, 2024](https://pypi.org/project/openai/1.42.0/)

[1\.41.1 Aug 20, 2024](https://pypi.org/project/openai/1.41.1/)

[1\.41.0 Aug 16, 2024](https://pypi.org/project/openai/1.41.0/)

[1\.40.8 Aug 15, 2024](https://pypi.org/project/openai/1.40.8/)

[1\.40.7 Aug 15, 2024](https://pypi.org/project/openai/1.40.7/)

[1\.40.6 Aug 12, 2024](https://pypi.org/project/openai/1.40.6/)

[1\.40.5 Aug 12, 2024](https://pypi.org/project/openai/1.40.5/)

[1\.40.4 Aug 12, 2024](https://pypi.org/project/openai/1.40.4/)

[1\.40.3 Aug 10, 2024](https://pypi.org/project/openai/1.40.3/)

[1\.40.2 Aug 8, 2024](https://pypi.org/project/openai/1.40.2/)

[1\.40.1 Aug 7, 2024](https://pypi.org/project/openai/1.40.1/)

[1\.40.0 Aug 6, 2024](https://pypi.org/project/openai/1.40.0/)

[1\.39.0 Aug 5, 2024](https://pypi.org/project/openai/1.39.0/)

[1\.38.0 Aug 2, 2024](https://pypi.org/project/openai/1.38.0/)

[1\.37.2 Aug 2, 2024](https://pypi.org/project/openai/1.37.2/)

[1\.37.1 Jul 25, 2024](https://pypi.org/project/openai/1.37.1/)

[1\.37.0 Jul 22, 2024](https://pypi.org/project/openai/1.37.0/)

[1\.36.1 Jul 20, 2024](https://pypi.org/project/openai/1.36.1/)

[1\.36.0 Jul 19, 2024](https://pypi.org/project/openai/1.36.0/)

[1\.35.15 Jul 18, 2024](https://pypi.org/project/openai/1.35.15/)

[1\.35.14 Jul 16, 2024](https://pypi.org/project/openai/1.35.14/)

[1\.35.13 Jul 10, 2024](https://pypi.org/project/openai/1.35.13/)

[1\.35.12 Jul 9, 2024](https://pypi.org/project/openai/1.35.12/)

[1\.35.11 Jul 9, 2024](https://pypi.org/project/openai/1.35.11/)

[1\.35.10 Jul 4, 2024](https://pypi.org/project/openai/1.35.10/)

[1\.35.9 Jul 2, 2024](https://pypi.org/project/openai/1.35.9/)

[1\.35.8 Jul 2, 2024](https://pypi.org/project/openai/1.35.8/)

[1\.35.7 Jun 27, 2024](https://pypi.org/project/openai/1.35.7/)

[1\.35.6 Jun 27, 2024](https://pypi.org/project/openai/1.35.6/)

[1\.35.5 Jun 26, 2024](https://pypi.org/project/openai/1.35.5/)

[1\.35.4 Jun 26, 2024](https://pypi.org/project/openai/1.35.4/)

[1\.35.3 Jun 20, 2024](https://pypi.org/project/openai/1.35.3/)

[1\.35.2 Jun 20, 2024](https://pypi.org/project/openai/1.35.2/)

[1\.35.1 Jun 19, 2024](https://pypi.org/project/openai/1.35.1/)

[1\.35.0 Jun 19, 2024](https://pypi.org/project/openai/1.35.0/)

[1\.34.0 Jun 12, 2024](https://pypi.org/project/openai/1.34.0/)

[1\.33.0 Jun 7, 2024](https://pypi.org/project/openai/1.33.0/)

[1\.32.1 Jun 7, 2024](https://pypi.org/project/openai/1.32.1/)

[1\.32.0 Jun 6, 2024](https://pypi.org/project/openai/1.32.0/)

[1\.31.2 Jun 6, 2024](https://pypi.org/project/openai/1.31.2/)

[1\.31.1 Jun 5, 2024](https://pypi.org/project/openai/1.31.1/)

[1\.31.0 Jun 3, 2024](https://pypi.org/project/openai/1.31.0/)

[1\.30.5 May 30, 2024](https://pypi.org/project/openai/1.30.5/)

[1\.30.4 May 28, 2024](https://pypi.org/project/openai/1.30.4/)

[1\.30.3 May 24, 2024](https://pypi.org/project/openai/1.30.3/)

[1\.30.2 May 23, 2024](https://pypi.org/project/openai/1.30.2/)

[1\.30.1 May 14, 2024](https://pypi.org/project/openai/1.30.1/)

[1\.30.0 May 14, 2024](https://pypi.org/project/openai/1.30.0/)

[1\.29.0 May 13, 2024](https://pypi.org/project/openai/1.29.0/)

[1\.28.2 May 13, 2024](https://pypi.org/project/openai/1.28.2/)

[1\.28.1 May 11, 2024](https://pypi.org/project/openai/1.28.1/)

[1\.28.0 May 9, 2024](https://pypi.org/project/openai/1.28.0/)

[1\.27.0 May 8, 2024](https://pypi.org/project/openai/1.27.0/)

[1\.26.0 May 6, 2024](https://pypi.org/project/openai/1.26.0/)

[1\.25.2 May 5, 2024](https://pypi.org/project/openai/1.25.2/)

[1\.25.1 May 2, 2024](https://pypi.org/project/openai/1.25.1/)

[1\.25.0 May 1, 2024](https://pypi.org/project/openai/1.25.0/)

[1\.24.1 Apr 30, 2024](https://pypi.org/project/openai/1.24.1/)

[1\.24.0 Apr 29, 2024](https://pypi.org/project/openai/1.24.0/)

[1\.23.6 Apr 25, 2024](https://pypi.org/project/openai/1.23.6/)

[1\.23.5 Apr 25, 2024](https://pypi.org/project/openai/1.23.5/)

[1\.23.4 Apr 24, 2024](https://pypi.org/project/openai/1.23.4/)

[1\.23.3 Apr 23, 2024](https://pypi.org/project/openai/1.23.3/)

[1\.23.2 Apr 19, 2024](https://pypi.org/project/openai/1.23.2/)

[1\.23.1 Apr 18, 2024](https://pypi.org/project/openai/1.23.1/)

[1\.23.0 Apr 18, 2024](https://pypi.org/project/openai/1.23.0/)

[1\.22.0 Apr 18, 2024](https://pypi.org/project/openai/1.22.0/)

[1\.21.2 Apr 17, 2024](https://pypi.org/project/openai/1.21.2/)

[1\.21.1 Apr 17, 2024](https://pypi.org/project/openai/1.21.1/)

[1\.21.0 Apr 17, 2024](https://pypi.org/project/openai/1.21.0/)

[1\.20.0 Apr 16, 2024](https://pypi.org/project/openai/1.20.0/)

[1\.19.0 Apr 16, 2024](https://pypi.org/project/openai/1.19.0/)

[1\.18.0 Apr 15, 2024](https://pypi.org/project/openai/1.18.0/)

[1\.17.1 Apr 13, 2024](https://pypi.org/project/openai/1.17.1/)

[1\.17.0 Apr 10, 2024](https://pypi.org/project/openai/1.17.0/)

[1\.16.2 Apr 4, 2024](https://pypi.org/project/openai/1.16.2/)

[1\.16.1 Apr 2, 2024](https://pypi.org/project/openai/1.16.1/)

[1\.16.0 Apr 1, 2024](https://pypi.org/project/openai/1.16.0/)

[1\.14.3 Mar 25, 2024](https://pypi.org/project/openai/1.14.3/)

[1\.14.2 Mar 19, 2024](https://pypi.org/project/openai/1.14.2/)

[1\.14.1 Mar 15, 2024](https://pypi.org/project/openai/1.14.1/)

[1\.14.0 Mar 13, 2024](https://pypi.org/project/openai/1.14.0/)

[1\.13.4 Mar 13, 2024](https://pypi.org/project/openai/1.13.4/)

[1\.13.3 Feb 28, 2024](https://pypi.org/project/openai/1.13.3/)

[1\.12.0 Feb 9, 2024](https://pypi.org/project/openai/1.12.0/)

[1\.11.1 Feb 4, 2024](https://pypi.org/project/openai/1.11.1/)

[1\.11.0 Feb 3, 2024](https://pypi.org/project/openai/1.11.0/)

[1\.10.0 Jan 25, 2024](https://pypi.org/project/openai/1.10.0/)

[1\.9.0 Jan 21, 2024](https://pypi.org/project/openai/1.9.0/)

[1\.8.0 Jan 16, 2024](https://pypi.org/project/openai/1.8.0/)

[1\.7.2 Jan 12, 2024](https://pypi.org/project/openai/1.7.2/)

[1\.7.1 Jan 10, 2024](https://pypi.org/project/openai/1.7.1/)

[1\.7.0 Jan 9, 2024](https://pypi.org/project/openai/1.7.0/)

[1\.6.1 Dec 22, 2023](https://pypi.org/project/openai/1.6.1/)

[1\.6.0 Dec 19, 2023](https://pypi.org/project/openai/1.6.0/)

[1\.5.0 Dec 17, 2023](https://pypi.org/project/openai/1.5.0/)

[1\.4.0 Dec 15, 2023](https://pypi.org/project/openai/1.4.0/)

[1\.3.9 Dec 13, 2023](https://pypi.org/project/openai/1.3.9/)

[1\.3.8 Dec 9, 2023](https://pypi.org/project/openai/1.3.8/)

[1\.3.7 Dec 1, 2023](https://pypi.org/project/openai/1.3.7/)

[1\.3.6 Nov 29, 2023](https://pypi.org/project/openai/1.3.6/)

[1\.3.5 Nov 22, 2023](https://pypi.org/project/openai/1.3.5/)

[1\.3.4 Nov 21, 2023](https://pypi.org/project/openai/1.3.4/)

[1\.3.3 Nov 17, 2023](https://pypi.org/project/openai/1.3.3/)

[1\.3.2 Nov 16, 2023](https://pypi.org/project/openai/1.3.2/)

[1\.3.1 Nov 16, 2023](https://pypi.org/project/openai/1.3.1/)

[1\.3.0 Nov 15, 2023](https://pypi.org/project/openai/1.3.0/)

[1\.2.4 Nov 13, 2023](https://pypi.org/project/openai/1.2.4/)

[1\.2.3 Nov 10, 2023](https://pypi.org/project/openai/1.2.3/)

[1\.2.2 Nov 9, 2023](https://pypi.org/project/openai/1.2.2/)

[1\.2.1 Nov 9, 2023](https://pypi.org/project/openai/1.2.1/)

[1\.2.0 Nov 9, 2023](https://pypi.org/project/openai/1.2.0/)

[1\.1.2 Nov 8, 2023](https://pypi.org/project/openai/1.1.2/)

[1\.1.1 Nov 6, 2023](https://pypi.org/project/openai/1.1.1/)

[1\.1.0 Nov 6, 2023](https://pypi.org/project/openai/1.1.0/)

[1\.0.1 Nov 6, 2023](https://pypi.org/project/openai/1.0.1/)

[1\.0.0 Nov 6, 2023](https://pypi.org/project/openai/1.0.0/)

[1\.0.0rc3 pre-release Nov 6, 2023](https://pypi.org/project/openai/1.0.0rc3/)

[1\.0.0rc2 pre-release Nov 3, 2023](https://pypi.org/project/openai/1.0.0rc2/)

[1\.0.0rc1 pre-release Oct 28, 2023](https://pypi.org/project/openai/1.0.0rc1/)

[1\.0.0b3 pre-release Oct 17, 2023](https://pypi.org/project/openai/1.0.0b3/)

[1\.0.0b2 pre-release Oct 12, 2023](https://pypi.org/project/openai/1.0.0b2/)

[1\.0.0b1 pre-release Sep 29, 2023](https://pypi.org/project/openai/1.0.0b1/)

[0\.28.1 Sep 26, 2023](https://pypi.org/project/openai/0.28.1/)

[0\.28.0 Aug 31, 2023](https://pypi.org/project/openai/0.28.0/)

[0\.27.10 Aug 30, 2023](https://pypi.org/project/openai/0.27.10/)

[0\.27.9 Aug 22, 2023](https://pypi.org/project/openai/0.27.9/)

[0\.27.8 Jun 7, 2023](https://pypi.org/project/openai/0.27.8/)

[0\.27.7 May 19, 2023](https://pypi.org/project/openai/0.27.7/)

[0\.27.6 May 1, 2023](https://pypi.org/project/openai/0.27.6/)

[0\.27.5 Apr 27, 2023](https://pypi.org/project/openai/0.27.5/)

[0\.27.4 Apr 4, 2023](https://pypi.org/project/openai/0.27.4/)

[0\.27.3 Apr 3, 2023](https://pypi.org/project/openai/0.27.3/)

[0\.27.2 Mar 11, 2023](https://pypi.org/project/openai/0.27.2/)

[0\.27.1 Mar 8, 2023](https://pypi.org/project/openai/0.27.1/)

[0\.27.0 Mar 1, 2023](https://pypi.org/project/openai/0.27.0/)

[0\.26.5 Feb 7, 2023](https://pypi.org/project/openai/0.26.5/)

[0\.26.4 Jan 26, 2023](https://pypi.org/project/openai/0.26.4/)

[0\.26.3 Jan 25, 2023](https://pypi.org/project/openai/0.26.3/)

[0\.26.2 Jan 24, 2023](https://pypi.org/project/openai/0.26.2/)

[0\.26.1 Jan 13, 2023](https://pypi.org/project/openai/0.26.1/)

[0\.26.0 Jan 6, 2023](https://pypi.org/project/openai/0.26.0/)

[0\.25.0 Nov 2, 2022](https://pypi.org/project/openai/0.25.0/)

[0\.24.0 Oct 21, 2022](https://pypi.org/project/openai/0.24.0/)

[0\.23.1 Sep 28, 2022](https://pypi.org/project/openai/0.23.1/)

[0\.23.0 Aug 24, 2022](https://pypi.org/project/openai/0.23.0/)

[0\.22.1 Aug 2, 2022](https://pypi.org/project/openai/0.22.1/)

[0\.22.0 Jul 26, 2022](https://pypi.org/project/openai/0.22.0/)

[0\.20.0 Jun 16, 2022](https://pypi.org/project/openai/0.20.0/)

[0\.19.0 May 24, 2022](https://pypi.org/project/openai/0.19.0/)

[0\.18.1 Apr 15, 2022](https://pypi.org/project/openai/0.18.1/)

[0\.18.0 Apr 8, 2022](https://pypi.org/project/openai/0.18.0/)

[0\.16.0 Mar 17, 2022](https://pypi.org/project/openai/0.16.0/)

[0\.15.0 Feb 24, 2022](https://pypi.org/project/openai/0.15.0/)

[0\.14.0 Feb 2, 2022](https://pypi.org/project/openai/0.14.0/)

[0\.13.0 Jan 25, 2022](https://pypi.org/project/openai/0.13.0/)

[0\.12.0 Jan 22, 2022](https://pypi.org/project/openai/0.12.0/)

[0\.11.6 Jan 21, 2022](https://pypi.org/project/openai/0.11.6/)

[0\.11.5 Dec 21, 2021](https://pypi.org/project/openai/0.11.5/)

[0\.11.4 Dec 14, 2021](https://pypi.org/project/openai/0.11.4/)

[0\.11.3 Dec 4, 2021](https://pypi.org/project/openai/0.11.3/)

[0\.11.2 Dec 4, 2021](https://pypi.org/project/openai/0.11.2/)

[0\.11.1 Dec 2, 2021](https://pypi.org/project/openai/0.11.1/)

[0\.11.0 Oct 27, 2021](https://pypi.org/project/openai/0.11.0/)

[0\.10.5 Oct 1, 2021](https://pypi.org/project/openai/0.10.5/)

[0\.10.4 Sep 9, 2021](https://pypi.org/project/openai/0.10.4/)

[0\.10.3 Aug 31, 2021](https://pypi.org/project/openai/0.10.3/)

[0\.10.2 Jul 29, 2021](https://pypi.org/project/openai/0.10.2/)

[0\.10.1 Jul 14, 2021](https://pypi.org/project/openai/0.10.1/)

[0\.10.0 Jul 14, 2021](https://pypi.org/project/openai/0.10.0/)

[0\.9.4 Jul 12, 2021](https://pypi.org/project/openai/0.9.4/)

[0\.9.3 Jun 30, 2021](https://pypi.org/project/openai/0.9.3/)

[0\.9.2 Jun 30, 2021](https://pypi.org/project/openai/0.9.2/)

[0\.9.1 Jun 30, 2021](https://pypi.org/project/openai/0.9.1/)

[0\.9.0 Jun 29, 2021](https://pypi.org/project/openai/0.9.0/)

[0\.8.0 Jun 17, 2021](https://pypi.org/project/openai/0.8.0/)

[0\.7.0 Jun 11, 2021](https://pypi.org/project/openai/0.7.0/)

[0\.6.4 May 21, 2021](https://pypi.org/project/openai/0.6.4/)

[0\.6.3 Apr 12, 2021](https://pypi.org/project/openai/0.6.3/)

[0\.6.2 Mar 20, 2021](https://pypi.org/project/openai/0.6.2/)

[0\.6.1 Mar 19, 2021](https://pypi.org/project/openai/0.6.1/)

[0\.6.0 Mar 18, 2021](https://pypi.org/project/openai/0.6.0/)

[0\.4.0 Mar 4, 2021](https://pypi.org/project/openai/0.4.0/)

[0\.3.0 Jan 27, 2021](https://pypi.org/project/openai/0.3.0/)

[0\.2.6 Oct 24, 2020](https://pypi.org/project/openai/0.2.6/)

[0\.2.5 Oct 5, 2020](https://pypi.org/project/openai/0.2.5/)

[0\.2.4 Jul 12, 2020](https://pypi.org/project/openai/0.2.4/)

[0\.2.3 Jul 7, 2020](https://pypi.org/project/openai/0.2.3/)

[0\.2.1 Jun 13, 2020](https://pypi.org/project/openai/0.2.1/)

[0\.2.0 Jun 13, 2020](https://pypi.org/project/openai/0.2.0/)

[0\.1.3 Jun 13, 2020](https://pypi.org/project/openai/0.1.3/)

[0\.1.2 Jun 13, 2020](https://pypi.org/project/openai/0.1.2/)

[0\.1.1 Jun 13, 2020](https://pypi.org/project/openai/0.1.1/)

[0\.1.0 Jun 13, 2020](https://pypi.org/project/openai/0.1.0/)

[0\.0.2 Feb 18, 2020](https://pypi.org/project/openai/0.0.2/)
## Download files
Download the file for your platform. If you're not sure which to choose, learn more about [installing packages](https://packaging.python.org/tutorials/installing-packages/ "External link").
### Source Distribution
[openai-2.31.0.tar.gz](https://files.pythonhosted.org/packages/94/fe/64b3d035780b3188f86c4f6f1bc202e7bb74757ef028802112273b9dcacf/openai-2.31.0.tar.gz) (684.8 kB [view details](https://pypi.org/project/openai/#openai-2.31.0.tar.gz))
Uploaded Apr 8, 2026 `Source`
### Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about [wheel file names](https://packaging.python.org/en/latest/specifications/binary-distribution-format/ "External link").
The dropdown lists show the available interpreters, ABIs, and platforms.
Enable javascript to be able to filter the list of wheel files.
Copy a direct link to the current filters <https://pypi.org/project/openai/#files> Copy
Showing 1 of 1 file.
File name
Interpreter
ABI
Platform
[openai-2.31.0-py3-none-any.whl](https://files.pythonhosted.org/packages/66/bc/a8f7c3aa03452fedbb9af8be83e959adba96a6b4a35e416faffcc959c568/openai-2.31.0-py3-none-any.whl) (1.2 MB [view details](https://pypi.org/project/openai/#openai-2.31.0-py3-none-any.whl))
Uploaded Apr 8, 2026 `Python 3`
## File details
Details for the file `openai-2.31.0.tar.gz`.
### File metadata
- Download URL: [openai-2.31.0.tar.gz](https://files.pythonhosted.org/packages/94/fe/64b3d035780b3188f86c4f6f1bc202e7bb74757ef028802112273b9dcacf/openai-2.31.0.tar.gz)
- Upload date:
Apr 8, 2026
- Size: 684.8 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.12.9
### File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 | `43ca59a88fc973ad1848d86b98d7fac207e265ebbd1828b5e4bdfc85f79427a5` | Copy |
| MD5 | `2687404315d7408b5753ae938fdbe688` | Copy |
| BLAKE2b-256 | `94fe64b3d035780b3188f86c4f6f1bc202e7bb74757ef028802112273b9dcacf` | Copy |
[See more details on using hashes here.](https://pip.pypa.io/en/stable/topics/secure-installs/#hash-checking-mode "External link")
## File details
Details for the file `openai-2.31.0-py3-none-any.whl`.
### File metadata
- Download URL: [openai-2.31.0-py3-none-any.whl](https://files.pythonhosted.org/packages/66/bc/a8f7c3aa03452fedbb9af8be83e959adba96a6b4a35e416faffcc959c568/openai-2.31.0-py3-none-any.whl)
- Upload date:
Apr 8, 2026
- Size: 1.2 MB
- Tags: Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/5.1.1 CPython/3.12.9
### File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 | `44e1344d87e56a493d649b17e2fac519d1368cbb0745f59f1957c4c26de50a0a` | Copy |
| MD5 | `ffe6c7936c6c0cd292214c65d192fd79` | Copy |
| BLAKE2b-256 | `66bca8f7c3aa03452fedbb9af8be83e959adba96a6b4a35e416faffcc959c568` | Copy |
[See more details on using hashes here.](https://pip.pypa.io/en/stable/topics/secure-installs/#hash-checking-mode "External link")

## Help
- [Installing packages](https://packaging.python.org/tutorials/installing-packages/ "External link")
- [Uploading packages](https://packaging.python.org/tutorials/packaging-projects/ "External link")
- [User guide](https://packaging.python.org/ "External link")
- [Project name retention](https://www.python.org/dev/peps/pep-0541/ "External link")
- [FAQs](https://pypi.org/help/)
## About PyPI
- [PyPI Blog](https://blog.pypi.org/ "External link")
- [Infrastructure dashboard](https://dtdg.co/pypi "External link")
- [Statistics](https://pypi.org/stats/)
- [Logos & trademarks](https://pypi.org/trademarks/)
- [Our sponsors](https://pypi.org/sponsors/)
## Contributing to PyPI
- [Bugs and feedback](https://pypi.org/help/#feedback)
- [Contribute on GitHub](https://github.com/pypi/warehouse "External link")
- [Translate PyPI](https://hosted.weblate.org/projects/pypa/warehouse/ "External link")
- [Sponsor PyPI](https://pypi.org/sponsors/)
- [Development credits](https://github.com/pypi/warehouse/graphs/contributors "External link")
## Using PyPI
- [Terms of Service](https://policies.python.org/pypi.org/Terms-of-Service/ "External link")
- [Report security issue](https://pypi.org/security/)
- [Code of conduct](https://policies.python.org/python.org/code-of-conduct/ "External link")
- [Privacy Notice](https://policies.python.org/pypi.org/Privacy-Notice/ "External link")
- [Acceptable Use Policy](https://policies.python.org/pypi.org/Acceptable-Use-Policy/ "External link")
***
Status: [all systems operational](https://status.python.org/ "External link")
Developed and maintained by the Python community, for the Python community.
[Donate today\!](https://donate.pypi.org/)
"PyPI", "Python Package Index", and the blocks logos are registered [trademarks](https://pypi.org/trademarks/) of the [Python Software Foundation](https://www.python.org/psf-landing).
© 2026 [Python Software Foundation](https://www.python.org/psf-landing/ "External link")
[Site map](https://pypi.org/sitemap/)
Switch to desktop version
Supported by
[ AWS Cloud computing and Security Sponsor](https://aws.amazon.com/) [ Datadog Monitoring](https://www.datadoghq.com/) [ Depot Continuous Integration](https://depot.dev/) [ Fastly CDN](https://www.fastly.com/) [ Google Download Analytics](https://careers.google.com/) [ Pingdom Monitoring](https://www.pingdom.com/) [ Sentry Error logging](https://sentry.io/for/python/?utm_source=pypi&utm_medium=paid-community&utm_campaign=python-na-evergreen&utm_content=static-ad-pypi-sponsor-learnmore) [ StatusPage Status page](https://statuspage.io/) |
| Readable Markdown | ## OpenAI Python API library
[](https://pypi.org/project/openai/)
The OpenAI Python library provides convenient access to the OpenAI REST API from any Python 3.9+ application. The library includes type definitions for all request params and response fields, and offers both synchronous and asynchronous clients powered by [httpx](https://github.com/encode/httpx).
It is generated from our [OpenAPI specification](https://github.com/openai/openai-openapi) with [Stainless](https://stainlessapi.com/).
## Documentation
The REST API documentation can be found on [platform.openai.com](https://platform.openai.com/docs/api-reference). The full API of this library can be found in [api.md](https://github.com/openai/openai-python/tree/main/api.md).
## Installation
```
# install from PyPI
pip install openai
```
## Usage
The full API of this library can be found in [api.md](https://github.com/openai/openai-python/tree/main/api.md).
The primary API for interacting with OpenAI models is the [Responses API](https://platform.openai.com/docs/api-reference/responses). You can generate text from the model with the code below.
```
import os
from openai import OpenAI
client = OpenAI(
# This is the default and can be omitted
api_key=os.environ.get("OPENAI_API_KEY"),
)
response = client.responses.create(
model="gpt-5.2",
instructions="You are a coding assistant that talks like a pirate.",
input="How do I check if a Python object is an instance of a class?",
)
print(response.output_text)
```
The previous standard (supported indefinitely) for generating text is the [Chat Completions API](https://platform.openai.com/docs/api-reference/chat). You can use that API to generate text from the model with the code below.
```
from openai import OpenAI
client = OpenAI()
completion = client.chat.completions.create(
model="gpt-5.2",
messages=[
{"role": "developer", "content": "Talk like a pirate."},
{
"role": "user",
"content": "How do I check if a Python object is an instance of a class?",
},
],
)
print(completion.choices[0].message.content)
```
While you can provide an `api_key` keyword argument, we recommend using [python-dotenv](https://pypi.org/project/python-dotenv/) to add `OPENAI_API_KEY="My API Key"` to your `.env` file so that your API key is not stored in source control. [Get an API key here](https://platform.openai.com/settings/organization/api-keys).
### Workload Identity Authentication
For secure, automated environments like cloud-managed Kubernetes, Azure, and Google Cloud Platform, you can use workload identity authentication with short-lived tokens from cloud identity providers instead of long-lived API keys.
#### Kubernetes (service account tokens)
```
from openai import OpenAI
from openai.auth import k8s_service_account_token_provider
client = OpenAI(
workload_identity={
"client_id": "your-client-id",
"identity_provider_id": "idp-123",
"service_account_id": "sa-456",
"provider": k8s_service_account_token_provider(
"/var/run/secrets/kubernetes.io/serviceaccount/token"
),
},
organization="org-xyz",
project="proj-abc",
)
response = client.chat.completions.create(
model="gpt-4",
messages=[{"role": "user", "content": "Hello!"}],
)
```
#### Azure (managed identity)
```
from openai import OpenAI
from openai.auth import azure_managed_identity_token_provider
client = OpenAI(
workload_identity={
"client_id": "your-client-id",
"identity_provider_id": "idp-123",
"service_account_id": "sa-456",
"provider": azure_managed_identity_token_provider(
resource="https://management.azure.com/",
),
},
)
```
#### Google Cloud Platform (compute engine metadata)
```
from openai import OpenAI
from openai.auth import gcp_id_token_provider
client = OpenAI(
workload_identity={
"client_id": "your-client-id",
"identity_provider_id": "idp-123",
"service_account_id": "sa-456",
"provider": gcp_id_token_provider(audience="https://api.openai.com/v1"),
},
)
```
#### Custom subject token provider
```
from openai import OpenAI
def get_custom_token() -> str:
return "your-jwt-token"
client = OpenAI(
workload_identity={
"client_id": "your-client-id",
"identity_provider_id": "idp-123",
"service_account_id": "sa-456",
"provider": {
"token_type": "jwt",
"get_token": get_custom_token,
},
}
)
```
You can also customize the token refresh buffer (default is 1200 seconds (20 minutes) before expiration):
```
from openai import OpenAI
from openai.auth import k8s_service_account_token_provider
client = OpenAI(
workload_identity={
"client_id": "your-client-id",
"identity_provider_id": "idp-123",
"service_account_id": "sa-456",
"provider": k8s_service_account_token_provider("/var/token"),
"refresh_buffer_seconds": 120.0,
}
)
```
### Vision
With an image URL:
```
prompt = "What is in this image?"
img_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d5/2023_06_08_Raccoon1.jpg/1599px-2023_06_08_Raccoon1.jpg"
response = client.responses.create(
model="gpt-5.2",
input=[
{
"role": "user",
"content": [
{"type": "input_text", "text": prompt},
{"type": "input_image", "image_url": f"{img_url}"},
],
}
],
)
```
With the image as a base64 encoded string:
```
import base64
from openai import OpenAI
client = OpenAI()
prompt = "What is in this image?"
with open("path/to/image.png", "rb") as image_file:
b64_image = base64.b64encode(image_file.read()).decode("utf-8")
response = client.responses.create(
model="gpt-5.2",
input=[
{
"role": "user",
"content": [
{"type": "input_text", "text": prompt},
{"type": "input_image", "image_url": f"data:image/png;base64,{b64_image}"},
],
}
],
)
```
## Async usage
Simply import `AsyncOpenAI` instead of `OpenAI` and use `await` with each API call:
```
import os
import asyncio
from openai import AsyncOpenAI
client = AsyncOpenAI(
# This is the default and can be omitted
api_key=os.environ.get("OPENAI_API_KEY"),
)
async def main() -> None:
response = await client.responses.create(
model="gpt-5.2", input="Explain disestablishmentarianism to a smart five year old."
)
print(response.output_text)
asyncio.run(main())
```
Functionality between the synchronous and asynchronous clients is otherwise identical.
### With aiohttp
By default, the async client uses `httpx` for HTTP requests. However, for improved concurrency performance you may also use `aiohttp` as the HTTP backend.
You can enable this by installing `aiohttp`:
```
# install from PyPI
pip install openai[aiohttp]
```
Then you can enable it by instantiating the client with `http_client=DefaultAioHttpClient()`:
```
import os
import asyncio
from openai import DefaultAioHttpClient
from openai import AsyncOpenAI
async def main() -> None:
async with AsyncOpenAI(
api_key=os.environ.get("OPENAI_API_KEY"), # This is the default and can be omitted
http_client=DefaultAioHttpClient(),
) as client:
chat_completion = await client.chat.completions.create(
messages=[
{
"role": "user",
"content": "Say this is a test",
}
],
model="gpt-5.2",
)
asyncio.run(main())
```
## Streaming responses
We provide support for streaming responses using Server Side Events (SSE).
```
from openai import OpenAI
client = OpenAI()
stream = client.responses.create(
model="gpt-5.2",
input="Write a one-sentence bedtime story about a unicorn.",
stream=True,
)
for event in stream:
print(event)
```
The async client uses the exact same interface.
```
import asyncio
from openai import AsyncOpenAI
client = AsyncOpenAI()
async def main():
stream = await client.responses.create(
model="gpt-5.2",
input="Write a one-sentence bedtime story about a unicorn.",
stream=True,
)
async for event in stream:
print(event)
asyncio.run(main())
```
## Realtime API
The Realtime API enables you to build low-latency, multi-modal conversational experiences. It currently supports text and audio as both input and output, as well as [function calling](https://platform.openai.com/docs/guides/function-calling) through a WebSocket connection.
Under the hood the SDK uses the [`websockets`](https://websockets.readthedocs.io/en/stable/) library to manage connections.
The Realtime API works through a combination of client-sent events and server-sent events. Clients can send events to do things like update session configuration or send text and audio inputs. Server events confirm when audio responses have completed, or when a text response from the model has been received. A full event reference can be found [here](https://platform.openai.com/docs/api-reference/realtime-client-events) and a guide can be found [here](https://platform.openai.com/docs/guides/realtime).
Basic text based example:
```
import asyncio
from openai import AsyncOpenAI
async def main():
client = AsyncOpenAI()
async with client.realtime.connect(model="gpt-realtime") as connection:
await connection.session.update(
session={"type": "realtime", "output_modalities": ["text"]}
)
await connection.conversation.item.create(
item={
"type": "message",
"role": "user",
"content": [{"type": "input_text", "text": "Say hello!"}],
}
)
await connection.response.create()
async for event in connection:
if event.type == "response.output_text.delta":
print(event.delta, flush=True, end="")
elif event.type == "response.output_text.done":
print()
elif event.type == "response.done":
break
asyncio.run(main())
```
However the real magic of the Realtime API is handling audio inputs / outputs, see this example [TUI script](https://github.com/openai/openai-python/blob/main/examples/realtime/push_to_talk_app.py) for a fully fledged example.
### Realtime error handling
Whenever an error occurs, the Realtime API will send an [`error` event](https://platform.openai.com/docs/guides/realtime-model-capabilities#error-handling) and the connection will stay open and remain usable. This means you need to handle it yourself, as *no errors are raised directly* by the SDK when an `error` event comes in.
```
client = AsyncOpenAI()
async with client.realtime.connect(model="gpt-realtime") as connection:
...
async for event in connection:
if event.type == 'error':
print(event.error.type)
print(event.error.code)
print(event.error.event_id)
print(event.error.message)
```
## Using types
Nested request parameters are [TypedDicts](https://docs.python.org/3/library/typing.html#typing.TypedDict). Responses are [Pydantic models](https://docs.pydantic.dev/) which also provide helper methods for things like:
- Serializing back into JSON, `model.to_json()`
- Converting to a dictionary, `model.to_dict()`
Typed requests and responses provide autocomplete and documentation within your editor. If you would like to see type errors in VS Code to help catch bugs earlier, set `python.analysis.typeCheckingMode` to `basic`.
## Pagination
List methods in the OpenAI API are paginated.
This library provides auto-paginating iterators with each list response, so you do not have to request successive pages manually:
```
from openai import OpenAI
client = OpenAI()
all_jobs = []
# Automatically fetches more pages as needed.
for job in client.fine_tuning.jobs.list(
limit=20,
):
# Do something with job here
all_jobs.append(job)
print(all_jobs)
```
Or, asynchronously:
```
import asyncio
from openai import AsyncOpenAI
client = AsyncOpenAI()
async def main() -> None:
all_jobs = []
# Iterate through items across all pages, issuing requests as needed.
async for job in client.fine_tuning.jobs.list(
limit=20,
):
all_jobs.append(job)
print(all_jobs)
asyncio.run(main())
```
Alternatively, you can use the `.has_next_page()`, `.next_page_info()`, or `.get_next_page()` methods for more granular control working with pages:
```
first_page = await client.fine_tuning.jobs.list(
limit=20,
)
if first_page.has_next_page():
print(f"will fetch next page using these details: {first_page.next_page_info()}")
next_page = await first_page.get_next_page()
print(f"number of items we just fetched: {len(next_page.data)}")
# Remove `await` for non-async usage.
```
Or just work directly with the returned data:
```
first_page = await client.fine_tuning.jobs.list(
limit=20,
)
print(f"next page cursor: {first_page.after}") # => "next page cursor: ..."
for job in first_page.data:
print(job.id)
# Remove `await` for non-async usage.
```
## Nested params
Nested parameters are dictionaries, typed using `TypedDict`, for example:
```
from openai import OpenAI
client = OpenAI()
response = client.chat.responses.create(
input=[
{
"role": "user",
"content": "How much ?",
}
],
model="gpt-5.2",
response_format={"type": "json_object"},
)
```
## File uploads
Request parameters that correspond to file uploads can be passed as `bytes`, or a [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike) instance or a tuple of `(filename, contents, media type)`.
```
from pathlib import Path
from openai import OpenAI
client = OpenAI()
client.files.create(
file=Path("input.jsonl"),
purpose="fine-tune",
)
```
The async client uses the exact same interface. If you pass a [`PathLike`](https://docs.python.org/3/library/os.html#os.PathLike) instance, the file contents will be read asynchronously automatically.
## Webhook Verification
Verifying webhook signatures is *optional but encouraged*.
For more information about webhooks, see [the API docs](https://platform.openai.com/docs/guides/webhooks).
### Parsing webhook payloads
For most use cases, you will likely want to verify the webhook and parse the payload at the same time. To achieve this, we provide the method `client.webhooks.unwrap()`, which parses a webhook request and verifies that it was sent by OpenAI. This method will raise an error if the signature is invalid.
Note that the `body` parameter must be the raw JSON string sent from the server (do not parse it first). The `.unwrap()` method will parse this JSON for you into an event object after verifying the webhook was sent from OpenAI.
```
from openai import OpenAI
from flask import Flask, request
app = Flask(__name__)
client = OpenAI() # OPENAI_WEBHOOK_SECRET environment variable is used by default
@app.route("/webhook", methods=["POST"])
def webhook():
request_body = request.get_data(as_text=True)
try:
event = client.webhooks.unwrap(request_body, request.headers)
if event.type == "response.completed":
print("Response completed:", event.data)
elif event.type == "response.failed":
print("Response failed:", event.data)
else:
print("Unhandled event type:", event.type)
return "ok"
except Exception as e:
print("Invalid signature:", e)
return "Invalid signature", 400
if __name__ == "__main__":
app.run(port=8000)
```
### Verifying webhook payloads directly
In some cases, you may want to verify the webhook separately from parsing the payload. If you prefer to handle these steps separately, we provide the method `client.webhooks.verify_signature()` to *only verify* the signature of a webhook request. Like `.unwrap()`, this method will raise an error if the signature is invalid.
Note that the `body` parameter must be the raw JSON string sent from the server (do not parse it first). You will then need to parse the body after verifying the signature.
```
import json
from openai import OpenAI
from flask import Flask, request
app = Flask(__name__)
client = OpenAI() # OPENAI_WEBHOOK_SECRET environment variable is used by default
@app.route("/webhook", methods=["POST"])
def webhook():
request_body = request.get_data(as_text=True)
try:
client.webhooks.verify_signature(request_body, request.headers)
# Parse the body after verification
event = json.loads(request_body)
print("Verified event:", event)
return "ok"
except Exception as e:
print("Invalid signature:", e)
return "Invalid signature", 400
if __name__ == "__main__":
app.run(port=8000)
```
## Handling errors
When the library is unable to connect to the API (for example, due to network connection problems or a timeout), a subclass of `openai.APIConnectionError` is raised.
When the API returns a non-success status code (that is, 4xx or 5xx response), a subclass of `openai.APIStatusError` is raised, containing `status_code` and `response` properties.
All errors inherit from `openai.APIError`.
```
import openai
from openai import OpenAI
client = OpenAI()
try:
client.fine_tuning.jobs.create(
model="gpt-4o",
training_file="file-abc123",
)
except openai.APIConnectionError as e:
print("The server could not be reached")
print(e.__cause__) # an underlying Exception, likely raised within httpx.
except openai.RateLimitError as e:
print("A 429 status code was received; we should back off a bit.")
except openai.APIStatusError as e:
print("Another non-200-range status code was received")
print(e.status_code)
print(e.response)
```
Error codes are as follows:
| Status Code | Error Type |
|---|---|
| 400 | `BadRequestError` |
| 401 | `AuthenticationError` |
| 403 | `PermissionDeniedError` |
| 404 | `NotFoundError` |
| 422 | `UnprocessableEntityError` |
| 429 | `RateLimitError` |
| \>=500 | `InternalServerError` |
| N/A | `APIConnectionError` |
## Request IDs
> For more information on debugging requests, see [these docs](https://platform.openai.com/docs/api-reference/debugging-requests)
All object responses in the SDK provide a `_request_id` property which is added from the `x-request-id` response header so that you can quickly log failing requests and report them back to OpenAI.
```
response = await client.responses.create(
model="gpt-5.2",
input="Say 'this is a test'.",
)
print(response._request_id) # req_123
```
Note that unlike other properties that use an `_` prefix, the `_request_id` property *is* public. Unless documented otherwise, *all* other `_` prefix properties, methods and modules are *private*.
> \[!IMPORTANT\]
> If you need to access request IDs for failed requests you must catch the `APIStatusError` exception
```
import openai
try:
completion = await client.chat.completions.create(
messages=[{"role": "user", "content": "Say this is a test"}], model="gpt-5.2"
)
except openai.APIStatusError as exc:
print(exc.request_id) # req_123
raise exc
```
## Retries
Certain errors are automatically retried 2 times by default, with a short exponential backoff. Connection errors (for example, due to a network connectivity problem), 408 Request Timeout, 409 Conflict, 429 Rate Limit, and \>=500 Internal errors are all retried by default.
You can use the `max_retries` option to configure or disable retry settings:
```
from openai import OpenAI
# Configure the default for all requests:
client = OpenAI(
# default is 2
max_retries=0,
)
# Or, configure per-request:
client.with_options(max_retries=5).chat.completions.create(
messages=[
{
"role": "user",
"content": "How can I get the name of the current day in JavaScript?",
}
],
model="gpt-5.2",
)
```
## Timeouts
By default requests time out after 10 minutes. You can configure this with a `timeout` option, which accepts a float or an [`httpx.Timeout`](https://www.python-httpx.org/advanced/timeouts/#fine-tuning-the-configuration) object:
```
from openai import OpenAI
# Configure the default for all requests:
client = OpenAI(
# 20 seconds (default is 10 minutes)
timeout=20.0,
)
# More granular control:
client = OpenAI(
timeout=httpx.Timeout(60.0, read=5.0, write=10.0, connect=2.0),
)
# Override per-request:
client.with_options(timeout=5.0).chat.completions.create(
messages=[
{
"role": "user",
"content": "How can I list all files in a directory using Python?",
}
],
model="gpt-5.2",
)
```
On timeout, an `APITimeoutError` is thrown.
Note that requests that time out are [retried twice by default](https://github.com/openai/openai-python/tree/main/#retries).
## Advanced
### Logging
We use the standard library [`logging`](https://docs.python.org/3/library/logging.html) module.
You can enable logging by setting the environment variable `OPENAI_LOG` to `info`.
```
$ export OPENAI_LOG=info
```
Or to `debug` for more verbose logging.
### How to tell whether `None` means `null` or missing
In an API response, a field may be explicitly `null`, or missing entirely; in either case, its value is `None` in this library. You can differentiate the two cases with `.model_fields_set`:
```
if response.my_field is None:
if 'my_field' not in response.model_fields_set:
print('Got json like {}, without a "my_field" key present at all.')
else:
print('Got json like {"my_field": null}.')
```
### Accessing raw response data (e.g. headers)
The "raw" Response object can be accessed by prefixing `.with_raw_response.` to any HTTP method call, e.g.,
```
from openai import OpenAI
client = OpenAI()
response = client.chat.completions.with_raw_response.create(
messages=[{
"role": "user",
"content": "Say this is a test",
}],
model="gpt-5.2",
)
print(response.headers.get('X-My-Header'))
completion = response.parse() # get the object that `chat.completions.create()` would have returned
print(completion)
```
These methods return a [`LegacyAPIResponse`](https://github.com/openai/openai-python/tree/main/src/openai/_legacy_response.py) object. This is a legacy class as we're changing it slightly in the next major version.
For the sync client this will mostly be the same with the exception of `content` & `text` will be methods instead of properties. In the async client, all methods will be async.
A migration script will be provided & the migration in general should be smooth.
#### `.with_streaming_response`
The above interface eagerly reads the full response body when you make the request, which may not always be what you want.
To stream the response body, use `.with_streaming_response` instead, which requires a context manager and only reads the response body once you call `.read()`, `.text()`, `.json()`, `.iter_bytes()`, `.iter_text()`, `.iter_lines()` or `.parse()`. In the async client, these are async methods.
As such, `.with_streaming_response` methods return a different [`APIResponse`](https://github.com/openai/openai-python/tree/main/src/openai/_response.py) object, and the async client returns an [`AsyncAPIResponse`](https://github.com/openai/openai-python/tree/main/src/openai/_response.py) object.
```
with client.chat.completions.with_streaming_response.create(
messages=[
{
"role": "user",
"content": "Say this is a test",
}
],
model="gpt-5.2",
) as response:
print(response.headers.get("X-My-Header"))
for line in response.iter_lines():
print(line)
```
The context manager is required so that the response will reliably be closed.
### Making custom/undocumented requests
This library is typed for convenient access to the documented API.
If you need to access undocumented endpoints, params, or response properties, the library can still be used.
#### Undocumented endpoints
To make requests to undocumented endpoints, you can make requests using `client.get`, `client.post`, and other http verbs. Options on the client will be respected (such as retries) when making this request.
```
import httpx
response = client.post(
"/foo",
cast_to=httpx.Response,
body={"my_param": True},
)
print(response.headers.get("x-foo"))
```
#### Undocumented request params
If you want to explicitly send an extra param, you can do so with the `extra_query`, `extra_body`, and `extra_headers` request options.
#### Undocumented response properties
To access undocumented response properties, you can access the extra fields like `response.unknown_prop`. You can also get all the extra fields on the Pydantic model as a dict with [`response.model_extra`](https://docs.pydantic.dev/latest/api/base_model/#pydantic.BaseModel.model_extra).
### Configuring the HTTP client
You can directly override the [httpx client](https://www.python-httpx.org/api/#client) to customize it for your use case, including:
- Support for [proxies](https://www.python-httpx.org/advanced/proxies/)
- Custom [transports](https://www.python-httpx.org/advanced/transports/)
- Additional [advanced](https://www.python-httpx.org/advanced/clients/) functionality
```
import httpx
from openai import OpenAI, DefaultHttpxClient
client = OpenAI(
# Or use the `OPENAI_BASE_URL` env var
base_url="http://my.test.server.example.com:8083/v1",
http_client=DefaultHttpxClient(
proxy="http://my.test.proxy.example.com",
transport=httpx.HTTPTransport(local_address="0.0.0.0"),
),
)
```
You can also customize the client on a per-request basis by using `with_options()`:
```
client.with_options(http_client=DefaultHttpxClient(...))
```
### Managing HTTP resources
By default the library closes underlying HTTP connections whenever the client is [garbage collected](https://docs.python.org/3/reference/datamodel.html#object.__del__). You can manually close the client using the `.close()` method if desired, or with a context manager that closes when exiting.
```
from openai import OpenAI
with OpenAI() as client:
# make requests here
...
# HTTP client is now closed
```
## Microsoft Azure OpenAI
To use this library with [Azure OpenAI](https://learn.microsoft.com/azure/ai-services/openai/overview), use the `AzureOpenAI` class instead of the `OpenAI` class.
> \[!IMPORTANT\] The Azure API shape differs from the core API shape which means that the static types for responses / params won't always be correct.
```
from openai import AzureOpenAI
# gets the API Key from environment variable AZURE_OPENAI_API_KEY
client = AzureOpenAI(
# https://learn.microsoft.com/azure/ai-services/openai/reference#rest-api-versioning
api_version="2023-07-01-preview",
# https://learn.microsoft.com/azure/cognitive-services/openai/how-to/create-resource?pivots=web-portal#create-a-resource
azure_endpoint="https://example-endpoint.openai.azure.com",
)
completion = client.chat.completions.create(
model="deployment-name", # e.g. gpt-35-instant
messages=[
{
"role": "user",
"content": "How do I output all files in a directory using Python?",
},
],
)
print(completion.to_json())
```
In addition to the options provided in the base `OpenAI` client, the following options are provided:
- `azure_endpoint` (or the `AZURE_OPENAI_ENDPOINT` environment variable)
- `azure_deployment`
- `api_version` (or the `OPENAI_API_VERSION` environment variable)
- `azure_ad_token` (or the `AZURE_OPENAI_AD_TOKEN` environment variable)
- `azure_ad_token_provider`
An example of using the client with Microsoft Entra ID (formerly known as Azure Active Directory) can be found [here](https://github.com/openai/openai-python/blob/main/examples/azure_ad.py).
## Versioning
This package generally follows [SemVer](https://semver.org/spec/v2.0.0.html) conventions, though certain backwards-incompatible changes may be released as minor versions:
1. Changes that only affect static types, without breaking runtime behavior.
2. Changes to library internals which are technically public but not intended or documented for external use. *(Please open a GitHub issue to let us know if you are relying on such internals.)*
3. Changes that we do not expect to impact the vast majority of users in practice.
We take backwards-compatibility seriously and work hard to ensure you can rely on a smooth upgrade experience.
We are keen for your feedback; please open an [issue](https://www.github.com/openai/openai-python/issues) with questions, bugs, or suggestions.
### Determining the installed version
If you've upgraded to the latest version but aren't seeing any new features you were expecting then your python environment is likely still using an older version.
You can determine the version that is being used at runtime with:
```
import openai
print(openai.__version__)
```
## Requirements
Python 3.9 or higher.
## Contributing
See [the contributing documentation](https://github.com/openai/openai-python/tree/main/CONTRIBUTING.md). |
| Shard | 59 (laksa) |
| Root Hash | 7813724874982801459 |
| Unparsed URL | org,pypi!/project/openai/ s443 |