Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +14 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/__init__.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/__main__.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_base_client.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_client.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_compat.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_constants.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_exceptions.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_files.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_legacy_response.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_models.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_module_client.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_qs.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_resource.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_response.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_streaming.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_types.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_version.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/pagination.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/version.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_extras/__init__.py +3 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_extras/__pycache__/__init__.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_extras/__pycache__/_common.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_extras/__pycache__/numpy_proxy.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_extras/__pycache__/pandas_proxy.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_extras/__pycache__/sounddevice_proxy.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_extras/_common.py +21 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_extras/numpy_proxy.py +37 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_extras/pandas_proxy.py +28 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_extras/sounddevice_proxy.py +28 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_utils/__init__.py +61 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_utils/__pycache__/__init__.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_utils/__pycache__/_logs.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_utils/__pycache__/_proxy.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_utils/__pycache__/_reflection.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_utils/__pycache__/_resources_proxy.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_utils/__pycache__/_streams.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_utils/__pycache__/_sync.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_utils/__pycache__/_transform.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_utils/__pycache__/_typing.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_utils/__pycache__/_utils.cpython-312.pyc +0 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_utils/_logs.py +42 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_utils/_proxy.py +65 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_utils/_reflection.py +45 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_utils/_resources_proxy.py +24 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_utils/_streams.py +12 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_utils/_sync.py +86 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_utils/_transform.py +453 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_utils/_typing.py +156 -0
- tool_server/.venv/lib/python3.12/site-packages/openai/_utils/_utils.py +438 -0
.gitattributes
CHANGED
|
@@ -4492,3 +4492,17 @@ tool_server/.venv/lib/python3.12/site-packages/torch/nn/modules/__pycache__/modu
|
|
| 4492 |
tool_server/.venv/lib/python3.12/site-packages/torch/nn/parallel/__pycache__/distributed.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 4493 |
tool_server/.venv/lib/python3.12/site-packages/torch/onnx/__pycache__/symbolic_opset9.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 4494 |
tool_server/.venv/lib/python3.12/site-packages/torch/sparse/__pycache__/_triton_ops_meta.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4492 |
tool_server/.venv/lib/python3.12/site-packages/torch/nn/parallel/__pycache__/distributed.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 4493 |
tool_server/.venv/lib/python3.12/site-packages/torch/onnx/__pycache__/symbolic_opset9.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 4494 |
tool_server/.venv/lib/python3.12/site-packages/torch/sparse/__pycache__/_triton_ops_meta.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 4495 |
+
tool_server/.venv/lib/python3.12/site-packages/torch/testing/_internal/__pycache__/common_methods_invocations.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 4496 |
+
tool_server/.venv/lib/python3.12/site-packages/torch/testing/_internal/__pycache__/common_modules.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 4497 |
+
tool_server/.venv/lib/python3.12/site-packages/torch/testing/_internal/__pycache__/common_nn.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 4498 |
+
tool_server/.venv/lib/python3.12/site-packages/torch/testing/_internal/__pycache__/common_quantization.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 4499 |
+
tool_server/.venv/lib/python3.12/site-packages/torch/testing/_internal/__pycache__/common_utils.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 4500 |
+
tool_server/.venv/lib/python3.12/site-packages/torch/testing/_internal/distributed/__pycache__/distributed_test.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 4501 |
+
tool_server/.venv/lib/python3.12/site-packages/torch/testing/_internal/distributed/rpc/__pycache__/dist_autograd_test.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 4502 |
+
tool_server/.venv/lib/python3.12/site-packages/torch/testing/_internal/distributed/rpc/__pycache__/rpc_test.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 4503 |
+
tool_server/.venv/lib/python3.12/site-packages/torch/testing/_internal/generated/__pycache__/annotated_fn_args.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 4504 |
+
tool_server/.venv/lib/python3.12/site-packages/torch/testing/_internal/opinfo/__pycache__/core.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 4505 |
+
tool_server/.venv/lib/python3.12/site-packages/torch/utils/__pycache__/cpp_extension.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 4506 |
+
tool_server/.venv/lib/python3.12/site-packages/torch/utils/hipify/__pycache__/cuda_to_hip_mappings.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 4507 |
+
tool_server/.venv/lib/python3.12/site-packages/torchgen/__pycache__/gen.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
| 4508 |
+
tool_server/.venv/lib/python3.12/site-packages/torchgen/__pycache__/model.cpython-312.pyc filter=lfs diff=lfs merge=lfs -text
|
tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (12.3 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/__main__.cpython-312.pyc
ADDED
|
Binary file (230 Bytes). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_base_client.cpython-312.pyc
ADDED
|
Binary file (73.1 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_client.cpython-312.pyc
ADDED
|
Binary file (50.6 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_compat.cpython-312.pyc
ADDED
|
Binary file (8.26 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_constants.cpython-312.pyc
ADDED
|
Binary file (706 Bytes). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_exceptions.cpython-312.pyc
ADDED
|
Binary file (7.56 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_files.cpython-312.pyc
ADDED
|
Binary file (6.12 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_legacy_response.cpython-312.pyc
ADDED
|
Binary file (22.7 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_models.cpython-312.pyc
ADDED
|
Binary file (31.2 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_module_client.cpython-312.pyc
ADDED
|
Binary file (9.95 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_qs.cpython-312.pyc
ADDED
|
Binary file (5.83 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_resource.cpython-312.pyc
ADDED
|
Binary file (2.14 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_response.cpython-312.pyc
ADDED
|
Binary file (37.2 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_streaming.cpython-312.pyc
ADDED
|
Binary file (17.1 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_types.cpython-312.pyc
ADDED
|
Binary file (8.77 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/_version.cpython-312.pyc
ADDED
|
Binary file (234 Bytes). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/pagination.cpython-312.pyc
ADDED
|
Binary file (6.65 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/__pycache__/version.cpython-312.pyc
ADDED
|
Binary file (284 Bytes). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/_extras/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .numpy_proxy import numpy as numpy, has_numpy as has_numpy
|
| 2 |
+
from .pandas_proxy import pandas as pandas
|
| 3 |
+
from .sounddevice_proxy import sounddevice as sounddevice
|
tool_server/.venv/lib/python3.12/site-packages/openai/_extras/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (346 Bytes). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/_extras/__pycache__/_common.cpython-312.pyc
ADDED
|
Binary file (841 Bytes). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/_extras/__pycache__/numpy_proxy.cpython-312.pyc
ADDED
|
Binary file (1.39 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/_extras/__pycache__/pandas_proxy.cpython-312.pyc
ADDED
|
Binary file (1.17 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/_extras/__pycache__/sounddevice_proxy.cpython-312.pyc
ADDED
|
Binary file (1.21 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/_extras/_common.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .._exceptions import OpenAIError
|
| 2 |
+
|
| 3 |
+
INSTRUCTIONS = """
|
| 4 |
+
|
| 5 |
+
OpenAI error:
|
| 6 |
+
|
| 7 |
+
missing `{library}`
|
| 8 |
+
|
| 9 |
+
This feature requires additional dependencies:
|
| 10 |
+
|
| 11 |
+
$ pip install openai[{extra}]
|
| 12 |
+
|
| 13 |
+
"""
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def format_instructions(*, library: str, extra: str) -> str:
|
| 17 |
+
return INSTRUCTIONS.format(library=library, extra=extra)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class MissingDependencyError(OpenAIError):
|
| 21 |
+
pass
|
tool_server/.venv/lib/python3.12/site-packages/openai/_extras/numpy_proxy.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING, Any
|
| 4 |
+
from typing_extensions import override
|
| 5 |
+
|
| 6 |
+
from .._utils import LazyProxy
|
| 7 |
+
from ._common import MissingDependencyError, format_instructions
|
| 8 |
+
|
| 9 |
+
if TYPE_CHECKING:
|
| 10 |
+
import numpy as numpy
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
NUMPY_INSTRUCTIONS = format_instructions(library="numpy", extra="voice_helpers")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class NumpyProxy(LazyProxy[Any]):
|
| 17 |
+
@override
|
| 18 |
+
def __load__(self) -> Any:
|
| 19 |
+
try:
|
| 20 |
+
import numpy
|
| 21 |
+
except ImportError as err:
|
| 22 |
+
raise MissingDependencyError(NUMPY_INSTRUCTIONS) from err
|
| 23 |
+
|
| 24 |
+
return numpy
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
if not TYPE_CHECKING:
|
| 28 |
+
numpy = NumpyProxy()
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def has_numpy() -> bool:
|
| 32 |
+
try:
|
| 33 |
+
import numpy # noqa: F401 # pyright: ignore[reportUnusedImport]
|
| 34 |
+
except ImportError:
|
| 35 |
+
return False
|
| 36 |
+
|
| 37 |
+
return True
|
tool_server/.venv/lib/python3.12/site-packages/openai/_extras/pandas_proxy.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING, Any
|
| 4 |
+
from typing_extensions import override
|
| 5 |
+
|
| 6 |
+
from .._utils import LazyProxy
|
| 7 |
+
from ._common import MissingDependencyError, format_instructions
|
| 8 |
+
|
| 9 |
+
if TYPE_CHECKING:
|
| 10 |
+
import pandas as pandas
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
PANDAS_INSTRUCTIONS = format_instructions(library="pandas", extra="datalib")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class PandasProxy(LazyProxy[Any]):
|
| 17 |
+
@override
|
| 18 |
+
def __load__(self) -> Any:
|
| 19 |
+
try:
|
| 20 |
+
import pandas
|
| 21 |
+
except ImportError as err:
|
| 22 |
+
raise MissingDependencyError(PANDAS_INSTRUCTIONS) from err
|
| 23 |
+
|
| 24 |
+
return pandas
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
if not TYPE_CHECKING:
|
| 28 |
+
pandas = PandasProxy()
|
tool_server/.venv/lib/python3.12/site-packages/openai/_extras/sounddevice_proxy.py
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import TYPE_CHECKING, Any
|
| 4 |
+
from typing_extensions import override
|
| 5 |
+
|
| 6 |
+
from .._utils import LazyProxy
|
| 7 |
+
from ._common import MissingDependencyError, format_instructions
|
| 8 |
+
|
| 9 |
+
if TYPE_CHECKING:
|
| 10 |
+
import sounddevice as sounddevice # type: ignore
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
SOUNDDEVICE_INSTRUCTIONS = format_instructions(library="sounddevice", extra="voice_helpers")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class SounddeviceProxy(LazyProxy[Any]):
|
| 17 |
+
@override
|
| 18 |
+
def __load__(self) -> Any:
|
| 19 |
+
try:
|
| 20 |
+
import sounddevice # type: ignore
|
| 21 |
+
except ImportError as err:
|
| 22 |
+
raise MissingDependencyError(SOUNDDEVICE_INSTRUCTIONS) from err
|
| 23 |
+
|
| 24 |
+
return sounddevice
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
if not TYPE_CHECKING:
|
| 28 |
+
sounddevice = SounddeviceProxy()
|
tool_server/.venv/lib/python3.12/site-packages/openai/_utils/__init__.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from ._logs import SensitiveHeadersFilter as SensitiveHeadersFilter
|
| 2 |
+
from ._sync import asyncify as asyncify
|
| 3 |
+
from ._proxy import LazyProxy as LazyProxy
|
| 4 |
+
from ._utils import (
|
| 5 |
+
flatten as flatten,
|
| 6 |
+
is_dict as is_dict,
|
| 7 |
+
is_list as is_list,
|
| 8 |
+
is_given as is_given,
|
| 9 |
+
is_tuple as is_tuple,
|
| 10 |
+
json_safe as json_safe,
|
| 11 |
+
lru_cache as lru_cache,
|
| 12 |
+
is_mapping as is_mapping,
|
| 13 |
+
is_tuple_t as is_tuple_t,
|
| 14 |
+
parse_date as parse_date,
|
| 15 |
+
is_iterable as is_iterable,
|
| 16 |
+
is_sequence as is_sequence,
|
| 17 |
+
coerce_float as coerce_float,
|
| 18 |
+
is_mapping_t as is_mapping_t,
|
| 19 |
+
removeprefix as removeprefix,
|
| 20 |
+
removesuffix as removesuffix,
|
| 21 |
+
extract_files as extract_files,
|
| 22 |
+
is_sequence_t as is_sequence_t,
|
| 23 |
+
required_args as required_args,
|
| 24 |
+
coerce_boolean as coerce_boolean,
|
| 25 |
+
coerce_integer as coerce_integer,
|
| 26 |
+
file_from_path as file_from_path,
|
| 27 |
+
parse_datetime as parse_datetime,
|
| 28 |
+
is_azure_client as is_azure_client,
|
| 29 |
+
strip_not_given as strip_not_given,
|
| 30 |
+
deepcopy_minimal as deepcopy_minimal,
|
| 31 |
+
get_async_library as get_async_library,
|
| 32 |
+
maybe_coerce_float as maybe_coerce_float,
|
| 33 |
+
get_required_header as get_required_header,
|
| 34 |
+
maybe_coerce_boolean as maybe_coerce_boolean,
|
| 35 |
+
maybe_coerce_integer as maybe_coerce_integer,
|
| 36 |
+
is_async_azure_client as is_async_azure_client,
|
| 37 |
+
)
|
| 38 |
+
from ._typing import (
|
| 39 |
+
is_list_type as is_list_type,
|
| 40 |
+
is_union_type as is_union_type,
|
| 41 |
+
extract_type_arg as extract_type_arg,
|
| 42 |
+
is_iterable_type as is_iterable_type,
|
| 43 |
+
is_required_type as is_required_type,
|
| 44 |
+
is_sequence_type as is_sequence_type,
|
| 45 |
+
is_annotated_type as is_annotated_type,
|
| 46 |
+
is_type_alias_type as is_type_alias_type,
|
| 47 |
+
strip_annotated_type as strip_annotated_type,
|
| 48 |
+
extract_type_var_from_base as extract_type_var_from_base,
|
| 49 |
+
)
|
| 50 |
+
from ._streams import consume_sync_iterator as consume_sync_iterator, consume_async_iterator as consume_async_iterator
|
| 51 |
+
from ._transform import (
|
| 52 |
+
PropertyInfo as PropertyInfo,
|
| 53 |
+
transform as transform,
|
| 54 |
+
async_transform as async_transform,
|
| 55 |
+
maybe_transform as maybe_transform,
|
| 56 |
+
async_maybe_transform as async_maybe_transform,
|
| 57 |
+
)
|
| 58 |
+
from ._reflection import (
|
| 59 |
+
function_has_argument as function_has_argument,
|
| 60 |
+
assert_signatures_in_sync as assert_signatures_in_sync,
|
| 61 |
+
)
|
tool_server/.venv/lib/python3.12/site-packages/openai/_utils/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (1.81 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/_utils/__pycache__/_logs.cpython-312.pyc
ADDED
|
Binary file (2.59 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/_utils/__pycache__/_proxy.cpython-312.pyc
ADDED
|
Binary file (3.34 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/_utils/__pycache__/_reflection.cpython-312.pyc
ADDED
|
Binary file (2.24 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/_utils/__pycache__/_resources_proxy.cpython-312.pyc
ADDED
|
Binary file (1.18 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/_utils/__pycache__/_streams.cpython-312.pyc
ADDED
|
Binary file (748 Bytes). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/_utils/__pycache__/_sync.cpython-312.pyc
ADDED
|
Binary file (3.84 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/_utils/__pycache__/_transform.cpython-312.pyc
ADDED
|
Binary file (15.3 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/_utils/__pycache__/_typing.cpython-312.pyc
ADDED
|
Binary file (5.56 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/_utils/__pycache__/_utils.cpython-312.pyc
ADDED
|
Binary file (17.2 kB). View file
|
|
|
tool_server/.venv/lib/python3.12/site-packages/openai/_utils/_logs.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import logging
|
| 3 |
+
from typing_extensions import override
|
| 4 |
+
|
| 5 |
+
from ._utils import is_dict
|
| 6 |
+
|
| 7 |
+
logger: logging.Logger = logging.getLogger("openai")
|
| 8 |
+
httpx_logger: logging.Logger = logging.getLogger("httpx")
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
SENSITIVE_HEADERS = {"api-key", "authorization"}
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def _basic_config() -> None:
|
| 15 |
+
# e.g. [2023-10-05 14:12:26 - openai._base_client:818 - DEBUG] HTTP Request: POST http://127.0.0.1:4010/foo/bar "200 OK"
|
| 16 |
+
logging.basicConfig(
|
| 17 |
+
format="[%(asctime)s - %(name)s:%(lineno)d - %(levelname)s] %(message)s",
|
| 18 |
+
datefmt="%Y-%m-%d %H:%M:%S",
|
| 19 |
+
)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def setup_logging() -> None:
|
| 23 |
+
env = os.environ.get("OPENAI_LOG")
|
| 24 |
+
if env == "debug":
|
| 25 |
+
_basic_config()
|
| 26 |
+
logger.setLevel(logging.DEBUG)
|
| 27 |
+
httpx_logger.setLevel(logging.DEBUG)
|
| 28 |
+
elif env == "info":
|
| 29 |
+
_basic_config()
|
| 30 |
+
logger.setLevel(logging.INFO)
|
| 31 |
+
httpx_logger.setLevel(logging.INFO)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class SensitiveHeadersFilter(logging.Filter):
|
| 35 |
+
@override
|
| 36 |
+
def filter(self, record: logging.LogRecord) -> bool:
|
| 37 |
+
if is_dict(record.args) and "headers" in record.args and is_dict(record.args["headers"]):
|
| 38 |
+
headers = record.args["headers"] = {**record.args["headers"]}
|
| 39 |
+
for header in headers:
|
| 40 |
+
if str(header).lower() in SENSITIVE_HEADERS:
|
| 41 |
+
headers[header] = "<redacted>"
|
| 42 |
+
return True
|
tool_server/.venv/lib/python3.12/site-packages/openai/_utils/_proxy.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from abc import ABC, abstractmethod
|
| 4 |
+
from typing import Generic, TypeVar, Iterable, cast
|
| 5 |
+
from typing_extensions import override
|
| 6 |
+
|
| 7 |
+
T = TypeVar("T")
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class LazyProxy(Generic[T], ABC):
|
| 11 |
+
"""Implements data methods to pretend that an instance is another instance.
|
| 12 |
+
|
| 13 |
+
This includes forwarding attribute access and other methods.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
# Note: we have to special case proxies that themselves return proxies
|
| 17 |
+
# to support using a proxy as a catch-all for any random access, e.g. `proxy.foo.bar.baz`
|
| 18 |
+
|
| 19 |
+
def __getattr__(self, attr: str) -> object:
|
| 20 |
+
proxied = self.__get_proxied__()
|
| 21 |
+
if isinstance(proxied, LazyProxy):
|
| 22 |
+
return proxied # pyright: ignore
|
| 23 |
+
return getattr(proxied, attr)
|
| 24 |
+
|
| 25 |
+
@override
|
| 26 |
+
def __repr__(self) -> str:
|
| 27 |
+
proxied = self.__get_proxied__()
|
| 28 |
+
if isinstance(proxied, LazyProxy):
|
| 29 |
+
return proxied.__class__.__name__
|
| 30 |
+
return repr(self.__get_proxied__())
|
| 31 |
+
|
| 32 |
+
@override
|
| 33 |
+
def __str__(self) -> str:
|
| 34 |
+
proxied = self.__get_proxied__()
|
| 35 |
+
if isinstance(proxied, LazyProxy):
|
| 36 |
+
return proxied.__class__.__name__
|
| 37 |
+
return str(proxied)
|
| 38 |
+
|
| 39 |
+
@override
|
| 40 |
+
def __dir__(self) -> Iterable[str]:
|
| 41 |
+
proxied = self.__get_proxied__()
|
| 42 |
+
if isinstance(proxied, LazyProxy):
|
| 43 |
+
return []
|
| 44 |
+
return proxied.__dir__()
|
| 45 |
+
|
| 46 |
+
@property # type: ignore
|
| 47 |
+
@override
|
| 48 |
+
def __class__(self) -> type: # pyright: ignore
|
| 49 |
+
try:
|
| 50 |
+
proxied = self.__get_proxied__()
|
| 51 |
+
except Exception:
|
| 52 |
+
return type(self)
|
| 53 |
+
if issubclass(type(proxied), LazyProxy):
|
| 54 |
+
return type(proxied)
|
| 55 |
+
return proxied.__class__
|
| 56 |
+
|
| 57 |
+
def __get_proxied__(self) -> T:
|
| 58 |
+
return self.__load__()
|
| 59 |
+
|
| 60 |
+
def __as_proxied__(self) -> T:
|
| 61 |
+
"""Helper method that returns the current proxy, typed as the loaded object"""
|
| 62 |
+
return cast(T, self)
|
| 63 |
+
|
| 64 |
+
@abstractmethod
|
| 65 |
+
def __load__(self) -> T: ...
|
tool_server/.venv/lib/python3.12/site-packages/openai/_utils/_reflection.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import inspect
|
| 4 |
+
from typing import Any, Callable
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def function_has_argument(func: Callable[..., Any], arg_name: str) -> bool:
|
| 8 |
+
"""Returns whether or not the given function has a specific parameter"""
|
| 9 |
+
sig = inspect.signature(func)
|
| 10 |
+
return arg_name in sig.parameters
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def assert_signatures_in_sync(
|
| 14 |
+
source_func: Callable[..., Any],
|
| 15 |
+
check_func: Callable[..., Any],
|
| 16 |
+
*,
|
| 17 |
+
exclude_params: set[str] = set(),
|
| 18 |
+
description: str = "",
|
| 19 |
+
) -> None:
|
| 20 |
+
"""Ensure that the signature of the second function matches the first."""
|
| 21 |
+
|
| 22 |
+
check_sig = inspect.signature(check_func)
|
| 23 |
+
source_sig = inspect.signature(source_func)
|
| 24 |
+
|
| 25 |
+
errors: list[str] = []
|
| 26 |
+
|
| 27 |
+
for name, source_param in source_sig.parameters.items():
|
| 28 |
+
if name in exclude_params:
|
| 29 |
+
continue
|
| 30 |
+
|
| 31 |
+
custom_param = check_sig.parameters.get(name)
|
| 32 |
+
if not custom_param:
|
| 33 |
+
errors.append(f"the `{name}` param is missing")
|
| 34 |
+
continue
|
| 35 |
+
|
| 36 |
+
if custom_param.annotation != source_param.annotation:
|
| 37 |
+
errors.append(
|
| 38 |
+
f"types for the `{name}` param are do not match; source={repr(source_param.annotation)} checking={repr(custom_param.annotation)}"
|
| 39 |
+
)
|
| 40 |
+
continue
|
| 41 |
+
|
| 42 |
+
if errors:
|
| 43 |
+
raise AssertionError(
|
| 44 |
+
f"{len(errors)} errors encountered when comparing signatures{description}:\n\n" + "\n\n".join(errors)
|
| 45 |
+
)
|
tool_server/.venv/lib/python3.12/site-packages/openai/_utils/_resources_proxy.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Any
|
| 4 |
+
from typing_extensions import override
|
| 5 |
+
|
| 6 |
+
from ._proxy import LazyProxy
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class ResourcesProxy(LazyProxy[Any]):
|
| 10 |
+
"""A proxy for the `openai.resources` module.
|
| 11 |
+
|
| 12 |
+
This is used so that we can lazily import `openai.resources` only when
|
| 13 |
+
needed *and* so that users can just import `openai` and reference `openai.resources`
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
@override
|
| 17 |
+
def __load__(self) -> Any:
|
| 18 |
+
import importlib
|
| 19 |
+
|
| 20 |
+
mod = importlib.import_module("openai.resources")
|
| 21 |
+
return mod
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
resources = ResourcesProxy().__as_proxied__()
|
tool_server/.venv/lib/python3.12/site-packages/openai/_utils/_streams.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from typing import Any
|
| 2 |
+
from typing_extensions import Iterator, AsyncIterator
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def consume_sync_iterator(iterator: Iterator[Any]) -> None:
|
| 6 |
+
for _ in iterator:
|
| 7 |
+
...
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
async def consume_async_iterator(iterator: AsyncIterator[Any]) -> None:
|
| 11 |
+
async for _ in iterator:
|
| 12 |
+
...
|
tool_server/.venv/lib/python3.12/site-packages/openai/_utils/_sync.py
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
import asyncio
|
| 5 |
+
import functools
|
| 6 |
+
import contextvars
|
| 7 |
+
from typing import Any, TypeVar, Callable, Awaitable
|
| 8 |
+
from typing_extensions import ParamSpec
|
| 9 |
+
|
| 10 |
+
import anyio
|
| 11 |
+
import sniffio
|
| 12 |
+
import anyio.to_thread
|
| 13 |
+
|
| 14 |
+
T_Retval = TypeVar("T_Retval")
|
| 15 |
+
T_ParamSpec = ParamSpec("T_ParamSpec")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
if sys.version_info >= (3, 9):
|
| 19 |
+
_asyncio_to_thread = asyncio.to_thread
|
| 20 |
+
else:
|
| 21 |
+
# backport of https://docs.python.org/3/library/asyncio-task.html#asyncio.to_thread
|
| 22 |
+
# for Python 3.8 support
|
| 23 |
+
async def _asyncio_to_thread(
|
| 24 |
+
func: Callable[T_ParamSpec, T_Retval], /, *args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs
|
| 25 |
+
) -> Any:
|
| 26 |
+
"""Asynchronously run function *func* in a separate thread.
|
| 27 |
+
|
| 28 |
+
Any *args and **kwargs supplied for this function are directly passed
|
| 29 |
+
to *func*. Also, the current :class:`contextvars.Context` is propagated,
|
| 30 |
+
allowing context variables from the main thread to be accessed in the
|
| 31 |
+
separate thread.
|
| 32 |
+
|
| 33 |
+
Returns a coroutine that can be awaited to get the eventual result of *func*.
|
| 34 |
+
"""
|
| 35 |
+
loop = asyncio.events.get_running_loop()
|
| 36 |
+
ctx = contextvars.copy_context()
|
| 37 |
+
func_call = functools.partial(ctx.run, func, *args, **kwargs)
|
| 38 |
+
return await loop.run_in_executor(None, func_call)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
async def to_thread(
|
| 42 |
+
func: Callable[T_ParamSpec, T_Retval], /, *args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs
|
| 43 |
+
) -> T_Retval:
|
| 44 |
+
if sniffio.current_async_library() == "asyncio":
|
| 45 |
+
return await _asyncio_to_thread(func, *args, **kwargs)
|
| 46 |
+
|
| 47 |
+
return await anyio.to_thread.run_sync(
|
| 48 |
+
functools.partial(func, *args, **kwargs),
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
# inspired by `asyncer`, https://github.com/tiangolo/asyncer
|
| 53 |
+
def asyncify(function: Callable[T_ParamSpec, T_Retval]) -> Callable[T_ParamSpec, Awaitable[T_Retval]]:
|
| 54 |
+
"""
|
| 55 |
+
Take a blocking function and create an async one that receives the same
|
| 56 |
+
positional and keyword arguments. For python version 3.9 and above, it uses
|
| 57 |
+
asyncio.to_thread to run the function in a separate thread. For python version
|
| 58 |
+
3.8, it uses locally defined copy of the asyncio.to_thread function which was
|
| 59 |
+
introduced in python 3.9.
|
| 60 |
+
|
| 61 |
+
Usage:
|
| 62 |
+
|
| 63 |
+
```python
|
| 64 |
+
def blocking_func(arg1, arg2, kwarg1=None):
|
| 65 |
+
# blocking code
|
| 66 |
+
return result
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
result = asyncify(blocking_function)(arg1, arg2, kwarg1=value1)
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
+
## Arguments
|
| 73 |
+
|
| 74 |
+
`function`: a blocking regular callable (e.g. a function)
|
| 75 |
+
|
| 76 |
+
## Return
|
| 77 |
+
|
| 78 |
+
An async function that takes the same positional and keyword arguments as the
|
| 79 |
+
original one, that when called runs the same original function in a thread worker
|
| 80 |
+
and returns the result.
|
| 81 |
+
"""
|
| 82 |
+
|
| 83 |
+
async def wrapper(*args: T_ParamSpec.args, **kwargs: T_ParamSpec.kwargs) -> T_Retval:
|
| 84 |
+
return await to_thread(function, *args, **kwargs)
|
| 85 |
+
|
| 86 |
+
return wrapper
|
tool_server/.venv/lib/python3.12/site-packages/openai/_utils/_transform.py
ADDED
|
@@ -0,0 +1,453 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import io
|
| 4 |
+
import base64
|
| 5 |
+
import pathlib
|
| 6 |
+
from typing import Any, Mapping, TypeVar, cast
|
| 7 |
+
from datetime import date, datetime
|
| 8 |
+
from typing_extensions import Literal, get_args, override, get_type_hints as _get_type_hints
|
| 9 |
+
|
| 10 |
+
import anyio
|
| 11 |
+
import pydantic
|
| 12 |
+
|
| 13 |
+
from ._utils import (
|
| 14 |
+
is_list,
|
| 15 |
+
is_given,
|
| 16 |
+
lru_cache,
|
| 17 |
+
is_mapping,
|
| 18 |
+
is_iterable,
|
| 19 |
+
is_sequence,
|
| 20 |
+
)
|
| 21 |
+
from .._files import is_base64_file_input
|
| 22 |
+
from ._typing import (
|
| 23 |
+
is_list_type,
|
| 24 |
+
is_union_type,
|
| 25 |
+
extract_type_arg,
|
| 26 |
+
is_iterable_type,
|
| 27 |
+
is_required_type,
|
| 28 |
+
is_sequence_type,
|
| 29 |
+
is_annotated_type,
|
| 30 |
+
strip_annotated_type,
|
| 31 |
+
)
|
| 32 |
+
from .._compat import get_origin, model_dump, is_typeddict
|
| 33 |
+
|
| 34 |
+
_T = TypeVar("_T")
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
# TODO: support for drilling globals() and locals()
|
| 38 |
+
# TODO: ensure works correctly with forward references in all cases
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
PropertyFormat = Literal["iso8601", "base64", "custom"]
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class PropertyInfo:
|
| 45 |
+
"""Metadata class to be used in Annotated types to provide information about a given type.
|
| 46 |
+
|
| 47 |
+
For example:
|
| 48 |
+
|
| 49 |
+
class MyParams(TypedDict):
|
| 50 |
+
account_holder_name: Annotated[str, PropertyInfo(alias='accountHolderName')]
|
| 51 |
+
|
| 52 |
+
This means that {'account_holder_name': 'Robert'} will be transformed to {'accountHolderName': 'Robert'} before being sent to the API.
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
alias: str | None
|
| 56 |
+
format: PropertyFormat | None
|
| 57 |
+
format_template: str | None
|
| 58 |
+
discriminator: str | None
|
| 59 |
+
|
| 60 |
+
def __init__(
|
| 61 |
+
self,
|
| 62 |
+
*,
|
| 63 |
+
alias: str | None = None,
|
| 64 |
+
format: PropertyFormat | None = None,
|
| 65 |
+
format_template: str | None = None,
|
| 66 |
+
discriminator: str | None = None,
|
| 67 |
+
) -> None:
|
| 68 |
+
self.alias = alias
|
| 69 |
+
self.format = format
|
| 70 |
+
self.format_template = format_template
|
| 71 |
+
self.discriminator = discriminator
|
| 72 |
+
|
| 73 |
+
@override
|
| 74 |
+
def __repr__(self) -> str:
|
| 75 |
+
return f"{self.__class__.__name__}(alias='{self.alias}', format={self.format}, format_template='{self.format_template}', discriminator='{self.discriminator}')"
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def maybe_transform(
|
| 79 |
+
data: object,
|
| 80 |
+
expected_type: object,
|
| 81 |
+
) -> Any | None:
|
| 82 |
+
"""Wrapper over `transform()` that allows `None` to be passed.
|
| 83 |
+
|
| 84 |
+
See `transform()` for more details.
|
| 85 |
+
"""
|
| 86 |
+
if data is None:
|
| 87 |
+
return None
|
| 88 |
+
return transform(data, expected_type)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
# Wrapper over _transform_recursive providing fake types
|
| 92 |
+
def transform(
|
| 93 |
+
data: _T,
|
| 94 |
+
expected_type: object,
|
| 95 |
+
) -> _T:
|
| 96 |
+
"""Transform dictionaries based off of type information from the given type, for example:
|
| 97 |
+
|
| 98 |
+
```py
|
| 99 |
+
class Params(TypedDict, total=False):
|
| 100 |
+
card_id: Required[Annotated[str, PropertyInfo(alias="cardID")]]
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
transformed = transform({"card_id": "<my card ID>"}, Params)
|
| 104 |
+
# {'cardID': '<my card ID>'}
|
| 105 |
+
```
|
| 106 |
+
|
| 107 |
+
Any keys / data that does not have type information given will be included as is.
|
| 108 |
+
|
| 109 |
+
It should be noted that the transformations that this function does are not represented in the type system.
|
| 110 |
+
"""
|
| 111 |
+
transformed = _transform_recursive(data, annotation=cast(type, expected_type))
|
| 112 |
+
return cast(_T, transformed)
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
@lru_cache(maxsize=8096)
|
| 116 |
+
def _get_annotated_type(type_: type) -> type | None:
|
| 117 |
+
"""If the given type is an `Annotated` type then it is returned, if not `None` is returned.
|
| 118 |
+
|
| 119 |
+
This also unwraps the type when applicable, e.g. `Required[Annotated[T, ...]]`
|
| 120 |
+
"""
|
| 121 |
+
if is_required_type(type_):
|
| 122 |
+
# Unwrap `Required[Annotated[T, ...]]` to `Annotated[T, ...]`
|
| 123 |
+
type_ = get_args(type_)[0]
|
| 124 |
+
|
| 125 |
+
if is_annotated_type(type_):
|
| 126 |
+
return type_
|
| 127 |
+
|
| 128 |
+
return None
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def _maybe_transform_key(key: str, type_: type) -> str:
|
| 132 |
+
"""Transform the given `data` based on the annotations provided in `type_`.
|
| 133 |
+
|
| 134 |
+
Note: this function only looks at `Annotated` types that contain `PropertyInfo` metadata.
|
| 135 |
+
"""
|
| 136 |
+
annotated_type = _get_annotated_type(type_)
|
| 137 |
+
if annotated_type is None:
|
| 138 |
+
# no `Annotated` definition for this type, no transformation needed
|
| 139 |
+
return key
|
| 140 |
+
|
| 141 |
+
# ignore the first argument as it is the actual type
|
| 142 |
+
annotations = get_args(annotated_type)[1:]
|
| 143 |
+
for annotation in annotations:
|
| 144 |
+
if isinstance(annotation, PropertyInfo) and annotation.alias is not None:
|
| 145 |
+
return annotation.alias
|
| 146 |
+
|
| 147 |
+
return key
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def _no_transform_needed(annotation: type) -> bool:
|
| 151 |
+
return annotation == float or annotation == int
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def _transform_recursive(
|
| 155 |
+
data: object,
|
| 156 |
+
*,
|
| 157 |
+
annotation: type,
|
| 158 |
+
inner_type: type | None = None,
|
| 159 |
+
) -> object:
|
| 160 |
+
"""Transform the given data against the expected type.
|
| 161 |
+
|
| 162 |
+
Args:
|
| 163 |
+
annotation: The direct type annotation given to the particular piece of data.
|
| 164 |
+
This may or may not be wrapped in metadata types, e.g. `Required[T]`, `Annotated[T, ...]` etc
|
| 165 |
+
|
| 166 |
+
inner_type: If applicable, this is the "inside" type. This is useful in certain cases where the outside type
|
| 167 |
+
is a container type such as `List[T]`. In that case `inner_type` should be set to `T` so that each entry in
|
| 168 |
+
the list can be transformed using the metadata from the container type.
|
| 169 |
+
|
| 170 |
+
Defaults to the same value as the `annotation` argument.
|
| 171 |
+
"""
|
| 172 |
+
if inner_type is None:
|
| 173 |
+
inner_type = annotation
|
| 174 |
+
|
| 175 |
+
stripped_type = strip_annotated_type(inner_type)
|
| 176 |
+
origin = get_origin(stripped_type) or stripped_type
|
| 177 |
+
if is_typeddict(stripped_type) and is_mapping(data):
|
| 178 |
+
return _transform_typeddict(data, stripped_type)
|
| 179 |
+
|
| 180 |
+
if origin == dict and is_mapping(data):
|
| 181 |
+
items_type = get_args(stripped_type)[1]
|
| 182 |
+
return {key: _transform_recursive(value, annotation=items_type) for key, value in data.items()}
|
| 183 |
+
|
| 184 |
+
if (
|
| 185 |
+
# List[T]
|
| 186 |
+
(is_list_type(stripped_type) and is_list(data))
|
| 187 |
+
# Iterable[T]
|
| 188 |
+
or (is_iterable_type(stripped_type) and is_iterable(data) and not isinstance(data, str))
|
| 189 |
+
# Sequence[T]
|
| 190 |
+
or (is_sequence_type(stripped_type) and is_sequence(data) and not isinstance(data, str))
|
| 191 |
+
):
|
| 192 |
+
# dicts are technically iterable, but it is an iterable on the keys of the dict and is not usually
|
| 193 |
+
# intended as an iterable, so we don't transform it.
|
| 194 |
+
if isinstance(data, dict):
|
| 195 |
+
return cast(object, data)
|
| 196 |
+
|
| 197 |
+
inner_type = extract_type_arg(stripped_type, 0)
|
| 198 |
+
if _no_transform_needed(inner_type):
|
| 199 |
+
# for some types there is no need to transform anything, so we can get a small
|
| 200 |
+
# perf boost from skipping that work.
|
| 201 |
+
#
|
| 202 |
+
# but we still need to convert to a list to ensure the data is json-serializable
|
| 203 |
+
if is_list(data):
|
| 204 |
+
return data
|
| 205 |
+
return list(data)
|
| 206 |
+
|
| 207 |
+
return [_transform_recursive(d, annotation=annotation, inner_type=inner_type) for d in data]
|
| 208 |
+
|
| 209 |
+
if is_union_type(stripped_type):
|
| 210 |
+
# For union types we run the transformation against all subtypes to ensure that everything is transformed.
|
| 211 |
+
#
|
| 212 |
+
# TODO: there may be edge cases where the same normalized field name will transform to two different names
|
| 213 |
+
# in different subtypes.
|
| 214 |
+
for subtype in get_args(stripped_type):
|
| 215 |
+
data = _transform_recursive(data, annotation=annotation, inner_type=subtype)
|
| 216 |
+
return data
|
| 217 |
+
|
| 218 |
+
if isinstance(data, pydantic.BaseModel):
|
| 219 |
+
return model_dump(data, exclude_unset=True, mode="json", exclude=getattr(data, "__api_exclude__", None))
|
| 220 |
+
|
| 221 |
+
annotated_type = _get_annotated_type(annotation)
|
| 222 |
+
if annotated_type is None:
|
| 223 |
+
return data
|
| 224 |
+
|
| 225 |
+
# ignore the first argument as it is the actual type
|
| 226 |
+
annotations = get_args(annotated_type)[1:]
|
| 227 |
+
for annotation in annotations:
|
| 228 |
+
if isinstance(annotation, PropertyInfo) and annotation.format is not None:
|
| 229 |
+
return _format_data(data, annotation.format, annotation.format_template)
|
| 230 |
+
|
| 231 |
+
return data
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def _format_data(data: object, format_: PropertyFormat, format_template: str | None) -> object:
|
| 235 |
+
if isinstance(data, (date, datetime)):
|
| 236 |
+
if format_ == "iso8601":
|
| 237 |
+
return data.isoformat()
|
| 238 |
+
|
| 239 |
+
if format_ == "custom" and format_template is not None:
|
| 240 |
+
return data.strftime(format_template)
|
| 241 |
+
|
| 242 |
+
if format_ == "base64" and is_base64_file_input(data):
|
| 243 |
+
binary: str | bytes | None = None
|
| 244 |
+
|
| 245 |
+
if isinstance(data, pathlib.Path):
|
| 246 |
+
binary = data.read_bytes()
|
| 247 |
+
elif isinstance(data, io.IOBase):
|
| 248 |
+
binary = data.read()
|
| 249 |
+
|
| 250 |
+
if isinstance(binary, str): # type: ignore[unreachable]
|
| 251 |
+
binary = binary.encode()
|
| 252 |
+
|
| 253 |
+
if not isinstance(binary, bytes):
|
| 254 |
+
raise RuntimeError(f"Could not read bytes from {data}; Received {type(binary)}")
|
| 255 |
+
|
| 256 |
+
return base64.b64encode(binary).decode("ascii")
|
| 257 |
+
|
| 258 |
+
return data
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def _transform_typeddict(
|
| 262 |
+
data: Mapping[str, object],
|
| 263 |
+
expected_type: type,
|
| 264 |
+
) -> Mapping[str, object]:
|
| 265 |
+
result: dict[str, object] = {}
|
| 266 |
+
annotations = get_type_hints(expected_type, include_extras=True)
|
| 267 |
+
for key, value in data.items():
|
| 268 |
+
if not is_given(value):
|
| 269 |
+
# we don't need to include `NotGiven` values here as they'll
|
| 270 |
+
# be stripped out before the request is sent anyway
|
| 271 |
+
continue
|
| 272 |
+
|
| 273 |
+
type_ = annotations.get(key)
|
| 274 |
+
if type_ is None:
|
| 275 |
+
# we do not have a type annotation for this field, leave it as is
|
| 276 |
+
result[key] = value
|
| 277 |
+
else:
|
| 278 |
+
result[_maybe_transform_key(key, type_)] = _transform_recursive(value, annotation=type_)
|
| 279 |
+
return result
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
async def async_maybe_transform(
|
| 283 |
+
data: object,
|
| 284 |
+
expected_type: object,
|
| 285 |
+
) -> Any | None:
|
| 286 |
+
"""Wrapper over `async_transform()` that allows `None` to be passed.
|
| 287 |
+
|
| 288 |
+
See `async_transform()` for more details.
|
| 289 |
+
"""
|
| 290 |
+
if data is None:
|
| 291 |
+
return None
|
| 292 |
+
return await async_transform(data, expected_type)
|
| 293 |
+
|
| 294 |
+
|
| 295 |
+
async def async_transform(
|
| 296 |
+
data: _T,
|
| 297 |
+
expected_type: object,
|
| 298 |
+
) -> _T:
|
| 299 |
+
"""Transform dictionaries based off of type information from the given type, for example:
|
| 300 |
+
|
| 301 |
+
```py
|
| 302 |
+
class Params(TypedDict, total=False):
|
| 303 |
+
card_id: Required[Annotated[str, PropertyInfo(alias="cardID")]]
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
transformed = transform({"card_id": "<my card ID>"}, Params)
|
| 307 |
+
# {'cardID': '<my card ID>'}
|
| 308 |
+
```
|
| 309 |
+
|
| 310 |
+
Any keys / data that does not have type information given will be included as is.
|
| 311 |
+
|
| 312 |
+
It should be noted that the transformations that this function does are not represented in the type system.
|
| 313 |
+
"""
|
| 314 |
+
transformed = await _async_transform_recursive(data, annotation=cast(type, expected_type))
|
| 315 |
+
return cast(_T, transformed)
|
| 316 |
+
|
| 317 |
+
|
| 318 |
+
async def _async_transform_recursive(
|
| 319 |
+
data: object,
|
| 320 |
+
*,
|
| 321 |
+
annotation: type,
|
| 322 |
+
inner_type: type | None = None,
|
| 323 |
+
) -> object:
|
| 324 |
+
"""Transform the given data against the expected type.
|
| 325 |
+
|
| 326 |
+
Args:
|
| 327 |
+
annotation: The direct type annotation given to the particular piece of data.
|
| 328 |
+
This may or may not be wrapped in metadata types, e.g. `Required[T]`, `Annotated[T, ...]` etc
|
| 329 |
+
|
| 330 |
+
inner_type: If applicable, this is the "inside" type. This is useful in certain cases where the outside type
|
| 331 |
+
is a container type such as `List[T]`. In that case `inner_type` should be set to `T` so that each entry in
|
| 332 |
+
the list can be transformed using the metadata from the container type.
|
| 333 |
+
|
| 334 |
+
Defaults to the same value as the `annotation` argument.
|
| 335 |
+
"""
|
| 336 |
+
if inner_type is None:
|
| 337 |
+
inner_type = annotation
|
| 338 |
+
|
| 339 |
+
stripped_type = strip_annotated_type(inner_type)
|
| 340 |
+
origin = get_origin(stripped_type) or stripped_type
|
| 341 |
+
if is_typeddict(stripped_type) and is_mapping(data):
|
| 342 |
+
return await _async_transform_typeddict(data, stripped_type)
|
| 343 |
+
|
| 344 |
+
if origin == dict and is_mapping(data):
|
| 345 |
+
items_type = get_args(stripped_type)[1]
|
| 346 |
+
return {key: _transform_recursive(value, annotation=items_type) for key, value in data.items()}
|
| 347 |
+
|
| 348 |
+
if (
|
| 349 |
+
# List[T]
|
| 350 |
+
(is_list_type(stripped_type) and is_list(data))
|
| 351 |
+
# Iterable[T]
|
| 352 |
+
or (is_iterable_type(stripped_type) and is_iterable(data) and not isinstance(data, str))
|
| 353 |
+
# Sequence[T]
|
| 354 |
+
or (is_sequence_type(stripped_type) and is_sequence(data) and not isinstance(data, str))
|
| 355 |
+
):
|
| 356 |
+
# dicts are technically iterable, but it is an iterable on the keys of the dict and is not usually
|
| 357 |
+
# intended as an iterable, so we don't transform it.
|
| 358 |
+
if isinstance(data, dict):
|
| 359 |
+
return cast(object, data)
|
| 360 |
+
|
| 361 |
+
inner_type = extract_type_arg(stripped_type, 0)
|
| 362 |
+
if _no_transform_needed(inner_type):
|
| 363 |
+
# for some types there is no need to transform anything, so we can get a small
|
| 364 |
+
# perf boost from skipping that work.
|
| 365 |
+
#
|
| 366 |
+
# but we still need to convert to a list to ensure the data is json-serializable
|
| 367 |
+
if is_list(data):
|
| 368 |
+
return data
|
| 369 |
+
return list(data)
|
| 370 |
+
|
| 371 |
+
return [await _async_transform_recursive(d, annotation=annotation, inner_type=inner_type) for d in data]
|
| 372 |
+
|
| 373 |
+
if is_union_type(stripped_type):
|
| 374 |
+
# For union types we run the transformation against all subtypes to ensure that everything is transformed.
|
| 375 |
+
#
|
| 376 |
+
# TODO: there may be edge cases where the same normalized field name will transform to two different names
|
| 377 |
+
# in different subtypes.
|
| 378 |
+
for subtype in get_args(stripped_type):
|
| 379 |
+
data = await _async_transform_recursive(data, annotation=annotation, inner_type=subtype)
|
| 380 |
+
return data
|
| 381 |
+
|
| 382 |
+
if isinstance(data, pydantic.BaseModel):
|
| 383 |
+
return model_dump(data, exclude_unset=True, mode="json")
|
| 384 |
+
|
| 385 |
+
annotated_type = _get_annotated_type(annotation)
|
| 386 |
+
if annotated_type is None:
|
| 387 |
+
return data
|
| 388 |
+
|
| 389 |
+
# ignore the first argument as it is the actual type
|
| 390 |
+
annotations = get_args(annotated_type)[1:]
|
| 391 |
+
for annotation in annotations:
|
| 392 |
+
if isinstance(annotation, PropertyInfo) and annotation.format is not None:
|
| 393 |
+
return await _async_format_data(data, annotation.format, annotation.format_template)
|
| 394 |
+
|
| 395 |
+
return data
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
async def _async_format_data(data: object, format_: PropertyFormat, format_template: str | None) -> object:
|
| 399 |
+
if isinstance(data, (date, datetime)):
|
| 400 |
+
if format_ == "iso8601":
|
| 401 |
+
return data.isoformat()
|
| 402 |
+
|
| 403 |
+
if format_ == "custom" and format_template is not None:
|
| 404 |
+
return data.strftime(format_template)
|
| 405 |
+
|
| 406 |
+
if format_ == "base64" and is_base64_file_input(data):
|
| 407 |
+
binary: str | bytes | None = None
|
| 408 |
+
|
| 409 |
+
if isinstance(data, pathlib.Path):
|
| 410 |
+
binary = await anyio.Path(data).read_bytes()
|
| 411 |
+
elif isinstance(data, io.IOBase):
|
| 412 |
+
binary = data.read()
|
| 413 |
+
|
| 414 |
+
if isinstance(binary, str): # type: ignore[unreachable]
|
| 415 |
+
binary = binary.encode()
|
| 416 |
+
|
| 417 |
+
if not isinstance(binary, bytes):
|
| 418 |
+
raise RuntimeError(f"Could not read bytes from {data}; Received {type(binary)}")
|
| 419 |
+
|
| 420 |
+
return base64.b64encode(binary).decode("ascii")
|
| 421 |
+
|
| 422 |
+
return data
|
| 423 |
+
|
| 424 |
+
|
| 425 |
+
async def _async_transform_typeddict(
|
| 426 |
+
data: Mapping[str, object],
|
| 427 |
+
expected_type: type,
|
| 428 |
+
) -> Mapping[str, object]:
|
| 429 |
+
result: dict[str, object] = {}
|
| 430 |
+
annotations = get_type_hints(expected_type, include_extras=True)
|
| 431 |
+
for key, value in data.items():
|
| 432 |
+
if not is_given(value):
|
| 433 |
+
# we don't need to include `NotGiven` values here as they'll
|
| 434 |
+
# be stripped out before the request is sent anyway
|
| 435 |
+
continue
|
| 436 |
+
|
| 437 |
+
type_ = annotations.get(key)
|
| 438 |
+
if type_ is None:
|
| 439 |
+
# we do not have a type annotation for this field, leave it as is
|
| 440 |
+
result[key] = value
|
| 441 |
+
else:
|
| 442 |
+
result[_maybe_transform_key(key, type_)] = await _async_transform_recursive(value, annotation=type_)
|
| 443 |
+
return result
|
| 444 |
+
|
| 445 |
+
|
| 446 |
+
@lru_cache(maxsize=8096)
|
| 447 |
+
def get_type_hints(
|
| 448 |
+
obj: Any,
|
| 449 |
+
globalns: dict[str, Any] | None = None,
|
| 450 |
+
localns: Mapping[str, Any] | None = None,
|
| 451 |
+
include_extras: bool = False,
|
| 452 |
+
) -> dict[str, Any]:
|
| 453 |
+
return _get_type_hints(obj, globalns=globalns, localns=localns, include_extras=include_extras)
|
tool_server/.venv/lib/python3.12/site-packages/openai/_utils/_typing.py
ADDED
|
@@ -0,0 +1,156 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
import typing
|
| 5 |
+
import typing_extensions
|
| 6 |
+
from typing import Any, TypeVar, Iterable, cast
|
| 7 |
+
from collections import abc as _c_abc
|
| 8 |
+
from typing_extensions import (
|
| 9 |
+
TypeIs,
|
| 10 |
+
Required,
|
| 11 |
+
Annotated,
|
| 12 |
+
get_args,
|
| 13 |
+
get_origin,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
from ._utils import lru_cache
|
| 17 |
+
from .._types import InheritsGeneric
|
| 18 |
+
from .._compat import is_union as _is_union
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def is_annotated_type(typ: type) -> bool:
|
| 22 |
+
return get_origin(typ) == Annotated
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def is_list_type(typ: type) -> bool:
|
| 26 |
+
return (get_origin(typ) or typ) == list
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def is_sequence_type(typ: type) -> bool:
|
| 30 |
+
origin = get_origin(typ) or typ
|
| 31 |
+
return origin == typing_extensions.Sequence or origin == typing.Sequence or origin == _c_abc.Sequence
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def is_iterable_type(typ: type) -> bool:
|
| 35 |
+
"""If the given type is `typing.Iterable[T]`"""
|
| 36 |
+
origin = get_origin(typ) or typ
|
| 37 |
+
return origin == Iterable or origin == _c_abc.Iterable
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def is_union_type(typ: type) -> bool:
|
| 41 |
+
return _is_union(get_origin(typ))
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def is_required_type(typ: type) -> bool:
|
| 45 |
+
return get_origin(typ) == Required
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def is_typevar(typ: type) -> bool:
|
| 49 |
+
# type ignore is required because type checkers
|
| 50 |
+
# think this expression will always return False
|
| 51 |
+
return type(typ) == TypeVar # type: ignore
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
_TYPE_ALIAS_TYPES: tuple[type[typing_extensions.TypeAliasType], ...] = (typing_extensions.TypeAliasType,)
|
| 55 |
+
if sys.version_info >= (3, 12):
|
| 56 |
+
_TYPE_ALIAS_TYPES = (*_TYPE_ALIAS_TYPES, typing.TypeAliasType)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def is_type_alias_type(tp: Any, /) -> TypeIs[typing_extensions.TypeAliasType]:
|
| 60 |
+
"""Return whether the provided argument is an instance of `TypeAliasType`.
|
| 61 |
+
|
| 62 |
+
```python
|
| 63 |
+
type Int = int
|
| 64 |
+
is_type_alias_type(Int)
|
| 65 |
+
# > True
|
| 66 |
+
Str = TypeAliasType("Str", str)
|
| 67 |
+
is_type_alias_type(Str)
|
| 68 |
+
# > True
|
| 69 |
+
```
|
| 70 |
+
"""
|
| 71 |
+
return isinstance(tp, _TYPE_ALIAS_TYPES)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
# Extracts T from Annotated[T, ...] or from Required[Annotated[T, ...]]
|
| 75 |
+
@lru_cache(maxsize=8096)
|
| 76 |
+
def strip_annotated_type(typ: type) -> type:
|
| 77 |
+
if is_required_type(typ) or is_annotated_type(typ):
|
| 78 |
+
return strip_annotated_type(cast(type, get_args(typ)[0]))
|
| 79 |
+
|
| 80 |
+
return typ
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
def extract_type_arg(typ: type, index: int) -> type:
|
| 84 |
+
args = get_args(typ)
|
| 85 |
+
try:
|
| 86 |
+
return cast(type, args[index])
|
| 87 |
+
except IndexError as err:
|
| 88 |
+
raise RuntimeError(f"Expected type {typ} to have a type argument at index {index} but it did not") from err
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def extract_type_var_from_base(
|
| 92 |
+
typ: type,
|
| 93 |
+
*,
|
| 94 |
+
generic_bases: tuple[type, ...],
|
| 95 |
+
index: int,
|
| 96 |
+
failure_message: str | None = None,
|
| 97 |
+
) -> type:
|
| 98 |
+
"""Given a type like `Foo[T]`, returns the generic type variable `T`.
|
| 99 |
+
|
| 100 |
+
This also handles the case where a concrete subclass is given, e.g.
|
| 101 |
+
```py
|
| 102 |
+
class MyResponse(Foo[bytes]):
|
| 103 |
+
...
|
| 104 |
+
|
| 105 |
+
extract_type_var(MyResponse, bases=(Foo,), index=0) -> bytes
|
| 106 |
+
```
|
| 107 |
+
|
| 108 |
+
And where a generic subclass is given:
|
| 109 |
+
```py
|
| 110 |
+
_T = TypeVar('_T')
|
| 111 |
+
class MyResponse(Foo[_T]):
|
| 112 |
+
...
|
| 113 |
+
|
| 114 |
+
extract_type_var(MyResponse[bytes], bases=(Foo,), index=0) -> bytes
|
| 115 |
+
```
|
| 116 |
+
"""
|
| 117 |
+
cls = cast(object, get_origin(typ) or typ)
|
| 118 |
+
if cls in generic_bases: # pyright: ignore[reportUnnecessaryContains]
|
| 119 |
+
# we're given the class directly
|
| 120 |
+
return extract_type_arg(typ, index)
|
| 121 |
+
|
| 122 |
+
# if a subclass is given
|
| 123 |
+
# ---
|
| 124 |
+
# this is needed as __orig_bases__ is not present in the typeshed stubs
|
| 125 |
+
# because it is intended to be for internal use only, however there does
|
| 126 |
+
# not seem to be a way to resolve generic TypeVars for inherited subclasses
|
| 127 |
+
# without using it.
|
| 128 |
+
if isinstance(cls, InheritsGeneric):
|
| 129 |
+
target_base_class: Any | None = None
|
| 130 |
+
for base in cls.__orig_bases__:
|
| 131 |
+
if base.__origin__ in generic_bases:
|
| 132 |
+
target_base_class = base
|
| 133 |
+
break
|
| 134 |
+
|
| 135 |
+
if target_base_class is None:
|
| 136 |
+
raise RuntimeError(
|
| 137 |
+
"Could not find the generic base class;\n"
|
| 138 |
+
"This should never happen;\n"
|
| 139 |
+
f"Does {cls} inherit from one of {generic_bases} ?"
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
extracted = extract_type_arg(target_base_class, index)
|
| 143 |
+
if is_typevar(extracted):
|
| 144 |
+
# If the extracted type argument is itself a type variable
|
| 145 |
+
# then that means the subclass itself is generic, so we have
|
| 146 |
+
# to resolve the type argument from the class itself, not
|
| 147 |
+
# the base class.
|
| 148 |
+
#
|
| 149 |
+
# Note: if there is more than 1 type argument, the subclass could
|
| 150 |
+
# change the ordering of the type arguments, this is not currently
|
| 151 |
+
# supported.
|
| 152 |
+
return extract_type_arg(typ, index)
|
| 153 |
+
|
| 154 |
+
return extracted
|
| 155 |
+
|
| 156 |
+
raise RuntimeError(failure_message or f"Could not resolve inner type variable at index {index} for {typ}")
|
tool_server/.venv/lib/python3.12/site-packages/openai/_utils/_utils.py
ADDED
|
@@ -0,0 +1,438 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
import re
|
| 5 |
+
import inspect
|
| 6 |
+
import functools
|
| 7 |
+
from typing import (
|
| 8 |
+
TYPE_CHECKING,
|
| 9 |
+
Any,
|
| 10 |
+
Tuple,
|
| 11 |
+
Mapping,
|
| 12 |
+
TypeVar,
|
| 13 |
+
Callable,
|
| 14 |
+
Iterable,
|
| 15 |
+
Sequence,
|
| 16 |
+
cast,
|
| 17 |
+
overload,
|
| 18 |
+
)
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
from datetime import date, datetime
|
| 21 |
+
from typing_extensions import TypeGuard
|
| 22 |
+
|
| 23 |
+
import sniffio
|
| 24 |
+
|
| 25 |
+
from .._types import NotGiven, FileTypes, NotGivenOr, HeadersLike
|
| 26 |
+
from .._compat import parse_date as parse_date, parse_datetime as parse_datetime
|
| 27 |
+
|
| 28 |
+
_T = TypeVar("_T")
|
| 29 |
+
_TupleT = TypeVar("_TupleT", bound=Tuple[object, ...])
|
| 30 |
+
_MappingT = TypeVar("_MappingT", bound=Mapping[str, object])
|
| 31 |
+
_SequenceT = TypeVar("_SequenceT", bound=Sequence[object])
|
| 32 |
+
CallableT = TypeVar("CallableT", bound=Callable[..., Any])
|
| 33 |
+
|
| 34 |
+
if TYPE_CHECKING:
|
| 35 |
+
from ..lib.azure import AzureOpenAI, AsyncAzureOpenAI
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def flatten(t: Iterable[Iterable[_T]]) -> list[_T]:
|
| 39 |
+
return [item for sublist in t for item in sublist]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def extract_files(
|
| 43 |
+
# TODO: this needs to take Dict but variance issues.....
|
| 44 |
+
# create protocol type ?
|
| 45 |
+
query: Mapping[str, object],
|
| 46 |
+
*,
|
| 47 |
+
paths: Sequence[Sequence[str]],
|
| 48 |
+
) -> list[tuple[str, FileTypes]]:
|
| 49 |
+
"""Recursively extract files from the given dictionary based on specified paths.
|
| 50 |
+
|
| 51 |
+
A path may look like this ['foo', 'files', '<array>', 'data'].
|
| 52 |
+
|
| 53 |
+
Note: this mutates the given dictionary.
|
| 54 |
+
"""
|
| 55 |
+
files: list[tuple[str, FileTypes]] = []
|
| 56 |
+
for path in paths:
|
| 57 |
+
files.extend(_extract_items(query, path, index=0, flattened_key=None))
|
| 58 |
+
return files
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _extract_items(
|
| 62 |
+
obj: object,
|
| 63 |
+
path: Sequence[str],
|
| 64 |
+
*,
|
| 65 |
+
index: int,
|
| 66 |
+
flattened_key: str | None,
|
| 67 |
+
) -> list[tuple[str, FileTypes]]:
|
| 68 |
+
try:
|
| 69 |
+
key = path[index]
|
| 70 |
+
except IndexError:
|
| 71 |
+
if isinstance(obj, NotGiven):
|
| 72 |
+
# no value was provided - we can safely ignore
|
| 73 |
+
return []
|
| 74 |
+
|
| 75 |
+
# cyclical import
|
| 76 |
+
from .._files import assert_is_file_content
|
| 77 |
+
|
| 78 |
+
# We have exhausted the path, return the entry we found.
|
| 79 |
+
assert flattened_key is not None
|
| 80 |
+
|
| 81 |
+
if is_list(obj):
|
| 82 |
+
files: list[tuple[str, FileTypes]] = []
|
| 83 |
+
for entry in obj:
|
| 84 |
+
assert_is_file_content(entry, key=flattened_key + "[]" if flattened_key else "")
|
| 85 |
+
files.append((flattened_key + "[]", cast(FileTypes, entry)))
|
| 86 |
+
return files
|
| 87 |
+
|
| 88 |
+
assert_is_file_content(obj, key=flattened_key)
|
| 89 |
+
return [(flattened_key, cast(FileTypes, obj))]
|
| 90 |
+
|
| 91 |
+
index += 1
|
| 92 |
+
if is_dict(obj):
|
| 93 |
+
try:
|
| 94 |
+
# We are at the last entry in the path so we must remove the field
|
| 95 |
+
if (len(path)) == index:
|
| 96 |
+
item = obj.pop(key)
|
| 97 |
+
else:
|
| 98 |
+
item = obj[key]
|
| 99 |
+
except KeyError:
|
| 100 |
+
# Key was not present in the dictionary, this is not indicative of an error
|
| 101 |
+
# as the given path may not point to a required field. We also do not want
|
| 102 |
+
# to enforce required fields as the API may differ from the spec in some cases.
|
| 103 |
+
return []
|
| 104 |
+
if flattened_key is None:
|
| 105 |
+
flattened_key = key
|
| 106 |
+
else:
|
| 107 |
+
flattened_key += f"[{key}]"
|
| 108 |
+
return _extract_items(
|
| 109 |
+
item,
|
| 110 |
+
path,
|
| 111 |
+
index=index,
|
| 112 |
+
flattened_key=flattened_key,
|
| 113 |
+
)
|
| 114 |
+
elif is_list(obj):
|
| 115 |
+
if key != "<array>":
|
| 116 |
+
return []
|
| 117 |
+
|
| 118 |
+
return flatten(
|
| 119 |
+
[
|
| 120 |
+
_extract_items(
|
| 121 |
+
item,
|
| 122 |
+
path,
|
| 123 |
+
index=index,
|
| 124 |
+
flattened_key=flattened_key + "[]" if flattened_key is not None else "[]",
|
| 125 |
+
)
|
| 126 |
+
for item in obj
|
| 127 |
+
]
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
# Something unexpected was passed, just ignore it.
|
| 131 |
+
return []
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def is_given(obj: NotGivenOr[_T]) -> TypeGuard[_T]:
|
| 135 |
+
return not isinstance(obj, NotGiven)
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
# Type safe methods for narrowing types with TypeVars.
|
| 139 |
+
# The default narrowing for isinstance(obj, dict) is dict[unknown, unknown],
|
| 140 |
+
# however this cause Pyright to rightfully report errors. As we know we don't
|
| 141 |
+
# care about the contained types we can safely use `object` in it's place.
|
| 142 |
+
#
|
| 143 |
+
# There are two separate functions defined, `is_*` and `is_*_t` for different use cases.
|
| 144 |
+
# `is_*` is for when you're dealing with an unknown input
|
| 145 |
+
# `is_*_t` is for when you're narrowing a known union type to a specific subset
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def is_tuple(obj: object) -> TypeGuard[tuple[object, ...]]:
|
| 149 |
+
return isinstance(obj, tuple)
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def is_tuple_t(obj: _TupleT | object) -> TypeGuard[_TupleT]:
|
| 153 |
+
return isinstance(obj, tuple)
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def is_sequence(obj: object) -> TypeGuard[Sequence[object]]:
|
| 157 |
+
return isinstance(obj, Sequence)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def is_sequence_t(obj: _SequenceT | object) -> TypeGuard[_SequenceT]:
|
| 161 |
+
return isinstance(obj, Sequence)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def is_mapping(obj: object) -> TypeGuard[Mapping[str, object]]:
|
| 165 |
+
return isinstance(obj, Mapping)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def is_mapping_t(obj: _MappingT | object) -> TypeGuard[_MappingT]:
|
| 169 |
+
return isinstance(obj, Mapping)
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def is_dict(obj: object) -> TypeGuard[dict[object, object]]:
|
| 173 |
+
return isinstance(obj, dict)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def is_list(obj: object) -> TypeGuard[list[object]]:
|
| 177 |
+
return isinstance(obj, list)
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def is_iterable(obj: object) -> TypeGuard[Iterable[object]]:
|
| 181 |
+
return isinstance(obj, Iterable)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def deepcopy_minimal(item: _T) -> _T:
|
| 185 |
+
"""Minimal reimplementation of copy.deepcopy() that will only copy certain object types:
|
| 186 |
+
|
| 187 |
+
- mappings, e.g. `dict`
|
| 188 |
+
- list
|
| 189 |
+
|
| 190 |
+
This is done for performance reasons.
|
| 191 |
+
"""
|
| 192 |
+
if is_mapping(item):
|
| 193 |
+
return cast(_T, {k: deepcopy_minimal(v) for k, v in item.items()})
|
| 194 |
+
if is_list(item):
|
| 195 |
+
return cast(_T, [deepcopy_minimal(entry) for entry in item])
|
| 196 |
+
return item
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
# copied from https://github.com/Rapptz/RoboDanny
|
| 200 |
+
def human_join(seq: Sequence[str], *, delim: str = ", ", final: str = "or") -> str:
|
| 201 |
+
size = len(seq)
|
| 202 |
+
if size == 0:
|
| 203 |
+
return ""
|
| 204 |
+
|
| 205 |
+
if size == 1:
|
| 206 |
+
return seq[0]
|
| 207 |
+
|
| 208 |
+
if size == 2:
|
| 209 |
+
return f"{seq[0]} {final} {seq[1]}"
|
| 210 |
+
|
| 211 |
+
return delim.join(seq[:-1]) + f" {final} {seq[-1]}"
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def quote(string: str) -> str:
|
| 215 |
+
"""Add single quotation marks around the given string. Does *not* do any escaping."""
|
| 216 |
+
return f"'{string}'"
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def required_args(*variants: Sequence[str]) -> Callable[[CallableT], CallableT]:
|
| 220 |
+
"""Decorator to enforce a given set of arguments or variants of arguments are passed to the decorated function.
|
| 221 |
+
|
| 222 |
+
Useful for enforcing runtime validation of overloaded functions.
|
| 223 |
+
|
| 224 |
+
Example usage:
|
| 225 |
+
```py
|
| 226 |
+
@overload
|
| 227 |
+
def foo(*, a: str) -> str: ...
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
@overload
|
| 231 |
+
def foo(*, b: bool) -> str: ...
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
# This enforces the same constraints that a static type checker would
|
| 235 |
+
# i.e. that either a or b must be passed to the function
|
| 236 |
+
@required_args(["a"], ["b"])
|
| 237 |
+
def foo(*, a: str | None = None, b: bool | None = None) -> str: ...
|
| 238 |
+
```
|
| 239 |
+
"""
|
| 240 |
+
|
| 241 |
+
def inner(func: CallableT) -> CallableT:
|
| 242 |
+
params = inspect.signature(func).parameters
|
| 243 |
+
positional = [
|
| 244 |
+
name
|
| 245 |
+
for name, param in params.items()
|
| 246 |
+
if param.kind
|
| 247 |
+
in {
|
| 248 |
+
param.POSITIONAL_ONLY,
|
| 249 |
+
param.POSITIONAL_OR_KEYWORD,
|
| 250 |
+
}
|
| 251 |
+
]
|
| 252 |
+
|
| 253 |
+
@functools.wraps(func)
|
| 254 |
+
def wrapper(*args: object, **kwargs: object) -> object:
|
| 255 |
+
given_params: set[str] = set()
|
| 256 |
+
for i, _ in enumerate(args):
|
| 257 |
+
try:
|
| 258 |
+
given_params.add(positional[i])
|
| 259 |
+
except IndexError:
|
| 260 |
+
raise TypeError(
|
| 261 |
+
f"{func.__name__}() takes {len(positional)} argument(s) but {len(args)} were given"
|
| 262 |
+
) from None
|
| 263 |
+
|
| 264 |
+
for key in kwargs.keys():
|
| 265 |
+
given_params.add(key)
|
| 266 |
+
|
| 267 |
+
for variant in variants:
|
| 268 |
+
matches = all((param in given_params for param in variant))
|
| 269 |
+
if matches:
|
| 270 |
+
break
|
| 271 |
+
else: # no break
|
| 272 |
+
if len(variants) > 1:
|
| 273 |
+
variations = human_join(
|
| 274 |
+
["(" + human_join([quote(arg) for arg in variant], final="and") + ")" for variant in variants]
|
| 275 |
+
)
|
| 276 |
+
msg = f"Missing required arguments; Expected either {variations} arguments to be given"
|
| 277 |
+
else:
|
| 278 |
+
assert len(variants) > 0
|
| 279 |
+
|
| 280 |
+
# TODO: this error message is not deterministic
|
| 281 |
+
missing = list(set(variants[0]) - given_params)
|
| 282 |
+
if len(missing) > 1:
|
| 283 |
+
msg = f"Missing required arguments: {human_join([quote(arg) for arg in missing])}"
|
| 284 |
+
else:
|
| 285 |
+
msg = f"Missing required argument: {quote(missing[0])}"
|
| 286 |
+
raise TypeError(msg)
|
| 287 |
+
return func(*args, **kwargs)
|
| 288 |
+
|
| 289 |
+
return wrapper # type: ignore
|
| 290 |
+
|
| 291 |
+
return inner
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
_K = TypeVar("_K")
|
| 295 |
+
_V = TypeVar("_V")
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
@overload
|
| 299 |
+
def strip_not_given(obj: None) -> None: ...
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
@overload
|
| 303 |
+
def strip_not_given(obj: Mapping[_K, _V | NotGiven]) -> dict[_K, _V]: ...
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
@overload
|
| 307 |
+
def strip_not_given(obj: object) -> object: ...
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def strip_not_given(obj: object | None) -> object:
|
| 311 |
+
"""Remove all top-level keys where their values are instances of `NotGiven`"""
|
| 312 |
+
if obj is None:
|
| 313 |
+
return None
|
| 314 |
+
|
| 315 |
+
if not is_mapping(obj):
|
| 316 |
+
return obj
|
| 317 |
+
|
| 318 |
+
return {key: value for key, value in obj.items() if not isinstance(value, NotGiven)}
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
def coerce_integer(val: str) -> int:
|
| 322 |
+
return int(val, base=10)
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def coerce_float(val: str) -> float:
|
| 326 |
+
return float(val)
|
| 327 |
+
|
| 328 |
+
|
| 329 |
+
def coerce_boolean(val: str) -> bool:
|
| 330 |
+
return val == "true" or val == "1" or val == "on"
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def maybe_coerce_integer(val: str | None) -> int | None:
|
| 334 |
+
if val is None:
|
| 335 |
+
return None
|
| 336 |
+
return coerce_integer(val)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
def maybe_coerce_float(val: str | None) -> float | None:
|
| 340 |
+
if val is None:
|
| 341 |
+
return None
|
| 342 |
+
return coerce_float(val)
|
| 343 |
+
|
| 344 |
+
|
| 345 |
+
def maybe_coerce_boolean(val: str | None) -> bool | None:
|
| 346 |
+
if val is None:
|
| 347 |
+
return None
|
| 348 |
+
return coerce_boolean(val)
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def removeprefix(string: str, prefix: str) -> str:
|
| 352 |
+
"""Remove a prefix from a string.
|
| 353 |
+
|
| 354 |
+
Backport of `str.removeprefix` for Python < 3.9
|
| 355 |
+
"""
|
| 356 |
+
if string.startswith(prefix):
|
| 357 |
+
return string[len(prefix) :]
|
| 358 |
+
return string
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def removesuffix(string: str, suffix: str) -> str:
|
| 362 |
+
"""Remove a suffix from a string.
|
| 363 |
+
|
| 364 |
+
Backport of `str.removesuffix` for Python < 3.9
|
| 365 |
+
"""
|
| 366 |
+
if string.endswith(suffix):
|
| 367 |
+
return string[: -len(suffix)]
|
| 368 |
+
return string
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def file_from_path(path: str) -> FileTypes:
|
| 372 |
+
contents = Path(path).read_bytes()
|
| 373 |
+
file_name = os.path.basename(path)
|
| 374 |
+
return (file_name, contents)
|
| 375 |
+
|
| 376 |
+
|
| 377 |
+
def get_required_header(headers: HeadersLike, header: str) -> str:
|
| 378 |
+
lower_header = header.lower()
|
| 379 |
+
if is_mapping_t(headers):
|
| 380 |
+
# mypy doesn't understand the type narrowing here
|
| 381 |
+
for k, v in headers.items(): # type: ignore
|
| 382 |
+
if k.lower() == lower_header and isinstance(v, str):
|
| 383 |
+
return v
|
| 384 |
+
|
| 385 |
+
# to deal with the case where the header looks like Stainless-Event-Id
|
| 386 |
+
intercaps_header = re.sub(r"([^\w])(\w)", lambda pat: pat.group(1) + pat.group(2).upper(), header.capitalize())
|
| 387 |
+
|
| 388 |
+
for normalized_header in [header, lower_header, header.upper(), intercaps_header]:
|
| 389 |
+
value = headers.get(normalized_header)
|
| 390 |
+
if value:
|
| 391 |
+
return value
|
| 392 |
+
|
| 393 |
+
raise ValueError(f"Could not find {header} header")
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def get_async_library() -> str:
|
| 397 |
+
try:
|
| 398 |
+
return sniffio.current_async_library()
|
| 399 |
+
except Exception:
|
| 400 |
+
return "false"
|
| 401 |
+
|
| 402 |
+
|
| 403 |
+
def lru_cache(*, maxsize: int | None = 128) -> Callable[[CallableT], CallableT]:
|
| 404 |
+
"""A version of functools.lru_cache that retains the type signature
|
| 405 |
+
for the wrapped function arguments.
|
| 406 |
+
"""
|
| 407 |
+
wrapper = functools.lru_cache( # noqa: TID251
|
| 408 |
+
maxsize=maxsize,
|
| 409 |
+
)
|
| 410 |
+
return cast(Any, wrapper) # type: ignore[no-any-return]
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def json_safe(data: object) -> object:
|
| 414 |
+
"""Translates a mapping / sequence recursively in the same fashion
|
| 415 |
+
as `pydantic` v2's `model_dump(mode="json")`.
|
| 416 |
+
"""
|
| 417 |
+
if is_mapping(data):
|
| 418 |
+
return {json_safe(key): json_safe(value) for key, value in data.items()}
|
| 419 |
+
|
| 420 |
+
if is_iterable(data) and not isinstance(data, (str, bytes, bytearray)):
|
| 421 |
+
return [json_safe(item) for item in data]
|
| 422 |
+
|
| 423 |
+
if isinstance(data, (datetime, date)):
|
| 424 |
+
return data.isoformat()
|
| 425 |
+
|
| 426 |
+
return data
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
def is_azure_client(client: object) -> TypeGuard[AzureOpenAI]:
|
| 430 |
+
from ..lib.azure import AzureOpenAI
|
| 431 |
+
|
| 432 |
+
return isinstance(client, AzureOpenAI)
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
def is_async_azure_client(client: object) -> TypeGuard[AsyncAzureOpenAI]:
|
| 436 |
+
from ..lib.azure import AsyncAzureOpenAI
|
| 437 |
+
|
| 438 |
+
return isinstance(client, AsyncAzureOpenAI)
|