From be0438a2e399bb0e0a94907229d02fc61ab479c0 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 4 Dec 2023 05:27:44 -0500 Subject: [PATCH 01/12] chore(package): lift anyio v4 restriction (#927) --- pyproject.toml | 4 ++-- requirements-dev.lock | 11 +++++------ requirements.lock | 13 ++++++------- tests/test_client.py | 14 +++++++------- 4 files changed, 20 insertions(+), 22 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 81ef1ca31..c46822049 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -11,7 +11,7 @@ dependencies = [ "httpx>=0.23.0, <1", "pydantic>=1.9.0, <3", "typing-extensions>=4.5, <5", - "anyio>=3.5.0, <4", + "anyio>=3.5.0, <5", "distro>=1.7.0, <2", "sniffio", "tqdm > 4" @@ -51,7 +51,7 @@ dev-dependencies = [ "pyright==1.1.332", "mypy==1.7.1", "black==23.3.0", - "respx==0.19.2", + "respx==0.20.2", "pytest==7.1.1", "pytest-asyncio==0.21.1", "ruff==0.0.282", diff --git a/requirements-dev.lock b/requirements-dev.lock index 683454d67..0ed197479 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -8,7 +8,7 @@ -e file:. annotated-types==0.6.0 -anyio==3.7.1 +anyio==4.1.0 argcomplete==3.1.2 attrs==23.1.0 azure-core==1.29.5 @@ -25,9 +25,9 @@ distlib==0.3.7 distro==1.8.0 exceptiongroup==1.1.3 filelock==3.12.4 -h11==0.12.0 -httpcore==0.15.0 -httpx==0.23.0 +h11==0.14.0 +httpcore==1.0.2 +httpx==0.25.2 idna==3.4 iniconfig==2.0.0 isort==5.10.1 @@ -56,8 +56,7 @@ pytest-asyncio==0.21.1 python-dateutil==2.8.2 pytz==2023.3.post1 requests==2.31.0 -respx==0.19.2 -rfc3986==1.5.0 +respx==0.20.2 ruff==0.0.282 six==1.16.0 sniffio==1.3.0 diff --git a/requirements.lock b/requirements.lock index be9606fc3..c178f26a8 100644 --- a/requirements.lock +++ b/requirements.lock @@ -8,22 +8,21 @@ -e file:. annotated-types==0.6.0 -anyio==3.7.1 +anyio==4.1.0 certifi==2023.7.22 distro==1.8.0 exceptiongroup==1.1.3 -h11==0.12.0 -httpcore==0.15.0 -httpx==0.23.0 +h11==0.14.0 +httpcore==1.0.2 +httpx==0.25.2 idna==3.4 -numpy==1.26.1 -pandas==2.1.1 +numpy==1.26.2 +pandas==2.1.3 pandas-stubs==2.1.1.230928 pydantic==2.4.2 pydantic-core==2.10.1 python-dateutil==2.8.2 pytz==2023.3.post1 -rfc3986==1.5.0 six==1.16.0 sniffio==1.3.0 tqdm==4.66.1 diff --git a/tests/test_client.py b/tests/test_client.py index 1f1ec6fc9..f8653507e 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -6,7 +6,7 @@ import json import asyncio import inspect -from typing import Any, Dict, Union, cast +from typing import Any, Union, cast from unittest import mock import httpx @@ -357,7 +357,7 @@ def test_request_extra_query(self) -> None: ), ), ) - params = cast(Dict[str, str], dict(request.url.params)) + params = dict(request.url.params) assert params == {"my_query_param": "Foo"} # if both `query` and `extra_query` are given, they are merged @@ -371,7 +371,7 @@ def test_request_extra_query(self) -> None: ), ), ) - params = cast(Dict[str, str], dict(request.url.params)) + params = dict(request.url.params) assert params == {"bar": "1", "foo": "2"} # `extra_query` takes priority over `query` when keys clash @@ -385,7 +385,7 @@ def test_request_extra_query(self) -> None: ), ), ) - params = cast(Dict[str, str], dict(request.url.params)) + params = dict(request.url.params) assert params == {"foo": "2"} @pytest.mark.respx(base_url=base_url) @@ -1022,7 +1022,7 @@ def test_request_extra_query(self) -> None: ), ), ) - params = cast(Dict[str, str], dict(request.url.params)) + params = dict(request.url.params) assert params == {"my_query_param": "Foo"} # if both `query` and `extra_query` are given, they are merged @@ -1036,7 +1036,7 @@ def test_request_extra_query(self) -> None: ), ), ) - params = cast(Dict[str, str], dict(request.url.params)) + params = dict(request.url.params) assert params == {"bar": "1", "foo": "2"} # `extra_query` takes priority over `query` when keys clash @@ -1050,7 +1050,7 @@ def test_request_extra_query(self) -> None: ), ), ) - params = cast(Dict[str, str], dict(request.url.params)) + params = dict(request.url.params) assert params == {"foo": "2"} @pytest.mark.respx(base_url=base_url) From e2d37d615fc82ebcf7a1f7e23f06f74da8477f9f Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Mon, 4 Dec 2023 05:45:51 -0500 Subject: [PATCH 02/12] ci: ensure PR titles use conventional commits (#929) --- .github/workflows/lint-pr.yml | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 .github/workflows/lint-pr.yml diff --git a/.github/workflows/lint-pr.yml b/.github/workflows/lint-pr.yml new file mode 100644 index 000000000..4074fb2ca --- /dev/null +++ b/.github/workflows/lint-pr.yml @@ -0,0 +1,21 @@ +name: "Lint PR" + +on: + pull_request_target: + types: + - opened + - edited + - synchronize + +permissions: + pull-requests: read + +jobs: + pr_title: + name: Validate PR title + runs-on: ubuntu-latest + if: github.ref == 'refs/heads/main' && github.repository == 'openai/openai-python' + steps: + - uses: amannn/action-semantic-pull-request@v5 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} From 7ab050e889d1ebc28a96967fcb3765bb2b55dbf0 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Wed, 6 Dec 2023 01:04:32 +0000 Subject: [PATCH 03/12] ci: remove PR title linter (#934) --- .github/workflows/lint-pr.yml | 21 --------------------- 1 file changed, 21 deletions(-) delete mode 100644 .github/workflows/lint-pr.yml diff --git a/.github/workflows/lint-pr.yml b/.github/workflows/lint-pr.yml deleted file mode 100644 index 4074fb2ca..000000000 --- a/.github/workflows/lint-pr.yml +++ /dev/null @@ -1,21 +0,0 @@ -name: "Lint PR" - -on: - pull_request_target: - types: - - opened - - edited - - synchronize - -permissions: - pull-requests: read - -jobs: - pr_title: - name: Validate PR title - runs-on: ubuntu-latest - if: github.ref == 'refs/heads/main' && github.repository == 'openai/openai-python' - steps: - - uses: amannn/action-semantic-pull-request@v5 - env: - GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} From ec651249de2f4e4cf959f816e1b52f03d3b1017a Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 7 Dec 2023 10:12:38 +0000 Subject: [PATCH 04/12] chore(internal): reformat imports (#939) --- pyproject.toml | 37 ++++----- requirements-dev.lock | 5 +- src/openai/__init__.py | 29 +++---- src/openai/_client.py | 3 +- src/openai/_compat.py | 30 ++++---- src/openai/_extras/__init__.py | 3 +- src/openai/_models.py | 14 +--- src/openai/_types.py | 9 +-- src/openai/_utils/__init__.py | 76 ++++++++++--------- src/openai/_utils/_utils.py | 4 +- src/openai/resources/__init__.py | 49 ++---------- src/openai/resources/audio/__init__.py | 14 +--- src/openai/resources/audio/audio.py | 14 +--- src/openai/resources/audio/speech.py | 13 +++- src/openai/resources/audio/transcriptions.py | 13 +++- src/openai/resources/audio/translations.py | 13 +++- src/openai/resources/beta/__init__.py | 14 +--- .../resources/beta/assistants/__init__.py | 7 +- .../resources/beta/assistants/assistants.py | 13 +++- src/openai/resources/beta/assistants/files.py | 13 +++- src/openai/resources/beta/beta.py | 14 +--- src/openai/resources/beta/threads/__init__.py | 14 +--- .../beta/threads/messages/__init__.py | 7 +- .../resources/beta/threads/messages/files.py | 13 +++- .../beta/threads/messages/messages.py | 13 +++- .../resources/beta/threads/runs/runs.py | 13 +++- .../resources/beta/threads/runs/steps.py | 13 +++- src/openai/resources/beta/threads/threads.py | 17 +++-- src/openai/resources/chat/__init__.py | 7 +- src/openai/resources/chat/chat.py | 7 +- src/openai/resources/chat/completions.py | 12 ++- src/openai/resources/completions.py | 12 ++- src/openai/resources/edits.py | 12 ++- src/openai/resources/embeddings.py | 15 +++- src/openai/resources/files.py | 16 +++- src/openai/resources/fine_tunes.py | 13 +++- src/openai/resources/fine_tuning/__init__.py | 7 +- src/openai/resources/fine_tuning/jobs.py | 13 +++- src/openai/resources/images.py | 13 +++- src/openai/resources/models.py | 13 +++- src/openai/resources/moderations.py | 12 ++- src/openai/types/__init__.py | 23 ++---- src/openai/types/audio/__init__.py | 8 +- src/openai/types/beta/__init__.py | 4 +- src/openai/types/beta/threads/__init__.py | 12 +-- .../types/beta/threads/runs/__init__.py | 4 +- src/openai/types/chat/__init__.py | 28 ++----- .../chat_completion_content_part_param.py | 4 +- .../types/chat/completion_create_params.py | 8 +- tests/api_resources/beta/test_assistants.py | 5 +- tests/api_resources/beta/test_threads.py | 5 +- tests/api_resources/beta/threads/test_runs.py | 4 +- tests/api_resources/fine_tuning/test_jobs.py | 5 +- tests/utils.py | 7 +- 54 files changed, 384 insertions(+), 362 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index c46822049..44e7bcb0e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -48,16 +48,16 @@ openai = "openai.cli:main" [tool.rye] managed = true dev-dependencies = [ - "pyright==1.1.332", - "mypy==1.7.1", - "black==23.3.0", - "respx==0.20.2", - "pytest==7.1.1", - "pytest-asyncio==0.21.1", - "ruff==0.0.282", - "isort==5.10.1", - "time-machine==2.9.0", - "nox==2023.4.22", + # version pins are in requirements-dev.lock + "pyright", + "mypy", + "black", + "respx", + "pytest", + "pytest-asyncio", + "ruff", + "time-machine", + "nox", "dirty-equals>=0.6.0", "azure-identity >=1.14.1", "types-tqdm > 4" @@ -68,12 +68,10 @@ format = { chain = [ "format:black", "format:docs", "format:ruff", - "format:isort", ]} "format:black" = "black ." "format:docs" = "python bin/blacken-docs.py README.md api.md" "format:ruff" = "ruff --fix ." -"format:isort" = "isort ." "check:ruff" = "ruff ." @@ -128,16 +126,13 @@ reportImplicitOverride = true reportImportCycles = false reportPrivateUsage = false -[tool.isort] -profile = "black" -length_sort = true -extra_standard_library = ["typing_extensions"] - [tool.ruff] line-length = 120 -format = "grouped" +output-format = "grouped" target-version = "py37" select = [ + # isort + "I", # remove unused imports "F401", # bare except statements @@ -155,6 +150,12 @@ unfixable = [ ] ignore-init-module-imports = 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"] diff --git a/requirements-dev.lock b/requirements-dev.lock index 0ed197479..bc993b16d 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -30,8 +30,7 @@ httpcore==1.0.2 httpx==0.25.2 idna==3.4 iniconfig==2.0.0 -isort==5.10.1 -msal==1.25.0 +msal==1.26.0 msal-extensions==1.0.0 mypy==1.7.1 mypy-extensions==1.0.0 @@ -57,7 +56,7 @@ python-dateutil==2.8.2 pytz==2023.3.post1 requests==2.31.0 respx==0.20.2 -ruff==0.0.282 +ruff==0.1.7 six==1.16.0 sniffio==1.3.0 time-machine==2.9.0 diff --git a/src/openai/__init__.py b/src/openai/__init__.py index d92dfe969..20ab72ee2 100644 --- a/src/openai/__init__.py +++ b/src/openai/__init__.py @@ -72,8 +72,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() @@ -330,15 +329,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/_client.py b/src/openai/_client.py index 202162070..79054aba2 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -22,8 +22,7 @@ ) 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 diff --git a/src/openai/_compat.py b/src/openai/_compat.py index 34323c9b7..d95db8ed1 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 diff --git a/src/openai/_extras/__init__.py b/src/openai/_extras/__init__.py index dc6625c5d..864dac417 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 5b8c96010..cdd44ccb0 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/_types.py b/src/openai/_types.py index 9e962a107..6f298c18c 100644 --- a/src/openai/_types.py +++ b/src/openai/_types.py @@ -19,14 +19,7 @@ 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 pydantic from httpx import URL, Proxy, Timeout, Response, BaseTransport, AsyncBaseTransport diff --git a/src/openai/_utils/__init__.py b/src/openai/_utils/__init__.py index 400ca9b82..e98636c92 100644 --- a/src/openai/_utils/__init__.py +++ b/src/openai/_utils/__init__.py @@ -1,37 +1,41 @@ 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_list_type as is_list_type -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 is_union_type as is_union_type -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 extract_type_arg as extract_type_arg -from ._utils import is_required_type as is_required_type -from ._utils import get_async_library as get_async_library -from ._utils import is_annotated_type as is_annotated_type -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 ._utils import strip_annotated_type as strip_annotated_type -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_list_type as is_list_type, + 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, + is_union_type as is_union_type, + 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, + extract_type_arg as extract_type_arg, + is_required_type as is_required_type, + get_async_library as get_async_library, + is_annotated_type as is_annotated_type, + 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, + strip_annotated_type as strip_annotated_type, +) +from ._transform import ( + PropertyInfo as PropertyInfo, + transform as transform, + maybe_transform as maybe_transform, +) diff --git a/src/openai/_utils/_utils.py b/src/openai/_utils/_utils.py index 83f88cc3e..cce692381 100644 --- a/src/openai/_utils/_utils.py +++ b/src/openai/_utils/_utils.py @@ -21,9 +21,7 @@ import sniffio from .._types import Headers, NotGiven, FileTypes, NotGivenOr, HeadersLike -from .._compat import is_union as _is_union -from .._compat import parse_date as parse_date -from .._compat import parse_datetime as parse_datetime +from .._compat import is_union as _is_union, parse_date as parse_date, parse_datetime as parse_datetime _T = TypeVar("_T") _TupleT = TypeVar("_TupleT", bound=Tuple[object, ...]) diff --git a/src/openai/resources/__init__.py b/src/openai/resources/__init__.py index e0f4f08d5..2cdbeb6ae 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 76547b5f3..b6ff4322d 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 6f7226ee5..6b9242f0c 100644 --- a/src/openai/resources/audio/audio.py +++ b/src/openai/resources/audio/audio.py @@ -4,19 +4,9 @@ from typing import TYPE_CHECKING -from .speech import ( - Speech, - AsyncSpeech, - SpeechWithRawResponse, - AsyncSpeechWithRawResponse, -) +from .speech import Speech, AsyncSpeech, SpeechWithRawResponse, AsyncSpeechWithRawResponse from ..._resource import SyncAPIResource, AsyncAPIResource -from .translations import ( - Translations, - AsyncTranslations, - TranslationsWithRawResponse, - AsyncTranslationsWithRawResponse, -) +from .translations import Translations, AsyncTranslations, TranslationsWithRawResponse, AsyncTranslationsWithRawResponse from .transcriptions import ( Transcriptions, AsyncTranscriptions, diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py index 458843866..ac81a8077 100644 --- a/src/openai/resources/audio/speech.py +++ b/src/openai/resources/audio/speech.py @@ -7,12 +7,21 @@ import httpx -from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ..._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from ..._utils import maybe_transform 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 +from ..._base_client import ( + HttpxBinaryResponseContent, + make_request_options, +) if TYPE_CHECKING: from ..._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index d2b445241..54be1c99a 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -7,12 +7,21 @@ import httpx -from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes +from ..._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, + FileTypes, +) from ..._utils import extract_files, maybe_transform, deepcopy_minimal 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 +from ..._base_client import ( + make_request_options, +) if TYPE_CHECKING: from ..._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/audio/translations.py b/src/openai/resources/audio/translations.py index fe7f7f2a4..c4489004a 100644 --- a/src/openai/resources/audio/translations.py +++ b/src/openai/resources/audio/translations.py @@ -7,12 +7,21 @@ import httpx -from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes +from ..._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, + FileTypes, +) from ..._utils import extract_files, maybe_transform, deepcopy_minimal 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 +from ..._base_client import ( + make_request_options, +) if TYPE_CHECKING: from ..._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/beta/__init__.py b/src/openai/resources/beta/__init__.py index 55ad243cc..561f8bef6 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 6efb0b21e..205b2cf0f 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 efa711ecf..944019bed 100644 --- a/src/openai/resources/beta/assistants/assistants.py +++ b/src/openai/resources/beta/assistants/assistants.py @@ -8,7 +8,13 @@ import httpx from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse -from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ...._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from ...._utils import maybe_transform from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_raw_response_wrapper, async_to_raw_response_wrapper @@ -20,7 +26,10 @@ assistant_create_params, assistant_update_params, ) -from ...._base_client import AsyncPaginator, make_request_options +from ...._base_client import ( + AsyncPaginator, + make_request_options, +) if TYPE_CHECKING: from ...._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/beta/assistants/files.py b/src/openai/resources/beta/assistants/files.py index 5ac5897ca..568258748 100644 --- a/src/openai/resources/beta/assistants/files.py +++ b/src/openai/resources/beta/assistants/files.py @@ -7,12 +7,21 @@ import httpx -from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ...._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from ...._utils import maybe_transform 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.assistants import ( AssistantFile, FileDeleteResponse, diff --git a/src/openai/resources/beta/beta.py b/src/openai/resources/beta/beta.py index b55256176..5cea6c146 100644 --- a/src/openai/resources/beta/beta.py +++ b/src/openai/resources/beta/beta.py @@ -4,18 +4,8 @@ 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 .assistants import Assistants, AsyncAssistants, AssistantsWithRawResponse, AsyncAssistantsWithRawResponse from ..._resource import SyncAPIResource, AsyncAPIResource if TYPE_CHECKING: diff --git a/src/openai/resources/beta/threads/__init__.py b/src/openai/resources/beta/threads/__init__.py index b9aaada46..fe7c5e5a2 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 d8d4ce448..cef618ed1 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 e028a6fda..24c9680f3 100644 --- a/src/openai/resources/beta/threads/messages/files.py +++ b/src/openai/resources/beta/threads/messages/files.py @@ -7,12 +7,21 @@ import httpx -from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ....._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from ....._utils import maybe_transform 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: diff --git a/src/openai/resources/beta/threads/messages/messages.py b/src/openai/resources/beta/threads/messages/messages.py index 30ae07251..9a6f5706c 100644 --- a/src/openai/resources/beta/threads/messages/messages.py +++ b/src/openai/resources/beta/threads/messages/messages.py @@ -8,12 +8,21 @@ import httpx from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse -from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ....._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from ....._utils import maybe_transform 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 ( ThreadMessage, message_list_params, diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 969bfab70..719e35ea4 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -8,12 +8,21 @@ import httpx from .steps import Steps, AsyncSteps, StepsWithRawResponse, AsyncStepsWithRawResponse -from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ....._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from ....._utils import maybe_transform 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, diff --git a/src/openai/resources/beta/threads/runs/steps.py b/src/openai/resources/beta/threads/runs/steps.py index 4fcc87a0f..f26034cf8 100644 --- a/src/openai/resources/beta/threads/runs/steps.py +++ b/src/openai/resources/beta/threads/runs/steps.py @@ -7,12 +7,21 @@ import httpx -from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ....._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from ....._utils import maybe_transform 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: diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index 9469fc051..b37667485 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -7,13 +7,14 @@ 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 ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ...._utils import maybe_transform from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_raw_response_wrapper, async_to_raw_response_wrapper @@ -24,7 +25,9 @@ thread_update_params, thread_create_and_run_params, ) -from ...._base_client import make_request_options +from ...._base_client import ( + make_request_options, +) from ....types.beta.threads import Run if TYPE_CHECKING: diff --git a/src/openai/resources/chat/__init__.py b/src/openai/resources/chat/__init__.py index 2e56c0cbf..85b246509 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 3847b2051..d93a501b1 100644 --- a/src/openai/resources/chat/chat.py +++ b/src/openai/resources/chat/chat.py @@ -5,12 +5,7 @@ from typing import TYPE_CHECKING from ..._resource import SyncAPIResource, AsyncAPIResource -from .completions import ( - Completions, - AsyncCompletions, - CompletionsWithRawResponse, - AsyncCompletionsWithRawResponse, -) +from .completions import Completions, AsyncCompletions, CompletionsWithRawResponse, AsyncCompletionsWithRawResponse if TYPE_CHECKING: from ..._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index d0657b2f7..e29554c26 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -7,7 +7,13 @@ import httpx -from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ..._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from ..._utils import required_args, maybe_transform from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper @@ -20,7 +26,9 @@ ChatCompletionToolChoiceOptionParam, completion_create_params, ) -from ..._base_client import make_request_options +from ..._base_client import ( + make_request_options, +) if TYPE_CHECKING: from ..._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py index baf6f04fe..39484c6f7 100644 --- a/src/openai/resources/completions.py +++ b/src/openai/resources/completions.py @@ -8,12 +8,20 @@ import httpx from ..types import Completion, completion_create_params -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from .._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from .._utils import required_args, maybe_transform 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 +from .._base_client import ( + make_request_options, +) if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/edits.py b/src/openai/resources/edits.py index eafaa82fd..587da02c8 100644 --- a/src/openai/resources/edits.py +++ b/src/openai/resources/edits.py @@ -9,11 +9,19 @@ import httpx from ..types import Edit, edit_create_params -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from .._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from .._utils import maybe_transform from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper -from .._base_client import make_request_options +from .._base_client import ( + make_request_options, +) if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/embeddings.py b/src/openai/resources/embeddings.py index c31ad9d93..2ff3d3d44 100644 --- a/src/openai/resources/embeddings.py +++ b/src/openai/resources/embeddings.py @@ -9,13 +9,20 @@ import httpx from ..types import CreateEmbeddingResponse, embedding_create_params -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven +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 .._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 +from .._base_client import ( + make_request_options, +) if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index a6f75e5a4..b9f815af8 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -9,8 +9,20 @@ import httpx -from ..types import FileObject, FileDeleted, file_list_params, file_create_params -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes +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 .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper diff --git a/src/openai/resources/fine_tunes.py b/src/openai/resources/fine_tunes.py index 91c8201cb..f50d78717 100644 --- a/src/openai/resources/fine_tunes.py +++ b/src/openai/resources/fine_tunes.py @@ -14,13 +14,22 @@ fine_tune_create_params, fine_tune_list_events_params, ) -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from .._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from .._utils import maybe_transform 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 +from .._base_client import ( + AsyncPaginator, + make_request_options, +) if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/fine_tuning/__init__.py b/src/openai/resources/fine_tuning/__init__.py index 9133c25d4..27445fb70 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/jobs.py b/src/openai/resources/fine_tuning/jobs.py index 3d9aed8d9..55eee6704 100644 --- a/src/openai/resources/fine_tuning/jobs.py +++ b/src/openai/resources/fine_tuning/jobs.py @@ -7,12 +7,21 @@ import httpx -from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from ..._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from ..._utils import maybe_transform 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, diff --git a/src/openai/resources/images.py b/src/openai/resources/images.py index 94b1bc1fc..0e1313078 100644 --- a/src/openai/resources/images.py +++ b/src/openai/resources/images.py @@ -13,11 +13,20 @@ image_generate_params, image_create_variation_params, ) -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes +from .._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, + FileTypes, +) from .._utils import extract_files, maybe_transform, deepcopy_minimal from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper -from .._base_client import make_request_options +from .._base_client import ( + make_request_options, +) if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/models.py b/src/openai/resources/models.py index 2d04bdc5c..a44a7ffbb 100644 --- a/src/openai/resources/models.py +++ b/src/openai/resources/models.py @@ -7,11 +7,20 @@ import httpx from ..types import Model, ModelDeleted -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from .._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) 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 +from .._base_client import ( + AsyncPaginator, + make_request_options, +) if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/moderations.py b/src/openai/resources/moderations.py index 12a7c68a7..9de7cd640 100644 --- a/src/openai/resources/moderations.py +++ b/src/openai/resources/moderations.py @@ -8,11 +8,19 @@ import httpx from ..types import ModerationCreateResponse, moderation_create_params -from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven +from .._types import ( + NOT_GIVEN, + Body, + Query, + Headers, + NotGiven, +) from .._utils import maybe_transform from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper -from .._base_client import make_request_options +from .._base_client import ( + make_request_options, +) if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index 1b4fca26e..df2b58058 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 83afa060f..ba5f7fd8e 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 c03d823b8..e6742521e 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/threads/__init__.py b/src/openai/types/beta/threads/__init__.py index 0cb557a51..8c77466de 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/runs/__init__.py b/src/openai/types/beta/threads/runs/__init__.py index 72b972a98..16cb85292 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/chat/__init__.py b/src/openai/types/chat/__init__.py index 5fe182f41..3f9091961 100644 --- a/src/openai/types/chat/__init__.py +++ b/src/openai/types/chat/__init__.py @@ -7,27 +7,13 @@ 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_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_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_content_part_param.py b/src/openai/types/chat/chat_completion_content_part_param.py index 587578e2e..8e5823925 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/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 69fe250ec..0d8495b0c 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/tests/api_resources/beta/test_assistants.py b/tests/api_resources/beta/test_assistants.py index 82e975b46..97e74c61e 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 8fa1fc20e..860159ffb 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 d323dfc35..39de3fa29 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 5716a23d5..927ca9bbd 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/utils.py b/tests/utils.py index b51379401..db2ca5601 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 From 8e5a156d555fe68731ba0604a7455cc03cb451ce Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 7 Dec 2023 10:57:27 +0000 Subject: [PATCH 05/12] chore(internal): update formatting (#941) --- src/openai/__init__.py | 12 +----------- src/openai/_client.py | 12 ++++++++++-- 2 files changed, 11 insertions(+), 13 deletions(-) diff --git a/src/openai/__init__.py b/src/openai/__init__.py index 20ab72ee2..d695b6898 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, diff --git a/src/openai/_client.py b/src/openai/_client.py index 79054aba2..7f8744c98 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -20,11 +20,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, 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", From 23fe7ee48a71539b0d1e95ceff349264aae4090e Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 7 Dec 2023 14:36:08 +0000 Subject: [PATCH 06/12] fix(pagination): use correct type hint for .object (#943) --- src/openai/pagination.py | 42 ++++++++++++++++++++++++++-------------- 1 file changed, 28 insertions(+), 14 deletions(-) diff --git a/src/openai/pagination.py b/src/openai/pagination.py index 17f2d1a4c..d47deb17b 100644 --- a/src/openai/pagination.py +++ b/src/openai/pagination.py @@ -1,7 +1,7 @@ # File generated from our OpenAPI spec by Stainless. from typing import Any, List, Generic, Optional, cast -from typing_extensions import Literal, Protocol, override, runtime_checkable +from typing_extensions import Protocol, override, runtime_checkable from ._types import ModelT from ._base_client import BasePage, PageInfo, BaseSyncPage, BaseAsyncPage @@ -11,18 +11,21 @@ @runtime_checkable class CursorPageItem(Protocol): - id: str + id: Optional[str] class SyncPage(BaseSyncPage[ModelT], BasePage[ModelT], Generic[ModelT]): """Note: no pagination actually occurs yet, this is for forwards-compatibility.""" data: List[ModelT] - object: Literal["list"] + object: str @override def _get_page_items(self) -> List[ModelT]: - return self.data + data = self.data + if not data: + return [] + return data @override def next_page_info(self) -> None: @@ -37,11 +40,14 @@ class AsyncPage(BaseAsyncPage[ModelT], BasePage[ModelT], Generic[ModelT]): """Note: no pagination actually occurs yet, this is for forwards-compatibility.""" data: List[ModelT] - object: Literal["list"] + object: str @override def _get_page_items(self) -> List[ModelT]: - return self.data + data = self.data + if not data: + return [] + return data @override def next_page_info(self) -> None: @@ -57,15 +63,19 @@ class SyncCursorPage(BaseSyncPage[ModelT], BasePage[ModelT], Generic[ModelT]): @override def _get_page_items(self) -> List[ModelT]: - return self.data + data = self.data + if not data: + return [] + return data @override def next_page_info(self) -> Optional[PageInfo]: - if not self.data: + data = self.data + if not data: return None - item = cast(Any, self.data[-1]) - if not isinstance(item, CursorPageItem): + item = cast(Any, data[-1]) + if not isinstance(item, CursorPageItem) or item.id is None: # TODO emit warning log return None @@ -77,15 +87,19 @@ class AsyncCursorPage(BaseAsyncPage[ModelT], BasePage[ModelT], Generic[ModelT]): @override def _get_page_items(self) -> List[ModelT]: - return self.data + data = self.data + if not data: + return [] + return data @override def next_page_info(self) -> Optional[PageInfo]: - if not self.data: + data = self.data + if not data: return None - item = cast(Any, self.data[-1]) - if not isinstance(item, CursorPageItem): + item = cast(Any, data[-1]) + if not isinstance(item, CursorPageItem) or item.id is None: # TODO emit warning log return None From 52906391c9b6633656ec7934e6bbac553ec667cd Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 7 Dec 2023 14:55:19 +0000 Subject: [PATCH 07/12] chore(internal): reformat imports (#944) --- pyproject.toml | 37 +++++---- requirements-dev.lock | 19 +---- src/openai/__init__.py | 41 ++++++---- src/openai/_client.py | 15 +--- src/openai/_compat.py | 30 ++++---- src/openai/_extras/__init__.py | 3 +- src/openai/_models.py | 14 +++- src/openai/_types.py | 9 ++- src/openai/_utils/__init__.py | 76 +++++++++---------- src/openai/_utils/_utils.py | 4 +- src/openai/resources/__init__.py | 49 ++++++++++-- src/openai/resources/audio/__init__.py | 14 +++- src/openai/resources/audio/audio.py | 14 +++- src/openai/resources/audio/speech.py | 13 +--- src/openai/resources/audio/transcriptions.py | 13 +--- src/openai/resources/audio/translations.py | 13 +--- src/openai/resources/beta/__init__.py | 14 +++- .../resources/beta/assistants/__init__.py | 7 +- .../resources/beta/assistants/assistants.py | 13 +--- src/openai/resources/beta/assistants/files.py | 13 +--- src/openai/resources/beta/beta.py | 14 +++- src/openai/resources/beta/threads/__init__.py | 14 +++- .../beta/threads/messages/__init__.py | 7 +- .../resources/beta/threads/messages/files.py | 13 +--- .../beta/threads/messages/messages.py | 13 +--- .../resources/beta/threads/runs/runs.py | 13 +--- .../resources/beta/threads/runs/steps.py | 13 +--- src/openai/resources/beta/threads/threads.py | 17 ++--- src/openai/resources/chat/__init__.py | 7 +- src/openai/resources/chat/chat.py | 7 +- src/openai/resources/chat/completions.py | 12 +-- src/openai/resources/completions.py | 12 +-- src/openai/resources/edits.py | 12 +-- src/openai/resources/embeddings.py | 15 +--- src/openai/resources/files.py | 16 +--- src/openai/resources/fine_tunes.py | 13 +--- src/openai/resources/fine_tuning/__init__.py | 7 +- src/openai/resources/fine_tuning/jobs.py | 13 +--- src/openai/resources/images.py | 13 +--- src/openai/resources/models.py | 13 +--- src/openai/resources/moderations.py | 12 +-- src/openai/types/__init__.py | 23 ++++-- src/openai/types/audio/__init__.py | 8 +- src/openai/types/beta/__init__.py | 4 +- src/openai/types/beta/threads/__init__.py | 12 ++- .../types/beta/threads/runs/__init__.py | 4 +- src/openai/types/chat/__init__.py | 28 +++++-- .../chat_completion_content_part_param.py | 4 +- .../types/chat/completion_create_params.py | 8 +- tests/api_resources/beta/test_assistants.py | 5 +- tests/api_resources/beta/test_threads.py | 5 +- tests/api_resources/beta/threads/test_runs.py | 4 +- tests/api_resources/fine_tuning/test_jobs.py | 5 +- tests/utils.py | 7 +- 54 files changed, 374 insertions(+), 410 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 44e7bcb0e..c46822049 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -48,16 +48,16 @@ openai = "openai.cli:main" [tool.rye] managed = true dev-dependencies = [ - # version pins are in requirements-dev.lock - "pyright", - "mypy", - "black", - "respx", - "pytest", - "pytest-asyncio", - "ruff", - "time-machine", - "nox", + "pyright==1.1.332", + "mypy==1.7.1", + "black==23.3.0", + "respx==0.20.2", + "pytest==7.1.1", + "pytest-asyncio==0.21.1", + "ruff==0.0.282", + "isort==5.10.1", + "time-machine==2.9.0", + "nox==2023.4.22", "dirty-equals>=0.6.0", "azure-identity >=1.14.1", "types-tqdm > 4" @@ -68,10 +68,12 @@ format = { chain = [ "format:black", "format:docs", "format:ruff", + "format:isort", ]} "format:black" = "black ." "format:docs" = "python bin/blacken-docs.py README.md api.md" "format:ruff" = "ruff --fix ." +"format:isort" = "isort ." "check:ruff" = "ruff ." @@ -126,13 +128,16 @@ 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" +format = "grouped" target-version = "py37" select = [ - # isort - "I", # remove unused imports "F401", # bare except statements @@ -150,12 +155,6 @@ unfixable = [ ] ignore-init-module-imports = 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"] diff --git a/requirements-dev.lock b/requirements-dev.lock index bc993b16d..b1a9428a0 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -11,15 +11,11 @@ annotated-types==0.6.0 anyio==4.1.0 argcomplete==3.1.2 attrs==23.1.0 -azure-core==1.29.5 azure-identity==1.15.0 black==23.3.0 certifi==2023.7.22 -cffi==1.16.0 -charset-normalizer==3.3.2 click==8.1.7 colorlog==6.7.0 -cryptography==41.0.7 dirty-equals==0.6.0 distlib==0.3.7 distro==1.8.0 @@ -30,43 +26,32 @@ httpcore==1.0.2 httpx==0.25.2 idna==3.4 iniconfig==2.0.0 -msal==1.26.0 -msal-extensions==1.0.0 +isort==5.10.1 mypy==1.7.1 mypy-extensions==1.0.0 nodeenv==1.8.0 nox==2023.4.22 -numpy==1.26.2 packaging==23.2 -pandas==2.1.3 -pandas-stubs==2.1.1.230928 pathspec==0.11.2 platformdirs==3.11.0 pluggy==1.3.0 -portalocker==2.8.2 py==1.11.0 -pycparser==2.21 pydantic==2.4.2 pydantic-core==2.10.1 -pyjwt==2.8.0 pyright==1.1.332 pytest==7.1.1 pytest-asyncio==0.21.1 python-dateutil==2.8.2 pytz==2023.3.post1 -requests==2.31.0 respx==0.20.2 -ruff==0.1.7 +ruff==0.0.282 six==1.16.0 sniffio==1.3.0 time-machine==2.9.0 tomli==2.0.1 tqdm==4.66.1 -types-pytz==2023.3.1.1 types-tqdm==4.66.0.2 typing-extensions==4.8.0 -tzdata==2023.3 -urllib3==2.1.0 virtualenv==20.24.5 # The following packages are considered to be unsafe in a requirements file: setuptools==68.2.2 diff --git a/src/openai/__init__.py b/src/openai/__init__.py index d695b6898..d92dfe969 100644 --- a/src/openai/__init__.py +++ b/src/openai/__init__.py @@ -8,7 +8,17 @@ 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, @@ -62,7 +72,8 @@ from .lib import azure as _azure from .version import VERSION as VERSION -from .lib.azure import AzureOpenAI as AzureOpenAI, AsyncAzureOpenAI as AsyncAzureOpenAI +from .lib.azure import AzureOpenAI as AzureOpenAI +from .lib.azure import AsyncAzureOpenAI as AsyncAzureOpenAI from .lib._old_api import * _setup_logging() @@ -319,17 +330,15 @@ def _reset_client() -> None: # type: ignore[reportUnusedFunction] _client = None -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, -) +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 diff --git a/src/openai/_client.py b/src/openai/_client.py index 7f8744c98..202162070 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -20,19 +20,12 @@ 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, AsyncStream as AsyncStream +from ._streaming import Stream as Stream +from ._streaming import 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 d95db8ed1..34323c9b7 100644 --- a/src/openai/_compat.py +++ b/src/openai/_compat.py @@ -43,23 +43,21 @@ def is_typeddict(type_: type[Any]) -> bool: # noqa: ARG001 else: if PYDANTIC_V2: - 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 + 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 else: - 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 + 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 # refactored config diff --git a/src/openai/_extras/__init__.py b/src/openai/_extras/__init__.py index 864dac417..dc6625c5d 100644 --- a/src/openai/_extras/__init__.py +++ b/src/openai/_extras/__init__.py @@ -1,2 +1,3 @@ -from .numpy_proxy import numpy as numpy, has_numpy as has_numpy +from .numpy_proxy import numpy as numpy +from .numpy_proxy import 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 cdd44ccb0..5b8c96010 100644 --- a/src/openai/_models.py +++ b/src/openai/_models.py @@ -30,11 +30,17 @@ AnyMapping, HttpxRequestFiles, ) -from ._utils import is_list, is_given, is_mapping, parse_date, parse_datetime, strip_not_given +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 ._compat import ( - PYDANTIC_V2, - ConfigDict, - GenericModel as BaseGenericModel, get_args, is_union, parse_obj, diff --git a/src/openai/_types.py b/src/openai/_types.py index 6f298c18c..9e962a107 100644 --- a/src/openai/_types.py +++ b/src/openai/_types.py @@ -19,7 +19,14 @@ 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 pydantic from httpx import URL, Proxy, Timeout, Response, BaseTransport, AsyncBaseTransport diff --git a/src/openai/_utils/__init__.py b/src/openai/_utils/__init__.py index e98636c92..400ca9b82 100644 --- a/src/openai/_utils/__init__.py +++ b/src/openai/_utils/__init__.py @@ -1,41 +1,37 @@ from ._proxy import LazyProxy as LazyProxy -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_list_type as is_list_type, - 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, - is_union_type as is_union_type, - 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, - extract_type_arg as extract_type_arg, - is_required_type as is_required_type, - get_async_library as get_async_library, - is_annotated_type as is_annotated_type, - 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, - strip_annotated_type as strip_annotated_type, -) -from ._transform import ( - PropertyInfo as PropertyInfo, - transform as transform, - maybe_transform as maybe_transform, -) +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_list_type as is_list_type +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 is_union_type as is_union_type +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 extract_type_arg as extract_type_arg +from ._utils import is_required_type as is_required_type +from ._utils import get_async_library as get_async_library +from ._utils import is_annotated_type as is_annotated_type +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 ._utils import strip_annotated_type as strip_annotated_type +from ._transform import PropertyInfo as PropertyInfo +from ._transform import transform as transform +from ._transform import maybe_transform as maybe_transform diff --git a/src/openai/_utils/_utils.py b/src/openai/_utils/_utils.py index cce692381..83f88cc3e 100644 --- a/src/openai/_utils/_utils.py +++ b/src/openai/_utils/_utils.py @@ -21,7 +21,9 @@ import sniffio from .._types import Headers, NotGiven, FileTypes, NotGivenOr, HeadersLike -from .._compat import is_union as _is_union, parse_date as parse_date, parse_datetime as parse_datetime +from .._compat import is_union as _is_union +from .._compat import parse_date as parse_date +from .._compat import parse_datetime as parse_datetime _T = TypeVar("_T") _TupleT = TypeVar("_TupleT", bound=Tuple[object, ...]) diff --git a/src/openai/resources/__init__.py b/src/openai/resources/__init__.py index 2cdbeb6ae..e0f4f08d5 100644 --- a/src/openai/resources/__init__.py +++ b/src/openai/resources/__init__.py @@ -5,13 +5,48 @@ 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 b6ff4322d..76547b5f3 100644 --- a/src/openai/resources/audio/__init__.py +++ b/src/openai/resources/audio/__init__.py @@ -1,8 +1,18 @@ # 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 6b9242f0c..6f7226ee5 100644 --- a/src/openai/resources/audio/audio.py +++ b/src/openai/resources/audio/audio.py @@ -4,9 +4,19 @@ from typing import TYPE_CHECKING -from .speech import Speech, AsyncSpeech, SpeechWithRawResponse, AsyncSpeechWithRawResponse +from .speech import ( + Speech, + AsyncSpeech, + SpeechWithRawResponse, + AsyncSpeechWithRawResponse, +) from ..._resource import SyncAPIResource, AsyncAPIResource -from .translations import Translations, AsyncTranslations, TranslationsWithRawResponse, AsyncTranslationsWithRawResponse +from .translations import ( + Translations, + AsyncTranslations, + TranslationsWithRawResponse, + AsyncTranslationsWithRawResponse, +) from .transcriptions import ( Transcriptions, AsyncTranscriptions, diff --git a/src/openai/resources/audio/speech.py b/src/openai/resources/audio/speech.py index ac81a8077..458843866 100644 --- a/src/openai/resources/audio/speech.py +++ b/src/openai/resources/audio/speech.py @@ -7,21 +7,12 @@ import httpx -from ..._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ..._utils import maybe_transform 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, -) +from ..._base_client import HttpxBinaryResponseContent, make_request_options if TYPE_CHECKING: from ..._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/audio/transcriptions.py b/src/openai/resources/audio/transcriptions.py index 54be1c99a..d2b445241 100644 --- a/src/openai/resources/audio/transcriptions.py +++ b/src/openai/resources/audio/transcriptions.py @@ -7,21 +7,12 @@ import httpx -from ..._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, - FileTypes, -) +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from ..._utils import extract_files, maybe_transform, deepcopy_minimal 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, -) +from ..._base_client import make_request_options if TYPE_CHECKING: from ..._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/audio/translations.py b/src/openai/resources/audio/translations.py index c4489004a..fe7f7f2a4 100644 --- a/src/openai/resources/audio/translations.py +++ b/src/openai/resources/audio/translations.py @@ -7,21 +7,12 @@ import httpx -from ..._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, - FileTypes, -) +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from ..._utils import extract_files, maybe_transform, deepcopy_minimal 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, -) +from ..._base_client import make_request_options if TYPE_CHECKING: from ..._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/beta/__init__.py b/src/openai/resources/beta/__init__.py index 561f8bef6..55ad243cc 100644 --- a/src/openai/resources/beta/__init__.py +++ b/src/openai/resources/beta/__init__.py @@ -1,8 +1,18 @@ # 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 205b2cf0f..6efb0b21e 100644 --- a/src/openai/resources/beta/assistants/__init__.py +++ b/src/openai/resources/beta/assistants/__init__.py @@ -1,7 +1,12 @@ # 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 944019bed..efa711ecf 100644 --- a/src/openai/resources/beta/assistants/assistants.py +++ b/src/openai/resources/beta/assistants/assistants.py @@ -8,13 +8,7 @@ import httpx from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse -from ...._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ...._utils import maybe_transform from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_raw_response_wrapper, async_to_raw_response_wrapper @@ -26,10 +20,7 @@ assistant_create_params, assistant_update_params, ) -from ...._base_client import ( - AsyncPaginator, - make_request_options, -) +from ...._base_client import AsyncPaginator, make_request_options if TYPE_CHECKING: from ...._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/beta/assistants/files.py b/src/openai/resources/beta/assistants/files.py index 568258748..5ac5897ca 100644 --- a/src/openai/resources/beta/assistants/files.py +++ b/src/openai/resources/beta/assistants/files.py @@ -7,21 +7,12 @@ import httpx -from ...._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ...._utils import maybe_transform 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.assistants import ( AssistantFile, FileDeleteResponse, diff --git a/src/openai/resources/beta/beta.py b/src/openai/resources/beta/beta.py index 5cea6c146..b55256176 100644 --- a/src/openai/resources/beta/beta.py +++ b/src/openai/resources/beta/beta.py @@ -4,8 +4,18 @@ 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 .assistants import ( + Assistants, + AsyncAssistants, + AssistantsWithRawResponse, + AsyncAssistantsWithRawResponse, +) from ..._resource import SyncAPIResource, AsyncAPIResource if TYPE_CHECKING: diff --git a/src/openai/resources/beta/threads/__init__.py b/src/openai/resources/beta/threads/__init__.py index fe7c5e5a2..b9aaada46 100644 --- a/src/openai/resources/beta/threads/__init__.py +++ b/src/openai/resources/beta/threads/__init__.py @@ -1,8 +1,18 @@ # 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 cef618ed1..d8d4ce448 100644 --- a/src/openai/resources/beta/threads/messages/__init__.py +++ b/src/openai/resources/beta/threads/messages/__init__.py @@ -1,7 +1,12 @@ # 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 24c9680f3..e028a6fda 100644 --- a/src/openai/resources/beta/threads/messages/files.py +++ b/src/openai/resources/beta/threads/messages/files.py @@ -7,21 +7,12 @@ import httpx -from ....._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ....._utils import maybe_transform 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: diff --git a/src/openai/resources/beta/threads/messages/messages.py b/src/openai/resources/beta/threads/messages/messages.py index 9a6f5706c..30ae07251 100644 --- a/src/openai/resources/beta/threads/messages/messages.py +++ b/src/openai/resources/beta/threads/messages/messages.py @@ -8,21 +8,12 @@ import httpx from .files import Files, AsyncFiles, FilesWithRawResponse, AsyncFilesWithRawResponse -from ....._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ....._utils import maybe_transform 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 ( ThreadMessage, message_list_params, diff --git a/src/openai/resources/beta/threads/runs/runs.py b/src/openai/resources/beta/threads/runs/runs.py index 719e35ea4..969bfab70 100644 --- a/src/openai/resources/beta/threads/runs/runs.py +++ b/src/openai/resources/beta/threads/runs/runs.py @@ -8,21 +8,12 @@ import httpx from .steps import Steps, AsyncSteps, StepsWithRawResponse, AsyncStepsWithRawResponse -from ....._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ....._utils import maybe_transform 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, diff --git a/src/openai/resources/beta/threads/runs/steps.py b/src/openai/resources/beta/threads/runs/steps.py index f26034cf8..4fcc87a0f 100644 --- a/src/openai/resources/beta/threads/runs/steps.py +++ b/src/openai/resources/beta/threads/runs/steps.py @@ -7,21 +7,12 @@ import httpx -from ....._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from ....._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ....._utils import maybe_transform 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: diff --git a/src/openai/resources/beta/threads/threads.py b/src/openai/resources/beta/threads/threads.py index b37667485..9469fc051 100644 --- a/src/openai/resources/beta/threads/threads.py +++ b/src/openai/resources/beta/threads/threads.py @@ -7,14 +7,13 @@ import httpx from .runs import Runs, AsyncRuns, RunsWithRawResponse, AsyncRunsWithRawResponse -from .messages import Messages, AsyncMessages, MessagesWithRawResponse, AsyncMessagesWithRawResponse -from ...._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, +from .messages import ( + Messages, + AsyncMessages, + MessagesWithRawResponse, + AsyncMessagesWithRawResponse, ) +from ...._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ...._utils import maybe_transform from ...._resource import SyncAPIResource, AsyncAPIResource from ...._response import to_raw_response_wrapper, async_to_raw_response_wrapper @@ -25,9 +24,7 @@ thread_update_params, thread_create_and_run_params, ) -from ...._base_client import ( - make_request_options, -) +from ...._base_client import make_request_options from ....types.beta.threads import Run if TYPE_CHECKING: diff --git a/src/openai/resources/chat/__init__.py b/src/openai/resources/chat/__init__.py index 85b246509..2e56c0cbf 100644 --- a/src/openai/resources/chat/__init__.py +++ b/src/openai/resources/chat/__init__.py @@ -1,7 +1,12 @@ # 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 d93a501b1..3847b2051 100644 --- a/src/openai/resources/chat/chat.py +++ b/src/openai/resources/chat/chat.py @@ -5,7 +5,12 @@ from typing import TYPE_CHECKING from ..._resource import SyncAPIResource, AsyncAPIResource -from .completions import Completions, AsyncCompletions, CompletionsWithRawResponse, AsyncCompletionsWithRawResponse +from .completions import ( + Completions, + AsyncCompletions, + CompletionsWithRawResponse, + AsyncCompletionsWithRawResponse, +) if TYPE_CHECKING: from ..._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/chat/completions.py b/src/openai/resources/chat/completions.py index e29554c26..d0657b2f7 100644 --- a/src/openai/resources/chat/completions.py +++ b/src/openai/resources/chat/completions.py @@ -7,13 +7,7 @@ import httpx -from ..._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ..._utils import required_args, maybe_transform from ..._resource import SyncAPIResource, AsyncAPIResource from ..._response import to_raw_response_wrapper, async_to_raw_response_wrapper @@ -26,9 +20,7 @@ ChatCompletionToolChoiceOptionParam, completion_create_params, ) -from ..._base_client import ( - make_request_options, -) +from ..._base_client import make_request_options if TYPE_CHECKING: from ..._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/completions.py b/src/openai/resources/completions.py index 39484c6f7..baf6f04fe 100644 --- a/src/openai/resources/completions.py +++ b/src/openai/resources/completions.py @@ -8,20 +8,12 @@ import httpx from ..types import Completion, completion_create_params -from .._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import required_args, maybe_transform 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, -) +from .._base_client import make_request_options if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/edits.py b/src/openai/resources/edits.py index 587da02c8..eafaa82fd 100644 --- a/src/openai/resources/edits.py +++ b/src/openai/resources/edits.py @@ -9,19 +9,11 @@ import httpx from ..types import Edit, edit_create_params -from .._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import maybe_transform from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper -from .._base_client import ( - make_request_options, -) +from .._base_client import make_request_options if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/embeddings.py b/src/openai/resources/embeddings.py index 2ff3d3d44..c31ad9d93 100644 --- a/src/openai/resources/embeddings.py +++ b/src/openai/resources/embeddings.py @@ -9,20 +9,13 @@ import httpx from ..types import CreateEmbeddingResponse, embedding_create_params -from .._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import is_given, maybe_transform -from .._extras import numpy as np, has_numpy +from .._extras import numpy as np +from .._extras import 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, -) +from .._base_client import make_request_options if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/files.py b/src/openai/resources/files.py index b9f815af8..a6f75e5a4 100644 --- a/src/openai/resources/files.py +++ b/src/openai/resources/files.py @@ -9,20 +9,8 @@ import httpx -from ..types import ( - FileObject, - FileDeleted, - file_list_params, - file_create_params, -) -from .._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, - FileTypes, -) +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 .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper diff --git a/src/openai/resources/fine_tunes.py b/src/openai/resources/fine_tunes.py index f50d78717..91c8201cb 100644 --- a/src/openai/resources/fine_tunes.py +++ b/src/openai/resources/fine_tunes.py @@ -14,22 +14,13 @@ fine_tune_create_params, fine_tune_list_events_params, ) -from .._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import maybe_transform 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, -) +from .._base_client import AsyncPaginator, make_request_options if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/fine_tuning/__init__.py b/src/openai/resources/fine_tuning/__init__.py index 27445fb70..9133c25d4 100644 --- a/src/openai/resources/fine_tuning/__init__.py +++ b/src/openai/resources/fine_tuning/__init__.py @@ -1,7 +1,12 @@ # 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/jobs.py b/src/openai/resources/fine_tuning/jobs.py index 55eee6704..3d9aed8d9 100644 --- a/src/openai/resources/fine_tuning/jobs.py +++ b/src/openai/resources/fine_tuning/jobs.py @@ -7,21 +7,12 @@ import httpx -from ..._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from ..._types import NOT_GIVEN, Body, Query, Headers, NotGiven from ..._utils import maybe_transform 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, diff --git a/src/openai/resources/images.py b/src/openai/resources/images.py index 0e1313078..94b1bc1fc 100644 --- a/src/openai/resources/images.py +++ b/src/openai/resources/images.py @@ -13,20 +13,11 @@ image_generate_params, image_create_variation_params, ) -from .._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, - FileTypes, -) +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven, FileTypes from .._utils import extract_files, maybe_transform, deepcopy_minimal from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper -from .._base_client import ( - make_request_options, -) +from .._base_client import make_request_options if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/models.py b/src/openai/resources/models.py index a44a7ffbb..2d04bdc5c 100644 --- a/src/openai/resources/models.py +++ b/src/openai/resources/models.py @@ -7,20 +7,11 @@ import httpx from ..types import Model, ModelDeleted -from .._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven 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, -) +from .._base_client import AsyncPaginator, make_request_options if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/resources/moderations.py b/src/openai/resources/moderations.py index 9de7cd640..12a7c68a7 100644 --- a/src/openai/resources/moderations.py +++ b/src/openai/resources/moderations.py @@ -8,19 +8,11 @@ import httpx from ..types import ModerationCreateResponse, moderation_create_params -from .._types import ( - NOT_GIVEN, - Body, - Query, - Headers, - NotGiven, -) +from .._types import NOT_GIVEN, Body, Query, Headers, NotGiven from .._utils import maybe_transform from .._resource import SyncAPIResource, AsyncAPIResource from .._response import to_raw_response_wrapper, async_to_raw_response_wrapper -from .._base_client import ( - make_request_options, -) +from .._base_client import make_request_options if TYPE_CHECKING: from .._client import OpenAI, AsyncOpenAI diff --git a/src/openai/types/__init__.py b/src/openai/types/__init__.py index df2b58058..1b4fca26e 100644 --- a/src/openai/types/__init__.py +++ b/src/openai/types/__init__.py @@ -5,7 +5,8 @@ from .edit import Edit as Edit from .image import Image as Image from .model import Model as Model -from .shared import FunctionDefinition as FunctionDefinition, FunctionParameters as FunctionParameters +from .shared import FunctionDefinition as FunctionDefinition +from .shared import FunctionParameters as FunctionParameters from .embedding import Embedding as Embedding from .fine_tune import FineTune as FineTune from .completion import Completion as Completion @@ -27,8 +28,18 @@ 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 ba5f7fd8e..83afa060f 100644 --- a/src/openai/types/audio/__init__.py +++ b/src/openai/types/audio/__init__.py @@ -5,5 +5,9 @@ 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 e6742521e..c03d823b8 100644 --- a/src/openai/types/beta/__init__.py +++ b/src/openai/types/beta/__init__.py @@ -11,4 +11,6 @@ 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/threads/__init__.py b/src/openai/types/beta/threads/__init__.py index 8c77466de..0cb557a51 100644 --- a/src/openai/types/beta/threads/__init__.py +++ b/src/openai/types/beta/threads/__init__.py @@ -11,6 +11,12 @@ 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/runs/__init__.py b/src/openai/types/beta/threads/runs/__init__.py index 16cb85292..72b972a98 100644 --- a/src/openai/types/beta/threads/runs/__init__.py +++ b/src/openai/types/beta/threads/runs/__init__.py @@ -8,4 +8,6 @@ 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/chat/__init__.py b/src/openai/types/chat/__init__.py index 3f9091961..5fe182f41 100644 --- a/src/openai/types/chat/__init__.py +++ b/src/openai/types/chat/__init__.py @@ -7,13 +7,27 @@ 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_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_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_content_part_param.py b/src/openai/types/chat/chat_completion_content_part_param.py index 8e5823925..587578e2e 100644 --- a/src/openai/types/chat/chat_completion_content_part_param.py +++ b/src/openai/types/chat/chat_completion_content_part_param.py @@ -5,7 +5,9 @@ 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/completion_create_params.py b/src/openai/types/chat/completion_create_params.py index 0d8495b0c..69fe250ec 100644 --- a/src/openai/types/chat/completion_create_params.py +++ b/src/openai/types/chat/completion_create_params.py @@ -8,8 +8,12 @@ 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/tests/api_resources/beta/test_assistants.py b/tests/api_resources/beta/test_assistants.py index 97e74c61e..82e975b46 100644 --- a/tests/api_resources/beta/test_assistants.py +++ b/tests/api_resources/beta/test_assistants.py @@ -10,10 +10,7 @@ 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 860159ffb..8fa1fc20e 100644 --- a/tests/api_resources/beta/test_threads.py +++ b/tests/api_resources/beta/test_threads.py @@ -9,10 +9,7 @@ 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 39de3fa29..d323dfc35 100644 --- a/tests/api_resources/beta/threads/test_runs.py +++ b/tests/api_resources/beta/threads/test_runs.py @@ -10,9 +10,7 @@ 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 927ca9bbd..5716a23d5 100644 --- a/tests/api_resources/fine_tuning/test_jobs.py +++ b/tests/api_resources/fine_tuning/test_jobs.py @@ -10,10 +10,7 @@ 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/utils.py b/tests/utils.py index db2ca5601..b51379401 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -8,12 +8,7 @@ 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 From 2c8add64a261dea731bd162bb0cca222518d5440 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Thu, 7 Dec 2023 18:27:29 +0000 Subject: [PATCH 08/12] chore(internal): enable more lint rules (#945) --- pyproject.toml | 31 +++++++++++++++++++----------- requirements-dev.lock | 18 ++++++++++++++++- src/openai/__init__.py | 2 +- src/openai/_extras/numpy_proxy.py | 4 ++-- src/openai/_extras/pandas_proxy.py | 4 ++-- src/openai/_streaming.py | 4 ++-- src/openai/_types.py | 1 + src/openai/_utils/_utils.py | 8 +++++--- src/openai/cli/_progress.py | 2 +- src/openai/cli/_tools/migrate.py | 4 ++-- tests/test_client.py | 5 +++-- tests/test_module_client.py | 6 +++--- tests/test_utils/test_proxy.py | 2 +- tests/utils.py | 2 +- 14 files changed, 61 insertions(+), 32 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index c46822049..8fe6a69b6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -47,17 +47,18 @@ openai = "openai.cli:main" [tool.rye] managed = true +# version pins are in requirements-dev.lock dev-dependencies = [ - "pyright==1.1.332", - "mypy==1.7.1", - "black==23.3.0", - "respx==0.20.2", - "pytest==7.1.1", - "pytest-asyncio==0.21.1", - "ruff==0.0.282", - "isort==5.10.1", - "time-machine==2.9.0", - "nox==2023.4.22", + "pyright", + "mypy", + "black", + "respx", + "pytest", + "pytest-asyncio", + "ruff", + "isort", + "time-machine", + "nox", "dirty-equals>=0.6.0", "azure-identity >=1.14.1", "types-tqdm > 4" @@ -135,9 +136,11 @@ extra_standard_library = ["typing_extensions"] [tool.ruff] line-length = 120 -format = "grouped" +output-format = "grouped" target-version = "py37" select = [ + # bugbear rules + "B", # remove unused imports "F401", # bare except statements @@ -148,6 +151,12 @@ select = [ "T201", "T203", ] +ignore = [ + # lru_cache in methods, will be fixed separately + "B019", + # mutable defaults + "B006", +] unfixable = [ # disable auto fix for print statements "T201", diff --git a/requirements-dev.lock b/requirements-dev.lock index b1a9428a0..6df880557 100644 --- a/requirements-dev.lock +++ b/requirements-dev.lock @@ -11,11 +11,15 @@ annotated-types==0.6.0 anyio==4.1.0 argcomplete==3.1.2 attrs==23.1.0 +azure-core==1.29.5 azure-identity==1.15.0 black==23.3.0 certifi==2023.7.22 +cffi==1.16.0 +charset-normalizer==3.3.2 click==8.1.7 colorlog==6.7.0 +cryptography==41.0.7 dirty-equals==0.6.0 distlib==0.3.7 distro==1.8.0 @@ -27,31 +31,43 @@ httpx==0.25.2 idna==3.4 iniconfig==2.0.0 isort==5.10.1 +msal==1.26.0 +msal-extensions==1.0.0 mypy==1.7.1 mypy-extensions==1.0.0 nodeenv==1.8.0 nox==2023.4.22 +numpy==1.26.2 packaging==23.2 +pandas==2.1.3 +pandas-stubs==2.1.1.230928 pathspec==0.11.2 platformdirs==3.11.0 pluggy==1.3.0 +portalocker==2.8.2 py==1.11.0 +pycparser==2.21 pydantic==2.4.2 pydantic-core==2.10.1 +pyjwt==2.8.0 pyright==1.1.332 pytest==7.1.1 pytest-asyncio==0.21.1 python-dateutil==2.8.2 pytz==2023.3.post1 +requests==2.31.0 respx==0.20.2 -ruff==0.0.282 +ruff==0.1.7 six==1.16.0 sniffio==1.3.0 time-machine==2.9.0 tomli==2.0.1 tqdm==4.66.1 +types-pytz==2023.3.1.1 types-tqdm==4.66.0.2 typing-extensions==4.8.0 +tzdata==2023.3 +urllib3==2.1.0 virtualenv==20.24.5 # The following packages are considered to be unsafe in a requirements file: setuptools==68.2.2 diff --git a/src/openai/__init__.py b/src/openai/__init__.py index d92dfe969..d90f777cd 100644 --- a/src/openai/__init__.py +++ b/src/openai/__init__.py @@ -86,7 +86,7 @@ for __name in __all__: if not __name.startswith("__"): try: - setattr(__locals[__name], "__module__", "openai") + __locals[__name].__module__ = "openai" except (TypeError, AttributeError): # Some of our exported symbols are builtins which we can't set attributes for. pass diff --git a/src/openai/_extras/numpy_proxy.py b/src/openai/_extras/numpy_proxy.py index 408eaebd3..3809991c4 100644 --- a/src/openai/_extras/numpy_proxy.py +++ b/src/openai/_extras/numpy_proxy.py @@ -20,8 +20,8 @@ class NumpyProxy(LazyProxy[Any]): def __load__(self) -> Any: try: import numpy - except ImportError: - raise MissingDependencyError(NUMPY_INSTRUCTIONS) + except ImportError as err: + raise MissingDependencyError(NUMPY_INSTRUCTIONS) from err return numpy diff --git a/src/openai/_extras/pandas_proxy.py b/src/openai/_extras/pandas_proxy.py index 2fc0d2a7e..a24f7fb60 100644 --- a/src/openai/_extras/pandas_proxy.py +++ b/src/openai/_extras/pandas_proxy.py @@ -20,8 +20,8 @@ class PandasProxy(LazyProxy[Any]): def __load__(self) -> Any: try: import pandas - except ImportError: - raise MissingDependencyError(PANDAS_INSTRUCTIONS) + except ImportError as err: + raise MissingDependencyError(PANDAS_INSTRUCTIONS) from err return pandas diff --git a/src/openai/_streaming.py b/src/openai/_streaming.py index 095746630..e48324fc7 100644 --- a/src/openai/_streaming.py +++ b/src/openai/_streaming.py @@ -65,7 +65,7 @@ def __stream__(self) -> Iterator[ResponseT]: yield process_data(data=data, cast_to=cast_to, response=response) # Ensure the entire stream is consumed - for sse in iterator: + for _sse in iterator: ... @@ -120,7 +120,7 @@ async def __stream__(self) -> AsyncIterator[ResponseT]: yield process_data(data=data, cast_to=cast_to, response=response) # Ensure the entire stream is consumed - async for sse in iterator: + async for _sse in iterator: ... diff --git a/src/openai/_types.py b/src/openai/_types.py index 9e962a107..8d543171e 100644 --- a/src/openai/_types.py +++ b/src/openai/_types.py @@ -44,6 +44,7 @@ class BinaryResponseContent(ABC): + @abstractmethod def __init__( self, response: Any, diff --git a/src/openai/_utils/_utils.py b/src/openai/_utils/_utils.py index 83f88cc3e..c874d3682 100644 --- a/src/openai/_utils/_utils.py +++ b/src/openai/_utils/_utils.py @@ -194,8 +194,8 @@ def extract_type_arg(typ: type, index: int) -> type: args = get_args(typ) try: return cast(type, args[index]) - except IndexError: - raise RuntimeError(f"Expected type {typ} to have a type argument at index {index} but it did not") + except IndexError as err: + raise RuntimeError(f"Expected type {typ} to have a type argument at index {index} but it did not") from err def deepcopy_minimal(item: _T) -> _T: @@ -275,7 +275,9 @@ def wrapper(*args: object, **kwargs: object) -> object: try: given_params.add(positional[i]) except IndexError: - raise TypeError(f"{func.__name__}() takes {len(positional)} argument(s) but {len(args)} were given") + raise TypeError( + f"{func.__name__}() takes {len(positional)} argument(s) but {len(args)} were given" + ) from None for key in kwargs.keys(): given_params.add(key) diff --git a/src/openai/cli/_progress.py b/src/openai/cli/_progress.py index 390aaa9df..8a7f2525d 100644 --- a/src/openai/cli/_progress.py +++ b/src/openai/cli/_progress.py @@ -35,7 +35,7 @@ def read(self, n: int | None = -1) -> bytes: try: self._callback(self._progress) except Exception as e: # catches exception from the callback - raise CancelledError("The upload was cancelled: {}".format(e)) + raise CancelledError("The upload was cancelled: {}".format(e)) from e return chunk diff --git a/src/openai/cli/_tools/migrate.py b/src/openai/cli/_tools/migrate.py index 714bead8e..14773302e 100644 --- a/src/openai/cli/_tools/migrate.py +++ b/src/openai/cli/_tools/migrate.py @@ -41,7 +41,7 @@ def grit(args: GritArgs) -> None: except subprocess.CalledProcessError: # stdout and stderr are forwarded by subprocess so an error will already # have been displayed - raise SilentCLIError() + raise SilentCLIError() from None class MigrateArgs(BaseModel): @@ -57,7 +57,7 @@ def migrate(args: MigrateArgs) -> None: except subprocess.CalledProcessError: # stdout and stderr are forwarded by subprocess so an error will already # have been displayed - raise SilentCLIError() + raise SilentCLIError() from None # handles downloading the Grit CLI until they provide their own PyPi package diff --git a/tests/test_client.py b/tests/test_client.py index f8653507e..c633e5eab 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -19,6 +19,7 @@ from openai._models import BaseModel, FinalRequestOptions from openai._streaming import Stream, AsyncStream from openai._exceptions import ( + OpenAIError, APIStatusError, APITimeoutError, APIConnectionError, @@ -269,7 +270,7 @@ def test_validate_headers(self) -> None: request = client._build_request(FinalRequestOptions(method="get", url="/foo")) assert request.headers.get("Authorization") == f"Bearer {api_key}" - with pytest.raises(Exception): + with pytest.raises(OpenAIError): client2 = OpenAI(base_url=base_url, api_key=None, _strict_response_validation=True) _ = client2 @@ -934,7 +935,7 @@ def test_validate_headers(self) -> None: request = client._build_request(FinalRequestOptions(method="get", url="/foo")) assert request.headers.get("Authorization") == f"Bearer {api_key}" - with pytest.raises(Exception): + with pytest.raises(OpenAIError): client2 = AsyncOpenAI(base_url=base_url, api_key=None, _strict_response_validation=True) _ = client2 diff --git a/tests/test_module_client.py b/tests/test_module_client.py index 50b7369e1..40b0bde10 100644 --- a/tests/test_module_client.py +++ b/tests/test_module_client.py @@ -129,7 +129,7 @@ def test_azure_api_key_env_without_api_version() -> None: ValueError, match=r"Must provide either the `api_version` argument or the `OPENAI_API_VERSION` environment variable", ): - openai.completions._client + openai.completions._client # noqa: B018 def test_azure_api_key_and_version_env() -> None: @@ -142,7 +142,7 @@ def test_azure_api_key_and_version_env() -> None: ValueError, match=r"Must provide one of the `base_url` or `azure_endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable", ): - openai.completions._client + openai.completions._client # noqa: B018 def test_azure_api_key_version_and_endpoint_env() -> None: @@ -152,7 +152,7 @@ def test_azure_api_key_version_and_endpoint_env() -> None: _os.environ["OPENAI_API_VERSION"] = "example-version" _os.environ["AZURE_OPENAI_ENDPOINT"] = "https://www.example" - openai.completions._client + openai.completions._client # noqa: B018 assert openai.api_type == "azure" diff --git a/tests/test_utils/test_proxy.py b/tests/test_utils/test_proxy.py index 57c059150..aedd3731e 100644 --- a/tests/test_utils/test_proxy.py +++ b/tests/test_utils/test_proxy.py @@ -19,5 +19,5 @@ def test_recursive_proxy() -> None: assert repr(proxy) == "RecursiveLazyProxy" assert str(proxy) == "RecursiveLazyProxy" assert dir(proxy) == [] - assert getattr(type(proxy), "__name__") == "RecursiveLazyProxy" + assert type(proxy).__name__ == "RecursiveLazyProxy" assert type(operator.attrgetter("name.foo.bar.baz")(proxy)).__name__ == "RecursiveLazyProxy" diff --git a/tests/utils.py b/tests/utils.py index b51379401..57486c733 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -91,7 +91,7 @@ def assert_matches_type( traceback.print_exc() continue - assert False, "Did not match any variants" + raise AssertionError("Did not match any variants") elif issubclass(origin, BaseModel): assert isinstance(value, type_) assert assert_matches_model(type_, cast(Any, value), path=path) From 54f0ce0000abe32e97ae400f2975c028b8a84273 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 8 Dec 2023 00:49:21 +0000 Subject: [PATCH 09/12] docs: fix typo in example (#950) --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 4cabdb897..471fd88ab 100644 --- a/README.md +++ b/README.md @@ -109,7 +109,7 @@ from openai import AsyncOpenAI client = AsyncOpenAI() stream = await client.chat.completions.create( - prompt="Say this is a test", + model="gpt-4", messages=[{"role": "user", "content": "Say this is a test"}], stream=True, ) From c70e194f0a253409ec851607ae5219e3b5a8c442 Mon Sep 17 00:00:00 2001 From: Hao Cen Date: Fri, 8 Dec 2023 02:02:18 -0800 Subject: [PATCH 10/12] fix(errors): properly assign APIError.body (#949) Co-authored-by: Hao Cen --- src/openai/_exceptions.py | 1 + 1 file changed, 1 insertion(+) diff --git a/src/openai/_exceptions.py b/src/openai/_exceptions.py index b79ac5fd6..40b163270 100644 --- a/src/openai/_exceptions.py +++ b/src/openai/_exceptions.py @@ -48,6 +48,7 @@ def __init__(self, message: str, request: httpx.Request, *, body: object | None) super().__init__(message) self.request = request self.message = message + self.body = body if is_dict(body): self.code = cast(Any, body.get("code")) From e37ecca04040ce946822a7e40f5604532a59ee85 Mon Sep 17 00:00:00 2001 From: Stainless Bot <107565488+stainless-bot@users.noreply.github.com> Date: Fri, 8 Dec 2023 19:02:27 +0000 Subject: [PATCH 11/12] fix: avoid leaking memory when Client.with_options is used (#956) Fixes https://github.com/openai/openai-python/issues/865. --- pyproject.toml | 2 - src/openai/_base_client.py | 28 +++++---- src/openai/_client.py | 4 +- tests/test_client.py | 124 +++++++++++++++++++++++++++++++++++++ 4 files changed, 141 insertions(+), 17 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 8fe6a69b6..ab4928134 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -152,8 +152,6 @@ select = [ "T203", ] ignore = [ - # lru_cache in methods, will be fixed separately - "B019", # mutable defaults "B006", ] diff --git a/src/openai/_base_client.py b/src/openai/_base_client.py index 2e5678e8e..bbbb8a54a 100644 --- a/src/openai/_base_client.py +++ b/src/openai/_base_client.py @@ -403,14 +403,12 @@ def _build_headers(self, options: FinalRequestOptions) -> httpx.Headers: headers_dict = _merge_mappings(self.default_headers, custom_headers) self._validate_headers(headers_dict, custom_headers) + # headers are case-insensitive while dictionaries are not. headers = httpx.Headers(headers_dict) idempotency_header = self._idempotency_header if idempotency_header and options.method.lower() != "get" and idempotency_header not in headers: - if not options.idempotency_key: - options.idempotency_key = self._idempotency_key() - - headers[idempotency_header] = options.idempotency_key + headers[idempotency_header] = options.idempotency_key or self._idempotency_key() return headers @@ -594,16 +592,8 @@ def base_url(self) -> URL: def base_url(self, url: URL | str) -> None: self._base_url = self._enforce_trailing_slash(url if isinstance(url, URL) else URL(url)) - @lru_cache(maxsize=None) def platform_headers(self) -> Dict[str, str]: - return { - "X-Stainless-Lang": "python", - "X-Stainless-Package-Version": self._version, - "X-Stainless-OS": str(get_platform()), - "X-Stainless-Arch": str(get_architecture()), - "X-Stainless-Runtime": platform.python_implementation(), - "X-Stainless-Runtime-Version": platform.python_version(), - } + return platform_headers(self._version) def _calculate_retry_timeout( self, @@ -1691,6 +1681,18 @@ def get_platform() -> Platform: return "Unknown" +@lru_cache(maxsize=None) +def platform_headers(version: str) -> Dict[str, str]: + return { + "X-Stainless-Lang": "python", + "X-Stainless-Package-Version": version, + "X-Stainless-OS": str(get_platform()), + "X-Stainless-Arch": str(get_architecture()), + "X-Stainless-Runtime": platform.python_implementation(), + "X-Stainless-Runtime-Version": platform.python_version(), + } + + class OtherArch: def __init__(self, name: str) -> None: self.name = name diff --git a/src/openai/_client.py b/src/openai/_client.py index 202162070..8cf0fa679 100644 --- a/src/openai/_client.py +++ b/src/openai/_client.py @@ -192,7 +192,7 @@ def copy( return self.__class__( api_key=api_key or self.api_key, organization=organization or self.organization, - base_url=base_url or str(self.base_url), + base_url=base_url or self.base_url, timeout=self.timeout if isinstance(timeout, NotGiven) else timeout, http_client=http_client, max_retries=max_retries if is_given(max_retries) else self.max_retries, @@ -402,7 +402,7 @@ def copy( return self.__class__( api_key=api_key or self.api_key, organization=organization or self.organization, - base_url=base_url or str(self.base_url), + base_url=base_url or self.base_url, timeout=self.timeout if isinstance(timeout, NotGiven) else timeout, http_client=http_client, max_retries=max_retries if is_given(max_retries) else self.max_retries, diff --git a/tests/test_client.py b/tests/test_client.py index c633e5eab..cd374a49d 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -2,10 +2,12 @@ from __future__ import annotations +import gc import os import json import asyncio import inspect +import tracemalloc from typing import Any, Union, cast from unittest import mock @@ -195,6 +197,67 @@ def test_copy_signature(self) -> None: copy_param = copy_signature.parameters.get(name) assert copy_param is not None, f"copy() signature is missing the {name} param" + def test_copy_build_request(self) -> None: + options = FinalRequestOptions(method="get", url="/foo") + + def build_request(options: FinalRequestOptions) -> None: + client = self.client.copy() + client._build_request(options) + + # ensure that the machinery is warmed up before tracing starts. + build_request(options) + gc.collect() + + tracemalloc.start(1000) + + snapshot_before = tracemalloc.take_snapshot() + + ITERATIONS = 10 + for _ in range(ITERATIONS): + build_request(options) + gc.collect() + + snapshot_after = tracemalloc.take_snapshot() + + tracemalloc.stop() + + def add_leak(leaks: list[tracemalloc.StatisticDiff], diff: tracemalloc.StatisticDiff) -> None: + if diff.count == 0: + # Avoid false positives by considering only leaks (i.e. allocations that persist). + return + + if diff.count % ITERATIONS != 0: + # Avoid false positives by considering only leaks that appear per iteration. + return + + for frame in diff.traceback: + if any( + frame.filename.endswith(fragment) + for fragment in [ + # to_raw_response_wrapper leaks through the @functools.wraps() decorator. + # + # removing the decorator fixes the leak for reasons we don't understand. + "openai/_response.py", + # pydantic.BaseModel.model_dump || pydantic.BaseModel.dict leak memory for some reason. + "openai/_compat.py", + # Standard library leaks we don't care about. + "/logging/__init__.py", + ] + ): + return + + leaks.append(diff) + + leaks: list[tracemalloc.StatisticDiff] = [] + for diff in snapshot_after.compare_to(snapshot_before, "traceback"): + add_leak(leaks, diff) + if leaks: + for leak in leaks: + print("MEMORY LEAK:", leak) + for frame in leak.traceback: + print(frame) + raise AssertionError() + def test_request_timeout(self) -> None: request = self.client._build_request(FinalRequestOptions(method="get", url="/foo")) timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore @@ -858,6 +921,67 @@ def test_copy_signature(self) -> None: copy_param = copy_signature.parameters.get(name) assert copy_param is not None, f"copy() signature is missing the {name} param" + def test_copy_build_request(self) -> None: + options = FinalRequestOptions(method="get", url="/foo") + + def build_request(options: FinalRequestOptions) -> None: + client = self.client.copy() + client._build_request(options) + + # ensure that the machinery is warmed up before tracing starts. + build_request(options) + gc.collect() + + tracemalloc.start(1000) + + snapshot_before = tracemalloc.take_snapshot() + + ITERATIONS = 10 + for _ in range(ITERATIONS): + build_request(options) + gc.collect() + + snapshot_after = tracemalloc.take_snapshot() + + tracemalloc.stop() + + def add_leak(leaks: list[tracemalloc.StatisticDiff], diff: tracemalloc.StatisticDiff) -> None: + if diff.count == 0: + # Avoid false positives by considering only leaks (i.e. allocations that persist). + return + + if diff.count % ITERATIONS != 0: + # Avoid false positives by considering only leaks that appear per iteration. + return + + for frame in diff.traceback: + if any( + frame.filename.endswith(fragment) + for fragment in [ + # to_raw_response_wrapper leaks through the @functools.wraps() decorator. + # + # removing the decorator fixes the leak for reasons we don't understand. + "openai/_response.py", + # pydantic.BaseModel.model_dump || pydantic.BaseModel.dict leak memory for some reason. + "openai/_compat.py", + # Standard library leaks we don't care about. + "/logging/__init__.py", + ] + ): + return + + leaks.append(diff) + + leaks: list[tracemalloc.StatisticDiff] = [] + for diff in snapshot_after.compare_to(snapshot_before, "traceback"): + add_leak(leaks, diff) + if leaks: + for leak in leaks: + print("MEMORY LEAK:", leak) + for frame in leak.traceback: + print(frame) + raise AssertionError() + async def test_request_timeout(self) -> None: request = self.client._build_request(FinalRequestOptions(method="get", url="/foo")) timeout = httpx.Timeout(**request.extensions["timeout"]) # type: ignore From 3717c7fcf9933b05bd622fc440afe1aba5ad72a3 Mon Sep 17 00:00:00 2001 From: Sahand Sojoodi Date: Fri, 8 Dec 2023 18:12:31 -0500 Subject: [PATCH 12/12] Small Improvement in the async chat response code. --- README.md | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index 4cabdb897..b7f278fe5 100644 --- a/README.md +++ b/README.md @@ -108,14 +108,17 @@ from openai import AsyncOpenAI client = AsyncOpenAI() -stream = await client.chat.completions.create( - prompt="Say this is a test", - messages=[{"role": "user", "content": "Say this is a test"}], - stream=True, -) -async for chunk in stream: - if chunk.choices[0].delta.content is not None: - print(chunk.choices[0].delta.content) +async def main(): + stream = await client.chat.completions.create( + model="gpt-4", + messages=[{"role": "user", "content": "Say this is a test"}], + stream=True, + ) + async for chunk in stream: + if chunk.choices[0].delta.content is not None: + print(chunk.choices[0].delta.content) + +asyncio.run(main()) ``` ## Module-level client