The OpenAI Python library provides convenient access to the OpenAI REST API from any Python 3.8+ 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.
The REST API documentation can be found on platform.openai.com. The full API of this library can be found in api.md.
[!importANT] The SDK was rewritten in v1, which was released November 6th 2023. See the v1 migration guide, which includes scripts to automatically update your code.
pipinstallopenai
The full API of this library can be found in api.md.
While you can provide an keyword argument, we recommend using python-dotenv to add to your file so that your API Key is not stored in source control.
With a hosted image:
With the image as a base64 encoded string:
When interacting with the API some actions such as starting a Run and adding files to vector stores are asynchronous and take time to complete. The SDK includes helper functions which will poll the status until it reaches a terminal state and then return the resulting object. If an API method results in an action that could benefit from polling there will be a corresponding version of the method ending in '_and_poll'.
For instance to create a Run and poll until it reaches a terminal state you can run:
More information on the lifecycle of a Run can be found in the Run Lifecycle documentation
When creating and interacting with vector stores, you can use polling helpers to monitor the status of operations. For convenience, we also provide a bulk upload helper to allow you to simultaneously upload several files at once.
The SDK also includes helpers to process streams and handle incoming events.
More information on streaming helpers can be found in the dedicated documentation: helpers.md
Simply import instead of and use with each API call:
Functionality between the synchronous and asynchronous clients is otherwise identical.
We provide support for streaming responses using Server Side Events (SSE).
The async client uses the exact same interface.
[!importANT] We highly recommend instantiating client instances instead of relying on the global client.
We also expose a global client instance that is accessible in a similar fashion to versions prior to v1.
The API is the exact same as the standard client instance-based API.
This is intended to be used within REPLs or notebooks for faster iteration, not in application code.
We recommend that you always instantiate a client (e.g., with ) in application code because:
- It can be difficult to reason about where client options are configured
- It's not possible to change certain client options without potentially causing race conditions
- It's harder to mock for testing purposes
- It's not possible to control cleanup of network connections
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 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:
However the real magic of the Realtime API is handling audio inputs / outputs, see this example TUI script for a fully fledged example.
Whenever an error occurs, the Realtime API will send an 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 event comes in.
Nested request parameters are TypedDicts. Responses are Pydantic models which also provide helper methods for things like:
- Serializing back into JSON,
- Converting to a dictionary,
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 to .
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:
Or, asynchronously:
Alternatively, you can use the , , or methods for more granular control working with pages:
Or just work directly with the returned data:
Nested parameters are dictionaries, typed using , for example:
Request parameters that correspond to file uploads can be passed as , a instance or a tuple of .
The async client uses the exact same interface. If you pass a instance, the file contents will be read asynchronously automatically.
When the library is unable to connect to the API (for example, due to network connection problems or a timeout), a subclass of is raised.
When the API returns a non-success status code (that is, 4xx or 5xx response), a subclass of is raised, containing and properties.
All errors inherit from .
Error codes are as followed:
For more information on debugging requests, see these docs
All object responses in the SDK provide a property which is added from the response header so that you can quickly log failing requests and report them back to OpenAI.
Note that unlike other properties that use an prefix, the property is public. Unless documented otherwise, all other prefix properties, methods and modules are private.
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 option to configure or disable retry settings:
By default requests time out after 10 minutes. You can configure this with a option, which accepts a float or an object:
On timeout, an is thrown.
Note that requests that time out are retried twice by default.
We use the standard library module.
You can enable logging by setting the environment variable to .
$info
Or to for more verbose logging.
In an API response, a field may be explicitly , or missing entirely; in either case, its value is in this library. You can differentiate the two cases with :
The "raw" Response object can be accessed by prefixing to any HTTP method call, e.g.,
These methods return an 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 & 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.
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 instead, which requires a context manager and only reads the response body once you call , , , , , or . In the async client, these are async methods.
As such, methods return a different object, and the async client returns an object.
The context manager is required so that the response will reliably be closed.
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 , , and other http verbs. Options on the client will be respected (such as retries) will be respected when making this request.
Undocumented request params
If you want to explicitly send an extra param, you can do so with the , , and request options.
Undocumented response properties
To access undocumented response properties, you can access the extra fields like . You can also get all the extra fields on the Pydantic model as a dict with .
You can directly override the httpx client to customize it for your use case, including:
- Support for proxies
- Custom transports
- Additional advanced functionality
You can also customize the client on a per-request basis by using :
By default the library closes underlying HTTP connections whenever the client is garbage collected. You can manually close the client using the method if desired, or with a context manager that closes when exiting.
To use this library with Azure OpenAI, use the class instead of the 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.
In addition to the options provided in the base client, the following options are provided:
- (or the environment variable)
- (or the environment variable)
- (or the environment variable)
An example of using the client with Microsoft Entra ID (formerly known as Azure Active Directory) can be found here.
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.
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:
Python 3.8 or higher.