openai
The openai package is the core library to install in Python projects that need
to call the OpenAI REST API. It includes modules for working with OpenAI
resources that provide access to its AI models,
including large language models (LLMs) like GPT-4 and models for working with images and audio. The openai
package
provides both synchronous and asynchronous API clients, options to configure their behavior, and modules that provide
Python code with an API surface to interact with the OpenAI platform.
To get started, read the submodule descriptions in resources
to determine which best fits your
project. For example, the resources.chat
submodule description indicates it's a good fit
for conversational chat-style interactions with an LLM like GPT-4 Turbo.
Or, maybe you need the resources.audio
module to perform audio transcription,
translation, and speech synthesis in your app.
Once you've determined the resource to use, create an OpenAI
or AsyncOpenAI
client instance and access the instance attribute for that resource on the client object. For example, if you instantiate
an OpenAI
client object named client
, you'd access the OpenAI.chat
instance attribute:
from openai import OpenAI
# Reads API key from OPENAI_API_KEY environment variable
client = OpenAI()
# Use the `chat` resource to interact with the OpenAI chat completions endpoint
completion = client.chat.completions.create(
model="gpt-4",
messages=[
{
"role": "user",
"content": "Say this is a test",
},
],
)
print(completion.choices[0].message.content)
For more information about the REST API this package talks to, or to find client libraries for other programming languages, see:
- REST API reference documentation for the OpenAPI REST API (platform.openai.com)
- OpenAPI Description (OAD) file for the OpenAPI REST API (GitHub)
- More client libraries for the OpenAI API (platform.openai.com)
MODULE | DESCRIPTION |
---|---|
cli |
|
pagination |
|
resources |
The The submodules' classes mirror the structure of the API's endpoints and offer synchronous and asynchronous communication with the API. Each resource is accessible as an attribute on the |
types |
|
version |
|
CLASS | DESCRIPTION |
---|---|
APIConnectionError |
|
APIError |
|
APIResponseValidationError |
|
APIStatusError |
Raised when an API response has a status code of 4xx or 5xx. |
APITimeoutError |
|
AsyncOpenAI |
|
AsyncStream |
Provides the core interface to iterate over an asynchronous stream response. |
AuthenticationError |
|
BadRequestError |
|
BaseModel |
|
ConflictError |
|
InternalServerError |
|
NotFoundError |
|
NotGiven |
A sentinel singleton class used to distinguish omitted keyword arguments |
OpenAI |
Primary synchronous client interface for interacting with the services (resources) provided by the OpenAI API. |
OpenAIError |
|
PermissionDeniedError |
|
RateLimitError |
|
RequestOptions |
|
Stream |
Provides the core interface to iterate over a synchronous stream response. |
UnprocessableEntityError |
|
FUNCTION | DESCRIPTION |
---|---|
file_from_path |
|
ATTRIBUTE | DESCRIPTION |
---|---|
AsyncClient |
|
Client |
|
NOT_GIVEN |
|
NoneType |
TYPE:
|
ProxiesTypes |
|
Transport |
|
api_key |
TYPE:
|
api_type |
TYPE:
|
api_version |
TYPE:
|
azure_ad_token |
TYPE:
|
azure_ad_token_provider |
TYPE:
|
azure_endpoint |
TYPE:
|
base_url |
TYPE:
|
default_headers |
|
default_query |
|
http_client |
TYPE:
|
max_retries |
TYPE:
|
organization |
TYPE:
|
timeout |
TYPE:
|
azure_ad_token_provider
module-attribute
APIError
ATTRIBUTE | DESCRIPTION |
---|---|
body |
The API response body.
TYPE:
|
code |
|
message |
TYPE:
|
param |
|
request |
TYPE:
|
type |
|
body
instance-attribute
The API response body.
If the API responded with a valid JSON structure then this property will be the decoded result.
If it isn't a valid JSON structure then this will be the raw response.
If there was no response associated with this error then it will be None
.
APIResponseValidationError
APIResponseValidationError(
response: Response,
body: object | None,
*,
message: str | None = None
)
ATTRIBUTE | DESCRIPTION |
---|---|
response |
TYPE:
|
status_code |
TYPE:
|
APIStatusError
Raised when an API response has a status code of 4xx or 5xx.
ATTRIBUTE | DESCRIPTION |
---|---|
response |
TYPE:
|
status_code |
TYPE:
|
AsyncOpenAI
AsyncOpenAI(
*,
api_key: str | None = None,
organization: str | None = None,
base_url: str | URL | None = None,
timeout: Union[
float, Timeout, None, NotGiven
] = NOT_GIVEN,
max_retries: int = DEFAULT_MAX_RETRIES,
default_headers: Mapping[str, str] | None = None,
default_query: Mapping[str, object] | None = None,
http_client: AsyncClient | None = None,
_strict_response_validation: bool = False
)
This automatically infers the following arguments from their corresponding environment variables if they are not provided:
- api_key
from OPENAI_API_KEY
- organization
from OPENAI_ORG_ID
METHOD | DESCRIPTION |
---|---|
copy |
Create a new client instance re-using the same options given to the current client with optional overriding. |
ATTRIBUTE | DESCRIPTION |
---|---|
api_key |
TYPE:
|
audio |
TYPE:
|
auth_headers |
|
beta |
TYPE:
|
chat |
TYPE:
|
completions |
TYPE:
|
default_headers |
|
embeddings |
TYPE:
|
files |
TYPE:
|
fine_tuning |
TYPE:
|
images |
TYPE:
|
models |
TYPE:
|
moderations |
TYPE:
|
organization |
TYPE:
|
qs |
TYPE:
|
with_options |
|
with_raw_response |
TYPE:
|
with_streaming_response |
TYPE:
|
with_raw_response
instance-attribute
with_streaming_response
instance-attribute
with_streaming_response: AsyncOpenAIWithStreamedResponse = (
AsyncOpenAIWithStreamedResponse(self)
)
copy
copy(
*,
api_key: str | None = None,
organization: str | None = None,
base_url: str | URL | None = None,
timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
http_client: AsyncClient | None = None,
max_retries: int | NotGiven = NOT_GIVEN,
default_headers: Mapping[str, str] | None = None,
set_default_headers: Mapping[str, str] | None = None,
default_query: Mapping[str, object] | None = None,
set_default_query: Mapping[str, object] | None = None,
_extra_kwargs: Mapping[str, Any] = {}
) -> Self
Create a new client instance re-using the same options given to the current client with optional overriding.
AsyncStream
AsyncStream(
*,
cast_to: type[_T],
response: Response,
client: AsyncOpenAI
)
AuthenticationError
ATTRIBUTE | DESCRIPTION |
---|---|
status_code |
TYPE:
|
BadRequestError
ATTRIBUTE | DESCRIPTION |
---|---|
status_code |
TYPE:
|
BaseModel
CLASS | DESCRIPTION |
---|---|
Config |
|
METHOD | DESCRIPTION |
---|---|
construct |
|
model_dump |
Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump |
model_dump_json |
Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump_json |
ATTRIBUTE | DESCRIPTION |
---|---|
model_config |
TYPE:
|
model_construct |
|
model_fields_set |
|
Config
model_dump
model_dump(
*,
mode: Literal["json", "python"] | str = "python",
include: IncEx = None,
exclude: IncEx = None,
by_alias: bool = False,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
round_trip: bool = False,
warnings: bool = True
) -> dict[str, Any]
Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
PARAMETER | DESCRIPTION |
---|---|
mode
|
The mode in which
TYPE:
|
include
|
A list of fields to include in the output.
TYPE:
|
exclude
|
A list of fields to exclude from the output.
TYPE:
|
by_alias
|
Whether to use the field's alias in the dictionary key if defined.
TYPE:
|
exclude_unset
|
Whether to exclude fields that are unset or None from the output.
TYPE:
|
exclude_defaults
|
Whether to exclude fields that are set to their default value from the output.
TYPE:
|
exclude_none
|
Whether to exclude fields that have a value of
TYPE:
|
round_trip
|
Whether to enable serialization and deserialization round-trip support.
TYPE:
|
warnings
|
Whether to log warnings when invalid fields are encountered.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
dict[str, Any]
|
A dictionary representation of the model. |
model_dump_json
model_dump_json(
*,
indent: int | None = None,
include: IncEx = None,
exclude: IncEx = None,
by_alias: bool = False,
exclude_unset: bool = False,
exclude_defaults: bool = False,
exclude_none: bool = False,
round_trip: bool = False,
warnings: bool = True
) -> str
Usage docs: https://docs.pydantic.dev/2.4/concepts/serialization/#modelmodel_dump_json
Generates a JSON representation of the model using Pydantic's to_json
method.
PARAMETER | DESCRIPTION |
---|---|
indent
|
Indentation to use in the JSON output. If None is passed, the output will be compact.
TYPE:
|
include
|
Field(s) to include in the JSON output. Can take either a string or set of strings.
TYPE:
|
exclude
|
Field(s) to exclude from the JSON output. Can take either a string or set of strings.
TYPE:
|
by_alias
|
Whether to serialize using field aliases.
TYPE:
|
exclude_unset
|
Whether to exclude fields that have not been explicitly set.
TYPE:
|
exclude_defaults
|
Whether to exclude fields that have the default value.
TYPE:
|
exclude_none
|
Whether to exclude fields that have a value of
TYPE:
|
round_trip
|
Whether to use serialization/deserialization between JSON and class instance.
TYPE:
|
warnings
|
Whether to show any warnings that occurred during serialization.
TYPE:
|
RETURNS | DESCRIPTION |
---|---|
str
|
A JSON string representation of the model. |
ConflictError
ATTRIBUTE | DESCRIPTION |
---|---|
status_code |
TYPE:
|
NotFoundError
ATTRIBUTE | DESCRIPTION |
---|---|
status_code |
TYPE:
|
NotGiven
A sentinel singleton class used to distinguish omitted keyword arguments from those passed in with the value None (which may have different behavior).
For example:
def get(timeout: Union[int, NotGiven, None] = NotGiven()) -> Response:
...
get(timeout=1) # 1s timeout
get(timeout=None) # No timeout
get() # Default timeout behavior, which may not be statically known at the method definition.
OpenAI
OpenAI(
*,
api_key: str | None = None,
organization: str | None = None,
base_url: str | URL | None = None,
timeout: Union[
float, Timeout, None, NotGiven
] = NOT_GIVEN,
max_retries: int = DEFAULT_MAX_RETRIES,
default_headers: Mapping[str, str] | None = None,
default_query: Mapping[str, object] | None = None,
http_client: Client | None = None,
_strict_response_validation: bool = False
)
Primary synchronous client interface for interacting with the services (resources) provided by the OpenAI API.
An instance of the OpenAI
class is the top-level object you interact with to make synchronous calls to the
OpenAI API. The client provides access to OpenAI's services, or resources, like text completion, chat,
embeddings, image and audio processing, and managing the files used by these resources.
The API authenticates requests to its endpoints by validating your API key, which you provide to the OpenAI
client object in one of two ways:
Set an environment variable named OPENAI_API_KEY
that contains
your API key and then instantiate the client without passing the api_key
parameter. This is the preferred
method.
Pass the api_key
parameter explicitly when you instantiate the client object. Choose this
method only if you're unwilling or unable to use a more secure method like setting the OPENAI_API_KEY
environment variable.
Danger
To prevent unauthorized access to OpenAI services, securely manage credentials like your OpenAI API key.
Examples:
The following code snippets each create an instance of the OpenAI
class ready to call the API. To interact
with an OpenAI service (a resource
in the API), you access the appropriate
attribute on the initialized client object and call the the methods provided by that resource.
-
Create client using inferred API key — The API key is obtained by the
OpenAI
client automatically from theOPENAI_API_KEY
environment variable if you omit theapi_key
constructor argument. -
Create client using explicit API key — Passing the API key explicitly directs the
OpenAI
client to use that key instead of theOPENAI_API_KEY
environment variable (if set).This instantiation method can pose an increased security risk. For example, by instantiating the client this way in your code, it's easier to accidentally commit your API key to version control, which you should never do.
PARAMETER | DESCRIPTION |
---|---|
api_key
|
The API key used for authenticating requests to OpenAI. If not provided, the
client attempts to retrieve the API key from the
TYPE:
|
organization
|
The ID of the organization under which the API calls are made. This is
optional and typically used for OpenAI services that require organization-level access control. If not
provided, the client attempts to retrieve the organization ID from the
TYPE:
|
base_url
|
The base URL for the OpenAI API. This allows for custom API endpoints like those used for testing or specific API versions. If not provided, defaults to the official OpenAI API URL.
TYPE:
|
timeout
|
The timeout for API requests. This can be
specified as a float representing seconds, a
TYPE:
|
max_retries
|
The maximum number of retries for failed requests. This can help handle
transient network issues or rate limit errors gracefully. Defaults to a predefined constant
TYPE:
|
default_headers
|
Default headers to include with every request. This
can be used to set global headers like |
default_query
|
Default query parameters to include with every request. This is useful for setting global parameters that should be included in all API calls. Defaults to None. |
http_client
|
An instance of
TYPE:
|
_strict_response_validation
|
Enables or disables strict validation of API responses against the expected schema. This is primarily used for development and debugging purposes to ensure the API responses match the expected format. Note that this argument may be removed or changed in future releases. Defaults to False.
TYPE:
|
RAISES | DESCRIPTION |
---|---|
OpenAIError
|
If neither the |
METHOD | DESCRIPTION |
---|---|
copy |
Create a new client instance re-using the same options given to the current client with optional overriding. |
ATTRIBUTE | DESCRIPTION |
---|---|
api_key |
TYPE:
|
audio |
TYPE:
|
auth_headers |
|
beta |
TYPE:
|
chat |
TYPE:
|
completions |
TYPE:
|
default_headers |
|
embeddings |
TYPE:
|
files |
TYPE:
|
fine_tuning |
TYPE:
|
images |
TYPE:
|
models |
TYPE:
|
moderations |
TYPE:
|
organization |
TYPE:
|
qs |
TYPE:
|
with_options |
|
with_raw_response |
TYPE:
|
with_streaming_response |
TYPE:
|
with_raw_response
instance-attribute
with_streaming_response
instance-attribute
copy
copy(
*,
api_key: str | None = None,
organization: str | None = None,
base_url: str | URL | None = None,
timeout: float | Timeout | None | NotGiven = NOT_GIVEN,
http_client: Client | None = None,
max_retries: int | NotGiven = NOT_GIVEN,
default_headers: Mapping[str, str] | None = None,
set_default_headers: Mapping[str, str] | None = None,
default_query: Mapping[str, object] | None = None,
set_default_query: Mapping[str, object] | None = None,
_extra_kwargs: Mapping[str, Any] = {}
) -> Self
Create a new client instance re-using the same options given to the current client with optional overriding.
OpenAIError
PermissionDeniedError
ATTRIBUTE | DESCRIPTION |
---|---|
status_code |
TYPE:
|
RateLimitError
ATTRIBUTE | DESCRIPTION |
---|---|
status_code |
TYPE:
|
RequestOptions
ATTRIBUTE | DESCRIPTION |
---|---|
extra_json |
TYPE:
|
headers |
TYPE:
|
idempotency_key |
TYPE:
|
max_retries |
TYPE:
|
params |
TYPE:
|
timeout |
TYPE:
|
Stream
UnprocessableEntityError
ATTRIBUTE | DESCRIPTION |
---|---|
status_code |
TYPE:
|