diff --git a/.release-please-manifest.json b/.release-please-manifest.json index 59565e8e31..cce9d1c6d3 100644 --- a/.release-please-manifest.json +++ b/.release-please-manifest.json @@ -1,3 +1,3 @@ { - ".": "1.6.1" + ".": "1.7.0" } \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 83bf20f775..09c81dae8d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,35 @@ # Changelog +## 1.7.0 (2024-01-08) + +Full Changelog: [v1.6.1...v1.7.0](https://github.com/openai/openai-python/compare/v1.6.1...v1.7.0) + +### Features + +* add `None` default value to nullable response properties ([#1043](https://github.com/openai/openai-python/issues/1043)) ([d94b4d3](https://github.com/openai/openai-python/commit/d94b4d3d0adcd1a49a1c25cc9730cef013a3e9c9)) + + +### Bug Fixes + +* **client:** correctly use custom http client auth ([#1028](https://github.com/openai/openai-python/issues/1028)) ([3d7d93e](https://github.com/openai/openai-python/commit/3d7d93e951eb7fe09cd9d94d10a62a020398c7f9)) + + +### Chores + +* add .keep files for examples and custom code directories ([#1057](https://github.com/openai/openai-python/issues/1057)) ([7524097](https://github.com/openai/openai-python/commit/7524097a47af0fdc8b560186ef3b111b59430741)) +* **internal:** bump license ([#1037](https://github.com/openai/openai-python/issues/1037)) ([d828527](https://github.com/openai/openai-python/commit/d828527540ebd97679075f48744818f06311b0cb)) +* **internal:** loosen type var restrictions ([#1049](https://github.com/openai/openai-python/issues/1049)) ([e00876b](https://github.com/openai/openai-python/commit/e00876b20b93038450eb317899d8775c7661b8eb)) +* **internal:** replace isort with ruff ([#1042](https://github.com/openai/openai-python/issues/1042)) ([f1fbc9c](https://github.com/openai/openai-python/commit/f1fbc9c0d62e7d89ab32c8bdfa39cd94b560690b)) +* **internal:** update formatting ([#1041](https://github.com/openai/openai-python/issues/1041)) ([2e9ecee](https://github.com/openai/openai-python/commit/2e9ecee9bdfa8ec33b1b1527d5187483b700fad3)) +* **src:** fix typos ([#988](https://github.com/openai/openai-python/issues/988)) ([6a8b806](https://github.com/openai/openai-python/commit/6a8b80624636f9a0e5ada151b2509710a6f74808)) +* use property declarations for resource members ([#1047](https://github.com/openai/openai-python/issues/1047)) ([131f6bc](https://github.com/openai/openai-python/commit/131f6bc6b0ccf79119096057079e10906b3d4678)) + + +### Documentation + +* fix docstring typos ([#1022](https://github.com/openai/openai-python/issues/1022)) ([ad3fd2c](https://github.com/openai/openai-python/commit/ad3fd2cd19bf91f94473e368554dff39a8f9ad16)) +* improve audio example to show how to stream to a file ([#1017](https://github.com/openai/openai-python/issues/1017)) ([d45ed7f](https://github.com/openai/openai-python/commit/d45ed7f0513b167555ae875f1877fa205c5790d2)) + ## 1.6.1 (2023-12-22) Full Changelog: [v1.6.0...v1.6.1](https://github.com/openai/openai-python/compare/v1.6.0...v1.6.1) diff --git a/LICENSE b/LICENSE index 7b1b36a644..621a6becfb 100644 --- a/LICENSE +++ b/LICENSE @@ -186,7 +186,7 @@ same "printed page" as the copyright notice for easier identification within third-party archives. - Copyright 2023 OpenAI + Copyright 2024 OpenAI Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. diff --git a/examples/.keep b/examples/.keep new file mode 100644 index 0000000000..d8c73e937a --- /dev/null +++ b/examples/.keep @@ -0,0 +1,4 @@ +File generated from our OpenAPI spec by Stainless. + +This directory can be used to store example files demonstrating usage of this SDK. +It is ignored by Stainless code generation and its content (other than this keep file) won't be touched. \ No newline at end of file diff --git a/examples/picture.py b/examples/picture.py new file mode 100644 index 0000000000..c27b52b0da --- /dev/null +++ b/examples/picture.py @@ -0,0 +1,21 @@ +#!/usr/bin/env python + +from openai import OpenAI + +# gets OPENAI_API_KEY from your environment variables +openai = OpenAI() + +prompt = "An astronaut lounging in a tropical resort in space, pixel art" +model = "dall-e-3" + + +def main() -> None: + # Generate an image based on the prompt + response = openai.images.generate(prompt=prompt, model=model) + + # Prints response containing a URL link to image + print(response) + + +if __name__ == "__main__": + main() diff --git a/pyproject.toml b/pyproject.toml index f39cfb8f15..85d19f1d0e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "openai" -version = "1.6.1" +version = "1.7.0" description = "The official Python library for the openai API" readme = "README.md" license = "Apache-2.0" @@ -14,6 +14,7 @@ dependencies = [ "anyio>=3.5.0, <5", "distro>=1.7.0, <2", "sniffio", + "cached-property; python_version < '3.8'", "tqdm > 4" ] requires-python = ">= 3.7.1" @@ -55,7 +56,6 @@ dev-dependencies = [ "pytest", "pytest-asyncio", "ruff", - "isort", "time-machine", "nox", "dirty-equals>=0.6.0", @@ -69,7 +69,6 @@ format = { chain = [ "format:ruff", "format:docs", "fix:ruff", - "format:isort", ]} "format:black" = "black ." "format:docs" = "python bin/ruffen-docs.py README.md api.md" @@ -130,16 +129,13 @@ reportImplicitOverride = true reportImportCycles = false reportPrivateUsage = false -[tool.isort] -profile = "black" -length_sort = true -extra_standard_library = ["typing_extensions"] - [tool.ruff] line-length = 120 output-format = "grouped" target-version = "py37" select = [ + # isort + "I", # bugbear rules "B", # remove unused imports @@ -166,6 +162,13 @@ ignore-init-module-imports = true [tool.ruff.format] docstring-code-format = true +[tool.ruff.lint.isort] +length-sort = true +length-sort-straight = true +combine-as-imports = true +extra-standard-library = ["typing_extensions"] +known-first-party = ["openai", "tests"] + [tool.ruff.per-file-ignores] "bin/**.py" = ["T201", "T203"] "tests/**.py" = ["T201", "T203"] diff --git a/requirements-dev.lock b/requirements-dev.lock index 53763f2aa9..088cb2bd98 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -29,17 +29,16 @@ httpx==0.25.2 idna==3.4 importlib-metadata==7.0.0 iniconfig==2.0.0 -isort==5.10.1 msal==1.26.0 msal-extensions==1.1.0 mypy==1.7.1 mypy-extensions==1.0.0 nodeenv==1.8.0 nox==2023.4.22 -numpy==1.26.2 +numpy==1.26.3 packaging==23.2 pandas==2.1.4 -pandas-stubs==2.1.4.231218 +pandas-stubs==2.1.4.231227 platformdirs==3.11.0 pluggy==1.3.0 portalocker==2.8.2 @@ -64,7 +63,7 @@ tqdm==4.66.1 types-pytz==2023.3.1.1 types-tqdm==4.66.0.2 typing-extensions==4.8.0 -tzdata==2023.3 +tzdata==2023.4 urllib3==2.1.0 virtualenv==20.24.5 zipp==3.17.0 diff --git a/src/openai/__init__.py b/src/openai/__init__.py index 0d66b3c682..ee96f06919 100644 --- a/src/openai/__init__.py +++ b/src/openai/__init__.py @@ -8,17 +8,7 @@ from . import types from ._types import NoneType, Transport, ProxiesTypes from ._utils import file_from_path -from ._client import ( - Client, - OpenAI, - Stream, - Timeout, - Transport, - AsyncClient, - AsyncOpenAI, - AsyncStream, - RequestOptions, -) +from ._client import Client, OpenAI, Stream, Timeout, Transport, AsyncClient, AsyncOpenAI, AsyncStream, RequestOptions from ._version import __title__, __version__ from ._exceptions import ( APIError, @@ -72,8 +62,7 @@ from .lib import azure as _azure from .version import VERSION as VERSION -from .lib.azure import AzureOpenAI as AzureOpenAI -from .lib.azure import AsyncAzureOpenAI as AsyncAzureOpenAI +from .lib.azure import AzureOpenAI as AzureOpenAI, AsyncAzureOpenAI as AsyncAzureOpenAI from .lib._old_api import * _setup_logging() @@ -323,15 +312,17 @@ def _reset_client() -> None: # type: ignore[reportUnusedFunction] _client = None -from ._module_client import beta as beta -from ._module_client import chat as chat -from ._module_client import audio as audio -from ._module_client import edits as edits -from ._module_client import files as files -from ._module_client import images as images -from ._module_client import models as models -from ._module_client import embeddings as embeddings -from ._module_client import fine_tunes as fine_tunes -from ._module_client import completions as completions -from ._module_client import fine_tuning as fine_tuning -from ._module_client import moderations as moderations +from ._module_client import ( + beta as beta, + chat as chat, + audio as audio, + edits as edits, + files as files, + images as images, + models as models, + embeddings as embeddings, + fine_tunes as fine_tunes, + completions as completions, + fine_tuning as fine_tuning, + moderations as moderations, +) diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 481171a447..97c6bef913 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -48,7 +48,6 @@ Body, Omit, Query, - ModelT, Headers, Timeout, NotGiven, @@ -58,9 +57,9 @@ PostParser, ProxiesTypes, RequestFiles, + HttpxSendArgs, AsyncTransport, RequestOptions, - UnknownResponse, ModelBuilderProtocol, BinaryResponseContent, ) @@ -141,7 +140,7 @@ def __init__( self.params = params -class BasePage(GenericModel, Generic[ModelT]): +class BasePage(GenericModel, Generic[_T]): """ Defines the core interface for pagination. @@ -154,7 +153,7 @@ class BasePage(GenericModel, Generic[ModelT]): """ _options: FinalRequestOptions = PrivateAttr() - _model: Type[ModelT] = PrivateAttr() + _model: Type[_T] = PrivateAttr() def has_next_page(self) -> bool: items = self._get_page_items() @@ -165,7 +164,7 @@ def has_next_page(self) -> bool: def next_page_info(self) -> Optional[PageInfo]: ... - def _get_page_items(self) -> Iterable[ModelT]: # type: ignore[empty-body] + def _get_page_items(self) -> Iterable[_T]: # type: ignore[empty-body] ... def _params_from_url(self, url: URL) -> httpx.QueryParams: @@ -190,13 +189,13 @@ def _info_to_options(self, info: PageInfo) -> FinalRequestOptions: raise ValueError("Unexpected PageInfo state") -class BaseSyncPage(BasePage[ModelT], Generic[ModelT]): +class BaseSyncPage(BasePage[_T], Generic[_T]): _client: SyncAPIClient = pydantic.PrivateAttr() def _set_private_attributes( self, client: SyncAPIClient, - model: Type[ModelT], + model: Type[_T], options: FinalRequestOptions, ) -> None: self._model = model @@ -211,7 +210,7 @@ def _set_private_attributes( # methods should continue to work as expected as there is an alternative method # to cast a model to a dictionary, model.dict(), which is used internally # by pydantic. - def __iter__(self) -> Iterator[ModelT]: # type: ignore + def __iter__(self) -> Iterator[_T]: # type: ignore for page in self.iter_pages(): for item in page._get_page_items(): yield item @@ -236,13 +235,13 @@ def get_next_page(self: SyncPageT) -> SyncPageT: return self._client._request_api_list(self._model, page=self.__class__, options=options) -class AsyncPaginator(Generic[ModelT, AsyncPageT]): +class AsyncPaginator(Generic[_T, AsyncPageT]): def __init__( self, client: AsyncAPIClient, options: FinalRequestOptions, page_cls: Type[AsyncPageT], - model: Type[ModelT], + model: Type[_T], ) -> None: self._model = model self._client = client @@ -265,7 +264,7 @@ def _parser(resp: AsyncPageT) -> AsyncPageT: return await self._client.request(self._page_cls, self._options) - async def __aiter__(self) -> AsyncIterator[ModelT]: + async def __aiter__(self) -> AsyncIterator[_T]: # https://github.com/microsoft/pyright/issues/3464 page = cast( AsyncPageT, @@ -275,12 +274,12 @@ async def __aiter__(self) -> AsyncIterator[ModelT]: yield item -class BaseAsyncPage(BasePage[ModelT], Generic[ModelT]): +class BaseAsyncPage(BasePage[_T], Generic[_T]): _client: AsyncAPIClient = pydantic.PrivateAttr() def _set_private_attributes( self, - model: Type[ModelT], + model: Type[_T], client: AsyncAPIClient, options: FinalRequestOptions, ) -> None: @@ -288,7 +287,7 @@ def _set_private_attributes( self._client = client self._options = options - async def __aiter__(self) -> AsyncIterator[ModelT]: + async def __aiter__(self) -> AsyncIterator[_T]: async for page in self.iter_pages(): for item in page._get_page_items(): yield item @@ -527,7 +526,7 @@ def _process_response_data( if data is None: return cast(ResponseT, None) - if cast_to is UnknownResponse: + if cast_to is object: return cast(ResponseT, data) try: @@ -873,11 +872,15 @@ def _request( request = self._build_request(options) self._prepare_request(request) + kwargs: HttpxSendArgs = {} + if self.custom_auth is not None: + kwargs["auth"] = self.custom_auth + try: response = self._client.send( request, - auth=self.custom_auth, stream=stream or self._should_stream_response_body(request=request), + **kwargs, ) except httpx.TimeoutException as err: if retries > 0: @@ -965,7 +968,7 @@ def _retry_request( def _request_api_list( self, - model: Type[ModelT], + model: Type[object], page: Type[SyncPageT], options: FinalRequestOptions, ) -> SyncPageT: @@ -1127,7 +1130,7 @@ def get_api_list( self, path: str, *, - model: Type[ModelT], + model: Type[object], page: Type[SyncPageT], body: Body | None = None, options: RequestOptions = {}, @@ -1335,11 +1338,15 @@ async def _request( request = self._build_request(options) await self._prepare_request(request) + kwargs: HttpxSendArgs = {} + if self.custom_auth is not None: + kwargs["auth"] = self.custom_auth + try: response = await self._client.send( request, - auth=self.custom_auth, stream=stream or self._should_stream_response_body(request=request), + **kwargs, ) except httpx.TimeoutException as err: if retries > 0: @@ -1425,10 +1432,10 @@ async def _retry_request( def _request_api_list( self, - model: Type[ModelT], + model: Type[_T], page: Type[AsyncPageT], options: FinalRequestOptions, - ) -> AsyncPaginator[ModelT, AsyncPageT]: + ) -> AsyncPaginator[_T, AsyncPageT]: return AsyncPaginator(client=self, options=options, page_cls=page, model=model) @overload @@ -1575,13 +1582,12 @@ def get_api_list( self, path: str, *, - # TODO: support paginating `str` - model: Type[ModelT], + model: Type[_T], page: Type[AsyncPageT], body: Body | None = None, options: RequestOptions = {}, method: str = "get", - ) -> AsyncPaginator[ModelT, AsyncPageT]: + ) -> AsyncPaginator[_T, AsyncPageT]: opts = FinalRequestOptions.construct(method=method, url=path, json_data=body, **options) return self._request_api_list(model, page, opts) diff --git a/src/openai/_client.py b/src/openai/_client.py index dacadf5aff..9eb6888909 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -19,12 +19,19 @@ ProxiesTypes, RequestOptions, ) -from ._utils import is_given, is_mapping, get_async_library +from ._utils import ( + is_given, + is_mapping, + get_async_library, +) from ._version import __version__ -from ._streaming import Stream as Stream -from ._streaming import AsyncStream as AsyncStream +from ._streaming import Stream as Stream, AsyncStream as AsyncStream from ._exceptions import OpenAIError, APIStatusError -from ._base_client import DEFAULT_MAX_RETRIES, SyncAPIClient, AsyncAPIClient +from ._base_client import ( + DEFAULT_MAX_RETRIES, + SyncAPIClient, + AsyncAPIClient, +) __all__ = [ "Timeout", diff --git a/src/openai/_compat.py b/src/openai/_compat.py index 34323c9b7e..3cda39909b 100644 --- a/src/openai/_compat.py +++ b/src/openai/_compat.py @@ -43,21 +43,23 @@ def is_typeddict(type_: type[Any]) -> bool: # noqa: ARG001 else: if PYDANTIC_V2: - from pydantic.v1.typing import get_args as get_args - from pydantic.v1.typing import is_union as is_union - from pydantic.v1.typing import get_origin as get_origin - from pydantic.v1.typing import is_typeddict as is_typeddict - from pydantic.v1.typing import is_literal_type as is_literal_type - from pydantic.v1.datetime_parse import parse_date as parse_date - from pydantic.v1.datetime_parse import parse_datetime as parse_datetime + from pydantic.v1.typing import ( + get_args as get_args, + is_union as is_union, + get_origin as get_origin, + is_typeddict as is_typeddict, + is_literal_type as is_literal_type, + ) + from pydantic.v1.datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime else: - from pydantic.typing import get_args as get_args - from pydantic.typing import is_union as is_union - from pydantic.typing import get_origin as get_origin - from pydantic.typing import is_typeddict as is_typeddict - from pydantic.typing import is_literal_type as is_literal_type - from pydantic.datetime_parse import parse_date as parse_date - from pydantic.datetime_parse import parse_datetime as parse_datetime + from pydantic.typing import ( + get_args as get_args, + is_union as is_union, + get_origin as get_origin, + is_typeddict as is_typeddict, + is_literal_type as is_literal_type, + ) + from pydantic.datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime # refactored config @@ -171,3 +173,13 @@ class GenericModel(pydantic.BaseModel): class GenericModel(pydantic.generics.GenericModel, pydantic.BaseModel): ... + + +# cached properties +if TYPE_CHECKING: + cached_property = property +else: + try: + from functools import cached_property as cached_property + except ImportError: + from cached_property import cached_property as cached_property diff --git a/src/openai/_exceptions.py b/src/openai/_exceptions.py index 40b163270d..d7ded1248f 100644 --- a/src/openai/_exceptions.py +++ b/src/openai/_exceptions.py @@ -40,8 +40,8 @@ class APIError(OpenAIError): If there was no response associated with this error then it will be `None`. """ - code: Optional[str] - param: Optional[str] + code: Optional[str] = None + param: Optional[str] = None type: Optional[str] def __init__(self, message: str, request: httpx.Request, *, body: object | None) -> None: diff --git a/src/openai/_extras/__init__.py b/src/openai/_extras/__init__.py index dc6625c5dc..864dac4171 100644 --- a/src/openai/_extras/__init__.py +++ b/src/openai/_extras/__init__.py @@ -1,3 +1,2 @@ -from .numpy_proxy import numpy as numpy -from .numpy_proxy import has_numpy as has_numpy +from .numpy_proxy import numpy as numpy, has_numpy as has_numpy from .pandas_proxy import pandas as pandas diff --git a/src/openai/_models.py b/src/openai/_models.py index 330a2064d8..48d5624f64 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -30,17 +30,11 @@ AnyMapping, HttpxRequestFiles, ) -from ._utils import ( - is_list, - is_given, - is_mapping, - parse_date, - parse_datetime, - strip_not_given, -) -from ._compat import PYDANTIC_V2, ConfigDict -from ._compat import GenericModel as BaseGenericModel +from ._utils import is_list, is_given, is_mapping, parse_date, parse_datetime, strip_not_given from ._compat import ( + PYDANTIC_V2, + ConfigDict, + GenericModel as BaseGenericModel, get_args, is_union, parse_obj, diff --git a/src/openai/_response.py b/src/openai/_response.py index 6b7c86e544..bf72d18fd5 100644 --- a/src/openai/_response.py +++ b/src/openai/_response.py @@ -9,7 +9,7 @@ import httpx -from ._types import NoneType, UnknownResponse, BinaryResponseContent +from ._types import NoneType, BinaryResponseContent from ._utils import is_given, extract_type_var_from_base from ._models import BaseModel, is_basemodel from ._constants import RAW_RESPONSE_HEADER @@ -162,7 +162,7 @@ def _parse(self) -> R: # `ResponseT` TypeVar, however if that TypeVar is ever updated in the future, then # this function would become unsafe but a type checker would not report an error. if ( - cast_to is not UnknownResponse + cast_to is not object and not origin is list and not origin is dict and not origin is Union diff --git a/src/openai/_types.py b/src/openai/_types.py index fc26d5458a..e6b83b2a3f 100644 --- a/src/openai/_types.py +++ b/src/openai/_types.py @@ -19,15 +19,9 @@ Sequence, AsyncIterator, ) -from typing_extensions import ( - Literal, - Protocol, - TypeAlias, - TypedDict, - override, - runtime_checkable, -) +from typing_extensions import Literal, Protocol, TypeAlias, TypedDict, override, runtime_checkable +import httpx import pydantic from httpx import URL, Proxy, Timeout, Response, BaseTransport, AsyncBaseTransport @@ -264,11 +258,6 @@ class RequestOptions(TypedDict, total=False): idempotency_key: str -# Sentinel class used when the response type is an object with an unknown schema -class UnknownResponse: - ... - - # Sentinel class used until PEP 0661 is accepted class NotGiven: """ @@ -345,7 +334,17 @@ def get(self, __key: str) -> str | None: ResponseT = TypeVar( "ResponseT", - bound="Union[str, None, BaseModel, List[Any], Dict[str, Any], Response, UnknownResponse, ModelBuilderProtocol, BinaryResponseContent]", + bound=Union[ + object, + str, + None, + "BaseModel", + List[Any], + Dict[str, Any], + Response, + ModelBuilderProtocol, + BinaryResponseContent, + ], ) StrBytesIntFloat = Union[str, bytes, int, float] @@ -369,3 +368,7 @@ class InheritsGeneric(Protocol): class _GenericAlias(Protocol): __origin__: type[object] + + +class HttpxSendArgs(TypedDict, total=False): + auth: httpx.Auth diff --git a/src/openai/_utils/__init__.py b/src/openai/_utils/__init__.py index a43201d3c7..2dcfc122f1 100644 --- a/src/openai/_utils/__init__.py +++ b/src/openai/_utils/__init__.py @@ -1,40 +1,45 @@ from ._proxy import LazyProxy as LazyProxy -from ._utils import flatten as flatten -from ._utils import is_dict as is_dict -from ._utils import is_list as is_list -from ._utils import is_given as is_given -from ._utils import is_tuple as is_tuple -from ._utils import is_mapping as is_mapping -from ._utils import is_tuple_t as is_tuple_t -from ._utils import parse_date as parse_date -from ._utils import is_sequence as is_sequence -from ._utils import coerce_float as coerce_float -from ._utils import is_mapping_t as is_mapping_t -from ._utils import removeprefix as removeprefix -from ._utils import removesuffix as removesuffix -from ._utils import extract_files as extract_files -from ._utils import is_sequence_t as is_sequence_t -from ._utils import required_args as required_args -from ._utils import coerce_boolean as coerce_boolean -from ._utils import coerce_integer as coerce_integer -from ._utils import file_from_path as file_from_path -from ._utils import parse_datetime as parse_datetime -from ._utils import strip_not_given as strip_not_given -from ._utils import deepcopy_minimal as deepcopy_minimal -from ._utils import get_async_library as get_async_library -from ._utils import maybe_coerce_float as maybe_coerce_float -from ._utils import get_required_header as get_required_header -from ._utils import maybe_coerce_boolean as maybe_coerce_boolean -from ._utils import maybe_coerce_integer as maybe_coerce_integer -from ._typing import is_list_type as is_list_type -from ._typing import is_union_type as is_union_type -from ._typing import extract_type_arg as extract_type_arg -from ._typing import is_required_type as is_required_type -from ._typing import is_annotated_type as is_annotated_type -from ._typing import strip_annotated_type as strip_annotated_type -from ._typing import extract_type_var_from_base as extract_type_var_from_base -from ._streams import consume_sync_iterator as consume_sync_iterator -from ._streams import consume_async_iterator as consume_async_iterator -from ._transform import PropertyInfo as PropertyInfo -from ._transform import transform as transform -from ._transform import maybe_transform as maybe_transform +from ._utils import ( + flatten as flatten, + is_dict as is_dict, + is_list as is_list, + is_given as is_given, + is_tuple as is_tuple, + is_mapping as is_mapping, + is_tuple_t as is_tuple_t, + parse_date as parse_date, + is_sequence as is_sequence, + coerce_float as coerce_float, + is_mapping_t as is_mapping_t, + removeprefix as removeprefix, + removesuffix as removesuffix, + extract_files as extract_files, + is_sequence_t as is_sequence_t, + required_args as required_args, + coerce_boolean as coerce_boolean, + coerce_integer as coerce_integer, + file_from_path as file_from_path, + parse_datetime as parse_datetime, + strip_not_given as strip_not_given, + deepcopy_minimal as deepcopy_minimal, + get_async_library as get_async_library, + maybe_coerce_float as maybe_coerce_float, + get_required_header as get_required_header, + maybe_coerce_boolean as maybe_coerce_boolean, + maybe_coerce_integer as maybe_coerce_integer, +) +from ._typing import ( + is_list_type as is_list_type, + is_union_type as is_union_type, + extract_type_arg as extract_type_arg, + is_required_type as is_required_type, + is_annotated_type as is_annotated_type, + strip_annotated_type as strip_annotated_type, + extract_type_var_from_base as extract_type_var_from_base, +) +from ._streams import consume_sync_iterator as consume_sync_iterator, consume_async_iterator as consume_async_iterator +from ._transform import ( + PropertyInfo as PropertyInfo, + transform as transform, + maybe_transform as maybe_transform, +) diff --git a/src/openai/_utils/_transform.py b/src/openai/_utils/_transform.py index 342b52416a..3a1c14969b 100644 --- a/src/openai/_utils/_transform.py +++ b/src/openai/_utils/_transform.py @@ -6,7 +6,10 @@ import pydantic -from ._utils import is_list, is_mapping +from ._utils import ( + is_list, + is_mapping, +) from ._typing import ( is_list_type, is_union_type, diff --git a/src/openai/_utils/_utils.py b/src/openai/_utils/_utils.py index cc624b0ce1..1c5c21a8ea 100644 --- a/src/openai/_utils/_utils.py +++ b/src/openai/_utils/_utils.py @@ -21,8 +21,7 @@ import sniffio from .._types import Headers, NotGiven, FileTypes, NotGivenOr, HeadersLike -from .._compat import parse_date as parse_date -from .._compat import parse_datetime as parse_datetime +from .._compat import parse_date as parse_date, parse_datetime as parse_datetime _T = TypeVar("_T") _TupleT = TypeVar("_TupleT", bound=Tuple[object, ...]) diff --git a/src/openai/_version.py b/src/openai/_version.py index 9ab131d176..aa1cd4305c 100644 --- a/src/openai/_version.py +++ b/src/openai/_version.py @@ -1,4 +1,4 @@ # File generated from our OpenAPI spec by Stainless. __title__ = "openai" -__version__ = "1.6.1" # x-release-please-version +__version__ = "1.7.0" # x-release-please-version diff --git a/src/openai/lib/.keep b/src/openai/lib/.keep new file mode 100644 index 0000000000..5e2c99fdbe --- /dev/null +++ b/src/openai/lib/.keep @@ -0,0 +1,4 @@ +File generated from our OpenAPI spec by Stainless. + +This directory can be used to store custom files to expand the SDK. +It is ignored by Stainless code generation and its content (other than this keep file) won't be touched. \ No newline at end of file diff --git a/src/openai/pagination.py b/src/openai/pagination.py index d47deb17be..f7527753e1 100644 --- a/src/openai/pagination.py +++ b/src/openai/pagination.py @@ -1,27 +1,28 @@ # File generated from our OpenAPI spec by Stainless. -from typing import Any, List, Generic, Optional, cast +from typing import Any, List, Generic, TypeVar, Optional, cast from typing_extensions import Protocol, override, runtime_checkable -from ._types import ModelT from ._base_client import BasePage, PageInfo, BaseSyncPage, BaseAsyncPage __all__ = ["SyncPage", "AsyncPage", "SyncCursorPage", "AsyncCursorPage"] +_T = TypeVar("_T") + @runtime_checkable class CursorPageItem(Protocol): id: Optional[str] -class SyncPage(BaseSyncPage[ModelT], BasePage[ModelT], Generic[ModelT]): +class SyncPage(BaseSyncPage[_T], BasePage[_T], Generic[_T]): """Note: no pagination actually occurs yet, this is for forwards-compatibility.""" - data: List[ModelT] + data: List[_T] object: str @override - def _get_page_items(self) -> List[ModelT]: + def _get_page_items(self) -> List[_T]: data = self.data if not data: return [] @@ -36,14 +37,14 @@ def next_page_info(self) -> None: return None -class AsyncPage(BaseAsyncPage[ModelT], BasePage[ModelT], Generic[ModelT]): +class AsyncPage(BaseAsyncPage[_T], BasePage[_T], Generic[_T]): """Note: no pagination actually occurs yet, this is for forwards-compatibility.""" - data: List[ModelT] + data: List[_T] object: str @override - def _get_page_items(self) -> List[ModelT]: + def _get_page_items(self) -> List[_T]: data = self.data if not data: return [] @@ -58,11 +59,11 @@ def next_page_info(self) -> None: return None -class SyncCursorPage(BaseSyncPage[ModelT], BasePage[ModelT], Generic[ModelT]): - data: List[ModelT] +class SyncCursorPage(BaseSyncPage[_T], BasePage[_T], Generic[_T]): + data: List[_T] @override - def _get_page_items(self) -> List[ModelT]: + def _get_page_items(self) -> List[_T]: data = self.data if not data: return [] @@ -82,11 +83,11 @@ def next_page_info(self) -> Optional[PageInfo]: return PageInfo(params={"after": item.id}) -class AsyncCursorPage(BaseAsyncPage[ModelT], BasePage[ModelT], Generic[ModelT]): - data: List[ModelT] +class AsyncCursorPage(BaseAsyncPage[_T], BasePage[_T], Generic[_T]): + data: List[_T] @override - def _get_page_items(self) -> List[ModelT]: + def _get_page_items(self) -> List[_T]: data = self.data if not data: return [] diff --git a/src/openai/resources/__init__.py b/src/openai/resources/__init__.py index e0f4f08d5c..2cdbeb6ae1 100644 --- a/src/openai/resources/__init__.py +++ b/src/openai/resources/__init__.py @@ -5,48 +5,13 @@ from .audio import Audio, AsyncAudio, AudioWithRawResponse, AsyncAudioWithRawResponse from .edits import Edits, AsyncEdits, EditsWithRawResponse, AsyncEditsWithRawResponse from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse -from .images import ( - Images, - AsyncImages, - ImagesWithRawResponse, - AsyncImagesWithRawResponse, -) -from .models import ( - Models, - AsyncModels, - ModelsWithRawResponse, - AsyncModelsWithRawResponse, -) -from .embeddings import ( - Embeddings, - AsyncEmbeddings, - EmbeddingsWithRawResponse, - AsyncEmbeddingsWithRawResponse, -) -from .fine_tunes import ( - FineTunes, - AsyncFineTunes, - FineTunesWithRawResponse, - AsyncFineTunesWithRawResponse, -) -from .completions import ( - Completions, - AsyncCompletions, - CompletionsWithRawResponse, - AsyncCompletionsWithRawResponse, -) -from .fine_tuning import ( - FineTuning, - AsyncFineTuning, - FineTuningWithRawResponse, - AsyncFineTuningWithRawResponse, -) -from .moderations import ( - Moderations, - AsyncModerations, - ModerationsWithRawResponse, - AsyncModerationsWithRawResponse, -) +from .images import Images, AsyncImages, ImagesWithRawResponse, AsyncImagesWithRawResponse +from .models import Models, AsyncModels, ModelsWithRawResponse, AsyncModelsWithRawResponse +from .embeddings import Embeddings, AsyncEmbeddings, EmbeddingsWithRawResponse, AsyncEmbeddingsWithRawResponse +from .fine_tunes import FineTunes, AsyncFineTunes, FineTunesWithRawResponse, AsyncFineTunesWithRawResponse +from .completions import Completions, AsyncCompletions, CompletionsWithRawResponse, AsyncCompletionsWithRawResponse +from .fine_tuning import FineTuning, AsyncFineTuning, FineTuningWithRawResponse, AsyncFineTuningWithRawResponse +from .moderations import Moderations, AsyncModerations, ModerationsWithRawResponse, AsyncModerationsWithRawResponse __all__ = [ "Completions", diff --git a/src/openai/resources/audio/__init__.py b/src/openai/resources/audio/__init__.py index 76547b5f34..b6ff4322d4 100644 --- a/src/openai/resources/audio/__init__.py +++ b/src/openai/resources/audio/__init__.py @@ -1,18 +1,8 @@ # File generated from our OpenAPI spec by Stainless. from .audio import Audio, AsyncAudio, AudioWithRawResponse, AsyncAudioWithRawResponse -from .speech import ( - Speech, - AsyncSpeech, - SpeechWithRawResponse, - AsyncSpeechWithRawResponse, -) -from .translations import ( - Translations, - AsyncTranslations, - TranslationsWithRawResponse, - AsyncTranslationsWithRawResponse, -) +from .speech import Speech, AsyncSpeech, SpeechWithRawResponse, AsyncSpeechWithRawResponse +from .translations import Translations, AsyncTranslations, TranslationsWithRawResponse, AsyncTranslationsWithRawResponse from .transcriptions import ( Transcriptions, AsyncTranscriptions, diff --git a/src/openai/resources/audio/audio.py b/src/openai/resources/audio/audio.py index 6f7226ee59..4e3ca0ed4f 100644 --- a/src/openai/resources/audio/audio.py +++ b/src/openai/resources/audio/audio.py @@ -2,21 +2,10 @@ from __future__ import annotations -from typing import TYPE_CHECKING - -from .speech import ( - Speech, - AsyncSpeech, - SpeechWithRawResponse, - AsyncSpeechWithRawResponse, -) +from .speech import Speech, AsyncSpeech, SpeechWithRawResponse, AsyncSpeechWithRawResponse +from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource -from .translations import ( - Translations, - AsyncTranslations, - TranslationsWithRawResponse, - AsyncTranslationsWithRawResponse, -) +from .translations import Translations, AsyncTranslations, TranslationsWithRawResponse, AsyncTranslationsWithRawResponse from .transcriptions import ( Transcriptions, AsyncTranscriptions, @@ -24,38 +13,43 @@ AsyncTranscriptionsWithRawResponse, ) -if TYPE_CHECKING: - from ..._client import OpenAI, AsyncOpenAI - __all__ = ["Audio", "AsyncAudio"] class Audio(SyncAPIResource): - transcriptions: Transcriptions - translations: Translations - speech: Speech - with_raw_response: AudioWithRawResponse + @cached_property + def transcriptions(self) -> Transcriptions: + return Transcriptions(self._client) + + @cached_property + def translations(self) -> Translations: + return Translations(self._client) - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.transcriptions = Transcriptions(client) - self.translations = Translations(client) - self.speech = Speech(client) - self.with_raw_response = AudioWithRawResponse(self) + @cached_property + def speech(self) -> Speech: + return Speech(self._client) + + @cached_property + def with_raw_response(self) -> AudioWithRawResponse: + return AudioWithRawResponse(self) class AsyncAudio(AsyncAPIResource): - transcriptions: AsyncTranscriptions - translations: AsyncTranslations - speech: AsyncSpeech - with_raw_response: AsyncAudioWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.transcriptions = AsyncTranscriptions(client) - self.translations = AsyncTranslations(client) - self.speech = AsyncSpeech(client) - self.with_raw_response = AsyncAudioWithRawResponse(self) + @cached_property + def transcriptions(self) -> AsyncTranscriptions: + return AsyncTranscriptions(self._client) + + @cached_property + def translations(self) -> AsyncTranslations: + return AsyncTranslations(self._client) + + @cached_property + def speech(self) -> AsyncSpeech: + return AsyncSpeech(self._client) + + @cached_property + def with_raw_response(self) -> AsyncAudioWithRawResponse: + return AsyncAudioWithRawResponse(self) class AudioWithRawResponse: diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py index aadb00bd02..b7cd3733a9 100644 --- a/src/openai/resources/audio/speech.py +++ b/src/openai/resources/audio/speech.py @@ -2,30 +2,29 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Union +from typing import Union from typing_extensions import Literal import httpx from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ..._utils import maybe_transform +from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ...types.audio import speech_create_params -from ..._base_client import HttpxBinaryResponseContent, make_request_options - -if TYPE_CHECKING: - from ..._client import OpenAI, AsyncOpenAI +from ..._base_client import ( + HttpxBinaryResponseContent, + make_request_options, +) __all__ = ["Speech", "AsyncSpeech"] class Speech(SyncAPIResource): - with_raw_response: SpeechWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = SpeechWithRawResponse(self) + @cached_property + def with_raw_response(self) -> SpeechWithRawResponse: + return SpeechWithRawResponse(self) def create( self, @@ -90,11 +89,9 @@ def create( class AsyncSpeech(AsyncAPIResource): - with_raw_response: AsyncSpeechWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncSpeechWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncSpeechWithRawResponse: + return AsyncSpeechWithRawResponse(self) async def create( self, diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index d2b4452411..7d7441a9f6 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -2,30 +2,28 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Union, Mapping, cast +from typing import Union, Mapping, cast from typing_extensions import Literal import httpx from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from ..._utils import extract_files, maybe_transform, deepcopy_minimal +from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ...types.audio import Transcription, transcription_create_params -from ..._base_client import make_request_options - -if TYPE_CHECKING: - from ..._client import OpenAI, AsyncOpenAI +from ..._base_client import ( + make_request_options, +) __all__ = ["Transcriptions", "AsyncTranscriptions"] class Transcriptions(SyncAPIResource): - with_raw_response: TranscriptionsWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = TranscriptionsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> TranscriptionsWithRawResponse: + return TranscriptionsWithRawResponse(self) def create( self, @@ -108,11 +106,9 @@ def create( class AsyncTranscriptions(AsyncAPIResource): - with_raw_response: AsyncTranscriptionsWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncTranscriptionsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncTranscriptionsWithRawResponse: + return AsyncTranscriptionsWithRawResponse(self) async def create( self, diff --git a/src/openai/resources/audio/translations.py b/src/openai/resources/audio/translations.py index fe7f7f2a40..7f5f65b6c8 100644 --- a/src/openai/resources/audio/translations.py +++ b/src/openai/resources/audio/translations.py @@ -2,30 +2,28 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Union, Mapping, cast +from typing import Union, Mapping, cast from typing_extensions import Literal import httpx from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from ..._utils import extract_files, maybe_transform, deepcopy_minimal +from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ...types.audio import Translation, translation_create_params -from ..._base_client import make_request_options - -if TYPE_CHECKING: - from ..._client import OpenAI, AsyncOpenAI +from ..._base_client import ( + make_request_options, +) __all__ = ["Translations", "AsyncTranslations"] class Translations(SyncAPIResource): - with_raw_response: TranslationsWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = TranslationsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> TranslationsWithRawResponse: + return TranslationsWithRawResponse(self) def create( self, @@ -101,11 +99,9 @@ def create( class AsyncTranslations(AsyncAPIResource): - with_raw_response: AsyncTranslationsWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncTranslationsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncTranslationsWithRawResponse: + return AsyncTranslationsWithRawResponse(self) async def create( self, diff --git a/src/openai/resources/beta/__init__.py b/src/openai/resources/beta/__init__.py index 55ad243cca..561f8bef60 100644 --- a/src/openai/resources/beta/__init__.py +++ b/src/openai/resources/beta/__init__.py @@ -1,18 +1,8 @@ # File generated from our OpenAPI spec by Stainless. from .beta import Beta, AsyncBeta, BetaWithRawResponse, AsyncBetaWithRawResponse -from .threads import ( - Threads, - AsyncThreads, - ThreadsWithRawResponse, - AsyncThreadsWithRawResponse, -) -from .assistants import ( - Assistants, - AsyncAssistants, - AssistantsWithRawResponse, - AsyncAssistantsWithRawResponse, -) +from .threads import Threads, AsyncThreads, ThreadsWithRawResponse, AsyncThreadsWithRawResponse +from .assistants import Assistants, AsyncAssistants, AssistantsWithRawResponse, AsyncAssistantsWithRawResponse __all__ = [ "Assistants", diff --git a/src/openai/resources/beta/assistants/__init__.py b/src/openai/resources/beta/assistants/__init__.py index 6efb0b21ec..205b2cf0f5 100644 --- a/src/openai/resources/beta/assistants/__init__.py +++ b/src/openai/resources/beta/assistants/__init__.py @@ -1,12 +1,7 @@ # File generated from our OpenAPI spec by Stainless. from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse -from .assistants import ( - Assistants, - AsyncAssistants, - AssistantsWithRawResponse, - AsyncAssistantsWithRawResponse, -) +from .assistants import Assistants, AsyncAssistants, AssistantsWithRawResponse, AsyncAssistantsWithRawResponse __all__ = [ "Files", diff --git a/src/openai/resources/beta/assistants/assistants.py b/src/openai/resources/beta/assistants/assistants.py index efa711ecf4..0ae054795d 100644 --- a/src/openai/resources/beta/assistants/assistants.py +++ b/src/openai/resources/beta/assistants/assistants.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, List, Optional +from typing import List, Optional from typing_extensions import Literal import httpx @@ -10,6 +10,7 @@ from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ...._utils import maybe_transform +from ...._compat import cached_property from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ....pagination import SyncCursorPage, AsyncCursorPage @@ -20,22 +21,22 @@ assistant_create_params, assistant_update_params, ) -from ...._base_client import AsyncPaginator, make_request_options - -if TYPE_CHECKING: - from ...._client import OpenAI, AsyncOpenAI +from ...._base_client import ( + AsyncPaginator, + make_request_options, +) __all__ = ["Assistants", "AsyncAssistants"] class Assistants(SyncAPIResource): - files: Files - with_raw_response: AssistantsWithRawResponse + @cached_property + def files(self) -> Files: + return Files(self._client) - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.files = Files(client) - self.with_raw_response = AssistantsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AssistantsWithRawResponse: + return AssistantsWithRawResponse(self) def create( self, @@ -172,7 +173,7 @@ def update( file_ids: A list of [File](https://platform.openai.com/docs/api-reference/files) IDs attached to this assistant. There can be a maximum of 20 files attached to the assistant. Files are ordered by their creation date in ascending order. If a - file was previosuly attached to the list but does not show up in the list, it + file was previously attached to the list but does not show up in the list, it will be deleted from the assistant. instructions: The system instructions that the assistant uses. The maximum length is 32768 @@ -322,13 +323,13 @@ def delete( class AsyncAssistants(AsyncAPIResource): - files: AsyncFiles - with_raw_response: AsyncAssistantsWithRawResponse + @cached_property + def files(self) -> AsyncFiles: + return AsyncFiles(self._client) - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.files = AsyncFiles(client) - self.with_raw_response = AsyncAssistantsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncAssistantsWithRawResponse: + return AsyncAssistantsWithRawResponse(self) async def create( self, @@ -465,7 +466,7 @@ async def update( file_ids: A list of [File](https://platform.openai.com/docs/api-reference/files) IDs attached to this assistant. There can be a maximum of 20 files attached to the assistant. Files are ordered by their creation date in ascending order. If a - file was previosuly attached to the list but does not show up in the list, it + file was previously attached to the list but does not show up in the list, it will be deleted from the assistant. instructions: The system instructions that the assistant uses. The maximum length is 32768 diff --git a/src/openai/resources/beta/assistants/files.py b/src/openai/resources/beta/assistants/files.py index 5ac5897ca3..0624e562f8 100644 --- a/src/openai/resources/beta/assistants/files.py +++ b/src/openai/resources/beta/assistants/files.py @@ -2,36 +2,29 @@ from __future__ import annotations -from typing import TYPE_CHECKING from typing_extensions import Literal import httpx from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ...._utils import maybe_transform +from ...._compat import cached_property from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ....pagination import SyncCursorPage, AsyncCursorPage -from ...._base_client import AsyncPaginator, make_request_options -from ....types.beta.assistants import ( - AssistantFile, - FileDeleteResponse, - file_list_params, - file_create_params, +from ...._base_client import ( + AsyncPaginator, + make_request_options, ) - -if TYPE_CHECKING: - from ...._client import OpenAI, AsyncOpenAI +from ....types.beta.assistants import AssistantFile, FileDeleteResponse, file_list_params, file_create_params __all__ = ["Files", "AsyncFiles"] class Files(SyncAPIResource): - with_raw_response: FilesWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = FilesWithRawResponse(self) + @cached_property + def with_raw_response(self) -> FilesWithRawResponse: + return FilesWithRawResponse(self) def create( self, @@ -206,11 +199,9 @@ def delete( class AsyncFiles(AsyncAPIResource): - with_raw_response: AsyncFilesWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncFilesWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncFilesWithRawResponse: + return AsyncFilesWithRawResponse(self) async def create( self, diff --git a/src/openai/resources/beta/beta.py b/src/openai/resources/beta/beta.py index b552561763..d87406ac9d 100644 --- a/src/openai/resources/beta/beta.py +++ b/src/openai/resources/beta/beta.py @@ -2,50 +2,42 @@ from __future__ import annotations -from typing import TYPE_CHECKING - -from .threads import ( - Threads, - AsyncThreads, - ThreadsWithRawResponse, - AsyncThreadsWithRawResponse, -) -from .assistants import ( - Assistants, - AsyncAssistants, - AssistantsWithRawResponse, - AsyncAssistantsWithRawResponse, -) +from .threads import Threads, AsyncThreads, ThreadsWithRawResponse, AsyncThreadsWithRawResponse +from ..._compat import cached_property +from .assistants import Assistants, AsyncAssistants, AssistantsWithRawResponse, AsyncAssistantsWithRawResponse from ..._resource import SyncAPIResource, AsyncAPIResource - -if TYPE_CHECKING: - from ..._client import OpenAI, AsyncOpenAI +from .threads.threads import Threads, AsyncThreads +from .assistants.assistants import Assistants, AsyncAssistants __all__ = ["Beta", "AsyncBeta"] class Beta(SyncAPIResource): - assistants: Assistants - threads: Threads - with_raw_response: BetaWithRawResponse + @cached_property + def assistants(self) -> Assistants: + return Assistants(self._client) + + @cached_property + def threads(self) -> Threads: + return Threads(self._client) - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.assistants = Assistants(client) - self.threads = Threads(client) - self.with_raw_response = BetaWithRawResponse(self) + @cached_property + def with_raw_response(self) -> BetaWithRawResponse: + return BetaWithRawResponse(self) class AsyncBeta(AsyncAPIResource): - assistants: AsyncAssistants - threads: AsyncThreads - with_raw_response: AsyncBetaWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.assistants = AsyncAssistants(client) - self.threads = AsyncThreads(client) - self.with_raw_response = AsyncBetaWithRawResponse(self) + @cached_property + def assistants(self) -> AsyncAssistants: + return AsyncAssistants(self._client) + + @cached_property + def threads(self) -> AsyncThreads: + return AsyncThreads(self._client) + + @cached_property + def with_raw_response(self) -> AsyncBetaWithRawResponse: + return AsyncBetaWithRawResponse(self) class BetaWithRawResponse: diff --git a/src/openai/resources/beta/threads/__init__.py b/src/openai/resources/beta/threads/__init__.py index b9aaada465..fe7c5e5a20 100644 --- a/src/openai/resources/beta/threads/__init__.py +++ b/src/openai/resources/beta/threads/__init__.py @@ -1,18 +1,8 @@ # File generated from our OpenAPI spec by Stainless. from .runs import Runs, AsyncRuns, RunsWithRawResponse, AsyncRunsWithRawResponse -from .threads import ( - Threads, - AsyncThreads, - ThreadsWithRawResponse, - AsyncThreadsWithRawResponse, -) -from .messages import ( - Messages, - AsyncMessages, - MessagesWithRawResponse, - AsyncMessagesWithRawResponse, -) +from .threads import Threads, AsyncThreads, ThreadsWithRawResponse, AsyncThreadsWithRawResponse +from .messages import Messages, AsyncMessages, MessagesWithRawResponse, AsyncMessagesWithRawResponse __all__ = [ "Runs", diff --git a/src/openai/resources/beta/threads/messages/__init__.py b/src/openai/resources/beta/threads/messages/__init__.py index d8d4ce448c..cef618ed14 100644 --- a/src/openai/resources/beta/threads/messages/__init__.py +++ b/src/openai/resources/beta/threads/messages/__init__.py @@ -1,12 +1,7 @@ # File generated from our OpenAPI spec by Stainless. from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse -from .messages import ( - Messages, - AsyncMessages, - MessagesWithRawResponse, - AsyncMessagesWithRawResponse, -) +from .messages import Messages, AsyncMessages, MessagesWithRawResponse, AsyncMessagesWithRawResponse __all__ = [ "Files", diff --git a/src/openai/resources/beta/threads/messages/files.py b/src/openai/resources/beta/threads/messages/files.py index e028a6fda7..4b95b200eb 100644 --- a/src/openai/resources/beta/threads/messages/files.py +++ b/src/openai/resources/beta/threads/messages/files.py @@ -2,31 +2,29 @@ from __future__ import annotations -from typing import TYPE_CHECKING from typing_extensions import Literal import httpx from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ....._utils import maybe_transform +from ....._compat import cached_property from ....._resource import SyncAPIResource, AsyncAPIResource from ....._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .....pagination import SyncCursorPage, AsyncCursorPage -from ....._base_client import AsyncPaginator, make_request_options +from ....._base_client import ( + AsyncPaginator, + make_request_options, +) from .....types.beta.threads.messages import MessageFile, file_list_params -if TYPE_CHECKING: - from ....._client import OpenAI, AsyncOpenAI - __all__ = ["Files", "AsyncFiles"] class Files(SyncAPIResource): - with_raw_response: FilesWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = FilesWithRawResponse(self) + @cached_property + def with_raw_response(self) -> FilesWithRawResponse: + return FilesWithRawResponse(self) def retrieve( self, @@ -131,11 +129,9 @@ def list( class AsyncFiles(AsyncAPIResource): - with_raw_response: AsyncFilesWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncFilesWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncFilesWithRawResponse: + return AsyncFilesWithRawResponse(self) async def retrieve( self, diff --git a/src/openai/resources/beta/threads/messages/messages.py b/src/openai/resources/beta/threads/messages/messages.py index 30ae072512..146f665624 100644 --- a/src/openai/resources/beta/threads/messages/messages.py +++ b/src/openai/resources/beta/threads/messages/messages.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, List, Optional +from typing import List, Optional from typing_extensions import Literal import httpx @@ -10,31 +10,27 @@ from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ....._utils import maybe_transform +from ....._compat import cached_property from ....._resource import SyncAPIResource, AsyncAPIResource from ....._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .....pagination import SyncCursorPage, AsyncCursorPage -from ....._base_client import AsyncPaginator, make_request_options -from .....types.beta.threads import ( - ThreadMessage, - message_list_params, - message_create_params, - message_update_params, +from ....._base_client import ( + AsyncPaginator, + make_request_options, ) - -if TYPE_CHECKING: - from ....._client import OpenAI, AsyncOpenAI +from .....types.beta.threads import ThreadMessage, message_list_params, message_create_params, message_update_params __all__ = ["Messages", "AsyncMessages"] class Messages(SyncAPIResource): - files: Files - with_raw_response: MessagesWithRawResponse + @cached_property + def files(self) -> Files: + return Files(self._client) - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.files = Files(client) - self.with_raw_response = MessagesWithRawResponse(self) + @cached_property + def with_raw_response(self) -> MessagesWithRawResponse: + return MessagesWithRawResponse(self) def create( self, @@ -236,13 +232,13 @@ def list( class AsyncMessages(AsyncAPIResource): - files: AsyncFiles - with_raw_response: AsyncMessagesWithRawResponse + @cached_property + def files(self) -> AsyncFiles: + return AsyncFiles(self._client) - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.files = AsyncFiles(client) - self.with_raw_response = AsyncMessagesWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncMessagesWithRawResponse: + return AsyncMessagesWithRawResponse(self) async def create( self, diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index aea3b8cefc..87e62eb362 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, List, Optional +from typing import List, Optional from typing_extensions import Literal import httpx @@ -10,10 +10,14 @@ from .steps import Steps, AsyncSteps, StepsWithRawResponse, AsyncStepsWithRawResponse from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ....._utils import maybe_transform +from ....._compat import cached_property from ....._resource import SyncAPIResource, AsyncAPIResource from ....._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .....pagination import SyncCursorPage, AsyncCursorPage -from ....._base_client import AsyncPaginator, make_request_options +from ....._base_client import ( + AsyncPaginator, + make_request_options, +) from .....types.beta.threads import ( Run, run_list_params, @@ -22,20 +26,17 @@ run_submit_tool_outputs_params, ) -if TYPE_CHECKING: - from ....._client import OpenAI, AsyncOpenAI - __all__ = ["Runs", "AsyncRuns"] class Runs(SyncAPIResource): - steps: Steps - with_raw_response: RunsWithRawResponse + @cached_property + def steps(self) -> Steps: + return Steps(self._client) - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.steps = Steps(client) - self.with_raw_response = RunsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> RunsWithRawResponse: + return RunsWithRawResponse(self) def create( self, @@ -326,13 +327,13 @@ def submit_tool_outputs( class AsyncRuns(AsyncAPIResource): - steps: AsyncSteps - with_raw_response: AsyncRunsWithRawResponse + @cached_property + def steps(self) -> AsyncSteps: + return AsyncSteps(self._client) - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.steps = AsyncSteps(client) - self.with_raw_response = AsyncRunsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncRunsWithRawResponse: + return AsyncRunsWithRawResponse(self) async def create( self, diff --git a/src/openai/resources/beta/threads/runs/steps.py b/src/openai/resources/beta/threads/runs/steps.py index 4fcc87a0ff..439926a412 100644 --- a/src/openai/resources/beta/threads/runs/steps.py +++ b/src/openai/resources/beta/threads/runs/steps.py @@ -2,31 +2,29 @@ from __future__ import annotations -from typing import TYPE_CHECKING from typing_extensions import Literal import httpx from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ....._utils import maybe_transform +from ....._compat import cached_property from ....._resource import SyncAPIResource, AsyncAPIResource from ....._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .....pagination import SyncCursorPage, AsyncCursorPage -from ....._base_client import AsyncPaginator, make_request_options +from ....._base_client import ( + AsyncPaginator, + make_request_options, +) from .....types.beta.threads.runs import RunStep, step_list_params -if TYPE_CHECKING: - from ....._client import OpenAI, AsyncOpenAI - __all__ = ["Steps", "AsyncSteps"] class Steps(SyncAPIResource): - with_raw_response: StepsWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = StepsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> StepsWithRawResponse: + return StepsWithRawResponse(self) def retrieve( self, @@ -130,11 +128,9 @@ def list( class AsyncSteps(AsyncAPIResource): - with_raw_response: AsyncStepsWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncStepsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncStepsWithRawResponse: + return AsyncStepsWithRawResponse(self) async def retrieve( self, diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 9469fc0513..0ae409bb24 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -2,19 +2,16 @@ from __future__ import annotations -from typing import TYPE_CHECKING, List, Optional +from typing import List, Optional import httpx from .runs import Runs, AsyncRuns, RunsWithRawResponse, AsyncRunsWithRawResponse -from .messages import ( - Messages, - AsyncMessages, - MessagesWithRawResponse, - AsyncMessagesWithRawResponse, -) +from .messages import Messages, AsyncMessages, MessagesWithRawResponse, AsyncMessagesWithRawResponse from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ...._utils import maybe_transform +from .runs.runs import Runs, AsyncRuns +from ...._compat import cached_property from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ....types.beta import ( @@ -24,25 +21,27 @@ thread_update_params, thread_create_and_run_params, ) -from ...._base_client import make_request_options +from ...._base_client import ( + make_request_options, +) +from .messages.messages import Messages, AsyncMessages from ....types.beta.threads import Run -if TYPE_CHECKING: - from ...._client import OpenAI, AsyncOpenAI - __all__ = ["Threads", "AsyncThreads"] class Threads(SyncAPIResource): - runs: Runs - messages: Messages - with_raw_response: ThreadsWithRawResponse + @cached_property + def runs(self) -> Runs: + return Runs(self._client) - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.runs = Runs(client) - self.messages = Messages(client) - self.with_raw_response = ThreadsWithRawResponse(self) + @cached_property + def messages(self) -> Messages: + return Messages(self._client) + + @cached_property + def with_raw_response(self) -> ThreadsWithRawResponse: + return ThreadsWithRawResponse(self) def create( self, @@ -267,15 +266,17 @@ def create_and_run( class AsyncThreads(AsyncAPIResource): - runs: AsyncRuns - messages: AsyncMessages - with_raw_response: AsyncThreadsWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.runs = AsyncRuns(client) - self.messages = AsyncMessages(client) - self.with_raw_response = AsyncThreadsWithRawResponse(self) + @cached_property + def runs(self) -> AsyncRuns: + return AsyncRuns(self._client) + + @cached_property + def messages(self) -> AsyncMessages: + return AsyncMessages(self._client) + + @cached_property + def with_raw_response(self) -> AsyncThreadsWithRawResponse: + return AsyncThreadsWithRawResponse(self) async def create( self, diff --git a/src/openai/resources/chat/__init__.py b/src/openai/resources/chat/__init__.py index 2e56c0cbfa..85b246509e 100644 --- a/src/openai/resources/chat/__init__.py +++ b/src/openai/resources/chat/__init__.py @@ -1,12 +1,7 @@ # File generated from our OpenAPI spec by Stainless. from .chat import Chat, AsyncChat, ChatWithRawResponse, AsyncChatWithRawResponse -from .completions import ( - Completions, - AsyncCompletions, - CompletionsWithRawResponse, - AsyncCompletionsWithRawResponse, -) +from .completions import Completions, AsyncCompletions, CompletionsWithRawResponse, AsyncCompletionsWithRawResponse __all__ = [ "Completions", diff --git a/src/openai/resources/chat/chat.py b/src/openai/resources/chat/chat.py index 3847b20512..000520de23 100644 --- a/src/openai/resources/chat/chat.py +++ b/src/openai/resources/chat/chat.py @@ -2,40 +2,31 @@ from __future__ import annotations -from typing import TYPE_CHECKING - +from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource -from .completions import ( - Completions, - AsyncCompletions, - CompletionsWithRawResponse, - AsyncCompletionsWithRawResponse, -) - -if TYPE_CHECKING: - from ..._client import OpenAI, AsyncOpenAI +from .completions import Completions, AsyncCompletions, CompletionsWithRawResponse, AsyncCompletionsWithRawResponse __all__ = ["Chat", "AsyncChat"] class Chat(SyncAPIResource): - completions: Completions - with_raw_response: ChatWithRawResponse + @cached_property + def completions(self) -> Completions: + return Completions(self._client) - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.completions = Completions(client) - self.with_raw_response = ChatWithRawResponse(self) + @cached_property + def with_raw_response(self) -> ChatWithRawResponse: + return ChatWithRawResponse(self) class AsyncChat(AsyncAPIResource): - completions: AsyncCompletions - with_raw_response: AsyncChatWithRawResponse + @cached_property + def completions(self) -> AsyncCompletions: + return AsyncCompletions(self._client) - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.completions = AsyncCompletions(client) - self.with_raw_response = AsyncChatWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncChatWithRawResponse: + return AsyncChatWithRawResponse(self) class ChatWithRawResponse: diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index 5aac234227..b047c1d2a0 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -2,13 +2,14 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Dict, List, Union, Optional, overload +from typing import Dict, List, Union, Optional, overload from typing_extensions import Literal import httpx from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ..._utils import required_args, maybe_transform +from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ..._streaming import Stream, AsyncStream @@ -20,20 +21,17 @@ ChatCompletionToolChoiceOptionParam, completion_create_params, ) -from ..._base_client import make_request_options - -if TYPE_CHECKING: - from ..._client import OpenAI, AsyncOpenAI +from ..._base_client import ( + make_request_options, +) __all__ = ["Completions", "AsyncCompletions"] class Completions(SyncAPIResource): - with_raw_response: CompletionsWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = CompletionsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> CompletionsWithRawResponse: + return CompletionsWithRawResponse(self) @overload def create( @@ -679,11 +677,9 @@ def create( class AsyncCompletions(AsyncAPIResource): - with_raw_response: AsyncCompletionsWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncCompletionsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncCompletionsWithRawResponse: + return AsyncCompletionsWithRawResponse(self) @overload async def create( diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py index d22e288054..d3e7c54b11 100644 --- a/src/openai/resources/completions.py +++ b/src/openai/resources/completions.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Dict, List, Union, Optional, overload +from typing import Dict, List, Union, Optional, overload from typing_extensions import Literal import httpx @@ -10,23 +10,21 @@ from ..types import Completion, completion_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import required_args, maybe_transform +from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .._streaming import Stream, AsyncStream -from .._base_client import make_request_options - -if TYPE_CHECKING: - from .._client import OpenAI, AsyncOpenAI +from .._base_client import ( + make_request_options, +) __all__ = ["Completions", "AsyncCompletions"] class Completions(SyncAPIResource): - with_raw_response: CompletionsWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = CompletionsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> CompletionsWithRawResponse: + return CompletionsWithRawResponse(self) @overload def create( @@ -593,11 +591,9 @@ def create( class AsyncCompletions(AsyncAPIResource): - with_raw_response: AsyncCompletionsWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncCompletionsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncCompletionsWithRawResponse: + return AsyncCompletionsWithRawResponse(self) @overload async def create( diff --git a/src/openai/resources/edits.py b/src/openai/resources/edits.py index eafaa82fdf..ac15494263 100644 --- a/src/openai/resources/edits.py +++ b/src/openai/resources/edits.py @@ -3,7 +3,7 @@ from __future__ import annotations import typing_extensions -from typing import TYPE_CHECKING, Union, Optional +from typing import Union, Optional from typing_extensions import Literal import httpx @@ -11,22 +11,20 @@ from ..types import Edit, edit_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import maybe_transform +from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper -from .._base_client import make_request_options - -if TYPE_CHECKING: - from .._client import OpenAI, AsyncOpenAI +from .._base_client import ( + make_request_options, +) __all__ = ["Edits", "AsyncEdits"] class Edits(SyncAPIResource): - with_raw_response: EditsWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = EditsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> EditsWithRawResponse: + return EditsWithRawResponse(self) @typing_extensions.deprecated( "The Edits API is deprecated; please use Chat Completions instead.\n\nhttps://openai.com/blog/gpt-4-api-general-availability#deprecation-of-the-edits-api\n" @@ -101,11 +99,9 @@ def create( class AsyncEdits(AsyncAPIResource): - with_raw_response: AsyncEditsWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncEditsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncEditsWithRawResponse: + return AsyncEditsWithRawResponse(self) @typing_extensions.deprecated( "The Edits API is deprecated; please use Chat Completions instead.\n\nhttps://openai.com/blog/gpt-4-api-general-availability#deprecation-of-the-edits-api\n" diff --git a/src/openai/resources/embeddings.py b/src/openai/resources/embeddings.py index 978d239774..e93b29d45b 100644 --- a/src/openai/resources/embeddings.py +++ b/src/openai/resources/embeddings.py @@ -3,7 +3,7 @@ from __future__ import annotations import base64 -from typing import TYPE_CHECKING, List, Union, cast +from typing import List, Union, cast from typing_extensions import Literal import httpx @@ -11,24 +11,21 @@ from ..types import CreateEmbeddingResponse, embedding_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import is_given, maybe_transform -from .._extras import numpy as np -from .._extras import has_numpy +from .._compat import cached_property +from .._extras import numpy as np, has_numpy from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper -from .._base_client import make_request_options - -if TYPE_CHECKING: - from .._client import OpenAI, AsyncOpenAI +from .._base_client import ( + make_request_options, +) __all__ = ["Embeddings", "AsyncEmbeddings"] class Embeddings(SyncAPIResource): - with_raw_response: EmbeddingsWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = EmbeddingsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> EmbeddingsWithRawResponse: + return EmbeddingsWithRawResponse(self) def create( self, @@ -118,11 +115,9 @@ def parser(obj: CreateEmbeddingResponse) -> CreateEmbeddingResponse: class AsyncEmbeddings(AsyncAPIResource): - with_raw_response: AsyncEmbeddingsWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncEmbeddingsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncEmbeddingsWithRawResponse: + return AsyncEmbeddingsWithRawResponse(self) async def create( self, diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index e4d978d3af..1acf6f8060 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -4,7 +4,7 @@ import time import typing_extensions -from typing import TYPE_CHECKING, Mapping, cast +from typing import Mapping, cast from typing_extensions import Literal import httpx @@ -12,6 +12,7 @@ from ..types import FileObject, FileDeleted, file_list_params, file_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from .._utils import extract_files, maybe_transform, deepcopy_minimal +from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ..pagination import SyncPage, AsyncPage @@ -21,18 +22,13 @@ make_request_options, ) -if TYPE_CHECKING: - from .._client import OpenAI, AsyncOpenAI - __all__ = ["Files", "AsyncFiles"] class Files(SyncAPIResource): - with_raw_response: FilesWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = FilesWithRawResponse(self) + @cached_property + def with_raw_response(self) -> FilesWithRawResponse: + return FilesWithRawResponse(self) def create( self, @@ -292,11 +288,9 @@ def wait_for_processing( class AsyncFiles(AsyncAPIResource): - with_raw_response: AsyncFilesWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncFilesWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncFilesWithRawResponse: + return AsyncFilesWithRawResponse(self) async def create( self, diff --git a/src/openai/resources/fine_tunes.py b/src/openai/resources/fine_tunes.py index 91c8201cbb..411952387c 100644 --- a/src/openai/resources/fine_tunes.py +++ b/src/openai/resources/fine_tunes.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, List, Union, Optional, overload +from typing import List, Union, Optional, overload from typing_extensions import Literal import httpx @@ -16,24 +16,23 @@ ) from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import maybe_transform +from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper from .._streaming import Stream, AsyncStream from ..pagination import SyncPage, AsyncPage -from .._base_client import AsyncPaginator, make_request_options - -if TYPE_CHECKING: - from .._client import OpenAI, AsyncOpenAI +from .._base_client import ( + AsyncPaginator, + make_request_options, +) __all__ = ["FineTunes", "AsyncFineTunes"] class FineTunes(SyncAPIResource): - with_raw_response: FineTunesWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = FineTunesWithRawResponse(self) + @cached_property + def with_raw_response(self) -> FineTunesWithRawResponse: + return FineTunesWithRawResponse(self) def create( self, @@ -407,11 +406,9 @@ def list_events( class AsyncFineTunes(AsyncAPIResource): - with_raw_response: AsyncFineTunesWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncFineTunesWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncFineTunesWithRawResponse: + return AsyncFineTunesWithRawResponse(self) async def create( self, diff --git a/src/openai/resources/fine_tuning/__init__.py b/src/openai/resources/fine_tuning/__init__.py index 9133c25d4a..27445fb707 100644 --- a/src/openai/resources/fine_tuning/__init__.py +++ b/src/openai/resources/fine_tuning/__init__.py @@ -1,12 +1,7 @@ # File generated from our OpenAPI spec by Stainless. from .jobs import Jobs, AsyncJobs, JobsWithRawResponse, AsyncJobsWithRawResponse -from .fine_tuning import ( - FineTuning, - AsyncFineTuning, - FineTuningWithRawResponse, - AsyncFineTuningWithRawResponse, -) +from .fine_tuning import FineTuning, AsyncFineTuning, FineTuningWithRawResponse, AsyncFineTuningWithRawResponse __all__ = [ "Jobs", diff --git a/src/openai/resources/fine_tuning/fine_tuning.py b/src/openai/resources/fine_tuning/fine_tuning.py index 2e5f36e546..a5a68b08eb 100644 --- a/src/openai/resources/fine_tuning/fine_tuning.py +++ b/src/openai/resources/fine_tuning/fine_tuning.py @@ -2,35 +2,31 @@ from __future__ import annotations -from typing import TYPE_CHECKING - from .jobs import Jobs, AsyncJobs, JobsWithRawResponse, AsyncJobsWithRawResponse +from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource -if TYPE_CHECKING: - from ..._client import OpenAI, AsyncOpenAI - __all__ = ["FineTuning", "AsyncFineTuning"] class FineTuning(SyncAPIResource): - jobs: Jobs - with_raw_response: FineTuningWithRawResponse + @cached_property + def jobs(self) -> Jobs: + return Jobs(self._client) - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.jobs = Jobs(client) - self.with_raw_response = FineTuningWithRawResponse(self) + @cached_property + def with_raw_response(self) -> FineTuningWithRawResponse: + return FineTuningWithRawResponse(self) class AsyncFineTuning(AsyncAPIResource): - jobs: AsyncJobs - with_raw_response: AsyncFineTuningWithRawResponse + @cached_property + def jobs(self) -> AsyncJobs: + return AsyncJobs(self._client) - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.jobs = AsyncJobs(client) - self.with_raw_response = AsyncFineTuningWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncFineTuningWithRawResponse: + return AsyncFineTuningWithRawResponse(self) class FineTuningWithRawResponse: diff --git a/src/openai/resources/fine_tuning/jobs.py b/src/openai/resources/fine_tuning/jobs.py index 3d9aed8d91..a8f24efce5 100644 --- a/src/openai/resources/fine_tuning/jobs.py +++ b/src/openai/resources/fine_tuning/jobs.py @@ -2,17 +2,21 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Union, Optional +from typing import Union, Optional from typing_extensions import Literal import httpx from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ..._utils import maybe_transform +from ..._compat import cached_property from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ...pagination import SyncCursorPage, AsyncCursorPage -from ..._base_client import AsyncPaginator, make_request_options +from ..._base_client import ( + AsyncPaginator, + make_request_options, +) from ...types.fine_tuning import ( FineTuningJob, FineTuningJobEvent, @@ -21,18 +25,13 @@ job_list_events_params, ) -if TYPE_CHECKING: - from ..._client import OpenAI, AsyncOpenAI - __all__ = ["Jobs", "AsyncJobs"] class Jobs(SyncAPIResource): - with_raw_response: JobsWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = JobsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> JobsWithRawResponse: + return JobsWithRawResponse(self) def create( self, @@ -280,11 +279,9 @@ def list_events( class AsyncJobs(AsyncAPIResource): - with_raw_response: AsyncJobsWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncJobsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncJobsWithRawResponse: + return AsyncJobsWithRawResponse(self) async def create( self, diff --git a/src/openai/resources/images.py b/src/openai/resources/images.py index 94b1bc1fc8..8e9c288af7 100644 --- a/src/openai/resources/images.py +++ b/src/openai/resources/images.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Union, Mapping, Optional, cast +from typing import Union, Mapping, Optional, cast from typing_extensions import Literal import httpx @@ -15,22 +15,20 @@ ) from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from .._utils import extract_files, maybe_transform, deepcopy_minimal +from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper -from .._base_client import make_request_options - -if TYPE_CHECKING: - from .._client import OpenAI, AsyncOpenAI +from .._base_client import ( + make_request_options, +) __all__ = ["Images", "AsyncImages"] class Images(SyncAPIResource): - with_raw_response: ImagesWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = ImagesWithRawResponse(self) + @cached_property + def with_raw_response(self) -> ImagesWithRawResponse: + return ImagesWithRawResponse(self) def create_variation( self, @@ -271,11 +269,9 @@ def generate( class AsyncImages(AsyncAPIResource): - with_raw_response: AsyncImagesWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncImagesWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncImagesWithRawResponse: + return AsyncImagesWithRawResponse(self) async def create_variation( self, diff --git a/src/openai/resources/models.py b/src/openai/resources/models.py index 2d04bdc5cc..48888d98b5 100644 --- a/src/openai/resources/models.py +++ b/src/openai/resources/models.py @@ -2,29 +2,26 @@ from __future__ import annotations -from typing import TYPE_CHECKING - import httpx from ..types import Model, ModelDeleted from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper from ..pagination import SyncPage, AsyncPage -from .._base_client import AsyncPaginator, make_request_options - -if TYPE_CHECKING: - from .._client import OpenAI, AsyncOpenAI +from .._base_client import ( + AsyncPaginator, + make_request_options, +) __all__ = ["Models", "AsyncModels"] class Models(SyncAPIResource): - with_raw_response: ModelsWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = ModelsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> ModelsWithRawResponse: + return ModelsWithRawResponse(self) def retrieve( self, @@ -116,11 +113,9 @@ def delete( class AsyncModels(AsyncAPIResource): - with_raw_response: AsyncModelsWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncModelsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncModelsWithRawResponse: + return AsyncModelsWithRawResponse(self) async def retrieve( self, diff --git a/src/openai/resources/moderations.py b/src/openai/resources/moderations.py index 12a7c68a7b..120a499186 100644 --- a/src/openai/resources/moderations.py +++ b/src/openai/resources/moderations.py @@ -2,7 +2,7 @@ from __future__ import annotations -from typing import TYPE_CHECKING, List, Union +from typing import List, Union from typing_extensions import Literal import httpx @@ -10,22 +10,20 @@ from ..types import ModerationCreateResponse, moderation_create_params from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import maybe_transform +from .._compat import cached_property from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper -from .._base_client import make_request_options - -if TYPE_CHECKING: - from .._client import OpenAI, AsyncOpenAI +from .._base_client import ( + make_request_options, +) __all__ = ["Moderations", "AsyncModerations"] class Moderations(SyncAPIResource): - with_raw_response: ModerationsWithRawResponse - - def __init__(self, client: OpenAI) -> None: - super().__init__(client) - self.with_raw_response = ModerationsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> ModerationsWithRawResponse: + return ModerationsWithRawResponse(self) def create( self, @@ -79,11 +77,9 @@ def create( class AsyncModerations(AsyncAPIResource): - with_raw_response: AsyncModerationsWithRawResponse - - def __init__(self, client: AsyncOpenAI) -> None: - super().__init__(client) - self.with_raw_response = AsyncModerationsWithRawResponse(self) + @cached_property + def with_raw_response(self) -> AsyncModerationsWithRawResponse: + return AsyncModerationsWithRawResponse(self) async def create( self, diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index 1b4fca26ee..df2b580587 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -5,8 +5,7 @@ from .edit import Edit as Edit from .image import Image as Image from .model import Model as Model -from .shared import FunctionDefinition as FunctionDefinition -from .shared import FunctionParameters as FunctionParameters +from .shared import FunctionDefinition as FunctionDefinition, FunctionParameters as FunctionParameters from .embedding import Embedding as Embedding from .fine_tune import FineTune as FineTune from .completion import Completion as Completion @@ -28,18 +27,8 @@ from .fine_tune_create_params import FineTuneCreateParams as FineTuneCreateParams from .completion_create_params import CompletionCreateParams as CompletionCreateParams from .moderation_create_params import ModerationCreateParams as ModerationCreateParams -from .create_embedding_response import ( - CreateEmbeddingResponse as CreateEmbeddingResponse, -) -from .moderation_create_response import ( - ModerationCreateResponse as ModerationCreateResponse, -) -from .fine_tune_list_events_params import ( - FineTuneListEventsParams as FineTuneListEventsParams, -) -from .image_create_variation_params import ( - ImageCreateVariationParams as ImageCreateVariationParams, -) -from .fine_tune_events_list_response import ( - FineTuneEventsListResponse as FineTuneEventsListResponse, -) +from .create_embedding_response import CreateEmbeddingResponse as CreateEmbeddingResponse +from .moderation_create_response import ModerationCreateResponse as ModerationCreateResponse +from .fine_tune_list_events_params import FineTuneListEventsParams as FineTuneListEventsParams +from .image_create_variation_params import ImageCreateVariationParams as ImageCreateVariationParams +from .fine_tune_events_list_response import FineTuneEventsListResponse as FineTuneEventsListResponse diff --git a/src/openai/types/audio/__init__.py b/src/openai/types/audio/__init__.py index 83afa060f8..ba5f7fd8e0 100644 --- a/src/openai/types/audio/__init__.py +++ b/src/openai/types/audio/__init__.py @@ -5,9 +5,5 @@ from .translation import Translation as Translation from .transcription import Transcription as Transcription from .speech_create_params import SpeechCreateParams as SpeechCreateParams -from .translation_create_params import ( - TranslationCreateParams as TranslationCreateParams, -) -from .transcription_create_params import ( - TranscriptionCreateParams as TranscriptionCreateParams, -) +from .translation_create_params import TranslationCreateParams as TranslationCreateParams +from .transcription_create_params import TranscriptionCreateParams as TranscriptionCreateParams diff --git a/src/openai/types/beta/__init__.py b/src/openai/types/beta/__init__.py index c03d823b8c..e6742521e9 100644 --- a/src/openai/types/beta/__init__.py +++ b/src/openai/types/beta/__init__.py @@ -11,6 +11,4 @@ from .assistant_list_params import AssistantListParams as AssistantListParams from .assistant_create_params import AssistantCreateParams as AssistantCreateParams from .assistant_update_params import AssistantUpdateParams as AssistantUpdateParams -from .thread_create_and_run_params import ( - ThreadCreateAndRunParams as ThreadCreateAndRunParams, -) +from .thread_create_and_run_params import ThreadCreateAndRunParams as ThreadCreateAndRunParams diff --git a/src/openai/types/beta/assistant.py b/src/openai/types/beta/assistant.py index a21206765a..89e45d4806 100644 --- a/src/openai/types/beta/assistant.py +++ b/src/openai/types/beta/assistant.py @@ -37,7 +37,7 @@ class Assistant(BaseModel): created_at: int """The Unix timestamp (in seconds) for when the assistant was created.""" - description: Optional[str] + description: Optional[str] = None """The description of the assistant. The maximum length is 512 characters.""" file_ids: List[str] @@ -47,13 +47,13 @@ class Assistant(BaseModel): assistant. Files are ordered by their creation date in ascending order. """ - instructions: Optional[str] + instructions: Optional[str] = None """The system instructions that the assistant uses. The maximum length is 32768 characters. """ - metadata: Optional[builtins.object] + metadata: Optional[builtins.object] = None """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a @@ -71,7 +71,7 @@ class Assistant(BaseModel): descriptions of them. """ - name: Optional[str] + name: Optional[str] = None """The name of the assistant. The maximum length is 256 characters.""" object: Literal["assistant"] diff --git a/src/openai/types/beta/assistant_update_params.py b/src/openai/types/beta/assistant_update_params.py index a0efd96ecd..dfb5d4c553 100644 --- a/src/openai/types/beta/assistant_update_params.py +++ b/src/openai/types/beta/assistant_update_params.py @@ -25,7 +25,7 @@ class AssistantUpdateParams(TypedDict, total=False): A list of [File](https://platform.openai.com/docs/api-reference/files) IDs attached to this assistant. There can be a maximum of 20 files attached to the assistant. Files are ordered by their creation date in ascending order. If a - file was previosuly attached to the list but does not show up in the list, it + file was previously attached to the list but does not show up in the list, it will be deleted from the assistant. """ diff --git a/src/openai/types/beta/thread.py b/src/openai/types/beta/thread.py index a340bffd60..474527033a 100644 --- a/src/openai/types/beta/thread.py +++ b/src/openai/types/beta/thread.py @@ -16,7 +16,7 @@ class Thread(BaseModel): created_at: int """The Unix timestamp (in seconds) for when the thread was created.""" - metadata: Optional[builtins.object] + metadata: Optional[builtins.object] = None """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a diff --git a/src/openai/types/beta/threads/__init__.py b/src/openai/types/beta/threads/__init__.py index 0cb557a514..8c77466dec 100644 --- a/src/openai/types/beta/threads/__init__.py +++ b/src/openai/types/beta/threads/__init__.py @@ -11,12 +11,6 @@ from .message_content_text import MessageContentText as MessageContentText from .message_create_params import MessageCreateParams as MessageCreateParams from .message_update_params import MessageUpdateParams as MessageUpdateParams -from .message_content_image_file import ( - MessageContentImageFile as MessageContentImageFile, -) -from .run_submit_tool_outputs_params import ( - RunSubmitToolOutputsParams as RunSubmitToolOutputsParams, -) -from .required_action_function_tool_call import ( - RequiredActionFunctionToolCall as RequiredActionFunctionToolCall, -) +from .message_content_image_file import MessageContentImageFile as MessageContentImageFile +from .run_submit_tool_outputs_params import RunSubmitToolOutputsParams as RunSubmitToolOutputsParams +from .required_action_function_tool_call import RequiredActionFunctionToolCall as RequiredActionFunctionToolCall diff --git a/src/openai/types/beta/threads/run.py b/src/openai/types/beta/threads/run.py index ffbba1e504..b6d66bd8dd 100644 --- a/src/openai/types/beta/threads/run.py +++ b/src/openai/types/beta/threads/run.py @@ -72,10 +72,10 @@ class Run(BaseModel): execution of this run. """ - cancelled_at: Optional[int] + cancelled_at: Optional[int] = None """The Unix timestamp (in seconds) for when the run was cancelled.""" - completed_at: Optional[int] + completed_at: Optional[int] = None """The Unix timestamp (in seconds) for when the run was completed.""" created_at: int @@ -84,7 +84,7 @@ class Run(BaseModel): expires_at: int """The Unix timestamp (in seconds) for when the run will expire.""" - failed_at: Optional[int] + failed_at: Optional[int] = None """The Unix timestamp (in seconds) for when the run failed.""" file_ids: List[str] @@ -101,10 +101,10 @@ class Run(BaseModel): this run. """ - last_error: Optional[LastError] + last_error: Optional[LastError] = None """The last error associated with this run. Will be `null` if there are no errors.""" - metadata: Optional[builtins.object] + metadata: Optional[builtins.object] = None """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a @@ -122,13 +122,13 @@ class Run(BaseModel): object: Literal["thread.run"] """The object type, which is always `thread.run`.""" - required_action: Optional[RequiredAction] + required_action: Optional[RequiredAction] = None """Details on the action required to continue the run. Will be `null` if no action is required. """ - started_at: Optional[int] + started_at: Optional[int] = None """The Unix timestamp (in seconds) for when the run was started.""" status: Literal[ diff --git a/src/openai/types/beta/threads/runs/__init__.py b/src/openai/types/beta/threads/runs/__init__.py index 72b972a986..16cb852922 100644 --- a/src/openai/types/beta/threads/runs/__init__.py +++ b/src/openai/types/beta/threads/runs/__init__.py @@ -8,6 +8,4 @@ from .function_tool_call import FunctionToolCall as FunctionToolCall from .retrieval_tool_call import RetrievalToolCall as RetrievalToolCall from .tool_calls_step_details import ToolCallsStepDetails as ToolCallsStepDetails -from .message_creation_step_details import ( - MessageCreationStepDetails as MessageCreationStepDetails, -) +from .message_creation_step_details import MessageCreationStepDetails as MessageCreationStepDetails diff --git a/src/openai/types/beta/threads/runs/function_tool_call.py b/src/openai/types/beta/threads/runs/function_tool_call.py index f4cf8bbdd0..bbd3cb7052 100644 --- a/src/openai/types/beta/threads/runs/function_tool_call.py +++ b/src/openai/types/beta/threads/runs/function_tool_call.py @@ -15,7 +15,7 @@ class Function(BaseModel): name: str """The name of the function.""" - output: Optional[str] + output: Optional[str] = None """The output of the function. This will be `null` if the outputs have not been diff --git a/src/openai/types/beta/threads/runs/run_step.py b/src/openai/types/beta/threads/runs/run_step.py index 5f8723b71a..1d95e9d6eb 100644 --- a/src/openai/types/beta/threads/runs/run_step.py +++ b/src/openai/types/beta/threads/runs/run_step.py @@ -33,31 +33,31 @@ class RunStep(BaseModel): associated with the run step. """ - cancelled_at: Optional[int] + cancelled_at: Optional[int] = None """The Unix timestamp (in seconds) for when the run step was cancelled.""" - completed_at: Optional[int] + completed_at: Optional[int] = None """The Unix timestamp (in seconds) for when the run step completed.""" created_at: int """The Unix timestamp (in seconds) for when the run step was created.""" - expired_at: Optional[int] + expired_at: Optional[int] = None """The Unix timestamp (in seconds) for when the run step expired. A step is considered expired if the parent run is expired. """ - failed_at: Optional[int] + failed_at: Optional[int] = None """The Unix timestamp (in seconds) for when the run step failed.""" - last_error: Optional[LastError] + last_error: Optional[LastError] = None """The last error associated with this run step. Will be `null` if there are no errors. """ - metadata: Optional[builtins.object] + metadata: Optional[builtins.object] = None """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a diff --git a/src/openai/types/beta/threads/thread_message.py b/src/openai/types/beta/threads/thread_message.py index 0f782ef845..8f1ac07d0a 100644 --- a/src/openai/types/beta/threads/thread_message.py +++ b/src/openai/types/beta/threads/thread_message.py @@ -17,7 +17,7 @@ class ThreadMessage(BaseModel): id: str """The identifier, which can be referenced in API endpoints.""" - assistant_id: Optional[str] + assistant_id: Optional[str] = None """ If applicable, the ID of the [assistant](https://platform.openai.com/docs/api-reference/assistants) that @@ -37,7 +37,7 @@ class ThreadMessage(BaseModel): that can access files. A maximum of 10 files can be attached to a message. """ - metadata: Optional[builtins.object] + metadata: Optional[builtins.object] = None """Set of 16 key-value pairs that can be attached to an object. This can be useful for storing additional information about the object in a @@ -51,7 +51,7 @@ class ThreadMessage(BaseModel): role: Literal["user", "assistant"] """The entity that produced the message. One of `user` or `assistant`.""" - run_id: Optional[str] + run_id: Optional[str] = None """ If applicable, the ID of the [run](https://platform.openai.com/docs/api-reference/runs) associated with the diff --git a/src/openai/types/chat/__init__.py b/src/openai/types/chat/__init__.py index ba21982a2b..39a6335f64 100644 --- a/src/openai/types/chat/__init__.py +++ b/src/openai/types/chat/__init__.py @@ -7,30 +7,14 @@ from .chat_completion_chunk import ChatCompletionChunk as ChatCompletionChunk from .chat_completion_message import ChatCompletionMessage as ChatCompletionMessage from .completion_create_params import CompletionCreateParams as CompletionCreateParams -from .chat_completion_tool_param import ( - ChatCompletionToolParam as ChatCompletionToolParam, -) -from .chat_completion_message_param import ( - ChatCompletionMessageParam as ChatCompletionMessageParam, -) -from .chat_completion_token_logprob import ( - ChatCompletionTokenLogprob as ChatCompletionTokenLogprob, -) -from .chat_completion_message_tool_call import ( - ChatCompletionMessageToolCall as ChatCompletionMessageToolCall, -) -from .chat_completion_content_part_param import ( - ChatCompletionContentPartParam as ChatCompletionContentPartParam, -) -from .chat_completion_tool_message_param import ( - ChatCompletionToolMessageParam as ChatCompletionToolMessageParam, -) -from .chat_completion_user_message_param import ( - ChatCompletionUserMessageParam as ChatCompletionUserMessageParam, -) -from .chat_completion_system_message_param import ( - ChatCompletionSystemMessageParam as ChatCompletionSystemMessageParam, -) +from .chat_completion_tool_param import ChatCompletionToolParam as ChatCompletionToolParam +from .chat_completion_message_param import ChatCompletionMessageParam as ChatCompletionMessageParam +from .chat_completion_token_logprob import ChatCompletionTokenLogprob as ChatCompletionTokenLogprob +from .chat_completion_message_tool_call import ChatCompletionMessageToolCall as ChatCompletionMessageToolCall +from .chat_completion_content_part_param import ChatCompletionContentPartParam as ChatCompletionContentPartParam +from .chat_completion_tool_message_param import ChatCompletionToolMessageParam as ChatCompletionToolMessageParam +from .chat_completion_user_message_param import ChatCompletionUserMessageParam as ChatCompletionUserMessageParam +from .chat_completion_system_message_param import ChatCompletionSystemMessageParam as ChatCompletionSystemMessageParam from .chat_completion_function_message_param import ( ChatCompletionFunctionMessageParam as ChatCompletionFunctionMessageParam, ) diff --git a/src/openai/types/chat/chat_completion.py b/src/openai/types/chat/chat_completion.py index 055280c347..dc63d84945 100644 --- a/src/openai/types/chat/chat_completion.py +++ b/src/openai/types/chat/chat_completion.py @@ -12,7 +12,7 @@ class ChoiceLogprobs(BaseModel): - content: Optional[List[ChatCompletionTokenLogprob]] + content: Optional[List[ChatCompletionTokenLogprob]] = None """A list of message content tokens with log probability information.""" @@ -30,7 +30,7 @@ class Choice(BaseModel): index: int """The index of the choice in the list of choices.""" - logprobs: Optional[ChoiceLogprobs] + logprobs: Optional[ChoiceLogprobs] = None """Log probability information for the choice.""" message: ChatCompletionMessage diff --git a/src/openai/types/chat/chat_completion_chunk.py b/src/openai/types/chat/chat_completion_chunk.py index ccc7ad79ec..95013e7a4f 100644 --- a/src/openai/types/chat/chat_completion_chunk.py +++ b/src/openai/types/chat/chat_completion_chunk.py @@ -73,7 +73,7 @@ class ChoiceDelta(BaseModel): class ChoiceLogprobs(BaseModel): - content: Optional[List[ChatCompletionTokenLogprob]] + content: Optional[List[ChatCompletionTokenLogprob]] = None """A list of message content tokens with log probability information.""" @@ -81,7 +81,7 @@ class Choice(BaseModel): delta: ChoiceDelta """A chat completion delta generated by streamed model responses.""" - finish_reason: Optional[Literal["stop", "length", "tool_calls", "content_filter", "function_call"]] + finish_reason: Optional[Literal["stop", "length", "tool_calls", "content_filter", "function_call"]] = None """The reason the model stopped generating tokens. This will be `stop` if the model hit a natural stop point or a provided stop diff --git a/src/openai/types/chat/chat_completion_content_part_param.py b/src/openai/types/chat/chat_completion_content_part_param.py index 587578e2ef..8e58239258 100644 --- a/src/openai/types/chat/chat_completion_content_part_param.py +++ b/src/openai/types/chat/chat_completion_content_part_param.py @@ -5,9 +5,7 @@ from typing import Union from .chat_completion_content_part_text_param import ChatCompletionContentPartTextParam -from .chat_completion_content_part_image_param import ( - ChatCompletionContentPartImageParam, -) +from .chat_completion_content_part_image_param import ChatCompletionContentPartImageParam __all__ = ["ChatCompletionContentPartParam"] diff --git a/src/openai/types/chat/chat_completion_message.py b/src/openai/types/chat/chat_completion_message.py index 4749798a33..da8b2fcd5c 100644 --- a/src/openai/types/chat/chat_completion_message.py +++ b/src/openai/types/chat/chat_completion_message.py @@ -23,7 +23,7 @@ class FunctionCall(BaseModel): class ChatCompletionMessage(BaseModel): - content: Optional[str] + content: Optional[str] = None """The contents of the message.""" role: Literal["assistant"] diff --git a/src/openai/types/chat/chat_completion_token_logprob.py b/src/openai/types/chat/chat_completion_token_logprob.py index 8896da8b85..728845fb33 100644 --- a/src/openai/types/chat/chat_completion_token_logprob.py +++ b/src/openai/types/chat/chat_completion_token_logprob.py @@ -11,7 +11,7 @@ class TopLogprob(BaseModel): token: str """The token.""" - bytes: Optional[List[int]] + bytes: Optional[List[int]] = None """A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and @@ -27,7 +27,7 @@ class ChatCompletionTokenLogprob(BaseModel): token: str """The token.""" - bytes: Optional[List[int]] + bytes: Optional[List[int]] = None """A list of integers representing the UTF-8 bytes representation of the token. Useful in instances where characters are represented by multiple tokens and diff --git a/src/openai/types/chat/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 41b71efa04..49807a372e 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -8,12 +8,8 @@ from ...types import shared_params from .chat_completion_tool_param import ChatCompletionToolParam from .chat_completion_message_param import ChatCompletionMessageParam -from .chat_completion_tool_choice_option_param import ( - ChatCompletionToolChoiceOptionParam, -) -from .chat_completion_function_call_option_param import ( - ChatCompletionFunctionCallOptionParam, -) +from .chat_completion_tool_choice_option_param import ChatCompletionToolChoiceOptionParam +from .chat_completion_function_call_option_param import ChatCompletionFunctionCallOptionParam __all__ = [ "CompletionCreateParamsBase", diff --git a/src/openai/types/completion_choice.py b/src/openai/types/completion_choice.py index 71de0f9247..7b08582bfd 100644 --- a/src/openai/types/completion_choice.py +++ b/src/openai/types/completion_choice.py @@ -30,6 +30,6 @@ class CompletionChoice(BaseModel): index: int - logprobs: Optional[Logprobs] + logprobs: Optional[Logprobs] = None text: str diff --git a/src/openai/types/fine_tune.py b/src/openai/types/fine_tune.py index de1e097ee4..d1a063a065 100644 --- a/src/openai/types/fine_tune.py +++ b/src/openai/types/fine_tune.py @@ -50,7 +50,7 @@ class FineTune(BaseModel): created_at: int """The Unix timestamp (in seconds) for when the fine-tuning job was created.""" - fine_tuned_model: Optional[str] + fine_tuned_model: Optional[str] = None """The name of the fine-tuned model that is being created.""" hyperparams: Hyperparams diff --git a/src/openai/types/fine_tuning/fine_tuning_job.py b/src/openai/types/fine_tuning/fine_tuning_job.py index 3897176a47..5aa4f07eb1 100644 --- a/src/openai/types/fine_tuning/fine_tuning_job.py +++ b/src/openai/types/fine_tuning/fine_tuning_job.py @@ -15,7 +15,7 @@ class Error(BaseModel): message: str """A human-readable error message.""" - param: Optional[str] + param: Optional[str] = None """The parameter that was invalid, usually `training_file` or `validation_file`. This field will be null if the failure was not parameter-specific. @@ -39,19 +39,19 @@ class FineTuningJob(BaseModel): created_at: int """The Unix timestamp (in seconds) for when the fine-tuning job was created.""" - error: Optional[Error] + error: Optional[Error] = None """ For fine-tuning jobs that have `failed`, this will contain more information on the cause of the failure. """ - fine_tuned_model: Optional[str] + fine_tuned_model: Optional[str] = None """The name of the fine-tuned model that is being created. The value will be null if the fine-tuning job is still running. """ - finished_at: Optional[int] + finished_at: Optional[int] = None """The Unix timestamp (in seconds) for when the fine-tuning job was finished. The value will be null if the fine-tuning job is still running. @@ -86,7 +86,7 @@ class FineTuningJob(BaseModel): `validating_files`, `queued`, `running`, `succeeded`, `failed`, or `cancelled`. """ - trained_tokens: Optional[int] + trained_tokens: Optional[int] = None """The total number of billable tokens processed by this fine-tuning job. The value will be null if the fine-tuning job is still running. @@ -99,7 +99,7 @@ class FineTuningJob(BaseModel): [Files API](https://platform.openai.com/docs/api-reference/files/retrieve-contents). """ - validation_file: Optional[str] + validation_file: Optional[str] = None """The file ID used for validation. You can retrieve the validation results with the diff --git a/src/openai/types/moderation.py b/src/openai/types/moderation.py index 3602a46985..09c9a6058b 100644 --- a/src/openai/types/moderation.py +++ b/src/openai/types/moderation.py @@ -25,7 +25,7 @@ class Categories(BaseModel): Content that expresses, incites, or promotes hate based on race, gender, ethnicity, religion, nationality, sexual orientation, disability status, or caste. Hateful content aimed at non-protected groups (e.g., chess players) is - harrassment. + harassment. """ hate_threatening: bool = FieldInfo(alias="hate/threatening") diff --git a/tests/api_resources/beta/test_assistants.py b/tests/api_resources/beta/test_assistants.py index 82e975b46d..97e74c61e4 100644 --- a/tests/api_resources/beta/test_assistants.py +++ b/tests/api_resources/beta/test_assistants.py @@ -10,7 +10,10 @@ from tests.utils import assert_matches_type from openai._client import OpenAI, AsyncOpenAI from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta import Assistant, AssistantDeleted +from openai.types.beta import ( + Assistant, + AssistantDeleted, +) base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") api_key = "My API Key" diff --git a/tests/api_resources/beta/test_threads.py b/tests/api_resources/beta/test_threads.py index 8fa1fc20ea..860159ffb3 100644 --- a/tests/api_resources/beta/test_threads.py +++ b/tests/api_resources/beta/test_threads.py @@ -9,7 +9,10 @@ from openai import OpenAI, AsyncOpenAI from tests.utils import assert_matches_type from openai._client import OpenAI, AsyncOpenAI -from openai.types.beta import Thread, ThreadDeleted +from openai.types.beta import ( + Thread, + ThreadDeleted, +) from openai.types.beta.threads import Run base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") diff --git a/tests/api_resources/beta/threads/test_runs.py b/tests/api_resources/beta/threads/test_runs.py index 494cae2656..9d04a95c80 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -10,7 +10,9 @@ from tests.utils import assert_matches_type from openai._client import OpenAI, AsyncOpenAI from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.beta.threads import Run +from openai.types.beta.threads import ( + Run, +) base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") api_key = "My API Key" diff --git a/tests/api_resources/fine_tuning/test_jobs.py b/tests/api_resources/fine_tuning/test_jobs.py index 5716a23d54..927ca9bbdd 100644 --- a/tests/api_resources/fine_tuning/test_jobs.py +++ b/tests/api_resources/fine_tuning/test_jobs.py @@ -10,7 +10,10 @@ from tests.utils import assert_matches_type from openai._client import OpenAI, AsyncOpenAI from openai.pagination import SyncCursorPage, AsyncCursorPage -from openai.types.fine_tuning import FineTuningJob, FineTuningJobEvent +from openai.types.fine_tuning import ( + FineTuningJob, + FineTuningJobEvent, +) base_url = os.environ.get("TEST_API_BASE_URL", "http://127.0.0.1:4010") api_key = "My API Key" diff --git a/tests/test_client.py b/tests/test_client.py index ffa779fb38..c49e4d629e 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -20,18 +20,8 @@ from openai._client import OpenAI, AsyncOpenAI from openai._models import BaseModel, FinalRequestOptions from openai._streaming import Stream, AsyncStream -from openai._exceptions import ( - OpenAIError, - APIStatusError, - APITimeoutError, - APIResponseValidationError, -) -from openai._base_client import ( - DEFAULT_TIMEOUT, - HTTPX_DEFAULT_TIMEOUT, - BaseClient, - make_request_options, -) +from openai._exceptions import OpenAIError, APIStatusError, APITimeoutError, APIResponseValidationError +from openai._base_client import DEFAULT_TIMEOUT, HTTPX_DEFAULT_TIMEOUT, BaseClient, make_request_options from .utils import update_env diff --git a/tests/utils.py b/tests/utils.py index 57486c733a..02dd9c0acc 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -8,7 +8,12 @@ from typing_extensions import Literal, get_args, get_origin, assert_type from openai._types import NoneType -from openai._utils import is_dict, is_list, is_list_type, is_union_type +from openai._utils import ( + is_dict, + is_list, + is_list_type, + is_union_type, +) from openai._compat import PYDANTIC_V2, field_outer_type, get_model_fields from openai._models import BaseModel